messages.ts

71.1 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        const { password, rootKeyHex } = (msg.payload ?? {}) as {299          password?: unknown;300          rootKeyHex?: unknown;301        };302        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {303          return { ok: false, error: "invalid_payload" };304        }305306        try {307          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);308          await setupAutoLock();309          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });310          onVaultUnlocked();311          return { ok: true, vaultId };312        } catch (err) {313          return { ok: false, error: err instanceof Error ? err.message : String(err) };314        }315      }316      case "UNLOCK": {317        const { password } = msg.payload as { password: string };318        const ok = await vault.unlock(password);319        if (ok) {320          // KAT: verify the WebCrypto stack is healthy before the user relies on it.321          // Runs after unlock so latency is hidden behind the vault-load time.322          const kat = await runSelfTest();323          if (!kat.ok) {324            console.error("[Peach] Crypto self-test FAILED:", kat.error);325            await vault.lock();326            return { ok: false, error: "self_test_failed" };327          }328          await vault.updateSettings({ pinPreferred: false });329          await setupAutoLock();330          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });331          onVaultUnlocked();332          return { ok: true };333        }334        // Distinguish corruption from wrong password so the popup can offer335        // a history-restore path instead of falsely accusing the user of336        // mistyping (M7/COR-007).337        const failure = vault.consumeLastUnlockFailureReason();338        if (failure) {339          return {340            ok: false,341            error: "vault_corrupted",342            canRestoreFromHistory: true,343          } as MessageResponse;344        }345        return { ok: false };346      }347      case "UNLOCK_WITH_PIN": {348        const { pin } = (msg.payload ?? {}) as { pin?: unknown };349        if (typeof pin !== "string") return { ok: false, error: "invalid_payload" };350        const ok = await vault.unlockWithPin(pin);351        if (!ok) return { ok: false };352        const kat = await runSelfTest();353        if (!kat.ok) {354          await vault.lock();355          return { ok: false, error: "self_test_failed" };356        }357        await vault.updateSettings({ pinPreferred: true });358        await setupAutoLock();359        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });360        onVaultUnlocked();361        return { ok: true };362      }363      case "VALIDATE_RECOVERY_WORDS": {364        const { words } = msg.payload as { words: string[] };365        const invalid = findInvalidWords(words);366        return { ok: true, data: { valid: invalid.length === 0, invalid } };367      }368      case "GET_RECOVERY_WORDS": {369        // Must be unlocked and have recovery set up (vault must be v2.12+).370        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };371        // LV-4: the recovery words re-derive the ROOT KEY — the highest-372        // value secret in the vault. A session unlock (which may be hours373        // old on a shared machine) is not enough; require a fresh password374        // proof, matching the 1Password/Bitwarden pattern for revealing375        // escrow material. EXEMPTION: the create-vault / rotation confirmation376        // window (peach_recovery_pending) shows the words immediately after377        // the user authenticated, and that confirmation UI has no password to378        // resend — skip the re-auth there only.379        if (!(await isRecoveryConfirmPending())) {380          const { password } = (msg.payload ?? {}) as { password?: string };381          if (typeof password !== "string" || !password) {382            return { ok: false, error: "password_required" };383          }384          if (!(await vault.verifyMainPassword(password))) {385            return { ok: false, error: "wrong_password" };386          }387        }388        try {389          const words = await vault.getRecoveryWords();390          return { ok: true, data: words };391        } catch {392          return { ok: false, error: "recovery_not_setup" };393        }394      }395      case "RECOVER_WITH_WORDS": {396        // User has lost their password but has their 12 recovery words.397        // We: (1) validate the words, (2) re-encrypt vault with new password.398        const { words, newPassword } = msg.payload as {399          words: string[];400          newPassword: string;401        };402        const stored = await vault.loadSlotA();403        if (!stored) return { ok: false, error: "no_vault" };404        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {405          return { ok: false, error: "recovery_not_setup" };406        }407        // Unwrap the root key from the recovery escrow.408        try {409          await vault.unwrapRootKeyForRecovery(410            stored.recovery_wrapped_root_key,411            stored.recovery_nonce ?? "",412            stored.recovery_tag ?? "",413            stored.recovery_salt,414            words415          );416        } catch {417          return { ok: false, error: "invalid_recovery_words" };418        }419        // Re-key: derive fresh salt + key from new password.420        const newSalt = vault.generateSalt();421        const newKey = await vault.deriveKey(newPassword, newSalt);422        // Re-wrap root key under the new password's derived key so the same423        // recovery words continue to work after the password change.424        await vault.rewrapRootKeyForPassword(newKey, newSalt);425        // Re-encrypt vault entries with the new key.426        await vault.changePasswordWithNewKey(newSalt, newKey);427        await setupAutoLock();428        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });429        return { ok: true };430      }431      case "LOCK":432        vault.lock();433        return { ok: true };434      case "IS_UNLOCKED":435        return { ok: true, data: vault.isUnlocked() };436      case "GET_VAULT_STATUS":437        return { ok: true, unlocked: vault.isUnlocked() };438      case "HAS_VAULT":439        return { ok: true, data: await vault.hasVault() };440      case "GET_ENTRIES":441        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };442        return { ok: true, data: vault.getEntries() };443      case "ADD_ENTRY": {444        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };445        const payload = msg.payload;446        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {447          return { ok: false, error: "invalid_payload" };448        }449        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);450        return { ok: true, data: entry };451      }452      case "BATCH_ADD_ENTRIES": {453        const payload = msg.payload as { entries?: unknown } | null | undefined;454        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {455          return { ok: false, error: "invalid_payload" };456        }457        if (!Array.isArray(payload.entries)) {458          return { ok: false, error: "invalid_payload" };459        }460        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);461        return { ok: true, data: added };462      }463      case "RESTORE_ENTRIES": {464        const payload = msg.payload as465          | { entries?: unknown; mode?: unknown; settings?: unknown }466          | null467          | undefined;468        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {469          return { ok: false, error: "invalid_payload" };470        }471        if (!Array.isArray(payload.entries)) {472          return { ok: false, error: "invalid_payload" };473        }474        if (payload.mode !== "replace" && payload.mode !== "merge") {475          return { ok: false, error: "invalid_payload" };476        }477        const summary = await vault.restoreEntries(478          payload.entries as Parameters<typeof vault.restoreEntries>[0],479          payload.mode480        );481        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {482          await vault.updateSettings(payload.settings as vault.VaultSettings);483        }484        return { ok: true, data: summary };485      }486      case "CLEAR_VAULT_ENTRIES": {487        await vault.clearVaultEntries("REPLACE_ALL");488        return { ok: true };489      }490      case "GET_VAULT_HISTORY": {491        const snapshots = await vault.getVaultHistory();492        return { ok: true, data: snapshots };493      }494      case "RESTORE_VAULT_SNAPSHOT": {495        const { snapshotId } = msg.payload as { snapshotId: string };496        const result = await vault.restoreVaultSnapshot(snapshotId);497        if (!result.ok) return { ok: false, error: result.error };498        broadcastToContentScripts({ type: "VAULT_LOCKED" });499        return { ok: true };500      }501      case "COUNT_DUPLICATES": {502        return { ok: true, data: vault.countDuplicates() };503      }504      case "DEDUPLICATE_ENTRIES": {505        const removed = await vault.deduplicateEntries();506        return { ok: true, data: removed };507      }508      case "UPDATE_ENTRY": {509        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;510        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {511          return { ok: false, error: "invalid_payload" };512        }513        const { id, patch } = payload;514        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {515          return { ok: false, error: "invalid_payload" };516        }517        // Single enforcement point for the Canary Entries Pro gate. Only518        // gates the transition into a canary entry — clearing/disabling a519        // canary (`canary: undefined`) is always allowed, so existing520        // canary entries remain manageable.521        const incomingCanary = (patch as { canary?: unknown }).canary;522        if (incomingCanary && typeof incomingCanary === "object") {523          const existing = vault.getEntryById(id);524          if (!existing?.canary) {525            const gate = await requirePro("canary_entry");526            if (!gate.allowed) return { ok: false, error: "pro_required" };527          }528        }529        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);530        return { ok: true };531      }532      case "ADD_ADDITIONAL_URL": {533        const { id, url } = msg.payload as { id: string; url: string };534        const trimmed = typeof url === "string" ? url.trim() : "";535        if (!trimmed) return { ok: false, error: "url_required" };536        const existing = vault.getEntryById(id);537        if (!existing) return { ok: false, error: "entry_not_found" };538        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };539        const merged = [...(existing.additionalUrls ?? []), trimmed];540        await vault.updateEntry(id, { additionalUrls: merged });541        return { ok: true };542      }543      case "DELETE_ENTRY": {544        const { id } = msg.payload as { id: string };545        await vault.deleteEntry(id);546        return { ok: true };547      }548      case "GET_DELETED_ENTRIES":549        return { ok: true, data: vault.getDeletedEntries() };550      case "RESTORE_ENTRY": {551        const { id } = msg.payload as { id: string };552        await vault.restoreEntry(id);553        return { ok: true };554      }555      case "PURGE_ENTRY": {556        const { id } = msg.payload as { id: string };557        await vault.purgeEntry(id);558        return { ok: true };559      }560      case "PURGE_EXPIRED_TRASH": {561        const { retentionMs } = msg.payload as { retentionMs: number };562        const purged = await vault.purgeExpiredTrash(retentionMs);563        return { ok: true, data: purged };564      }565      case "SAVE_NOTE": {566        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };567        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };568        const now = Date.now();569        if (id) {570          const existing = vault.getEntryById(id);571          if (!existing) return { ok: false, error: "not_found" };572          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });573          return { ok: true, data: vault.getEntryById(id) };574        } else {575          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt576          // (EntryDraft omits both), so passing them was the only reason the577          // `as any` cast existed. Dropping them makes the call type-check.578          const entry = await vault.addEntry({579            type: "note",580            title: title || "Untitled",581            notes: body,582          });583          return { ok: true, data: entry };584        }585      }586      case "DELETE_NOTE": {587        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };588        const { id } = msg.payload as { id: string };589        await vault.deleteEntry(id);590        return { ok: true };591      }592      case "GET_NOTES": {593        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };594        const notes = vault.getEntries().filter(595          (e) => e.type === "note" && !e.deletedAt596        );597        return { ok: true, data: notes } as MessageResponse;598      }599      case "SEARCH_VAULT": {600        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };601        // AUD-002: shape-validate the payload before calling string methods.602        // A raw cast lets a malformed message crash the handler with TypeError.603        const { query } = (msg.payload ?? {}) as { query?: unknown };604        if (typeof query !== "string") {605          return { ok: false, error: "invalid_payload" };606        }607        const q = query.toLowerCase();608        const searchResults = vault.getEntries().filter(609          (e) =>610            !e.deletedAt &&611            (e.title.toLowerCase().includes(q) ||612              e.notes?.toLowerCase().includes(q) ||613              e.username?.toLowerCase().includes(q))614        );615        return { ok: true, data: searchResults } as MessageResponse;616      }617      case "AUTOFILL_QUERY": {618        if (!vault.isUnlocked()) {619          return { ok: false, error: "vault_locked" };620        }621        let { includeAll } = msg.payload as { includeAll?: boolean };622        const { domain, kind, userGesture } = msg.payload as {623          domain: string;624          kind?: "login" | "card" | "totp";625          userGesture?: boolean;626        };627        // MV-2: the vault-wide inventory (every title/username/email/url)628        // may only leave the background on an explicit user gesture — the629        // user opening the search affordance — never on passive form focus.630        // userGesture is self-declared by our own content script; the value631        // of this gate is that PASSIVE code paths (which never set it)632        // cannot ship the inventory, shrinking what a compromised page that633        // merely triggers focus events can observe.634        if (includeAll && userGesture !== true) {635          includeAll = false;636        }637        // kind="card": return saved cards as compact summaries for the638        // inline card silver platter. Cards are not domain-scoped — every639        // saved card is a candidate on every checkout page — so domain is640        // ignored when kind === "card".641        if (kind === "card") {642          const cards = vault.getEntries().filter((e) => e.type === "card");643          return {644            ok: true,645            data: cards.map((e) => ({646              id: e.id,647              title: e.cardNickname || e.title,648              cardholderName: e.cardholderName,649              last4: e.last4,650              expMonth: e.expMonth,651              expYear: e.expYear,652              network: e.network,653            })),654          };655        }656        if (kind === "totp") {657          const matches = (658            includeAll659              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")660              : vault.queryDomain(domain)661          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));662          return {663            ok: true,664            data: matches.map((e) => ({665              id: e.id,666              title: e.title,667              username: e.username,668              email: e.email,669              url: e.url,670              hasTotp: true,671            })),672          };673        }674        // The inline selector fills username+password into a form. Passkey-675        // only entries have no password to fill; sign-in for those goes676        // through the WebAuthn path instead. Filter them out everywhere so677        // the user doesn't see four "GitHub" rows that mostly do nothing.678        // Notes and cards never belonged here either.679        const matches = (680          includeAll681            ? vault682                .getEntries()683                .filter((entry) => entry.type !== "note" && entry.type !== "card")684            : vault.queryDomain(domain)685        ).filter((entry) => !isPasskeyOnly(entry));686        return {687          ok: true,688          data: matches.map((e) =>689            includeAll690              ? {691                  id: e.id,692                  title: e.title,693                  // username/email/url shipped so the inline popup's search694                  // affordance can match on them, not just titles. No secrets695                  // cross the boundary — same shape as the domain-matched696                  // response below minus hasTotp (which the search list697                  // doesn't surface).698                  username: e.username,699                  email: e.email,700                  url: e.url,701                  hasPasskey: e.passkey !== undefined,702                }703              : {704                  id: e.id,705                  title: e.title,706                  username: e.username,707                  email: e.email,708                  url: e.url,709                  hasTotp: Boolean(e.totp),710                  hasPasskey: e.passkey !== undefined,711                }712          ),713        };714      }715      case "GET_ENTRY_FOR_FILL": {716        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };717        const { id, explicitSummon } = msg.payload as {718          id: string;719          explicitSummon?: boolean;720        };721        const entry = vault.getEntryById(id);722        if (!entry) return { ok: false, error: "entry_not_found" };723        // Passkey-only entries (passkey credential, no password) cannot be724        // filled into a form — sign-in goes through the WebAuthn path. A725        // login that ALSO has a passkey is still fillable for its password.726        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };727728        // MV-1: re-validate the entry against the requesting tab's origin.729        // sender.tab.url is browser-attested — a page cannot forge it. When730        // the request does not come from a tab at all (popup surfaces use731        // GET_ENTRY_FOR_EDIT, not this), refuse.732        if (sender.tab !== undefined || sender.url !== undefined) {733          let senderDomain: string | null = null;734          try {735            const rawUrl = sender.tab?.url ?? sender.url ?? "";736            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;737          } catch {738            senderDomain = null;739          }740          if (!senderDomain) return { ok: false, error: "origin_unverified" };741742          const entryDomains = new Set<string>();743          const primary = extractDomain(entry.url ?? "");744          if (primary) entryDomains.add(primary);745          for (const extra of entry.additionalUrls ?? []) {746            const d = extractDomain(extra);747            if (d) entryDomains.add(d);748          }749750          // explicitSummon=true means the user actively picked this entry751          // from the cross-domain search affordance — an intentional752          // off-domain fill. Passive fill paths must stay domain-bound.753          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {754            // Domain mismatch — refuse silently (no oracle about which ids exist).755            return { ok: false, error: "entry_not_found" };756          }757        }758        // Strip the passkey credential AND the raw base32 TOTP seed from the759        // response. Content scripts never need either: the private key is the760        // authenticator's, and handing over the TOTP seed would let a761        // compromised content script mint valid codes indefinitely (SEV-3-C).762        // Generate the *current* 6-digit code here in the background and send763        // only that, plus the seconds left so the UI can render a countdown.764        // Also drop passwordHistory: filling needs only the *current* password.765        // Handing every past password to a content script during passive766        // autofill on an arbitrary page would widen the blast radius of a767        // compromised page far beyond the one credential being filled.768        const {769          passkey: _strippedPasskey,770          totp: seed,771          totpAlgorithm,772          totpDigits,773          totpPeriod,774          passwordHistory: _ph,775          ...safeEntry776        } = entry;777        let totpCode: string | undefined;778        let totpRemaining: number | undefined;779        if (seed) {780          try {781            // PCH-01-019: honour stored algorithm/digits/period (defaults apply782            // when these are undefined, i.e. RFC-default bare-seed entries).783            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);784            totpCode = generated.code;785            totpRemaining = generated.remaining;786          } catch {787            totpCode = undefined;788          }789        }790        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };791      }792      // Trusted full-entry fetch for Peach's own inline-popup surfaces that793      // genuinely need the raw TOTP seed: the edit form (which re-saves the794      // seed and would otherwise wipe it) and nothing else. Unlike795      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside796      // the inline popup, never during passive autofill on an arbitrary page.797      // The passkey credential is still stripped — the edit form never touches it.798      case "GET_ENTRY_FOR_EDIT": {799        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };800        const { id, explicitSummon } = msg.payload as {801          id: string;802          explicitSummon?: boolean;803        };804        const entry = vault.getEntryById(id);805        if (!entry) return { ok: false, error: "entry_not_found" };806807        // PCH-01-006: re-validate the browser-attested sender origin, mirroring808        // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and809        // full password history — at least as sensitive as the fill response — so810        // the boundary must be enforced here, not only by UI reachability. Today811        // the sole caller is the popup (no sender.tab, so this is a structural812        // no-op), but a future tab-context caller or an id leak would otherwise813        // inherit a full-credential oracle. Unlike the fill path we SKIP (not814        // refuse) when no sender domain resolves, to keep the popup caller working.815        if (sender.tab !== undefined || sender.url !== undefined) {816          let senderDomain: string | null = null;817          try {818            const rawUrl = sender.tab?.url ?? sender.url ?? "";819            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;820          } catch {821            senderDomain = null;822          }823          if (senderDomain) {824            const entryDomains = new Set<string>();825            const primary = extractDomain(entry.url ?? "");826            if (primary) entryDomains.add(primary);827            for (const extra of entry.additionalUrls ?? []) {828              const d = extractDomain(extra);829              if (d) entryDomains.add(d);830            }831            if (explicitSummon !== true && !entryDomains.has(senderDomain)) {832              return { ok: false, error: "entry_not_found" }; // no id oracle833            }834          }835        }836837        const { passkey: _passkey, ...safeEntry } = entry;838        return { ok: true, data: safeEntry };839      }840      case "COPY": {841        // AUD-002: shape-validate the payload before passing to the clipboard842        // helper. A raw cast lets a malformed message reach the clipboard API843        // with a non-string and throw.844        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {845          text?: unknown;846          label?: unknown;847          alreadyWritten?: unknown;848        };849        if (typeof text !== "string" || typeof label !== "string") {850          return { ok: false, error: "invalid_payload" };851        }852        await copyToClipboard(text, label, Boolean(alreadyWritten));853        return { ok: true, clearSeconds: getEffectiveClearSeconds() };854      }855      case "CHECK_ALL_BREACHES": {856        const allEntries = vault.getEntries();857        const results: Record<string, number> = {};858        for (const entry of allEntries) {859          if (entry.type === "note") continue;860          if (!entry.password) continue;861          results[entry.id] = await vault.checkBreach(entry.password);862          // Small delay — be a good citizen to the HIBP API863          await new Promise((r) => setTimeout(r, 200));864        }865        // Persist any non-zero counts back to entries866        for (const [id, count] of Object.entries(results)) {867          const entry = vault.getEntryById(id);868          if (entry && (entry.breach ?? 0) !== count) {869            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });870          }871        }872        return { ok: true, data: results };873      }874      case "GET_SETTINGS":875        return { ok: true, data: await vault.ensureSettingsLoaded() };876      case "UPDATE_SETTINGS": {877        const patch = msg.payload;878        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {879          return { ok: false, error: "invalid_payload" };880        }881        await vault.updateSettings(patch as vault.VaultSettings);882        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {883          await setupAutoLock();884          if (vault.isUnlocked()) touchAutoLock();885        }886        return { ok: true };887      }888      case "SETUP_PIN": {889        const { currentPassword, pin } = (msg.payload ?? {}) as {890          currentPassword?: unknown;891          pin?: unknown;892        };893        if (typeof currentPassword !== "string" || typeof pin !== "string") {894          return { ok: false, error: "invalid_payload" };895        }896        return (await vault.setupPinUnlock(currentPassword, pin))897          ? { ok: true }898          : { ok: false, error: "incorrect_current_password" };899      }900      case "DISABLE_PIN": {901        const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown };902        if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" };903        return (await vault.disablePinUnlock(currentPassword))904          ? { ok: true }905          : { ok: false, error: "incorrect_current_password" };906      }907      case "GET_PENDING_PASSKEY":908        return { ok: true, data: await getPendingPasskeyRequest() };909      case "APPROVE_PASSKEY": {910        const { requestId } = msg.payload as { requestId: number };911        await resolvePendingPasskeyRequest(requestId, true);912        return { ok: true };913      }914      case "DENY_PASSKEY": {915        const { requestId } = msg.payload as { requestId: number };916        await resolvePendingPasskeyRequest(requestId, false);917        return { ok: true };918      }919      case "GET_PASSKEY_PROVIDER_STATE":920        return { ok: true, data: await getPasskeyProviderState() };921      case "SET_PASSKEY_PROVIDER_ENABLED": {922        const { enabled } = msg.payload as { enabled: boolean };923        // Disabling is always free; gating fires only when a free user is924        // trying to turn passkey interception on.925        if (enabled) {926          const gate = await requirePro("passkeys");927          if (!gate.allowed) return { ok: false, error: "pro_required" };928        }929        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };930      }931      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS932      // endpoint. Intentional product behavior — users configure their own933      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private934      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-935      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to936      // users that the entry title leaves the device when the canary fires.937      case "FIRE_CANARY_PING": {938        // Canary alert fires unconditionally for any entry with canary: true.939        // The Pro gate only governs creation/flagging of canary entries; once940        // an entry is flagged, the alert path is a security property and must941        // never be license-gated.942        const { webhookUrl, entryTitle, trigger } = msg.payload as {943          webhookUrl: string;944          entryTitle: string;945          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";946        };947        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {948          return { ok: false, error: "invalid_webhook_url" };949        }950        // LV-3: debounce non-test pings per (webhook, entry) so a page that951        // strobes focus/fill events can't turn the canary into a request952        // firehose at the user's endpoint. Test pings are exempt — they are953        // explicit user clicks in the settings UI and are awaited for954        // feedback. The FIRST ping in a window always goes out, so the955        // dead-man's-switch property (canary fires on access) is preserved;956        // only repeats within the window are coalesced.957        if (trigger !== "test") {958          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;959          const stored = await chrome.storage.local.get(rlKey);960          const last = (stored as Record<string, unknown>)[rlKey];961          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {962            return { ok: true, data: { rateLimited: true } };963          }964          await chrome.storage.local.set({ [rlKey]: Date.now() });965        }966        const body = JSON.stringify({967          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",968          entry: entryTitle,969          trigger,970          timestamp: new Date().toISOString(),971          source: "peach-extension",972        });973        if (trigger === "test") {974          // Permitted outbound fetch: user-configured canary alert endpoint975          // (validated by isAllowedCanaryWebhookUrl above). This is the976          // only non-HIBP outbound call in the extension — see977          // Projects.md §3.7. Test pings are awaited so the UI can show978          // success/failure.979          try {980            const res = await fetch(webhookUrl, {981              method: "POST",982              headers: { "Content-Type": "application/json" },983              body,984            });985            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };986          } catch (err) {987            return { ok: false, error: err instanceof Error ? err.message : "network_error" };988          }989        }990        // Non-test triggers are fire-and-forget991        fetch(webhookUrl, {992          method: "POST",993          headers: { "Content-Type": "application/json" },994          body,995        }).catch(() => {});996        return { ok: true };997      }998      case "ACTIVATE_LICENSE": {999        const { key } = msg.payload as { key: string };1000        const licenseInfo = await activateLicense(key);1001        return { ok: true, data: licenseInfo };1002      }1003      case "GET_LICENSE": {1004        const licenseInfo = await getLicenseInfo();1005        return { ok: true, data: licenseInfo };1006      }1007      case "GET_LICENSE_KEY": {1008        const key = await getLicenseKey();1009        return { ok: true, data: key };1010      }1011      case "DEACTIVATE_LICENSE": {1012        await deactivateLicense();1013        return { ok: true };1014      }1015      case "SHOULD_PLAY_CELEBRATION": {1016        const should = await shouldPlayCelebration();1017        return { ok: true, data: should };1018      }1019      case "MARK_CELEBRATION_PLAYED": {1020        await markCelebrationPlayed();1021        return { ok: true };1022      }1023      case "GET_CODEX_VAULT_DATA": {1024        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1025        // popup navigates to the License section without further coordination.1026        const gate = await requirePro("codex");1027        if (!gate.allowed) return { ok: false, error: "pro_required" };1028        return await handleGetCodexVaultData();1029      }1030      case "ESTIMATE_CODEX_PAGES": {1031        const gate = await requirePro("codex");1032        if (!gate.allowed) return { ok: false, error: "pro_required" };1033        return await handleEstimateCodexPages();1034      }1035      case "RESTORE_FROM_CODEX": {1036        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1037        // be able to restore a vault that was printed by a Pro user.1038        // DO NOT add a Pro gate here.1039        const payload = msg.payload as CodexRestorePayload;1040        return await handleRestoreFromCodex(payload);1041      }1042      case "OPEN_PRO_GATE": {1043        // Content script requests: open popup and navigate to License section.1044        const { feature } = (msg.payload ?? {}) as { feature?: string };1045        if (chrome.storage.session) {1046          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1047        }1048        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1049        return { ok: true };1050      }1051      case "OPEN_POPUP": {1052        // Content script asks to open the trusted extension popup — used by the1053        // inline locked bubble so the master password is entered in the popup,1054        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1055        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1056        // toolbar icon. The badge already signals Peach needs attention.1057        //1058        // Set a session flag so the popup knows it was opened for inline unlock1059        // and should close itself once the vault is unlocked (returning the user1060        // to the inline autofill selector on the page).1061        if (chrome.storage.session) {1062          await chrome.storage.session.set({ peach_inline_unlock: true });1063        }1064        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1065        return { ok: true };1066      }1067      case "OPEN_DETACHED_POPUP": {1068        // A window created by the action popup and then orphaned with1069        // window.close() is cascaded shut by Chrome, so the file-picker1070        // flows (OS dialogs that dismiss the popup on focus loss) ask the SW1071        // to open the standalone window instead — the SW has no window to be1072        // associated with. The query string is allowlisted so this can never1073        // open an arbitrary URL.1074        const { route } = (msg.payload ?? {}) as { route?: string };1075        const search = route === "peachscript"1076          ? "?restore=peachscript"1077          : route === "csv"1078            ? "?restore=csv"1079            : route === "codex-pdf"1080              ? "?codex=pdf"1081              : null;1082        if (!search) return { ok: false, error: "bad_route" };1083        try {1084          const popupHtml =1085            chrome.runtime.getManifest().action?.default_popup ?? "src/popup/index.html";1086          await chrome.windows.create({1087            url: chrome.runtime.getURL(`${popupHtml}${search}`),1088            type: "popup",1089            width: 320,1090            height: 550,1091          });1092          return { ok: true, data: { detached: true } };1093        } catch {1094          return { ok: false };1095        }1096      }1097      case "GET_IDENTITIES": {1098        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1099        return { ok: true, data: vault.getIdentities() };1100      }1101      case "TOUCH_AUTO_LOCK": {1102        // touchAutoLock() is already called by shouldRefreshAutoLock above;1103        // this case just gives the popup a typed message to keep the session alive.1104        return { ok: true };1105      }1106      case "GET_ADVANCED_HEALTH_REPORT": {1107        const gate = await requirePro("advanced_health");1108        if (!gate.allowed) return { ok: false, error: "pro_required" };1109        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1110        const report = await buildAdvancedHealthReport(vault.getEntries());1111        return { ok: true, data: report };1112      }1113      case "IS_DURESS_ENABLED": {1114        const enabled = await vault.isDuressEnabled();1115        return { ok: true, data: enabled };1116      }1117      case "SETUP_DURESS": {1118        // Single enforcement point for the Duress Vault Pro gate. Free users1119        // who somehow reach this handler are rejected here; the popup also1120        // pre-checks isPro() to avoid showing the setup form to free users,1121        // but server-side is the actual security boundary.1122        const gate = await requirePro("duress_vault");1123        if (!gate.allowed) return { ok: false, error: "pro_required" };1124        // MV3 service workers restart after inactivity, losing the in-memory1125        // derived key. Detect this before calling setupDuress so the popup1126        // can show a meaningful prompt to re-lock and re-unlock.1127        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1128        const { duressPassword } = msg.payload as { duressPassword: string };1129        await vault.setupDuress(duressPassword);1130        return { ok: true };1131      }1132      case "DISABLE_DURESS": {1133        await vault.disableDuress();1134        return { ok: true };1135      }1136      case "VERIFY_MAIN_PASSWORD": {1137        const { password } = msg.payload as { password: string };1138        const ok = await vault.verifyMainPassword(password);1139        return { ok: true, data: ok };1140      }1141      case "CHANGE_PASSWORD": {1142        const { currentPassword, newPassword } = msg.payload as {1143          currentPassword: string;1144          newPassword: string;1145        };1146        const changed = await vault.changePassword(currentPassword, newPassword);1147        return changed1148          ? { ok: true }1149          : { ok: false, error: "incorrect_current_password" };1150      }1151      case "GET_SITE_PASSWORD_POLICY": {1152        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1153        if (!tab?.id) return { ok: true, data: null };1154        try {1155          const response = await chrome.tabs.sendMessage(tab.id, {1156            type: "GET_SITE_PASSWORD_POLICY",1157          });1158          return (response as MessageResponse) ?? { ok: true, data: null };1159        } catch {1160          return { ok: true, data: null };1161        }1162      }1163      case "RECORD_MANUAL_SUMMON": {1164        const { domain } = msg.payload as { domain: string };1165        const settings = vault.getSettings();1166        const existing = settings.manualSummonDomains?.[domain];1167        const now = Date.now();1168        await vault.updateSettings({1169          manualSummonDomains: {1170            ...settings.manualSummonDomains,1171            [domain]: {1172              firstSummonedAt: existing?.firstSummonedAt ?? now,1173              summonCount: (existing?.summonCount ?? 0) + 1,1174              lastSummonedAt: now,1175            },1176          },1177        });1178        return { ok: true };1179      }1180      case "DECLINE_CARD_SAVE": {1181        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1182        await vault.declineCardSaveOffer(last4, expMonth, expYear);1183        return { ok: true };1184      }1185      case "IS_CARD_DECLINED": {1186        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1187        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1188        return { ok: true, data: declined };1189      }1190      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1191        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1192          rpId?: string;1193          rpName?: string;1194          userName?: string;1195          userDisplayName?: string;1196        };1197        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1198        return await initiateFirefoxPasskeyCreate({1199          rpId,1200          rpName: rpName ?? rpId,1201          userName,1202          userDisplayName,1203        }, attestedSenderOrigin(sender));1204      }12051206      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1207        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1208        if (!payload) return { ok: false, error: "missing_payload" };1209        return await completeFirefoxPasskeyCreate(payload);1210      }12111212      case "PASSKEY_OFFER_DECLINE": {1213        const { domain } = (msg.payload ?? {}) as { domain?: string };1214        if (!domain) return { ok: false, error: "domain_required" };1215        await recordPasskeyOfferDecline(domain);1216        return { ok: true };1217      }12181219      case "GET_PASSKEY_OFFER_DECLINED": {1220        const { domain } = (msg.payload ?? {}) as { domain?: string };1221        if (!domain) return { ok: false, error: "domain_required" };1222        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1223      }12241225      case "PASSKEY_HAS_CREDENTIALS": {1226        const payload = msg.payload as {1227          rpId?: string;1228          allowCredentials?: Array<{ id: string; type?: string }>;1229        } | undefined;1230        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1231        return await handlePasskeyHasCredentials({1232          rpId: payload.rpId,1233          allowCredentials: payload.allowCredentials ?? [],1234        }, attestedSenderOrigin(sender));1235      }12361237      case "PASSKEY_CREATE": {1238        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1239        if (!payload?.rpId || !payload?.userName) {1240          return { ok: false, error: "rpid_and_username_required" };1241        }1242        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1243      }12441245      case "PASSKEY_GET": {1246        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1247        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1248        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1249      }12501251      case "PASSKEY_AUTH_RESPONSE": {1252        const { requestId, approved } = (msg.payload ?? {}) as {1253          requestId?: string | number;1254          approved?: boolean;1255        };1256        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1257          return { ok: false, error: 'requestId and approved required' };1258        }1259        await resolvePendingPasskeyRequest(Number(requestId), approved);1260        return { ok: true };1261      }12621263      case "GET_PASSKEY_FOR_DOMAIN": {1264        const { domain } = (msg.payload ?? {}) as { domain?: string };1265        if (!domain) return { ok: false, error: "domain_required" };1266        // Scope to the caller's own origin: a page may only ask about passkeys1267        // for a domain it actually owns, so an arbitrary page cannot enumerate1268        // which sites the user holds passkeys for or read the username (audit MEDIUM).1269        const origin = attestedSenderOrigin(sender);1270        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1271        if (!vault.isUnlocked()) return { ok: true, data: null };1272        const match = vault1273          .getEntries()1274          .find((entry) => entry.passkey?.rpId === domain);1275        if (!match || !match.passkey) return { ok: true, data: null };1276        // Slim shape — only the fields State 11 needs. Never expose private1277        // key material, even though this is locked behind isUnlocked.1278        return {1279          ok: true,1280          data: {1281            rpId: match.passkey.rpId,1282            userName: match.passkey.userName,1283            browser: match.passkey.browser,1284          },1285        };1286      }12871288      case "DESTROY_VAULT": {1289        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1290        // storage.local.clear() wipes every Peach key (slots, settings, license,1291        // onboarded flag, history, sync state, declined cards, recall, etc.);1292        // session.clear() wipes pending passkey requests + pro-notice queues.1293        // Caller (Panic.tsx) handles UI navigation back to onboarding.1294        //1295        // The Pro license is the one thing that must survive: the user paid for1296        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1297        // Capture it before the clear and restore it after. peach_pro_celebrated1298        // rides along so the Pro celebration doesn't replay on the next unlock.1299        const preserved = await chrome.storage.local.get([1300          "peach_license",1301          "peach_pro_celebrated",1302        ]);1303        vault.lock();1304        await storageClear();1305        await vault.clearVaultHistory();1306        const toRestore: Record<string, unknown> = {};1307        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1308        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1309        if (Object.keys(toRestore).length > 0) {1310          await chrome.storage.local.set(toRestore);1311        }1312        if (chrome.storage.session) {1313          await chrome.storage.session.clear();1314        }1315        return { ok: true };1316      }13171318      case "GET_IDENTITY_SUGGESTIONS": {1319        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1320        const entries = vault.getEntries();1321        const suggestions = buildIdentitySuggestions(entries);1322        return { ok: true, data: { suggestions } };1323      }1324      case "ML_INIT":1325        return { ok: true };13261327      case "ML_PREDICT_BATCH": {1328        // AUD-002: shape-validate before forwarding to the ML helper.1329        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1330        if (!Array.isArray(featuresArray)) {1331          return { ok: false, error: "invalid_payload" };1332        }1333        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1334      }13351336      // ── Vault sync (v3) ───────────────────────────────────────────────1337      // Returns the public-facing local identity needed by the popup to1338      // drive Phase-1 audio pairing. The private long-term key never1339      // leaves the background.1340      case "GET_LOCAL_IDENTITY": {1341        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1342        // Pro license from an already-Pro peer (at least one device must be Pro).1343        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1344        // Identity derives from the stable root key, not the password-derived1345        // key, so pairing survives a master-password change (SEV-2-B).1346        const masterKeyHex = vault.getRootKeyHex();1347        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1348        const masterKey = unhexBytes(masterKeyHex);1349        try {1350          const identity = await buildLocalIdentity(masterKey);1351          // If this device is Pro, advertise the signed license so the peer can1352          // activate it after SAS confirmation — pairing carries Pro across.1353          if (await isProUser()) {1354            const license = await getLicenseKey();1355            if (license) (identity as { license?: string }).license = license;1356          }1357          return { ok: true, data: identity };1358        } finally {1359          masterKey.fill(0);1360        }1361      }13621363      case "LIST_PAIRED_DEVICES": {1364        const devices = await listPairedDevicesV3();1365        return { ok: true, data: { devices } };1366      }13671368      case "RENAME_PAIRED_DEVICE": {1369        const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string };1370        if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") {1371          return { ok: false, error: "invalid_payload" };1372        }1373        await renamePairedDeviceV3(deviceId, name);1374        return { ok: true };1375      }13761377      case "UNPAIR_DEVICE": {1378        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1379        if (typeof deviceId !== "string" || !deviceId) {1380          return { ok: false, error: "invalid_payload" };1381        }1382        // Removing a device REVOKES it rather than just dropping the local1383        // row: a plain removal is undone the moment any other peer vouches it1384        // back through a manifest, which is exactly what the relay makes easy.1385        await revokeDeviceByIdV3(deviceId, await getOrCreateDeviceId());1386        // Sync against the remaining hosts — the unpaired device no longer1387        // matters but the next alarm tick is up to ten minutes away.1388        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1389        return { ok: true };1390      }13911392      case "RENAME_LOCAL_DEVICE": {1393        const { name } = (msg.payload ?? {}) as { name?: string };1394        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1395        await setDeviceNameV3(name);1396        return { ok: true };1397      }13981399      // ── Relay pairing ─────────────────────────────────────────────────────1400      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1401      // session runs in the background; the SAS and the terminal result reach1402      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1403      case "START_ADOPTION_SOURCE": {1404        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1405        if (isRelayAdoptionSourceInFlight()) {1406          return { ok: false, error: "adoption_source_in_progress" };1407        }1408        try {1409          return { ok: true, data: await startRelayAdoptionSource() };1410        } catch (error) {1411          return {1412            ok: false,1413            error: error instanceof Error ? error.message : "adoption_source_failed",1414          };1415        }1416      }14171418      // Onboarding receiver — empty extension shows a QR, phone scans and1419      // sends the vault. The popup supplies the local-only password here so1420      // the background can wrap the adopted root key at rest without ever1421      // asking the user to retype it.1422      case "START_ADOPTION_RECEIVER": {1423        if (isRelayAdoptionSourceInFlight()) {1424          return { ok: false, error: "adoption_receiver_in_progress" };1425        }1426        const password = (msg.payload as { password?: unknown } | undefined)?.password;1427        if (typeof password !== "string" || password.length === 0) {1428          return { ok: false, error: "invalid_payload" };1429        }1430        try {1431          return { ok: true, data: await startRelayAdoptionReceiver(password) };1432        } catch (error) {1433          return {1434            ok: false,1435            error: error instanceof Error ? error.message : "adoption_receiver_failed",1436          };1437        }1438      }14391440      // Popup→bg counterpart to ADOPTION_SOURCE_SAS (receiver flow).1441      // The receiver now auto-accepts the SAS (both sides derive it from the1442      // same Noise handshake hash, so the codes match by construction) so1443      // the popup never has a SAS screen to tap on. The id round-trips the1444      // same way so a stale late response can't approve the wrong session.1445      // Popup→bg counterpart for the source flow: Confirm/Cancel on the1446      // source's SAS screen.14471448      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1449      // on the source's SAS screen. The id round-trips the same way so a stale1450      // late response can't approve the wrong session.1451      case "SOURCE_SAS_DECISION": {1452        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1453        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1454          return { ok: false, error: "invalid_payload" };1455        }1456        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1457      }14581459      case "CANCEL_ADOPTION_SOURCE": {1460        cancelRelayAdoptionSource();1461        return { ok: true };1462      }14631464      case "TRIGGER_SYNC": {1465        const payload = (msg.payload ?? {}) as {1466          reason?: "vault_change" | "foreground" | "manual";1467          force?: boolean;1468        };1469        const reason = payload.reason ?? "foreground";14701471        void triggerSyncIfReachable({ reason, force: payload.force === true });1472        return { ok: true };1473      }14741475      case "GET_SYNC_STATE": {1476        return { ok: true, data: getSyncState() };1477      }14781479      case "GET_SYNC_SETTINGS": {1480        return { ok: true, data: await getSyncSettings() };1481      }14821483      case "SET_SYNC_SETTINGS": {1484        const payload = (msg.payload ?? {}) as {1485          mode?: unknown;1486          relayUrl?: unknown;1487        };1488        try {1489          // A custom relay URL implies private mode; Peach's own relay stays1490          // public. See setRelayUrl.1491          if (payload.relayUrl !== undefined) {1492            if (typeof payload.relayUrl !== "string") {1493              return { ok: false, error: "invalid_relay_url" };1494            }1495            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1496          }1497          if (payload.mode !== undefined) {1498            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1499              return { ok: false, error: "invalid_sync_mode" };1500            }1501            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1502          }1503          return { ok: true, data: await getSyncSettings() };1504        } catch (error) {1505          return {1506            ok: false,1507            error: error instanceof Error ? error.message : "invalid_relay_url",1508          };1509        }1510      }15111512      case "GET_SYNC_ALERTS": {1513        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1514        const alerts = await getPendingSyncAlerts();1515        // The popup reads on open and acknowledges with consume:true after1516        // rendering, so a popup crash between read and render doesn't lose1517        // the alerts.1518        if (consume) await clearPendingSyncAlerts();1519        return { ok: true, data: alerts };1520      }15211522      case "GET_PENDING_VOUCHED_DEVICES": {1523        return { ok: true, data: await listPendingVouchedDevices() };1524      }1525      case "CONFIRM_VOUCHED_DEVICE": {1526        const { deviceId } = msg.payload as { deviceId: string };1527        const pending = await getPendingVouchedDevice(deviceId);1528        if (!pending) return { ok: false, error: "not_pending" };1529        // Last gate before a vouched device becomes a sync peer. A queue entry1530        // can predate the revocation that names it, so revocation is re-checked1531        // here rather than trusted to have swept the queue.1532        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {1533          await removePendingVouchedDevice(deviceId);1534          return { ok: false, error: "device_revoked" };1535        }1536        await upsertPairedDeviceV3({1537          deviceId: pending.deviceId,1538          deviceName: pending.deviceName,1539          deviceType:1540            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1541          longTermPublicKeyHex: pending.longTermPublicKeyHex,1542          signingPublicKeyHex: pending.signingPublicKeyHex,1543          wsPort: pending.wsPort,1544          pairedAt: pending.pairedAt,1545          trustSource: "vouched",1546        });1547        await removePendingVouchedDevice(deviceId);1548        // Newly confirmed vouched device is now a sync target — kick a round1549        // so the mesh introduction pays off without a 10-minute wait.1550        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1551        return { ok: true };1552      }1553      case "REJECT_VOUCHED_DEVICE": {1554        const { deviceId } = msg.payload as { deviceId: string };1555        await removePendingVouchedDevice(deviceId);1556        return { ok: true };1557      }1558      case "ROTATE_SYNC_IDENTITY": {1559        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1560        const result = await vault.rotateSyncIdentity();1561        return result.ok ? { ok: true } : { ok: false, error: result.error };1562      }15631564      default:1565        return { ok: false, error: "unknown_message_type" };1566    }1567  } catch (err) {1568    return {1569      ok: false,1570      error: err instanceof Error ? err.message : "operation_failed",1571    };1572  }1573}15741575// Returns username use-counts from the vault, sorted by frequency. Each row1576// also carries the entry's email so the popup can suggest the email/username1577// pair the user has actually used together.1578function buildIdentitySuggestions(1579  entries: VaultEntry[],1580): Array<{ email: string; username: string; count: number }> {1581  const usernameCounts = new Map<string, number>();1582  const usernameEmail = new Map<string, string>();1583  for (const entry of entries) {1584    const username = entry.username ?? "";1585    const email = (entry as VaultEntry & { email?: string }).email ?? "";1586    if (!username && !email) continue;1587    const key = username || email;1588    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1589    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1590  }1591  return Array.from(usernameCounts.entries())1592    .sort((a, b) => b[1] - a[1])1593    .map(([username, count]) => ({1594      email: usernameEmail.get(username) ?? "",1595      username,1596      count,1597    }));1598}15991600/** Notify all content scripts that the vault just became available. */1601function broadcastToContentScripts(message: { type: string }): void {1602  if (!chrome.tabs?.query) return;1603  chrome.tabs.query({}, (tabs) => {1604    for (const tab of tabs) {1605      if (tab.id !== undefined) {1606        chrome.tabs.sendMessage(tab.id, message).catch(() => {1607          // Tab may not have a content script — silently ignore1608        });1609      }1610    }1611  });1612}16131614function shouldRefreshAutoLock(type: MessageType): boolean {1615  return (1616    type !== "HAS_VAULT" &&1617    type !== "IS_UNLOCKED" &&1618    type !== "GET_VAULT_STATUS" &&1619    type !== "LOCK" &&1620    type !== "UPDATE_SETTINGS" &&1621    type !== "GET_PENDING_PASSKEY" &&1622    type !== "GET_PASSKEY_PROVIDER_STATE" &&1623    type !== "DECLINE_CARD_SAVE" &&1624    type !== "IS_CARD_DECLINED"1625  );1626}16271628function isAllowedCanaryWebhookUrl(value: string): boolean {1629  try {1630    const url = new URL(value);1631    if (url.protocol !== "https:") return false;16321633    const hostname = url.hostname.toLowerCase();1634    if (1635      hostname === "localhost" ||1636      hostname.endsWith(".localhost") ||1637      isPrivateIpv4(hostname) ||1638      isPrivateIpv6(hostname)1639    ) {1640      return false;1641    }16421643    return true;1644  } catch {1645    return false;1646  }1647}16481649function isPrivateIpv4(hostname: string): boolean {1650  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1651    return true;1652  }16531654  const octets = hostname.split(".").map((part) => Number(part));1655  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1656    return false;1657  }16581659  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1660}16611662function isPrivateIpv6(hostname: string): boolean {1663  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1664  // IPv4-mapped IPv6 literals embed a plain IPv4 address that the prefix1665  // list below can never match (WHATWG URL serializes [::ffff:192.168.0.1]1666  // as ::ffff:c0a8:1). Unwrap and test the embedded IPv4; unparseable mapped1667  // tails fail closed. (Codex Security 2026-08-04 LOW,1668  // ssrf.webhook-url-private-ip-filter.) DNS rebinding is out of scope for a1669  // one-shot host check.1670  const mapped = /^::ffff:(.+)$/.exec(normalized);1671  if (mapped) {1672    const tail = mapped[1] ?? "";1673    if (tail.includes(".")) return isPrivateIpv4(tail);1674    const parts = tail.split(":");1675    const [hi, lo] = parts;1676    if (1677      parts.length !== 2 ||1678      !hi ||1679      !lo ||1680      !/^[0-9a-f]{1,4}$/.test(hi) ||1681      !/^[0-9a-f]{1,4}$/.test(lo)1682    ) {1683      return true;1684    }1685    const octets = [1686      (Number.parseInt(hi, 16) >>> 8) & 0xff,1687      Number.parseInt(hi, 16) & 0xff,1688      (Number.parseInt(lo, 16) >>> 8) & 0xff,1689      Number.parseInt(lo, 16) & 0xff,1690    ];1691    return isPrivateIpv4(octets.join("."));1692  }1693  return (1694    normalized === "::1" ||1695    normalized.startsWith("fc") ||1696    normalized.startsWith("fd") ||1697    normalized.startsWith("fe80:")1698  );1699}