messages.ts

70.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 { computeVaultId } from "../shared/sync-identity";16import {17  getPendingVouchedDevice,18  listPendingVouchedDevices,19  removePendingVouchedDevice,20} from "./pending-vouched-devices";21import { isRecoveryConfirmPending } from "./recovery-pending";22import { setupAutoLock, touchAutoLock } from "./alarms";23import { runSelfTest } from "./self-test";24import * as vault from "./vault";25import {26  handleEstimateCodexPages,27  handleGetCodexVaultData,28  handleRestoreFromCodex,29} from "./codex-handlers";30import type { CodexRestorePayload } from "../shared/codex-types";31import {32  activateLicense,33  deactivateLicense,34  getLicenseInfo,35  getLicenseKey,36  isProUser,37  markCelebrationPlayed,38  shouldPlayCelebration,39} from "./license";40import {41  completeFirefoxPasskeyCreate,42  getPasskeyProviderState,43  getPendingPasskeyRequest,44  handleFirefoxPasskeyCreate,45  handleFirefoxPasskeyGet,46  handlePasskeyHasCredentials,47  initiateFirefoxPasskeyCreate,48  isPasskeyOfferDeclined,49  onVaultUnlocked,50  recordPasskeyOfferDecline,51  resolvePendingPasskeyRequest,52  setPasskeyProviderEnabled,53} from "./passkey";54import { buildAdvancedHealthReport } from "./health";55import { storageClear } from "../shared/storage";56import { findInvalidWords } from "../shared/recovery-words";57import type {58  Message,59  MessageResponse,60  MessageType,61  ProFeature,62  VaultEntry,63} from "../shared/types";64import { isPasskeyOnly } from "../shared/types";65import { generateTOTP } from "../crypto/totp";66import { isValidRpId } from "../shared/passkey-utils";67import { isNativePlatform, nativePlugin } from "../shared/native";68import { predictBatch as mlPredictBatch } from "./ml";69import type { MLFieldFeatures } from "../shared/ml";70import {71  buildLocalIdentity,72  getOrCreateDeviceId,73  setDeviceName as setDeviceNameV3,74} from "./device-identity";75import {76  listPairedDevices as listPairedDevicesV3,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  confirmRelayAdoptionSource,90  isRelayAdoptionSourceInFlight,91  startRelayAdoptionSource,92} from "./relay-adoption-source-bg";93import {94  getSyncSettings,95  setRelayUrl,96  setSyncMode,97  type SyncMode,98} from "./sync-settings";99import {100  getSyncState,101  hydratePersistedSyncState,102  setSyncRunner,103  triggerSyncIfReachable,104} from "./sync-trigger";105import { productionSyncRunner } from "./sync-runner";106107// Compile-time E2E flag, folded to a literal by Vite's `define` (false in108// every production build — verified in the bundled output). Mirrors the109// create-path bypass in passkey.ts so the Playwright passkey smoke can enable110// the provider without a real Pro licence; the gate is fully intact for users.111declare const __PEACH_E2E_PASSKEYS__: boolean;112const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true;113114let nativeSyncRunnerBootstrapped = false;115116function unhexBytes(hex: string): Uint8Array {117  if (hex.length % 2 !== 0) throw new Error("invalid hex");118  const out = new Uint8Array(hex.length / 2);119  for (let i = 0; i < out.length; i++) {120    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);121  }122  return out;123}124125/**126 * The single Pro gate. Every gated handler calls this first; the broadcast127 * lets the popup react (navigate to the License section, highlight the128 * relevant feature). Background never touches the popup view directly —129 * the popup owns navigation. See Projects.md "Pro gate rule".130 */131async function requirePro(132  feature: ProFeature,133  trigger: "user" | "background" = "user"134): Promise<{ allowed: boolean }> {135  if (PASSKEY_E2E_PRO_BYPASS && feature === "passkeys") return { allowed: true };136  if (await isProUser()) return { allowed: true };137138  if (trigger === "user") {139    // User deliberately triggered this feature — redirect the popup immediately.140    chrome.runtime141      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })142      .catch(() => {143        // Popup may be closed — the gate signal is best-effort.144      });145  } else {146    // Background trigger (e.g. passive sync initiation) — no popup is open.147    // Queue a notice so the next popup open shows a soft banner instead of148    // silently failing.149    if (chrome.storage.session) {150      chrome.storage.session151        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })152        .catch(() => {});153    }154  }155156  return { allowed: false };157}158159// ---------------------------------------------------------------------------160// PCH-01-018: operations that irreversibly destroy or replace vault contents.161// These are gated to trusted extension-page senders in handleMessage; the162// confirmation UX otherwise lives only in the popup. Keep this in sync when163// adding new destructive handlers.164const DESTRUCTIVE_MESSAGE_TYPES: ReadonlySet<string> = new Set([165  "DESTROY_VAULT",166  "CLEAR_VAULT_ENTRIES",167  "RESTORE_VAULT_SNAPSHOT",168  "RESTORE_FROM_CODEX",169]);170171// LV-3: minimum interval between non-test canary pings per webhook+entry.172const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour173174const PRIVATE_IPV4_RANGES = [175  { prefix: "10." },176  { prefix: "127." },177  { prefix: "169.254." },178  { prefix: "192.168." },179];180181export function setupMessageHandler(): void {182  chrome.runtime.onMessage.addListener(183    (msg: unknown, sender, sendResponse) => {184      if (!isMessage(msg)) {185        sendResponse({ ok: false, error: "invalid_message" });186        return true;187      }188      handleMessage(msg, sender)189        .then(sendResponse)190        .catch((err) =>191          sendResponse({192            ok: false,193            error: err instanceof Error ? err.message : String(err),194          })195        );196      return true;197    }198  );199200  // Android: the chrome shim queues sendMessage calls until this handler is201  // registered. Without this hookup, every message hangs on Capacitor builds.202  // eslint-disable-next-line @typescript-eslint/no-explicit-any203  const reg = (globalThis as any).__peachRegisterMessageHandler;204  if (typeof reg === "function") {205    reg(async (m: unknown) => {206      if (!isMessage(m)) return { ok: false, error: "invalid_message" };207      try {208        return await handleMessage(m);209      } catch (err) {210        return {211          ok: false,212          error: err instanceof Error ? err.message : String(err),213        };214      }215    });216  }217  if (isNativePlatform()) {218    void bootstrapNativeSyncRunner();219  }220}221222async function bootstrapNativeSyncRunner(): Promise<void> {223  if (nativeSyncRunnerBootstrapped) return;224  nativeSyncRunnerBootstrapped = true;225  try {226    setSyncRunner(productionSyncRunner);227    await hydratePersistedSyncState();228  } catch (err) {229    nativeSyncRunnerBootstrapped = false;230    console.warn("[Peach] failed to bootstrap native sync runner:", err);231  }232}233234function isMessage(m: unknown): m is Message {235  return typeof m === "object" && m !== null && "type" in m;236}237238/**239 * The browser-attested origin of the page that originated this message. A web240 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),241 * so every page-driven message arrives via the content-script relay and the242 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a243 * value the page cannot forge. This is the ONLY trustworthy origin for passkey244 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.245 */246function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {247  if (sender.origin) return sender.origin;248  if (sender.url) {249    try { return new URL(sender.url).origin; } catch { return undefined; }250  }251  return undefined;252}253254// Resolves once restoreFromSession() has run, so handlers see the correct255// post-restore unlock state. entry.ts registers this BEFORE the message256// handler so the onMessage listener is added synchronously at SW startup257// (MV3 requirement) while unlock-dependent handlers still wait for restore.258let restoreReady: Promise<void> = Promise.resolve();259260/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */261export function setRestoreReady(p: Promise<unknown>): void {262  restoreReady = p.then(() => undefined, () => undefined);263}264265export async function handleMessage(266  msg: Message,267  sender: Partial<chrome.runtime.MessageSender> = {}268): Promise<MessageResponse> {269  try {270    // Wait for session-restore to finish before reading any unlock/vault state.271    // On a cold SW start the popup's first message arrives while restore is272    // still in flight; without this gate IS_UNLOCKED would report locked (a273    // spurious lock screen) and the storage reads could race. The onMessage274    // listener itself is registered synchronously (entry.ts) so this gate, not275    // listener registration, is what absorbs the cold-start window.276    await restoreReady;277    // Validate sender — only allow messages from our extension pages/scripts.278    // `sender.id` is undefined for messages originating from extension UI279    // (popup/options), which is legitimate; reject only when it is defined280    // and does not match our extension id.281    if (282      sender.id !== undefined &&283      sender.id !== chrome.runtime.id284    ) {285      return { ok: false, error: "invalid_sender" };286    }287288    // PCH-01-018: irreversible operations must originate from a trusted extension289    // page (popup/options), never from a content script. The sender.id check above290    // only proves the message came from *our* extension — a content script injected291    // into an attacker page passes it. A single XSS-class bug in the injected UI292    // would otherwise escalate to vault destruction. Extension pages carry an293    // extension-origin sender.url; content scripts carry a page URL.294    if (DESTRUCTIVE_MESSAGE_TYPES.has(msg.type)) {295      const extensionOrigin = chrome.runtime.getURL("");296      if (!sender.url?.startsWith(extensionOrigin)) {297        return { ok: false, error: "invalid_sender" };298      }299    }300301    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {302      touchAutoLock();303    }304305    switch (msg.type) {306      case "CREATE_VAULT": {307        const { password } = msg.payload as { password: string };308        // Refuse to create a vault under an empty master password — the derived309        // key would be publicly known and the at-rest AES-GCM protection void310        // (audit HIGH; the CSV-import path previously passed ""). Length/strength311        // policy lives in the onboarding UI; this is the non-negotiable floor.312        if (typeof password !== "string" || password.length === 0) {313          return { ok: false, error: "invalid_payload" };314        }315        await vault.createVault(password);316        await setupAutoLock();317        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });318        onVaultUnlocked();319        return { ok: true };320      }321      case "CREATE_VAULT_FROM_ROOT_KEY": {322        const { password, rootKeyHex } = (msg.payload ?? {}) as {323          password?: unknown;324          rootKeyHex?: unknown;325        };326        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {327          return { ok: false, error: "invalid_payload" };328        }329330        try {331          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);332          await setupAutoLock();333          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });334          onVaultUnlocked();335          return { ok: true, vaultId };336        } catch (err) {337          return { ok: false, error: err instanceof Error ? err.message : String(err) };338        }339      }340      case "UNLOCK": {341        const { password } = msg.payload as { password: string };342        const ok = await vault.unlock(password);343        if (ok) {344          // KAT: verify the WebCrypto stack is healthy before the user relies on it.345          // Runs after unlock so latency is hidden behind the vault-load time.346          const kat = await runSelfTest();347          if (!kat.ok) {348            console.error("[Peach] Crypto self-test FAILED:", kat.error);349            await vault.lock();350            return { ok: false, error: "self_test_failed" };351          }352          await setupAutoLock();353          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });354          onVaultUnlocked();355          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());356          return { ok: true };357        }358        // Distinguish corruption from wrong password so the popup can offer359        // a history-restore path instead of falsely accusing the user of360        // mistyping (M7/COR-007).361        const failure = vault.consumeLastUnlockFailureReason();362        if (failure) {363          return {364            ok: false,365            error: "vault_corrupted",366            canRestoreFromHistory: true,367          } as MessageResponse;368        }369        return { ok: false };370      }371      case "VALIDATE_RECOVERY_WORDS": {372        const { words } = msg.payload as { words: string[] };373        const invalid = findInvalidWords(words);374        return { ok: true, data: { valid: invalid.length === 0, invalid } };375      }376      case "GET_RECOVERY_WORDS": {377        // Must be unlocked and have recovery set up (vault must be v2.12+).378        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };379        // LV-4: the recovery words re-derive the ROOT KEY — the highest-380        // value secret in the vault. A session unlock (which may be hours381        // old on a shared machine) is not enough; require a fresh password382        // proof, matching the 1Password/Bitwarden pattern for revealing383        // escrow material. EXEMPTION: the create-vault / rotation confirmation384        // window (peach_recovery_pending) shows the words immediately after385        // the user authenticated, and that confirmation UI has no password to386        // resend — skip the re-auth there only.387        if (!(await isRecoveryConfirmPending())) {388          const { password } = (msg.payload ?? {}) as { password?: string };389          if (typeof password !== "string" || !password) {390            return { ok: false, error: "password_required" };391          }392          if (!(await vault.verifyMainPassword(password))) {393            return { ok: false, error: "wrong_password" };394          }395        }396        try {397          const words = await vault.getRecoveryWords();398          return { ok: true, data: words };399        } catch (e) {400          // pre-v2.12 vault that hasn't migrated401          return { ok: false, error: "recovery_not_setup" };402        }403      }404      case "RECOVER_WITH_WORDS": {405        // User has lost their password but has their 12 recovery words.406        // We: (1) validate the words, (2) re-encrypt vault with new password.407        const { words, newPassword } = msg.payload as {408          words: string[];409          newPassword: string;410        };411        const stored = await vault.loadSlotA();412        if (!stored) return { ok: false, error: "no_vault" };413        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {414          return { ok: false, error: "recovery_not_setup" };415        }416        // Unwrap the root key from the recovery escrow.417        try {418          await vault.unwrapRootKeyForRecovery(419            stored.recovery_wrapped_root_key,420            stored.recovery_nonce ?? "",421            stored.recovery_tag ?? "",422            stored.recovery_salt,423            words424          );425        } catch {426          return { ok: false, error: "invalid_recovery_words" };427        }428        // Re-key: derive fresh salt + key from new password.429        const newSalt = vault.generateSalt();430        const newKey = await vault.deriveKey(newPassword, newSalt);431        // Re-wrap root key under the new password's derived key so the same432        // recovery words continue to work after the password change.433        await vault.rewrapRootKeyForPassword(newKey, newSalt);434        // Re-encrypt vault entries with the new key.435        await vault.changePasswordWithNewKey(newSalt, newKey);436        await setupAutoLock();437        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });438        return { ok: true };439      }440      case "LOCK":441        vault.lock();442        if (isNativePlatform()) await clearInMemoryVault();443        return { ok: true };444      case "IS_UNLOCKED":445        return { ok: true, data: vault.isUnlocked() };446      case "GET_VAULT_STATUS":447        return { ok: true, unlocked: vault.isUnlocked() };448      case "HAS_VAULT":449        return { ok: true, data: await vault.hasVault() };450      case "GET_ENTRIES":451        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };452        return { ok: true, data: vault.getEntries() };453      case "ADD_ENTRY": {454        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };455        const payload = msg.payload;456        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {457          return { ok: false, error: "invalid_payload" };458        }459        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);460        return { ok: true, data: entry };461      }462      case "BATCH_ADD_ENTRIES": {463        const payload = msg.payload as { entries?: unknown } | null | undefined;464        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {465          return { ok: false, error: "invalid_payload" };466        }467        if (!Array.isArray(payload.entries)) {468          return { ok: false, error: "invalid_payload" };469        }470        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);471        return { ok: true, data: added };472      }473      case "RESTORE_ENTRIES": {474        const payload = msg.payload as475          | { entries?: unknown; mode?: unknown; settings?: unknown }476          | null477          | undefined;478        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {479          return { ok: false, error: "invalid_payload" };480        }481        if (!Array.isArray(payload.entries)) {482          return { ok: false, error: "invalid_payload" };483        }484        if (payload.mode !== "replace" && payload.mode !== "merge") {485          return { ok: false, error: "invalid_payload" };486        }487        const summary = await vault.restoreEntries(488          payload.entries as Parameters<typeof vault.restoreEntries>[0],489          payload.mode490        );491        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {492          await vault.updateSettings(payload.settings as vault.VaultSettings);493        }494        return { ok: true, data: summary };495      }496      case "CLEAR_VAULT_ENTRIES": {497        await vault.clearVaultEntries("REPLACE_ALL");498        return { ok: true };499      }500      case "GET_VAULT_HISTORY": {501        const snapshots = await vault.getVaultHistory();502        return { ok: true, data: snapshots };503      }504      case "RESTORE_VAULT_SNAPSHOT": {505        const { snapshotId } = msg.payload as { snapshotId: string };506        const result = await vault.restoreVaultSnapshot(snapshotId);507        if (!result.ok) return { ok: false, error: result.error };508        broadcastToContentScripts({ type: "VAULT_LOCKED" });509        return { ok: true };510      }511      case "COUNT_DUPLICATES": {512        return { ok: true, data: vault.countDuplicates() };513      }514      case "DEDUPLICATE_ENTRIES": {515        const removed = await vault.deduplicateEntries();516        return { ok: true, data: removed };517      }518      case "UPDATE_ENTRY": {519        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;520        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {521          return { ok: false, error: "invalid_payload" };522        }523        const { id, patch } = payload;524        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {525          return { ok: false, error: "invalid_payload" };526        }527        // Single enforcement point for the Canary Entries Pro gate. Only528        // gates the transition into a canary entry — clearing/disabling a529        // canary (`canary: undefined`) is always allowed, so existing530        // canary entries remain manageable.531        const incomingCanary = (patch as { canary?: unknown }).canary;532        if (incomingCanary && typeof incomingCanary === "object") {533          const existing = vault.getEntryById(id);534          if (!existing?.canary) {535            const gate = await requirePro("canary_entry");536            if (!gate.allowed) return { ok: false, error: "pro_required" };537          }538        }539        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);540        return { ok: true };541      }542      case "ADD_ADDITIONAL_URL": {543        const { id, url } = msg.payload as { id: string; url: string };544        const trimmed = typeof url === "string" ? url.trim() : "";545        if (!trimmed) return { ok: false, error: "url_required" };546        const existing = vault.getEntryById(id);547        if (!existing) return { ok: false, error: "entry_not_found" };548        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };549        const merged = [...(existing.additionalUrls ?? []), trimmed];550        await vault.updateEntry(id, { additionalUrls: merged });551        return { ok: true };552      }553      case "DELETE_ENTRY": {554        const { id } = msg.payload as { id: string };555        await vault.deleteEntry(id);556        return { ok: true };557      }558      case "GET_DELETED_ENTRIES":559        return { ok: true, data: vault.getDeletedEntries() };560      case "RESTORE_ENTRY": {561        const { id } = msg.payload as { id: string };562        await vault.restoreEntry(id);563        return { ok: true };564      }565      case "PURGE_ENTRY": {566        const { id } = msg.payload as { id: string };567        await vault.purgeEntry(id);568        return { ok: true };569      }570      case "PURGE_EXPIRED_TRASH": {571        const { retentionMs } = msg.payload as { retentionMs: number };572        const purged = await vault.purgeExpiredTrash(retentionMs);573        return { ok: true, data: purged };574      }575      case "SAVE_NOTE": {576        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };577        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };578        const now = Date.now();579        if (id) {580          const existing = vault.getEntryById(id);581          if (!existing) return { ok: false, error: "not_found" };582          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });583          return { ok: true, data: vault.getEntryById(id) };584        } else {585          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt586          // (EntryDraft omits both), so passing them was the only reason the587          // `as any` cast existed. Dropping them makes the call type-check.588          const entry = await vault.addEntry({589            type: "note",590            title: title || "Untitled",591            notes: body,592          });593          return { ok: true, data: entry };594        }595      }596      case "DELETE_NOTE": {597        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };598        const { id } = msg.payload as { id: string };599        await vault.deleteEntry(id);600        return { ok: true };601      }602      case "GET_NOTES": {603        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };604        const notes = vault.getEntries().filter(605          (e) => e.type === "note" && !e.deletedAt606        );607        return { ok: true, data: notes } as MessageResponse;608      }609      case "SEARCH_VAULT": {610        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };611        // AUD-002: shape-validate the payload before calling string methods.612        // A raw cast lets a malformed message crash the handler with TypeError.613        const { query } = (msg.payload ?? {}) as { query?: unknown };614        if (typeof query !== "string") {615          return { ok: false, error: "invalid_payload" };616        }617        const q = query.toLowerCase();618        const searchResults = vault.getEntries().filter(619          (e) =>620            !e.deletedAt &&621            (e.title.toLowerCase().includes(q) ||622              e.notes?.toLowerCase().includes(q) ||623              e.username?.toLowerCase().includes(q))624        );625        return { ok: true, data: searchResults } as MessageResponse;626      }627      case "AUTOFILL_QUERY": {628        if (!vault.isUnlocked()) {629          return { ok: false, error: "vault_locked" };630        }631        let { includeAll } = msg.payload as { includeAll?: boolean };632        const { domain, kind, userGesture } = msg.payload as {633          domain: string;634          kind?: "login" | "card" | "totp";635          userGesture?: boolean;636        };637        // MV-2: the vault-wide inventory (every title/username/email/url)638        // may only leave the background on an explicit user gesture — the639        // user opening the search affordance — never on passive form focus.640        // userGesture is self-declared by our own content script; the value641        // of this gate is that PASSIVE code paths (which never set it)642        // cannot ship the inventory, shrinking what a compromised page that643        // merely triggers focus events can observe.644        if (includeAll && userGesture !== true) {645          includeAll = false;646        }647        // kind="card": return saved cards as compact summaries for the648        // inline card silver platter. Cards are not domain-scoped — every649        // saved card is a candidate on every checkout page — so domain is650        // ignored when kind === "card".651        if (kind === "card") {652          const cards = vault.getEntries().filter((e) => e.type === "card");653          return {654            ok: true,655            data: cards.map((e) => ({656              id: e.id,657              title: e.cardNickname || e.title,658              cardholderName: e.cardholderName,659              last4: e.last4,660              expMonth: e.expMonth,661              expYear: e.expYear,662              network: e.network,663            })),664          };665        }666        if (kind === "totp") {667          const matches = (668            includeAll669              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")670              : vault.queryDomain(domain)671          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));672          return {673            ok: true,674            data: matches.map((e) => ({675              id: e.id,676              title: e.title,677              username: e.username,678              email: e.email,679              url: e.url,680              hasTotp: true,681            })),682          };683        }684        // The inline selector fills username+password into a form. Passkey-685        // only entries have no password to fill; sign-in for those goes686        // through the WebAuthn path instead. Filter them out everywhere so687        // the user doesn't see four "GitHub" rows that mostly do nothing.688        // Notes and cards never belonged here either.689        const matches = (690          includeAll691            ? vault692                .getEntries()693                .filter((entry) => entry.type !== "note" && entry.type !== "card")694            : vault.queryDomain(domain)695        ).filter((entry) => !isPasskeyOnly(entry));696        return {697          ok: true,698          data: matches.map((e) =>699            includeAll700              ? {701                  id: e.id,702                  title: e.title,703                  // username/email/url shipped so the inline popup's search704                  // affordance can match on them, not just titles. No secrets705                  // cross the boundary — same shape as the domain-matched706                  // response below minus hasTotp (which the search list707                  // doesn't surface).708                  username: e.username,709                  email: e.email,710                  url: e.url,711                  hasPasskey: e.passkey !== undefined,712                }713              : {714                  id: e.id,715                  title: e.title,716                  username: e.username,717                  email: e.email,718                  url: e.url,719                  hasTotp: Boolean(e.totp),720                  hasPasskey: e.passkey !== undefined,721                }722          ),723        };724      }725      case "GET_ENTRY_FOR_FILL": {726        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };727        const { id, explicitSummon } = msg.payload as {728          id: string;729          explicitSummon?: boolean;730        };731        const entry = vault.getEntryById(id);732        if (!entry) return { ok: false, error: "entry_not_found" };733        // Passkey-only entries (passkey credential, no password) cannot be734        // filled into a form — sign-in goes through the WebAuthn path. A735        // login that ALSO has a passkey is still fillable for its password.736        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };737738        // MV-1: re-validate the entry against the requesting tab's origin.739        // sender.tab.url is browser-attested — a page cannot forge it. When740        // the request does not come from a tab at all (popup surfaces use741        // GET_ENTRY_FOR_EDIT, not this), refuse.742        if (sender.tab !== undefined || sender.url !== undefined) {743          let senderDomain: string | null = null;744          try {745            const rawUrl = sender.tab?.url ?? sender.url ?? "";746            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;747          } catch {748            senderDomain = null;749          }750          if (!senderDomain) return { ok: false, error: "origin_unverified" };751752          const entryDomains = new Set<string>();753          const primary = extractDomain(entry.url ?? "");754          if (primary) entryDomains.add(primary);755          for (const extra of entry.additionalUrls ?? []) {756            const d = extractDomain(extra);757            if (d) entryDomains.add(d);758          }759760          // explicitSummon=true means the user actively picked this entry761          // from the cross-domain search affordance — an intentional762          // off-domain fill. Passive fill paths must stay domain-bound.763          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {764            // Domain mismatch — refuse silently (no oracle about which ids exist).765            return { ok: false, error: "entry_not_found" };766          }767        }768        // Strip the passkey credential AND the raw base32 TOTP seed from the769        // response. Content scripts never need either: the private key is the770        // authenticator's, and handing over the TOTP seed would let a771        // compromised content script mint valid codes indefinitely (SEV-3-C).772        // Generate the *current* 6-digit code here in the background and send773        // only that, plus the seconds left so the UI can render a countdown.774        // Also drop passwordHistory: filling needs only the *current* password.775        // Handing every past password to a content script during passive776        // autofill on an arbitrary page would widen the blast radius of a777        // compromised page far beyond the one credential being filled.778        const {779          passkey: _strippedPasskey,780          totp: seed,781          totpAlgorithm,782          totpDigits,783          totpPeriod,784          passwordHistory: _ph,785          ...safeEntry786        } = entry;787        let totpCode: string | undefined;788        let totpRemaining: number | undefined;789        if (seed) {790          try {791            // PCH-01-019: honour stored algorithm/digits/period (defaults apply792            // when these are undefined, i.e. legacy bare-seed entries).793            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);794            totpCode = generated.code;795            totpRemaining = generated.remaining;796          } catch {797            totpCode = undefined;798          }799        }800        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };801      }802      // Trusted full-entry fetch for Peach's own inline-popup surfaces that803      // genuinely need the raw TOTP seed: the edit form (which re-saves the804      // seed and would otherwise wipe it) and nothing else. Unlike805      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside806      // the inline popup, never during passive autofill on an arbitrary page.807      // The passkey credential is still stripped — the edit form never touches it.808      case "GET_ENTRY_FOR_EDIT": {809        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };810        const { id, explicitSummon } = msg.payload as {811          id: string;812          explicitSummon?: boolean;813        };814        const entry = vault.getEntryById(id);815        if (!entry) return { ok: false, error: "entry_not_found" };816817        // PCH-01-006: re-validate the browser-attested sender origin, mirroring818        // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and819        // full password history — at least as sensitive as the fill response — so820        // the boundary must be enforced here, not only by UI reachability. Today821        // the sole caller is the popup (no sender.tab, so this is a structural822        // no-op), but a future tab-context caller or an id leak would otherwise823        // inherit a full-credential oracle. Unlike the fill path we SKIP (not824        // refuse) when no sender domain resolves, to keep the popup caller working.825        if (sender.tab !== undefined || sender.url !== undefined) {826          let senderDomain: string | null = null;827          try {828            const rawUrl = sender.tab?.url ?? sender.url ?? "";829            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;830          } catch {831            senderDomain = null;832          }833          if (senderDomain) {834            const entryDomains = new Set<string>();835            const primary = extractDomain(entry.url ?? "");836            if (primary) entryDomains.add(primary);837            for (const extra of entry.additionalUrls ?? []) {838              const d = extractDomain(extra);839              if (d) entryDomains.add(d);840            }841            if (explicitSummon !== true && !entryDomains.has(senderDomain)) {842              return { ok: false, error: "entry_not_found" }; // no id oracle843            }844          }845        }846847        const { passkey: _passkey, ...safeEntry } = entry;848        return { ok: true, data: safeEntry };849      }850      case "COPY": {851        // AUD-002: shape-validate the payload before passing to the clipboard852        // helper. A raw cast lets a malformed message reach the clipboard API853        // with a non-string and throw.854        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {855          text?: unknown;856          label?: unknown;857          alreadyWritten?: unknown;858        };859        if (typeof text !== "string" || typeof label !== "string") {860          return { ok: false, error: "invalid_payload" };861        }862        await copyToClipboard(text, label, Boolean(alreadyWritten));863        return { ok: true, clearSeconds: getEffectiveClearSeconds() };864      }865      case "CHECK_ALL_BREACHES": {866        const allEntries = vault.getEntries();867        const results: Record<string, number> = {};868        for (const entry of allEntries) {869          if (entry.type === "note") continue;870          if (!entry.password) continue;871          results[entry.id] = await vault.checkBreach(entry.password);872          // Small delay — be a good citizen to the HIBP API873          await new Promise((r) => setTimeout(r, 200));874        }875        // Persist any non-zero counts back to entries876        for (const [id, count] of Object.entries(results)) {877          const entry = vault.getEntryById(id);878          if (entry && (entry.breach ?? 0) !== count) {879            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });880          }881        }882        return { ok: true, data: results };883      }884      case "GET_SETTINGS":885        return { ok: true, data: await vault.ensureSettingsLoaded() };886      case "UPDATE_SETTINGS": {887        const patch = msg.payload;888        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {889          return { ok: false, error: "invalid_payload" };890        }891        await vault.updateSettings(patch as vault.VaultSettings);892        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {893          await setupAutoLock();894          if (vault.isUnlocked()) touchAutoLock();895        }896        return { ok: true };897      }898      case "GET_PENDING_PASSKEY":899        return { ok: true, data: await getPendingPasskeyRequest() };900      case "APPROVE_PASSKEY": {901        const { requestId } = msg.payload as { requestId: number };902        await resolvePendingPasskeyRequest(requestId, true);903        return { ok: true };904      }905      case "DENY_PASSKEY": {906        const { requestId } = msg.payload as { requestId: number };907        await resolvePendingPasskeyRequest(requestId, false);908        return { ok: true };909      }910      case "GET_PASSKEY_PROVIDER_STATE":911        return { ok: true, data: await getPasskeyProviderState() };912      case "SET_PASSKEY_PROVIDER_ENABLED": {913        const { enabled } = msg.payload as { enabled: boolean };914        // Disabling is always free; gating fires only when a free user is915        // trying to turn passkey interception on.916        if (enabled) {917          const gate = await requirePro("passkeys");918          if (!gate.allowed) return { ok: false, error: "pro_required" };919        }920        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };921      }922      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS923      // endpoint. Intentional product behavior — users configure their own924      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private925      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-926      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to927      // users that the entry title leaves the device when the canary fires.928      case "FIRE_CANARY_PING": {929        // Canary alert fires unconditionally for any entry with canary: true.930        // The Pro gate only governs creation/flagging of canary entries; once931        // an entry is flagged, the alert path is a security property and must932        // never be license-gated.933        const { webhookUrl, entryTitle, trigger } = msg.payload as {934          webhookUrl: string;935          entryTitle: string;936          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";937        };938        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {939          return { ok: false, error: "invalid_webhook_url" };940        }941        // LV-3: debounce non-test pings per (webhook, entry) so a page that942        // strobes focus/fill events can't turn the canary into a request943        // firehose at the user's endpoint. Test pings are exempt — they are944        // explicit user clicks in the settings UI and are awaited for945        // feedback. The FIRST ping in a window always goes out, so the946        // dead-man's-switch property (canary fires on access) is preserved;947        // only repeats within the window are coalesced.948        if (trigger !== "test") {949          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;950          const stored = await chrome.storage.local.get(rlKey);951          const last = (stored as Record<string, unknown>)[rlKey];952          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {953            return { ok: true, data: { rateLimited: true } };954          }955          await chrome.storage.local.set({ [rlKey]: Date.now() });956        }957        const body = JSON.stringify({958          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",959          entry: entryTitle,960          trigger,961          timestamp: new Date().toISOString(),962          source: "peach-extension",963        });964        if (trigger === "test") {965          // Permitted outbound fetch: user-configured canary alert endpoint966          // (validated by isAllowedCanaryWebhookUrl above). This is the967          // only non-HIBP outbound call in the extension — see968          // Projects.md §3.7. Test pings are awaited so the UI can show969          // success/failure.970          try {971            const res = await fetch(webhookUrl, {972              method: "POST",973              headers: { "Content-Type": "application/json" },974              body,975            });976            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };977          } catch (err) {978            return { ok: false, error: err instanceof Error ? err.message : "network_error" };979          }980        }981        // Non-test triggers are fire-and-forget982        fetch(webhookUrl, {983          method: "POST",984          headers: { "Content-Type": "application/json" },985          body,986        }).catch(() => {});987        return { ok: true };988      }989      case "ACTIVATE_LICENSE": {990        const { key } = msg.payload as { key: string };991        const licenseInfo = await activateLicense(key);992        return { ok: true, data: licenseInfo };993      }994      case "GET_LICENSE": {995        const licenseInfo = await getLicenseInfo();996        return { ok: true, data: licenseInfo };997      }998      case "GET_LICENSE_KEY": {999        const key = await getLicenseKey();1000        return { ok: true, data: key };1001      }1002      case "DEACTIVATE_LICENSE": {1003        await deactivateLicense();1004        return { ok: true };1005      }1006      case "SHOULD_PLAY_CELEBRATION": {1007        const should = await shouldPlayCelebration();1008        return { ok: true, data: should };1009      }1010      case "MARK_CELEBRATION_PLAYED": {1011        await markCelebrationPlayed();1012        return { ok: true };1013      }1014      case "GET_CODEX_VAULT_DATA": {1015        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1016        // popup navigates to the License section without further coordination.1017        const gate = await requirePro("codex");1018        if (!gate.allowed) return { ok: false, error: "pro_required" };1019        return await handleGetCodexVaultData();1020      }1021      case "ESTIMATE_CODEX_PAGES": {1022        const gate = await requirePro("codex");1023        if (!gate.allowed) return { ok: false, error: "pro_required" };1024        return await handleEstimateCodexPages();1025      }1026      case "RESTORE_FROM_CODEX": {1027        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1028        // be able to restore a vault that was printed by a Pro user.1029        // DO NOT add a Pro gate here.1030        const payload = msg.payload as CodexRestorePayload;1031        return await handleRestoreFromCodex(payload);1032      }1033      case "OPEN_PRO_GATE": {1034        // Content script requests: open popup and navigate to License section.1035        const { feature } = (msg.payload ?? {}) as { feature?: string };1036        if (chrome.storage.session) {1037          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1038        }1039        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1040        return { ok: true };1041      }1042      case "OPEN_POPUP": {1043        // Content script asks to open the trusted extension popup — used by the1044        // inline locked bubble so the master password is entered in the popup,1045        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1046        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1047        // toolbar icon. The badge already signals Peach needs attention.1048        //1049        // Set a session flag so the popup knows it was opened for inline unlock1050        // and should close itself once the vault is unlocked (returning the user1051        // to the inline autofill selector on the page).1052        if (chrome.storage.session) {1053          await chrome.storage.session.set({ peach_inline_unlock: true });1054        }1055        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1056        return { ok: true };1057      }1058      case "GET_IDENTITIES": {1059        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1060        return { ok: true, data: vault.getIdentities() };1061      }1062      case "TOUCH_AUTO_LOCK": {1063        // touchAutoLock() is already called by shouldRefreshAutoLock above;1064        // this case just gives the popup a typed message to keep the session alive.1065        return { ok: true };1066      }1067      case "GET_ADVANCED_HEALTH_REPORT": {1068        const gate = await requirePro("advanced_health");1069        if (!gate.allowed) return { ok: false, error: "pro_required" };1070        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1071        const report = await buildAdvancedHealthReport(vault.getEntries());1072        return { ok: true, data: report };1073      }1074      case "IS_DURESS_ENABLED": {1075        const enabled = await vault.isDuressEnabled();1076        return { ok: true, data: enabled };1077      }1078      case "SETUP_DURESS": {1079        // Single enforcement point for the Duress Vault Pro gate. Free users1080        // who somehow reach this handler are rejected here; the popup also1081        // pre-checks isPro() to avoid showing the setup form to free users,1082        // but server-side is the actual security boundary.1083        const gate = await requirePro("duress_vault");1084        if (!gate.allowed) return { ok: false, error: "pro_required" };1085        // MV3 service workers restart after inactivity, losing the in-memory1086        // derived key. Detect this before calling setupDuress so the popup1087        // can show a meaningful prompt to re-lock and re-unlock.1088        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1089        const { duressPassword } = msg.payload as { duressPassword: string };1090        await vault.setupDuress(duressPassword);1091        return { ok: true };1092      }1093      case "DISABLE_DURESS": {1094        await vault.disableDuress();1095        return { ok: true };1096      }1097      case "VERIFY_MAIN_PASSWORD": {1098        const { password } = msg.payload as { password: string };1099        const ok = await vault.verifyMainPassword(password);1100        return { ok: true, data: ok };1101      }1102      case "CHANGE_PASSWORD": {1103        const { currentPassword, newPassword } = msg.payload as {1104          currentPassword: string;1105          newPassword: string;1106        };1107        const changed = await vault.changePassword(currentPassword, newPassword);1108        return changed1109          ? { ok: true }1110          : { ok: false, error: "incorrect_current_password" };1111      }1112      case "GET_SITE_PASSWORD_POLICY": {1113        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1114        if (!tab?.id) return { ok: true, data: null };1115        try {1116          const response = await chrome.tabs.sendMessage(tab.id, {1117            type: "GET_SITE_PASSWORD_POLICY",1118          });1119          return (response as MessageResponse) ?? { ok: true, data: null };1120        } catch {1121          return { ok: true, data: null };1122        }1123      }1124      case "RECORD_MANUAL_SUMMON": {1125        const { domain } = msg.payload as { domain: string };1126        const settings = vault.getSettings();1127        const existing = settings.manualSummonDomains?.[domain];1128        const now = Date.now();1129        await vault.updateSettings({1130          manualSummonDomains: {1131            ...settings.manualSummonDomains,1132            [domain]: {1133              firstSummonedAt: existing?.firstSummonedAt ?? now,1134              summonCount: (existing?.summonCount ?? 0) + 1,1135              lastSummonedAt: now,1136            },1137          },1138        });1139        return { ok: true };1140      }1141      case "DECLINE_CARD_SAVE": {1142        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1143        await vault.declineCardSaveOffer(last4, expMonth, expYear);1144        return { ok: true };1145      }1146      case "IS_CARD_DECLINED": {1147        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1148        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1149        return { ok: true, data: declined };1150      }1151      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1152        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1153          rpId?: string;1154          rpName?: string;1155          userName?: string;1156          userDisplayName?: string;1157        };1158        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1159        return await initiateFirefoxPasskeyCreate({1160          rpId,1161          rpName: rpName ?? rpId,1162          userName,1163          userDisplayName,1164        });1165      }11661167      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1168        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1169        if (!payload) return { ok: false, error: "missing_payload" };1170        return await completeFirefoxPasskeyCreate(payload);1171      }11721173      case "PASSKEY_OFFER_DECLINE": {1174        const { domain } = (msg.payload ?? {}) as { domain?: string };1175        if (!domain) return { ok: false, error: "domain_required" };1176        await recordPasskeyOfferDecline(domain);1177        return { ok: true };1178      }11791180      case "GET_PASSKEY_OFFER_DECLINED": {1181        const { domain } = (msg.payload ?? {}) as { domain?: string };1182        if (!domain) return { ok: false, error: "domain_required" };1183        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1184      }11851186      case "PASSKEY_HAS_CREDENTIALS": {1187        const payload = msg.payload as {1188          rpId?: string;1189          allowCredentials?: Array<{ id: string; type?: string }>;1190        } | undefined;1191        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1192        return await handlePasskeyHasCredentials({1193          rpId: payload.rpId,1194          allowCredentials: payload.allowCredentials ?? [],1195        }, attestedSenderOrigin(sender));1196      }11971198      case "PASSKEY_CREATE": {1199        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1200        if (!payload?.rpId || !payload?.userName) {1201          return { ok: false, error: "rpid_and_username_required" };1202        }1203        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1204      }12051206      case "PASSKEY_GET": {1207        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1208        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1209        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1210      }12111212      case "PASSKEY_AUTH_RESPONSE": {1213        const { requestId, approved } = (msg.payload ?? {}) as {1214          requestId?: string | number;1215          approved?: boolean;1216        };1217        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1218          return { ok: false, error: 'requestId and approved required' };1219        }1220        await resolvePendingPasskeyRequest(Number(requestId), approved);1221        return { ok: true };1222      }12231224      case "GET_PASSKEY_FOR_DOMAIN": {1225        const { domain } = (msg.payload ?? {}) as { domain?: string };1226        if (!domain) return { ok: false, error: "domain_required" };1227        // Scope to the caller's own origin: a page may only ask about passkeys1228        // for a domain it actually owns, so an arbitrary page cannot enumerate1229        // which sites the user holds passkeys for or read the username (audit MEDIUM).1230        const origin = attestedSenderOrigin(sender);1231        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1232        if (!vault.isUnlocked()) return { ok: true, data: null };1233        const match = vault1234          .getEntries()1235          .find((entry) => entry.passkey?.rpId === domain);1236        if (!match || !match.passkey) return { ok: true, data: null };1237        // Slim shape — only the fields State 11 needs. Never expose private1238        // key material, even though this is locked behind isUnlocked.1239        return {1240          ok: true,1241          data: {1242            rpId: match.passkey.rpId,1243            userName: match.passkey.userName,1244            browser: match.passkey.browser,1245          },1246        };1247      }12481249      case "DESTROY_VAULT": {1250        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1251        // storage.local.clear() wipes every Peach key (slots, settings, license,1252        // onboarded flag, history, sync state, declined cards, recall, etc.);1253        // session.clear() wipes pending passkey requests + pro-notice queues.1254        // Caller (Panic.tsx) handles UI navigation back to onboarding.1255        //1256        // The Pro license is the one thing that must survive: the user paid for1257        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1258        // Capture it before the clear and restore it after. peach_pro_celebrated1259        // rides along so the Pro celebration doesn't replay on the next unlock.1260        const preserved = await chrome.storage.local.get([1261          "peach_license",1262          "peach_pro_celebrated",1263        ]);1264        vault.lock();1265        await storageClear();1266        await vault.clearVaultHistory();1267        const toRestore: Record<string, unknown> = {};1268        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1269        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1270        if (Object.keys(toRestore).length > 0) {1271          await chrome.storage.local.set(toRestore);1272        }1273        if (chrome.storage.session) {1274          await chrome.storage.session.clear();1275        }1276        return { ok: true };1277      }12781279      // Android-only: biometric unlock with pre-derived key.1280      case "UNLOCK_WITH_KEY": {1281        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1282        if (!isNativePlatform()) {1283          return { ok: false, error: "desktop_only_uses_password" };1284        }1285        try {1286          const result = await vault.unlockWithKey(masterKeyHex);1287          if (result.ok) {1288            onVaultUnlocked();1289            await publishInMemoryVault(result.entries);1290          }1291          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1292        } catch {1293          return { ok: false, error: "invalid_key" };1294        }1295      }1296      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1297      case "GET_DERIVED_KEY": {1298        if (!isNativePlatform()) {1299          return { ok: false, error: "android_only" };1300        }1301        if (!vault.isUnlocked()) {1302          return { ok: false, error: "vault_locked" };1303        }1304        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1305      }1306      case "GET_IDENTITY_SUGGESTIONS": {1307        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1308        const entries = vault.getEntries();1309        const suggestions = buildIdentitySuggestions(entries);1310        return { ok: true, data: { suggestions } };1311      }1312      case "POPULATE_INLINE_VAULT": {1313        if (!isNativePlatform()) return { ok: false };1314        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1315        const entries = vault.getEntries();1316        await publishInMemoryVault(entries);1317        return { ok: true };1318      }1319      case "ML_INIT":1320        return { ok: true };13211322      case "ML_PREDICT_BATCH": {1323        // AUD-002: shape-validate before forwarding to the ML helper.1324        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1325        if (!Array.isArray(featuresArray)) {1326          return { ok: false, error: "invalid_payload" };1327        }1328        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1329      }13301331      // ── Vault sync (v3) ───────────────────────────────────────────────1332      // Returns the public-facing local identity needed by the popup to1333      // drive Phase-1 audio pairing. The private long-term key never1334      // leaves the background.1335      case "GET_LOCAL_IDENTITY": {1336        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1337        // Pro license from an already-Pro peer (at least one device must be Pro).1338        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1339        // Identity derives from the stable root key, not the password-derived1340        // key, so pairing survives a master-password change (SEV-2-B).1341        const masterKeyHex = vault.getRootKeyHex();1342        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1343        const masterKey = unhexBytes(masterKeyHex);1344        try {1345          const identity = await buildLocalIdentity(masterKey);1346          // If this device is Pro, advertise the signed license so the peer can1347          // activate it after SAS confirmation — pairing carries Pro across.1348          if (await isProUser()) {1349            const license = await getLicenseKey();1350            if (license) (identity as { license?: string }).license = license;1351          }1352          return { ok: true, data: identity };1353        } finally {1354          masterKey.fill(0);1355        }1356      }13571358      case "GET_ADOPTION_MATERIAL": {1359        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1360        const rootKeyHex = vault.getRootKeyHex();1361        if (!rootKeyHex) return { ok: false, error: "vault_locked" };1362        const rootKeyBytes = unhexBytes(rootKeyHex);1363        try {1364          const data: { rootKeyHex: string; vaultId: string; license?: string } = {1365            rootKeyHex,1366            vaultId: await computeVaultId(rootKeyBytes),1367          };1368          if (await isProUser()) {1369            const license = await getLicenseKey();1370            if (license) data.license = license;1371          }1372          return { ok: true, data };1373        } finally {1374          rootKeyBytes.fill(0);1375        }1376      }13771378      case "COMPLETE_PAIRING": {1379        // Not Pro-gated — see GET_LOCAL_IDENTITY.1380        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1381        const paired = (msg.payload as { paired?: unknown })?.paired;1382        if (typeof paired !== "object" || paired === null) {1383          return { ok: false, error: "invalid_payload" };1384        }1385        const candidate = paired as Record<string, unknown>;1386        if (1387          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1388          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1389          typeof candidate.deviceType !== "string" ||1390          typeof candidate.longTermPublicKeyHex !== "string" ||1391          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1392          (1393            candidate.signingPublicKeyHex !== undefined &&1394            (1395              typeof candidate.signingPublicKeyHex !== "string" ||1396              !/^[0-9a-f]{64}$/.test(candidate.signingPublicKeyHex)1397            )1398          ) ||1399          typeof candidate.pairedAt !== "number"1400        ) {1401          return { ok: false, error: "invalid_paired_device" };1402        }1403        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1404        return { ok: true };1405      }14061407      case "LIST_PAIRED_DEVICES": {1408        const devices = await listPairedDevicesV3();1409        return { ok: true, data: { devices } };1410      }14111412      case "UNPAIR_DEVICE": {1413        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1414        if (typeof deviceId !== "string" || !deviceId) {1415          return { ok: false, error: "invalid_payload" };1416        }1417        // Removing a device REVOKES it rather than just dropping the local1418        // row: a plain removal is undone the moment any other peer vouches it1419        // back through a manifest, which is exactly what the relay makes easy.1420        await revokeDeviceByIdV3(deviceId, await getOrCreateDeviceId());1421        return { ok: true };1422      }14231424      case "RENAME_LOCAL_DEVICE": {1425        const { name } = (msg.payload ?? {}) as { name?: string };1426        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1427        await setDeviceNameV3(name);1428        return { ok: true };1429      }14301431      // ── Relay pairing ─────────────────────────────────────────────────────1432      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1433      // session runs in the background; the SAS and the terminal result reach1434      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1435      case "START_ADOPTION_SOURCE": {1436        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1437        if (isRelayAdoptionSourceInFlight()) {1438          return { ok: false, error: "adoption_source_in_progress" };1439        }1440        try {1441          return { ok: true, data: await startRelayAdoptionSource() };1442        } catch (error) {1443          return {1444            ok: false,1445            error: error instanceof Error ? error.message : "adoption_source_failed",1446          };1447        }1448      }14491450      case "ADOPTION_SOURCE_CONFIRM": {1451        const { password, cancel } = (msg.payload ?? {}) as {1452          password?: unknown;1453          cancel?: unknown;1454        };1455        if (cancel === true) {1456          return {1457            ok: true,1458            data: await confirmRelayAdoptionSource(null),1459          };1460        }1461        if (typeof password !== "string" || password.length === 0) {1462          return { ok: false, error: "invalid_payload" };1463        }1464        return {1465          ok: true,1466          data: await confirmRelayAdoptionSource(password),1467        };1468      }14691470      case "CANCEL_ADOPTION_SOURCE": {1471        cancelRelayAdoptionSource();1472        return { ok: true };1473      }14741475      case "TRIGGER_SYNC": {1476        const payload = (msg.payload ?? {}) as {1477          reason?: "vault_change" | "foreground" | "manual";1478          force?: boolean;1479        };1480        const reason = payload.reason ?? "foreground";14811482        void triggerSyncIfReachable({ reason, force: payload.force === true });1483        return { ok: true };1484      }14851486      case "GET_SYNC_STATE": {1487        return { ok: true, data: getSyncState() };1488      }14891490      case "GET_SYNC_SETTINGS": {1491        return { ok: true, data: await getSyncSettings() };1492      }14931494      case "SET_SYNC_SETTINGS": {1495        const payload = (msg.payload ?? {}) as {1496          mode?: unknown;1497          relayUrl?: unknown;1498        };1499        try {1500          // A custom relay URL implies private mode; Peach's own relay stays1501          // public. See setRelayUrl.1502          if (payload.relayUrl !== undefined) {1503            if (typeof payload.relayUrl !== "string") {1504              return { ok: false, error: "invalid_relay_url" };1505            }1506            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1507          }1508          if (payload.mode !== undefined) {1509            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1510              return { ok: false, error: "invalid_sync_mode" };1511            }1512            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1513          }1514          return { ok: true, data: await getSyncSettings() };1515        } catch (error) {1516          return {1517            ok: false,1518            error: error instanceof Error ? error.message : "invalid_relay_url",1519          };1520        }1521      }15221523      case "GET_SYNC_ALERTS": {1524        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1525        const alerts = await getPendingSyncAlerts();1526        // The popup reads on open and acknowledges with consume:true after1527        // rendering, so a popup crash between read and render doesn't lose1528        // the alerts.1529        if (consume) await clearPendingSyncAlerts();1530        return { ok: true, data: alerts };1531      }15321533      case "GET_PENDING_VOUCHED_DEVICES": {1534        return { ok: true, data: await listPendingVouchedDevices() };1535      }1536      case "CONFIRM_VOUCHED_DEVICE": {1537        const { deviceId } = msg.payload as { deviceId: string };1538        const pending = await getPendingVouchedDevice(deviceId);1539        if (!pending) return { ok: false, error: "not_pending" };1540        await upsertPairedDeviceV3({1541          deviceId: pending.deviceId,1542          deviceName: pending.deviceName,1543          deviceType:1544            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1545          longTermPublicKeyHex: pending.longTermPublicKeyHex,1546          signingPublicKeyHex: pending.signingPublicKeyHex,1547          wsPort: pending.wsPort,1548          pairedAt: pending.pairedAt,1549          trustSource: "vouched",1550        });1551        await removePendingVouchedDevice(deviceId);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// --- Mobile platform helpers ---15771578// Android: populates the in-memory vault used by PeachAutofillService.1579async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1580  const plugin = nativePlugin<{1581    setEntries?: (args: {1582      entries: Array<{1583        id: string;1584        title: string;1585        username: string;1586        email: string;1587        password: string;1588        url: string;1589        totp: string;1590        additionalUrls: string[];1591      }>;1592    }) => Promise<void>;1593  }>("InMemoryVaultPlugin");1594  if (!plugin?.setEntries) return;1595  await plugin.setEntries({1596    entries: entries.map((e) => ({1597      id: e.id,1598      title: e.title ?? "",1599      username: e.username ?? "",1600      email: (e as VaultEntry & { email?: string }).email ?? "",1601      password: e.password ?? "",1602      url: e.url ?? "",1603      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1604      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1605    })),1606  });1607}16081609// Android: clear the autofill in-memory store on lock.1610async function clearInMemoryVault(): Promise<void> {1611  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1612  if (!plugin?.clearEntries) return;1613  await plugin.clearEntries();1614}16151616// Returns username use-counts from the vault, sorted by frequency. Each row1617// also carries the entry's email so the popup can suggest the email/username1618// pair the user has actually used together.1619function buildIdentitySuggestions(1620  entries: VaultEntry[],1621): Array<{ email: string; username: string; count: number }> {1622  const usernameCounts = new Map<string, number>();1623  const usernameEmail = new Map<string, string>();1624  for (const entry of entries) {1625    const username = entry.username ?? "";1626    const email = (entry as VaultEntry & { email?: string }).email ?? "";1627    if (!username && !email) continue;1628    const key = username || email;1629    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1630    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1631  }1632  return Array.from(usernameCounts.entries())1633    .sort((a, b) => b[1] - a[1])1634    .map(([username, count]) => ({1635      email: usernameEmail.get(username) ?? "",1636      username,1637      count,1638    }));1639}16401641/** Notify all content scripts that the vault just became available. */1642function broadcastToContentScripts(message: { type: string }): void {1643  if (!chrome.tabs?.query) return;1644  chrome.tabs.query({}, (tabs) => {1645    for (const tab of tabs) {1646      if (tab.id !== undefined) {1647        chrome.tabs.sendMessage(tab.id, message).catch(() => {1648          // Tab may not have a content script — silently ignore1649        });1650      }1651    }1652  });1653}16541655function shouldRefreshAutoLock(type: MessageType): boolean {1656  return (1657    type !== "HAS_VAULT" &&1658    type !== "IS_UNLOCKED" &&1659    type !== "GET_VAULT_STATUS" &&1660    type !== "LOCK" &&1661    type !== "UPDATE_SETTINGS" &&1662    type !== "GET_PENDING_PASSKEY" &&1663    type !== "GET_PASSKEY_PROVIDER_STATE" &&1664    type !== "DECLINE_CARD_SAVE" &&1665    type !== "IS_CARD_DECLINED"1666  );1667}16681669function isAllowedCanaryWebhookUrl(value: string): boolean {1670  try {1671    const url = new URL(value);1672    if (url.protocol !== "https:") return false;16731674    const hostname = url.hostname.toLowerCase();1675    if (1676      hostname === "localhost" ||1677      hostname.endsWith(".localhost") ||1678      isPrivateIpv4(hostname) ||1679      isPrivateIpv6(hostname)1680    ) {1681      return false;1682    }16831684    return true;1685  } catch {1686    return false;1687  }1688}16891690function isPrivateIpv4(hostname: string): boolean {1691  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1692    return true;1693  }16941695  const octets = hostname.split(".").map((part) => Number(part));1696  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1697    return false;1698  }16991700  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1701}17021703function isPrivateIpv6(hostname: string): boolean {1704  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1705  return (1706    normalized === "::1" ||1707    normalized.startsWith("fc") ||1708    normalized.startsWith("fd") ||1709    normalized.startsWith("fe80:")1710  );1711}