messages.ts

71.8 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, getEffectiveClearSeconds } from "./clipboard";13import { getPendingSyncAlerts, clearPendingSyncAlerts } from "./sync-alerts";14import { extractDomain } from "../shared/domain";15import {16  getPendingVouchedDevice,17  listPendingVouchedDevices,18  removePendingVouchedDevice,19} from "./pending-vouched-devices";20import { isRecoveryConfirmPending } from "./recovery-pending";21import { setupAutoLock, touchAutoLock } from "./alarms";22import { runSelfTest } from "./self-test";23import * as vault from "./vault";24import {25  handleEstimateCodexPages,26  handleGetCodexVaultData,27  handleRestoreFromCodex,28} from "./codex-handlers";29import type { CodexRestorePayload } from "../shared/codex-types";30import {31  activateLicense,32  deactivateLicense,33  getLicenseInfo,34  getLicenseKey,35  isProUser,36  markCelebrationPlayed,37  shouldPlayCelebration,38} from "./license";39import {40  completeFirefoxPasskeyCreate,41  getPasskeyProviderState,42  getPendingPasskeyRequest,43  handleFirefoxPasskeyCreate,44  handleFirefoxPasskeyGet,45  handlePasskeyHasCredentials,46  initiateFirefoxPasskeyCreate,47  isPasskeyOfferDeclined,48  onVaultUnlocked,49  recordPasskeyOfferDecline,50  resolvePendingPasskeyRequest,51  setPasskeyProviderEnabled,52} from "./passkey";53import { buildAdvancedHealthReport } from "./health";54import { storageClear } from "../shared/storage";55import { findInvalidWords } from "../shared/recovery-words";56import type {57  Message,58  MessageResponse,59  MessageType,60  ProFeature,61  VaultEntry,62} from "../shared/types";63import { isPasskeyOnly } from "../shared/types";64import { generateTOTP } from "../crypto/totp";65import { isValidRpId } from "../shared/passkey-utils";66import { predictBatch as mlPredictBatch } from "./ml";67import type { MLFieldFeatures } from "../shared/ml";68import {69  buildLocalIdentity,70  getOrCreateDeviceId,71  setDeviceName as setDeviceNameV3,72} from "./device-identity";73import {74  isDeviceRevoked,75  listPairedDevices as listPairedDevicesV3,76  renamePairedDevice as renamePairedDeviceV3,77  revokeDeviceById as revokeDeviceByIdV3,78  upsertPairedDevice as upsertPairedDeviceV3,79} from "./paired-devices";80// Sync and pairing are imported statically, never with `await import()`.81// `import()` throws `TypeError: import() is disallowed on82// ServiceWorkerGlobalScope` at runtime in MV3, and Vite's preload helper83// reports the failure through `window.dispatchEvent`, which does not exist in84// a worker either — so the real reason was replaced by "window is not defined"85// and the pairing UI just stopped. scripts/check-sw-static-imports.mjs fails86// the build if a runtime import() reappears anywhere in the worker's graph.87import {88  cancelRelayAdoptionSource,89  isRelayAdoptionSourceInFlight,90  resolveSourceSasConfirmation,91  startRelayAdoptionReceiver,92  startRelayAdoptionSource,93} from "./relay-adoption-bg";94import {95  getSyncSettings,96  setRelayUrl,97  setSyncMode,98  type SyncMode,99} from "./sync-settings";100import {101  getSyncState,102  triggerSyncIfReachable,103} from "./sync-trigger";104105// Compile-time E2E flag, folded to a literal by Vite's `define` (false in106// every production build — verified in the bundled output). Mirrors the107// create-path bypass in passkey.ts so the Playwright passkey smoke can enable108// the provider without a real Pro licence; the gate is fully intact for users.109declare const __PEACH_E2E_PASSKEYS__: boolean;110const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true;111112function unhexBytes(hex: string): Uint8Array {113  if (hex.length % 2 !== 0) throw new Error("invalid hex");114  const out = new Uint8Array(hex.length / 2);115  for (let i = 0; i < out.length; i++) {116    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);117  }118  return out;119}120121/**122 * The single Pro gate. Every gated handler calls this first; the broadcast123 * lets the popup react (navigate to the License section, highlight the124 * relevant feature). Background never touches the popup view directly —125 * the popup owns navigation. See Projects.md "Pro gate rule".126 */127async function requirePro(128  feature: ProFeature,129  trigger: "user" | "background" = "user"130): Promise<{ allowed: boolean }> {131  if (PASSKEY_E2E_PRO_BYPASS && feature === "passkeys") return { allowed: true };132  if (await isProUser()) return { allowed: true };133134  if (trigger === "user") {135    // User deliberately triggered this feature — redirect the popup immediately.136    chrome.runtime137      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })138      .catch(() => {139        // Popup may be closed — the gate signal is best-effort.140      });141  } else {142    // Background trigger (e.g. passive sync initiation) — no popup is open.143    // Queue a notice so the next popup open shows a soft banner instead of144    // silently failing.145    if (chrome.storage.session) {146      chrome.storage.session147        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })148        .catch(() => {});149    }150  }151152  return { allowed: false };153}154155// ---------------------------------------------------------------------------156// PCH-01-018: operations that irreversibly destroy or replace vault contents,157// handlers that store passkey material, and handlers that return sensitive158// credential material (e.g. the Pro license key). These are gated to trusted159// extension-page senders in handleMessage; the confirmation UX otherwise160// lives only in the popup. Keep this in sync when adding new destructive or161// sensitive handlers. (Codex Security 2026-08-04: GET_ADOPTION_MATERIAL and162// COMPLETE_PAIRING were gated here, then deleted outright — they had no163// legitimate senders; adoption runs in-background via relay-adoption-bg.ts.164// Audit 2026-08-20 #4: GET_LOCAL_IDENTITY gated here — it returns the Pro165// license key, which a compromised content script could exfiltrate.)166const PRIVILEGED_MESSAGE_TYPES: ReadonlySet<string> = new Set([167  "DESTROY_VAULT",168  "CLEAR_VAULT_ENTRIES",169  "RESTORE_VAULT_SNAPSHOT",170  "RESTORE_FROM_CODEX",171  "COMPLETE_FIREFOX_PASSKEY_CREATE",172  "UNLOCK_WITH_PIN",173  "SETUP_PIN",174  "DISABLE_PIN",175  "GET_LOCAL_IDENTITY",176]);177178// LV-3: minimum interval between non-test canary pings per webhook+entry.179const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour180181const PRIVATE_IPV4_RANGES = [182  { prefix: "10." },183  { prefix: "127." },184  { prefix: "169.254." },185  { prefix: "192.168." },186];187188export function setupMessageHandler(): void {189  chrome.runtime.onMessage.addListener(190    (msg: unknown, sender, sendResponse) => {191      if (!isMessage(msg)) {192        sendResponse({ ok: false, error: "invalid_message" });193        return true;194      }195      handleMessage(msg, sender)196        .then(sendResponse)197        .catch((err) =>198          sendResponse({199            ok: false,200            error: err instanceof Error ? err.message : String(err),201          })202        );203      return true;204    }205  );206}207208function isMessage(m: unknown): m is Message {209  return typeof m === "object" && m !== null && "type" in m;210}211212/**213 * The browser-attested origin of the page that originated this message. A web214 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),215 * so every page-driven message arrives via the content-script relay and the216 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a217 * value the page cannot forge. This is the ONLY trustworthy origin for passkey218 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.219 */220function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {221  if (sender.origin) return sender.origin;222  if (sender.url) {223    try { return new URL(sender.url).origin; } catch { return undefined; }224  }225  return undefined;226}227228// Resolves once restoreFromSession() has run, so handlers see the correct229// post-restore unlock state. entry.ts registers this BEFORE the message230// handler so the onMessage listener is added synchronously at SW startup231// (MV3 requirement) while unlock-dependent handlers still wait for restore.232let restoreReady: Promise<void> = Promise.resolve();233234/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */235export function setRestoreReady(p: Promise<unknown>): void {236  restoreReady = p.then(() => undefined, () => undefined);237}238239export async function handleMessage(240  msg: Message,241  sender: Partial<chrome.runtime.MessageSender> = {}242): Promise<MessageResponse> {243  try {244    // Wait for session-restore to finish before reading any unlock/vault state.245    // On a cold SW start the popup's first message arrives while restore is246    // still in flight; without this gate IS_UNLOCKED would report locked (a247    // spurious lock screen) and the storage reads could race. The onMessage248    // listener itself is registered synchronously (entry.ts) so this gate, not249    // listener registration, is what absorbs the cold-start window.250    await restoreReady;251    // Validate sender — only allow messages from our extension pages/scripts.252    // `sender.id` is undefined for messages originating from extension UI253    // (popup/options), which is legitimate; reject only when it is defined254    // and does not match our extension id.255    if (256      sender.id !== undefined &&257      sender.id !== chrome.runtime.id258    ) {259      return { ok: false, error: "invalid_sender" };260    }261262    // PCH-01-018: destructive and sensitive operations must originate from a263    // trusted extension page (popup/options), never from a content script. The264    // sender.id check above only proves the message came from *our* extension —265    // a content script injected into an attacker page passes it. A single266    // XSS-class bug in the injected UI would otherwise escalate to vault267    // destruction, root-key exfiltration, or attacker device registration.268    // Extension pages carry an extension-origin sender.url; content scripts269    // carry a page URL.270    if (PRIVILEGED_MESSAGE_TYPES.has(msg.type)) {271      const extensionOrigin = chrome.runtime.getURL("");272      if (!sender.url?.startsWith(extensionOrigin)) {273        return { ok: false, error: "invalid_sender" };274      }275    }276277    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {278      touchAutoLock();279    }280281    switch (msg.type) {282      case "CREATE_VAULT": {283        const { password } = msg.payload as { password: string };284        // Refuse to create a vault under an empty master password — the derived285        // key would be publicly known and the at-rest AES-GCM protection void286        // (audit HIGH; the CSV-import path previously passed ""). Length/strength287        // policy lives in the onboarding UI; this is the non-negotiable floor.288        if (typeof password !== "string" || password.length === 0) {289          return { ok: false, error: "invalid_payload" };290        }291        await vault.createVault(password);292        await setupAutoLock();293        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });294        onVaultUnlocked();295        return { ok: true };296      }297      case "CREATE_VAULT_FROM_ROOT_KEY": {298        console.log("[Peach diag] CREATE_VAULT_FROM_ROOT_KEY handler entered");299        const { password, rootKeyHex } = (msg.payload ?? {}) as {300          password?: unknown;301          rootKeyHex?: unknown;302        };303        console.log("[Peach diag] payload types:", typeof password, typeof rootKeyHex, "lengths:", (password as string)?.length, (rootKeyHex as string)?.length);304        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {305          console.log("[Peach diag] payload invalid, returning invalid_payload");306          return { ok: false, error: "invalid_payload" };307        }308309        try {310          console.log("[Peach diag] calling vault.createVaultFromRootKey");311          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);312          console.log("[Peach diag] createVaultFromRootKey returned vaultId", vaultId);313          await setupAutoLock();314          console.log("[Peach diag] setupAutoLock done");315          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });316          onVaultUnlocked();317          console.log("[Peach diag] handler completing successfully");318          return { ok: true, vaultId };319        } catch (err) {320          console.error("[Peach diag] handler caught error:", err);321          return { ok: false, error: err instanceof Error ? err.message : String(err) };322        }323      }324      case "UNLOCK": {325        const { password } = msg.payload as { password: string };326        const ok = await vault.unlock(password);327        if (ok) {328          // KAT: verify the WebCrypto stack is healthy before the user relies on it.329          // Runs after unlock so latency is hidden behind the vault-load time.330          const kat = await runSelfTest();331          if (!kat.ok) {332            console.error("[Peach] Crypto self-test FAILED:", kat.error);333            await vault.lock();334            return { ok: false, error: "self_test_failed" };335          }336          await vault.updateSettings({ pinPreferred: false });337          await setupAutoLock();338          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });339          onVaultUnlocked();340          return { ok: true };341        }342        // Distinguish corruption from wrong password so the popup can offer343        // a history-restore path instead of falsely accusing the user of344        // mistyping (M7/COR-007).345        const failure = vault.consumeLastUnlockFailureReason();346        if (failure) {347          return {348            ok: false,349            error: "vault_corrupted",350            canRestoreFromHistory: true,351          } as MessageResponse;352        }353        return { ok: false };354      }355      case "UNLOCK_WITH_PIN": {356        const { pin } = (msg.payload ?? {}) as { pin?: unknown };357        if (typeof pin !== "string") return { ok: false, error: "invalid_payload" };358        const ok = await vault.unlockWithPin(pin);359        if (!ok) return { ok: false };360        const kat = await runSelfTest();361        if (!kat.ok) {362          await vault.lock();363          return { ok: false, error: "self_test_failed" };364        }365        await vault.updateSettings({ pinPreferred: true });366        await setupAutoLock();367        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });368        onVaultUnlocked();369        return { ok: true };370      }371      case "VALIDATE_RECOVERY_WORDS": {372        const { words } = msg.payload as { words: string[] };373        const invalid = findInvalidWords(words);374        return { ok: true, data: { valid: invalid.length === 0, invalid } };375      }376      case "GET_RECOVERY_WORDS": {377        // Must be unlocked and have recovery set up (vault must be v2.12+).378        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };379        // LV-4: the recovery words re-derive the ROOT KEY — the highest-380        // value secret in the vault. A session unlock (which may be hours381        // old on a shared machine) is not enough; require a fresh password382        // proof, matching the 1Password/Bitwarden pattern for revealing383        // escrow material. EXEMPTION: the create-vault / rotation confirmation384        // window (peach_recovery_pending) shows the words immediately after385        // the user authenticated, and that confirmation UI has no password to386        // resend — skip the re-auth there only.387        if (!(await isRecoveryConfirmPending())) {388          const { password } = (msg.payload ?? {}) as { password?: string };389          if (typeof password !== "string" || !password) {390            return { ok: false, error: "password_required" };391          }392          if (!(await vault.verifyMainPassword(password))) {393            return { ok: false, error: "wrong_password" };394          }395        }396        try {397          const words = await vault.getRecoveryWords();398          return { ok: true, data: words };399        } catch {400          // pre-v2.12 vault that hasn't migrated401          return { ok: false, error: "recovery_not_setup" };402        }403      }404      case "RECOVER_WITH_WORDS": {405        // User has lost their password but has their 12 recovery words.406        // We: (1) validate the words, (2) re-encrypt vault with new password.407        const { words, newPassword } = msg.payload as {408          words: string[];409          newPassword: string;410        };411        const stored = await vault.loadSlotA();412        if (!stored) return { ok: false, error: "no_vault" };413        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {414          return { ok: false, error: "recovery_not_setup" };415        }416        // Unwrap the root key from the recovery escrow.417        try {418          await vault.unwrapRootKeyForRecovery(419            stored.recovery_wrapped_root_key,420            stored.recovery_nonce ?? "",421            stored.recovery_tag ?? "",422            stored.recovery_salt,423            words424          );425        } catch {426          return { ok: false, error: "invalid_recovery_words" };427        }428        // Re-key: derive fresh salt + key from new password.429        const newSalt = vault.generateSalt();430        const newKey = await vault.deriveKey(newPassword, newSalt);431        // Re-wrap root key under the new password's derived key so the same432        // recovery words continue to work after the password change.433        await vault.rewrapRootKeyForPassword(newKey, newSalt);434        // Re-encrypt vault entries with the new key.435        await vault.changePasswordWithNewKey(newSalt, newKey);436        await setupAutoLock();437        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });438        return { ok: true };439      }440      case "LOCK":441        vault.lock();442        return { ok: true };443      case "IS_UNLOCKED":444        return { ok: true, data: vault.isUnlocked() };445      case "GET_VAULT_STATUS":446        return { ok: true, unlocked: vault.isUnlocked() };447      case "HAS_VAULT":448        return { ok: true, data: await vault.hasVault() };449      case "GET_ENTRIES":450        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };451        return { ok: true, data: vault.getEntries() };452      case "ADD_ENTRY": {453        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };454        const payload = msg.payload;455        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {456          return { ok: false, error: "invalid_payload" };457        }458        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);459        return { ok: true, data: entry };460      }461      case "BATCH_ADD_ENTRIES": {462        const payload = msg.payload as { entries?: unknown } | null | undefined;463        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {464          return { ok: false, error: "invalid_payload" };465        }466        if (!Array.isArray(payload.entries)) {467          return { ok: false, error: "invalid_payload" };468        }469        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);470        return { ok: true, data: added };471      }472      case "RESTORE_ENTRIES": {473        const payload = msg.payload as474          | { entries?: unknown; mode?: unknown; settings?: unknown }475          | null476          | undefined;477        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {478          return { ok: false, error: "invalid_payload" };479        }480        if (!Array.isArray(payload.entries)) {481          return { ok: false, error: "invalid_payload" };482        }483        if (payload.mode !== "replace" && payload.mode !== "merge") {484          return { ok: false, error: "invalid_payload" };485        }486        const summary = await vault.restoreEntries(487          payload.entries as Parameters<typeof vault.restoreEntries>[0],488          payload.mode489        );490        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {491          await vault.updateSettings(payload.settings as vault.VaultSettings);492        }493        return { ok: true, data: summary };494      }495      case "CLEAR_VAULT_ENTRIES": {496        await vault.clearVaultEntries("REPLACE_ALL");497        return { ok: true };498      }499      case "GET_VAULT_HISTORY": {500        const snapshots = await vault.getVaultHistory();501        return { ok: true, data: snapshots };502      }503      case "RESTORE_VAULT_SNAPSHOT": {504        const { snapshotId } = msg.payload as { snapshotId: string };505        const result = await vault.restoreVaultSnapshot(snapshotId);506        if (!result.ok) return { ok: false, error: result.error };507        broadcastToContentScripts({ type: "VAULT_LOCKED" });508        return { ok: true };509      }510      case "COUNT_DUPLICATES": {511        return { ok: true, data: vault.countDuplicates() };512      }513      case "DEDUPLICATE_ENTRIES": {514        const removed = await vault.deduplicateEntries();515        return { ok: true, data: removed };516      }517      case "UPDATE_ENTRY": {518        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;519        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {520          return { ok: false, error: "invalid_payload" };521        }522        const { id, patch } = payload;523        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {524          return { ok: false, error: "invalid_payload" };525        }526        // Single enforcement point for the Canary Entries Pro gate. Only527        // gates the transition into a canary entry — clearing/disabling a528        // canary (`canary: undefined`) is always allowed, so existing529        // canary entries remain manageable.530        const incomingCanary = (patch as { canary?: unknown }).canary;531        if (incomingCanary && typeof incomingCanary === "object") {532          const existing = vault.getEntryById(id);533          if (!existing?.canary) {534            const gate = await requirePro("canary_entry");535            if (!gate.allowed) return { ok: false, error: "pro_required" };536          }537        }538        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);539        return { ok: true };540      }541      case "ADD_ADDITIONAL_URL": {542        const { id, url } = msg.payload as { id: string; url: string };543        const trimmed = typeof url === "string" ? url.trim() : "";544        if (!trimmed) return { ok: false, error: "url_required" };545        const existing = vault.getEntryById(id);546        if (!existing) return { ok: false, error: "entry_not_found" };547        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };548        const merged = [...(existing.additionalUrls ?? []), trimmed];549        await vault.updateEntry(id, { additionalUrls: merged });550        return { ok: true };551      }552      case "DELETE_ENTRY": {553        const { id } = msg.payload as { id: string };554        await vault.deleteEntry(id);555        return { ok: true };556      }557      case "GET_DELETED_ENTRIES":558        return { ok: true, data: vault.getDeletedEntries() };559      case "RESTORE_ENTRY": {560        const { id } = msg.payload as { id: string };561        await vault.restoreEntry(id);562        return { ok: true };563      }564      case "PURGE_ENTRY": {565        const { id } = msg.payload as { id: string };566        await vault.purgeEntry(id);567        return { ok: true };568      }569      case "PURGE_EXPIRED_TRASH": {570        const { retentionMs } = msg.payload as { retentionMs: number };571        const purged = await vault.purgeExpiredTrash(retentionMs);572        return { ok: true, data: purged };573      }574      case "SAVE_NOTE": {575        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };576        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };577        const now = Date.now();578        if (id) {579          const existing = vault.getEntryById(id);580          if (!existing) return { ok: false, error: "not_found" };581          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });582          return { ok: true, data: vault.getEntryById(id) };583        } else {584          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt585          // (EntryDraft omits both), so passing them was the only reason the586          // `as any` cast existed. Dropping them makes the call type-check.587          const entry = await vault.addEntry({588            type: "note",589            title: title || "Untitled",590            notes: body,591          });592          return { ok: true, data: entry };593        }594      }595      case "DELETE_NOTE": {596        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };597        const { id } = msg.payload as { id: string };598        await vault.deleteEntry(id);599        return { ok: true };600      }601      case "GET_NOTES": {602        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };603        const notes = vault.getEntries().filter(604          (e) => e.type === "note" && !e.deletedAt605        );606        return { ok: true, data: notes } as MessageResponse;607      }608      case "SEARCH_VAULT": {609        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };610        // AUD-002: shape-validate the payload before calling string methods.611        // A raw cast lets a malformed message crash the handler with TypeError.612        const { query } = (msg.payload ?? {}) as { query?: unknown };613        if (typeof query !== "string") {614          return { ok: false, error: "invalid_payload" };615        }616        const q = query.toLowerCase();617        const searchResults = vault.getEntries().filter(618          (e) =>619            !e.deletedAt &&620            (e.title.toLowerCase().includes(q) ||621              e.notes?.toLowerCase().includes(q) ||622              e.username?.toLowerCase().includes(q))623        );624        return { ok: true, data: searchResults } as MessageResponse;625      }626      case "AUTOFILL_QUERY": {627        if (!vault.isUnlocked()) {628          return { ok: false, error: "vault_locked" };629        }630        let { includeAll } = msg.payload as { includeAll?: boolean };631        const { domain, kind, userGesture } = msg.payload as {632          domain: string;633          kind?: "login" | "card" | "totp";634          userGesture?: boolean;635        };636        // MV-2: the vault-wide inventory (every title/username/email/url)637        // may only leave the background on an explicit user gesture — the638        // user opening the search affordance — never on passive form focus.639        // userGesture is self-declared by our own content script; the value640        // of this gate is that PASSIVE code paths (which never set it)641        // cannot ship the inventory, shrinking what a compromised page that642        // merely triggers focus events can observe.643        if (includeAll && userGesture !== true) {644          includeAll = false;645        }646        // kind="card": return saved cards as compact summaries for the647        // inline card silver platter. Cards are not domain-scoped — every648        // saved card is a candidate on every checkout page — so domain is649        // ignored when kind === "card".650        if (kind === "card") {651          const cards = vault.getEntries().filter((e) => e.type === "card");652          return {653            ok: true,654            data: cards.map((e) => ({655              id: e.id,656              title: e.cardNickname || e.title,657              cardholderName: e.cardholderName,658              last4: e.last4,659              expMonth: e.expMonth,660              expYear: e.expYear,661              network: e.network,662            })),663          };664        }665        if (kind === "totp") {666          const matches = (667            includeAll668              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")669              : vault.queryDomain(domain)670          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));671          return {672            ok: true,673            data: matches.map((e) => ({674              id: e.id,675              title: e.title,676              username: e.username,677              email: e.email,678              url: e.url,679              hasTotp: true,680            })),681          };682        }683        // The inline selector fills username+password into a form. Passkey-684        // only entries have no password to fill; sign-in for those goes685        // through the WebAuthn path instead. Filter them out everywhere so686        // the user doesn't see four "GitHub" rows that mostly do nothing.687        // Notes and cards never belonged here either.688        const matches = (689          includeAll690            ? vault691                .getEntries()692                .filter((entry) => entry.type !== "note" && entry.type !== "card")693            : vault.queryDomain(domain)694        ).filter((entry) => !isPasskeyOnly(entry));695        return {696          ok: true,697          data: matches.map((e) =>698            includeAll699              ? {700                  id: e.id,701                  title: e.title,702                  // username/email/url shipped so the inline popup's search703                  // affordance can match on them, not just titles. No secrets704                  // cross the boundary — same shape as the domain-matched705                  // response below minus hasTotp (which the search list706                  // doesn't surface).707                  username: e.username,708                  email: e.email,709                  url: e.url,710                  hasPasskey: e.passkey !== undefined,711                }712              : {713                  id: e.id,714                  title: e.title,715                  username: e.username,716                  email: e.email,717                  url: e.url,718                  hasTotp: Boolean(e.totp),719                  hasPasskey: e.passkey !== undefined,720                }721          ),722        };723      }724      case "GET_ENTRY_FOR_FILL": {725        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };726        const { id, explicitSummon } = msg.payload as {727          id: string;728          explicitSummon?: boolean;729        };730        const entry = vault.getEntryById(id);731        if (!entry) return { ok: false, error: "entry_not_found" };732        // Passkey-only entries (passkey credential, no password) cannot be733        // filled into a form — sign-in goes through the WebAuthn path. A734        // login that ALSO has a passkey is still fillable for its password.735        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };736737        // MV-1: re-validate the entry against the requesting tab's origin.738        // sender.tab.url is browser-attested — a page cannot forge it. When739        // the request does not come from a tab at all (popup surfaces use740        // GET_ENTRY_FOR_EDIT, not this), refuse.741        if (sender.tab !== undefined || sender.url !== undefined) {742          let senderDomain: string | null = null;743          try {744            const rawUrl = sender.tab?.url ?? sender.url ?? "";745            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;746          } catch {747            senderDomain = null;748          }749          if (!senderDomain) return { ok: false, error: "origin_unverified" };750751          const entryDomains = new Set<string>();752          const primary = extractDomain(entry.url ?? "");753          if (primary) entryDomains.add(primary);754          for (const extra of entry.additionalUrls ?? []) {755            const d = extractDomain(extra);756            if (d) entryDomains.add(d);757          }758759          // explicitSummon=true means the user actively picked this entry760          // from the cross-domain search affordance — an intentional761          // off-domain fill. Passive fill paths must stay domain-bound.762          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {763            // Domain mismatch — refuse silently (no oracle about which ids exist).764            return { ok: false, error: "entry_not_found" };765          }766        }767        // Strip the passkey credential AND the raw base32 TOTP seed from the768        // response. Content scripts never need either: the private key is the769        // authenticator's, and handing over the TOTP seed would let a770        // compromised content script mint valid codes indefinitely (SEV-3-C).771        // Generate the *current* 6-digit code here in the background and send772        // only that, plus the seconds left so the UI can render a countdown.773        // Also drop passwordHistory: filling needs only the *current* password.774        // Handing every past password to a content script during passive775        // autofill on an arbitrary page would widen the blast radius of a776        // compromised page far beyond the one credential being filled.777        const {778          passkey: _strippedPasskey,779          totp: seed,780          totpAlgorithm,781          totpDigits,782          totpPeriod,783          passwordHistory: _ph,784          ...safeEntry785        } = entry;786        let totpCode: string | undefined;787        let totpRemaining: number | undefined;788        if (seed) {789          try {790            // PCH-01-019: honour stored algorithm/digits/period (defaults apply791            // when these are undefined, i.e. legacy bare-seed entries).792            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);793            totpCode = generated.code;794            totpRemaining = generated.remaining;795          } catch {796            totpCode = undefined;797          }798        }799        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };800      }801      // Trusted full-entry fetch for Peach's own inline-popup surfaces that802      // genuinely need the raw TOTP seed: the edit form (which re-saves the803      // seed and would otherwise wipe it) and nothing else. Unlike804      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside805      // the inline popup, never during passive autofill on an arbitrary page.806      // The passkey credential is still stripped — the edit form never touches it.807      case "GET_ENTRY_FOR_EDIT": {808        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };809        const { id, explicitSummon } = msg.payload as {810          id: string;811          explicitSummon?: boolean;812        };813        const entry = vault.getEntryById(id);814        if (!entry) return { ok: false, error: "entry_not_found" };815816        // PCH-01-006: re-validate the browser-attested sender origin, mirroring817        // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and818        // full password history — at least as sensitive as the fill response — so819        // the boundary must be enforced here, not only by UI reachability. Today820        // the sole caller is the popup (no sender.tab, so this is a structural821        // no-op), but a future tab-context caller or an id leak would otherwise822        // inherit a full-credential oracle. Unlike the fill path we SKIP (not823        // refuse) when no sender domain resolves, to keep the popup caller working.824        if (sender.tab !== undefined || sender.url !== undefined) {825          let senderDomain: string | null = null;826          try {827            const rawUrl = sender.tab?.url ?? sender.url ?? "";828            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;829          } catch {830            senderDomain = null;831          }832          if (senderDomain) {833            const entryDomains = new Set<string>();834            const primary = extractDomain(entry.url ?? "");835            if (primary) entryDomains.add(primary);836            for (const extra of entry.additionalUrls ?? []) {837              const d = extractDomain(extra);838              if (d) entryDomains.add(d);839            }840            if (explicitSummon !== true && !entryDomains.has(senderDomain)) {841              return { ok: false, error: "entry_not_found" }; // no id oracle842            }843          }844        }845846        const { passkey: _passkey, ...safeEntry } = entry;847        return { ok: true, data: safeEntry };848      }849      case "COPY": {850        // AUD-002: shape-validate the payload before passing to the clipboard851        // helper. A raw cast lets a malformed message reach the clipboard API852        // with a non-string and throw.853        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {854          text?: unknown;855          label?: unknown;856          alreadyWritten?: unknown;857        };858        if (typeof text !== "string" || typeof label !== "string") {859          return { ok: false, error: "invalid_payload" };860        }861        await copyToClipboard(text, label, Boolean(alreadyWritten));862        return { ok: true, clearSeconds: getEffectiveClearSeconds() };863      }864      case "CHECK_ALL_BREACHES": {865        const allEntries = vault.getEntries();866        const results: Record<string, number> = {};867        for (const entry of allEntries) {868          if (entry.type === "note") continue;869          if (!entry.password) continue;870          results[entry.id] = await vault.checkBreach(entry.password);871          // Small delay — be a good citizen to the HIBP API872          await new Promise((r) => setTimeout(r, 200));873        }874        // Persist any non-zero counts back to entries875        for (const [id, count] of Object.entries(results)) {876          const entry = vault.getEntryById(id);877          if (entry && (entry.breach ?? 0) !== count) {878            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });879          }880        }881        return { ok: true, data: results };882      }883      case "GET_SETTINGS":884        return { ok: true, data: await vault.ensureSettingsLoaded() };885      case "UPDATE_SETTINGS": {886        const patch = msg.payload;887        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {888          return { ok: false, error: "invalid_payload" };889        }890        await vault.updateSettings(patch as vault.VaultSettings);891        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {892          await setupAutoLock();893          if (vault.isUnlocked()) touchAutoLock();894        }895        return { ok: true };896      }897      case "SETUP_PIN": {898        const { currentPassword, pin } = (msg.payload ?? {}) as {899          currentPassword?: unknown;900          pin?: unknown;901        };902        if (typeof currentPassword !== "string" || typeof pin !== "string") {903          return { ok: false, error: "invalid_payload" };904        }905        return (await vault.setupPinUnlock(currentPassword, pin))906          ? { ok: true }907          : { ok: false, error: "incorrect_current_password" };908      }909      case "DISABLE_PIN": {910        const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown };911        if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" };912        return (await vault.disablePinUnlock(currentPassword))913          ? { ok: true }914          : { ok: false, error: "incorrect_current_password" };915      }916      case "GET_PENDING_PASSKEY":917        return { ok: true, data: await getPendingPasskeyRequest() };918      case "APPROVE_PASSKEY": {919        const { requestId } = msg.payload as { requestId: number };920        await resolvePendingPasskeyRequest(requestId, true);921        return { ok: true };922      }923      case "DENY_PASSKEY": {924        const { requestId } = msg.payload as { requestId: number };925        await resolvePendingPasskeyRequest(requestId, false);926        return { ok: true };927      }928      case "GET_PASSKEY_PROVIDER_STATE":929        return { ok: true, data: await getPasskeyProviderState() };930      case "SET_PASSKEY_PROVIDER_ENABLED": {931        const { enabled } = msg.payload as { enabled: boolean };932        // Disabling is always free; gating fires only when a free user is933        // trying to turn passkey interception on.934        if (enabled) {935          const gate = await requirePro("passkeys");936          if (!gate.allowed) return { ok: false, error: "pro_required" };937        }938        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };939      }940      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS941      // endpoint. Intentional product behavior — users configure their own942      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private943      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-944      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to945      // users that the entry title leaves the device when the canary fires.946      case "FIRE_CANARY_PING": {947        // Canary alert fires unconditionally for any entry with canary: true.948        // The Pro gate only governs creation/flagging of canary entries; once949        // an entry is flagged, the alert path is a security property and must950        // never be license-gated.951        const { webhookUrl, entryTitle, trigger } = msg.payload as {952          webhookUrl: string;953          entryTitle: string;954          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";955        };956        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {957          return { ok: false, error: "invalid_webhook_url" };958        }959        // LV-3: debounce non-test pings per (webhook, entry) so a page that960        // strobes focus/fill events can't turn the canary into a request961        // firehose at the user's endpoint. Test pings are exempt — they are962        // explicit user clicks in the settings UI and are awaited for963        // feedback. The FIRST ping in a window always goes out, so the964        // dead-man's-switch property (canary fires on access) is preserved;965        // only repeats within the window are coalesced.966        if (trigger !== "test") {967          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;968          const stored = await chrome.storage.local.get(rlKey);969          const last = (stored as Record<string, unknown>)[rlKey];970          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {971            return { ok: true, data: { rateLimited: true } };972          }973          await chrome.storage.local.set({ [rlKey]: Date.now() });974        }975        const body = JSON.stringify({976          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",977          entry: entryTitle,978          trigger,979          timestamp: new Date().toISOString(),980          source: "peach-extension",981        });982        if (trigger === "test") {983          // Permitted outbound fetch: user-configured canary alert endpoint984          // (validated by isAllowedCanaryWebhookUrl above). This is the985          // only non-HIBP outbound call in the extension — see986          // Projects.md §3.7. Test pings are awaited so the UI can show987          // success/failure.988          try {989            const res = await fetch(webhookUrl, {990              method: "POST",991              headers: { "Content-Type": "application/json" },992              body,993            });994            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };995          } catch (err) {996            return { ok: false, error: err instanceof Error ? err.message : "network_error" };997          }998        }999        // Non-test triggers are fire-and-forget1000        fetch(webhookUrl, {1001          method: "POST",1002          headers: { "Content-Type": "application/json" },1003          body,1004        }).catch(() => {});1005        return { ok: true };1006      }1007      case "ACTIVATE_LICENSE": {1008        const { key } = msg.payload as { key: string };1009        const licenseInfo = await activateLicense(key);1010        return { ok: true, data: licenseInfo };1011      }1012      case "GET_LICENSE": {1013        const licenseInfo = await getLicenseInfo();1014        return { ok: true, data: licenseInfo };1015      }1016      case "GET_LICENSE_KEY": {1017        const key = await getLicenseKey();1018        return { ok: true, data: key };1019      }1020      case "DEACTIVATE_LICENSE": {1021        await deactivateLicense();1022        return { ok: true };1023      }1024      case "SHOULD_PLAY_CELEBRATION": {1025        const should = await shouldPlayCelebration();1026        return { ok: true, data: should };1027      }1028      case "MARK_CELEBRATION_PLAYED": {1029        await markCelebrationPlayed();1030        return { ok: true };1031      }1032      case "GET_CODEX_VAULT_DATA": {1033        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1034        // popup navigates to the License section without further coordination.1035        const gate = await requirePro("codex");1036        if (!gate.allowed) return { ok: false, error: "pro_required" };1037        return await handleGetCodexVaultData();1038      }1039      case "ESTIMATE_CODEX_PAGES": {1040        const gate = await requirePro("codex");1041        if (!gate.allowed) return { ok: false, error: "pro_required" };1042        return await handleEstimateCodexPages();1043      }1044      case "RESTORE_FROM_CODEX": {1045        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1046        // be able to restore a vault that was printed by a Pro user.1047        // DO NOT add a Pro gate here.1048        const payload = msg.payload as CodexRestorePayload;1049        return await handleRestoreFromCodex(payload);1050      }1051      case "OPEN_PRO_GATE": {1052        // Content script requests: open popup and navigate to License section.1053        const { feature } = (msg.payload ?? {}) as { feature?: string };1054        if (chrome.storage.session) {1055          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1056        }1057        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1058        return { ok: true };1059      }1060      case "OPEN_POPUP": {1061        // Content script asks to open the trusted extension popup — used by the1062        // inline locked bubble so the master password is entered in the popup,1063        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1064        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1065        // toolbar icon. The badge already signals Peach needs attention.1066        //1067        // Set a session flag so the popup knows it was opened for inline unlock1068        // and should close itself once the vault is unlocked (returning the user1069        // to the inline autofill selector on the page).1070        if (chrome.storage.session) {1071          await chrome.storage.session.set({ peach_inline_unlock: true });1072        }1073        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1074        return { ok: true };1075      }1076      case "OPEN_DETACHED_POPUP": {1077        // A window created by the action popup and then orphaned with1078        // window.close() is cascaded shut by Chrome, so the file-picker1079        // flows (OS dialogs that dismiss the popup on focus loss) ask the SW1080        // to open the standalone window instead — the SW has no window to be1081        // associated with. The query string is allowlisted so this can never1082        // open an arbitrary URL.1083        const { route } = (msg.payload ?? {}) as { route?: string };1084        const search = route === "peachscript"1085          ? "?restore=peachscript"1086          : route === "csv"1087            ? "?restore=csv"1088            : route === "codex-pdf"1089              ? "?codex=pdf"1090              : null;1091        if (!search) return { ok: false, error: "bad_route" };1092        try {1093          const popupHtml =1094            chrome.runtime.getManifest().action?.default_popup ?? "src/popup/index.html";1095          await chrome.windows.create({1096            url: chrome.runtime.getURL(`${popupHtml}${search}`),1097            type: "popup",1098            width: 320,1099            height: 550,1100          });1101          return { ok: true, data: { detached: true } };1102        } catch {1103          return { ok: false };1104        }1105      }1106      case "GET_IDENTITIES": {1107        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1108        return { ok: true, data: vault.getIdentities() };1109      }1110      case "TOUCH_AUTO_LOCK": {1111        // touchAutoLock() is already called by shouldRefreshAutoLock above;1112        // this case just gives the popup a typed message to keep the session alive.1113        return { ok: true };1114      }1115      case "GET_ADVANCED_HEALTH_REPORT": {1116        const gate = await requirePro("advanced_health");1117        if (!gate.allowed) return { ok: false, error: "pro_required" };1118        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1119        const report = await buildAdvancedHealthReport(vault.getEntries());1120        return { ok: true, data: report };1121      }1122      case "IS_DURESS_ENABLED": {1123        const enabled = await vault.isDuressEnabled();1124        return { ok: true, data: enabled };1125      }1126      case "SETUP_DURESS": {1127        // Single enforcement point for the Duress Vault Pro gate. Free users1128        // who somehow reach this handler are rejected here; the popup also1129        // pre-checks isPro() to avoid showing the setup form to free users,1130        // but server-side is the actual security boundary.1131        const gate = await requirePro("duress_vault");1132        if (!gate.allowed) return { ok: false, error: "pro_required" };1133        // MV3 service workers restart after inactivity, losing the in-memory1134        // derived key. Detect this before calling setupDuress so the popup1135        // can show a meaningful prompt to re-lock and re-unlock.1136        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1137        const { duressPassword } = msg.payload as { duressPassword: string };1138        await vault.setupDuress(duressPassword);1139        return { ok: true };1140      }1141      case "DISABLE_DURESS": {1142        await vault.disableDuress();1143        return { ok: true };1144      }1145      case "VERIFY_MAIN_PASSWORD": {1146        const { password } = msg.payload as { password: string };1147        const ok = await vault.verifyMainPassword(password);1148        return { ok: true, data: ok };1149      }1150      case "CHANGE_PASSWORD": {1151        const { currentPassword, newPassword } = msg.payload as {1152          currentPassword: string;1153          newPassword: string;1154        };1155        const changed = await vault.changePassword(currentPassword, newPassword);1156        return changed1157          ? { ok: true }1158          : { ok: false, error: "incorrect_current_password" };1159      }1160      case "GET_SITE_PASSWORD_POLICY": {1161        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1162        if (!tab?.id) return { ok: true, data: null };1163        try {1164          const response = await chrome.tabs.sendMessage(tab.id, {1165            type: "GET_SITE_PASSWORD_POLICY",1166          });1167          return (response as MessageResponse) ?? { ok: true, data: null };1168        } catch {1169          return { ok: true, data: null };1170        }1171      }1172      case "RECORD_MANUAL_SUMMON": {1173        const { domain } = msg.payload as { domain: string };1174        const settings = vault.getSettings();1175        const existing = settings.manualSummonDomains?.[domain];1176        const now = Date.now();1177        await vault.updateSettings({1178          manualSummonDomains: {1179            ...settings.manualSummonDomains,1180            [domain]: {1181              firstSummonedAt: existing?.firstSummonedAt ?? now,1182              summonCount: (existing?.summonCount ?? 0) + 1,1183              lastSummonedAt: now,1184            },1185          },1186        });1187        return { ok: true };1188      }1189      case "DECLINE_CARD_SAVE": {1190        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1191        await vault.declineCardSaveOffer(last4, expMonth, expYear);1192        return { ok: true };1193      }1194      case "IS_CARD_DECLINED": {1195        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1196        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1197        return { ok: true, data: declined };1198      }1199      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1200        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1201          rpId?: string;1202          rpName?: string;1203          userName?: string;1204          userDisplayName?: string;1205        };1206        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1207        return await initiateFirefoxPasskeyCreate({1208          rpId,1209          rpName: rpName ?? rpId,1210          userName,1211          userDisplayName,1212        }, attestedSenderOrigin(sender));1213      }12141215      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1216        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1217        if (!payload) return { ok: false, error: "missing_payload" };1218        return await completeFirefoxPasskeyCreate(payload);1219      }12201221      case "PASSKEY_OFFER_DECLINE": {1222        const { domain } = (msg.payload ?? {}) as { domain?: string };1223        if (!domain) return { ok: false, error: "domain_required" };1224        await recordPasskeyOfferDecline(domain);1225        return { ok: true };1226      }12271228      case "GET_PASSKEY_OFFER_DECLINED": {1229        const { domain } = (msg.payload ?? {}) as { domain?: string };1230        if (!domain) return { ok: false, error: "domain_required" };1231        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1232      }12331234      case "PASSKEY_HAS_CREDENTIALS": {1235        const payload = msg.payload as {1236          rpId?: string;1237          allowCredentials?: Array<{ id: string; type?: string }>;1238        } | undefined;1239        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1240        return await handlePasskeyHasCredentials({1241          rpId: payload.rpId,1242          allowCredentials: payload.allowCredentials ?? [],1243        }, attestedSenderOrigin(sender));1244      }12451246      case "PASSKEY_CREATE": {1247        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1248        if (!payload?.rpId || !payload?.userName) {1249          return { ok: false, error: "rpid_and_username_required" };1250        }1251        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1252      }12531254      case "PASSKEY_GET": {1255        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1256        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1257        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1258      }12591260      case "PASSKEY_AUTH_RESPONSE": {1261        const { requestId, approved } = (msg.payload ?? {}) as {1262          requestId?: string | number;1263          approved?: boolean;1264        };1265        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1266          return { ok: false, error: 'requestId and approved required' };1267        }1268        await resolvePendingPasskeyRequest(Number(requestId), approved);1269        return { ok: true };1270      }12711272      case "GET_PASSKEY_FOR_DOMAIN": {1273        const { domain } = (msg.payload ?? {}) as { domain?: string };1274        if (!domain) return { ok: false, error: "domain_required" };1275        // Scope to the caller's own origin: a page may only ask about passkeys1276        // for a domain it actually owns, so an arbitrary page cannot enumerate1277        // which sites the user holds passkeys for or read the username (audit MEDIUM).1278        const origin = attestedSenderOrigin(sender);1279        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1280        if (!vault.isUnlocked()) return { ok: true, data: null };1281        const match = vault1282          .getEntries()1283          .find((entry) => entry.passkey?.rpId === domain);1284        if (!match || !match.passkey) return { ok: true, data: null };1285        // Slim shape — only the fields State 11 needs. Never expose private1286        // key material, even though this is locked behind isUnlocked.1287        return {1288          ok: true,1289          data: {1290            rpId: match.passkey.rpId,1291            userName: match.passkey.userName,1292            browser: match.passkey.browser,1293          },1294        };1295      }12961297      case "DESTROY_VAULT": {1298        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1299        // storage.local.clear() wipes every Peach key (slots, settings, license,1300        // onboarded flag, history, sync state, declined cards, recall, etc.);1301        // session.clear() wipes pending passkey requests + pro-notice queues.1302        // Caller (Panic.tsx) handles UI navigation back to onboarding.1303        //1304        // The Pro license is the one thing that must survive: the user paid for1305        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1306        // Capture it before the clear and restore it after. peach_pro_celebrated1307        // rides along so the Pro celebration doesn't replay on the next unlock.1308        const preserved = await chrome.storage.local.get([1309          "peach_license",1310          "peach_pro_celebrated",1311        ]);1312        vault.lock();1313        await storageClear();1314        await vault.clearVaultHistory();1315        const toRestore: Record<string, unknown> = {};1316        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1317        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1318        if (Object.keys(toRestore).length > 0) {1319          await chrome.storage.local.set(toRestore);1320        }1321        if (chrome.storage.session) {1322          await chrome.storage.session.clear();1323        }1324        return { ok: true };1325      }13261327      case "GET_IDENTITY_SUGGESTIONS": {1328        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1329        const entries = vault.getEntries();1330        const suggestions = buildIdentitySuggestions(entries);1331        return { ok: true, data: { suggestions } };1332      }1333      case "ML_INIT":1334        return { ok: true };13351336      case "ML_PREDICT_BATCH": {1337        // AUD-002: shape-validate before forwarding to the ML helper.1338        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1339        if (!Array.isArray(featuresArray)) {1340          return { ok: false, error: "invalid_payload" };1341        }1342        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1343      }13441345      // ── Vault sync (v3) ───────────────────────────────────────────────1346      // Returns the public-facing local identity needed by the popup to1347      // drive Phase-1 audio pairing. The private long-term key never1348      // leaves the background.1349      case "GET_LOCAL_IDENTITY": {1350        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1351        // Pro license from an already-Pro peer (at least one device must be Pro).1352        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1353        // Identity derives from the stable root key, not the password-derived1354        // key, so pairing survives a master-password change (SEV-2-B).1355        const masterKeyHex = vault.getRootKeyHex();1356        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1357        const masterKey = unhexBytes(masterKeyHex);1358        try {1359          const identity = await buildLocalIdentity(masterKey);1360          // If this device is Pro, advertise the signed license so the peer can1361          // activate it after SAS confirmation — pairing carries Pro across.1362          if (await isProUser()) {1363            const license = await getLicenseKey();1364            if (license) (identity as { license?: string }).license = license;1365          }1366          return { ok: true, data: identity };1367        } finally {1368          masterKey.fill(0);1369        }1370      }13711372      case "LIST_PAIRED_DEVICES": {1373        const devices = await listPairedDevicesV3();1374        return { ok: true, data: { devices } };1375      }13761377      case "RENAME_PAIRED_DEVICE": {1378        const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string };1379        if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") {1380          return { ok: false, error: "invalid_payload" };1381        }1382        await renamePairedDeviceV3(deviceId, name);1383        return { ok: true };1384      }13851386      case "UNPAIR_DEVICE": {1387        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1388        if (typeof deviceId !== "string" || !deviceId) {1389          return { ok: false, error: "invalid_payload" };1390        }1391        // Removing a device REVOKES it rather than just dropping the local1392        // row: a plain removal is undone the moment any other peer vouches it1393        // back through a manifest, which is exactly what the relay makes easy.1394        await revokeDeviceByIdV3(deviceId, await getOrCreateDeviceId());1395        // Sync against the remaining hosts — the unpaired device no longer1396        // matters but the next alarm tick is up to ten minutes away.1397        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1398        return { ok: true };1399      }14001401      case "RENAME_LOCAL_DEVICE": {1402        const { name } = (msg.payload ?? {}) as { name?: string };1403        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1404        await setDeviceNameV3(name);1405        return { ok: true };1406      }14071408      // ── Relay pairing ─────────────────────────────────────────────────────1409      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1410      // session runs in the background; the SAS and the terminal result reach1411      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1412      case "START_ADOPTION_SOURCE": {1413        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1414        if (isRelayAdoptionSourceInFlight()) {1415          return { ok: false, error: "adoption_source_in_progress" };1416        }1417        try {1418          return { ok: true, data: await startRelayAdoptionSource() };1419        } catch (error) {1420          return {1421            ok: false,1422            error: error instanceof Error ? error.message : "adoption_source_failed",1423          };1424        }1425      }14261427      // Onboarding receiver — empty extension shows a QR, phone scans and1428      // sends the vault. The popup supplies the local-only password here so1429      // the background can wrap the adopted root key at rest without ever1430      // asking the user to retype it.1431      case "START_ADOPTION_RECEIVER": {1432        if (isRelayAdoptionSourceInFlight()) {1433          return { ok: false, error: "adoption_receiver_in_progress" };1434        }1435        const password = (msg.payload as { password?: unknown } | undefined)?.password;1436        if (typeof password !== "string" || password.length === 0) {1437          return { ok: false, error: "invalid_payload" };1438        }1439        try {1440          return { ok: true, data: await startRelayAdoptionReceiver(password) };1441        } catch (error) {1442          return {1443            ok: false,1444            error: error instanceof Error ? error.message : "adoption_receiver_failed",1445          };1446        }1447      }14481449      // Popup→bg counterpart to ADOPTION_SOURCE_SAS (receiver flow).1450      // The receiver now auto-accepts the SAS (both sides derive it from the1451      // same Noise handshake hash, so the codes match by construction) so1452      // the popup never has a SAS screen to tap on. The id round-trips the1453      // same way so a stale late response can't approve the wrong session.1454      // Popup→bg counterpart for the source flow: Confirm/Cancel on the1455      // source's SAS screen.14561457      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1458      // on the source's SAS screen. The id round-trips the same way so a stale1459      // late response can't approve the wrong session.1460      case "SOURCE_SAS_DECISION": {1461        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1462        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1463          return { ok: false, error: "invalid_payload" };1464        }1465        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1466      }14671468      case "CANCEL_ADOPTION_SOURCE": {1469        cancelRelayAdoptionSource();1470        return { ok: true };1471      }14721473      case "TRIGGER_SYNC": {1474        const payload = (msg.payload ?? {}) as {1475          reason?: "vault_change" | "foreground" | "manual";1476          force?: boolean;1477        };1478        const reason = payload.reason ?? "foreground";14791480        void triggerSyncIfReachable({ reason, force: payload.force === true });1481        return { ok: true };1482      }14831484      case "GET_SYNC_STATE": {1485        return { ok: true, data: getSyncState() };1486      }14871488      case "GET_SYNC_SETTINGS": {1489        return { ok: true, data: await getSyncSettings() };1490      }14911492      case "SET_SYNC_SETTINGS": {1493        const payload = (msg.payload ?? {}) as {1494          mode?: unknown;1495          relayUrl?: unknown;1496        };1497        try {1498          // A custom relay URL implies private mode; Peach's own relay stays1499          // public. See setRelayUrl.1500          if (payload.relayUrl !== undefined) {1501            if (typeof payload.relayUrl !== "string") {1502              return { ok: false, error: "invalid_relay_url" };1503            }1504            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1505          }1506          if (payload.mode !== undefined) {1507            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1508              return { ok: false, error: "invalid_sync_mode" };1509            }1510            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1511          }1512          return { ok: true, data: await getSyncSettings() };1513        } catch (error) {1514          return {1515            ok: false,1516            error: error instanceof Error ? error.message : "invalid_relay_url",1517          };1518        }1519      }15201521      case "GET_SYNC_ALERTS": {1522        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1523        const alerts = await getPendingSyncAlerts();1524        // The popup reads on open and acknowledges with consume:true after1525        // rendering, so a popup crash between read and render doesn't lose1526        // the alerts.1527        if (consume) await clearPendingSyncAlerts();1528        return { ok: true, data: alerts };1529      }15301531      case "GET_PENDING_VOUCHED_DEVICES": {1532        return { ok: true, data: await listPendingVouchedDevices() };1533      }1534      case "CONFIRM_VOUCHED_DEVICE": {1535        const { deviceId } = msg.payload as { deviceId: string };1536        const pending = await getPendingVouchedDevice(deviceId);1537        if (!pending) return { ok: false, error: "not_pending" };1538        // Last gate before a vouched device becomes a sync peer. A queue entry1539        // can predate the revocation that names it, so revocation is re-checked1540        // here rather than trusted to have swept the queue.1541        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {1542          await removePendingVouchedDevice(deviceId);1543          return { ok: false, error: "device_revoked" };1544        }1545        await upsertPairedDeviceV3({1546          deviceId: pending.deviceId,1547          deviceName: pending.deviceName,1548          deviceType:1549            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1550          longTermPublicKeyHex: pending.longTermPublicKeyHex,1551          signingPublicKeyHex: pending.signingPublicKeyHex,1552          wsPort: pending.wsPort,1553          pairedAt: pending.pairedAt,1554          trustSource: "vouched",1555        });1556        await removePendingVouchedDevice(deviceId);1557        // Newly confirmed vouched device is now a sync target — kick a round1558        // so the mesh introduction pays off without a 10-minute wait.1559        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1560        return { ok: true };1561      }1562      case "REJECT_VOUCHED_DEVICE": {1563        const { deviceId } = msg.payload as { deviceId: string };1564        await removePendingVouchedDevice(deviceId);1565        return { ok: true };1566      }1567      case "ROTATE_SYNC_IDENTITY": {1568        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1569        const result = await vault.rotateSyncIdentity();1570        return result.ok ? { ok: true } : { ok: false, error: result.error };1571      }15721573      default:1574        return { ok: false, error: "unknown_message_type" };1575    }1576  } catch (err) {1577    return {1578      ok: false,1579      error: err instanceof Error ? err.message : "operation_failed",1580    };1581  }1582}15831584// Returns username use-counts from the vault, sorted by frequency. Each row1585// also carries the entry's email so the popup can suggest the email/username1586// pair the user has actually used together.1587function buildIdentitySuggestions(1588  entries: VaultEntry[],1589): Array<{ email: string; username: string; count: number }> {1590  const usernameCounts = new Map<string, number>();1591  const usernameEmail = new Map<string, string>();1592  for (const entry of entries) {1593    const username = entry.username ?? "";1594    const email = (entry as VaultEntry & { email?: string }).email ?? "";1595    if (!username && !email) continue;1596    const key = username || email;1597    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1598    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1599  }1600  return Array.from(usernameCounts.entries())1601    .sort((a, b) => b[1] - a[1])1602    .map(([username, count]) => ({1603      email: usernameEmail.get(username) ?? "",1604      username,1605      count,1606    }));1607}16081609/** Notify all content scripts that the vault just became available. */1610function broadcastToContentScripts(message: { type: string }): void {1611  if (!chrome.tabs?.query) return;1612  chrome.tabs.query({}, (tabs) => {1613    for (const tab of tabs) {1614      if (tab.id !== undefined) {1615        chrome.tabs.sendMessage(tab.id, message).catch(() => {1616          // Tab may not have a content script — silently ignore1617        });1618      }1619    }1620  });1621}16221623function shouldRefreshAutoLock(type: MessageType): boolean {1624  return (1625    type !== "HAS_VAULT" &&1626    type !== "IS_UNLOCKED" &&1627    type !== "GET_VAULT_STATUS" &&1628    type !== "LOCK" &&1629    type !== "UPDATE_SETTINGS" &&1630    type !== "GET_PENDING_PASSKEY" &&1631    type !== "GET_PASSKEY_PROVIDER_STATE" &&1632    type !== "DECLINE_CARD_SAVE" &&1633    type !== "IS_CARD_DECLINED"1634  );1635}16361637function isAllowedCanaryWebhookUrl(value: string): boolean {1638  try {1639    const url = new URL(value);1640    if (url.protocol !== "https:") return false;16411642    const hostname = url.hostname.toLowerCase();1643    if (1644      hostname === "localhost" ||1645      hostname.endsWith(".localhost") ||1646      isPrivateIpv4(hostname) ||1647      isPrivateIpv6(hostname)1648    ) {1649      return false;1650    }16511652    return true;1653  } catch {1654    return false;1655  }1656}16571658function isPrivateIpv4(hostname: string): boolean {1659  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1660    return true;1661  }16621663  const octets = hostname.split(".").map((part) => Number(part));1664  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1665    return false;1666  }16671668  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1669}16701671function isPrivateIpv6(hostname: string): boolean {1672  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1673  // IPv4-mapped IPv6 literals embed a plain IPv4 address that the prefix1674  // list below can never match (WHATWG URL serializes [::ffff:192.168.0.1]1675  // as ::ffff:c0a8:1). Unwrap and test the embedded IPv4; unparseable mapped1676  // tails fail closed. (Codex Security 2026-08-04 LOW,1677  // ssrf.webhook-url-private-ip-filter.) DNS rebinding is out of scope for a1678  // one-shot host check.1679  const mapped = /^::ffff:(.+)$/.exec(normalized);1680  if (mapped) {1681    const tail = mapped[1] ?? "";1682    if (tail.includes(".")) return isPrivateIpv4(tail);1683    const parts = tail.split(":");1684    const [hi, lo] = parts;1685    if (1686      parts.length !== 2 ||1687      !hi ||1688      !lo ||1689      !/^[0-9a-f]{1,4}$/.test(hi) ||1690      !/^[0-9a-f]{1,4}$/.test(lo)1691    ) {1692      return true;1693    }1694    const octets = [1695      (Number.parseInt(hi, 16) >>> 8) & 0xff,1696      Number.parseInt(hi, 16) & 0xff,1697      (Number.parseInt(lo, 16) >>> 8) & 0xff,1698      Number.parseInt(lo, 16) & 0xff,1699    ];1700    return isPrivateIpv4(octets.join("."));1701  }1702  return (1703    normalized === "::1" ||1704    normalized.startsWith("fc") ||1705    normalized.startsWith("fd") ||1706    normalized.startsWith("fe80:")1707  );1708}