messages.ts

71.7 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.166// PB-26-001: GET_CODEX_VAULT_DATA gated here — it returns the encrypted vault167// slots and (with a fresh password proof) the recovery words, i.e. everything168// needed to reconstruct the root key. ESTIMATE_CODEX_PAGES is gated for169// symmetry (it is popup-only and reveals vault size).170const PRIVILEGED_MESSAGE_TYPES: ReadonlySet<string> = new Set([171  "DESTROY_VAULT",172  "CLEAR_VAULT_ENTRIES",173  "RESTORE_VAULT_SNAPSHOT",174  "RESTORE_FROM_CODEX",175  "COMPLETE_FIREFOX_PASSKEY_CREATE",176  "UNLOCK_WITH_PIN",177  "SETUP_PIN",178  "DISABLE_PIN",179  "GET_LOCAL_IDENTITY",180  "GET_CODEX_VAULT_DATA",181  "ESTIMATE_CODEX_PAGES",182]);183184// LV-3: minimum interval between non-test canary pings per webhook+entry.185const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour186187const PRIVATE_IPV4_RANGES = [188  { prefix: "10." },189  { prefix: "127." },190  { prefix: "169.254." },191  { prefix: "192.168." },192];193194export function setupMessageHandler(): void {195  chrome.runtime.onMessage.addListener(196    (msg: unknown, sender, sendResponse) => {197      if (!isMessage(msg)) {198        sendResponse({ ok: false, error: "invalid_message" });199        return true;200      }201      handleMessage(msg, sender)202        .then(sendResponse)203        .catch((err) =>204          sendResponse({205            ok: false,206            error: err instanceof Error ? err.message : String(err),207          })208        );209      return true;210    }211  );212}213214function isMessage(m: unknown): m is Message {215  return typeof m === "object" && m !== null && "type" in m;216}217218/**219 * The browser-attested origin of the page that originated this message. A web220 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),221 * so every page-driven message arrives via the content-script relay and the222 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a223 * value the page cannot forge. This is the ONLY trustworthy origin for passkey224 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.225 */226function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {227  if (sender.origin) return sender.origin;228  if (sender.url) {229    try { return new URL(sender.url).origin; } catch { return undefined; }230  }231  return undefined;232}233234// Resolves once restoreFromSession() has run, so handlers see the correct235// post-restore unlock state. entry.ts registers this BEFORE the message236// handler so the onMessage listener is added synchronously at SW startup237// (MV3 requirement) while unlock-dependent handlers still wait for restore.238let restoreReady: Promise<void> = Promise.resolve();239240/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */241export function setRestoreReady(p: Promise<unknown>): void {242  restoreReady = p.then(() => undefined, () => undefined);243}244245export async function handleMessage(246  msg: Message,247  sender: Partial<chrome.runtime.MessageSender> = {}248): Promise<MessageResponse> {249  try {250    // Wait for session-restore to finish before reading any unlock/vault state.251    // On a cold SW start the popup's first message arrives while restore is252    // still in flight; without this gate IS_UNLOCKED would report locked (a253    // spurious lock screen) and the storage reads could race. The onMessage254    // listener itself is registered synchronously (entry.ts) so this gate, not255    // listener registration, is what absorbs the cold-start window.256    await restoreReady;257    // Validate sender — only allow messages from our extension pages/scripts.258    // `sender.id` is undefined for messages originating from extension UI259    // (popup/options), which is legitimate; reject only when it is defined260    // and does not match our extension id.261    if (262      sender.id !== undefined &&263      sender.id !== chrome.runtime.id264    ) {265      return { ok: false, error: "invalid_sender" };266    }267268    // PCH-01-018: destructive and sensitive operations must originate from a269    // trusted extension page (popup/options), never from a content script. The270    // sender.id check above only proves the message came from *our* extension —271    // a content script injected into an attacker page passes it. A single272    // XSS-class bug in the injected UI would otherwise escalate to vault273    // destruction, root-key exfiltration, or attacker device registration.274    // Extension pages carry an extension-origin sender.url; content scripts275    // carry a page URL.276    if (PRIVILEGED_MESSAGE_TYPES.has(msg.type)) {277      const extensionOrigin = chrome.runtime.getURL("");278      if (!sender.url?.startsWith(extensionOrigin)) {279        return { ok: false, error: "invalid_sender" };280      }281    }282283    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {284      touchAutoLock();285    }286287    switch (msg.type) {288      case "CREATE_VAULT": {289        const { password } = msg.payload as { password: string };290        // Refuse to create a vault under an empty master password — the derived291        // key would be publicly known and the at-rest AES-GCM protection void292        // (audit HIGH; the CSV-import path previously passed ""). Length/strength293        // policy lives in the onboarding UI; this is the non-negotiable floor.294        if (typeof password !== "string" || password.length === 0) {295          return { ok: false, error: "invalid_payload" };296        }297        await vault.createVault(password);298        await setupAutoLock();299        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });300        onVaultUnlocked();301        return { ok: true };302      }303      case "CREATE_VAULT_FROM_ROOT_KEY": {304        const { password, rootKeyHex } = (msg.payload ?? {}) as {305          password?: unknown;306          rootKeyHex?: unknown;307        };308        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {309          return { ok: false, error: "invalid_payload" };310        }311312        try {313          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);314          await setupAutoLock();315          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });316          onVaultUnlocked();317          return { ok: true, vaultId };318        } catch (err) {319          return { ok: false, error: err instanceof Error ? err.message : String(err) };320        }321      }322      case "UNLOCK": {323        const { password } = msg.payload as { password: string };324        const ok = await vault.unlock(password);325        if (ok) {326          // KAT: verify the WebCrypto stack is healthy before the user relies on it.327          // Runs after unlock so latency is hidden behind the vault-load time.328          const kat = await runSelfTest();329          if (!kat.ok) {330            console.error("[Peach] Crypto self-test FAILED:", kat.error);331            await vault.lock();332            return { ok: false, error: "self_test_failed" };333          }334          await vault.updateSettings({ pinPreferred: false });335          await setupAutoLock();336          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });337          onVaultUnlocked();338          return { ok: true };339        }340        // Distinguish corruption from wrong password so the popup can offer341        // a history-restore path instead of falsely accusing the user of342        // mistyping (M7/COR-007).343        const failure = vault.consumeLastUnlockFailureReason();344        if (failure) {345          return {346            ok: false,347            error: "vault_corrupted",348            canRestoreFromHistory: true,349          } as MessageResponse;350        }351        return { ok: false };352      }353      case "UNLOCK_WITH_PIN": {354        const { pin } = (msg.payload ?? {}) as { pin?: unknown };355        if (typeof pin !== "string") return { ok: false, error: "invalid_payload" };356        const ok = await vault.unlockWithPin(pin);357        if (!ok) return { ok: false };358        const kat = await runSelfTest();359        if (!kat.ok) {360          await vault.lock();361          return { ok: false, error: "self_test_failed" };362        }363        await vault.updateSettings({ pinPreferred: true });364        await setupAutoLock();365        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });366        onVaultUnlocked();367        return { ok: true };368      }369      case "VALIDATE_RECOVERY_WORDS": {370        const { words } = msg.payload as { words: string[] };371        const invalid = findInvalidWords(words);372        return { ok: true, data: { valid: invalid.length === 0, invalid } };373      }374      case "GET_RECOVERY_WORDS": {375        // Must be unlocked and have recovery set up (vault must be v2.12+).376        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };377        // LV-4: the recovery words re-derive the ROOT KEY — the highest-378        // value secret in the vault. A session unlock (which may be hours379        // old on a shared machine) is not enough; require a fresh password380        // proof, matching the 1Password/Bitwarden pattern for revealing381        // escrow material. EXEMPTION: the create-vault / rotation confirmation382        // window (peach_recovery_pending) shows the words immediately after383        // the user authenticated, and that confirmation UI has no password to384        // resend — skip the re-auth there only.385        if (!(await isRecoveryConfirmPending())) {386          const { password } = (msg.payload ?? {}) as { password?: string };387          if (typeof password !== "string" || !password) {388            return { ok: false, error: "password_required" };389          }390          if (!(await vault.verifyMainPassword(password))) {391            return { ok: false, error: "wrong_password" };392          }393        }394        try {395          const words = await vault.getRecoveryWords();396          return { ok: true, data: words };397        } catch {398          return { ok: false, error: "recovery_not_setup" };399        }400      }401      case "RECOVER_WITH_WORDS": {402        // User has lost their password but has their 12 recovery words.403        // We: (1) validate the words, (2) re-encrypt vault with new password.404        const { words, newPassword } = msg.payload as {405          words: string[];406          newPassword: string;407        };408        const stored = await vault.loadSlotA();409        if (!stored) return { ok: false, error: "no_vault" };410        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {411          return { ok: false, error: "recovery_not_setup" };412        }413        // Unwrap the root key from the recovery escrow.414        try {415          await vault.unwrapRootKeyForRecovery(416            stored.recovery_wrapped_root_key,417            stored.recovery_nonce ?? "",418            stored.recovery_tag ?? "",419            stored.recovery_salt,420            words421          );422        } catch {423          return { ok: false, error: "invalid_recovery_words" };424        }425        // Re-key: derive fresh salt + key from new password.426        const newSalt = vault.generateSalt();427        const newKey = await vault.deriveKey(newPassword, newSalt);428        // Re-wrap root key under the new password's derived key so the same429        // recovery words continue to work after the password change.430        await vault.rewrapRootKeyForPassword(newKey, newSalt);431        // Re-encrypt vault entries with the new key.432        await vault.changePasswordWithNewKey(newSalt, newKey);433        await setupAutoLock();434        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });435        return { ok: true };436      }437      case "LOCK":438        vault.lock();439        return { ok: true };440      case "IS_UNLOCKED":441        return { ok: true, data: vault.isUnlocked() };442      case "GET_VAULT_STATUS":443        return { ok: true, unlocked: vault.isUnlocked() };444      case "HAS_VAULT":445        return { ok: true, data: await vault.hasVault() };446      case "GET_ENTRIES":447        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };448        return { ok: true, data: vault.getEntries() };449      case "ADD_ENTRY": {450        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };451        const payload = msg.payload;452        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {453          return { ok: false, error: "invalid_payload" };454        }455        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);456        return { ok: true, data: entry };457      }458      case "BATCH_ADD_ENTRIES": {459        const payload = msg.payload as { entries?: unknown } | null | undefined;460        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {461          return { ok: false, error: "invalid_payload" };462        }463        if (!Array.isArray(payload.entries)) {464          return { ok: false, error: "invalid_payload" };465        }466        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);467        return { ok: true, data: added };468      }469      case "RESTORE_ENTRIES": {470        const payload = msg.payload as471          | { entries?: unknown; mode?: unknown; settings?: unknown }472          | null473          | undefined;474        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {475          return { ok: false, error: "invalid_payload" };476        }477        if (!Array.isArray(payload.entries)) {478          return { ok: false, error: "invalid_payload" };479        }480        if (payload.mode !== "replace" && payload.mode !== "merge") {481          return { ok: false, error: "invalid_payload" };482        }483        const summary = await vault.restoreEntries(484          payload.entries as Parameters<typeof vault.restoreEntries>[0],485          payload.mode486        );487        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {488          await vault.updateSettings(payload.settings as vault.VaultSettings);489        }490        return { ok: true, data: summary };491      }492      case "CLEAR_VAULT_ENTRIES": {493        await vault.clearVaultEntries("REPLACE_ALL");494        return { ok: true };495      }496      case "GET_VAULT_HISTORY": {497        const snapshots = await vault.getVaultHistory();498        return { ok: true, data: snapshots };499      }500      case "RESTORE_VAULT_SNAPSHOT": {501        const { snapshotId } = msg.payload as { snapshotId: string };502        const result = await vault.restoreVaultSnapshot(snapshotId);503        if (!result.ok) return { ok: false, error: result.error };504        broadcastToContentScripts({ type: "VAULT_LOCKED" });505        return { ok: true };506      }507      case "COUNT_DUPLICATES": {508        return { ok: true, data: vault.countDuplicates() };509      }510      case "DEDUPLICATE_ENTRIES": {511        const removed = await vault.deduplicateEntries();512        return { ok: true, data: removed };513      }514      case "UPDATE_ENTRY": {515        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;516        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {517          return { ok: false, error: "invalid_payload" };518        }519        const { id, patch } = payload;520        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {521          return { ok: false, error: "invalid_payload" };522        }523        // Single enforcement point for the Canary Entries Pro gate. Only524        // gates the transition into a canary entry — clearing/disabling a525        // canary (`canary: undefined`) is always allowed, so existing526        // canary entries remain manageable.527        const incomingCanary = (patch as { canary?: unknown }).canary;528        if (incomingCanary && typeof incomingCanary === "object") {529          const existing = vault.getEntryById(id);530          if (!existing?.canary) {531            const gate = await requirePro("canary_entry");532            if (!gate.allowed) return { ok: false, error: "pro_required" };533          }534        }535        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);536        return { ok: true };537      }538      case "ADD_ADDITIONAL_URL": {539        const { id, url } = msg.payload as { id: string; url: string };540        const trimmed = typeof url === "string" ? url.trim() : "";541        if (!trimmed) return { ok: false, error: "url_required" };542        const existing = vault.getEntryById(id);543        if (!existing) return { ok: false, error: "entry_not_found" };544        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };545        const merged = [...(existing.additionalUrls ?? []), trimmed];546        await vault.updateEntry(id, { additionalUrls: merged });547        return { ok: true };548      }549      case "DELETE_ENTRY": {550        const { id } = msg.payload as { id: string };551        await vault.deleteEntry(id);552        return { ok: true };553      }554      case "GET_DELETED_ENTRIES":555        return { ok: true, data: vault.getDeletedEntries() };556      case "RESTORE_ENTRY": {557        const { id } = msg.payload as { id: string };558        await vault.restoreEntry(id);559        return { ok: true };560      }561      case "PURGE_ENTRY": {562        const { id } = msg.payload as { id: string };563        await vault.purgeEntry(id);564        return { ok: true };565      }566      case "PURGE_EXPIRED_TRASH": {567        const { retentionMs } = msg.payload as { retentionMs: number };568        const purged = await vault.purgeExpiredTrash(retentionMs);569        return { ok: true, data: purged };570      }571      case "SAVE_NOTE": {572        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };573        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };574        const now = Date.now();575        if (id) {576          const existing = vault.getEntryById(id);577          if (!existing) return { ok: false, error: "not_found" };578          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });579          return { ok: true, data: vault.getEntryById(id) };580        } else {581          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt582          // (EntryDraft omits both), so passing them was the only reason the583          // `as any` cast existed. Dropping them makes the call type-check.584          const entry = await vault.addEntry({585            type: "note",586            title: title || "Untitled",587            notes: body,588          });589          return { ok: true, data: entry };590        }591      }592      case "DELETE_NOTE": {593        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };594        const { id } = msg.payload as { id: string };595        await vault.deleteEntry(id);596        return { ok: true };597      }598      case "GET_NOTES": {599        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };600        const notes = vault.getEntries().filter(601          (e) => e.type === "note" && !e.deletedAt602        );603        return { ok: true, data: notes } as MessageResponse;604      }605      case "SEARCH_VAULT": {606        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };607        // AUD-002: shape-validate the payload before calling string methods.608        // A raw cast lets a malformed message crash the handler with TypeError.609        const { query } = (msg.payload ?? {}) as { query?: unknown };610        if (typeof query !== "string") {611          return { ok: false, error: "invalid_payload" };612        }613        const q = query.toLowerCase();614        const searchResults = vault.getEntries().filter(615          (e) =>616            !e.deletedAt &&617            (e.title.toLowerCase().includes(q) ||618              e.notes?.toLowerCase().includes(q) ||619              e.username?.toLowerCase().includes(q))620        );621        return { ok: true, data: searchResults } as MessageResponse;622      }623      case "AUTOFILL_QUERY": {624        if (!vault.isUnlocked()) {625          return { ok: false, error: "vault_locked" };626        }627        let { includeAll } = msg.payload as { includeAll?: boolean };628        const { domain, kind, userGesture } = msg.payload as {629          domain: string;630          kind?: "login" | "card" | "totp";631          userGesture?: boolean;632        };633        // MV-2: the vault-wide inventory (every title/username/email/url)634        // may only leave the background on an explicit user gesture — the635        // user opening the search affordance — never on passive form focus.636        // userGesture is self-declared by our own content script; the value637        // of this gate is that PASSIVE code paths (which never set it)638        // cannot ship the inventory, shrinking what a compromised page that639        // merely triggers focus events can observe.640        if (includeAll && userGesture !== true) {641          includeAll = false;642        }643        // kind="card": return saved cards as compact summaries for the644        // inline card silver platter. Cards are not domain-scoped — every645        // saved card is a candidate on every checkout page — so domain is646        // ignored when kind === "card".647        if (kind === "card") {648          const cards = vault.getEntries().filter((e) => e.type === "card");649          return {650            ok: true,651            data: cards.map((e) => ({652              id: e.id,653              title: e.cardNickname || e.title,654              cardholderName: e.cardholderName,655              last4: e.last4,656              expMonth: e.expMonth,657              expYear: e.expYear,658              network: e.network,659            })),660          };661        }662        if (kind === "totp") {663          const matches = (664            includeAll665              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")666              : vault.queryDomain(domain)667          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));668          return {669            ok: true,670            data: matches.map((e) => ({671              id: e.id,672              title: e.title,673              username: e.username,674              email: e.email,675              url: e.url,676              hasTotp: true,677            })),678          };679        }680        // The inline selector fills username+password into a form. Passkey-681        // only entries have no password to fill; sign-in for those goes682        // through the WebAuthn path instead. Filter them out everywhere so683        // the user doesn't see four "GitHub" rows that mostly do nothing.684        // Notes and cards never belonged here either.685        const matches = (686          includeAll687            ? vault688                .getEntries()689                .filter((entry) => entry.type !== "note" && entry.type !== "card")690            : vault.queryDomain(domain)691        ).filter((entry) => !isPasskeyOnly(entry));692        return {693          ok: true,694          data: matches.map((e) =>695            includeAll696              ? {697                  id: e.id,698                  title: e.title,699                  // username/email/url shipped so the inline popup's search700                  // affordance can match on them, not just titles. No secrets701                  // cross the boundary — same shape as the domain-matched702                  // response below minus hasTotp (which the search list703                  // doesn't surface).704                  username: e.username,705                  email: e.email,706                  url: e.url,707                  hasPasskey: e.passkey !== undefined,708                }709              : {710                  id: e.id,711                  title: e.title,712                  username: e.username,713                  email: e.email,714                  url: e.url,715                  hasTotp: Boolean(e.totp),716                  hasPasskey: e.passkey !== undefined,717                }718          ),719        };720      }721      case "GET_ENTRY_FOR_FILL": {722        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };723        const { id, explicitSummon } = msg.payload as {724          id: string;725          explicitSummon?: boolean;726        };727        const entry = vault.getEntryById(id);728        if (!entry) return { ok: false, error: "entry_not_found" };729        // Passkey-only entries (passkey credential, no password) cannot be730        // filled into a form — sign-in goes through the WebAuthn path. A731        // login that ALSO has a passkey is still fillable for its password.732        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };733734        // MV-1: re-validate the entry against the requesting tab's origin.735        // sender.tab.url is browser-attested — a page cannot forge it. When736        // the request does not come from a tab at all (popup surfaces use737        // GET_ENTRY_FOR_EDIT, not this), refuse.738        if (sender.tab !== undefined || sender.url !== undefined) {739          let senderDomain: string | null = null;740          try {741            const rawUrl = sender.tab?.url ?? sender.url ?? "";742            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;743          } catch {744            senderDomain = null;745          }746          if (!senderDomain) return { ok: false, error: "origin_unverified" };747748          const entryDomains = new Set<string>();749          const primary = extractDomain(entry.url ?? "");750          if (primary) entryDomains.add(primary);751          for (const extra of entry.additionalUrls ?? []) {752            const d = extractDomain(extra);753            if (d) entryDomains.add(d);754          }755756          // explicitSummon=true means the user actively picked this entry757          // from the cross-domain search affordance — an intentional758          // off-domain fill. Passive fill paths must stay domain-bound.759          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {760            // Domain mismatch — refuse silently (no oracle about which ids exist).761            return { ok: false, error: "entry_not_found" };762          }763        }764        // Strip the passkey credential AND the raw base32 TOTP seed from the765        // response. Content scripts never need either: the private key is the766        // authenticator's, and handing over the TOTP seed would let a767        // compromised content script mint valid codes indefinitely (SEV-3-C).768        // Generate the *current* 6-digit code here in the background and send769        // only that, plus the seconds left so the UI can render a countdown.770        // Also drop passwordHistory: filling needs only the *current* password.771        // Handing every past password to a content script during passive772        // autofill on an arbitrary page would widen the blast radius of a773        // compromised page far beyond the one credential being filled.774        const {775          passkey: _strippedPasskey,776          totp: seed,777          totpAlgorithm,778          totpDigits,779          totpPeriod,780          passwordHistory: _ph,781          ...safeEntry782        } = entry;783        let totpCode: string | undefined;784        let totpRemaining: number | undefined;785        if (seed) {786          try {787            // PCH-01-019: honour stored algorithm/digits/period (defaults apply788            // when these are undefined, i.e. RFC-default bare-seed entries).789            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);790            totpCode = generated.code;791            totpRemaining = generated.remaining;792          } catch {793            totpCode = undefined;794          }795        }796        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };797      }798      // Trusted full-entry fetch for Peach's own inline-popup surfaces that799      // genuinely need the raw TOTP seed: the edit form (which re-saves the800      // seed and would otherwise wipe it) and nothing else. Unlike801      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside802      // the inline popup, never during passive autofill on an arbitrary page.803      // The passkey credential is still stripped — the edit form never touches it.804      case "GET_ENTRY_FOR_EDIT": {805        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };806        const { id, explicitSummon } = msg.payload as {807          id: string;808          explicitSummon?: boolean;809        };810        const entry = vault.getEntryById(id);811        if (!entry) return { ok: false, error: "entry_not_found" };812813        // PCH-01-006: re-validate the browser-attested sender origin, mirroring814        // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and815        // full password history — at least as sensitive as the fill response — so816        // the boundary must be enforced here, not only by UI reachability. Today817        // the sole caller is the popup (no sender.tab, so this is a structural818        // no-op), but a future tab-context caller or an id leak would otherwise819        // inherit a full-credential oracle. Unlike the fill path we SKIP (not820        // refuse) when no sender domain resolves, to keep the popup caller working.821        if (sender.tab !== undefined || sender.url !== undefined) {822          let senderDomain: string | null = null;823          try {824            const rawUrl = sender.tab?.url ?? sender.url ?? "";825            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;826          } catch {827            senderDomain = null;828          }829          if (senderDomain) {830            const entryDomains = new Set<string>();831            const primary = extractDomain(entry.url ?? "");832            if (primary) entryDomains.add(primary);833            for (const extra of entry.additionalUrls ?? []) {834              const d = extractDomain(extra);835              if (d) entryDomains.add(d);836            }837            if (explicitSummon !== true && !entryDomains.has(senderDomain)) {838              return { ok: false, error: "entry_not_found" }; // no id oracle839            }840          }841        }842843        const { passkey: _passkey, ...safeEntry } = entry;844        return { ok: true, data: safeEntry };845      }846      case "COPY": {847        // AUD-002: shape-validate the payload before passing to the clipboard848        // helper. A raw cast lets a malformed message reach the clipboard API849        // with a non-string and throw.850        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {851          text?: unknown;852          label?: unknown;853          alreadyWritten?: unknown;854        };855        if (typeof text !== "string" || typeof label !== "string") {856          return { ok: false, error: "invalid_payload" };857        }858        await copyToClipboard(text, label, Boolean(alreadyWritten));859        return { ok: true, clearSeconds: getEffectiveClearSeconds() };860      }861      case "CHECK_ALL_BREACHES": {862        const allEntries = vault.getEntries();863        const results: Record<string, number> = {};864        for (const entry of allEntries) {865          if (entry.type === "note") continue;866          if (!entry.password) continue;867          results[entry.id] = await vault.checkBreach(entry.password);868          // Small delay — be a good citizen to the HIBP API869          await new Promise((r) => setTimeout(r, 200));870        }871        // Persist any non-zero counts back to entries872        for (const [id, count] of Object.entries(results)) {873          const entry = vault.getEntryById(id);874          if (entry && (entry.breach ?? 0) !== count) {875            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });876          }877        }878        return { ok: true, data: results };879      }880      case "GET_SETTINGS":881        return { ok: true, data: await vault.ensureSettingsLoaded() };882      case "UPDATE_SETTINGS": {883        const patch = msg.payload;884        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {885          return { ok: false, error: "invalid_payload" };886        }887        await vault.updateSettings(patch as vault.VaultSettings);888        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {889          await setupAutoLock();890          if (vault.isUnlocked()) touchAutoLock();891        }892        return { ok: true };893      }894      case "SETUP_PIN": {895        const { currentPassword, pin } = (msg.payload ?? {}) as {896          currentPassword?: unknown;897          pin?: unknown;898        };899        if (typeof currentPassword !== "string" || typeof pin !== "string") {900          return { ok: false, error: "invalid_payload" };901        }902        return (await vault.setupPinUnlock(currentPassword, pin))903          ? { ok: true }904          : { ok: false, error: "incorrect_current_password" };905      }906      case "DISABLE_PIN": {907        const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown };908        if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" };909        return (await vault.disablePinUnlock(currentPassword))910          ? { ok: true }911          : { ok: false, error: "incorrect_current_password" };912      }913      case "GET_PENDING_PASSKEY":914        return { ok: true, data: await getPendingPasskeyRequest() };915      case "APPROVE_PASSKEY": {916        const { requestId } = msg.payload as { requestId: number };917        await resolvePendingPasskeyRequest(requestId, true);918        return { ok: true };919      }920      case "DENY_PASSKEY": {921        const { requestId } = msg.payload as { requestId: number };922        await resolvePendingPasskeyRequest(requestId, false);923        return { ok: true };924      }925      case "GET_PASSKEY_PROVIDER_STATE":926        return { ok: true, data: await getPasskeyProviderState() };927      case "SET_PASSKEY_PROVIDER_ENABLED": {928        const { enabled } = msg.payload as { enabled: boolean };929        // Disabling is always free; gating fires only when a free user is930        // trying to turn passkey interception on.931        if (enabled) {932          const gate = await requirePro("passkeys");933          if (!gate.allowed) return { ok: false, error: "pro_required" };934        }935        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };936      }937      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS938      // endpoint. Intentional product behavior — users configure their own939      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private940      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-941      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to942      // users that the entry title leaves the device when the canary fires.943      case "FIRE_CANARY_PING": {944        // Canary alert fires unconditionally for any entry with canary: true.945        // The Pro gate only governs creation/flagging of canary entries; once946        // an entry is flagged, the alert path is a security property and must947        // never be license-gated.948        const { webhookUrl, entryTitle, trigger } = msg.payload as {949          webhookUrl: string;950          entryTitle: string;951          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";952        };953        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {954          return { ok: false, error: "invalid_webhook_url" };955        }956        // LV-3: debounce non-test pings per (webhook, entry) so a page that957        // strobes focus/fill events can't turn the canary into a request958        // firehose at the user's endpoint. Test pings are exempt — they are959        // explicit user clicks in the settings UI and are awaited for960        // feedback. The FIRST ping in a window always goes out, so the961        // dead-man's-switch property (canary fires on access) is preserved;962        // only repeats within the window are coalesced.963        if (trigger !== "test") {964          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;965          const stored = await chrome.storage.local.get(rlKey);966          const last = (stored as Record<string, unknown>)[rlKey];967          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {968            return { ok: true, data: { rateLimited: true } };969          }970          await chrome.storage.local.set({ [rlKey]: Date.now() });971        }972        const body = JSON.stringify({973          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",974          entry: entryTitle,975          trigger,976          timestamp: new Date().toISOString(),977          source: "peach-extension",978        });979        if (trigger === "test") {980          // Permitted outbound fetch: user-configured canary alert endpoint981          // (validated by isAllowedCanaryWebhookUrl above). This is the982          // only non-HIBP outbound call in the extension — see983          // Projects.md §3.7. Test pings are awaited so the UI can show984          // success/failure.985          try {986            const res = await fetch(webhookUrl, {987              method: "POST",988              headers: { "Content-Type": "application/json" },989              body,990            });991            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };992          } catch (err) {993            return { ok: false, error: err instanceof Error ? err.message : "network_error" };994          }995        }996        // Non-test triggers are fire-and-forget997        fetch(webhookUrl, {998          method: "POST",999          headers: { "Content-Type": "application/json" },1000          body,1001        }).catch(() => {});1002        return { ok: true };1003      }1004      case "ACTIVATE_LICENSE": {1005        const { key } = msg.payload as { key: string };1006        const licenseInfo = await activateLicense(key);1007        return { ok: true, data: licenseInfo };1008      }1009      case "GET_LICENSE": {1010        const licenseInfo = await getLicenseInfo();1011        return { ok: true, data: licenseInfo };1012      }1013      case "GET_LICENSE_KEY": {1014        const key = await getLicenseKey();1015        return { ok: true, data: key };1016      }1017      case "DEACTIVATE_LICENSE": {1018        await deactivateLicense();1019        return { ok: true };1020      }1021      case "SHOULD_PLAY_CELEBRATION": {1022        const should = await shouldPlayCelebration();1023        return { ok: true, data: should };1024      }1025      case "MARK_CELEBRATION_PLAYED": {1026        await markCelebrationPlayed();1027        return { ok: true };1028      }1029      case "GET_CODEX_VAULT_DATA": {1030        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1031        // popup navigates to the License section without further coordination.1032        // Also privileged-page-gated (PB-26-001), and recoveryWords inside the1033        // snapshot additionally require a fresh master-password proof.1034        const gate = await requirePro("codex");1035        if (!gate.allowed) return { ok: false, error: "pro_required" };1036        const { password } = (msg.payload ?? {}) as { password?: string };1037        return await handleGetCodexVaultData(password);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}