messages.ts

69.0 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard, getEffectiveClearSeconds } from "./clipboard";13import { getPendingSyncAlerts, clearPendingSyncAlerts } from "./sync-alerts";14import { extractDomain } from "../shared/domain";15import {16  getPendingVouchedDevice,17  listPendingVouchedDevices,18  removePendingVouchedDevice,19} from "./pending-vouched-devices";20import { isRecoveryConfirmPending } from "./recovery-pending";21import { setupAutoLock, touchAutoLock } from "./alarms";22import { runSelfTest } from "./self-test";23import * as vault from "./vault";24import {25  handleEstimateCodexPages,26  handleGetCodexVaultData,27  handleRestoreFromCodex,28} from "./codex-handlers";29import type { CodexRestorePayload } from "../shared/codex-types";30import {31  activateLicense,32  deactivateLicense,33  getLicenseInfo,34  getLicenseKey,35  isProUser,36  markCelebrationPlayed,37  shouldPlayCelebration,38} from "./license";39import {40  completeFirefoxPasskeyCreate,41  getPasskeyProviderState,42  getPendingPasskeyRequest,43  handleFirefoxPasskeyCreate,44  handleFirefoxPasskeyGet,45  handlePasskeyHasCredentials,46  initiateFirefoxPasskeyCreate,47  isPasskeyOfferDeclined,48  onVaultUnlocked,49  recordPasskeyOfferDecline,50  resolvePendingPasskeyRequest,51  setPasskeyProviderEnabled,52} from "./passkey";53import { buildAdvancedHealthReport } from "./health";54import { storageClear } from "../shared/storage";55import { findInvalidWords } from "../shared/recovery-words";56import type {57  Message,58  MessageResponse,59  MessageType,60  ProFeature,61  VaultEntry,62} from "../shared/types";63import { isPasskeyOnly } from "../shared/types";64import { generateTOTP } from "../crypto/totp";65import { isValidRpId } from "../shared/passkey-utils";66import { isNativePlatform, nativePlugin } from "../shared/native";67import { predictBatch as mlPredictBatch } from "./ml";68import type { MLFieldFeatures } from "../shared/ml";69import { buildLocalIdentity, setDeviceName as setDeviceNameV3 } from "./chirp-identity";70import {71  listPairedDevices as listPairedDevicesV3,72  removePairedDeviceById as removePairedDeviceByIdV3,73  upsertPairedDevice as upsertPairedDeviceV3,74} from "./paired-devices";7576// Compile-time E2E flag, folded to a literal by Vite's `define` (false in77// every production build — verified in the bundled output). Mirrors the78// create-path bypass in passkey.ts so the Playwright passkey smoke can enable79// the provider without a real Pro licence; the gate is fully intact for users.80declare const __PEACH_E2E_PASSKEYS__: boolean;81const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true;8283let nativeSyncRunnerBootstrapped = false;8485function unhexBytes(hex: string): Uint8Array {86  if (hex.length % 2 !== 0) throw new Error("invalid hex");87  const out = new Uint8Array(hex.length / 2);88  for (let i = 0; i < out.length; i++) {89    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);90  }91  return out;92}9394/**95 * The single Pro gate. Every gated handler calls this first; the broadcast96 * lets the popup react (navigate to the License section, highlight the97 * relevant feature). Background never touches the popup view directly —98 * the popup owns navigation. See Projects.md "Pro gate rule".99 */100async function requirePro(101  feature: ProFeature,102  trigger: "user" | "background" = "user"103): Promise<{ allowed: boolean }> {104  if (PASSKEY_E2E_PRO_BYPASS && feature === "passkeys") return { allowed: true };105  if (await isProUser()) return { allowed: true };106107  if (trigger === "user") {108    // User deliberately triggered this feature — redirect the popup immediately.109    chrome.runtime110      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })111      .catch(() => {112        // Popup may be closed — the gate signal is best-effort.113      });114  } else {115    // Background trigger (e.g. passive sync initiation) — no popup is open.116    // Queue a notice so the next popup open shows a soft banner instead of117    // silently failing.118    if (chrome.storage.session) {119      chrome.storage.session120        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })121        .catch(() => {});122    }123  }124125  return { allowed: false };126}127128// ---------------------------------------------------------------------------129// Feedback submission target. Empty disables network submission while the UI130// continues to function as a no-op (the handler returns ok:true without131// calling fetch). When set, the URL is validated by132// `isAllowedCanaryWebhookUrl` before any request.133// ---------------------------------------------------------------------------134135const FEEDBACK_ENDPOINT = "";136137// PCH-01-018: operations that irreversibly destroy or replace vault contents.138// These are gated to trusted extension-page senders in handleMessage; the139// confirmation UX otherwise lives only in the popup. Keep this in sync when140// adding new destructive handlers.141const DESTRUCTIVE_MESSAGE_TYPES: ReadonlySet<string> = new Set([142  "DESTROY_VAULT",143  "CLEAR_VAULT_ENTRIES",144  "RESTORE_VAULT_SNAPSHOT",145  "RESTORE_FROM_CODEX",146]);147148// LV-3: minimum interval between non-test canary pings per webhook+entry.149const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour150151const PRIVATE_IPV4_RANGES = [152  { prefix: "10." },153  { prefix: "127." },154  { prefix: "169.254." },155  { prefix: "192.168." },156];157158export function setupMessageHandler(): void {159  chrome.runtime.onMessage.addListener(160    (msg: unknown, sender, sendResponse) => {161      if (!isMessage(msg)) {162        sendResponse({ ok: false, error: "invalid_message" });163        return true;164      }165      handleMessage(msg, sender)166        .then(sendResponse)167        .catch((err) =>168          sendResponse({169            ok: false,170            error: err instanceof Error ? err.message : String(err),171          })172        );173      return true;174    }175  );176177  // Android: the chrome shim queues sendMessage calls until this handler is178  // registered. Without this hookup, every message hangs on Capacitor builds.179  // eslint-disable-next-line @typescript-eslint/no-explicit-any180  const reg = (globalThis as any).__peachRegisterMessageHandler;181  if (typeof reg === "function") {182    reg(async (m: unknown) => {183      if (!isMessage(m)) return { ok: false, error: "invalid_message" };184      try {185        return await handleMessage(m);186      } catch (err) {187        return {188          ok: false,189          error: err instanceof Error ? err.message : String(err),190        };191      }192    });193  }194  if (isNativePlatform()) {195    void bootstrapNativeSyncRunner();196  }197}198199async function bootstrapNativeSyncRunner(): Promise<void> {200  if (nativeSyncRunnerBootstrapped) return;201  nativeSyncRunnerBootstrapped = true;202  try {203    const { setSyncRunner, hydratePersistedSyncState } = await import("./sync-trigger");204    const { productionSyncRunner } = await import("./chirp-sync-runner");205    setSyncRunner(productionSyncRunner);206    await hydratePersistedSyncState();207  } catch (err) {208    nativeSyncRunnerBootstrapped = false;209    console.warn("[Peach] failed to bootstrap native sync runner:", err);210  }211}212213function isMessage(m: unknown): m is Message {214  return typeof m === "object" && m !== null && "type" in m;215}216217/**218 * The browser-attested origin of the page that originated this message. A web219 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),220 * so every page-driven message arrives via the content-script relay and the221 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a222 * value the page cannot forge. This is the ONLY trustworthy origin for passkey223 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.224 */225function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {226  if (sender.origin) return sender.origin;227  if (sender.url) {228    try { return new URL(sender.url).origin; } catch { return undefined; }229  }230  return undefined;231}232233// Resolves once restoreFromSession() has run, so handlers see the correct234// post-restore unlock state. entry.ts registers this BEFORE the message235// handler so the onMessage listener is added synchronously at SW startup236// (MV3 requirement) while unlock-dependent handlers still wait for restore.237let restoreReady: Promise<void> = Promise.resolve();238239/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */240export function setRestoreReady(p: Promise<unknown>): void {241  restoreReady = p.then(() => undefined, () => undefined);242}243244export async function handleMessage(245  msg: Message,246  sender: Partial<chrome.runtime.MessageSender> = {}247): Promise<MessageResponse> {248  try {249    // Wait for session-restore to finish before reading any unlock/vault state.250    // On a cold SW start the popup's first message arrives while restore is251    // still in flight; without this gate IS_UNLOCKED would report locked (a252    // spurious lock screen) and the storage reads could race. The onMessage253    // listener itself is registered synchronously (entry.ts) so this gate, not254    // listener registration, is what absorbs the cold-start window.255    await restoreReady;256    // Validate sender — only allow messages from our extension pages/scripts.257    // `sender.id` is undefined for messages originating from extension UI258    // (popup/options), which is legitimate; reject only when it is defined259    // and does not match our extension id.260    if (261      sender.id !== undefined &&262      sender.id !== chrome.runtime.id263    ) {264      return { ok: false, error: "invalid_sender" };265    }266267    // PCH-01-018: irreversible operations must originate from a trusted extension268    // page (popup/options), never from a content script. The sender.id check above269    // only proves the message came from *our* extension — a content script injected270    // into an attacker page passes it. A single XSS-class bug in the injected UI271    // would otherwise escalate to vault destruction. Extension pages carry an272    // extension-origin sender.url; content scripts carry a page URL.273    if (DESTRUCTIVE_MESSAGE_TYPES.has(msg.type)) {274      const extensionOrigin = chrome.runtime.getURL("");275      if (!sender.url?.startsWith(extensionOrigin)) {276        return { ok: false, error: "invalid_sender" };277      }278    }279280    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {281      touchAutoLock();282    }283284    switch (msg.type) {285      case "CREATE_VAULT": {286        const { password } = msg.payload as { password: string };287        // Refuse to create a vault under an empty master password — the derived288        // key would be publicly known and the at-rest AES-GCM protection void289        // (audit HIGH; the CSV-import path previously passed ""). Length/strength290        // policy lives in the onboarding UI; this is the non-negotiable floor.291        if (typeof password !== "string" || password.length === 0) {292          return { ok: false, error: "invalid_payload" };293        }294        await vault.createVault(password);295        await setupAutoLock();296        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });297        onVaultUnlocked();298        return { ok: true };299      }300      case "CREATE_VAULT_FROM_ROOT_KEY": {301        const { password, rootKeyHex } = (msg.payload ?? {}) as {302          password?: unknown;303          rootKeyHex?: unknown;304        };305        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {306          return { ok: false, error: "invalid_payload" };307        }308309        try {310          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);311          await setupAutoLock();312          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });313          onVaultUnlocked();314          return { ok: true, vaultId };315        } catch (err) {316          return { ok: false, error: err instanceof Error ? err.message : String(err) };317        }318      }319      case "UNLOCK": {320        const { password } = msg.payload as { password: string };321        const ok = await vault.unlock(password);322        if (ok) {323          // KAT: verify the WebCrypto stack is healthy before the user relies on it.324          // Runs after unlock so latency is hidden behind the vault-load time.325          const kat = await runSelfTest();326          if (!kat.ok) {327            console.error("[Peach] Crypto self-test FAILED:", kat.error);328            await vault.lock();329            return { ok: false, error: "self_test_failed" };330          }331          await setupAutoLock();332          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });333          onVaultUnlocked();334          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());335          return { ok: true };336        }337        // Distinguish corruption from wrong password so the popup can offer338        // a history-restore path instead of falsely accusing the user of339        // mistyping (M7/COR-007).340        const failure = vault.consumeLastUnlockFailureReason();341        if (failure) {342          return {343            ok: false,344            error: "vault_corrupted",345            canRestoreFromHistory: true,346          } as MessageResponse;347        }348        return { ok: false };349      }350      case "VALIDATE_RECOVERY_WORDS": {351        const { words } = msg.payload as { words: string[] };352        const invalid = findInvalidWords(words);353        return { ok: true, data: { valid: invalid.length === 0, invalid } };354      }355      case "GET_RECOVERY_WORDS": {356        // Must be unlocked and have recovery set up (vault must be v2.12+).357        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };358        // LV-4: the recovery words re-derive the ROOT KEY — the highest-359        // value secret in the vault. A session unlock (which may be hours360        // old on a shared machine) is not enough; require a fresh password361        // proof, matching the 1Password/Bitwarden pattern for revealing362        // escrow material. EXEMPTION: the create-vault / rotation confirmation363        // window (peach_recovery_pending) shows the words immediately after364        // the user authenticated, and that confirmation UI has no password to365        // resend — skip the re-auth there only.366        if (!(await isRecoveryConfirmPending())) {367          const { password } = (msg.payload ?? {}) as { password?: string };368          if (typeof password !== "string" || !password) {369            return { ok: false, error: "password_required" };370          }371          if (!(await vault.verifyMainPassword(password))) {372            return { ok: false, error: "wrong_password" };373          }374        }375        try {376          const words = await vault.getRecoveryWords();377          return { ok: true, data: words };378        } catch (e) {379          // pre-v2.12 vault that hasn't migrated380          return { ok: false, error: "recovery_not_setup" };381        }382      }383      case "RECOVER_WITH_WORDS": {384        // User has lost their password but has their 12 recovery words.385        // We: (1) validate the words, (2) re-encrypt vault with new password.386        const { words, newPassword } = msg.payload as {387          words: string[];388          newPassword: string;389        };390        const stored = await vault.loadSlotA();391        if (!stored) return { ok: false, error: "no_vault" };392        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {393          return { ok: false, error: "recovery_not_setup" };394        }395        // Unwrap the root key from the recovery escrow.396        try {397          await vault.unwrapRootKeyForRecovery(398            stored.recovery_wrapped_root_key,399            stored.recovery_nonce ?? "",400            stored.recovery_tag ?? "",401            stored.recovery_salt,402            words403          );404        } catch {405          return { ok: false, error: "invalid_recovery_words" };406        }407        // Re-key: derive fresh salt + key from new password.408        const newSalt = vault.generateSalt();409        const newKey = await vault.deriveKey(newPassword, newSalt);410        // Re-wrap root key under the new password's derived key so the same411        // recovery words continue to work after the password change.412        await vault.rewrapRootKeyForPassword(newKey, newSalt);413        // Re-encrypt vault entries with the new key.414        await vault.changePasswordWithNewKey(newSalt, newKey);415        await setupAutoLock();416        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });417        return { ok: true };418      }419      case "LOCK":420        vault.lock();421        if (isNativePlatform()) await clearInMemoryVault();422        return { ok: true };423      case "IS_UNLOCKED":424        return { ok: true, data: vault.isUnlocked() };425      case "GET_VAULT_STATUS":426        return { ok: true, unlocked: vault.isUnlocked() };427      case "HAS_VAULT":428        return { ok: true, data: await vault.hasVault() };429      case "GET_ENTRIES":430        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };431        return { ok: true, data: vault.getEntries() };432      case "ADD_ENTRY": {433        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };434        const payload = msg.payload;435        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {436          return { ok: false, error: "invalid_payload" };437        }438        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);439        return { ok: true, data: entry };440      }441      case "BATCH_ADD_ENTRIES": {442        const payload = msg.payload as { entries?: unknown } | null | undefined;443        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {444          return { ok: false, error: "invalid_payload" };445        }446        if (!Array.isArray(payload.entries)) {447          return { ok: false, error: "invalid_payload" };448        }449        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);450        return { ok: true, data: added };451      }452      case "RESTORE_ENTRIES": {453        const payload = msg.payload as454          | { entries?: unknown; mode?: unknown; settings?: unknown }455          | null456          | undefined;457        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {458          return { ok: false, error: "invalid_payload" };459        }460        if (!Array.isArray(payload.entries)) {461          return { ok: false, error: "invalid_payload" };462        }463        if (payload.mode !== "replace" && payload.mode !== "merge") {464          return { ok: false, error: "invalid_payload" };465        }466        const summary = await vault.restoreEntries(467          payload.entries as Parameters<typeof vault.restoreEntries>[0],468          payload.mode469        );470        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {471          await vault.updateSettings(payload.settings as vault.VaultSettings);472        }473        return { ok: true, data: summary };474      }475      case "CLEAR_VAULT_ENTRIES": {476        await vault.clearVaultEntries("REPLACE_ALL");477        return { ok: true };478      }479      case "GET_VAULT_HISTORY": {480        const snapshots = await vault.getVaultHistory();481        return { ok: true, data: snapshots };482      }483      case "RESTORE_VAULT_SNAPSHOT": {484        const { snapshotId } = msg.payload as { snapshotId: string };485        const result = await vault.restoreVaultSnapshot(snapshotId);486        if (!result.ok) return { ok: false, error: result.error };487        broadcastToContentScripts({ type: "VAULT_LOCKED" });488        return { ok: true };489      }490      case "COUNT_DUPLICATES": {491        return { ok: true, data: vault.countDuplicates() };492      }493      case "DEDUPLICATE_ENTRIES": {494        const removed = await vault.deduplicateEntries();495        return { ok: true, data: removed };496      }497      case "UPDATE_ENTRY": {498        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;499        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {500          return { ok: false, error: "invalid_payload" };501        }502        const { id, patch } = payload;503        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {504          return { ok: false, error: "invalid_payload" };505        }506        // Single enforcement point for the Canary Entries Pro gate. Only507        // gates the transition into a canary entry — clearing/disabling a508        // canary (`canary: undefined`) is always allowed, so existing509        // canary entries remain manageable.510        const incomingCanary = (patch as { canary?: unknown }).canary;511        if (incomingCanary && typeof incomingCanary === "object") {512          const existing = vault.getEntryById(id);513          if (!existing?.canary) {514            const gate = await requirePro("canary_entry");515            if (!gate.allowed) return { ok: false, error: "pro_required" };516          }517        }518        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);519        return { ok: true };520      }521      case "ADD_ADDITIONAL_URL": {522        const { id, url } = msg.payload as { id: string; url: string };523        const trimmed = typeof url === "string" ? url.trim() : "";524        if (!trimmed) return { ok: false, error: "url_required" };525        const existing = vault.getEntryById(id);526        if (!existing) return { ok: false, error: "entry_not_found" };527        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };528        const merged = [...(existing.additionalUrls ?? []), trimmed];529        await vault.updateEntry(id, { additionalUrls: merged });530        return { ok: true };531      }532      case "DELETE_ENTRY": {533        const { id } = msg.payload as { id: string };534        await vault.deleteEntry(id);535        return { ok: true };536      }537      case "GET_DELETED_ENTRIES":538        return { ok: true, data: vault.getDeletedEntries() };539      case "RESTORE_ENTRY": {540        const { id } = msg.payload as { id: string };541        await vault.restoreEntry(id);542        return { ok: true };543      }544      case "PURGE_ENTRY": {545        const { id } = msg.payload as { id: string };546        await vault.purgeEntry(id);547        return { ok: true };548      }549      case "PURGE_EXPIRED_TRASH": {550        const { retentionMs } = msg.payload as { retentionMs: number };551        const purged = await vault.purgeExpiredTrash(retentionMs);552        return { ok: true, data: purged };553      }554      case "SAVE_NOTE": {555        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };556        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };557        const now = Date.now();558        if (id) {559          const existing = vault.getEntryById(id);560          if (!existing) return { ok: false, error: "not_found" };561          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });562          return { ok: true, data: vault.getEntryById(id) };563        } else {564          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt565          // (EntryDraft omits both), so passing them was the only reason the566          // `as any` cast existed. Dropping them makes the call type-check.567          const entry = await vault.addEntry({568            type: "note",569            title: title || "Untitled",570            notes: body,571          });572          return { ok: true, data: entry };573        }574      }575      case "DELETE_NOTE": {576        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };577        const { id } = msg.payload as { id: string };578        await vault.deleteEntry(id);579        return { ok: true };580      }581      case "GET_NOTES": {582        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };583        const notes = vault.getEntries().filter(584          (e) => e.type === "note" && !e.deletedAt585        );586        return { ok: true, data: notes } as MessageResponse;587      }588      case "SEARCH_VAULT": {589        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };590        // AUD-002: shape-validate the payload before calling string methods.591        // A raw cast lets a malformed message crash the handler with TypeError.592        const { query } = (msg.payload ?? {}) as { query?: unknown };593        if (typeof query !== "string") {594          return { ok: false, error: "invalid_payload" };595        }596        const q = query.toLowerCase();597        const searchResults = vault.getEntries().filter(598          (e) =>599            !e.deletedAt &&600            (e.title.toLowerCase().includes(q) ||601              e.notes?.toLowerCase().includes(q) ||602              e.username?.toLowerCase().includes(q))603        );604        return { ok: true, data: searchResults } as MessageResponse;605      }606      case "AUTOFILL_QUERY": {607        if (!vault.isUnlocked()) {608          return { ok: false, error: "vault_locked" };609        }610        let { includeAll } = msg.payload as { includeAll?: boolean };611        const { domain, kind, userGesture } = msg.payload as {612          domain: string;613          kind?: "login" | "card" | "totp";614          userGesture?: boolean;615        };616        // MV-2: the vault-wide inventory (every title/username/email/url)617        // may only leave the background on an explicit user gesture — the618        // user opening the search affordance — never on passive form focus.619        // userGesture is self-declared by our own content script; the value620        // of this gate is that PASSIVE code paths (which never set it)621        // cannot ship the inventory, shrinking what a compromised page that622        // merely triggers focus events can observe.623        if (includeAll && userGesture !== true) {624          includeAll = false;625        }626        // kind="card": return saved cards as compact summaries for the627        // inline card silver platter. Cards are not domain-scoped — every628        // saved card is a candidate on every checkout page — so domain is629        // ignored when kind === "card".630        if (kind === "card") {631          const cards = vault.getEntries().filter((e) => e.type === "card");632          return {633            ok: true,634            data: cards.map((e) => ({635              id: e.id,636              title: e.cardNickname || e.title,637              cardholderName: e.cardholderName,638              last4: e.last4,639              expMonth: e.expMonth,640              expYear: e.expYear,641              network: e.network,642            })),643          };644        }645        if (kind === "totp") {646          const matches = (647            includeAll648              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")649              : vault.queryDomain(domain)650          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));651          return {652            ok: true,653            data: matches.map((e) => ({654              id: e.id,655              title: e.title,656              username: e.username,657              email: e.email,658              url: e.url,659              hasTotp: true,660            })),661          };662        }663        // The inline selector fills username+password into a form. Passkey-664        // only entries have no password to fill; sign-in for those goes665        // through the WebAuthn path instead. Filter them out everywhere so666        // the user doesn't see four "GitHub" rows that mostly do nothing.667        // Notes and cards never belonged here either.668        const matches = (669          includeAll670            ? vault671                .getEntries()672                .filter((entry) => entry.type !== "note" && entry.type !== "card")673            : vault.queryDomain(domain)674        ).filter((entry) => !isPasskeyOnly(entry));675        return {676          ok: true,677          data: matches.map((e) =>678            includeAll679              ? {680                  id: e.id,681                  title: e.title,682                  // username/email/url shipped so the inline popup's search683                  // affordance can match on them, not just titles. No secrets684                  // cross the boundary — same shape as the domain-matched685                  // response below minus hasTotp (which the search list686                  // doesn't surface).687                  username: e.username,688                  email: e.email,689                  url: e.url,690                  hasPasskey: e.passkey !== undefined,691                }692              : {693                  id: e.id,694                  title: e.title,695                  username: e.username,696                  email: e.email,697                  url: e.url,698                  hasTotp: Boolean(e.totp),699                  hasPasskey: e.passkey !== undefined,700                }701          ),702        };703      }704      case "GET_ENTRY_FOR_FILL": {705        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };706        const { id, explicitSummon } = msg.payload as {707          id: string;708          explicitSummon?: boolean;709        };710        const entry = vault.getEntryById(id);711        if (!entry) return { ok: false, error: "entry_not_found" };712        // Passkey-only entries (passkey credential, no password) cannot be713        // filled into a form — sign-in goes through the WebAuthn path. A714        // login that ALSO has a passkey is still fillable for its password.715        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };716717        // MV-1: re-validate the entry against the requesting tab's origin.718        // sender.tab.url is browser-attested — a page cannot forge it. When719        // the request does not come from a tab at all (popup surfaces use720        // GET_ENTRY_FOR_EDIT, not this), refuse.721        if (sender.tab !== undefined || sender.url !== undefined) {722          let senderDomain: string | null = null;723          try {724            const rawUrl = sender.tab?.url ?? sender.url ?? "";725            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;726          } catch {727            senderDomain = null;728          }729          if (!senderDomain) return { ok: false, error: "origin_unverified" };730731          const entryDomains = new Set<string>();732          const primary = extractDomain(entry.url ?? "");733          if (primary) entryDomains.add(primary);734          for (const extra of entry.additionalUrls ?? []) {735            const d = extractDomain(extra);736            if (d) entryDomains.add(d);737          }738739          // explicitSummon=true means the user actively picked this entry740          // from the cross-domain search affordance — an intentional741          // off-domain fill. Passive fill paths must stay domain-bound.742          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {743            // Domain mismatch — refuse silently (no oracle about which ids exist).744            return { ok: false, error: "entry_not_found" };745          }746        }747        // Strip the passkey credential AND the raw base32 TOTP seed from the748        // response. Content scripts never need either: the private key is the749        // authenticator's, and handing over the TOTP seed would let a750        // compromised content script mint valid codes indefinitely (SEV-3-C).751        // Generate the *current* 6-digit code here in the background and send752        // only that, plus the seconds left so the UI can render a countdown.753        // Also drop passwordHistory: filling needs only the *current* password.754        // Handing every past password to a content script during passive755        // autofill on an arbitrary page would widen the blast radius of a756        // compromised page far beyond the one credential being filled.757        const {758          passkey: _strippedPasskey,759          totp: seed,760          totpAlgorithm,761          totpDigits,762          totpPeriod,763          passwordHistory: _ph,764          ...safeEntry765        } = entry;766        let totpCode: string | undefined;767        let totpRemaining: number | undefined;768        if (seed) {769          try {770            // PCH-01-019: honour stored algorithm/digits/period (defaults apply771            // when these are undefined, i.e. legacy bare-seed entries).772            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);773            totpCode = generated.code;774            totpRemaining = generated.remaining;775          } catch {776            totpCode = undefined;777          }778        }779        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };780      }781      // Trusted full-entry fetch for Peach's own inline-popup surfaces that782      // genuinely need the raw TOTP seed: the edit form (which re-saves the783      // seed and would otherwise wipe it) and nothing else. Unlike784      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside785      // the inline popup, never during passive autofill on an arbitrary page.786      // The passkey credential is still stripped — the edit form never touches it.787      case "GET_ENTRY_FOR_EDIT": {788        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };789        const { id, explicitSummon } = msg.payload as {790          id: string;791          explicitSummon?: boolean;792        };793        const entry = vault.getEntryById(id);794        if (!entry) return { ok: false, error: "entry_not_found" };795796        // PCH-01-006: re-validate the browser-attested sender origin, mirroring797        // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and798        // full password history — at least as sensitive as the fill response — so799        // the boundary must be enforced here, not only by UI reachability. Today800        // the sole caller is the popup (no sender.tab, so this is a structural801        // no-op), but a future tab-context caller or an id leak would otherwise802        // inherit a full-credential oracle. Unlike the fill path we SKIP (not803        // refuse) when no sender domain resolves, to keep the popup caller working.804        if (sender.tab !== undefined || sender.url !== undefined) {805          let senderDomain: string | null = null;806          try {807            const rawUrl = sender.tab?.url ?? sender.url ?? "";808            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;809          } catch {810            senderDomain = null;811          }812          if (senderDomain) {813            const entryDomains = new Set<string>();814            const primary = extractDomain(entry.url ?? "");815            if (primary) entryDomains.add(primary);816            for (const extra of entry.additionalUrls ?? []) {817              const d = extractDomain(extra);818              if (d) entryDomains.add(d);819            }820            if (explicitSummon !== true && !entryDomains.has(senderDomain)) {821              return { ok: false, error: "entry_not_found" }; // no id oracle822            }823          }824        }825826        const { passkey: _passkey, ...safeEntry } = entry;827        return { ok: true, data: safeEntry };828      }829      case "COPY": {830        // AUD-002: shape-validate the payload before passing to the clipboard831        // helper. A raw cast lets a malformed message reach the clipboard API832        // with a non-string and throw.833        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {834          text?: unknown;835          label?: unknown;836          alreadyWritten?: unknown;837        };838        if (typeof text !== "string" || typeof label !== "string") {839          return { ok: false, error: "invalid_payload" };840        }841        await copyToClipboard(text, label, Boolean(alreadyWritten));842        return { ok: true, clearSeconds: getEffectiveClearSeconds() };843      }844      case "CHECK_ALL_BREACHES": {845        const allEntries = vault.getEntries();846        const results: Record<string, number> = {};847        for (const entry of allEntries) {848          if (entry.type === "note") continue;849          if (!entry.password) continue;850          results[entry.id] = await vault.checkBreach(entry.password);851          // Small delay — be a good citizen to the HIBP API852          await new Promise((r) => setTimeout(r, 200));853        }854        // Persist any non-zero counts back to entries855        for (const [id, count] of Object.entries(results)) {856          const entry = vault.getEntryById(id);857          if (entry && (entry.breach ?? 0) !== count) {858            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });859          }860        }861        return { ok: true, data: results };862      }863      case "GET_SETTINGS":864        return { ok: true, data: await vault.ensureSettingsLoaded() };865      case "UPDATE_SETTINGS": {866        const patch = msg.payload;867        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {868          return { ok: false, error: "invalid_payload" };869        }870        await vault.updateSettings(patch as vault.VaultSettings);871        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {872          await setupAutoLock();873          if (vault.isUnlocked()) touchAutoLock();874        }875        return { ok: true };876      }877      case "GET_PENDING_PASSKEY":878        return { ok: true, data: await getPendingPasskeyRequest() };879      case "APPROVE_PASSKEY": {880        const { requestId } = msg.payload as { requestId: number };881        await resolvePendingPasskeyRequest(requestId, true);882        return { ok: true };883      }884      case "DENY_PASSKEY": {885        const { requestId } = msg.payload as { requestId: number };886        await resolvePendingPasskeyRequest(requestId, false);887        return { ok: true };888      }889      case "GET_PASSKEY_PROVIDER_STATE":890        return { ok: true, data: await getPasskeyProviderState() };891      case "SET_PASSKEY_PROVIDER_ENABLED": {892        const { enabled } = msg.payload as { enabled: boolean };893        // Disabling is always free; gating fires only when a free user is894        // trying to turn passkey interception on.895        if (enabled) {896          const gate = await requirePro("passkeys");897          if (!gate.allowed) return { ok: false, error: "pro_required" };898        }899        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };900      }901      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS902      // endpoint. Intentional product behavior — users configure their own903      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private904      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-905      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to906      // users that the entry title leaves the device when the canary fires.907      case "FIRE_CANARY_PING": {908        // Canary alert fires unconditionally for any entry with canary: true.909        // The Pro gate only governs creation/flagging of canary entries; once910        // an entry is flagged, the alert path is a security property and must911        // never be license-gated.912        const { webhookUrl, entryTitle, trigger } = msg.payload as {913          webhookUrl: string;914          entryTitle: string;915          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";916        };917        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {918          return { ok: false, error: "invalid_webhook_url" };919        }920        // LV-3: debounce non-test pings per (webhook, entry) so a page that921        // strobes focus/fill events can't turn the canary into a request922        // firehose at the user's endpoint. Test pings are exempt — they are923        // explicit user clicks in the settings UI and are awaited for924        // feedback. The FIRST ping in a window always goes out, so the925        // dead-man's-switch property (canary fires on access) is preserved;926        // only repeats within the window are coalesced.927        if (trigger !== "test") {928          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;929          const stored = await chrome.storage.local.get(rlKey);930          const last = (stored as Record<string, unknown>)[rlKey];931          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {932            return { ok: true, data: { rateLimited: true } };933          }934          await chrome.storage.local.set({ [rlKey]: Date.now() });935        }936        const body = JSON.stringify({937          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",938          entry: entryTitle,939          trigger,940          timestamp: new Date().toISOString(),941          source: "peach-extension",942        });943        if (trigger === "test") {944          // Permitted outbound fetch: user-configured canary alert endpoint945          // (validated by isAllowedCanaryWebhookUrl above). This is the946          // only non-HIBP outbound call in the extension — see947          // Projects.md §3.7. Test pings are awaited so the UI can show948          // success/failure.949          try {950            const res = await fetch(webhookUrl, {951              method: "POST",952              headers: { "Content-Type": "application/json" },953              body,954            });955            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };956          } catch (err) {957            return { ok: false, error: err instanceof Error ? err.message : "network_error" };958          }959        }960        // Non-test triggers are fire-and-forget961        fetch(webhookUrl, {962          method: "POST",963          headers: { "Content-Type": "application/json" },964          body,965        }).catch(() => {});966        return { ok: true };967      }968      case "ACTIVATE_LICENSE": {969        const { key } = msg.payload as { key: string };970        const licenseInfo = await activateLicense(key);971        return { ok: true, data: licenseInfo };972      }973      case "GET_LICENSE": {974        const licenseInfo = await getLicenseInfo();975        return { ok: true, data: licenseInfo };976      }977      case "GET_LICENSE_KEY": {978        const key = await getLicenseKey();979        return { ok: true, data: key };980      }981      case "DEACTIVATE_LICENSE": {982        await deactivateLicense();983        return { ok: true };984      }985      case "SHOULD_PLAY_CELEBRATION": {986        const should = await shouldPlayCelebration();987        return { ok: true, data: should };988      }989      case "MARK_CELEBRATION_PLAYED": {990        await markCelebrationPlayed();991        return { ok: true };992      }993      case "GET_CODEX_VAULT_DATA": {994        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the995        // popup navigates to the License section without further coordination.996        const gate = await requirePro("codex");997        if (!gate.allowed) return { ok: false, error: "pro_required" };998        return await handleGetCodexVaultData();999      }1000      case "ESTIMATE_CODEX_PAGES": {1001        const gate = await requirePro("codex");1002        if (!gate.allowed) return { ok: false, error: "pro_required" };1003        return await handleEstimateCodexPages();1004      }1005      case "RESTORE_FROM_CODEX": {1006        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1007        // be able to restore a vault that was printed by a Pro user.1008        // DO NOT add a Pro gate here.1009        const payload = msg.payload as CodexRestorePayload;1010        return await handleRestoreFromCodex(payload);1011      }1012      case "OPEN_PRO_GATE": {1013        // Content script requests: open popup and navigate to License section.1014        const { feature } = (msg.payload ?? {}) as { feature?: string };1015        if (chrome.storage.session) {1016          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1017        }1018        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1019        return { ok: true };1020      }1021      case "OPEN_POPUP": {1022        // Content script asks to open the trusted extension popup — used by the1023        // inline locked bubble so the master password is entered in the popup,1024        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1025        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1026        // toolbar icon. The badge already signals Peach needs attention.1027        //1028        // Set a session flag so the popup knows it was opened for inline unlock1029        // and should close itself once the vault is unlocked (returning the user1030        // to the inline autofill selector on the page).1031        if (chrome.storage.session) {1032          await chrome.storage.session.set({ peach_inline_unlock: true });1033        }1034        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1035        return { ok: true };1036      }1037      case "GET_IDENTITIES": {1038        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1039        return { ok: true, data: vault.getIdentities() };1040      }1041      case "TOUCH_AUTO_LOCK": {1042        // touchAutoLock() is already called by shouldRefreshAutoLock above;1043        // this case just gives the popup a typed message to keep the session alive.1044        return { ok: true };1045      }1046      case "GET_ADVANCED_HEALTH_REPORT": {1047        const gate = await requirePro("advanced_health");1048        if (!gate.allowed) return { ok: false, error: "pro_required" };1049        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1050        const report = await buildAdvancedHealthReport(vault.getEntries());1051        return { ok: true, data: report };1052      }1053      case "IS_DURESS_ENABLED": {1054        const enabled = await vault.isDuressEnabled();1055        return { ok: true, data: enabled };1056      }1057      case "SETUP_DURESS": {1058        // Single enforcement point for the Duress Vault Pro gate. Free users1059        // who somehow reach this handler are rejected here; the popup also1060        // pre-checks isPro() to avoid showing the setup form to free users,1061        // but server-side is the actual security boundary.1062        const gate = await requirePro("duress_vault");1063        if (!gate.allowed) return { ok: false, error: "pro_required" };1064        // MV3 service workers restart after inactivity, losing the in-memory1065        // derived key. Detect this before calling setupDuress so the popup1066        // can show a meaningful prompt to re-lock and re-unlock.1067        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1068        const { duressPassword } = msg.payload as { duressPassword: string };1069        await vault.setupDuress(duressPassword);1070        return { ok: true };1071      }1072      case "DISABLE_DURESS": {1073        await vault.disableDuress();1074        return { ok: true };1075      }1076      case "VERIFY_MAIN_PASSWORD": {1077        const { password } = msg.payload as { password: string };1078        const ok = await vault.verifyMainPassword(password);1079        return { ok: true, data: ok };1080      }1081      case "CHANGE_PASSWORD": {1082        const { currentPassword, newPassword } = msg.payload as {1083          currentPassword: string;1084          newPassword: string;1085        };1086        const changed = await vault.changePassword(currentPassword, newPassword);1087        return changed1088          ? { ok: true }1089          : { ok: false, error: "incorrect_current_password" };1090      }1091      case "GET_SITE_PASSWORD_POLICY": {1092        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1093        if (!tab?.id) return { ok: true, data: null };1094        try {1095          const response = await chrome.tabs.sendMessage(tab.id, {1096            type: "GET_SITE_PASSWORD_POLICY",1097          });1098          return (response as MessageResponse) ?? { ok: true, data: null };1099        } catch {1100          return { ok: true, data: null };1101        }1102      }1103      case "RECORD_MANUAL_SUMMON": {1104        const { domain } = msg.payload as { domain: string };1105        const settings = vault.getSettings();1106        const existing = settings.manualSummonDomains?.[domain];1107        const now = Date.now();1108        await vault.updateSettings({1109          manualSummonDomains: {1110            ...settings.manualSummonDomains,1111            [domain]: {1112              firstSummonedAt: existing?.firstSummonedAt ?? now,1113              summonCount: (existing?.summonCount ?? 0) + 1,1114              lastSummonedAt: now,1115            },1116          },1117        });1118        return { ok: true };1119      }1120      case "DECLINE_CARD_SAVE": {1121        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1122        await vault.declineCardSaveOffer(last4, expMonth, expYear);1123        return { ok: true };1124      }1125      case "IS_CARD_DECLINED": {1126        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1127        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1128        return { ok: true, data: declined };1129      }1130      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1131        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1132          rpId?: string;1133          rpName?: string;1134          userName?: string;1135          userDisplayName?: string;1136        };1137        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1138        return await initiateFirefoxPasskeyCreate({1139          rpId,1140          rpName: rpName ?? rpId,1141          userName,1142          userDisplayName,1143        });1144      }11451146      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1147        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1148        if (!payload) return { ok: false, error: "missing_payload" };1149        return await completeFirefoxPasskeyCreate(payload);1150      }11511152      case "PASSKEY_OFFER_DECLINE": {1153        const { domain } = (msg.payload ?? {}) as { domain?: string };1154        if (!domain) return { ok: false, error: "domain_required" };1155        await recordPasskeyOfferDecline(domain);1156        return { ok: true };1157      }11581159      case "GET_PASSKEY_OFFER_DECLINED": {1160        const { domain } = (msg.payload ?? {}) as { domain?: string };1161        if (!domain) return { ok: false, error: "domain_required" };1162        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1163      }11641165      case "PASSKEY_HAS_CREDENTIALS": {1166        const payload = msg.payload as {1167          rpId?: string;1168          allowCredentials?: Array<{ id: string; type?: string }>;1169        } | undefined;1170        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1171        return await handlePasskeyHasCredentials({1172          rpId: payload.rpId,1173          allowCredentials: payload.allowCredentials ?? [],1174        }, attestedSenderOrigin(sender));1175      }11761177      case "PASSKEY_CREATE": {1178        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1179        if (!payload?.rpId || !payload?.userName) {1180          return { ok: false, error: "rpid_and_username_required" };1181        }1182        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1183      }11841185      case "PASSKEY_GET": {1186        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1187        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1188        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1189      }11901191      case "PASSKEY_AUTH_RESPONSE": {1192        const { requestId, approved } = (msg.payload ?? {}) as {1193          requestId?: string | number;1194          approved?: boolean;1195        };1196        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1197          return { ok: false, error: 'requestId and approved required' };1198        }1199        await resolvePendingPasskeyRequest(Number(requestId), approved);1200        return { ok: true };1201      }12021203      case "GET_PASSKEY_FOR_DOMAIN": {1204        const { domain } = (msg.payload ?? {}) as { domain?: string };1205        if (!domain) return { ok: false, error: "domain_required" };1206        // Scope to the caller's own origin: a page may only ask about passkeys1207        // for a domain it actually owns, so an arbitrary page cannot enumerate1208        // which sites the user holds passkeys for or read the username (audit MEDIUM).1209        const origin = attestedSenderOrigin(sender);1210        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1211        if (!vault.isUnlocked()) return { ok: true, data: null };1212        const match = vault1213          .getEntries()1214          .find((entry) => entry.passkey?.rpId === domain);1215        if (!match || !match.passkey) return { ok: true, data: null };1216        // Slim shape — only the fields State 11 needs. Never expose private1217        // key material, even though this is locked behind isUnlocked.1218        return {1219          ok: true,1220          data: {1221            rpId: match.passkey.rpId,1222            userName: match.passkey.userName,1223            browser: match.passkey.browser,1224          },1225        };1226      }12271228      case "DESTROY_VAULT": {1229        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1230        // storage.local.clear() wipes every Peach key (slots, settings, license,1231        // onboarded flag, history, sync state, declined cards, recall, etc.);1232        // session.clear() wipes pending passkey requests + pro-notice queues.1233        // Caller (Panic.tsx) handles UI navigation back to onboarding.1234        //1235        // The Pro license is the one thing that must survive: the user paid for1236        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1237        // Capture it before the clear and restore it after. peach_pro_celebrated1238        // rides along so the Pro celebration doesn't replay on the next unlock.1239        const preserved = await chrome.storage.local.get([1240          "peach_license",1241          "peach_pro_celebrated",1242        ]);1243        vault.lock();1244        await storageClear();1245        await vault.clearVaultHistory();1246        const toRestore: Record<string, unknown> = {};1247        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1248        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1249        if (Object.keys(toRestore).length > 0) {1250          await chrome.storage.local.set(toRestore);1251        }1252        if (chrome.storage.session) {1253          await chrome.storage.session.clear();1254        }1255        return { ok: true };1256      }12571258      case "SUBMIT_FEEDBACK": {1259        const { category, message, version, browser } = msg.payload as {1260          category: string;1261          message: string;1262          version: string;1263          browser: string;1264        };1265        if (!message.trim()) return { ok: false, error: "message_empty" };1266        if (!FEEDBACK_ENDPOINT) return { ok: true };1267        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1268          return { ok: false, error: "invalid_feedback_endpoint" };1269        }1270        try {1271          const res = await fetch(FEEDBACK_ENDPOINT, {1272            method: "POST",1273            headers: { "Content-Type": "application/json" },1274            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1275          });1276          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1277        } catch (err) {1278          return { ok: false, error: err instanceof Error ? err.message : "network_error" };1279        }1280      }1281      // Android-only: biometric unlock with pre-derived key.1282      case "UNLOCK_WITH_KEY": {1283        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1284        if (!isNativePlatform()) {1285          return { ok: false, error: "desktop_only_uses_password" };1286        }1287        try {1288          const result = await vault.unlockWithKey(masterKeyHex);1289          if (result.ok) {1290            onVaultUnlocked();1291            await publishInMemoryVault(result.entries);1292          }1293          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1294        } catch {1295          return { ok: false, error: "invalid_key" };1296        }1297      }1298      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1299      case "GET_DERIVED_KEY": {1300        if (!isNativePlatform()) {1301          return { ok: false, error: "android_only" };1302        }1303        if (!vault.isUnlocked()) {1304          return { ok: false, error: "vault_locked" };1305        }1306        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1307      }1308      case "GET_IDENTITY_SUGGESTIONS": {1309        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1310        const entries = vault.getEntries();1311        const suggestions = buildIdentitySuggestions(entries);1312        return { ok: true, data: { suggestions } };1313      }1314      case "POPULATE_INLINE_VAULT": {1315        if (!isNativePlatform()) return { ok: false };1316        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1317        const entries = vault.getEntries();1318        await publishInMemoryVault(entries);1319        return { ok: true };1320      }1321      case "ML_INIT":1322        return { ok: true };13231324      case "ML_PREDICT_BATCH": {1325        // AUD-002: shape-validate before forwarding to the ML helper.1326        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1327        if (!Array.isArray(featuresArray)) {1328          return { ok: false, error: "invalid_payload" };1329        }1330        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1331      }13321333      // ── Chirp Sync (v3) ───────────────────────────────────────────────1334      // Returns the public-facing local identity needed by the popup to1335      // drive Phase-1 audio pairing. The private long-term key never1336      // leaves the background.1337      case "CHIRP_GET_LOCAL_IDENTITY": {1338        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1339        // Pro license from an already-Pro peer (at least one device must be Pro).1340        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1341        // Identity derives from the stable root key, not the password-derived1342        // key, so pairing survives a master-password change (SEV-2-B).1343        const masterKeyHex = vault.getRootKeyHex();1344        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1345        const masterKey = unhexBytes(masterKeyHex);1346        try {1347          const identity = await buildLocalIdentity(masterKey);1348          // If this device is Pro, advertise the signed license so the peer can1349          // activate it after SAS confirmation — pairing carries Pro across.1350          if (await isProUser()) {1351            const license = await getLicenseKey();1352            if (license) (identity as { license?: string }).license = license;1353          }1354          return { ok: true, data: identity };1355        } finally {1356          masterKey.fill(0);1357        }1358      }13591360      case "CHIRP_COMPLETE_PAIRING": {1361        // Not Pro-gated — see CHIRP_GET_LOCAL_IDENTITY.1362        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1363        const paired = (msg.payload as { paired?: unknown })?.paired;1364        if (typeof paired !== "object" || paired === null) {1365          return { ok: false, error: "invalid_payload" };1366        }1367        const candidate = paired as Record<string, unknown>;1368        if (1369          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1370          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1371          typeof candidate.deviceType !== "string" ||1372          typeof candidate.longTermPublicKeyHex !== "string" ||1373          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1374          (1375            candidate.signingPublicKeyHex !== undefined &&1376            (1377              typeof candidate.signingPublicKeyHex !== "string" ||1378              !/^[0-9a-f]{64}$/.test(candidate.signingPublicKeyHex)1379            )1380          ) ||1381          typeof candidate.pairedAt !== "number"1382        ) {1383          return { ok: false, error: "invalid_paired_device" };1384        }1385        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1386        return { ok: true };1387      }13881389      case "CHIRP_LIST_PAIRED_DEVICES": {1390        const devices = await listPairedDevicesV3();1391        return { ok: true, data: { devices } };1392      }13931394      case "CHIRP_UNPAIR_DEVICE": {1395        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1396        if (typeof deviceId !== "string" || !deviceId) {1397          return { ok: false, error: "invalid_payload" };1398        }1399        await removePairedDeviceByIdV3(deviceId);1400        return { ok: true };1401      }14021403      case "CHIRP_RENAME_LOCAL_DEVICE": {1404        const { name } = (msg.payload ?? {}) as { name?: string };1405        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1406        await setDeviceNameV3(name);1407        return { ok: true };1408      }14091410      // ── Desktop helper code pairing (peach-sync) ──────────────────────────1411      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1412      // pairing runs in the background; the SAS and the terminal result reach the1413      // popup as DESKTOP_PAIR_SAS / DESKTOP_PAIR_RESULT pushes.1414      case "PAIR_WITH_DESKTOP": {1415        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1416        const { code } = (msg.payload ?? {}) as { code?: string };1417        if (typeof code !== "string" || !/\d/.test(code)) {1418          return { ok: false, error: "invalid_payload" };1419        }1420        const { startDesktopPairing, isDesktopPairingInFlight } = await import(1421          "./desktop-pairing-bg"1422        );1423        if (isDesktopPairingInFlight()) return { ok: false, error: "pairing_in_progress" };1424        startDesktopPairing(code);1425        return { ok: true };1426      }14271428      case "DESKTOP_PAIR_CONFIRM": {1429        const { confirmed } = (msg.payload ?? {}) as { confirmed?: boolean };1430        const { resolveDesktopPairingConfirm } = await import("./desktop-pairing-bg");1431        resolveDesktopPairingConfirm(confirmed === true);1432        return { ok: true };1433      }14341435      case "TRIGGER_SYNC": {1436        const payload = (msg.payload ?? {}) as {1437          reason?: "vault_change" | "foreground" | "manual" | "mdns";1438          force?: boolean;1439          deviceId?: string;1440          discoveredIp?: string;1441          discoveredPort?: number;1442        };1443        const reason = payload.reason ?? "foreground";14441445        // mDNS discovery delivers a fresh (ip, port) resolved by the native1446        // side. Update the cached address before the sync runner tries to1447        // connect — avoids a subnet probe on the very next round.1448        if (1449          reason === "mdns" &&1450          typeof payload.deviceId === "string" &&1451          typeof payload.discoveredIp === "string"1452        ) {1453          const { findPairedDeviceById, setLastKnownIp } = await import("./paired-devices");1454          const device = await findPairedDeviceById(payload.deviceId);1455          if (device?.longTermPublicKeyHex) {1456            await setLastKnownIp(device.longTermPublicKeyHex, payload.discoveredIp).catch(() => undefined);1457          }1458        }14591460        const { triggerSyncIfReachable } = await import("./sync-trigger");1461        void triggerSyncIfReachable({ reason, force: payload.force === true });1462        return { ok: true };1463      }14641465      case "GET_SYNC_STATE": {1466        const { getSyncState } = await import("./sync-trigger");1467        return { ok: true, data: getSyncState() };1468      }14691470      case "GET_SYNC_ALERTS": {1471        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1472        const alerts = await getPendingSyncAlerts();1473        // The popup reads on open and acknowledges with consume:true after1474        // rendering, so a popup crash between read and render doesn't lose1475        // the alerts.1476        if (consume) await clearPendingSyncAlerts();1477        return { ok: true, data: alerts };1478      }14791480      case "GET_PENDING_VOUCHED_DEVICES": {1481        return { ok: true, data: await listPendingVouchedDevices() };1482      }1483      case "CONFIRM_VOUCHED_DEVICE": {1484        const { deviceId } = msg.payload as { deviceId: string };1485        const pending = await getPendingVouchedDevice(deviceId);1486        if (!pending) return { ok: false, error: "not_pending" };1487        await upsertPairedDeviceV3({1488          deviceId: pending.deviceId,1489          deviceName: pending.deviceName,1490          deviceType:1491            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1492          longTermPublicKeyHex: pending.longTermPublicKeyHex,1493          signingPublicKeyHex: pending.signingPublicKeyHex,1494          wsPort: pending.wsPort,1495          pairedAt: pending.pairedAt,1496          trustSource: "vouched",1497        });1498        await removePendingVouchedDevice(deviceId);1499        return { ok: true };1500      }1501      case "REJECT_VOUCHED_DEVICE": {1502        const { deviceId } = msg.payload as { deviceId: string };1503        await removePendingVouchedDevice(deviceId);1504        return { ok: true };1505      }1506      case "ROTATE_SYNC_IDENTITY": {1507        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1508        const result = await vault.rotateSyncIdentity();1509        return result.ok ? { ok: true } : { ok: false, error: result.error };1510      }15111512      default:1513        return { ok: false, error: "unknown_message_type" };1514    }1515  } catch (err) {1516    return {1517      ok: false,1518      error: err instanceof Error ? err.message : "operation_failed",1519    };1520  }1521}15221523// --- Mobile platform helpers ---15241525// Android: populates the in-memory vault used by PeachAutofillService.1526async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1527  const plugin = nativePlugin<{1528    setEntries?: (args: {1529      entries: Array<{1530        id: string;1531        title: string;1532        username: string;1533        email: string;1534        password: string;1535        url: string;1536        totp: string;1537        additionalUrls: string[];1538      }>;1539    }) => Promise<void>;1540  }>("InMemoryVaultPlugin");1541  if (!plugin?.setEntries) return;1542  await plugin.setEntries({1543    entries: entries.map((e) => ({1544      id: e.id,1545      title: e.title ?? "",1546      username: e.username ?? "",1547      email: (e as VaultEntry & { email?: string }).email ?? "",1548      password: e.password ?? "",1549      url: e.url ?? "",1550      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1551      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1552    })),1553  });1554}15551556// Android: clear the autofill in-memory store on lock.1557async function clearInMemoryVault(): Promise<void> {1558  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1559  if (!plugin?.clearEntries) return;1560  await plugin.clearEntries();1561}15621563// Returns username use-counts from the vault, sorted by frequency. Each row1564// also carries the entry's email so the popup can suggest the email/username1565// pair the user has actually used together.1566function buildIdentitySuggestions(1567  entries: VaultEntry[],1568): Array<{ email: string; username: string; count: number }> {1569  const usernameCounts = new Map<string, number>();1570  const usernameEmail = new Map<string, string>();1571  for (const entry of entries) {1572    const username = entry.username ?? "";1573    const email = (entry as VaultEntry & { email?: string }).email ?? "";1574    if (!username && !email) continue;1575    const key = username || email;1576    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1577    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1578  }1579  return Array.from(usernameCounts.entries())1580    .sort((a, b) => b[1] - a[1])1581    .map(([username, count]) => ({1582      email: usernameEmail.get(username) ?? "",1583      username,1584      count,1585    }));1586}15871588/** Notify all content scripts that the vault just became available. */1589function broadcastToContentScripts(message: { type: string }): void {1590  if (!chrome.tabs?.query) return;1591  chrome.tabs.query({}, (tabs) => {1592    for (const tab of tabs) {1593      if (tab.id !== undefined) {1594        chrome.tabs.sendMessage(tab.id, message).catch(() => {1595          // Tab may not have a content script — silently ignore1596        });1597      }1598    }1599  });1600}16011602function shouldRefreshAutoLock(type: MessageType): boolean {1603  return (1604    type !== "HAS_VAULT" &&1605    type !== "IS_UNLOCKED" &&1606    type !== "GET_VAULT_STATUS" &&1607    type !== "LOCK" &&1608    type !== "UPDATE_SETTINGS" &&1609    type !== "GET_PENDING_PASSKEY" &&1610    type !== "GET_PASSKEY_PROVIDER_STATE" &&1611    type !== "DECLINE_CARD_SAVE" &&1612    type !== "IS_CARD_DECLINED" &&1613    type !== "SUBMIT_FEEDBACK"1614  );1615}16161617function isAllowedCanaryWebhookUrl(value: string): boolean {1618  try {1619    const url = new URL(value);1620    if (url.protocol !== "https:") return false;16211622    const hostname = url.hostname.toLowerCase();1623    if (1624      hostname === "localhost" ||1625      hostname.endsWith(".localhost") ||1626      isPrivateIpv4(hostname) ||1627      isPrivateIpv6(hostname)1628    ) {1629      return false;1630    }16311632    return true;1633  } catch {1634    return false;1635  }1636}16371638function isPrivateIpv4(hostname: string): boolean {1639  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1640    return true;1641  }16421643  const octets = hostname.split(".").map((part) => Number(part));1644  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1645    return false;1646  }16471648  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1649}16501651function isPrivateIpv6(hostname: string): boolean {1652  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1653  return (1654    normalized === "::1" ||1655    normalized.startsWith("fc") ||1656    normalized.startsWith("fd") ||1657    normalized.startsWith("fe80:")1658  );1659}