messages.ts

71.2 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard, getEffectiveClearSeconds } from "./clipboard";13import { getPendingSyncAlerts, clearPendingSyncAlerts } from "./sync-alerts";14import { extractDomain } from "../shared/domain";15import {16  getPendingVouchedDevice,17  listPendingVouchedDevices,18  removePendingVouchedDevice,19} from "./pending-vouched-devices";20import { isRecoveryConfirmPending } from "./recovery-pending";21import { setupAutoLock, touchAutoLock } from "./alarms";22import { runSelfTest } from "./self-test";23import * as vault from "./vault";24import {25  handleEstimateCodexPages,26  handleGetCodexVaultData,27  handleRestoreFromCodex,28} from "./codex-handlers";29import type { CodexRestorePayload } from "../shared/codex-types";30import {31  activateLicense,32  deactivateLicense,33  getLicenseInfo,34  getLicenseKey,35  isProUser,36  markCelebrationPlayed,37  shouldPlayCelebration,38} from "./license";39import {40  completeFirefoxPasskeyCreate,41  getPasskeyProviderState,42  getPendingPasskeyRequest,43  handleFirefoxPasskeyCreate,44  handleFirefoxPasskeyGet,45  handlePasskeyHasCredentials,46  initiateFirefoxPasskeyCreate,47  isPasskeyOfferDeclined,48  onVaultUnlocked,49  recordPasskeyOfferDecline,50  resolvePendingPasskeyRequest,51  setPasskeyProviderEnabled,52} from "./passkey";53import { buildAdvancedHealthReport } from "./health";54import { storageClear } from "../shared/storage";55import { findInvalidWords } from "../shared/recovery-words";56import type {57  Message,58  MessageResponse,59  MessageType,60  ProFeature,61  VaultEntry,62} from "../shared/types";63import { isPasskeyOnly } from "../shared/types";64import { generateTOTP } from "../crypto/totp";65import { isValidRpId } from "../shared/passkey-utils";66import { predictBatch as mlPredictBatch } from "./ml";67import type { MLFieldFeatures } from "../shared/ml";68import {69  buildLocalIdentity,70  getOrCreateDeviceId,71  setDeviceName as setDeviceNameV3,72} from "./device-identity";73import {74  isDeviceRevoked,75  listPairedDevices as listPairedDevicesV3,76  renamePairedDevice as renamePairedDeviceV3,77  revokeDeviceById as revokeDeviceByIdV3,78  upsertPairedDevice as upsertPairedDeviceV3,79} from "./paired-devices";80// Sync and pairing are imported statically, never with `await import()`.81// `import()` throws `TypeError: import() is disallowed on82// ServiceWorkerGlobalScope` at runtime in MV3, and Vite's preload helper83// reports the failure through `window.dispatchEvent`, which does not exist in84// a worker either — so the real reason was replaced by "window is not defined"85// and the pairing UI just stopped. scripts/check-sw-static-imports.mjs fails86// the build if a runtime import() reappears anywhere in the worker's graph.87import {88  cancelRelayAdoptionSource,89  isRelayAdoptionSourceInFlight,90  resolveSourceSasConfirmation,91  startRelayAdoptionReceiver,92  startRelayAdoptionSource,93} from "./relay-adoption-bg";94import {95  getSyncSettings,96  setRelayUrl,97  setSyncMode,98  type SyncMode,99} from "./sync-settings";100import {101  getSyncState,102  triggerSyncIfReachable,103} from "./sync-trigger";104105// Compile-time E2E flag, folded to a literal by Vite's `define` (false in106// every production build — verified in the bundled output). Mirrors the107// create-path bypass in passkey.ts so the Playwright passkey smoke can enable108// the provider without a real Pro licence; the gate is fully intact for users.109declare const __PEACH_E2E_PASSKEYS__: boolean;110const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true;111112function unhexBytes(hex: string): Uint8Array {113  if (hex.length % 2 !== 0) throw new Error("invalid hex");114  const out = new Uint8Array(hex.length / 2);115  for (let i = 0; i < out.length; i++) {116    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);117  }118  return out;119}120121/**122 * The single Pro gate. Every gated handler calls this first; the broadcast123 * lets the popup react (navigate to the License section, highlight the124 * relevant feature). Background never touches the popup view directly —125 * the popup owns navigation. See Projects.md "Pro gate rule".126 */127async function requirePro(128  feature: ProFeature,129  trigger: "user" | "background" = "user"130): Promise<{ allowed: boolean }> {131  if (PASSKEY_E2E_PRO_BYPASS && feature === "passkeys") return { allowed: true };132  if (await isProUser()) return { allowed: true };133134  if (trigger === "user") {135    // User deliberately triggered this feature — redirect the popup immediately.136    chrome.runtime137      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })138      .catch(() => {139        // Popup may be closed — the gate signal is best-effort.140      });141  } else {142    // Background trigger (e.g. passive sync initiation) — no popup is open.143    // Queue a notice so the next popup open shows a soft banner instead of144    // silently failing.145    if (chrome.storage.session) {146      chrome.storage.session147        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })148        .catch(() => {});149    }150  }151152  return { allowed: false };153}154155// ---------------------------------------------------------------------------156// PCH-01-018: operations that irreversibly destroy or replace vault contents,157// handlers that store passkey material, and handlers that return sensitive158// credential material (e.g. the Pro license key). These are gated to trusted159// extension-page senders in handleMessage; the confirmation UX otherwise160// lives only in the popup. Keep this in sync when adding new destructive or161// sensitive handlers. (Codex Security 2026-08-04: GET_ADOPTION_MATERIAL and162// COMPLETE_PAIRING were gated here, then deleted outright — they had no163// legitimate senders; adoption runs in-background via relay-adoption-bg.ts.164// Audit 2026-08-20 #4: GET_LOCAL_IDENTITY gated here — it returns the Pro165// license key, which a compromised content script could exfiltrate.)166const PRIVILEGED_MESSAGE_TYPES: ReadonlySet<string> = new Set([167  "DESTROY_VAULT",168  "CLEAR_VAULT_ENTRIES",169  "RESTORE_VAULT_SNAPSHOT",170  "RESTORE_FROM_CODEX",171  "COMPLETE_FIREFOX_PASSKEY_CREATE",172  "UNLOCK_WITH_PIN",173  "SETUP_PIN",174  "DISABLE_PIN",175  "GET_LOCAL_IDENTITY",176]);177178// LV-3: minimum interval between non-test canary pings per webhook+entry.179const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour180181const PRIVATE_IPV4_RANGES = [182  { prefix: "10." },183  { prefix: "127." },184  { prefix: "169.254." },185  { prefix: "192.168." },186];187188export function setupMessageHandler(): void {189  chrome.runtime.onMessage.addListener(190    (msg: unknown, sender, sendResponse) => {191      if (!isMessage(msg)) {192        sendResponse({ ok: false, error: "invalid_message" });193        return true;194      }195      handleMessage(msg, sender)196        .then(sendResponse)197        .catch((err) =>198          sendResponse({199            ok: false,200            error: err instanceof Error ? err.message : String(err),201          })202        );203      return true;204    }205  );206}207208function isMessage(m: unknown): m is Message {209  return typeof m === "object" && m !== null && "type" in m;210}211212/**213 * The browser-attested origin of the page that originated this message. A web214 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),215 * so every page-driven message arrives via the content-script relay and the216 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a217 * value the page cannot forge. This is the ONLY trustworthy origin for passkey218 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.219 */220function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {221  if (sender.origin) return sender.origin;222  if (sender.url) {223    try { return new URL(sender.url).origin; } catch { return undefined; }224  }225  return undefined;226}227228// Resolves once restoreFromSession() has run, so handlers see the correct229// post-restore unlock state. entry.ts registers this BEFORE the message230// handler so the onMessage listener is added synchronously at SW startup231// (MV3 requirement) while unlock-dependent handlers still wait for restore.232let restoreReady: Promise<void> = Promise.resolve();233234/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */235export function setRestoreReady(p: Promise<unknown>): void {236  restoreReady = p.then(() => undefined, () => undefined);237}238239export async function handleMessage(240  msg: Message,241  sender: Partial<chrome.runtime.MessageSender> = {}242): Promise<MessageResponse> {243  try {244    // Wait for session-restore to finish before reading any unlock/vault state.245    // On a cold SW start the popup's first message arrives while restore is246    // still in flight; without this gate IS_UNLOCKED would report locked (a247    // spurious lock screen) and the storage reads could race. The onMessage248    // listener itself is registered synchronously (entry.ts) so this gate, not249    // listener registration, is what absorbs the cold-start window.250    await restoreReady;251    // Validate sender — only allow messages from our extension pages/scripts.252    // `sender.id` is undefined for messages originating from extension UI253    // (popup/options), which is legitimate; reject only when it is defined254    // and does not match our extension id.255    if (256      sender.id !== undefined &&257      sender.id !== chrome.runtime.id258    ) {259      return { ok: false, error: "invalid_sender" };260    }261262    // PCH-01-018: destructive and sensitive operations must originate from a263    // trusted extension page (popup/options), never from a content script. The264    // sender.id check above only proves the message came from *our* extension —265    // a content script injected into an attacker page passes it. A single266    // XSS-class bug in the injected UI would otherwise escalate to vault267    // destruction, root-key exfiltration, or attacker device registration.268    // Extension pages carry an extension-origin sender.url; content scripts269    // carry a page URL.270    if (PRIVILEGED_MESSAGE_TYPES.has(msg.type)) {271      const extensionOrigin = chrome.runtime.getURL("");272      if (!sender.url?.startsWith(extensionOrigin)) {273        return { ok: false, error: "invalid_sender" };274      }275    }276277    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {278      touchAutoLock();279    }280281    switch (msg.type) {282      case "CREATE_VAULT": {283        const { password } = msg.payload as { password: string };284        // Refuse to create a vault under an empty master password — the derived285        // key would be publicly known and the at-rest AES-GCM protection void286        // (audit HIGH; the CSV-import path previously passed ""). Length/strength287        // policy lives in the onboarding UI; this is the non-negotiable floor.288        if (typeof password !== "string" || password.length === 0) {289          return { ok: false, error: "invalid_payload" };290        }291        await vault.createVault(password);292        await setupAutoLock();293        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });294        onVaultUnlocked();295        return { ok: true };296      }297      case "CREATE_VAULT_FROM_ROOT_KEY": {298        const { password, rootKeyHex } = (msg.payload ?? {}) as {299          password?: unknown;300          rootKeyHex?: unknown;301        };302        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {303          return { ok: false, error: "invalid_payload" };304        }305306        try {307          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);308          await setupAutoLock();309          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });310          onVaultUnlocked();311          return { ok: true, vaultId };312        } catch (err) {313          return { ok: false, error: err instanceof Error ? err.message : String(err) };314        }315      }316      case "UNLOCK": {317        const { password } = msg.payload as { password: string };318        const ok = await vault.unlock(password);319        if (ok) {320          // KAT: verify the WebCrypto stack is healthy before the user relies on it.321          // Runs after unlock so latency is hidden behind the vault-load time.322          const kat = await runSelfTest();323          if (!kat.ok) {324            console.error("[Peach] Crypto self-test FAILED:", kat.error);325            await vault.lock();326            return { ok: false, error: "self_test_failed" };327          }328          await vault.updateSettings({ pinPreferred: false });329          await setupAutoLock();330          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });331          onVaultUnlocked();332          return { ok: true };333        }334        // Distinguish corruption from wrong password so the popup can offer335        // a history-restore path instead of falsely accusing the user of336        // mistyping (M7/COR-007).337        const failure = vault.consumeLastUnlockFailureReason();338        if (failure) {339          return {340            ok: false,341            error: "vault_corrupted",342            canRestoreFromHistory: true,343          } as MessageResponse;344        }345        return { ok: false };346      }347      case "UNLOCK_WITH_PIN": {348        const { pin } = (msg.payload ?? {}) as { pin?: unknown };349        if (typeof pin !== "string") return { ok: false, error: "invalid_payload" };350        const ok = await vault.unlockWithPin(pin);351        if (!ok) return { ok: false };352        const kat = await runSelfTest();353        if (!kat.ok) {354          await vault.lock();355          return { ok: false, error: "self_test_failed" };356        }357        await vault.updateSettings({ pinPreferred: true });358        await setupAutoLock();359        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });360        onVaultUnlocked();361        return { ok: true };362      }363      case "VALIDATE_RECOVERY_WORDS": {364        const { words } = msg.payload as { words: string[] };365        const invalid = findInvalidWords(words);366        return { ok: true, data: { valid: invalid.length === 0, invalid } };367      }368      case "GET_RECOVERY_WORDS": {369        // Must be unlocked and have recovery set up (vault must be v2.12+).370        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };371        // LV-4: the recovery words re-derive the ROOT KEY — the highest-372        // value secret in the vault. A session unlock (which may be hours373        // old on a shared machine) is not enough; require a fresh password374        // proof, matching the 1Password/Bitwarden pattern for revealing375        // escrow material. EXEMPTION: the create-vault / rotation confirmation376        // window (peach_recovery_pending) shows the words immediately after377        // the user authenticated, and that confirmation UI has no password to378        // resend — skip the re-auth there only.379        if (!(await isRecoveryConfirmPending())) {380          const { password } = (msg.payload ?? {}) as { password?: string };381          if (typeof password !== "string" || !password) {382            return { ok: false, error: "password_required" };383          }384          if (!(await vault.verifyMainPassword(password))) {385            return { ok: false, error: "wrong_password" };386          }387        }388        try {389          const words = await vault.getRecoveryWords();390          return { ok: true, data: words };391        } catch {392          // pre-v2.12 vault that hasn't migrated393          return { ok: false, error: "recovery_not_setup" };394        }395      }396      case "RECOVER_WITH_WORDS": {397        // User has lost their password but has their 12 recovery words.398        // We: (1) validate the words, (2) re-encrypt vault with new password.399        const { words, newPassword } = msg.payload as {400          words: string[];401          newPassword: string;402        };403        const stored = await vault.loadSlotA();404        if (!stored) return { ok: false, error: "no_vault" };405        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {406          return { ok: false, error: "recovery_not_setup" };407        }408        // Unwrap the root key from the recovery escrow.409        try {410          await vault.unwrapRootKeyForRecovery(411            stored.recovery_wrapped_root_key,412            stored.recovery_nonce ?? "",413            stored.recovery_tag ?? "",414            stored.recovery_salt,415            words416          );417        } catch {418          return { ok: false, error: "invalid_recovery_words" };419        }420        // Re-key: derive fresh salt + key from new password.421        const newSalt = vault.generateSalt();422        const newKey = await vault.deriveKey(newPassword, newSalt);423        // Re-wrap root key under the new password's derived key so the same424        // recovery words continue to work after the password change.425        await vault.rewrapRootKeyForPassword(newKey, newSalt);426        // Re-encrypt vault entries with the new key.427        await vault.changePasswordWithNewKey(newSalt, newKey);428        await setupAutoLock();429        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });430        return { ok: true };431      }432      case "LOCK":433        vault.lock();434        return { ok: true };435      case "IS_UNLOCKED":436        return { ok: true, data: vault.isUnlocked() };437      case "GET_VAULT_STATUS":438        return { ok: true, unlocked: vault.isUnlocked() };439      case "HAS_VAULT":440        return { ok: true, data: await vault.hasVault() };441      case "GET_ENTRIES":442        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };443        return { ok: true, data: vault.getEntries() };444      case "ADD_ENTRY": {445        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };446        const payload = msg.payload;447        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {448          return { ok: false, error: "invalid_payload" };449        }450        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);451        return { ok: true, data: entry };452      }453      case "BATCH_ADD_ENTRIES": {454        const payload = msg.payload as { entries?: unknown } | null | undefined;455        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {456          return { ok: false, error: "invalid_payload" };457        }458        if (!Array.isArray(payload.entries)) {459          return { ok: false, error: "invalid_payload" };460        }461        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);462        return { ok: true, data: added };463      }464      case "RESTORE_ENTRIES": {465        const payload = msg.payload as466          | { entries?: unknown; mode?: unknown; settings?: unknown }467          | null468          | undefined;469        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {470          return { ok: false, error: "invalid_payload" };471        }472        if (!Array.isArray(payload.entries)) {473          return { ok: false, error: "invalid_payload" };474        }475        if (payload.mode !== "replace" && payload.mode !== "merge") {476          return { ok: false, error: "invalid_payload" };477        }478        const summary = await vault.restoreEntries(479          payload.entries as Parameters<typeof vault.restoreEntries>[0],480          payload.mode481        );482        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {483          await vault.updateSettings(payload.settings as vault.VaultSettings);484        }485        return { ok: true, data: summary };486      }487      case "CLEAR_VAULT_ENTRIES": {488        await vault.clearVaultEntries("REPLACE_ALL");489        return { ok: true };490      }491      case "GET_VAULT_HISTORY": {492        const snapshots = await vault.getVaultHistory();493        return { ok: true, data: snapshots };494      }495      case "RESTORE_VAULT_SNAPSHOT": {496        const { snapshotId } = msg.payload as { snapshotId: string };497        const result = await vault.restoreVaultSnapshot(snapshotId);498        if (!result.ok) return { ok: false, error: result.error };499        broadcastToContentScripts({ type: "VAULT_LOCKED" });500        return { ok: true };501      }502      case "COUNT_DUPLICATES": {503        return { ok: true, data: vault.countDuplicates() };504      }505      case "DEDUPLICATE_ENTRIES": {506        const removed = await vault.deduplicateEntries();507        return { ok: true, data: removed };508      }509      case "UPDATE_ENTRY": {510        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;511        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {512          return { ok: false, error: "invalid_payload" };513        }514        const { id, patch } = payload;515        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {516          return { ok: false, error: "invalid_payload" };517        }518        // Single enforcement point for the Canary Entries Pro gate. Only519        // gates the transition into a canary entry — clearing/disabling a520        // canary (`canary: undefined`) is always allowed, so existing521        // canary entries remain manageable.522        const incomingCanary = (patch as { canary?: unknown }).canary;523        if (incomingCanary && typeof incomingCanary === "object") {524          const existing = vault.getEntryById(id);525          if (!existing?.canary) {526            const gate = await requirePro("canary_entry");527            if (!gate.allowed) return { ok: false, error: "pro_required" };528          }529        }530        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);531        return { ok: true };532      }533      case "ADD_ADDITIONAL_URL": {534        const { id, url } = msg.payload as { id: string; url: string };535        const trimmed = typeof url === "string" ? url.trim() : "";536        if (!trimmed) return { ok: false, error: "url_required" };537        const existing = vault.getEntryById(id);538        if (!existing) return { ok: false, error: "entry_not_found" };539        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };540        const merged = [...(existing.additionalUrls ?? []), trimmed];541        await vault.updateEntry(id, { additionalUrls: merged });542        return { ok: true };543      }544      case "DELETE_ENTRY": {545        const { id } = msg.payload as { id: string };546        await vault.deleteEntry(id);547        return { ok: true };548      }549      case "GET_DELETED_ENTRIES":550        return { ok: true, data: vault.getDeletedEntries() };551      case "RESTORE_ENTRY": {552        const { id } = msg.payload as { id: string };553        await vault.restoreEntry(id);554        return { ok: true };555      }556      case "PURGE_ENTRY": {557        const { id } = msg.payload as { id: string };558        await vault.purgeEntry(id);559        return { ok: true };560      }561      case "PURGE_EXPIRED_TRASH": {562        const { retentionMs } = msg.payload as { retentionMs: number };563        const purged = await vault.purgeExpiredTrash(retentionMs);564        return { ok: true, data: purged };565      }566      case "SAVE_NOTE": {567        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };568        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };569        const now = Date.now();570        if (id) {571          const existing = vault.getEntryById(id);572          if (!existing) return { ok: false, error: "not_found" };573          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });574          return { ok: true, data: vault.getEntryById(id) };575        } else {576          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt577          // (EntryDraft omits both), so passing them was the only reason the578          // `as any` cast existed. Dropping them makes the call type-check.579          const entry = await vault.addEntry({580            type: "note",581            title: title || "Untitled",582            notes: body,583          });584          return { ok: true, data: entry };585        }586      }587      case "DELETE_NOTE": {588        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };589        const { id } = msg.payload as { id: string };590        await vault.deleteEntry(id);591        return { ok: true };592      }593      case "GET_NOTES": {594        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };595        const notes = vault.getEntries().filter(596          (e) => e.type === "note" && !e.deletedAt597        );598        return { ok: true, data: notes } as MessageResponse;599      }600      case "SEARCH_VAULT": {601        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };602        // AUD-002: shape-validate the payload before calling string methods.603        // A raw cast lets a malformed message crash the handler with TypeError.604        const { query } = (msg.payload ?? {}) as { query?: unknown };605        if (typeof query !== "string") {606          return { ok: false, error: "invalid_payload" };607        }608        const q = query.toLowerCase();609        const searchResults = vault.getEntries().filter(610          (e) =>611            !e.deletedAt &&612            (e.title.toLowerCase().includes(q) ||613              e.notes?.toLowerCase().includes(q) ||614              e.username?.toLowerCase().includes(q))615        );616        return { ok: true, data: searchResults } as MessageResponse;617      }618      case "AUTOFILL_QUERY": {619        if (!vault.isUnlocked()) {620          return { ok: false, error: "vault_locked" };621        }622        let { includeAll } = msg.payload as { includeAll?: boolean };623        const { domain, kind, userGesture } = msg.payload as {624          domain: string;625          kind?: "login" | "card" | "totp";626          userGesture?: boolean;627        };628        // MV-2: the vault-wide inventory (every title/username/email/url)629        // may only leave the background on an explicit user gesture — the630        // user opening the search affordance — never on passive form focus.631        // userGesture is self-declared by our own content script; the value632        // of this gate is that PASSIVE code paths (which never set it)633        // cannot ship the inventory, shrinking what a compromised page that634        // merely triggers focus events can observe.635        if (includeAll && userGesture !== true) {636          includeAll = false;637        }638        // kind="card": return saved cards as compact summaries for the639        // inline card silver platter. Cards are not domain-scoped — every640        // saved card is a candidate on every checkout page — so domain is641        // ignored when kind === "card".642        if (kind === "card") {643          const cards = vault.getEntries().filter((e) => e.type === "card");644          return {645            ok: true,646            data: cards.map((e) => ({647              id: e.id,648              title: e.cardNickname || e.title,649              cardholderName: e.cardholderName,650              last4: e.last4,651              expMonth: e.expMonth,652              expYear: e.expYear,653              network: e.network,654            })),655          };656        }657        if (kind === "totp") {658          const matches = (659            includeAll660              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")661              : vault.queryDomain(domain)662          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));663          return {664            ok: true,665            data: matches.map((e) => ({666              id: e.id,667              title: e.title,668              username: e.username,669              email: e.email,670              url: e.url,671              hasTotp: true,672            })),673          };674        }675        // The inline selector fills username+password into a form. Passkey-676        // only entries have no password to fill; sign-in for those goes677        // through the WebAuthn path instead. Filter them out everywhere so678        // the user doesn't see four "GitHub" rows that mostly do nothing.679        // Notes and cards never belonged here either.680        const matches = (681          includeAll682            ? vault683                .getEntries()684                .filter((entry) => entry.type !== "note" && entry.type !== "card")685            : vault.queryDomain(domain)686        ).filter((entry) => !isPasskeyOnly(entry));687        return {688          ok: true,689          data: matches.map((e) =>690            includeAll691              ? {692                  id: e.id,693                  title: e.title,694                  // username/email/url shipped so the inline popup's search695                  // affordance can match on them, not just titles. No secrets696                  // cross the boundary — same shape as the domain-matched697                  // response below minus hasTotp (which the search list698                  // doesn't surface).699                  username: e.username,700                  email: e.email,701                  url: e.url,702                  hasPasskey: e.passkey !== undefined,703                }704              : {705                  id: e.id,706                  title: e.title,707                  username: e.username,708                  email: e.email,709                  url: e.url,710                  hasTotp: Boolean(e.totp),711                  hasPasskey: e.passkey !== undefined,712                }713          ),714        };715      }716      case "GET_ENTRY_FOR_FILL": {717        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };718        const { id, explicitSummon } = msg.payload as {719          id: string;720          explicitSummon?: boolean;721        };722        const entry = vault.getEntryById(id);723        if (!entry) return { ok: false, error: "entry_not_found" };724        // Passkey-only entries (passkey credential, no password) cannot be725        // filled into a form — sign-in goes through the WebAuthn path. A726        // login that ALSO has a passkey is still fillable for its password.727        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };728729        // MV-1: re-validate the entry against the requesting tab's origin.730        // sender.tab.url is browser-attested — a page cannot forge it. When731        // the request does not come from a tab at all (popup surfaces use732        // GET_ENTRY_FOR_EDIT, not this), refuse.733        if (sender.tab !== undefined || sender.url !== undefined) {734          let senderDomain: string | null = null;735          try {736            const rawUrl = sender.tab?.url ?? sender.url ?? "";737            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;738          } catch {739            senderDomain = null;740          }741          if (!senderDomain) return { ok: false, error: "origin_unverified" };742743          const entryDomains = new Set<string>();744          const primary = extractDomain(entry.url ?? "");745          if (primary) entryDomains.add(primary);746          for (const extra of entry.additionalUrls ?? []) {747            const d = extractDomain(extra);748            if (d) entryDomains.add(d);749          }750751          // explicitSummon=true means the user actively picked this entry752          // from the cross-domain search affordance — an intentional753          // off-domain fill. Passive fill paths must stay domain-bound.754          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {755            // Domain mismatch — refuse silently (no oracle about which ids exist).756            return { ok: false, error: "entry_not_found" };757          }758        }759        // Strip the passkey credential AND the raw base32 TOTP seed from the760        // response. Content scripts never need either: the private key is the761        // authenticator's, and handing over the TOTP seed would let a762        // compromised content script mint valid codes indefinitely (SEV-3-C).763        // Generate the *current* 6-digit code here in the background and send764        // only that, plus the seconds left so the UI can render a countdown.765        // Also drop passwordHistory: filling needs only the *current* password.766        // Handing every past password to a content script during passive767        // autofill on an arbitrary page would widen the blast radius of a768        // compromised page far beyond the one credential being filled.769        const {770          passkey: _strippedPasskey,771          totp: seed,772          totpAlgorithm,773          totpDigits,774          totpPeriod,775          passwordHistory: _ph,776          ...safeEntry777        } = entry;778        let totpCode: string | undefined;779        let totpRemaining: number | undefined;780        if (seed) {781          try {782            // PCH-01-019: honour stored algorithm/digits/period (defaults apply783            // when these are undefined, i.e. legacy bare-seed entries).784            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);785            totpCode = generated.code;786            totpRemaining = generated.remaining;787          } catch {788            totpCode = undefined;789          }790        }791        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };792      }793      // Trusted full-entry fetch for Peach's own inline-popup surfaces that794      // genuinely need the raw TOTP seed: the edit form (which re-saves the795      // seed and would otherwise wipe it) and nothing else. Unlike796      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside797      // the inline popup, never during passive autofill on an arbitrary page.798      // The passkey credential is still stripped — the edit form never touches it.799      case "GET_ENTRY_FOR_EDIT": {800        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };801        const { id, explicitSummon } = msg.payload as {802          id: string;803          explicitSummon?: boolean;804        };805        const entry = vault.getEntryById(id);806        if (!entry) return { ok: false, error: "entry_not_found" };807808        // PCH-01-006: re-validate the browser-attested sender origin, mirroring809        // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and810        // full password history — at least as sensitive as the fill response — so811        // the boundary must be enforced here, not only by UI reachability. Today812        // the sole caller is the popup (no sender.tab, so this is a structural813        // no-op), but a future tab-context caller or an id leak would otherwise814        // inherit a full-credential oracle. Unlike the fill path we SKIP (not815        // refuse) when no sender domain resolves, to keep the popup caller working.816        if (sender.tab !== undefined || sender.url !== undefined) {817          let senderDomain: string | null = null;818          try {819            const rawUrl = sender.tab?.url ?? sender.url ?? "";820            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;821          } catch {822            senderDomain = null;823          }824          if (senderDomain) {825            const entryDomains = new Set<string>();826            const primary = extractDomain(entry.url ?? "");827            if (primary) entryDomains.add(primary);828            for (const extra of entry.additionalUrls ?? []) {829              const d = extractDomain(extra);830              if (d) entryDomains.add(d);831            }832            if (explicitSummon !== true && !entryDomains.has(senderDomain)) {833              return { ok: false, error: "entry_not_found" }; // no id oracle834            }835          }836        }837838        const { passkey: _passkey, ...safeEntry } = entry;839        return { ok: true, data: safeEntry };840      }841      case "COPY": {842        // AUD-002: shape-validate the payload before passing to the clipboard843        // helper. A raw cast lets a malformed message reach the clipboard API844        // with a non-string and throw.845        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {846          text?: unknown;847          label?: unknown;848          alreadyWritten?: unknown;849        };850        if (typeof text !== "string" || typeof label !== "string") {851          return { ok: false, error: "invalid_payload" };852        }853        await copyToClipboard(text, label, Boolean(alreadyWritten));854        return { ok: true, clearSeconds: getEffectiveClearSeconds() };855      }856      case "CHECK_ALL_BREACHES": {857        const allEntries = vault.getEntries();858        const results: Record<string, number> = {};859        for (const entry of allEntries) {860          if (entry.type === "note") continue;861          if (!entry.password) continue;862          results[entry.id] = await vault.checkBreach(entry.password);863          // Small delay — be a good citizen to the HIBP API864          await new Promise((r) => setTimeout(r, 200));865        }866        // Persist any non-zero counts back to entries867        for (const [id, count] of Object.entries(results)) {868          const entry = vault.getEntryById(id);869          if (entry && (entry.breach ?? 0) !== count) {870            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });871          }872        }873        return { ok: true, data: results };874      }875      case "GET_SETTINGS":876        return { ok: true, data: await vault.ensureSettingsLoaded() };877      case "UPDATE_SETTINGS": {878        const patch = msg.payload;879        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {880          return { ok: false, error: "invalid_payload" };881        }882        await vault.updateSettings(patch as vault.VaultSettings);883        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {884          await setupAutoLock();885          if (vault.isUnlocked()) touchAutoLock();886        }887        return { ok: true };888      }889      case "SETUP_PIN": {890        const { currentPassword, pin } = (msg.payload ?? {}) as {891          currentPassword?: unknown;892          pin?: unknown;893        };894        if (typeof currentPassword !== "string" || typeof pin !== "string") {895          return { ok: false, error: "invalid_payload" };896        }897        return (await vault.setupPinUnlock(currentPassword, pin))898          ? { ok: true }899          : { ok: false, error: "incorrect_current_password" };900      }901      case "DISABLE_PIN": {902        const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown };903        if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" };904        return (await vault.disablePinUnlock(currentPassword))905          ? { ok: true }906          : { ok: false, error: "incorrect_current_password" };907      }908      case "GET_PENDING_PASSKEY":909        return { ok: true, data: await getPendingPasskeyRequest() };910      case "APPROVE_PASSKEY": {911        const { requestId } = msg.payload as { requestId: number };912        await resolvePendingPasskeyRequest(requestId, true);913        return { ok: true };914      }915      case "DENY_PASSKEY": {916        const { requestId } = msg.payload as { requestId: number };917        await resolvePendingPasskeyRequest(requestId, false);918        return { ok: true };919      }920      case "GET_PASSKEY_PROVIDER_STATE":921        return { ok: true, data: await getPasskeyProviderState() };922      case "SET_PASSKEY_PROVIDER_ENABLED": {923        const { enabled } = msg.payload as { enabled: boolean };924        // Disabling is always free; gating fires only when a free user is925        // trying to turn passkey interception on.926        if (enabled) {927          const gate = await requirePro("passkeys");928          if (!gate.allowed) return { ok: false, error: "pro_required" };929        }930        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };931      }932      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS933      // endpoint. Intentional product behavior — users configure their own934      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private935      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-936      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to937      // users that the entry title leaves the device when the canary fires.938      case "FIRE_CANARY_PING": {939        // Canary alert fires unconditionally for any entry with canary: true.940        // The Pro gate only governs creation/flagging of canary entries; once941        // an entry is flagged, the alert path is a security property and must942        // never be license-gated.943        const { webhookUrl, entryTitle, trigger } = msg.payload as {944          webhookUrl: string;945          entryTitle: string;946          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";947        };948        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {949          return { ok: false, error: "invalid_webhook_url" };950        }951        // LV-3: debounce non-test pings per (webhook, entry) so a page that952        // strobes focus/fill events can't turn the canary into a request953        // firehose at the user's endpoint. Test pings are exempt — they are954        // explicit user clicks in the settings UI and are awaited for955        // feedback. The FIRST ping in a window always goes out, so the956        // dead-man's-switch property (canary fires on access) is preserved;957        // only repeats within the window are coalesced.958        if (trigger !== "test") {959          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;960          const stored = await chrome.storage.local.get(rlKey);961          const last = (stored as Record<string, unknown>)[rlKey];962          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {963            return { ok: true, data: { rateLimited: true } };964          }965          await chrome.storage.local.set({ [rlKey]: Date.now() });966        }967        const body = JSON.stringify({968          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",969          entry: entryTitle,970          trigger,971          timestamp: new Date().toISOString(),972          source: "peach-extension",973        });974        if (trigger === "test") {975          // Permitted outbound fetch: user-configured canary alert endpoint976          // (validated by isAllowedCanaryWebhookUrl above). This is the977          // only non-HIBP outbound call in the extension — see978          // Projects.md §3.7. Test pings are awaited so the UI can show979          // success/failure.980          try {981            const res = await fetch(webhookUrl, {982              method: "POST",983              headers: { "Content-Type": "application/json" },984              body,985            });986            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };987          } catch (err) {988            return { ok: false, error: err instanceof Error ? err.message : "network_error" };989          }990        }991        // Non-test triggers are fire-and-forget992        fetch(webhookUrl, {993          method: "POST",994          headers: { "Content-Type": "application/json" },995          body,996        }).catch(() => {});997        return { ok: true };998      }999      case "ACTIVATE_LICENSE": {1000        const { key } = msg.payload as { key: string };1001        const licenseInfo = await activateLicense(key);1002        return { ok: true, data: licenseInfo };1003      }1004      case "GET_LICENSE": {1005        const licenseInfo = await getLicenseInfo();1006        return { ok: true, data: licenseInfo };1007      }1008      case "GET_LICENSE_KEY": {1009        const key = await getLicenseKey();1010        return { ok: true, data: key };1011      }1012      case "DEACTIVATE_LICENSE": {1013        await deactivateLicense();1014        return { ok: true };1015      }1016      case "SHOULD_PLAY_CELEBRATION": {1017        const should = await shouldPlayCelebration();1018        return { ok: true, data: should };1019      }1020      case "MARK_CELEBRATION_PLAYED": {1021        await markCelebrationPlayed();1022        return { ok: true };1023      }1024      case "GET_CODEX_VAULT_DATA": {1025        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1026        // popup navigates to the License section without further coordination.1027        const gate = await requirePro("codex");1028        if (!gate.allowed) return { ok: false, error: "pro_required" };1029        return await handleGetCodexVaultData();1030      }1031      case "ESTIMATE_CODEX_PAGES": {1032        const gate = await requirePro("codex");1033        if (!gate.allowed) return { ok: false, error: "pro_required" };1034        return await handleEstimateCodexPages();1035      }1036      case "RESTORE_FROM_CODEX": {1037        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1038        // be able to restore a vault that was printed by a Pro user.1039        // DO NOT add a Pro gate here.1040        const payload = msg.payload as CodexRestorePayload;1041        return await handleRestoreFromCodex(payload);1042      }1043      case "OPEN_PRO_GATE": {1044        // Content script requests: open popup and navigate to License section.1045        const { feature } = (msg.payload ?? {}) as { feature?: string };1046        if (chrome.storage.session) {1047          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1048        }1049        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1050        return { ok: true };1051      }1052      case "OPEN_POPUP": {1053        // Content script asks to open the trusted extension popup — used by the1054        // inline locked bubble so the master password is entered in the popup,1055        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1056        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1057        // toolbar icon. The badge already signals Peach needs attention.1058        //1059        // Set a session flag so the popup knows it was opened for inline unlock1060        // and should close itself once the vault is unlocked (returning the user1061        // to the inline autofill selector on the page).1062        if (chrome.storage.session) {1063          await chrome.storage.session.set({ peach_inline_unlock: true });1064        }1065        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1066        return { ok: true };1067      }1068      case "OPEN_DETACHED_POPUP": {1069        // A window created by the action popup and then orphaned with1070        // window.close() is cascaded shut by Chrome, so the file-picker1071        // flows (OS dialogs that dismiss the popup on focus loss) ask the SW1072        // to open the standalone window instead — the SW has no window to be1073        // associated with. The query string is allowlisted so this can never1074        // open an arbitrary URL.1075        const { route } = (msg.payload ?? {}) as { route?: string };1076        const search = route === "peachscript"1077          ? "?restore=peachscript"1078          : route === "csv"1079            ? "?restore=csv"1080            : route === "codex-pdf"1081              ? "?codex=pdf"1082              : null;1083        if (!search) return { ok: false, error: "bad_route" };1084        try {1085          const popupHtml =1086            chrome.runtime.getManifest().action?.default_popup ?? "src/popup/index.html";1087          await chrome.windows.create({1088            url: chrome.runtime.getURL(`${popupHtml}${search}`),1089            type: "popup",1090            width: 320,1091            height: 550,1092          });1093          return { ok: true, data: { detached: true } };1094        } catch {1095          return { ok: false };1096        }1097      }1098      case "GET_IDENTITIES": {1099        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1100        return { ok: true, data: vault.getIdentities() };1101      }1102      case "TOUCH_AUTO_LOCK": {1103        // touchAutoLock() is already called by shouldRefreshAutoLock above;1104        // this case just gives the popup a typed message to keep the session alive.1105        return { ok: true };1106      }1107      case "GET_ADVANCED_HEALTH_REPORT": {1108        const gate = await requirePro("advanced_health");1109        if (!gate.allowed) return { ok: false, error: "pro_required" };1110        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1111        const report = await buildAdvancedHealthReport(vault.getEntries());1112        return { ok: true, data: report };1113      }1114      case "IS_DURESS_ENABLED": {1115        const enabled = await vault.isDuressEnabled();1116        return { ok: true, data: enabled };1117      }1118      case "SETUP_DURESS": {1119        // Single enforcement point for the Duress Vault Pro gate. Free users1120        // who somehow reach this handler are rejected here; the popup also1121        // pre-checks isPro() to avoid showing the setup form to free users,1122        // but server-side is the actual security boundary.1123        const gate = await requirePro("duress_vault");1124        if (!gate.allowed) return { ok: false, error: "pro_required" };1125        // MV3 service workers restart after inactivity, losing the in-memory1126        // derived key. Detect this before calling setupDuress so the popup1127        // can show a meaningful prompt to re-lock and re-unlock.1128        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1129        const { duressPassword } = msg.payload as { duressPassword: string };1130        await vault.setupDuress(duressPassword);1131        return { ok: true };1132      }1133      case "DISABLE_DURESS": {1134        await vault.disableDuress();1135        return { ok: true };1136      }1137      case "VERIFY_MAIN_PASSWORD": {1138        const { password } = msg.payload as { password: string };1139        const ok = await vault.verifyMainPassword(password);1140        return { ok: true, data: ok };1141      }1142      case "CHANGE_PASSWORD": {1143        const { currentPassword, newPassword } = msg.payload as {1144          currentPassword: string;1145          newPassword: string;1146        };1147        const changed = await vault.changePassword(currentPassword, newPassword);1148        return changed1149          ? { ok: true }1150          : { ok: false, error: "incorrect_current_password" };1151      }1152      case "GET_SITE_PASSWORD_POLICY": {1153        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1154        if (!tab?.id) return { ok: true, data: null };1155        try {1156          const response = await chrome.tabs.sendMessage(tab.id, {1157            type: "GET_SITE_PASSWORD_POLICY",1158          });1159          return (response as MessageResponse) ?? { ok: true, data: null };1160        } catch {1161          return { ok: true, data: null };1162        }1163      }1164      case "RECORD_MANUAL_SUMMON": {1165        const { domain } = msg.payload as { domain: string };1166        const settings = vault.getSettings();1167        const existing = settings.manualSummonDomains?.[domain];1168        const now = Date.now();1169        await vault.updateSettings({1170          manualSummonDomains: {1171            ...settings.manualSummonDomains,1172            [domain]: {1173              firstSummonedAt: existing?.firstSummonedAt ?? now,1174              summonCount: (existing?.summonCount ?? 0) + 1,1175              lastSummonedAt: now,1176            },1177          },1178        });1179        return { ok: true };1180      }1181      case "DECLINE_CARD_SAVE": {1182        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1183        await vault.declineCardSaveOffer(last4, expMonth, expYear);1184        return { ok: true };1185      }1186      case "IS_CARD_DECLINED": {1187        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1188        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1189        return { ok: true, data: declined };1190      }1191      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1192        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1193          rpId?: string;1194          rpName?: string;1195          userName?: string;1196          userDisplayName?: string;1197        };1198        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1199        return await initiateFirefoxPasskeyCreate({1200          rpId,1201          rpName: rpName ?? rpId,1202          userName,1203          userDisplayName,1204        }, attestedSenderOrigin(sender));1205      }12061207      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1208        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1209        if (!payload) return { ok: false, error: "missing_payload" };1210        return await completeFirefoxPasskeyCreate(payload);1211      }12121213      case "PASSKEY_OFFER_DECLINE": {1214        const { domain } = (msg.payload ?? {}) as { domain?: string };1215        if (!domain) return { ok: false, error: "domain_required" };1216        await recordPasskeyOfferDecline(domain);1217        return { ok: true };1218      }12191220      case "GET_PASSKEY_OFFER_DECLINED": {1221        const { domain } = (msg.payload ?? {}) as { domain?: string };1222        if (!domain) return { ok: false, error: "domain_required" };1223        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1224      }12251226      case "PASSKEY_HAS_CREDENTIALS": {1227        const payload = msg.payload as {1228          rpId?: string;1229          allowCredentials?: Array<{ id: string; type?: string }>;1230        } | undefined;1231        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1232        return await handlePasskeyHasCredentials({1233          rpId: payload.rpId,1234          allowCredentials: payload.allowCredentials ?? [],1235        }, attestedSenderOrigin(sender));1236      }12371238      case "PASSKEY_CREATE": {1239        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1240        if (!payload?.rpId || !payload?.userName) {1241          return { ok: false, error: "rpid_and_username_required" };1242        }1243        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1244      }12451246      case "PASSKEY_GET": {1247        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1248        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1249        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1250      }12511252      case "PASSKEY_AUTH_RESPONSE": {1253        const { requestId, approved } = (msg.payload ?? {}) as {1254          requestId?: string | number;1255          approved?: boolean;1256        };1257        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1258          return { ok: false, error: 'requestId and approved required' };1259        }1260        await resolvePendingPasskeyRequest(Number(requestId), approved);1261        return { ok: true };1262      }12631264      case "GET_PASSKEY_FOR_DOMAIN": {1265        const { domain } = (msg.payload ?? {}) as { domain?: string };1266        if (!domain) return { ok: false, error: "domain_required" };1267        // Scope to the caller's own origin: a page may only ask about passkeys1268        // for a domain it actually owns, so an arbitrary page cannot enumerate1269        // which sites the user holds passkeys for or read the username (audit MEDIUM).1270        const origin = attestedSenderOrigin(sender);1271        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1272        if (!vault.isUnlocked()) return { ok: true, data: null };1273        const match = vault1274          .getEntries()1275          .find((entry) => entry.passkey?.rpId === domain);1276        if (!match || !match.passkey) return { ok: true, data: null };1277        // Slim shape — only the fields State 11 needs. Never expose private1278        // key material, even though this is locked behind isUnlocked.1279        return {1280          ok: true,1281          data: {1282            rpId: match.passkey.rpId,1283            userName: match.passkey.userName,1284            browser: match.passkey.browser,1285          },1286        };1287      }12881289      case "DESTROY_VAULT": {1290        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1291        // storage.local.clear() wipes every Peach key (slots, settings, license,1292        // onboarded flag, history, sync state, declined cards, recall, etc.);1293        // session.clear() wipes pending passkey requests + pro-notice queues.1294        // Caller (Panic.tsx) handles UI navigation back to onboarding.1295        //1296        // The Pro license is the one thing that must survive: the user paid for1297        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1298        // Capture it before the clear and restore it after. peach_pro_celebrated1299        // rides along so the Pro celebration doesn't replay on the next unlock.1300        const preserved = await chrome.storage.local.get([1301          "peach_license",1302          "peach_pro_celebrated",1303        ]);1304        vault.lock();1305        await storageClear();1306        await vault.clearVaultHistory();1307        const toRestore: Record<string, unknown> = {};1308        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1309        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1310        if (Object.keys(toRestore).length > 0) {1311          await chrome.storage.local.set(toRestore);1312        }1313        if (chrome.storage.session) {1314          await chrome.storage.session.clear();1315        }1316        return { ok: true };1317      }13181319      case "GET_IDENTITY_SUGGESTIONS": {1320        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1321        const entries = vault.getEntries();1322        const suggestions = buildIdentitySuggestions(entries);1323        return { ok: true, data: { suggestions } };1324      }1325      case "ML_INIT":1326        return { ok: true };13271328      case "ML_PREDICT_BATCH": {1329        // AUD-002: shape-validate before forwarding to the ML helper.1330        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1331        if (!Array.isArray(featuresArray)) {1332          return { ok: false, error: "invalid_payload" };1333        }1334        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1335      }13361337      // ── Vault sync (v3) ───────────────────────────────────────────────1338      // Returns the public-facing local identity needed by the popup to1339      // drive Phase-1 audio pairing. The private long-term key never1340      // leaves the background.1341      case "GET_LOCAL_IDENTITY": {1342        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1343        // Pro license from an already-Pro peer (at least one device must be Pro).1344        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1345        // Identity derives from the stable root key, not the password-derived1346        // key, so pairing survives a master-password change (SEV-2-B).1347        const masterKeyHex = vault.getRootKeyHex();1348        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1349        const masterKey = unhexBytes(masterKeyHex);1350        try {1351          const identity = await buildLocalIdentity(masterKey);1352          // If this device is Pro, advertise the signed license so the peer can1353          // activate it after SAS confirmation — pairing carries Pro across.1354          if (await isProUser()) {1355            const license = await getLicenseKey();1356            if (license) (identity as { license?: string }).license = license;1357          }1358          return { ok: true, data: identity };1359        } finally {1360          masterKey.fill(0);1361        }1362      }13631364      case "LIST_PAIRED_DEVICES": {1365        const devices = await listPairedDevicesV3();1366        return { ok: true, data: { devices } };1367      }13681369      case "RENAME_PAIRED_DEVICE": {1370        const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string };1371        if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") {1372          return { ok: false, error: "invalid_payload" };1373        }1374        await renamePairedDeviceV3(deviceId, name);1375        return { ok: true };1376      }13771378      case "UNPAIR_DEVICE": {1379        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1380        if (typeof deviceId !== "string" || !deviceId) {1381          return { ok: false, error: "invalid_payload" };1382        }1383        // Removing a device REVOKES it rather than just dropping the local1384        // row: a plain removal is undone the moment any other peer vouches it1385        // back through a manifest, which is exactly what the relay makes easy.1386        await revokeDeviceByIdV3(deviceId, await getOrCreateDeviceId());1387        // Sync against the remaining hosts — the unpaired device no longer1388        // matters but the next alarm tick is up to ten minutes away.1389        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1390        return { ok: true };1391      }13921393      case "RENAME_LOCAL_DEVICE": {1394        const { name } = (msg.payload ?? {}) as { name?: string };1395        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1396        await setDeviceNameV3(name);1397        return { ok: true };1398      }13991400      // ── Relay pairing ─────────────────────────────────────────────────────1401      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1402      // session runs in the background; the SAS and the terminal result reach1403      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1404      case "START_ADOPTION_SOURCE": {1405        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1406        if (isRelayAdoptionSourceInFlight()) {1407          return { ok: false, error: "adoption_source_in_progress" };1408        }1409        try {1410          return { ok: true, data: await startRelayAdoptionSource() };1411        } catch (error) {1412          return {1413            ok: false,1414            error: error instanceof Error ? error.message : "adoption_source_failed",1415          };1416        }1417      }14181419      // Onboarding receiver — empty extension shows a QR, phone scans and1420      // sends the vault. The popup supplies the local-only password here so1421      // the background can wrap the adopted root key at rest without ever1422      // asking the user to retype it.1423      case "START_ADOPTION_RECEIVER": {1424        if (isRelayAdoptionSourceInFlight()) {1425          return { ok: false, error: "adoption_receiver_in_progress" };1426        }1427        const password = (msg.payload as { password?: unknown } | undefined)?.password;1428        if (typeof password !== "string" || password.length === 0) {1429          return { ok: false, error: "invalid_payload" };1430        }1431        try {1432          return { ok: true, data: await startRelayAdoptionReceiver(password) };1433        } catch (error) {1434          return {1435            ok: false,1436            error: error instanceof Error ? error.message : "adoption_receiver_failed",1437          };1438        }1439      }14401441      // Popup→bg counterpart to ADOPTION_SOURCE_SAS (receiver flow).1442      // The receiver now auto-accepts the SAS (both sides derive it from the1443      // same Noise handshake hash, so the codes match by construction) so1444      // the popup never has a SAS screen to tap on. The id round-trips the1445      // same way so a stale late response can't approve the wrong session.1446      // Popup→bg counterpart for the source flow: Confirm/Cancel on the1447      // source's SAS screen.14481449      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1450      // on the source's SAS screen. The id round-trips the same way so a stale1451      // late response can't approve the wrong session.1452      case "SOURCE_SAS_DECISION": {1453        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1454        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1455          return { ok: false, error: "invalid_payload" };1456        }1457        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1458      }14591460      case "CANCEL_ADOPTION_SOURCE": {1461        cancelRelayAdoptionSource();1462        return { ok: true };1463      }14641465      case "TRIGGER_SYNC": {1466        const payload = (msg.payload ?? {}) as {1467          reason?: "vault_change" | "foreground" | "manual";1468          force?: boolean;1469        };1470        const reason = payload.reason ?? "foreground";14711472        void triggerSyncIfReachable({ reason, force: payload.force === true });1473        return { ok: true };1474      }14751476      case "GET_SYNC_STATE": {1477        return { ok: true, data: getSyncState() };1478      }14791480      case "GET_SYNC_SETTINGS": {1481        return { ok: true, data: await getSyncSettings() };1482      }14831484      case "SET_SYNC_SETTINGS": {1485        const payload = (msg.payload ?? {}) as {1486          mode?: unknown;1487          relayUrl?: unknown;1488        };1489        try {1490          // A custom relay URL implies private mode; Peach's own relay stays1491          // public. See setRelayUrl.1492          if (payload.relayUrl !== undefined) {1493            if (typeof payload.relayUrl !== "string") {1494              return { ok: false, error: "invalid_relay_url" };1495            }1496            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1497          }1498          if (payload.mode !== undefined) {1499            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1500              return { ok: false, error: "invalid_sync_mode" };1501            }1502            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1503          }1504          return { ok: true, data: await getSyncSettings() };1505        } catch (error) {1506          return {1507            ok: false,1508            error: error instanceof Error ? error.message : "invalid_relay_url",1509          };1510        }1511      }15121513      case "GET_SYNC_ALERTS": {1514        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1515        const alerts = await getPendingSyncAlerts();1516        // The popup reads on open and acknowledges with consume:true after1517        // rendering, so a popup crash between read and render doesn't lose1518        // the alerts.1519        if (consume) await clearPendingSyncAlerts();1520        return { ok: true, data: alerts };1521      }15221523      case "GET_PENDING_VOUCHED_DEVICES": {1524        return { ok: true, data: await listPendingVouchedDevices() };1525      }1526      case "CONFIRM_VOUCHED_DEVICE": {1527        const { deviceId } = msg.payload as { deviceId: string };1528        const pending = await getPendingVouchedDevice(deviceId);1529        if (!pending) return { ok: false, error: "not_pending" };1530        // Last gate before a vouched device becomes a sync peer. A queue entry1531        // can predate the revocation that names it, so revocation is re-checked1532        // here rather than trusted to have swept the queue.1533        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {1534          await removePendingVouchedDevice(deviceId);1535          return { ok: false, error: "device_revoked" };1536        }1537        await upsertPairedDeviceV3({1538          deviceId: pending.deviceId,1539          deviceName: pending.deviceName,1540          deviceType:1541            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1542          longTermPublicKeyHex: pending.longTermPublicKeyHex,1543          signingPublicKeyHex: pending.signingPublicKeyHex,1544          wsPort: pending.wsPort,1545          pairedAt: pending.pairedAt,1546          trustSource: "vouched",1547        });1548        await removePendingVouchedDevice(deviceId);1549        // Newly confirmed vouched device is now a sync target — kick a round1550        // so the mesh introduction pays off without a 10-minute wait.1551        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1552        return { ok: true };1553      }1554      case "REJECT_VOUCHED_DEVICE": {1555        const { deviceId } = msg.payload as { deviceId: string };1556        await removePendingVouchedDevice(deviceId);1557        return { ok: true };1558      }1559      case "ROTATE_SYNC_IDENTITY": {1560        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1561        const result = await vault.rotateSyncIdentity();1562        return result.ok ? { ok: true } : { ok: false, error: result.error };1563      }15641565      default:1566        return { ok: false, error: "unknown_message_type" };1567    }1568  } catch (err) {1569    return {1570      ok: false,1571      error: err instanceof Error ? err.message : "operation_failed",1572    };1573  }1574}15751576// Returns username use-counts from the vault, sorted by frequency. Each row1577// also carries the entry's email so the popup can suggest the email/username1578// pair the user has actually used together.1579function buildIdentitySuggestions(1580  entries: VaultEntry[],1581): Array<{ email: string; username: string; count: number }> {1582  const usernameCounts = new Map<string, number>();1583  const usernameEmail = new Map<string, string>();1584  for (const entry of entries) {1585    const username = entry.username ?? "";1586    const email = (entry as VaultEntry & { email?: string }).email ?? "";1587    if (!username && !email) continue;1588    const key = username || email;1589    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1590    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1591  }1592  return Array.from(usernameCounts.entries())1593    .sort((a, b) => b[1] - a[1])1594    .map(([username, count]) => ({1595      email: usernameEmail.get(username) ?? "",1596      username,1597      count,1598    }));1599}16001601/** Notify all content scripts that the vault just became available. */1602function broadcastToContentScripts(message: { type: string }): void {1603  if (!chrome.tabs?.query) return;1604  chrome.tabs.query({}, (tabs) => {1605    for (const tab of tabs) {1606      if (tab.id !== undefined) {1607        chrome.tabs.sendMessage(tab.id, message).catch(() => {1608          // Tab may not have a content script — silently ignore1609        });1610      }1611    }1612  });1613}16141615function shouldRefreshAutoLock(type: MessageType): boolean {1616  return (1617    type !== "HAS_VAULT" &&1618    type !== "IS_UNLOCKED" &&1619    type !== "GET_VAULT_STATUS" &&1620    type !== "LOCK" &&1621    type !== "UPDATE_SETTINGS" &&1622    type !== "GET_PENDING_PASSKEY" &&1623    type !== "GET_PASSKEY_PROVIDER_STATE" &&1624    type !== "DECLINE_CARD_SAVE" &&1625    type !== "IS_CARD_DECLINED"1626  );1627}16281629function isAllowedCanaryWebhookUrl(value: string): boolean {1630  try {1631    const url = new URL(value);1632    if (url.protocol !== "https:") return false;16331634    const hostname = url.hostname.toLowerCase();1635    if (1636      hostname === "localhost" ||1637      hostname.endsWith(".localhost") ||1638      isPrivateIpv4(hostname) ||1639      isPrivateIpv6(hostname)1640    ) {1641      return false;1642    }16431644    return true;1645  } catch {1646    return false;1647  }1648}16491650function isPrivateIpv4(hostname: string): boolean {1651  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1652    return true;1653  }16541655  const octets = hostname.split(".").map((part) => Number(part));1656  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1657    return false;1658  }16591660  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1661}16621663function isPrivateIpv6(hostname: string): boolean {1664  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1665  // IPv4-mapped IPv6 literals embed a plain IPv4 address that the prefix1666  // list below can never match (WHATWG URL serializes [::ffff:192.168.0.1]1667  // as ::ffff:c0a8:1). Unwrap and test the embedded IPv4; unparseable mapped1668  // tails fail closed. (Codex Security 2026-08-04 LOW,1669  // ssrf.webhook-url-private-ip-filter.) DNS rebinding is out of scope for a1670  // one-shot host check.1671  const mapped = /^::ffff:(.+)$/.exec(normalized);1672  if (mapped) {1673    const tail = mapped[1] ?? "";1674    if (tail.includes(".")) return isPrivateIpv4(tail);1675    const parts = tail.split(":");1676    const [hi, lo] = parts;1677    if (1678      parts.length !== 2 ||1679      !hi ||1680      !lo ||1681      !/^[0-9a-f]{1,4}$/.test(hi) ||1682      !/^[0-9a-f]{1,4}$/.test(lo)1683    ) {1684      return true;1685    }1686    const octets = [1687      (Number.parseInt(hi, 16) >>> 8) & 0xff,1688      Number.parseInt(hi, 16) & 0xff,1689      (Number.parseInt(lo, 16) >>> 8) & 0xff,1690      Number.parseInt(lo, 16) & 0xff,1691    ];1692    return isPrivateIpv4(octets.join("."));1693  }1694  return (1695    normalized === "::1" ||1696    normalized.startsWith("fc") ||1697    normalized.startsWith("fd") ||1698    normalized.startsWith("fe80:")1699  );1700}