messages.ts

72.0 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard, 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 frame's origin.735        // sender.url / sender.tab.url are browser-attested — a page cannot736        // forge them. PB-26-005: the FRAME url (sender.url) is authoritative737        // for an all_frames content script; the top-frame tab.url would738        // misattribute a cross-origin iframe's request to the top page. When739        // the request does not come from a tab at all (popup surfaces use740        // GET_ENTRY_FOR_EDIT, not this), refuse.741        if (sender.tab !== undefined || sender.url !== undefined) {742          let senderDomain: string | null = null;743          try {744            const rawUrl = sender.url ?? sender.tab?.url ?? "";745            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;746          } catch {747            senderDomain = null;748          }749          if (!senderDomain) return { ok: false, error: "origin_unverified" };750751          const entryDomains = new Set<string>();752          const primary = extractDomain(entry.url ?? "");753          if (primary) entryDomains.add(primary);754          for (const extra of entry.additionalUrls ?? []) {755            const d = extractDomain(extra);756            if (d) entryDomains.add(d);757          }758759          // explicitSummon=true means the user actively picked this entry760          // from the cross-domain search affordance — an intentional761          // off-domain fill. Passive fill paths must stay domain-bound.762          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {763            // Domain mismatch — refuse silently (no oracle about which ids exist).764            return { ok: false, error: "entry_not_found" };765          }766        }767        // Strip the passkey credential AND the raw base32 TOTP seed from the768        // response. Content scripts never need either: the private key is the769        // authenticator's, and handing over the TOTP seed would let a770        // compromised content script mint valid codes indefinitely (SEV-3-C).771        // Generate the *current* 6-digit code here in the background and send772        // only that, plus the seconds left so the UI can render a countdown.773        // Also drop passwordHistory: filling needs only the *current* password.774        // Handing every past password to a content script during passive775        // autofill on an arbitrary page would widen the blast radius of a776        // compromised page far beyond the one credential being filled.777        const {778          passkey: _strippedPasskey,779          totp: seed,780          totpAlgorithm,781          totpDigits,782          totpPeriod,783          passwordHistory: _ph,784          ...safeEntry785        } = entry;786        let totpCode: string | undefined;787        let totpRemaining: number | undefined;788        if (seed) {789          try {790            // PCH-01-019: honour stored algorithm/digits/period (defaults apply791            // when these are undefined, i.e. RFC-default bare-seed entries).792            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);793            totpCode = generated.code;794            totpRemaining = generated.remaining;795          } catch {796            totpCode = undefined;797          }798        }799        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };800      }801      // Trusted full-entry fetch for Peach's own inline-popup surfaces that802      // genuinely need the raw TOTP seed: the edit form (which re-saves the803      // seed and would otherwise wipe it) and nothing else. Unlike804      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside805      // the inline popup, never during passive autofill on an arbitrary page.806      // The passkey credential is still stripped — the edit form never touches it.807      case "GET_ENTRY_FOR_EDIT": {808        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };809        const { id, explicitSummon } = msg.payload as {810          id: string;811          explicitSummon?: boolean;812        };813        const entry = vault.getEntryById(id);814        if (!entry) return { ok: false, error: "entry_not_found" };815816        // PCH-01-006: re-validate the browser-attested sender origin, mirroring817        // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and818        // full password history — at least as sensitive as the fill response — so819        // the boundary must be enforced here, not only by UI reachability. Today820        // the sole caller is the popup (no sender.tab, so this is a structural821        // no-op), but a future tab-context caller or an id leak would otherwise822        // inherit a full-credential oracle. Unlike the fill path we SKIP (not823        // refuse) when no sender domain resolves, to keep the popup caller working.824        // PB-26-005: the frame url (sender.url) is authoritative over the825        // top-frame sender.tab.url — mirrors the fill path.826        if (sender.tab !== undefined || sender.url !== undefined) {827          let senderDomain: string | null = null;828          try {829            const rawUrl = sender.url ?? sender.tab?.url ?? "";830            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;831          } catch {832            senderDomain = null;833          }834          if (senderDomain) {835            const entryDomains = new Set<string>();836            const primary = extractDomain(entry.url ?? "");837            if (primary) entryDomains.add(primary);838            for (const extra of entry.additionalUrls ?? []) {839              const d = extractDomain(extra);840              if (d) entryDomains.add(d);841            }842            if (explicitSummon !== true && !entryDomains.has(senderDomain)) {843              return { ok: false, error: "entry_not_found" }; // no id oracle844            }845          }846        }847848        const { passkey: _passkey, ...safeEntry } = entry;849        return { ok: true, data: safeEntry };850      }851      case "COPY": {852        // AUD-002: shape-validate the payload before passing to the clipboard853        // helper. A raw cast lets a malformed message reach the clipboard API854        // with a non-string and throw.855        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {856          text?: unknown;857          label?: unknown;858          alreadyWritten?: unknown;859        };860        if (typeof text !== "string" || typeof label !== "string") {861          return { ok: false, error: "invalid_payload" };862        }863        await copyToClipboard(text, label, Boolean(alreadyWritten));864        return { ok: true, clearSeconds: getEffectiveClearSeconds() };865      }866      case "CHECK_ALL_BREACHES": {867        const allEntries = vault.getEntries();868        const results: Record<string, number> = {};869        for (const entry of allEntries) {870          if (entry.type === "note") continue;871          if (!entry.password) continue;872          results[entry.id] = await vault.checkBreach(entry.password);873          // Small delay — be a good citizen to the HIBP API874          await new Promise((r) => setTimeout(r, 200));875        }876        // Persist any non-zero counts back to entries877        for (const [id, count] of Object.entries(results)) {878          const entry = vault.getEntryById(id);879          if (entry && (entry.breach ?? 0) !== count) {880            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });881          }882        }883        return { ok: true, data: results };884      }885      case "GET_SETTINGS":886        return { ok: true, data: await vault.ensureSettingsLoaded() };887      case "UPDATE_SETTINGS": {888        const patch = msg.payload;889        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {890          return { ok: false, error: "invalid_payload" };891        }892        await vault.updateSettings(patch as vault.VaultSettings);893        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {894          await setupAutoLock();895          if (vault.isUnlocked()) touchAutoLock();896        }897        return { ok: true };898      }899      case "SETUP_PIN": {900        const { currentPassword, pin } = (msg.payload ?? {}) as {901          currentPassword?: unknown;902          pin?: unknown;903        };904        if (typeof currentPassword !== "string" || typeof pin !== "string") {905          return { ok: false, error: "invalid_payload" };906        }907        return (await vault.setupPinUnlock(currentPassword, pin))908          ? { ok: true }909          : { ok: false, error: "incorrect_current_password" };910      }911      case "DISABLE_PIN": {912        const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown };913        if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" };914        return (await vault.disablePinUnlock(currentPassword))915          ? { ok: true }916          : { ok: false, error: "incorrect_current_password" };917      }918      case "GET_PENDING_PASSKEY":919        return { ok: true, data: await getPendingPasskeyRequest() };920      case "APPROVE_PASSKEY": {921        const { requestId } = msg.payload as { requestId: number };922        await resolvePendingPasskeyRequest(requestId, true);923        return { ok: true };924      }925      case "DENY_PASSKEY": {926        const { requestId } = msg.payload as { requestId: number };927        await resolvePendingPasskeyRequest(requestId, false);928        return { ok: true };929      }930      case "GET_PASSKEY_PROVIDER_STATE":931        return { ok: true, data: await getPasskeyProviderState() };932      case "SET_PASSKEY_PROVIDER_ENABLED": {933        const { enabled } = msg.payload as { enabled: boolean };934        // Disabling is always free; gating fires only when a free user is935        // trying to turn passkey interception on.936        if (enabled) {937          const gate = await requirePro("passkeys");938          if (!gate.allowed) return { ok: false, error: "pro_required" };939        }940        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };941      }942      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS943      // endpoint. Intentional product behavior — users configure their own944      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private945      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-946      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to947      // users that the entry title leaves the device when the canary fires.948      case "FIRE_CANARY_PING": {949        // Canary alert fires unconditionally for any entry with canary: true.950        // The Pro gate only governs creation/flagging of canary entries; once951        // an entry is flagged, the alert path is a security property and must952        // never be license-gated.953        const { webhookUrl, entryTitle, trigger } = msg.payload as {954          webhookUrl: string;955          entryTitle: string;956          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";957        };958        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {959          return { ok: false, error: "invalid_webhook_url" };960        }961        // LV-3: debounce non-test pings per (webhook, entry) so a page that962        // strobes focus/fill events can't turn the canary into a request963        // firehose at the user's endpoint. Test pings are exempt — they are964        // explicit user clicks in the settings UI and are awaited for965        // feedback. The FIRST ping in a window always goes out, so the966        // dead-man's-switch property (canary fires on access) is preserved;967        // only repeats within the window are coalesced.968        if (trigger !== "test") {969          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;970          const stored = await chrome.storage.local.get(rlKey);971          const last = (stored as Record<string, unknown>)[rlKey];972          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {973            return { ok: true, data: { rateLimited: true } };974          }975          await chrome.storage.local.set({ [rlKey]: Date.now() });976        }977        const body = JSON.stringify({978          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",979          entry: entryTitle,980          trigger,981          timestamp: new Date().toISOString(),982          source: "peach-extension",983        });984        if (trigger === "test") {985          // Permitted outbound fetch: user-configured canary alert endpoint986          // (validated by isAllowedCanaryWebhookUrl above). This is the987          // only non-HIBP outbound call in the extension — see988          // Projects.md §3.7. Test pings are awaited so the UI can show989          // success/failure.990          try {991            const res = await fetch(webhookUrl, {992              method: "POST",993              headers: { "Content-Type": "application/json" },994              body,995            });996            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };997          } catch (err) {998            return { ok: false, error: err instanceof Error ? err.message : "network_error" };999          }1000        }1001        // Non-test triggers are fire-and-forget1002        fetch(webhookUrl, {1003          method: "POST",1004          headers: { "Content-Type": "application/json" },1005          body,1006        }).catch(() => {});1007        return { ok: true };1008      }1009      case "ACTIVATE_LICENSE": {1010        const { key } = msg.payload as { key: string };1011        const licenseInfo = await activateLicense(key);1012        return { ok: true, data: licenseInfo };1013      }1014      case "GET_LICENSE": {1015        const licenseInfo = await getLicenseInfo();1016        return { ok: true, data: licenseInfo };1017      }1018      case "GET_LICENSE_KEY": {1019        const key = await getLicenseKey();1020        return { ok: true, data: key };1021      }1022      case "DEACTIVATE_LICENSE": {1023        await deactivateLicense();1024        return { ok: true };1025      }1026      case "SHOULD_PLAY_CELEBRATION": {1027        const should = await shouldPlayCelebration();1028        return { ok: true, data: should };1029      }1030      case "MARK_CELEBRATION_PLAYED": {1031        await markCelebrationPlayed();1032        return { ok: true };1033      }1034      case "GET_CODEX_VAULT_DATA": {1035        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1036        // popup navigates to the License section without further coordination.1037        // Also privileged-page-gated (PB-26-001), and recoveryWords inside the1038        // snapshot additionally require a fresh master-password proof.1039        const gate = await requirePro("codex");1040        if (!gate.allowed) return { ok: false, error: "pro_required" };1041        const { password } = (msg.payload ?? {}) as { password?: string };1042        return await handleGetCodexVaultData(password);1043      }1044      case "ESTIMATE_CODEX_PAGES": {1045        const gate = await requirePro("codex");1046        if (!gate.allowed) return { ok: false, error: "pro_required" };1047        return await handleEstimateCodexPages();1048      }1049      case "RESTORE_FROM_CODEX": {1050        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1051        // be able to restore a vault that was printed by a Pro user.1052        // DO NOT add a Pro gate here.1053        const payload = msg.payload as CodexRestorePayload;1054        return await handleRestoreFromCodex(payload);1055      }1056      case "OPEN_PRO_GATE": {1057        // Content script requests: open popup and navigate to License section.1058        const { feature } = (msg.payload ?? {}) as { feature?: string };1059        if (chrome.storage.session) {1060          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1061        }1062        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1063        return { ok: true };1064      }1065      case "OPEN_POPUP": {1066        // Content script asks to open the trusted extension popup — used by the1067        // inline locked bubble so the master password is entered in the popup,1068        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1069        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1070        // toolbar icon. The badge already signals Peach needs attention.1071        //1072        // Set a session flag so the popup knows it was opened for inline unlock1073        // and should close itself once the vault is unlocked (returning the user1074        // to the inline autofill selector on the page).1075        if (chrome.storage.session) {1076          await chrome.storage.session.set({ peach_inline_unlock: true });1077        }1078        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1079        return { ok: true };1080      }1081      case "OPEN_DETACHED_POPUP": {1082        // A window created by the action popup and then orphaned with1083        // window.close() is cascaded shut by Chrome, so the file-picker1084        // flows (OS dialogs that dismiss the popup on focus loss) ask the SW1085        // to open the standalone window instead — the SW has no window to be1086        // associated with. The query string is allowlisted so this can never1087        // open an arbitrary URL.1088        const { route } = (msg.payload ?? {}) as { route?: string };1089        const search = route === "peachscript"1090          ? "?restore=peachscript"1091          : route === "csv"1092            ? "?restore=csv"1093            : route === "codex-pdf"1094              ? "?codex=pdf"1095              : null;1096        if (!search) return { ok: false, error: "bad_route" };1097        try {1098          const popupHtml =1099            chrome.runtime.getManifest().action?.default_popup ?? "src/popup/index.html";1100          await chrome.windows.create({1101            url: chrome.runtime.getURL(`${popupHtml}${search}`),1102            type: "popup",1103            width: 320,1104            height: 550,1105          });1106          return { ok: true, data: { detached: true } };1107        } catch {1108          return { ok: false };1109        }1110      }1111      case "GET_IDENTITIES": {1112        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1113        return { ok: true, data: vault.getIdentities() };1114      }1115      case "TOUCH_AUTO_LOCK": {1116        // touchAutoLock() is already called by shouldRefreshAutoLock above;1117        // this case just gives the popup a typed message to keep the session alive.1118        return { ok: true };1119      }1120      case "GET_ADVANCED_HEALTH_REPORT": {1121        const gate = await requirePro("advanced_health");1122        if (!gate.allowed) return { ok: false, error: "pro_required" };1123        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1124        const report = await buildAdvancedHealthReport(vault.getEntries());1125        return { ok: true, data: report };1126      }1127      case "IS_DURESS_ENABLED": {1128        const enabled = await vault.isDuressEnabled();1129        return { ok: true, data: enabled };1130      }1131      case "SETUP_DURESS": {1132        // Single enforcement point for the Duress Vault Pro gate. Free users1133        // who somehow reach this handler are rejected here; the popup also1134        // pre-checks isPro() to avoid showing the setup form to free users,1135        // but server-side is the actual security boundary.1136        const gate = await requirePro("duress_vault");1137        if (!gate.allowed) return { ok: false, error: "pro_required" };1138        // MV3 service workers restart after inactivity, losing the in-memory1139        // derived key. Detect this before calling setupDuress so the popup1140        // can show a meaningful prompt to re-lock and re-unlock.1141        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1142        const { duressPassword } = msg.payload as { duressPassword: string };1143        await vault.setupDuress(duressPassword);1144        return { ok: true };1145      }1146      case "DISABLE_DURESS": {1147        await vault.disableDuress();1148        return { ok: true };1149      }1150      case "VERIFY_MAIN_PASSWORD": {1151        const { password } = msg.payload as { password: string };1152        const ok = await vault.verifyMainPassword(password);1153        return { ok: true, data: ok };1154      }1155      case "CHANGE_PASSWORD": {1156        const { currentPassword, newPassword } = msg.payload as {1157          currentPassword: string;1158          newPassword: string;1159        };1160        const changed = await vault.changePassword(currentPassword, newPassword);1161        return changed1162          ? { ok: true }1163          : { ok: false, error: "incorrect_current_password" };1164      }1165      case "GET_SITE_PASSWORD_POLICY": {1166        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1167        if (!tab?.id) return { ok: true, data: null };1168        try {1169          const response = await chrome.tabs.sendMessage(tab.id, {1170            type: "GET_SITE_PASSWORD_POLICY",1171          });1172          return (response as MessageResponse) ?? { ok: true, data: null };1173        } catch {1174          return { ok: true, data: null };1175        }1176      }1177      case "RECORD_MANUAL_SUMMON": {1178        const { domain } = msg.payload as { domain: string };1179        const settings = vault.getSettings();1180        const existing = settings.manualSummonDomains?.[domain];1181        const now = Date.now();1182        await vault.updateSettings({1183          manualSummonDomains: {1184            ...settings.manualSummonDomains,1185            [domain]: {1186              firstSummonedAt: existing?.firstSummonedAt ?? now,1187              summonCount: (existing?.summonCount ?? 0) + 1,1188              lastSummonedAt: now,1189            },1190          },1191        });1192        return { ok: true };1193      }1194      case "DECLINE_CARD_SAVE": {1195        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1196        await vault.declineCardSaveOffer(last4, expMonth, expYear);1197        return { ok: true };1198      }1199      case "IS_CARD_DECLINED": {1200        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1201        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1202        return { ok: true, data: declined };1203      }1204      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1205        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1206          rpId?: string;1207          rpName?: string;1208          userName?: string;1209          userDisplayName?: string;1210        };1211        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1212        return await initiateFirefoxPasskeyCreate({1213          rpId,1214          rpName: rpName ?? rpId,1215          userName,1216          userDisplayName,1217        }, attestedSenderOrigin(sender));1218      }12191220      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1221        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1222        if (!payload) return { ok: false, error: "missing_payload" };1223        return await completeFirefoxPasskeyCreate(payload);1224      }12251226      case "PASSKEY_OFFER_DECLINE": {1227        const { domain } = (msg.payload ?? {}) as { domain?: string };1228        if (!domain) return { ok: false, error: "domain_required" };1229        await recordPasskeyOfferDecline(domain);1230        return { ok: true };1231      }12321233      case "GET_PASSKEY_OFFER_DECLINED": {1234        const { domain } = (msg.payload ?? {}) as { domain?: string };1235        if (!domain) return { ok: false, error: "domain_required" };1236        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1237      }12381239      case "PASSKEY_HAS_CREDENTIALS": {1240        const payload = msg.payload as {1241          rpId?: string;1242          allowCredentials?: Array<{ id: string; type?: string }>;1243        } | undefined;1244        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1245        return await handlePasskeyHasCredentials({1246          rpId: payload.rpId,1247          allowCredentials: payload.allowCredentials ?? [],1248        }, attestedSenderOrigin(sender));1249      }12501251      case "PASSKEY_CREATE": {1252        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1253        if (!payload?.rpId || !payload?.userName) {1254          return { ok: false, error: "rpid_and_username_required" };1255        }1256        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1257      }12581259      case "PASSKEY_GET": {1260        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1261        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1262        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1263      }12641265      case "PASSKEY_AUTH_RESPONSE": {1266        const { requestId, approved } = (msg.payload ?? {}) as {1267          requestId?: string | number;1268          approved?: boolean;1269        };1270        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1271          return { ok: false, error: 'requestId and approved required' };1272        }1273        await resolvePendingPasskeyRequest(Number(requestId), approved);1274        return { ok: true };1275      }12761277      case "GET_PASSKEY_FOR_DOMAIN": {1278        const { domain } = (msg.payload ?? {}) as { domain?: string };1279        if (!domain) return { ok: false, error: "domain_required" };1280        // Scope to the caller's own origin: a page may only ask about passkeys1281        // for a domain it actually owns, so an arbitrary page cannot enumerate1282        // which sites the user holds passkeys for or read the username (audit MEDIUM).1283        const origin = attestedSenderOrigin(sender);1284        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1285        if (!vault.isUnlocked()) return { ok: true, data: null };1286        const match = vault1287          .getEntries()1288          .find((entry) => entry.passkey?.rpId === domain);1289        if (!match || !match.passkey) return { ok: true, data: null };1290        // Slim shape — only the fields State 11 needs. Never expose private1291        // key material, even though this is locked behind isUnlocked.1292        return {1293          ok: true,1294          data: {1295            rpId: match.passkey.rpId,1296            userName: match.passkey.userName,1297            browser: match.passkey.browser,1298          },1299        };1300      }13011302      case "DESTROY_VAULT": {1303        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1304        // storage.local.clear() wipes every Peach key (slots, settings, license,1305        // onboarded flag, history, sync state, declined cards, recall, etc.);1306        // session.clear() wipes pending passkey requests + pro-notice queues.1307        // Caller (Panic.tsx) handles UI navigation back to onboarding.1308        //1309        // The Pro license is the one thing that must survive: the user paid for1310        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1311        // Capture it before the clear and restore it after. peach_pro_celebrated1312        // rides along so the Pro celebration doesn't replay on the next unlock.1313        const preserved = await chrome.storage.local.get([1314          "peach_license",1315          "peach_pro_celebrated",1316        ]);1317        vault.lock();1318        await storageClear();1319        await vault.clearVaultHistory();1320        const toRestore: Record<string, unknown> = {};1321        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1322        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1323        if (Object.keys(toRestore).length > 0) {1324          await chrome.storage.local.set(toRestore);1325        }1326        if (chrome.storage.session) {1327          await chrome.storage.session.clear();1328        }1329        return { ok: true };1330      }13311332      case "GET_IDENTITY_SUGGESTIONS": {1333        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1334        const entries = vault.getEntries();1335        const suggestions = buildIdentitySuggestions(entries);1336        return { ok: true, data: { suggestions } };1337      }1338      case "ML_INIT":1339        return { ok: true };13401341      case "ML_PREDICT_BATCH": {1342        // AUD-002: shape-validate before forwarding to the ML helper.1343        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1344        if (!Array.isArray(featuresArray)) {1345          return { ok: false, error: "invalid_payload" };1346        }1347        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1348      }13491350      // ── Vault sync (v3) ───────────────────────────────────────────────1351      // Returns the public-facing local identity needed by the popup to1352      // drive Phase-1 audio pairing. The private long-term key never1353      // leaves the background.1354      case "GET_LOCAL_IDENTITY": {1355        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1356        // Pro license from an already-Pro peer (at least one device must be Pro).1357        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1358        // Identity derives from the stable root key, not the password-derived1359        // key, so pairing survives a master-password change (SEV-2-B).1360        const masterKeyHex = vault.getRootKeyHex();1361        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1362        const masterKey = unhexBytes(masterKeyHex);1363        try {1364          const identity = await buildLocalIdentity(masterKey);1365          // If this device is Pro, advertise the signed license so the peer can1366          // activate it after SAS confirmation — pairing carries Pro across.1367          if (await isProUser()) {1368            const license = await getLicenseKey();1369            if (license) (identity as { license?: string }).license = license;1370          }1371          return { ok: true, data: identity };1372        } finally {1373          masterKey.fill(0);1374        }1375      }13761377      case "LIST_PAIRED_DEVICES": {1378        const devices = await listPairedDevicesV3();1379        return { ok: true, data: { devices } };1380      }13811382      case "RENAME_PAIRED_DEVICE": {1383        const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string };1384        if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") {1385          return { ok: false, error: "invalid_payload" };1386        }1387        await renamePairedDeviceV3(deviceId, name);1388        return { ok: true };1389      }13901391      case "UNPAIR_DEVICE": {1392        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1393        if (typeof deviceId !== "string" || !deviceId) {1394          return { ok: false, error: "invalid_payload" };1395        }1396        // Removing a device REVOKES it rather than just dropping the local1397        // row: a plain removal is undone the moment any other peer vouches it1398        // back through a manifest, which is exactly what the relay makes easy.1399        await revokeDeviceByIdV3(deviceId, await getOrCreateDeviceId());1400        // Sync against the remaining hosts — the unpaired device no longer1401        // matters but the next alarm tick is up to ten minutes away.1402        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1403        return { ok: true };1404      }14051406      case "RENAME_LOCAL_DEVICE": {1407        const { name } = (msg.payload ?? {}) as { name?: string };1408        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1409        await setDeviceNameV3(name);1410        return { ok: true };1411      }14121413      // ── Relay pairing ─────────────────────────────────────────────────────1414      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1415      // session runs in the background; the SAS and the terminal result reach1416      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1417      case "START_ADOPTION_SOURCE": {1418        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1419        if (isRelayAdoptionSourceInFlight()) {1420          return { ok: false, error: "adoption_source_in_progress" };1421        }1422        try {1423          return { ok: true, data: await startRelayAdoptionSource() };1424        } catch (error) {1425          return {1426            ok: false,1427            error: error instanceof Error ? error.message : "adoption_source_failed",1428          };1429        }1430      }14311432      // Onboarding receiver — empty extension shows a QR, phone scans and1433      // sends the vault. The popup supplies the local-only password here so1434      // the background can wrap the adopted root key at rest without ever1435      // asking the user to retype it.1436      case "START_ADOPTION_RECEIVER": {1437        if (isRelayAdoptionSourceInFlight()) {1438          return { ok: false, error: "adoption_receiver_in_progress" };1439        }1440        const password = (msg.payload as { password?: unknown } | undefined)?.password;1441        if (typeof password !== "string" || password.length === 0) {1442          return { ok: false, error: "invalid_payload" };1443        }1444        try {1445          return { ok: true, data: await startRelayAdoptionReceiver(password) };1446        } catch (error) {1447          return {1448            ok: false,1449            error: error instanceof Error ? error.message : "adoption_receiver_failed",1450          };1451        }1452      }14531454      // Popup→bg counterpart to ADOPTION_SOURCE_SAS (receiver flow).1455      // The receiver now auto-accepts the SAS (both sides derive it from the1456      // same Noise handshake hash, so the codes match by construction) so1457      // the popup never has a SAS screen to tap on. The id round-trips the1458      // same way so a stale late response can't approve the wrong session.1459      // Popup→bg counterpart for the source flow: Confirm/Cancel on the1460      // source's SAS screen.14611462      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1463      // on the source's SAS screen. The id round-trips the same way so a stale1464      // late response can't approve the wrong session.1465      case "SOURCE_SAS_DECISION": {1466        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1467        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1468          return { ok: false, error: "invalid_payload" };1469        }1470        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1471      }14721473      case "CANCEL_ADOPTION_SOURCE": {1474        cancelRelayAdoptionSource();1475        return { ok: true };1476      }14771478      case "TRIGGER_SYNC": {1479        const payload = (msg.payload ?? {}) as {1480          reason?: "vault_change" | "foreground" | "manual";1481          force?: boolean;1482        };1483        const reason = payload.reason ?? "foreground";14841485        void triggerSyncIfReachable({ reason, force: payload.force === true });1486        return { ok: true };1487      }14881489      case "GET_SYNC_STATE": {1490        return { ok: true, data: getSyncState() };1491      }14921493      case "GET_SYNC_SETTINGS": {1494        return { ok: true, data: await getSyncSettings() };1495      }14961497      case "SET_SYNC_SETTINGS": {1498        const payload = (msg.payload ?? {}) as {1499          mode?: unknown;1500          relayUrl?: unknown;1501        };1502        try {1503          // A custom relay URL implies private mode; Peach's own relay stays1504          // public. See setRelayUrl.1505          if (payload.relayUrl !== undefined) {1506            if (typeof payload.relayUrl !== "string") {1507              return { ok: false, error: "invalid_relay_url" };1508            }1509            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1510          }1511          if (payload.mode !== undefined) {1512            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1513              return { ok: false, error: "invalid_sync_mode" };1514            }1515            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1516          }1517          return { ok: true, data: await getSyncSettings() };1518        } catch (error) {1519          return {1520            ok: false,1521            error: error instanceof Error ? error.message : "invalid_relay_url",1522          };1523        }1524      }15251526      case "GET_SYNC_ALERTS": {1527        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1528        const alerts = await getPendingSyncAlerts();1529        // The popup reads on open and acknowledges with consume:true after1530        // rendering, so a popup crash between read and render doesn't lose1531        // the alerts.1532        if (consume) await clearPendingSyncAlerts();1533        return { ok: true, data: alerts };1534      }15351536      case "GET_PENDING_VOUCHED_DEVICES": {1537        return { ok: true, data: await listPendingVouchedDevices() };1538      }1539      case "CONFIRM_VOUCHED_DEVICE": {1540        const { deviceId } = msg.payload as { deviceId: string };1541        const pending = await getPendingVouchedDevice(deviceId);1542        if (!pending) return { ok: false, error: "not_pending" };1543        // Last gate before a vouched device becomes a sync peer. A queue entry1544        // can predate the revocation that names it, so revocation is re-checked1545        // here rather than trusted to have swept the queue.1546        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {1547          await removePendingVouchedDevice(deviceId);1548          return { ok: false, error: "device_revoked" };1549        }1550        await upsertPairedDeviceV3({1551          deviceId: pending.deviceId,1552          deviceName: pending.deviceName,1553          deviceType:1554            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1555          longTermPublicKeyHex: pending.longTermPublicKeyHex,1556          signingPublicKeyHex: pending.signingPublicKeyHex,1557          wsPort: pending.wsPort,1558          pairedAt: pending.pairedAt,1559          trustSource: "vouched",1560        });1561        await removePendingVouchedDevice(deviceId);1562        // Newly confirmed vouched device is now a sync target — kick a round1563        // so the mesh introduction pays off without a 10-minute wait.1564        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1565        return { ok: true };1566      }1567      case "REJECT_VOUCHED_DEVICE": {1568        const { deviceId } = msg.payload as { deviceId: string };1569        await removePendingVouchedDevice(deviceId);1570        return { ok: true };1571      }1572      case "ROTATE_SYNC_IDENTITY": {1573        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1574        const result = await vault.rotateSyncIdentity();1575        return result.ok ? { ok: true } : { ok: false, error: result.error };1576      }15771578      default:1579        return { ok: false, error: "unknown_message_type" };1580    }1581  } catch (err) {1582    return {1583      ok: false,1584      error: err instanceof Error ? err.message : "operation_failed",1585    };1586  }1587}15881589// Returns username use-counts from the vault, sorted by frequency. Each row1590// also carries the entry's email so the popup can suggest the email/username1591// pair the user has actually used together.1592function buildIdentitySuggestions(1593  entries: VaultEntry[],1594): Array<{ email: string; username: string; count: number }> {1595  const usernameCounts = new Map<string, number>();1596  const usernameEmail = new Map<string, string>();1597  for (const entry of entries) {1598    const username = entry.username ?? "";1599    const email = (entry as VaultEntry & { email?: string }).email ?? "";1600    if (!username && !email) continue;1601    const key = username || email;1602    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1603    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1604  }1605  return Array.from(usernameCounts.entries())1606    .sort((a, b) => b[1] - a[1])1607    .map(([username, count]) => ({1608      email: usernameEmail.get(username) ?? "",1609      username,1610      count,1611    }));1612}16131614/** Notify all content scripts that the vault just became available. */1615function broadcastToContentScripts(message: { type: string }): void {1616  if (!chrome.tabs?.query) return;1617  chrome.tabs.query({}, (tabs) => {1618    for (const tab of tabs) {1619      if (tab.id !== undefined) {1620        chrome.tabs.sendMessage(tab.id, message).catch(() => {1621          // Tab may not have a content script — silently ignore1622        });1623      }1624    }1625  });1626}16271628function shouldRefreshAutoLock(type: MessageType): boolean {1629  return (1630    type !== "HAS_VAULT" &&1631    type !== "IS_UNLOCKED" &&1632    type !== "GET_VAULT_STATUS" &&1633    type !== "LOCK" &&1634    type !== "UPDATE_SETTINGS" &&1635    type !== "GET_PENDING_PASSKEY" &&1636    type !== "GET_PASSKEY_PROVIDER_STATE" &&1637    type !== "DECLINE_CARD_SAVE" &&1638    type !== "IS_CARD_DECLINED"1639  );1640}16411642function isAllowedCanaryWebhookUrl(value: string): boolean {1643  try {1644    const url = new URL(value);1645    if (url.protocol !== "https:") return false;16461647    const hostname = url.hostname.toLowerCase();1648    if (1649      hostname === "localhost" ||1650      hostname.endsWith(".localhost") ||1651      isPrivateIpv4(hostname) ||1652      isPrivateIpv6(hostname)1653    ) {1654      return false;1655    }16561657    return true;1658  } catch {1659    return false;1660  }1661}16621663function isPrivateIpv4(hostname: string): boolean {1664  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1665    return true;1666  }16671668  const octets = hostname.split(".").map((part) => Number(part));1669  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1670    return false;1671  }16721673  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1674}16751676function isPrivateIpv6(hostname: string): boolean {1677  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1678  // IPv4-mapped IPv6 literals embed a plain IPv4 address that the prefix1679  // list below can never match (WHATWG URL serializes [::ffff:192.168.0.1]1680  // as ::ffff:c0a8:1). Unwrap and test the embedded IPv4; unparseable mapped1681  // tails fail closed. (Codex Security 2026-08-04 LOW,1682  // ssrf.webhook-url-private-ip-filter.) DNS rebinding is out of scope for a1683  // one-shot host check.1684  const mapped = /^::ffff:(.+)$/.exec(normalized);1685  if (mapped) {1686    const tail = mapped[1] ?? "";1687    if (tail.includes(".")) return isPrivateIpv4(tail);1688    const parts = tail.split(":");1689    const [hi, lo] = parts;1690    if (1691      parts.length !== 2 ||1692      !hi ||1693      !lo ||1694      !/^[0-9a-f]{1,4}$/.test(hi) ||1695      !/^[0-9a-f]{1,4}$/.test(lo)1696    ) {1697      return true;1698    }1699    const octets = [1700      (Number.parseInt(hi, 16) >>> 8) & 0xff,1701      Number.parseInt(hi, 16) & 0xff,1702      (Number.parseInt(lo, 16) >>> 8) & 0xff,1703      Number.parseInt(lo, 16) & 0xff,1704    ];1705    return isPrivateIpv4(octets.join("."));1706  }1707  return (1708    normalized === "::1" ||1709    normalized.startsWith("fc") ||1710    normalized.startsWith("fd") ||1711    normalized.startsWith("fe80:")1712  );1713}