messages.ts

69.7 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard, getEffectiveClearSeconds } from "./clipboard";13import { getPendingSyncAlerts, clearPendingSyncAlerts } from "./sync-alerts";14import { extractDomain } from "../shared/domain";15import { 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 { buildLocalIdentity, setDeviceName as setDeviceNameV3 } from "./chirp-identity";71import {72  listPairedDevices as listPairedDevicesV3,73  removePairedDeviceById as removePairedDeviceByIdV3,74  upsertPairedDevice as upsertPairedDeviceV3,75} from "./paired-devices";7677// Compile-time E2E flag, folded to a literal by Vite's `define` (false in78// every production build — verified in the bundled output). Mirrors the79// create-path bypass in passkey.ts so the Playwright passkey smoke can enable80// the provider without a real Pro licence; the gate is fully intact for users.81declare const __PEACH_E2E_PASSKEYS__: boolean;82const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true;8384let nativeSyncRunnerBootstrapped = false;8586function unhexBytes(hex: string): Uint8Array {87  if (hex.length % 2 !== 0) throw new Error("invalid hex");88  const out = new Uint8Array(hex.length / 2);89  for (let i = 0; i < out.length; i++) {90    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);91  }92  return out;93}9495/**96 * The single Pro gate. Every gated handler calls this first; the broadcast97 * lets the popup react (navigate to the License section, highlight the98 * relevant feature). Background never touches the popup view directly —99 * the popup owns navigation. See Projects.md "Pro gate rule".100 */101async function requirePro(102  feature: ProFeature,103  trigger: "user" | "background" = "user"104): Promise<{ allowed: boolean }> {105  if (PASSKEY_E2E_PRO_BYPASS && feature === "passkeys") return { allowed: true };106  if (await isProUser()) return { allowed: true };107108  if (trigger === "user") {109    // User deliberately triggered this feature — redirect the popup immediately.110    chrome.runtime111      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })112      .catch(() => {113        // Popup may be closed — the gate signal is best-effort.114      });115  } else {116    // Background trigger (e.g. passive sync initiation) — no popup is open.117    // Queue a notice so the next popup open shows a soft banner instead of118    // silently failing.119    if (chrome.storage.session) {120      chrome.storage.session121        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })122        .catch(() => {});123    }124  }125126  return { allowed: false };127}128129// ---------------------------------------------------------------------------130// Feedback submission target. Empty disables network submission while the UI131// continues to function as a no-op (the handler returns ok:true without132// calling fetch). When set, the URL is validated by133// `isAllowedCanaryWebhookUrl` before any request.134// ---------------------------------------------------------------------------135136const FEEDBACK_ENDPOINT = "";137138// PCH-01-018: operations that irreversibly destroy or replace vault contents.139// These are gated to trusted extension-page senders in handleMessage; the140// confirmation UX otherwise lives only in the popup. Keep this in sync when141// adding new destructive handlers.142const DESTRUCTIVE_MESSAGE_TYPES: ReadonlySet<string> = new Set([143  "DESTROY_VAULT",144  "CLEAR_VAULT_ENTRIES",145  "RESTORE_VAULT_SNAPSHOT",146  "RESTORE_FROM_CODEX",147]);148149// LV-3: minimum interval between non-test canary pings per webhook+entry.150const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour151152const PRIVATE_IPV4_RANGES = [153  { prefix: "10." },154  { prefix: "127." },155  { prefix: "169.254." },156  { prefix: "192.168." },157];158159export function setupMessageHandler(): void {160  chrome.runtime.onMessage.addListener(161    (msg: unknown, sender, sendResponse) => {162      if (!isMessage(msg)) {163        sendResponse({ ok: false, error: "invalid_message" });164        return true;165      }166      handleMessage(msg, sender)167        .then(sendResponse)168        .catch((err) =>169          sendResponse({170            ok: false,171            error: err instanceof Error ? err.message : String(err),172          })173        );174      return true;175    }176  );177178  // Android: the chrome shim queues sendMessage calls until this handler is179  // registered. Without this hookup, every message hangs on Capacitor builds.180  // eslint-disable-next-line @typescript-eslint/no-explicit-any181  const reg = (globalThis as any).__peachRegisterMessageHandler;182  if (typeof reg === "function") {183    reg(async (m: unknown) => {184      if (!isMessage(m)) return { ok: false, error: "invalid_message" };185      try {186        return await handleMessage(m);187      } catch (err) {188        return {189          ok: false,190          error: err instanceof Error ? err.message : String(err),191        };192      }193    });194  }195  if (isNativePlatform()) {196    void bootstrapNativeSyncRunner();197  }198}199200async function bootstrapNativeSyncRunner(): Promise<void> {201  if (nativeSyncRunnerBootstrapped) return;202  nativeSyncRunnerBootstrapped = true;203  try {204    const { setSyncRunner, hydratePersistedSyncState } = await import("./sync-trigger");205    const { productionSyncRunner } = await import("./chirp-sync-runner");206    setSyncRunner(productionSyncRunner);207    await hydratePersistedSyncState();208  } catch (err) {209    nativeSyncRunnerBootstrapped = false;210    console.warn("[Peach] failed to bootstrap native sync runner:", err);211  }212}213214function isMessage(m: unknown): m is Message {215  return typeof m === "object" && m !== null && "type" in m;216}217218/**219 * The browser-attested origin of the page that originated this message. A web220 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),221 * so every page-driven message arrives via the content-script relay and the222 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a223 * value the page cannot forge. This is the ONLY trustworthy origin for passkey224 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.225 */226function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {227  if (sender.origin) return sender.origin;228  if (sender.url) {229    try { return new URL(sender.url).origin; } catch { return undefined; }230  }231  return undefined;232}233234// Resolves once restoreFromSession() has run, so handlers see the correct235// post-restore unlock state. entry.ts registers this BEFORE the message236// handler so the onMessage listener is added synchronously at SW startup237// (MV3 requirement) while unlock-dependent handlers still wait for restore.238let restoreReady: Promise<void> = Promise.resolve();239240/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */241export function setRestoreReady(p: Promise<unknown>): void {242  restoreReady = p.then(() => undefined, () => undefined);243}244245export async function handleMessage(246  msg: Message,247  sender: Partial<chrome.runtime.MessageSender> = {}248): Promise<MessageResponse> {249  try {250    // Wait for session-restore to finish before reading any unlock/vault state.251    // On a cold SW start the popup's first message arrives while restore is252    // still in flight; without this gate IS_UNLOCKED would report locked (a253    // spurious lock screen) and the storage reads could race. The onMessage254    // listener itself is registered synchronously (entry.ts) so this gate, not255    // listener registration, is what absorbs the cold-start window.256    await restoreReady;257    // Validate sender — only allow messages from our extension pages/scripts.258    // `sender.id` is undefined for messages originating from extension UI259    // (popup/options), which is legitimate; reject only when it is defined260    // and does not match our extension id.261    if (262      sender.id !== undefined &&263      sender.id !== chrome.runtime.id264    ) {265      return { ok: false, error: "invalid_sender" };266    }267268    // PCH-01-018: irreversible operations must originate from a trusted extension269    // page (popup/options), never from a content script. The sender.id check above270    // only proves the message came from *our* extension — a content script injected271    // into an attacker page passes it. A single XSS-class bug in the injected UI272    // would otherwise escalate to vault destruction. Extension pages carry an273    // extension-origin sender.url; content scripts carry a page URL.274    if (DESTRUCTIVE_MESSAGE_TYPES.has(msg.type)) {275      const extensionOrigin = chrome.runtime.getURL("");276      if (!sender.url?.startsWith(extensionOrigin)) {277        return { ok: false, error: "invalid_sender" };278      }279    }280281    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {282      touchAutoLock();283    }284285    switch (msg.type) {286      case "CREATE_VAULT": {287        const { password } = msg.payload as { password: string };288        // Refuse to create a vault under an empty master password — the derived289        // key would be publicly known and the at-rest AES-GCM protection void290        // (audit HIGH; the CSV-import path previously passed ""). Length/strength291        // policy lives in the onboarding UI; this is the non-negotiable floor.292        if (typeof password !== "string" || password.length === 0) {293          return { ok: false, error: "invalid_payload" };294        }295        await vault.createVault(password);296        await setupAutoLock();297        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });298        onVaultUnlocked();299        return { ok: true };300      }301      case "CREATE_VAULT_FROM_ROOT_KEY": {302        const { password, rootKeyHex } = (msg.payload ?? {}) as {303          password?: unknown;304          rootKeyHex?: unknown;305        };306        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {307          return { ok: false, error: "invalid_payload" };308        }309310        try {311          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);312          await setupAutoLock();313          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });314          onVaultUnlocked();315          return { ok: true, vaultId };316        } catch (err) {317          return { ok: false, error: err instanceof Error ? err.message : String(err) };318        }319      }320      case "UNLOCK": {321        const { password } = msg.payload as { password: string };322        const ok = await vault.unlock(password);323        if (ok) {324          // KAT: verify the WebCrypto stack is healthy before the user relies on it.325          // Runs after unlock so latency is hidden behind the vault-load time.326          const kat = await runSelfTest();327          if (!kat.ok) {328            console.error("[Peach] Crypto self-test FAILED:", kat.error);329            await vault.lock();330            return { ok: false, error: "self_test_failed" };331          }332          await setupAutoLock();333          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });334          onVaultUnlocked();335          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());336          return { ok: true };337        }338        // Distinguish corruption from wrong password so the popup can offer339        // a history-restore path instead of falsely accusing the user of340        // mistyping (M7/COR-007).341        const failure = vault.consumeLastUnlockFailureReason();342        if (failure) {343          return {344            ok: false,345            error: "vault_corrupted",346            canRestoreFromHistory: true,347          } as MessageResponse;348        }349        return { ok: false };350      }351      case "VALIDATE_RECOVERY_WORDS": {352        const { words } = msg.payload as { words: string[] };353        const invalid = findInvalidWords(words);354        return { ok: true, data: { valid: invalid.length === 0, invalid } };355      }356      case "GET_RECOVERY_WORDS": {357        // Must be unlocked and have recovery set up (vault must be v2.12+).358        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };359        // LV-4: the recovery words re-derive the ROOT KEY — the highest-360        // value secret in the vault. A session unlock (which may be hours361        // old on a shared machine) is not enough; require a fresh password362        // proof, matching the 1Password/Bitwarden pattern for revealing363        // escrow material. EXEMPTION: the create-vault / rotation confirmation364        // window (peach_recovery_pending) shows the words immediately after365        // the user authenticated, and that confirmation UI has no password to366        // resend — skip the re-auth there only.367        if (!(await isRecoveryConfirmPending())) {368          const { password } = (msg.payload ?? {}) as { password?: string };369          if (typeof password !== "string" || !password) {370            return { ok: false, error: "password_required" };371          }372          if (!(await vault.verifyMainPassword(password))) {373            return { ok: false, error: "wrong_password" };374          }375        }376        try {377          const words = await vault.getRecoveryWords();378          return { ok: true, data: words };379        } catch (e) {380          // pre-v2.12 vault that hasn't migrated381          return { ok: false, error: "recovery_not_setup" };382        }383      }384      case "RECOVER_WITH_WORDS": {385        // User has lost their password but has their 12 recovery words.386        // We: (1) validate the words, (2) re-encrypt vault with new password.387        const { words, newPassword } = msg.payload as {388          words: string[];389          newPassword: string;390        };391        const stored = await vault.loadSlotA();392        if (!stored) return { ok: false, error: "no_vault" };393        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {394          return { ok: false, error: "recovery_not_setup" };395        }396        // Unwrap the root key from the recovery escrow.397        try {398          await vault.unwrapRootKeyForRecovery(399            stored.recovery_wrapped_root_key,400            stored.recovery_nonce ?? "",401            stored.recovery_tag ?? "",402            stored.recovery_salt,403            words404          );405        } catch {406          return { ok: false, error: "invalid_recovery_words" };407        }408        // Re-key: derive fresh salt + key from new password.409        const newSalt = vault.generateSalt();410        const newKey = await vault.deriveKey(newPassword, newSalt);411        // Re-wrap root key under the new password's derived key so the same412        // recovery words continue to work after the password change.413        await vault.rewrapRootKeyForPassword(newKey, newSalt);414        // Re-encrypt vault entries with the new key.415        await vault.changePasswordWithNewKey(newSalt, newKey);416        await setupAutoLock();417        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });418        return { ok: true };419      }420      case "LOCK":421        vault.lock();422        if (isNativePlatform()) await clearInMemoryVault();423        return { ok: true };424      case "IS_UNLOCKED":425        return { ok: true, data: vault.isUnlocked() };426      case "GET_VAULT_STATUS":427        return { ok: true, unlocked: vault.isUnlocked() };428      case "HAS_VAULT":429        return { ok: true, data: await vault.hasVault() };430      case "GET_ENTRIES":431        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };432        return { ok: true, data: vault.getEntries() };433      case "ADD_ENTRY": {434        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };435        const payload = msg.payload;436        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {437          return { ok: false, error: "invalid_payload" };438        }439        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);440        return { ok: true, data: entry };441      }442      case "BATCH_ADD_ENTRIES": {443        const payload = msg.payload as { entries?: unknown } | null | undefined;444        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {445          return { ok: false, error: "invalid_payload" };446        }447        if (!Array.isArray(payload.entries)) {448          return { ok: false, error: "invalid_payload" };449        }450        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);451        return { ok: true, data: added };452      }453      case "RESTORE_ENTRIES": {454        const payload = msg.payload as455          | { entries?: unknown; mode?: unknown; settings?: unknown }456          | null457          | undefined;458        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {459          return { ok: false, error: "invalid_payload" };460        }461        if (!Array.isArray(payload.entries)) {462          return { ok: false, error: "invalid_payload" };463        }464        if (payload.mode !== "replace" && payload.mode !== "merge") {465          return { ok: false, error: "invalid_payload" };466        }467        const summary = await vault.restoreEntries(468          payload.entries as Parameters<typeof vault.restoreEntries>[0],469          payload.mode470        );471        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {472          await vault.updateSettings(payload.settings as vault.VaultSettings);473        }474        return { ok: true, data: summary };475      }476      case "CLEAR_VAULT_ENTRIES": {477        await vault.clearVaultEntries("REPLACE_ALL");478        return { ok: true };479      }480      case "GET_VAULT_HISTORY": {481        const snapshots = await vault.getVaultHistory();482        return { ok: true, data: snapshots };483      }484      case "RESTORE_VAULT_SNAPSHOT": {485        const { snapshotId } = msg.payload as { snapshotId: string };486        const result = await vault.restoreVaultSnapshot(snapshotId);487        if (!result.ok) return { ok: false, error: result.error };488        broadcastToContentScripts({ type: "VAULT_LOCKED" });489        return { ok: true };490      }491      case "COUNT_DUPLICATES": {492        return { ok: true, data: vault.countDuplicates() };493      }494      case "DEDUPLICATE_ENTRIES": {495        const removed = await vault.deduplicateEntries();496        return { ok: true, data: removed };497      }498      case "UPDATE_ENTRY": {499        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;500        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {501          return { ok: false, error: "invalid_payload" };502        }503        const { id, patch } = payload;504        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {505          return { ok: false, error: "invalid_payload" };506        }507        // Single enforcement point for the Canary Entries Pro gate. Only508        // gates the transition into a canary entry — clearing/disabling a509        // canary (`canary: undefined`) is always allowed, so existing510        // canary entries remain manageable.511        const incomingCanary = (patch as { canary?: unknown }).canary;512        if (incomingCanary && typeof incomingCanary === "object") {513          const existing = vault.getEntryById(id);514          if (!existing?.canary) {515            const gate = await requirePro("canary_entry");516            if (!gate.allowed) return { ok: false, error: "pro_required" };517          }518        }519        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);520        return { ok: true };521      }522      case "ADD_ADDITIONAL_URL": {523        const { id, url } = msg.payload as { id: string; url: string };524        const trimmed = typeof url === "string" ? url.trim() : "";525        if (!trimmed) return { ok: false, error: "url_required" };526        const existing = vault.getEntryById(id);527        if (!existing) return { ok: false, error: "entry_not_found" };528        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };529        const merged = [...(existing.additionalUrls ?? []), trimmed];530        await vault.updateEntry(id, { additionalUrls: merged });531        return { ok: true };532      }533      case "DELETE_ENTRY": {534        const { id } = msg.payload as { id: string };535        await vault.deleteEntry(id);536        return { ok: true };537      }538      case "GET_DELETED_ENTRIES":539        return { ok: true, data: vault.getDeletedEntries() };540      case "RESTORE_ENTRY": {541        const { id } = msg.payload as { id: string };542        await vault.restoreEntry(id);543        return { ok: true };544      }545      case "PURGE_ENTRY": {546        const { id } = msg.payload as { id: string };547        await vault.purgeEntry(id);548        return { ok: true };549      }550      case "PURGE_EXPIRED_TRASH": {551        const { retentionMs } = msg.payload as { retentionMs: number };552        const purged = await vault.purgeExpiredTrash(retentionMs);553        return { ok: true, data: purged };554      }555      case "SAVE_NOTE": {556        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };557        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };558        const now = Date.now();559        if (id) {560          const existing = vault.getEntryById(id);561          if (!existing) return { ok: false, error: "not_found" };562          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });563          return { ok: true, data: vault.getEntryById(id) };564        } else {565          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt566          // (EntryDraft omits both), so passing them was the only reason the567          // `as any` cast existed. Dropping them makes the call type-check.568          const entry = await vault.addEntry({569            type: "note",570            title: title || "Untitled",571            notes: body,572          });573          return { ok: true, data: entry };574        }575      }576      case "DELETE_NOTE": {577        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };578        const { id } = msg.payload as { id: string };579        await vault.deleteEntry(id);580        return { ok: true };581      }582      case "GET_NOTES": {583        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };584        const notes = vault.getEntries().filter(585          (e) => e.type === "note" && !e.deletedAt586        );587        return { ok: true, data: notes } as MessageResponse;588      }589      case "SEARCH_VAULT": {590        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };591        // AUD-002: shape-validate the payload before calling string methods.592        // A raw cast lets a malformed message crash the handler with TypeError.593        const { query } = (msg.payload ?? {}) as { query?: unknown };594        if (typeof query !== "string") {595          return { ok: false, error: "invalid_payload" };596        }597        const q = query.toLowerCase();598        const searchResults = vault.getEntries().filter(599          (e) =>600            !e.deletedAt &&601            (e.title.toLowerCase().includes(q) ||602              e.notes?.toLowerCase().includes(q) ||603              e.username?.toLowerCase().includes(q))604        );605        return { ok: true, data: searchResults } as MessageResponse;606      }607      case "AUTOFILL_QUERY": {608        if (!vault.isUnlocked()) {609          return { ok: false, error: "vault_locked" };610        }611        let { includeAll } = msg.payload as { includeAll?: boolean };612        const { domain, kind, userGesture } = msg.payload as {613          domain: string;614          kind?: "login" | "card" | "totp";615          userGesture?: boolean;616        };617        // MV-2: the vault-wide inventory (every title/username/email/url)618        // may only leave the background on an explicit user gesture — the619        // user opening the search affordance — never on passive form focus.620        // userGesture is self-declared by our own content script; the value621        // of this gate is that PASSIVE code paths (which never set it)622        // cannot ship the inventory, shrinking what a compromised page that623        // merely triggers focus events can observe.624        if (includeAll && userGesture !== true) {625          includeAll = false;626        }627        // kind="card": return saved cards as compact summaries for the628        // inline card silver platter. Cards are not domain-scoped — every629        // saved card is a candidate on every checkout page — so domain is630        // ignored when kind === "card".631        if (kind === "card") {632          const cards = vault.getEntries().filter((e) => e.type === "card");633          return {634            ok: true,635            data: cards.map((e) => ({636              id: e.id,637              title: e.cardNickname || e.title,638              cardholderName: e.cardholderName,639              last4: e.last4,640              expMonth: e.expMonth,641              expYear: e.expYear,642              network: e.network,643            })),644          };645        }646        if (kind === "totp") {647          const matches = (648            includeAll649              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")650              : vault.queryDomain(domain)651          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));652          return {653            ok: true,654            data: matches.map((e) => ({655              id: e.id,656              title: e.title,657              username: e.username,658              email: e.email,659              url: e.url,660              hasTotp: true,661            })),662          };663        }664        // The inline selector fills username+password into a form. Passkey-665        // only entries have no password to fill; sign-in for those goes666        // through the WebAuthn path instead. Filter them out everywhere so667        // the user doesn't see four "GitHub" rows that mostly do nothing.668        // Notes and cards never belonged here either.669        const matches = (670          includeAll671            ? vault672                .getEntries()673                .filter((entry) => entry.type !== "note" && entry.type !== "card")674            : vault.queryDomain(domain)675        ).filter((entry) => !isPasskeyOnly(entry));676        return {677          ok: true,678          data: matches.map((e) =>679            includeAll680              ? {681                  id: e.id,682                  title: e.title,683                  // username/email/url shipped so the inline popup's search684                  // affordance can match on them, not just titles. No secrets685                  // cross the boundary — same shape as the domain-matched686                  // response below minus hasTotp (which the search list687                  // doesn't surface).688                  username: e.username,689                  email: e.email,690                  url: e.url,691                  hasPasskey: e.passkey !== undefined,692                }693              : {694                  id: e.id,695                  title: e.title,696                  username: e.username,697                  email: e.email,698                  url: e.url,699                  hasTotp: Boolean(e.totp),700                  hasPasskey: e.passkey !== undefined,701                }702          ),703        };704      }705      case "GET_ENTRY_FOR_FILL": {706        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };707        const { id, explicitSummon } = msg.payload as {708          id: string;709          explicitSummon?: boolean;710        };711        const entry = vault.getEntryById(id);712        if (!entry) return { ok: false, error: "entry_not_found" };713        // Passkey-only entries (passkey credential, no password) cannot be714        // filled into a form — sign-in goes through the WebAuthn path. A715        // login that ALSO has a passkey is still fillable for its password.716        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };717718        // MV-1: re-validate the entry against the requesting tab's origin.719        // sender.tab.url is browser-attested — a page cannot forge it. When720        // the request does not come from a tab at all (popup surfaces use721        // GET_ENTRY_FOR_EDIT, not this), refuse.722        if (sender.tab !== undefined || sender.url !== undefined) {723          let senderDomain: string | null = null;724          try {725            const rawUrl = sender.tab?.url ?? sender.url ?? "";726            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;727          } catch {728            senderDomain = null;729          }730          if (!senderDomain) return { ok: false, error: "origin_unverified" };731732          const entryDomains = new Set<string>();733          const primary = extractDomain(entry.url ?? "");734          if (primary) entryDomains.add(primary);735          for (const extra of entry.additionalUrls ?? []) {736            const d = extractDomain(extra);737            if (d) entryDomains.add(d);738          }739740          // explicitSummon=true means the user actively picked this entry741          // from the cross-domain search affordance — an intentional742          // off-domain fill. Passive fill paths must stay domain-bound.743          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {744            // Domain mismatch — refuse silently (no oracle about which ids exist).745            return { ok: false, error: "entry_not_found" };746          }747        }748        // Strip the passkey credential AND the raw base32 TOTP seed from the749        // response. Content scripts never need either: the private key is the750        // authenticator's, and handing over the TOTP seed would let a751        // compromised content script mint valid codes indefinitely (SEV-3-C).752        // Generate the *current* 6-digit code here in the background and send753        // only that, plus the seconds left so the UI can render a countdown.754        // Also drop passwordHistory: filling needs only the *current* password.755        // Handing every past password to a content script during passive756        // autofill on an arbitrary page would widen the blast radius of a757        // compromised page far beyond the one credential being filled.758        const {759          passkey: _strippedPasskey,760          totp: seed,761          totpAlgorithm,762          totpDigits,763          totpPeriod,764          passwordHistory: _ph,765          ...safeEntry766        } = entry;767        let totpCode: string | undefined;768        let totpRemaining: number | undefined;769        if (seed) {770          try {771            // PCH-01-019: honour stored algorithm/digits/period (defaults apply772            // when these are undefined, i.e. legacy bare-seed entries).773            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);774            totpCode = generated.code;775            totpRemaining = generated.remaining;776          } catch {777            totpCode = undefined;778          }779        }780        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };781      }782      // Trusted full-entry fetch for Peach's own inline-popup surfaces that783      // genuinely need the raw TOTP seed: the edit form (which re-saves the784      // seed and would otherwise wipe it) and nothing else. Unlike785      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside786      // the inline popup, never during passive autofill on an arbitrary page.787      // The passkey credential is still stripped — the edit form never touches it.788      case "GET_ENTRY_FOR_EDIT": {789        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };790        const { id, explicitSummon } = msg.payload as {791          id: string;792          explicitSummon?: boolean;793        };794        const entry = vault.getEntryById(id);795        if (!entry) return { ok: false, error: "entry_not_found" };796797        // PCH-01-006: re-validate the browser-attested sender origin, mirroring798        // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and799        // full password history — at least as sensitive as the fill response — so800        // the boundary must be enforced here, not only by UI reachability. Today801        // the sole caller is the popup (no sender.tab, so this is a structural802        // no-op), but a future tab-context caller or an id leak would otherwise803        // inherit a full-credential oracle. Unlike the fill path we SKIP (not804        // refuse) when no sender domain resolves, to keep the popup caller working.805        if (sender.tab !== undefined || sender.url !== undefined) {806          let senderDomain: string | null = null;807          try {808            const rawUrl = sender.tab?.url ?? sender.url ?? "";809            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;810          } catch {811            senderDomain = null;812          }813          if (senderDomain) {814            const entryDomains = new Set<string>();815            const primary = extractDomain(entry.url ?? "");816            if (primary) entryDomains.add(primary);817            for (const extra of entry.additionalUrls ?? []) {818              const d = extractDomain(extra);819              if (d) entryDomains.add(d);820            }821            if (explicitSummon !== true && !entryDomains.has(senderDomain)) {822              return { ok: false, error: "entry_not_found" }; // no id oracle823            }824          }825        }826827        const { passkey: _passkey, ...safeEntry } = entry;828        return { ok: true, data: safeEntry };829      }830      case "COPY": {831        // AUD-002: shape-validate the payload before passing to the clipboard832        // helper. A raw cast lets a malformed message reach the clipboard API833        // with a non-string and throw.834        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {835          text?: unknown;836          label?: unknown;837          alreadyWritten?: unknown;838        };839        if (typeof text !== "string" || typeof label !== "string") {840          return { ok: false, error: "invalid_payload" };841        }842        await copyToClipboard(text, label, Boolean(alreadyWritten));843        return { ok: true, clearSeconds: getEffectiveClearSeconds() };844      }845      case "CHECK_ALL_BREACHES": {846        const allEntries = vault.getEntries();847        const results: Record<string, number> = {};848        for (const entry of allEntries) {849          if (entry.type === "note") continue;850          if (!entry.password) continue;851          results[entry.id] = await vault.checkBreach(entry.password);852          // Small delay — be a good citizen to the HIBP API853          await new Promise((r) => setTimeout(r, 200));854        }855        // Persist any non-zero counts back to entries856        for (const [id, count] of Object.entries(results)) {857          const entry = vault.getEntryById(id);858          if (entry && (entry.breach ?? 0) !== count) {859            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });860          }861        }862        return { ok: true, data: results };863      }864      case "GET_SETTINGS":865        return { ok: true, data: await vault.ensureSettingsLoaded() };866      case "UPDATE_SETTINGS": {867        const patch = msg.payload;868        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {869          return { ok: false, error: "invalid_payload" };870        }871        await vault.updateSettings(patch as vault.VaultSettings);872        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {873          await setupAutoLock();874          if (vault.isUnlocked()) touchAutoLock();875        }876        return { ok: true };877      }878      case "GET_PENDING_PASSKEY":879        return { ok: true, data: await getPendingPasskeyRequest() };880      case "APPROVE_PASSKEY": {881        const { requestId } = msg.payload as { requestId: number };882        await resolvePendingPasskeyRequest(requestId, true);883        return { ok: true };884      }885      case "DENY_PASSKEY": {886        const { requestId } = msg.payload as { requestId: number };887        await resolvePendingPasskeyRequest(requestId, false);888        return { ok: true };889      }890      case "GET_PASSKEY_PROVIDER_STATE":891        return { ok: true, data: await getPasskeyProviderState() };892      case "SET_PASSKEY_PROVIDER_ENABLED": {893        const { enabled } = msg.payload as { enabled: boolean };894        // Disabling is always free; gating fires only when a free user is895        // trying to turn passkey interception on.896        if (enabled) {897          const gate = await requirePro("passkeys");898          if (!gate.allowed) return { ok: false, error: "pro_required" };899        }900        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };901      }902      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS903      // endpoint. Intentional product behavior — users configure their own904      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private905      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-906      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to907      // users that the entry title leaves the device when the canary fires.908      case "FIRE_CANARY_PING": {909        // Canary alert fires unconditionally for any entry with canary: true.910        // The Pro gate only governs creation/flagging of canary entries; once911        // an entry is flagged, the alert path is a security property and must912        // never be license-gated.913        const { webhookUrl, entryTitle, trigger } = msg.payload as {914          webhookUrl: string;915          entryTitle: string;916          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";917        };918        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {919          return { ok: false, error: "invalid_webhook_url" };920        }921        // LV-3: debounce non-test pings per (webhook, entry) so a page that922        // strobes focus/fill events can't turn the canary into a request923        // firehose at the user's endpoint. Test pings are exempt — they are924        // explicit user clicks in the settings UI and are awaited for925        // feedback. The FIRST ping in a window always goes out, so the926        // dead-man's-switch property (canary fires on access) is preserved;927        // only repeats within the window are coalesced.928        if (trigger !== "test") {929          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;930          const stored = await chrome.storage.local.get(rlKey);931          const last = (stored as Record<string, unknown>)[rlKey];932          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {933            return { ok: true, data: { rateLimited: true } };934          }935          await chrome.storage.local.set({ [rlKey]: Date.now() });936        }937        const body = JSON.stringify({938          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",939          entry: entryTitle,940          trigger,941          timestamp: new Date().toISOString(),942          source: "peach-extension",943        });944        if (trigger === "test") {945          // Permitted outbound fetch: user-configured canary alert endpoint946          // (validated by isAllowedCanaryWebhookUrl above). This is the947          // only non-HIBP outbound call in the extension — see948          // Projects.md §3.7. Test pings are awaited so the UI can show949          // success/failure.950          try {951            const res = await fetch(webhookUrl, {952              method: "POST",953              headers: { "Content-Type": "application/json" },954              body,955            });956            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };957          } catch (err) {958            return { ok: false, error: err instanceof Error ? err.message : "network_error" };959          }960        }961        // Non-test triggers are fire-and-forget962        fetch(webhookUrl, {963          method: "POST",964          headers: { "Content-Type": "application/json" },965          body,966        }).catch(() => {});967        return { ok: true };968      }969      case "ACTIVATE_LICENSE": {970        const { key } = msg.payload as { key: string };971        const licenseInfo = await activateLicense(key);972        return { ok: true, data: licenseInfo };973      }974      case "GET_LICENSE": {975        const licenseInfo = await getLicenseInfo();976        return { ok: true, data: licenseInfo };977      }978      case "GET_LICENSE_KEY": {979        const key = await getLicenseKey();980        return { ok: true, data: key };981      }982      case "DEACTIVATE_LICENSE": {983        await deactivateLicense();984        return { ok: true };985      }986      case "SHOULD_PLAY_CELEBRATION": {987        const should = await shouldPlayCelebration();988        return { ok: true, data: should };989      }990      case "MARK_CELEBRATION_PLAYED": {991        await markCelebrationPlayed();992        return { ok: true };993      }994      case "GET_CODEX_VAULT_DATA": {995        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the996        // popup navigates to the License section without further coordination.997        const gate = await requirePro("codex");998        if (!gate.allowed) return { ok: false, error: "pro_required" };999        return await handleGetCodexVaultData();1000      }1001      case "ESTIMATE_CODEX_PAGES": {1002        const gate = await requirePro("codex");1003        if (!gate.allowed) return { ok: false, error: "pro_required" };1004        return await handleEstimateCodexPages();1005      }1006      case "RESTORE_FROM_CODEX": {1007        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1008        // be able to restore a vault that was printed by a Pro user.1009        // DO NOT add a Pro gate here.1010        const payload = msg.payload as CodexRestorePayload;1011        return await handleRestoreFromCodex(payload);1012      }1013      case "OPEN_PRO_GATE": {1014        // Content script requests: open popup and navigate to License section.1015        const { feature } = (msg.payload ?? {}) as { feature?: string };1016        if (chrome.storage.session) {1017          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1018        }1019        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1020        return { ok: true };1021      }1022      case "OPEN_POPUP": {1023        // Content script asks to open the trusted extension popup — used by the1024        // inline locked bubble so the master password is entered in the popup,1025        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1026        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1027        // toolbar icon. The badge already signals Peach needs attention.1028        //1029        // Set a session flag so the popup knows it was opened for inline unlock1030        // and should close itself once the vault is unlocked (returning the user1031        // to the inline autofill selector on the page).1032        if (chrome.storage.session) {1033          await chrome.storage.session.set({ peach_inline_unlock: true });1034        }1035        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1036        return { ok: true };1037      }1038      case "GET_IDENTITIES": {1039        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1040        return { ok: true, data: vault.getIdentities() };1041      }1042      case "TOUCH_AUTO_LOCK": {1043        // touchAutoLock() is already called by shouldRefreshAutoLock above;1044        // this case just gives the popup a typed message to keep the session alive.1045        return { ok: true };1046      }1047      case "GET_ADVANCED_HEALTH_REPORT": {1048        const gate = await requirePro("advanced_health");1049        if (!gate.allowed) return { ok: false, error: "pro_required" };1050        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1051        const report = await buildAdvancedHealthReport(vault.getEntries());1052        return { ok: true, data: report };1053      }1054      case "IS_DURESS_ENABLED": {1055        const enabled = await vault.isDuressEnabled();1056        return { ok: true, data: enabled };1057      }1058      case "SETUP_DURESS": {1059        // Single enforcement point for the Duress Vault Pro gate. Free users1060        // who somehow reach this handler are rejected here; the popup also1061        // pre-checks isPro() to avoid showing the setup form to free users,1062        // but server-side is the actual security boundary.1063        const gate = await requirePro("duress_vault");1064        if (!gate.allowed) return { ok: false, error: "pro_required" };1065        // MV3 service workers restart after inactivity, losing the in-memory1066        // derived key. Detect this before calling setupDuress so the popup1067        // can show a meaningful prompt to re-lock and re-unlock.1068        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1069        const { duressPassword } = msg.payload as { duressPassword: string };1070        await vault.setupDuress(duressPassword);1071        return { ok: true };1072      }1073      case "DISABLE_DURESS": {1074        await vault.disableDuress();1075        return { ok: true };1076      }1077      case "VERIFY_MAIN_PASSWORD": {1078        const { password } = msg.payload as { password: string };1079        const ok = await vault.verifyMainPassword(password);1080        return { ok: true, data: ok };1081      }1082      case "CHANGE_PASSWORD": {1083        const { currentPassword, newPassword } = msg.payload as {1084          currentPassword: string;1085          newPassword: string;1086        };1087        const changed = await vault.changePassword(currentPassword, newPassword);1088        return changed1089          ? { ok: true }1090          : { ok: false, error: "incorrect_current_password" };1091      }1092      case "GET_SITE_PASSWORD_POLICY": {1093        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1094        if (!tab?.id) return { ok: true, data: null };1095        try {1096          const response = await chrome.tabs.sendMessage(tab.id, {1097            type: "GET_SITE_PASSWORD_POLICY",1098          });1099          return (response as MessageResponse) ?? { ok: true, data: null };1100        } catch {1101          return { ok: true, data: null };1102        }1103      }1104      case "RECORD_MANUAL_SUMMON": {1105        const { domain } = msg.payload as { domain: string };1106        const settings = vault.getSettings();1107        const existing = settings.manualSummonDomains?.[domain];1108        const now = Date.now();1109        await vault.updateSettings({1110          manualSummonDomains: {1111            ...settings.manualSummonDomains,1112            [domain]: {1113              firstSummonedAt: existing?.firstSummonedAt ?? now,1114              summonCount: (existing?.summonCount ?? 0) + 1,1115              lastSummonedAt: now,1116            },1117          },1118        });1119        return { ok: true };1120      }1121      case "DECLINE_CARD_SAVE": {1122        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1123        await vault.declineCardSaveOffer(last4, expMonth, expYear);1124        return { ok: true };1125      }1126      case "IS_CARD_DECLINED": {1127        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1128        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1129        return { ok: true, data: declined };1130      }1131      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1132        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1133          rpId?: string;1134          rpName?: string;1135          userName?: string;1136          userDisplayName?: string;1137        };1138        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1139        return await initiateFirefoxPasskeyCreate({1140          rpId,1141          rpName: rpName ?? rpId,1142          userName,1143          userDisplayName,1144        });1145      }11461147      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1148        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1149        if (!payload) return { ok: false, error: "missing_payload" };1150        return await completeFirefoxPasskeyCreate(payload);1151      }11521153      case "PASSKEY_OFFER_DECLINE": {1154        const { domain } = (msg.payload ?? {}) as { domain?: string };1155        if (!domain) return { ok: false, error: "domain_required" };1156        await recordPasskeyOfferDecline(domain);1157        return { ok: true };1158      }11591160      case "GET_PASSKEY_OFFER_DECLINED": {1161        const { domain } = (msg.payload ?? {}) as { domain?: string };1162        if (!domain) return { ok: false, error: "domain_required" };1163        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1164      }11651166      case "PASSKEY_HAS_CREDENTIALS": {1167        const payload = msg.payload as {1168          rpId?: string;1169          allowCredentials?: Array<{ id: string; type?: string }>;1170        } | undefined;1171        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1172        return await handlePasskeyHasCredentials({1173          rpId: payload.rpId,1174          allowCredentials: payload.allowCredentials ?? [],1175        }, attestedSenderOrigin(sender));1176      }11771178      case "PASSKEY_CREATE": {1179        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1180        if (!payload?.rpId || !payload?.userName) {1181          return { ok: false, error: "rpid_and_username_required" };1182        }1183        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1184      }11851186      case "PASSKEY_GET": {1187        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1188        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1189        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1190      }11911192      case "PASSKEY_AUTH_RESPONSE": {1193        const { requestId, approved } = (msg.payload ?? {}) as {1194          requestId?: string | number;1195          approved?: boolean;1196        };1197        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1198          return { ok: false, error: 'requestId and approved required' };1199        }1200        await resolvePendingPasskeyRequest(Number(requestId), approved);1201        return { ok: true };1202      }12031204      case "GET_PASSKEY_FOR_DOMAIN": {1205        const { domain } = (msg.payload ?? {}) as { domain?: string };1206        if (!domain) return { ok: false, error: "domain_required" };1207        // Scope to the caller's own origin: a page may only ask about passkeys1208        // for a domain it actually owns, so an arbitrary page cannot enumerate1209        // which sites the user holds passkeys for or read the username (audit MEDIUM).1210        const origin = attestedSenderOrigin(sender);1211        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1212        if (!vault.isUnlocked()) return { ok: true, data: null };1213        const match = vault1214          .getEntries()1215          .find((entry) => entry.passkey?.rpId === domain);1216        if (!match || !match.passkey) return { ok: true, data: null };1217        // Slim shape — only the fields State 11 needs. Never expose private1218        // key material, even though this is locked behind isUnlocked.1219        return {1220          ok: true,1221          data: {1222            rpId: match.passkey.rpId,1223            userName: match.passkey.userName,1224            browser: match.passkey.browser,1225          },1226        };1227      }12281229      case "DESTROY_VAULT": {1230        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1231        // storage.local.clear() wipes every Peach key (slots, settings, license,1232        // onboarded flag, history, sync state, declined cards, recall, etc.);1233        // session.clear() wipes pending passkey requests + pro-notice queues.1234        // Caller (Panic.tsx) handles UI navigation back to onboarding.1235        //1236        // The Pro license is the one thing that must survive: the user paid for1237        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1238        // Capture it before the clear and restore it after. peach_pro_celebrated1239        // rides along so the Pro celebration doesn't replay on the next unlock.1240        const preserved = await chrome.storage.local.get([1241          "peach_license",1242          "peach_pro_celebrated",1243        ]);1244        vault.lock();1245        await storageClear();1246        await vault.clearVaultHistory();1247        const toRestore: Record<string, unknown> = {};1248        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1249        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1250        if (Object.keys(toRestore).length > 0) {1251          await chrome.storage.local.set(toRestore);1252        }1253        if (chrome.storage.session) {1254          await chrome.storage.session.clear();1255        }1256        return { ok: true };1257      }12581259      case "SUBMIT_FEEDBACK": {1260        const { category, message, version, browser } = msg.payload as {1261          category: string;1262          message: string;1263          version: string;1264          browser: string;1265        };1266        if (!message.trim()) return { ok: false, error: "message_empty" };1267        if (!FEEDBACK_ENDPOINT) return { ok: true };1268        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1269          return { ok: false, error: "invalid_feedback_endpoint" };1270        }1271        try {1272          const res = await fetch(FEEDBACK_ENDPOINT, {1273            method: "POST",1274            headers: { "Content-Type": "application/json" },1275            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1276          });1277          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1278        } catch (err) {1279          return { ok: false, error: err instanceof Error ? err.message : "network_error" };1280        }1281      }1282      // Android-only: biometric unlock with pre-derived key.1283      case "UNLOCK_WITH_KEY": {1284        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1285        if (!isNativePlatform()) {1286          return { ok: false, error: "desktop_only_uses_password" };1287        }1288        try {1289          const result = await vault.unlockWithKey(masterKeyHex);1290          if (result.ok) {1291            onVaultUnlocked();1292            await publishInMemoryVault(result.entries);1293          }1294          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1295        } catch {1296          return { ok: false, error: "invalid_key" };1297        }1298      }1299      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1300      case "GET_DERIVED_KEY": {1301        if (!isNativePlatform()) {1302          return { ok: false, error: "android_only" };1303        }1304        if (!vault.isUnlocked()) {1305          return { ok: false, error: "vault_locked" };1306        }1307        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1308      }1309      case "GET_IDENTITY_SUGGESTIONS": {1310        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1311        const entries = vault.getEntries();1312        const suggestions = buildIdentitySuggestions(entries);1313        return { ok: true, data: { suggestions } };1314      }1315      case "POPULATE_INLINE_VAULT": {1316        if (!isNativePlatform()) return { ok: false };1317        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1318        const entries = vault.getEntries();1319        await publishInMemoryVault(entries);1320        return { ok: true };1321      }1322      case "ML_INIT":1323        return { ok: true };13241325      case "ML_PREDICT_BATCH": {1326        // AUD-002: shape-validate before forwarding to the ML helper.1327        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1328        if (!Array.isArray(featuresArray)) {1329          return { ok: false, error: "invalid_payload" };1330        }1331        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1332      }13331334      // ── Chirp Sync (v3) ───────────────────────────────────────────────1335      // Returns the public-facing local identity needed by the popup to1336      // drive Phase-1 audio pairing. The private long-term key never1337      // leaves the background.1338      case "CHIRP_GET_LOCAL_IDENTITY": {1339        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1340        // Pro license from an already-Pro peer (at least one device must be Pro).1341        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1342        // Identity derives from the stable root key, not the password-derived1343        // key, so pairing survives a master-password change (SEV-2-B).1344        const masterKeyHex = vault.getRootKeyHex();1345        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1346        const masterKey = unhexBytes(masterKeyHex);1347        try {1348          const identity = await buildLocalIdentity(masterKey);1349          // If this device is Pro, advertise the signed license so the peer can1350          // activate it after SAS confirmation — pairing carries Pro across.1351          if (await isProUser()) {1352            const license = await getLicenseKey();1353            if (license) (identity as { license?: string }).license = license;1354          }1355          return { ok: true, data: identity };1356        } finally {1357          masterKey.fill(0);1358        }1359      }13601361      case "CHIRP_GET_ADOPTION_MATERIAL": {1362        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1363        const rootKeyHex = vault.getRootKeyHex();1364        if (!rootKeyHex) return { ok: false, error: "vault_locked" };1365        const rootKeyBytes = unhexBytes(rootKeyHex);1366        try {1367          const data: { rootKeyHex: string; vaultId: string; license?: string } = {1368            rootKeyHex,1369            vaultId: await computeVaultId(rootKeyBytes),1370          };1371          if (await isProUser()) {1372            const license = await getLicenseKey();1373            if (license) data.license = license;1374          }1375          return { ok: true, data };1376        } finally {1377          rootKeyBytes.fill(0);1378        }1379      }13801381      case "CHIRP_COMPLETE_PAIRING": {1382        // Not Pro-gated — see CHIRP_GET_LOCAL_IDENTITY.1383        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1384        const paired = (msg.payload as { paired?: unknown })?.paired;1385        if (typeof paired !== "object" || paired === null) {1386          return { ok: false, error: "invalid_payload" };1387        }1388        const candidate = paired as Record<string, unknown>;1389        if (1390          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1391          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1392          typeof candidate.deviceType !== "string" ||1393          typeof candidate.longTermPublicKeyHex !== "string" ||1394          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1395          (1396            candidate.signingPublicKeyHex !== undefined &&1397            (1398              typeof candidate.signingPublicKeyHex !== "string" ||1399              !/^[0-9a-f]{64}$/.test(candidate.signingPublicKeyHex)1400            )1401          ) ||1402          typeof candidate.pairedAt !== "number"1403        ) {1404          return { ok: false, error: "invalid_paired_device" };1405        }1406        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1407        return { ok: true };1408      }14091410      case "CHIRP_LIST_PAIRED_DEVICES": {1411        const devices = await listPairedDevicesV3();1412        return { ok: true, data: { devices } };1413      }14141415      case "CHIRP_UNPAIR_DEVICE": {1416        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1417        if (typeof deviceId !== "string" || !deviceId) {1418          return { ok: false, error: "invalid_payload" };1419        }1420        await removePairedDeviceByIdV3(deviceId);1421        return { ok: true };1422      }14231424      case "CHIRP_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      // ── Desktop helper code pairing (peach-sync) ──────────────────────────1432      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1433      // pairing runs in the background; the SAS and the terminal result reach the1434      // popup as CODE_PAIR_SAS / CODE_PAIR_RESULT pushes.1435      case "PAIR_WITH_CODE": {1436        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1437        const { code } = (msg.payload ?? {}) as { code?: string };1438        if (typeof code !== "string" || !/\d/.test(code)) {1439          return { ok: false, error: "invalid_payload" };1440        }1441        const { startCodePairing, isCodePairingInFlight } = await import(1442          "./code-pairing-bg"1443        );1444        if (isCodePairingInFlight()) return { ok: false, error: "pairing_in_progress" };1445        startCodePairing(code);1446        return { ok: true };1447      }14481449      case "CODE_PAIR_CONFIRM": {1450        const { confirmed } = (msg.payload ?? {}) as { confirmed?: boolean };1451        const { resolveCodePairingConfirm } = await import("./code-pairing-bg");1452        resolveCodePairingConfirm(confirmed === true);1453        return { ok: true };1454      }14551456      case "TRIGGER_SYNC": {1457        const payload = (msg.payload ?? {}) as {1458          reason?: "vault_change" | "foreground" | "manual" | "mdns";1459          force?: boolean;1460          deviceId?: string;1461          discoveredIp?: string;1462          discoveredPort?: number;1463        };1464        const reason = payload.reason ?? "foreground";14651466        // mDNS discovery delivers a fresh (ip, port) resolved by the native1467        // side. Update the cached address before the sync runner tries to1468        // connect — avoids a subnet probe on the very next round.1469        if (1470          reason === "mdns" &&1471          typeof payload.deviceId === "string" &&1472          typeof payload.discoveredIp === "string"1473        ) {1474          const { findPairedDeviceById, setLastKnownIp } = await import("./paired-devices");1475          const device = await findPairedDeviceById(payload.deviceId);1476          if (device?.longTermPublicKeyHex) {1477            await setLastKnownIp(device.longTermPublicKeyHex, payload.discoveredIp).catch(() => undefined);1478          }1479        }14801481        const { triggerSyncIfReachable } = await import("./sync-trigger");1482        void triggerSyncIfReachable({ reason, force: payload.force === true });1483        return { ok: true };1484      }14851486      case "GET_SYNC_STATE": {1487        const { getSyncState } = await import("./sync-trigger");1488        return { ok: true, data: getSyncState() };1489      }14901491      case "GET_SYNC_ALERTS": {1492        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1493        const alerts = await getPendingSyncAlerts();1494        // The popup reads on open and acknowledges with consume:true after1495        // rendering, so a popup crash between read and render doesn't lose1496        // the alerts.1497        if (consume) await clearPendingSyncAlerts();1498        return { ok: true, data: alerts };1499      }15001501      case "GET_PENDING_VOUCHED_DEVICES": {1502        return { ok: true, data: await listPendingVouchedDevices() };1503      }1504      case "CONFIRM_VOUCHED_DEVICE": {1505        const { deviceId } = msg.payload as { deviceId: string };1506        const pending = await getPendingVouchedDevice(deviceId);1507        if (!pending) return { ok: false, error: "not_pending" };1508        await upsertPairedDeviceV3({1509          deviceId: pending.deviceId,1510          deviceName: pending.deviceName,1511          deviceType:1512            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1513          longTermPublicKeyHex: pending.longTermPublicKeyHex,1514          signingPublicKeyHex: pending.signingPublicKeyHex,1515          wsPort: pending.wsPort,1516          pairedAt: pending.pairedAt,1517          trustSource: "vouched",1518        });1519        await removePendingVouchedDevice(deviceId);1520        return { ok: true };1521      }1522      case "REJECT_VOUCHED_DEVICE": {1523        const { deviceId } = msg.payload as { deviceId: string };1524        await removePendingVouchedDevice(deviceId);1525        return { ok: true };1526      }1527      case "ROTATE_SYNC_IDENTITY": {1528        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1529        const result = await vault.rotateSyncIdentity();1530        return result.ok ? { ok: true } : { ok: false, error: result.error };1531      }15321533      default:1534        return { ok: false, error: "unknown_message_type" };1535    }1536  } catch (err) {1537    return {1538      ok: false,1539      error: err instanceof Error ? err.message : "operation_failed",1540    };1541  }1542}15431544// --- Mobile platform helpers ---15451546// Android: populates the in-memory vault used by PeachAutofillService.1547async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1548  const plugin = nativePlugin<{1549    setEntries?: (args: {1550      entries: Array<{1551        id: string;1552        title: string;1553        username: string;1554        email: string;1555        password: string;1556        url: string;1557        totp: string;1558        additionalUrls: string[];1559      }>;1560    }) => Promise<void>;1561  }>("InMemoryVaultPlugin");1562  if (!plugin?.setEntries) return;1563  await plugin.setEntries({1564    entries: entries.map((e) => ({1565      id: e.id,1566      title: e.title ?? "",1567      username: e.username ?? "",1568      email: (e as VaultEntry & { email?: string }).email ?? "",1569      password: e.password ?? "",1570      url: e.url ?? "",1571      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1572      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1573    })),1574  });1575}15761577// Android: clear the autofill in-memory store on lock.1578async function clearInMemoryVault(): Promise<void> {1579  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1580  if (!plugin?.clearEntries) return;1581  await plugin.clearEntries();1582}15831584// Returns username use-counts from the vault, sorted by frequency. Each row1585// also carries the entry's email so the popup can suggest the email/username1586// pair the user has actually used together.1587function buildIdentitySuggestions(1588  entries: VaultEntry[],1589): Array<{ email: string; username: string; count: number }> {1590  const usernameCounts = new Map<string, number>();1591  const usernameEmail = new Map<string, string>();1592  for (const entry of entries) {1593    const username = entry.username ?? "";1594    const email = (entry as VaultEntry & { email?: string }).email ?? "";1595    if (!username && !email) continue;1596    const key = username || email;1597    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1598    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1599  }1600  return Array.from(usernameCounts.entries())1601    .sort((a, b) => b[1] - a[1])1602    .map(([username, count]) => ({1603      email: usernameEmail.get(username) ?? "",1604      username,1605      count,1606    }));1607}16081609/** Notify all content scripts that the vault just became available. */1610function broadcastToContentScripts(message: { type: string }): void {1611  if (!chrome.tabs?.query) return;1612  chrome.tabs.query({}, (tabs) => {1613    for (const tab of tabs) {1614      if (tab.id !== undefined) {1615        chrome.tabs.sendMessage(tab.id, message).catch(() => {1616          // Tab may not have a content script — silently ignore1617        });1618      }1619    }1620  });1621}16221623function shouldRefreshAutoLock(type: MessageType): boolean {1624  return (1625    type !== "HAS_VAULT" &&1626    type !== "IS_UNLOCKED" &&1627    type !== "GET_VAULT_STATUS" &&1628    type !== "LOCK" &&1629    type !== "UPDATE_SETTINGS" &&1630    type !== "GET_PENDING_PASSKEY" &&1631    type !== "GET_PASSKEY_PROVIDER_STATE" &&1632    type !== "DECLINE_CARD_SAVE" &&1633    type !== "IS_CARD_DECLINED" &&1634    type !== "SUBMIT_FEEDBACK"1635  );1636}16371638function isAllowedCanaryWebhookUrl(value: string): boolean {1639  try {1640    const url = new URL(value);1641    if (url.protocol !== "https:") return false;16421643    const hostname = url.hostname.toLowerCase();1644    if (1645      hostname === "localhost" ||1646      hostname.endsWith(".localhost") ||1647      isPrivateIpv4(hostname) ||1648      isPrivateIpv6(hostname)1649    ) {1650      return false;1651    }16521653    return true;1654  } catch {1655    return false;1656  }1657}16581659function isPrivateIpv4(hostname: string): boolean {1660  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1661    return true;1662  }16631664  const octets = hostname.split(".").map((part) => Number(part));1665  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1666    return false;1667  }16681669  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1670}16711672function isPrivateIpv6(hostname: string): boolean {1673  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1674  return (1675    normalized === "::1" ||1676    normalized.startsWith("fc") ||1677    normalized.startsWith("fd") ||1678    normalized.startsWith("fe80:")1679  );1680}