messages.ts

54.0 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard } from "./clipboard";13import { setupAutoLock, touchAutoLock } from "./alarms";14import { runSelfTest } from "./self-test";15import * as vault from "./vault";16import {17  handleEstimateCodexPages,18  handleGetCodexVaultData,19  handleRestoreFromCodex,20} from "./codex-handlers";21import type { CodexRestorePayload } from "../shared/codex-types";22import {23  activateLicense,24  deactivateLicense,25  getLicenseInfo,26  getLicenseKey,27  isProUser,28  markCelebrationPlayed,29  shouldPlayCelebration,30} from "./license";31import {32  completeFirefoxPasskeyCreate,33  getPasskeyProviderState,34  getPendingPasskeyRequest,35  handleFirefoxPasskeyCreate,36  handleFirefoxPasskeyGet,37  handlePasskeyHasCredentials,38  initiateFirefoxPasskeyCreate,39  isPasskeyOfferDeclined,40  onVaultUnlocked,41  recordPasskeyOfferDecline,42  resolvePendingPasskeyRequest,43  setPasskeyProviderEnabled,44} from "./passkey";45import { buildAdvancedHealthReport } from "./health";46import { storageClear } from "../shared/storage";47import { findInvalidWords } from "../shared/recovery-words";48import type {49  Message,50  MessageResponse,51  MessageType,52  ProFeature,53  VaultEntry,54} from "../shared/types";55import { isPasskeyOnly } from "../shared/types";56import { generateTOTP } from "../crypto/totp";57import { isValidRpId } from "../shared/passkey-utils";58import { isNativePlatform, nativePlugin } from "../shared/native";59import { predictBatch as mlPredictBatch } from "./ml";60import type { MLFieldFeatures } from "../shared/ml";61import { buildLocalIdentity, setDeviceName as setDeviceNameV3 } from "./chirp-identity";62import {63  listPairedDevices as listPairedDevicesV3,64  removePairedDeviceById as removePairedDeviceByIdV3,65  upsertPairedDevice as upsertPairedDeviceV3,66} from "./paired-devices";6768let nativeSyncRunnerBootstrapped = false;6970function unhexBytes(hex: string): Uint8Array {71  if (hex.length % 2 !== 0) throw new Error("invalid hex");72  const out = new Uint8Array(hex.length / 2);73  for (let i = 0; i < out.length; i++) {74    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);75  }76  return out;77}7879/**80 * The single Pro gate. Every gated handler calls this first; the broadcast81 * lets the popup react (navigate to the License section, highlight the82 * relevant feature). Background never touches the popup view directly —83 * the popup owns navigation. See Projects.md "Pro gate rule".84 */85async function requirePro(86  feature: ProFeature,87  trigger: "user" | "background" = "user"88): Promise<{ allowed: boolean }> {89  if (await isProUser()) return { allowed: true };9091  if (trigger === "user") {92    // User deliberately triggered this feature — redirect the popup immediately.93    chrome.runtime94      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })95      .catch(() => {96        // Popup may be closed — the gate signal is best-effort.97      });98  } else {99    // Background trigger (e.g. passive sync initiation) — no popup is open.100    // Queue a notice so the next popup open shows a soft banner instead of101    // silently failing.102    if (chrome.storage.session) {103      chrome.storage.session104        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })105        .catch(() => {});106    }107  }108109  return { allowed: false };110}111112// ---------------------------------------------------------------------------113// Feedback submission target. Empty disables network submission while the UI114// continues to function as a no-op (the handler returns ok:true without115// calling fetch). When set, the URL is validated by116// `isAllowedCanaryWebhookUrl` before any request.117// ---------------------------------------------------------------------------118119const FEEDBACK_ENDPOINT = "";120121const PRIVATE_IPV4_RANGES = [122  { prefix: "10." },123  { prefix: "127." },124  { prefix: "169.254." },125  { prefix: "192.168." },126];127128export function setupMessageHandler(): void {129  chrome.runtime.onMessage.addListener(130    (msg: unknown, sender, sendResponse) => {131      if (!isMessage(msg)) {132        sendResponse({ ok: false, error: "invalid_message" });133        return true;134      }135      handleMessage(msg, sender)136        .then(sendResponse)137        .catch((err) =>138          sendResponse({139            ok: false,140            error: err instanceof Error ? err.message : String(err),141          })142        );143      return true;144    }145  );146147  // Android: the chrome shim queues sendMessage calls until this handler is148  // registered. Without this hookup, every message hangs on Capacitor builds.149  // eslint-disable-next-line @typescript-eslint/no-explicit-any150  const reg = (globalThis as any).__peachRegisterMessageHandler;151  if (typeof reg === "function") {152    reg(async (m: unknown) => {153      if (!isMessage(m)) return { ok: false, error: "invalid_message" };154      try {155        return await handleMessage(m);156      } catch (err) {157        return {158          ok: false,159          error: err instanceof Error ? err.message : String(err),160        };161      }162    });163  }164  if (isNativePlatform()) {165    void bootstrapNativeSyncRunner();166  }167}168169async function bootstrapNativeSyncRunner(): Promise<void> {170  if (nativeSyncRunnerBootstrapped) return;171  nativeSyncRunnerBootstrapped = true;172  try {173    const { setSyncRunner, hydratePersistedSyncState } = await import("./sync-trigger");174    const { productionSyncRunner } = await import("./chirp-sync-runner");175    setSyncRunner(productionSyncRunner);176    await hydratePersistedSyncState();177  } catch (err) {178    nativeSyncRunnerBootstrapped = false;179    console.warn("[Peach] failed to bootstrap native sync runner:", err);180  }181}182183function isMessage(m: unknown): m is Message {184  return typeof m === "object" && m !== null && "type" in m;185}186187/**188 * The browser-attested origin of the page that originated this message. A web189 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),190 * so every page-driven message arrives via the content-script relay and the191 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a192 * value the page cannot forge. This is the ONLY trustworthy origin for passkey193 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.194 */195function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {196  if (sender.origin) return sender.origin;197  if (sender.url) {198    try { return new URL(sender.url).origin; } catch { return undefined; }199  }200  return undefined;201}202203export async function handleMessage(204  msg: Message,205  sender: Partial<chrome.runtime.MessageSender> = {}206): Promise<MessageResponse> {207  try {208    // Validate sender — only allow messages from our extension pages/scripts.209    // `sender.id` is undefined for messages originating from extension UI210    // (popup/options), which is legitimate; reject only when it is defined211    // and does not match our extension id.212    if (213      sender.id !== undefined &&214      sender.id !== chrome.runtime.id215    ) {216      return { ok: false, error: "invalid_sender" };217    }218219    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {220      touchAutoLock();221    }222223    switch (msg.type) {224      case "CREATE_VAULT": {225        const { password } = msg.payload as { password: string };226        await vault.createVault(password);227        await setupAutoLock();228        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });229        onVaultUnlocked();230        return { ok: true };231      }232      case "UNLOCK": {233        const { password } = msg.payload as { password: string };234        const ok = await vault.unlock(password);235        if (ok) {236          // KAT: verify the WebCrypto stack is healthy before the user relies on it.237          // Runs after unlock so latency is hidden behind the vault-load time.238          const kat = await runSelfTest();239          if (!kat.ok) {240            console.error("[Peach] Crypto self-test FAILED:", kat.error);241            await vault.lock();242            return { ok: false, error: "self_test_failed" };243          }244          await setupAutoLock();245          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });246          onVaultUnlocked();247          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());248          return { ok: true };249        }250        // Distinguish corruption from wrong password so the popup can offer251        // a history-restore path instead of falsely accusing the user of252        // mistyping (M7/COR-007).253        const failure = vault.consumeLastUnlockFailureReason();254        if (failure) {255          return {256            ok: false,257            error: "vault_corrupted",258            canRestoreFromHistory: true,259          } as MessageResponse;260        }261        return { ok: false };262      }263      case "VALIDATE_RECOVERY_WORDS": {264        const { words } = msg.payload as { words: string[] };265        const invalid = findInvalidWords(words);266        return { ok: true, data: { valid: invalid.length === 0, invalid } };267      }268      case "GET_RECOVERY_WORDS": {269        // Must be unlocked and have recovery set up (vault must be v2.12+).270        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };271        try {272          const words = await vault.getRecoveryWords();273          return { ok: true, data: words };274        } catch (e) {275          // pre-v2.12 vault that hasn't migrated276          return { ok: false, error: "recovery_not_setup" };277        }278      }279      case "RECOVER_WITH_WORDS": {280        // User has lost their password but has their 12 recovery words.281        // We: (1) validate the words, (2) re-encrypt vault with new password.282        const { words, newPassword } = msg.payload as {283          words: string[];284          newPassword: string;285        };286        const stored = await vault.loadSlotA();287        if (!stored) return { ok: false, error: "no_vault" };288        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {289          return { ok: false, error: "recovery_not_setup" };290        }291        // Unwrap the root key from the recovery escrow.292        try {293          await vault.unwrapRootKeyForRecovery(294            stored.recovery_wrapped_root_key,295            stored.recovery_nonce ?? "",296            stored.recovery_tag ?? "",297            stored.recovery_salt,298            words299          );300        } catch {301          return { ok: false, error: "invalid_recovery_words" };302        }303        // Re-key: derive fresh salt + key from new password.304        const newSalt = vault.generateSalt();305        const newKey = await vault.deriveKey(newPassword, newSalt);306        // Re-wrap root key under the new password's derived key so the same307        // recovery words continue to work after the password change.308        await vault.rewrapRootKeyForPassword(newKey, newSalt);309        // Re-encrypt vault entries with the new key.310        await vault.changePasswordWithNewKey(newSalt, newKey);311        await setupAutoLock();312        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });313        return { ok: true };314      }315      case "LOCK":316        vault.lock();317        if (isNativePlatform()) await clearInMemoryVault();318        return { ok: true };319      case "IS_UNLOCKED":320        return { ok: true, data: vault.isUnlocked() };321      case "GET_VAULT_STATUS":322        return { ok: true, unlocked: vault.isUnlocked() };323      case "HAS_VAULT":324        return { ok: true, data: await vault.hasVault() };325      case "GET_ENTRIES":326        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };327        return { ok: true, data: vault.getEntries() };328      case "ADD_ENTRY": {329        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };330        const payload = msg.payload;331        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {332          return { ok: false, error: "invalid_payload" };333        }334        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);335        return { ok: true, data: entry };336      }337      case "BATCH_ADD_ENTRIES": {338        const payload = msg.payload as { entries?: unknown } | null | undefined;339        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {340          return { ok: false, error: "invalid_payload" };341        }342        if (!Array.isArray(payload.entries)) {343          return { ok: false, error: "invalid_payload" };344        }345        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);346        return { ok: true, data: added };347      }348      case "RESTORE_ENTRIES": {349        const payload = msg.payload as350          | { entries?: unknown; mode?: unknown; settings?: unknown }351          | null352          | undefined;353        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {354          return { ok: false, error: "invalid_payload" };355        }356        if (!Array.isArray(payload.entries)) {357          return { ok: false, error: "invalid_payload" };358        }359        if (payload.mode !== "replace" && payload.mode !== "merge") {360          return { ok: false, error: "invalid_payload" };361        }362        const summary = await vault.restoreEntries(363          payload.entries as Parameters<typeof vault.restoreEntries>[0],364          payload.mode365        );366        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {367          await vault.updateSettings(payload.settings as vault.VaultSettings);368        }369        return { ok: true, data: summary };370      }371      case "CLEAR_VAULT_ENTRIES": {372        await vault.clearVaultEntries("REPLACE_ALL");373        return { ok: true };374      }375      case "GET_VAULT_HISTORY": {376        const snapshots = await vault.getVaultHistory();377        return { ok: true, data: snapshots };378      }379      case "RESTORE_VAULT_SNAPSHOT": {380        const { snapshotId } = msg.payload as { snapshotId: string };381        const result = await vault.restoreVaultSnapshot(snapshotId);382        if (!result.ok) return { ok: false, error: result.error };383        broadcastToContentScripts({ type: "VAULT_LOCKED" });384        return { ok: true };385      }386      case "COUNT_DUPLICATES": {387        return { ok: true, data: vault.countDuplicates() };388      }389      case "DEDUPLICATE_ENTRIES": {390        const removed = await vault.deduplicateEntries();391        return { ok: true, data: removed };392      }393      case "UPDATE_ENTRY": {394        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;395        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {396          return { ok: false, error: "invalid_payload" };397        }398        const { id, patch } = payload;399        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {400          return { ok: false, error: "invalid_payload" };401        }402        // Single enforcement point for the Canary Entries Pro gate. Only403        // gates the transition into a canary entry — clearing/disabling a404        // canary (`canary: undefined`) is always allowed, so existing405        // canary entries remain manageable.406        const incomingCanary = (patch as { canary?: unknown }).canary;407        if (incomingCanary && typeof incomingCanary === "object") {408          const existing = vault.getEntryById(id);409          if (!existing?.canary) {410            const gate = await requirePro("canary_entry");411            if (!gate.allowed) return { ok: false, error: "pro_required" };412          }413        }414        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);415        return { ok: true };416      }417      case "ADD_ADDITIONAL_URL": {418        const { id, url } = msg.payload as { id: string; url: string };419        const trimmed = typeof url === "string" ? url.trim() : "";420        if (!trimmed) return { ok: false, error: "url_required" };421        const existing = vault.getEntryById(id);422        if (!existing) return { ok: false, error: "entry_not_found" };423        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };424        const merged = [...(existing.additionalUrls ?? []), trimmed];425        await vault.updateEntry(id, { additionalUrls: merged });426        return { ok: true };427      }428      case "DELETE_ENTRY": {429        const { id } = msg.payload as { id: string };430        await vault.deleteEntry(id);431        return { ok: true };432      }433      case "GET_DELETED_ENTRIES":434        return { ok: true, data: vault.getDeletedEntries() };435      case "RESTORE_ENTRY": {436        const { id } = msg.payload as { id: string };437        await vault.restoreEntry(id);438        return { ok: true };439      }440      case "PURGE_ENTRY": {441        const { id } = msg.payload as { id: string };442        await vault.purgeEntry(id);443        return { ok: true };444      }445      case "PURGE_EXPIRED_TRASH": {446        const { retentionMs } = msg.payload as { retentionMs: number };447        const purged = await vault.purgeExpiredTrash(retentionMs);448        return { ok: true, data: purged };449      }450      case "SAVE_NOTE": {451        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };452        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };453        const now = Date.now();454        if (id) {455          const existing = vault.getEntryById(id);456          if (!existing) return { ok: false, error: "not_found" };457          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });458          return { ok: true, data: vault.getEntryById(id) };459        } else {460          const entry = await vault.addEntry({461            type: "note",462            title: title || "Untitled",463            notes: body,464            createdAt: now,465            modifiedAt: now,466          } as any);467          return { ok: true, data: entry };468        }469      }470      case "DELETE_NOTE": {471        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };472        const { id } = msg.payload as { id: string };473        await vault.deleteEntry(id);474        return { ok: true };475      }476      case "GET_NOTES": {477        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };478        const notes = vault.getEntries().filter(479          (e) => e.type === "note" && !e.deletedAt480        );481        return { ok: true, data: notes } as MessageResponse;482      }483      case "SEARCH_VAULT": {484        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };485        // AUD-002: shape-validate the payload before calling string methods.486        // A raw cast lets a malformed message crash the handler with TypeError.487        const { query } = (msg.payload ?? {}) as { query?: unknown };488        if (typeof query !== "string") {489          return { ok: false, error: "invalid_payload" };490        }491        const q = query.toLowerCase();492        const searchResults = vault.getEntries().filter(493          (e) =>494            !e.deletedAt &&495            (e.title.toLowerCase().includes(q) ||496              e.notes?.toLowerCase().includes(q) ||497              e.username?.toLowerCase().includes(q))498        );499        return { ok: true, data: searchResults } as MessageResponse;500      }501      case "AUTOFILL_QUERY": {502        if (!vault.isUnlocked()) {503          return { ok: false, error: "vault_locked" };504        }505        const { domain, includeAll, kind } = msg.payload as {506          domain: string;507          includeAll?: boolean;508          kind?: "login" | "card" | "totp";509        };510        // kind="card": return saved cards as compact summaries for the511        // inline card silver platter. Cards are not domain-scoped — every512        // saved card is a candidate on every checkout page — so domain is513        // ignored when kind === "card".514        if (kind === "card") {515          const cards = vault.getEntries().filter((e) => e.type === "card");516          return {517            ok: true,518            data: cards.map((e) => ({519              id: e.id,520              title: e.cardNickname || e.title,521              cardholderName: e.cardholderName,522              last4: e.last4,523              expMonth: e.expMonth,524              expYear: e.expYear,525              network: e.network,526            })),527          };528        }529        if (kind === "totp") {530          const matches = (531            includeAll532              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")533              : vault.queryDomain(domain)534          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));535          return {536            ok: true,537            data: matches.map((e) => ({538              id: e.id,539              title: e.title,540              username: e.username,541              email: e.email,542              url: e.url,543              hasTotp: true,544            })),545          };546        }547        // The inline selector fills username+password into a form. Passkey-548        // only entries have no password to fill; sign-in for those goes549        // through the WebAuthn path instead. Filter them out everywhere so550        // the user doesn't see four "GitHub" rows that mostly do nothing.551        // Notes and cards never belonged here either.552        const matches = (553          includeAll554            ? vault555                .getEntries()556                .filter((entry) => entry.type !== "note" && entry.type !== "card")557            : vault.queryDomain(domain)558        ).filter((entry) => !isPasskeyOnly(entry));559        return {560          ok: true,561          data: matches.map((e) =>562            includeAll563              ? {564                  id: e.id,565                  title: e.title,566                  // username/email/url shipped so the inline popup's search567                  // affordance can match on them, not just titles. No secrets568                  // cross the boundary — same shape as the domain-matched569                  // response below minus hasTotp (which the search list570                  // doesn't surface).571                  username: e.username,572                  email: e.email,573                  url: e.url,574                  hasPasskey: e.passkey !== undefined,575                }576              : {577                  id: e.id,578                  title: e.title,579                  username: e.username,580                  email: e.email,581                  url: e.url,582                  hasTotp: Boolean(e.totp),583                  hasPasskey: e.passkey !== undefined,584                }585          ),586        };587      }588      case "GET_ENTRY_FOR_FILL": {589        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };590        const { id } = msg.payload as { id: string };591        const entry = vault.getEntryById(id);592        if (!entry) return { ok: false, error: "entry_not_found" };593        // Passkey-only entries (passkey credential, no password) cannot be594        // filled into a form — sign-in goes through the WebAuthn path. A595        // login that ALSO has a passkey is still fillable for its password.596        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };597        // Strip the passkey credential AND the raw base32 TOTP seed from the598        // response. Content scripts never need either: the private key is the599        // authenticator's, and handing over the TOTP seed would let a600        // compromised content script mint valid codes indefinitely (SEV-3-C).601        // Generate the *current* 6-digit code here in the background and send602        // only that, plus the seconds left so the UI can render a countdown.603        const { passkey: _strippedPasskey, totp: seed, ...safeEntry } = entry;604        let totpCode: string | undefined;605        let totpRemaining: number | undefined;606        if (seed) {607          try {608            const generated = generateTOTP(seed);609            totpCode = generated.code;610            totpRemaining = generated.remaining;611          } catch {612            totpCode = undefined;613          }614        }615        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };616      }617      // Trusted full-entry fetch for Peach's own inline-popup surfaces that618      // genuinely need the raw TOTP seed: the edit form (which re-saves the619      // seed and would otherwise wipe it) and nothing else. Unlike620      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside621      // the inline popup, never during passive autofill on an arbitrary page.622      // The passkey credential is still stripped — the edit form never touches it.623      case "GET_ENTRY_FOR_EDIT": {624        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };625        const { id } = msg.payload as { id: string };626        const entry = vault.getEntryById(id);627        if (!entry) return { ok: false, error: "entry_not_found" };628        const { passkey: _passkey, ...safeEntry } = entry;629        return { ok: true, data: safeEntry };630      }631      case "COPY": {632        // AUD-002: shape-validate the payload before passing to the clipboard633        // helper. A raw cast lets a malformed message reach the clipboard API634        // with a non-string and throw.635        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {636          text?: unknown;637          label?: unknown;638          alreadyWritten?: unknown;639        };640        if (typeof text !== "string" || typeof label !== "string") {641          return { ok: false, error: "invalid_payload" };642        }643        await copyToClipboard(text, label, Boolean(alreadyWritten));644        return { ok: true };645      }646      case "CHECK_ALL_BREACHES": {647        const allEntries = vault.getEntries();648        const results: Record<string, number> = {};649        for (const entry of allEntries) {650          if (entry.type === "note") continue;651          if (!entry.password) continue;652          results[entry.id] = await vault.checkBreach(entry.password);653          // Small delay — be a good citizen to the HIBP API654          await new Promise((r) => setTimeout(r, 200));655        }656        // Persist any non-zero counts back to entries657        for (const [id, count] of Object.entries(results)) {658          const entry = vault.getEntryById(id);659          if (entry && (entry.breach ?? 0) !== count) {660            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });661          }662        }663        return { ok: true, data: results };664      }665      case "GET_SETTINGS":666        return { ok: true, data: await vault.ensureSettingsLoaded() };667      case "UPDATE_SETTINGS": {668        const patch = msg.payload;669        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {670          return { ok: false, error: "invalid_payload" };671        }672        await vault.updateSettings(patch as vault.VaultSettings);673        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {674          await setupAutoLock();675          if (vault.isUnlocked()) touchAutoLock();676        }677        return { ok: true };678      }679      case "GET_PENDING_PASSKEY":680        return { ok: true, data: await getPendingPasskeyRequest() };681      case "APPROVE_PASSKEY": {682        const { requestId } = msg.payload as { requestId: number };683        await resolvePendingPasskeyRequest(requestId, true);684        return { ok: true };685      }686      case "DENY_PASSKEY": {687        const { requestId } = msg.payload as { requestId: number };688        await resolvePendingPasskeyRequest(requestId, false);689        return { ok: true };690      }691      case "GET_PASSKEY_PROVIDER_STATE":692        return { ok: true, data: await getPasskeyProviderState() };693      case "SET_PASSKEY_PROVIDER_ENABLED": {694        const { enabled } = msg.payload as { enabled: boolean };695        // Disabling is always free; gating fires only when a free user is696        // trying to turn passkey interception on.697        if (enabled) {698          const gate = await requirePro("passkeys");699          if (!gate.allowed) return { ok: false, error: "pro_required" };700        }701        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };702      }703      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS704      // endpoint. Intentional product behavior — users configure their own705      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private706      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-707      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to708      // users that the entry title leaves the device when the canary fires.709      case "FIRE_CANARY_PING": {710        // Canary alert fires unconditionally for any entry with canary: true.711        // The Pro gate only governs creation/flagging of canary entries; once712        // an entry is flagged, the alert path is a security property and must713        // never be license-gated.714        const { webhookUrl, entryTitle, trigger } = msg.payload as {715          webhookUrl: string;716          entryTitle: string;717          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";718        };719        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {720          return { ok: false, error: "invalid_webhook_url" };721        }722        const body = JSON.stringify({723          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",724          entry: entryTitle,725          trigger,726          timestamp: new Date().toISOString(),727          source: "peach-extension",728        });729        if (trigger === "test") {730          // Permitted outbound fetch: user-configured canary alert endpoint731          // (validated by isAllowedCanaryWebhookUrl above). This is the732          // only non-HIBP outbound call in the extension — see733          // Projects.md §3.7. Test pings are awaited so the UI can show734          // success/failure.735          try {736            const res = await fetch(webhookUrl, {737              method: "POST",738              headers: { "Content-Type": "application/json" },739              body,740            });741            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };742          } catch (err) {743            return { ok: false, error: err instanceof Error ? err.message : "network_error" };744          }745        }746        // Non-test triggers are fire-and-forget747        fetch(webhookUrl, {748          method: "POST",749          headers: { "Content-Type": "application/json" },750          body,751        }).catch(() => {});752        return { ok: true };753      }754      case "ACTIVATE_LICENSE": {755        const { key } = msg.payload as { key: string };756        const licenseInfo = await activateLicense(key);757        return { ok: true, data: licenseInfo };758      }759      case "GET_LICENSE": {760        const licenseInfo = await getLicenseInfo();761        return { ok: true, data: licenseInfo };762      }763      case "GET_LICENSE_KEY": {764        const key = await getLicenseKey();765        return { ok: true, data: key };766      }767      case "DEACTIVATE_LICENSE": {768        await deactivateLicense();769        return { ok: true };770      }771      case "SHOULD_PLAY_CELEBRATION": {772        const should = await shouldPlayCelebration();773        return { ok: true, data: should };774      }775      case "MARK_CELEBRATION_PLAYED": {776        await markCelebrationPlayed();777        return { ok: true };778      }779      case "GET_CODEX_VAULT_DATA": {780        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the781        // popup navigates to the License section without further coordination.782        const gate = await requirePro("codex");783        if (!gate.allowed) return { ok: false, error: "pro_required" };784        return await handleGetCodexVaultData();785      }786      case "ESTIMATE_CODEX_PAGES": {787        const gate = await requirePro("codex");788        if (!gate.allowed) return { ok: false, error: "pro_required" };789        return await handleEstimateCodexPages();790      }791      case "RESTORE_FROM_CODEX": {792        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still793        // be able to restore a vault that was printed by a Pro user.794        // DO NOT add a Pro gate here.795        const payload = msg.payload as CodexRestorePayload;796        return await handleRestoreFromCodex(payload);797      }798      case "OPEN_PRO_GATE": {799        // Content script requests: open popup and navigate to License section.800        const { feature } = (msg.payload ?? {}) as { feature?: string };801        if (chrome.storage.session) {802          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });803        }804        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }805        return { ok: true };806      }807      case "GET_IDENTITIES": {808        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };809        return { ok: true, data: vault.getIdentities() };810      }811      case "TOUCH_AUTO_LOCK": {812        // touchAutoLock() is already called by shouldRefreshAutoLock above;813        // this case just gives the popup a typed message to keep the session alive.814        return { ok: true };815      }816      case "GET_ADVANCED_HEALTH_REPORT": {817        const gate = await requirePro("advanced_health");818        if (!gate.allowed) return { ok: false, error: "pro_required" };819        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };820        const report = await buildAdvancedHealthReport(vault.getEntries());821        return { ok: true, data: report };822      }823      case "IS_DURESS_ENABLED": {824        const enabled = await vault.isDuressEnabled();825        return { ok: true, data: enabled };826      }827      case "SETUP_DURESS": {828        // Single enforcement point for the Duress Vault Pro gate. Free users829        // who somehow reach this handler are rejected here; the popup also830        // pre-checks isPro() to avoid showing the setup form to free users,831        // but server-side is the actual security boundary.832        const gate = await requirePro("duress_vault");833        if (!gate.allowed) return { ok: false, error: "pro_required" };834        // MV3 service workers restart after inactivity, losing the in-memory835        // derived key. Detect this before calling setupDuress so the popup836        // can show a meaningful prompt to re-lock and re-unlock.837        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };838        const { duressPassword } = msg.payload as { duressPassword: string };839        await vault.setupDuress(duressPassword);840        return { ok: true };841      }842      case "DISABLE_DURESS": {843        await vault.disableDuress();844        return { ok: true };845      }846      case "VERIFY_MAIN_PASSWORD": {847        const { password } = msg.payload as { password: string };848        const ok = await vault.verifyMainPassword(password);849        return { ok: true, data: ok };850      }851      case "CHANGE_PASSWORD": {852        const { currentPassword, newPassword } = msg.payload as {853          currentPassword: string;854          newPassword: string;855        };856        const changed = await vault.changePassword(currentPassword, newPassword);857        return changed858          ? { ok: true }859          : { ok: false, error: "incorrect_current_password" };860      }861      case "GET_SITE_PASSWORD_POLICY": {862        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });863        if (!tab?.id) return { ok: true, data: null };864        try {865          const response = await chrome.tabs.sendMessage(tab.id, {866            type: "GET_SITE_PASSWORD_POLICY",867          });868          return (response as MessageResponse) ?? { ok: true, data: null };869        } catch {870          return { ok: true, data: null };871        }872      }873      case "RECORD_MANUAL_SUMMON": {874        const { domain } = msg.payload as { domain: string };875        const settings = vault.getSettings();876        const existing = settings.manualSummonDomains?.[domain];877        const now = Date.now();878        await vault.updateSettings({879          manualSummonDomains: {880            ...settings.manualSummonDomains,881            [domain]: {882              firstSummonedAt: existing?.firstSummonedAt ?? now,883              summonCount: (existing?.summonCount ?? 0) + 1,884              lastSummonedAt: now,885            },886          },887        });888        return { ok: true };889      }890      case "DECLINE_CARD_SAVE": {891        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };892        await vault.declineCardSaveOffer(last4, expMonth, expYear);893        return { ok: true };894      }895      case "IS_CARD_DECLINED": {896        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };897        const declined = await vault.isCardDeclined(last4, expMonth, expYear);898        return { ok: true, data: declined };899      }900      case "INITIATE_FIREFOX_PASSKEY_CREATE": {901        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {902          rpId?: string;903          rpName?: string;904          userName?: string;905          userDisplayName?: string;906        };907        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };908        return await initiateFirefoxPasskeyCreate({909          rpId,910          rpName: rpName ?? rpId,911          userName,912          userDisplayName,913        });914      }915916      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {917        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;918        if (!payload) return { ok: false, error: "missing_payload" };919        return await completeFirefoxPasskeyCreate(payload);920      }921922      case "PASSKEY_OFFER_DECLINE": {923        const { domain } = (msg.payload ?? {}) as { domain?: string };924        if (!domain) return { ok: false, error: "domain_required" };925        await recordPasskeyOfferDecline(domain);926        return { ok: true };927      }928929      case "GET_PASSKEY_OFFER_DECLINED": {930        const { domain } = (msg.payload ?? {}) as { domain?: string };931        if (!domain) return { ok: false, error: "domain_required" };932        return { ok: true, data: await isPasskeyOfferDeclined(domain) };933      }934935      case "PASSKEY_HAS_CREDENTIALS": {936        const payload = msg.payload as {937          rpId?: string;938          allowCredentials?: Array<{ id: string; type?: string }>;939        } | undefined;940        if (!payload?.rpId) return { ok: false, error: "rpid_required" };941        return await handlePasskeyHasCredentials({942          rpId: payload.rpId,943          allowCredentials: payload.allowCredentials ?? [],944        }, attestedSenderOrigin(sender));945      }946947      case "PASSKEY_CREATE": {948        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;949        if (!payload?.rpId || !payload?.userName) {950          return { ok: false, error: "rpid_and_username_required" };951        }952        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));953      }954955      case "PASSKEY_GET": {956        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;957        if (!payload?.rpId) return { ok: false, error: "rpid_required" };958        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));959      }960961      case "PASSKEY_AUTH_RESPONSE": {962        const { requestId, approved } = (msg.payload ?? {}) as {963          requestId?: string | number;964          approved?: boolean;965        };966        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {967          return { ok: false, error: 'requestId and approved required' };968        }969        await resolvePendingPasskeyRequest(Number(requestId), approved);970        return { ok: true };971      }972973      case "GET_PASSKEY_FOR_DOMAIN": {974        const { domain } = (msg.payload ?? {}) as { domain?: string };975        if (!domain) return { ok: false, error: "domain_required" };976        // Scope to the caller's own origin: a page may only ask about passkeys977        // for a domain it actually owns, so an arbitrary page cannot enumerate978        // which sites the user holds passkeys for or read the username (audit MEDIUM).979        const origin = attestedSenderOrigin(sender);980        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };981        if (!vault.isUnlocked()) return { ok: true, data: null };982        const match = vault983          .getEntries()984          .find((entry) => entry.passkey?.rpId === domain);985        if (!match || !match.passkey) return { ok: true, data: null };986        // Slim shape — only the fields State 11 needs. Never expose private987        // key material, even though this is locked behind isUnlocked.988        return {989          ok: true,990          data: {991            rpId: match.passkey.rpId,992            userName: match.passkey.userName,993            browser: match.passkey.browser,994          },995        };996      }997998      case "DESTROY_VAULT": {999        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1000        // storage.local.clear() wipes every Peach key (slots, settings, license,1001        // onboarded flag, history, sync state, declined cards, recall, etc.);1002        // session.clear() wipes pending passkey requests + pro-notice queues.1003        // Caller (Panic.tsx) handles UI navigation back to onboarding.1004        //1005        // The Pro license is the one thing that must survive: the user paid for1006        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1007        // Capture it before the clear and restore it after. peach_pro_celebrated1008        // rides along so the Pro celebration doesn't replay on the next unlock.1009        const preserved = await chrome.storage.local.get([1010          "peach_license",1011          "peach_pro_celebrated",1012        ]);1013        vault.lock();1014        await storageClear();1015        await vault.clearVaultHistory();1016        const toRestore: Record<string, unknown> = {};1017        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1018        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1019        if (Object.keys(toRestore).length > 0) {1020          await chrome.storage.local.set(toRestore);1021        }1022        if (chrome.storage.session) {1023          await chrome.storage.session.clear();1024        }1025        return { ok: true };1026      }10271028      case "SUBMIT_FEEDBACK": {1029        const { category, message, version, browser } = msg.payload as {1030          category: string;1031          message: string;1032          version: string;1033          browser: string;1034        };1035        if (!message.trim()) return { ok: false, error: "message_empty" };1036        if (!FEEDBACK_ENDPOINT) return { ok: true };1037        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1038          return { ok: false, error: "invalid_feedback_endpoint" };1039        }1040        try {1041          const res = await fetch(FEEDBACK_ENDPOINT, {1042            method: "POST",1043            headers: { "Content-Type": "application/json" },1044            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1045          });1046          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1047        } catch (err) {1048          return { ok: false, error: err instanceof Error ? err.message : "network_error" };1049        }1050      }1051      // Android-only: biometric unlock with pre-derived key.1052      case "UNLOCK_WITH_KEY": {1053        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1054        if (!isNativePlatform()) {1055          return { ok: false, error: "desktop_only_uses_password" };1056        }1057        try {1058          const result = await vault.unlockWithKey(masterKeyHex);1059          if (result.ok) {1060            onVaultUnlocked();1061            await publishInMemoryVault(result.entries);1062          }1063          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1064        } catch {1065          return { ok: false, error: "invalid_key" };1066        }1067      }1068      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1069      case "GET_DERIVED_KEY": {1070        if (!isNativePlatform()) {1071          return { ok: false, error: "android_only" };1072        }1073        if (!vault.isUnlocked()) {1074          return { ok: false, error: "vault_locked" };1075        }1076        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1077      }1078      case "GET_IDENTITY_SUGGESTIONS": {1079        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1080        const entries = vault.getEntries();1081        const suggestions = buildIdentitySuggestions(entries);1082        return { ok: true, data: { suggestions } };1083      }1084      case "POPULATE_INLINE_VAULT": {1085        if (!isNativePlatform()) return { ok: false };1086        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1087        const entries = vault.getEntries();1088        await publishInMemoryVault(entries);1089        return { ok: true };1090      }1091      case "ML_INIT":1092        return { ok: true };10931094      case "ML_PREDICT_BATCH": {1095        // AUD-002: shape-validate before forwarding to the ML helper.1096        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1097        if (!Array.isArray(featuresArray)) {1098          return { ok: false, error: "invalid_payload" };1099        }1100        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1101      }11021103      // ── Chirp Sync (v3) ───────────────────────────────────────────────1104      // Returns the public-facing local identity needed by the popup to1105      // drive Phase-1 audio pairing. The private long-term key never1106      // leaves the background.1107      case "CHIRP_GET_LOCAL_IDENTITY": {1108        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1109        const proCheck = await requirePro("sync");1110        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1111        // Identity derives from the stable root key, not the password-derived1112        // key, so pairing survives a master-password change (SEV-2-B).1113        const masterKeyHex = vault.getRootKeyHex();1114        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1115        const masterKey = unhexBytes(masterKeyHex);1116        try {1117          const identity = await buildLocalIdentity(masterKey);1118          return { ok: true, data: identity };1119        } finally {1120          masterKey.fill(0);1121        }1122      }11231124      case "CHIRP_COMPLETE_PAIRING": {1125        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1126        const proCheck = await requirePro("sync");1127        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1128        const paired = (msg.payload as { paired?: unknown })?.paired;1129        if (typeof paired !== "object" || paired === null) {1130          return { ok: false, error: "invalid_payload" };1131        }1132        const candidate = paired as Record<string, unknown>;1133        if (1134          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1135          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1136          typeof candidate.deviceType !== "string" ||1137          typeof candidate.longTermPublicKeyHex !== "string" ||1138          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1139          (1140            candidate.signingPublicKeyHex !== undefined &&1141            (1142              typeof candidate.signingPublicKeyHex !== "string" ||1143              !/^[0-9a-f]{64}$/.test(candidate.signingPublicKeyHex)1144            )1145          ) ||1146          typeof candidate.pairedAt !== "number"1147        ) {1148          return { ok: false, error: "invalid_paired_device" };1149        }1150        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1151        return { ok: true };1152      }11531154      case "CHIRP_LIST_PAIRED_DEVICES": {1155        const devices = await listPairedDevicesV3();1156        return { ok: true, data: { devices } };1157      }11581159      case "CHIRP_UNPAIR_DEVICE": {1160        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1161        if (typeof deviceId !== "string" || !deviceId) {1162          return { ok: false, error: "invalid_payload" };1163        }1164        await removePairedDeviceByIdV3(deviceId);1165        return { ok: true };1166      }11671168      case "CHIRP_RENAME_LOCAL_DEVICE": {1169        const { name } = (msg.payload ?? {}) as { name?: string };1170        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1171        await setDeviceNameV3(name);1172        return { ok: true };1173      }11741175      case "TRIGGER_SYNC": {1176        const payload = (msg.payload ?? {}) as {1177          reason?: "vault_change" | "foreground" | "manual" | "mdns";1178          force?: boolean;1179          deviceId?: string;1180          discoveredIp?: string;1181          discoveredPort?: number;1182        };1183        const reason = payload.reason ?? "foreground";11841185        // mDNS discovery delivers a fresh (ip, port) resolved by the native1186        // side. Update the cached address before the sync runner tries to1187        // connect — avoids a subnet probe on the very next round.1188        if (1189          reason === "mdns" &&1190          typeof payload.deviceId === "string" &&1191          typeof payload.discoveredIp === "string"1192        ) {1193          const { findPairedDeviceById, setLastKnownIp } = await import("./paired-devices");1194          const device = await findPairedDeviceById(payload.deviceId);1195          if (device?.longTermPublicKeyHex) {1196            await setLastKnownIp(device.longTermPublicKeyHex, payload.discoveredIp).catch(() => undefined);1197          }1198        }11991200        const { triggerSyncIfReachable } = await import("./sync-trigger");1201        void triggerSyncIfReachable({ reason, force: payload.force === true });1202        return { ok: true };1203      }12041205      case "GET_SYNC_STATE": {1206        const { getSyncState } = await import("./sync-trigger");1207        return { ok: true, data: getSyncState() };1208      }12091210      default:1211        return { ok: false, error: "unknown_message_type" };1212    }1213  } catch (err) {1214    return {1215      ok: false,1216      error: err instanceof Error ? err.message : "operation_failed",1217    };1218  }1219}12201221// --- Mobile platform helpers ---12221223// Android: populates the in-memory vault used by PeachAutofillService.1224async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1225  const plugin = nativePlugin<{1226    setEntries?: (args: {1227      entries: Array<{1228        id: string;1229        title: string;1230        username: string;1231        email: string;1232        password: string;1233        url: string;1234        totp: string;1235        additionalUrls: string[];1236      }>;1237    }) => Promise<void>;1238  }>("InMemoryVaultPlugin");1239  if (!plugin?.setEntries) return;1240  await plugin.setEntries({1241    entries: entries.map((e) => ({1242      id: e.id,1243      title: e.title ?? "",1244      username: e.username ?? "",1245      email: (e as VaultEntry & { email?: string }).email ?? "",1246      password: e.password ?? "",1247      url: e.url ?? "",1248      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1249      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1250    })),1251  });1252}12531254// Android: clear the autofill in-memory store on lock.1255async function clearInMemoryVault(): Promise<void> {1256  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1257  if (!plugin?.clearEntries) return;1258  await plugin.clearEntries();1259}12601261// Returns username use-counts from the vault, sorted by frequency. Each row1262// also carries the entry's email so the popup can suggest the email/username1263// pair the user has actually used together.1264function buildIdentitySuggestions(1265  entries: VaultEntry[],1266): Array<{ email: string; username: string; count: number }> {1267  const usernameCounts = new Map<string, number>();1268  const usernameEmail = new Map<string, string>();1269  for (const entry of entries) {1270    const username = entry.username ?? "";1271    const email = (entry as VaultEntry & { email?: string }).email ?? "";1272    if (!username && !email) continue;1273    const key = username || email;1274    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1275    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1276  }1277  return Array.from(usernameCounts.entries())1278    .sort((a, b) => b[1] - a[1])1279    .map(([username, count]) => ({1280      email: usernameEmail.get(username) ?? "",1281      username,1282      count,1283    }));1284}12851286/** Notify all content scripts that the vault just became available. */1287function broadcastToContentScripts(message: { type: string }): void {1288  if (!chrome.tabs?.query) return;1289  chrome.tabs.query({}, (tabs) => {1290    for (const tab of tabs) {1291      if (tab.id !== undefined) {1292        chrome.tabs.sendMessage(tab.id, message).catch(() => {1293          // Tab may not have a content script — silently ignore1294        });1295      }1296    }1297  });1298}12991300function shouldRefreshAutoLock(type: MessageType): boolean {1301  return (1302    type !== "HAS_VAULT" &&1303    type !== "IS_UNLOCKED" &&1304    type !== "GET_VAULT_STATUS" &&1305    type !== "LOCK" &&1306    type !== "UPDATE_SETTINGS" &&1307    type !== "GET_PENDING_PASSKEY" &&1308    type !== "GET_PASSKEY_PROVIDER_STATE" &&1309    type !== "DECLINE_CARD_SAVE" &&1310    type !== "IS_CARD_DECLINED" &&1311    type !== "SUBMIT_FEEDBACK"1312  );1313}13141315function isAllowedCanaryWebhookUrl(value: string): boolean {1316  try {1317    const url = new URL(value);1318    if (url.protocol !== "https:") return false;13191320    const hostname = url.hostname.toLowerCase();1321    if (1322      hostname === "localhost" ||1323      hostname.endsWith(".localhost") ||1324      isPrivateIpv4(hostname) ||1325      isPrivateIpv6(hostname)1326    ) {1327      return false;1328    }13291330    return true;1331  } catch {1332    return false;1333  }1334}13351336function isPrivateIpv4(hostname: string): boolean {1337  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1338    return true;1339  }13401341  const octets = hostname.split(".").map((part) => Number(part));1342  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1343    return false;1344  }13451346  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1347}13481349function isPrivateIpv6(hostname: string): boolean {1350  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1351  return (1352    normalized === "::1" ||1353    normalized.startsWith("fc") ||1354    normalized.startsWith("fd") ||1355    normalized.startsWith("fe80:")1356  );1357}