messages.ts

66.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 {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 "UNLOCK": {301        const { password } = msg.payload as { password: string };302        const ok = await vault.unlock(password);303        if (ok) {304          // KAT: verify the WebCrypto stack is healthy before the user relies on it.305          // Runs after unlock so latency is hidden behind the vault-load time.306          const kat = await runSelfTest();307          if (!kat.ok) {308            console.error("[Peach] Crypto self-test FAILED:", kat.error);309            await vault.lock();310            return { ok: false, error: "self_test_failed" };311          }312          await setupAutoLock();313          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });314          onVaultUnlocked();315          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());316          return { ok: true };317        }318        // Distinguish corruption from wrong password so the popup can offer319        // a history-restore path instead of falsely accusing the user of320        // mistyping (M7/COR-007).321        const failure = vault.consumeLastUnlockFailureReason();322        if (failure) {323          return {324            ok: false,325            error: "vault_corrupted",326            canRestoreFromHistory: true,327          } as MessageResponse;328        }329        return { ok: false };330      }331      case "VALIDATE_RECOVERY_WORDS": {332        const { words } = msg.payload as { words: string[] };333        const invalid = findInvalidWords(words);334        return { ok: true, data: { valid: invalid.length === 0, invalid } };335      }336      case "GET_RECOVERY_WORDS": {337        // Must be unlocked and have recovery set up (vault must be v2.12+).338        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };339        // LV-4: the recovery words re-derive the ROOT KEY — the highest-340        // value secret in the vault. A session unlock (which may be hours341        // old on a shared machine) is not enough; require a fresh password342        // proof, matching the 1Password/Bitwarden pattern for revealing343        // escrow material. EXEMPTION: the create-vault / rotation confirmation344        // window (peach_recovery_pending) shows the words immediately after345        // the user authenticated, and that confirmation UI has no password to346        // resend — skip the re-auth there only.347        if (!(await isRecoveryConfirmPending())) {348          const { password } = (msg.payload ?? {}) as { password?: string };349          if (typeof password !== "string" || !password) {350            return { ok: false, error: "password_required" };351          }352          if (!(await vault.verifyMainPassword(password))) {353            return { ok: false, error: "wrong_password" };354          }355        }356        try {357          const words = await vault.getRecoveryWords();358          return { ok: true, data: words };359        } catch (e) {360          // pre-v2.12 vault that hasn't migrated361          return { ok: false, error: "recovery_not_setup" };362        }363      }364      case "RECOVER_WITH_WORDS": {365        // User has lost their password but has their 12 recovery words.366        // We: (1) validate the words, (2) re-encrypt vault with new password.367        const { words, newPassword } = msg.payload as {368          words: string[];369          newPassword: string;370        };371        const stored = await vault.loadSlotA();372        if (!stored) return { ok: false, error: "no_vault" };373        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {374          return { ok: false, error: "recovery_not_setup" };375        }376        // Unwrap the root key from the recovery escrow.377        try {378          await vault.unwrapRootKeyForRecovery(379            stored.recovery_wrapped_root_key,380            stored.recovery_nonce ?? "",381            stored.recovery_tag ?? "",382            stored.recovery_salt,383            words384          );385        } catch {386          return { ok: false, error: "invalid_recovery_words" };387        }388        // Re-key: derive fresh salt + key from new password.389        const newSalt = vault.generateSalt();390        const newKey = await vault.deriveKey(newPassword, newSalt);391        // Re-wrap root key under the new password's derived key so the same392        // recovery words continue to work after the password change.393        await vault.rewrapRootKeyForPassword(newKey, newSalt);394        // Re-encrypt vault entries with the new key.395        await vault.changePasswordWithNewKey(newSalt, newKey);396        await setupAutoLock();397        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });398        return { ok: true };399      }400      case "LOCK":401        vault.lock();402        if (isNativePlatform()) await clearInMemoryVault();403        return { ok: true };404      case "IS_UNLOCKED":405        return { ok: true, data: vault.isUnlocked() };406      case "GET_VAULT_STATUS":407        return { ok: true, unlocked: vault.isUnlocked() };408      case "HAS_VAULT":409        return { ok: true, data: await vault.hasVault() };410      case "GET_ENTRIES":411        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };412        return { ok: true, data: vault.getEntries() };413      case "ADD_ENTRY": {414        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };415        const payload = msg.payload;416        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {417          return { ok: false, error: "invalid_payload" };418        }419        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);420        return { ok: true, data: entry };421      }422      case "BATCH_ADD_ENTRIES": {423        const payload = msg.payload as { entries?: unknown } | null | undefined;424        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {425          return { ok: false, error: "invalid_payload" };426        }427        if (!Array.isArray(payload.entries)) {428          return { ok: false, error: "invalid_payload" };429        }430        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);431        return { ok: true, data: added };432      }433      case "RESTORE_ENTRIES": {434        const payload = msg.payload as435          | { entries?: unknown; mode?: unknown; settings?: unknown }436          | null437          | undefined;438        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {439          return { ok: false, error: "invalid_payload" };440        }441        if (!Array.isArray(payload.entries)) {442          return { ok: false, error: "invalid_payload" };443        }444        if (payload.mode !== "replace" && payload.mode !== "merge") {445          return { ok: false, error: "invalid_payload" };446        }447        const summary = await vault.restoreEntries(448          payload.entries as Parameters<typeof vault.restoreEntries>[0],449          payload.mode450        );451        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {452          await vault.updateSettings(payload.settings as vault.VaultSettings);453        }454        return { ok: true, data: summary };455      }456      case "CLEAR_VAULT_ENTRIES": {457        await vault.clearVaultEntries("REPLACE_ALL");458        return { ok: true };459      }460      case "GET_VAULT_HISTORY": {461        const snapshots = await vault.getVaultHistory();462        return { ok: true, data: snapshots };463      }464      case "RESTORE_VAULT_SNAPSHOT": {465        const { snapshotId } = msg.payload as { snapshotId: string };466        const result = await vault.restoreVaultSnapshot(snapshotId);467        if (!result.ok) return { ok: false, error: result.error };468        broadcastToContentScripts({ type: "VAULT_LOCKED" });469        return { ok: true };470      }471      case "COUNT_DUPLICATES": {472        return { ok: true, data: vault.countDuplicates() };473      }474      case "DEDUPLICATE_ENTRIES": {475        const removed = await vault.deduplicateEntries();476        return { ok: true, data: removed };477      }478      case "UPDATE_ENTRY": {479        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;480        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {481          return { ok: false, error: "invalid_payload" };482        }483        const { id, patch } = payload;484        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {485          return { ok: false, error: "invalid_payload" };486        }487        // Single enforcement point for the Canary Entries Pro gate. Only488        // gates the transition into a canary entry — clearing/disabling a489        // canary (`canary: undefined`) is always allowed, so existing490        // canary entries remain manageable.491        const incomingCanary = (patch as { canary?: unknown }).canary;492        if (incomingCanary && typeof incomingCanary === "object") {493          const existing = vault.getEntryById(id);494          if (!existing?.canary) {495            const gate = await requirePro("canary_entry");496            if (!gate.allowed) return { ok: false, error: "pro_required" };497          }498        }499        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);500        return { ok: true };501      }502      case "ADD_ADDITIONAL_URL": {503        const { id, url } = msg.payload as { id: string; url: string };504        const trimmed = typeof url === "string" ? url.trim() : "";505        if (!trimmed) return { ok: false, error: "url_required" };506        const existing = vault.getEntryById(id);507        if (!existing) return { ok: false, error: "entry_not_found" };508        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };509        const merged = [...(existing.additionalUrls ?? []), trimmed];510        await vault.updateEntry(id, { additionalUrls: merged });511        return { ok: true };512      }513      case "DELETE_ENTRY": {514        const { id } = msg.payload as { id: string };515        await vault.deleteEntry(id);516        return { ok: true };517      }518      case "GET_DELETED_ENTRIES":519        return { ok: true, data: vault.getDeletedEntries() };520      case "RESTORE_ENTRY": {521        const { id } = msg.payload as { id: string };522        await vault.restoreEntry(id);523        return { ok: true };524      }525      case "PURGE_ENTRY": {526        const { id } = msg.payload as { id: string };527        await vault.purgeEntry(id);528        return { ok: true };529      }530      case "PURGE_EXPIRED_TRASH": {531        const { retentionMs } = msg.payload as { retentionMs: number };532        const purged = await vault.purgeExpiredTrash(retentionMs);533        return { ok: true, data: purged };534      }535      case "SAVE_NOTE": {536        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };537        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };538        const now = Date.now();539        if (id) {540          const existing = vault.getEntryById(id);541          if (!existing) return { ok: false, error: "not_found" };542          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });543          return { ok: true, data: vault.getEntryById(id) };544        } else {545          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt546          // (EntryDraft omits both), so passing them was the only reason the547          // `as any` cast existed. Dropping them makes the call type-check.548          const entry = await vault.addEntry({549            type: "note",550            title: title || "Untitled",551            notes: body,552          });553          return { ok: true, data: entry };554        }555      }556      case "DELETE_NOTE": {557        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };558        const { id } = msg.payload as { id: string };559        await vault.deleteEntry(id);560        return { ok: true };561      }562      case "GET_NOTES": {563        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };564        const notes = vault.getEntries().filter(565          (e) => e.type === "note" && !e.deletedAt566        );567        return { ok: true, data: notes } as MessageResponse;568      }569      case "SEARCH_VAULT": {570        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };571        // AUD-002: shape-validate the payload before calling string methods.572        // A raw cast lets a malformed message crash the handler with TypeError.573        const { query } = (msg.payload ?? {}) as { query?: unknown };574        if (typeof query !== "string") {575          return { ok: false, error: "invalid_payload" };576        }577        const q = query.toLowerCase();578        const searchResults = vault.getEntries().filter(579          (e) =>580            !e.deletedAt &&581            (e.title.toLowerCase().includes(q) ||582              e.notes?.toLowerCase().includes(q) ||583              e.username?.toLowerCase().includes(q))584        );585        return { ok: true, data: searchResults } as MessageResponse;586      }587      case "AUTOFILL_QUERY": {588        if (!vault.isUnlocked()) {589          return { ok: false, error: "vault_locked" };590        }591        let { includeAll } = msg.payload as { includeAll?: boolean };592        const { domain, kind, userGesture } = msg.payload as {593          domain: string;594          kind?: "login" | "card" | "totp";595          userGesture?: boolean;596        };597        // MV-2: the vault-wide inventory (every title/username/email/url)598        // may only leave the background on an explicit user gesture — the599        // user opening the search affordance — never on passive form focus.600        // userGesture is self-declared by our own content script; the value601        // of this gate is that PASSIVE code paths (which never set it)602        // cannot ship the inventory, shrinking what a compromised page that603        // merely triggers focus events can observe.604        if (includeAll && userGesture !== true) {605          includeAll = false;606        }607        // kind="card": return saved cards as compact summaries for the608        // inline card silver platter. Cards are not domain-scoped — every609        // saved card is a candidate on every checkout page — so domain is610        // ignored when kind === "card".611        if (kind === "card") {612          const cards = vault.getEntries().filter((e) => e.type === "card");613          return {614            ok: true,615            data: cards.map((e) => ({616              id: e.id,617              title: e.cardNickname || e.title,618              cardholderName: e.cardholderName,619              last4: e.last4,620              expMonth: e.expMonth,621              expYear: e.expYear,622              network: e.network,623            })),624          };625        }626        if (kind === "totp") {627          const matches = (628            includeAll629              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")630              : vault.queryDomain(domain)631          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));632          return {633            ok: true,634            data: matches.map((e) => ({635              id: e.id,636              title: e.title,637              username: e.username,638              email: e.email,639              url: e.url,640              hasTotp: true,641            })),642          };643        }644        // The inline selector fills username+password into a form. Passkey-645        // only entries have no password to fill; sign-in for those goes646        // through the WebAuthn path instead. Filter them out everywhere so647        // the user doesn't see four "GitHub" rows that mostly do nothing.648        // Notes and cards never belonged here either.649        const matches = (650          includeAll651            ? vault652                .getEntries()653                .filter((entry) => entry.type !== "note" && entry.type !== "card")654            : vault.queryDomain(domain)655        ).filter((entry) => !isPasskeyOnly(entry));656        return {657          ok: true,658          data: matches.map((e) =>659            includeAll660              ? {661                  id: e.id,662                  title: e.title,663                  // username/email/url shipped so the inline popup's search664                  // affordance can match on them, not just titles. No secrets665                  // cross the boundary — same shape as the domain-matched666                  // response below minus hasTotp (which the search list667                  // doesn't surface).668                  username: e.username,669                  email: e.email,670                  url: e.url,671                  hasPasskey: e.passkey !== undefined,672                }673              : {674                  id: e.id,675                  title: e.title,676                  username: e.username,677                  email: e.email,678                  url: e.url,679                  hasTotp: Boolean(e.totp),680                  hasPasskey: e.passkey !== undefined,681                }682          ),683        };684      }685      case "GET_ENTRY_FOR_FILL": {686        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };687        const { id, explicitSummon } = msg.payload as {688          id: string;689          explicitSummon?: boolean;690        };691        const entry = vault.getEntryById(id);692        if (!entry) return { ok: false, error: "entry_not_found" };693        // Passkey-only entries (passkey credential, no password) cannot be694        // filled into a form — sign-in goes through the WebAuthn path. A695        // login that ALSO has a passkey is still fillable for its password.696        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };697698        // MV-1: re-validate the entry against the requesting tab's origin.699        // sender.tab.url is browser-attested — a page cannot forge it. When700        // the request does not come from a tab at all (popup surfaces use701        // GET_ENTRY_FOR_EDIT, not this), refuse.702        if (sender.tab !== undefined || sender.url !== undefined) {703          let senderDomain: string | null = null;704          try {705            const rawUrl = sender.tab?.url ?? sender.url ?? "";706            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;707          } catch {708            senderDomain = null;709          }710          if (!senderDomain) return { ok: false, error: "origin_unverified" };711712          const entryDomains = new Set<string>();713          const primary = extractDomain(entry.url ?? "");714          if (primary) entryDomains.add(primary);715          for (const extra of entry.additionalUrls ?? []) {716            const d = extractDomain(extra);717            if (d) entryDomains.add(d);718          }719720          // explicitSummon=true means the user actively picked this entry721          // from the cross-domain search affordance — an intentional722          // off-domain fill. Passive fill paths must stay domain-bound.723          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {724            // Domain mismatch — refuse silently (no oracle about which ids exist).725            return { ok: false, error: "entry_not_found" };726          }727        }728        // Strip the passkey credential AND the raw base32 TOTP seed from the729        // response. Content scripts never need either: the private key is the730        // authenticator's, and handing over the TOTP seed would let a731        // compromised content script mint valid codes indefinitely (SEV-3-C).732        // Generate the *current* 6-digit code here in the background and send733        // only that, plus the seconds left so the UI can render a countdown.734        // Also drop passwordHistory: filling needs only the *current* password.735        // Handing every past password to a content script during passive736        // autofill on an arbitrary page would widen the blast radius of a737        // compromised page far beyond the one credential being filled.738        const {739          passkey: _strippedPasskey,740          totp: seed,741          totpAlgorithm,742          totpDigits,743          totpPeriod,744          passwordHistory: _ph,745          ...safeEntry746        } = entry;747        let totpCode: string | undefined;748        let totpRemaining: number | undefined;749        if (seed) {750          try {751            // PCH-01-019: honour stored algorithm/digits/period (defaults apply752            // when these are undefined, i.e. legacy bare-seed entries).753            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);754            totpCode = generated.code;755            totpRemaining = generated.remaining;756          } catch {757            totpCode = undefined;758          }759        }760        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };761      }762      // Trusted full-entry fetch for Peach's own inline-popup surfaces that763      // genuinely need the raw TOTP seed: the edit form (which re-saves the764      // seed and would otherwise wipe it) and nothing else. Unlike765      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside766      // the inline popup, never during passive autofill on an arbitrary page.767      // The passkey credential is still stripped — the edit form never touches it.768      case "GET_ENTRY_FOR_EDIT": {769        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };770        const { id, explicitSummon } = msg.payload as {771          id: string;772          explicitSummon?: boolean;773        };774        const entry = vault.getEntryById(id);775        if (!entry) return { ok: false, error: "entry_not_found" };776777        // PCH-01-006: re-validate the browser-attested sender origin, mirroring778        // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and779        // full password history — at least as sensitive as the fill response — so780        // the boundary must be enforced here, not only by UI reachability. Today781        // the sole caller is the popup (no sender.tab, so this is a structural782        // no-op), but a future tab-context caller or an id leak would otherwise783        // inherit a full-credential oracle. Unlike the fill path we SKIP (not784        // refuse) when no sender domain resolves, to keep the popup caller working.785        if (sender.tab !== undefined || sender.url !== undefined) {786          let senderDomain: string | null = null;787          try {788            const rawUrl = sender.tab?.url ?? sender.url ?? "";789            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;790          } catch {791            senderDomain = null;792          }793          if (senderDomain) {794            const entryDomains = new Set<string>();795            const primary = extractDomain(entry.url ?? "");796            if (primary) entryDomains.add(primary);797            for (const extra of entry.additionalUrls ?? []) {798              const d = extractDomain(extra);799              if (d) entryDomains.add(d);800            }801            if (explicitSummon !== true && !entryDomains.has(senderDomain)) {802              return { ok: false, error: "entry_not_found" }; // no id oracle803            }804          }805        }806807        const { passkey: _passkey, ...safeEntry } = entry;808        return { ok: true, data: safeEntry };809      }810      case "COPY": {811        // AUD-002: shape-validate the payload before passing to the clipboard812        // helper. A raw cast lets a malformed message reach the clipboard API813        // with a non-string and throw.814        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {815          text?: unknown;816          label?: unknown;817          alreadyWritten?: unknown;818        };819        if (typeof text !== "string" || typeof label !== "string") {820          return { ok: false, error: "invalid_payload" };821        }822        await copyToClipboard(text, label, Boolean(alreadyWritten));823        return { ok: true, clearSeconds: getEffectiveClearSeconds() };824      }825      case "CHECK_ALL_BREACHES": {826        const allEntries = vault.getEntries();827        const results: Record<string, number> = {};828        for (const entry of allEntries) {829          if (entry.type === "note") continue;830          if (!entry.password) continue;831          results[entry.id] = await vault.checkBreach(entry.password);832          // Small delay — be a good citizen to the HIBP API833          await new Promise((r) => setTimeout(r, 200));834        }835        // Persist any non-zero counts back to entries836        for (const [id, count] of Object.entries(results)) {837          const entry = vault.getEntryById(id);838          if (entry && (entry.breach ?? 0) !== count) {839            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });840          }841        }842        return { ok: true, data: results };843      }844      case "GET_SETTINGS":845        return { ok: true, data: await vault.ensureSettingsLoaded() };846      case "UPDATE_SETTINGS": {847        const patch = msg.payload;848        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {849          return { ok: false, error: "invalid_payload" };850        }851        await vault.updateSettings(patch as vault.VaultSettings);852        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {853          await setupAutoLock();854          if (vault.isUnlocked()) touchAutoLock();855        }856        return { ok: true };857      }858      case "GET_PENDING_PASSKEY":859        return { ok: true, data: await getPendingPasskeyRequest() };860      case "APPROVE_PASSKEY": {861        const { requestId } = msg.payload as { requestId: number };862        await resolvePendingPasskeyRequest(requestId, true);863        return { ok: true };864      }865      case "DENY_PASSKEY": {866        const { requestId } = msg.payload as { requestId: number };867        await resolvePendingPasskeyRequest(requestId, false);868        return { ok: true };869      }870      case "GET_PASSKEY_PROVIDER_STATE":871        return { ok: true, data: await getPasskeyProviderState() };872      case "SET_PASSKEY_PROVIDER_ENABLED": {873        const { enabled } = msg.payload as { enabled: boolean };874        // Disabling is always free; gating fires only when a free user is875        // trying to turn passkey interception on.876        if (enabled) {877          const gate = await requirePro("passkeys");878          if (!gate.allowed) return { ok: false, error: "pro_required" };879        }880        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };881      }882      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS883      // endpoint. Intentional product behavior — users configure their own884      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private885      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-886      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to887      // users that the entry title leaves the device when the canary fires.888      case "FIRE_CANARY_PING": {889        // Canary alert fires unconditionally for any entry with canary: true.890        // The Pro gate only governs creation/flagging of canary entries; once891        // an entry is flagged, the alert path is a security property and must892        // never be license-gated.893        const { webhookUrl, entryTitle, trigger } = msg.payload as {894          webhookUrl: string;895          entryTitle: string;896          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";897        };898        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {899          return { ok: false, error: "invalid_webhook_url" };900        }901        // LV-3: debounce non-test pings per (webhook, entry) so a page that902        // strobes focus/fill events can't turn the canary into a request903        // firehose at the user's endpoint. Test pings are exempt — they are904        // explicit user clicks in the settings UI and are awaited for905        // feedback. The FIRST ping in a window always goes out, so the906        // dead-man's-switch property (canary fires on access) is preserved;907        // only repeats within the window are coalesced.908        if (trigger !== "test") {909          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;910          const stored = await chrome.storage.local.get(rlKey);911          const last = (stored as Record<string, unknown>)[rlKey];912          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {913            return { ok: true, data: { rateLimited: true } };914          }915          await chrome.storage.local.set({ [rlKey]: Date.now() });916        }917        const body = JSON.stringify({918          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",919          entry: entryTitle,920          trigger,921          timestamp: new Date().toISOString(),922          source: "peach-extension",923        });924        if (trigger === "test") {925          // Permitted outbound fetch: user-configured canary alert endpoint926          // (validated by isAllowedCanaryWebhookUrl above). This is the927          // only non-HIBP outbound call in the extension — see928          // Projects.md §3.7. Test pings are awaited so the UI can show929          // success/failure.930          try {931            const res = await fetch(webhookUrl, {932              method: "POST",933              headers: { "Content-Type": "application/json" },934              body,935            });936            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };937          } catch (err) {938            return { ok: false, error: err instanceof Error ? err.message : "network_error" };939          }940        }941        // Non-test triggers are fire-and-forget942        fetch(webhookUrl, {943          method: "POST",944          headers: { "Content-Type": "application/json" },945          body,946        }).catch(() => {});947        return { ok: true };948      }949      case "ACTIVATE_LICENSE": {950        const { key } = msg.payload as { key: string };951        const licenseInfo = await activateLicense(key);952        return { ok: true, data: licenseInfo };953      }954      case "GET_LICENSE": {955        const licenseInfo = await getLicenseInfo();956        return { ok: true, data: licenseInfo };957      }958      case "GET_LICENSE_KEY": {959        const key = await getLicenseKey();960        return { ok: true, data: key };961      }962      case "DEACTIVATE_LICENSE": {963        await deactivateLicense();964        return { ok: true };965      }966      case "SHOULD_PLAY_CELEBRATION": {967        const should = await shouldPlayCelebration();968        return { ok: true, data: should };969      }970      case "MARK_CELEBRATION_PLAYED": {971        await markCelebrationPlayed();972        return { ok: true };973      }974      case "GET_CODEX_VAULT_DATA": {975        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the976        // popup navigates to the License section without further coordination.977        const gate = await requirePro("codex");978        if (!gate.allowed) return { ok: false, error: "pro_required" };979        return await handleGetCodexVaultData();980      }981      case "ESTIMATE_CODEX_PAGES": {982        const gate = await requirePro("codex");983        if (!gate.allowed) return { ok: false, error: "pro_required" };984        return await handleEstimateCodexPages();985      }986      case "RESTORE_FROM_CODEX": {987        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still988        // be able to restore a vault that was printed by a Pro user.989        // DO NOT add a Pro gate here.990        const payload = msg.payload as CodexRestorePayload;991        return await handleRestoreFromCodex(payload);992      }993      case "OPEN_PRO_GATE": {994        // Content script requests: open popup and navigate to License section.995        const { feature } = (msg.payload ?? {}) as { feature?: string };996        if (chrome.storage.session) {997          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });998        }999        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1000        return { ok: true };1001      }1002      case "OPEN_POPUP": {1003        // Content script asks to open the trusted extension popup — used by the1004        // inline locked bubble so the master password is entered in the popup,1005        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1006        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1007        // toolbar icon. The badge already signals Peach needs attention.1008        //1009        // Set a session flag so the popup knows it was opened for inline unlock1010        // and should close itself once the vault is unlocked (returning the user1011        // to the inline autofill selector on the page).1012        if (chrome.storage.session) {1013          await chrome.storage.session.set({ peach_inline_unlock: true });1014        }1015        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1016        return { ok: true };1017      }1018      case "GET_IDENTITIES": {1019        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1020        return { ok: true, data: vault.getIdentities() };1021      }1022      case "TOUCH_AUTO_LOCK": {1023        // touchAutoLock() is already called by shouldRefreshAutoLock above;1024        // this case just gives the popup a typed message to keep the session alive.1025        return { ok: true };1026      }1027      case "GET_ADVANCED_HEALTH_REPORT": {1028        const gate = await requirePro("advanced_health");1029        if (!gate.allowed) return { ok: false, error: "pro_required" };1030        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1031        const report = await buildAdvancedHealthReport(vault.getEntries());1032        return { ok: true, data: report };1033      }1034      case "IS_DURESS_ENABLED": {1035        const enabled = await vault.isDuressEnabled();1036        return { ok: true, data: enabled };1037      }1038      case "SETUP_DURESS": {1039        // Single enforcement point for the Duress Vault Pro gate. Free users1040        // who somehow reach this handler are rejected here; the popup also1041        // pre-checks isPro() to avoid showing the setup form to free users,1042        // but server-side is the actual security boundary.1043        const gate = await requirePro("duress_vault");1044        if (!gate.allowed) return { ok: false, error: "pro_required" };1045        // MV3 service workers restart after inactivity, losing the in-memory1046        // derived key. Detect this before calling setupDuress so the popup1047        // can show a meaningful prompt to re-lock and re-unlock.1048        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1049        const { duressPassword } = msg.payload as { duressPassword: string };1050        await vault.setupDuress(duressPassword);1051        return { ok: true };1052      }1053      case "DISABLE_DURESS": {1054        await vault.disableDuress();1055        return { ok: true };1056      }1057      case "VERIFY_MAIN_PASSWORD": {1058        const { password } = msg.payload as { password: string };1059        const ok = await vault.verifyMainPassword(password);1060        return { ok: true, data: ok };1061      }1062      case "CHANGE_PASSWORD": {1063        const { currentPassword, newPassword } = msg.payload as {1064          currentPassword: string;1065          newPassword: string;1066        };1067        const changed = await vault.changePassword(currentPassword, newPassword);1068        return changed1069          ? { ok: true }1070          : { ok: false, error: "incorrect_current_password" };1071      }1072      case "GET_SITE_PASSWORD_POLICY": {1073        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1074        if (!tab?.id) return { ok: true, data: null };1075        try {1076          const response = await chrome.tabs.sendMessage(tab.id, {1077            type: "GET_SITE_PASSWORD_POLICY",1078          });1079          return (response as MessageResponse) ?? { ok: true, data: null };1080        } catch {1081          return { ok: true, data: null };1082        }1083      }1084      case "RECORD_MANUAL_SUMMON": {1085        const { domain } = msg.payload as { domain: string };1086        const settings = vault.getSettings();1087        const existing = settings.manualSummonDomains?.[domain];1088        const now = Date.now();1089        await vault.updateSettings({1090          manualSummonDomains: {1091            ...settings.manualSummonDomains,1092            [domain]: {1093              firstSummonedAt: existing?.firstSummonedAt ?? now,1094              summonCount: (existing?.summonCount ?? 0) + 1,1095              lastSummonedAt: now,1096            },1097          },1098        });1099        return { ok: true };1100      }1101      case "DECLINE_CARD_SAVE": {1102        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1103        await vault.declineCardSaveOffer(last4, expMonth, expYear);1104        return { ok: true };1105      }1106      case "IS_CARD_DECLINED": {1107        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1108        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1109        return { ok: true, data: declined };1110      }1111      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1112        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1113          rpId?: string;1114          rpName?: string;1115          userName?: string;1116          userDisplayName?: string;1117        };1118        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1119        return await initiateFirefoxPasskeyCreate({1120          rpId,1121          rpName: rpName ?? rpId,1122          userName,1123          userDisplayName,1124        });1125      }11261127      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1128        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1129        if (!payload) return { ok: false, error: "missing_payload" };1130        return await completeFirefoxPasskeyCreate(payload);1131      }11321133      case "PASSKEY_OFFER_DECLINE": {1134        const { domain } = (msg.payload ?? {}) as { domain?: string };1135        if (!domain) return { ok: false, error: "domain_required" };1136        await recordPasskeyOfferDecline(domain);1137        return { ok: true };1138      }11391140      case "GET_PASSKEY_OFFER_DECLINED": {1141        const { domain } = (msg.payload ?? {}) as { domain?: string };1142        if (!domain) return { ok: false, error: "domain_required" };1143        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1144      }11451146      case "PASSKEY_HAS_CREDENTIALS": {1147        const payload = msg.payload as {1148          rpId?: string;1149          allowCredentials?: Array<{ id: string; type?: string }>;1150        } | undefined;1151        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1152        return await handlePasskeyHasCredentials({1153          rpId: payload.rpId,1154          allowCredentials: payload.allowCredentials ?? [],1155        }, attestedSenderOrigin(sender));1156      }11571158      case "PASSKEY_CREATE": {1159        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1160        if (!payload?.rpId || !payload?.userName) {1161          return { ok: false, error: "rpid_and_username_required" };1162        }1163        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1164      }11651166      case "PASSKEY_GET": {1167        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1168        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1169        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1170      }11711172      case "PASSKEY_AUTH_RESPONSE": {1173        const { requestId, approved } = (msg.payload ?? {}) as {1174          requestId?: string | number;1175          approved?: boolean;1176        };1177        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1178          return { ok: false, error: 'requestId and approved required' };1179        }1180        await resolvePendingPasskeyRequest(Number(requestId), approved);1181        return { ok: true };1182      }11831184      case "GET_PASSKEY_FOR_DOMAIN": {1185        const { domain } = (msg.payload ?? {}) as { domain?: string };1186        if (!domain) return { ok: false, error: "domain_required" };1187        // Scope to the caller's own origin: a page may only ask about passkeys1188        // for a domain it actually owns, so an arbitrary page cannot enumerate1189        // which sites the user holds passkeys for or read the username (audit MEDIUM).1190        const origin = attestedSenderOrigin(sender);1191        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1192        if (!vault.isUnlocked()) return { ok: true, data: null };1193        const match = vault1194          .getEntries()1195          .find((entry) => entry.passkey?.rpId === domain);1196        if (!match || !match.passkey) return { ok: true, data: null };1197        // Slim shape — only the fields State 11 needs. Never expose private1198        // key material, even though this is locked behind isUnlocked.1199        return {1200          ok: true,1201          data: {1202            rpId: match.passkey.rpId,1203            userName: match.passkey.userName,1204            browser: match.passkey.browser,1205          },1206        };1207      }12081209      case "DESTROY_VAULT": {1210        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1211        // storage.local.clear() wipes every Peach key (slots, settings, license,1212        // onboarded flag, history, sync state, declined cards, recall, etc.);1213        // session.clear() wipes pending passkey requests + pro-notice queues.1214        // Caller (Panic.tsx) handles UI navigation back to onboarding.1215        //1216        // The Pro license is the one thing that must survive: the user paid for1217        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1218        // Capture it before the clear and restore it after. peach_pro_celebrated1219        // rides along so the Pro celebration doesn't replay on the next unlock.1220        const preserved = await chrome.storage.local.get([1221          "peach_license",1222          "peach_pro_celebrated",1223        ]);1224        vault.lock();1225        await storageClear();1226        await vault.clearVaultHistory();1227        const toRestore: Record<string, unknown> = {};1228        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1229        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1230        if (Object.keys(toRestore).length > 0) {1231          await chrome.storage.local.set(toRestore);1232        }1233        if (chrome.storage.session) {1234          await chrome.storage.session.clear();1235        }1236        return { ok: true };1237      }12381239      case "SUBMIT_FEEDBACK": {1240        const { category, message, version, browser } = msg.payload as {1241          category: string;1242          message: string;1243          version: string;1244          browser: string;1245        };1246        if (!message.trim()) return { ok: false, error: "message_empty" };1247        if (!FEEDBACK_ENDPOINT) return { ok: true };1248        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1249          return { ok: false, error: "invalid_feedback_endpoint" };1250        }1251        try {1252          const res = await fetch(FEEDBACK_ENDPOINT, {1253            method: "POST",1254            headers: { "Content-Type": "application/json" },1255            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1256          });1257          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1258        } catch (err) {1259          return { ok: false, error: err instanceof Error ? err.message : "network_error" };1260        }1261      }1262      // Android-only: biometric unlock with pre-derived key.1263      case "UNLOCK_WITH_KEY": {1264        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1265        if (!isNativePlatform()) {1266          return { ok: false, error: "desktop_only_uses_password" };1267        }1268        try {1269          const result = await vault.unlockWithKey(masterKeyHex);1270          if (result.ok) {1271            onVaultUnlocked();1272            await publishInMemoryVault(result.entries);1273          }1274          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1275        } catch {1276          return { ok: false, error: "invalid_key" };1277        }1278      }1279      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1280      case "GET_DERIVED_KEY": {1281        if (!isNativePlatform()) {1282          return { ok: false, error: "android_only" };1283        }1284        if (!vault.isUnlocked()) {1285          return { ok: false, error: "vault_locked" };1286        }1287        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1288      }1289      case "GET_IDENTITY_SUGGESTIONS": {1290        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1291        const entries = vault.getEntries();1292        const suggestions = buildIdentitySuggestions(entries);1293        return { ok: true, data: { suggestions } };1294      }1295      case "POPULATE_INLINE_VAULT": {1296        if (!isNativePlatform()) return { ok: false };1297        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1298        const entries = vault.getEntries();1299        await publishInMemoryVault(entries);1300        return { ok: true };1301      }1302      case "ML_INIT":1303        return { ok: true };13041305      case "ML_PREDICT_BATCH": {1306        // AUD-002: shape-validate before forwarding to the ML helper.1307        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1308        if (!Array.isArray(featuresArray)) {1309          return { ok: false, error: "invalid_payload" };1310        }1311        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1312      }13131314      // ── Chirp Sync (v3) ───────────────────────────────────────────────1315      // Returns the public-facing local identity needed by the popup to1316      // drive Phase-1 audio pairing. The private long-term key never1317      // leaves the background.1318      case "CHIRP_GET_LOCAL_IDENTITY": {1319        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1320        const proCheck = await requirePro("sync");1321        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1322        // Identity derives from the stable root key, not the password-derived1323        // key, so pairing survives a master-password change (SEV-2-B).1324        const masterKeyHex = vault.getRootKeyHex();1325        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1326        const masterKey = unhexBytes(masterKeyHex);1327        try {1328          const identity = await buildLocalIdentity(masterKey);1329          return { ok: true, data: identity };1330        } finally {1331          masterKey.fill(0);1332        }1333      }13341335      case "CHIRP_COMPLETE_PAIRING": {1336        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1337        const proCheck = await requirePro("sync");1338        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1339        const paired = (msg.payload as { paired?: unknown })?.paired;1340        if (typeof paired !== "object" || paired === null) {1341          return { ok: false, error: "invalid_payload" };1342        }1343        const candidate = paired as Record<string, unknown>;1344        if (1345          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1346          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1347          typeof candidate.deviceType !== "string" ||1348          typeof candidate.longTermPublicKeyHex !== "string" ||1349          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1350          (1351            candidate.signingPublicKeyHex !== undefined &&1352            (1353              typeof candidate.signingPublicKeyHex !== "string" ||1354              !/^[0-9a-f]{64}$/.test(candidate.signingPublicKeyHex)1355            )1356          ) ||1357          typeof candidate.pairedAt !== "number"1358        ) {1359          return { ok: false, error: "invalid_paired_device" };1360        }1361        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1362        return { ok: true };1363      }13641365      case "CHIRP_LIST_PAIRED_DEVICES": {1366        const devices = await listPairedDevicesV3();1367        return { ok: true, data: { devices } };1368      }13691370      case "CHIRP_UNPAIR_DEVICE": {1371        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1372        if (typeof deviceId !== "string" || !deviceId) {1373          return { ok: false, error: "invalid_payload" };1374        }1375        await removePairedDeviceByIdV3(deviceId);1376        return { ok: true };1377      }13781379      case "CHIRP_RENAME_LOCAL_DEVICE": {1380        const { name } = (msg.payload ?? {}) as { name?: string };1381        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1382        await setDeviceNameV3(name);1383        return { ok: true };1384      }13851386      case "TRIGGER_SYNC": {1387        const payload = (msg.payload ?? {}) as {1388          reason?: "vault_change" | "foreground" | "manual" | "mdns";1389          force?: boolean;1390          deviceId?: string;1391          discoveredIp?: string;1392          discoveredPort?: number;1393        };1394        const reason = payload.reason ?? "foreground";13951396        // mDNS discovery delivers a fresh (ip, port) resolved by the native1397        // side. Update the cached address before the sync runner tries to1398        // connect — avoids a subnet probe on the very next round.1399        if (1400          reason === "mdns" &&1401          typeof payload.deviceId === "string" &&1402          typeof payload.discoveredIp === "string"1403        ) {1404          const { findPairedDeviceById, setLastKnownIp } = await import("./paired-devices");1405          const device = await findPairedDeviceById(payload.deviceId);1406          if (device?.longTermPublicKeyHex) {1407            await setLastKnownIp(device.longTermPublicKeyHex, payload.discoveredIp).catch(() => undefined);1408          }1409        }14101411        const { triggerSyncIfReachable } = await import("./sync-trigger");1412        void triggerSyncIfReachable({ reason, force: payload.force === true });1413        return { ok: true };1414      }14151416      case "GET_SYNC_STATE": {1417        const { getSyncState } = await import("./sync-trigger");1418        return { ok: true, data: getSyncState() };1419      }14201421      case "GET_SYNC_ALERTS": {1422        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1423        const alerts = await getPendingSyncAlerts();1424        // The popup reads on open and acknowledges with consume:true after1425        // rendering, so a popup crash between read and render doesn't lose1426        // the alerts.1427        if (consume) await clearPendingSyncAlerts();1428        return { ok: true, data: alerts };1429      }14301431      case "GET_PENDING_VOUCHED_DEVICES": {1432        return { ok: true, data: await listPendingVouchedDevices() };1433      }1434      case "CONFIRM_VOUCHED_DEVICE": {1435        const { deviceId } = msg.payload as { deviceId: string };1436        const pending = await getPendingVouchedDevice(deviceId);1437        if (!pending) return { ok: false, error: "not_pending" };1438        await upsertPairedDeviceV3({1439          deviceId: pending.deviceId,1440          deviceName: pending.deviceName,1441          deviceType:1442            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1443          longTermPublicKeyHex: pending.longTermPublicKeyHex,1444          signingPublicKeyHex: pending.signingPublicKeyHex,1445          wsPort: pending.wsPort,1446          pairedAt: pending.pairedAt,1447          trustSource: "vouched",1448        });1449        await removePendingVouchedDevice(deviceId);1450        return { ok: true };1451      }1452      case "REJECT_VOUCHED_DEVICE": {1453        const { deviceId } = msg.payload as { deviceId: string };1454        await removePendingVouchedDevice(deviceId);1455        return { ok: true };1456      }1457      case "ROTATE_SYNC_IDENTITY": {1458        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1459        const result = await vault.rotateSyncIdentity();1460        return result.ok ? { ok: true } : { ok: false, error: result.error };1461      }14621463      default:1464        return { ok: false, error: "unknown_message_type" };1465    }1466  } catch (err) {1467    return {1468      ok: false,1469      error: err instanceof Error ? err.message : "operation_failed",1470    };1471  }1472}14731474// --- Mobile platform helpers ---14751476// Android: populates the in-memory vault used by PeachAutofillService.1477async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1478  const plugin = nativePlugin<{1479    setEntries?: (args: {1480      entries: Array<{1481        id: string;1482        title: string;1483        username: string;1484        email: string;1485        password: string;1486        url: string;1487        totp: string;1488        additionalUrls: string[];1489      }>;1490    }) => Promise<void>;1491  }>("InMemoryVaultPlugin");1492  if (!plugin?.setEntries) return;1493  await plugin.setEntries({1494    entries: entries.map((e) => ({1495      id: e.id,1496      title: e.title ?? "",1497      username: e.username ?? "",1498      email: (e as VaultEntry & { email?: string }).email ?? "",1499      password: e.password ?? "",1500      url: e.url ?? "",1501      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1502      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1503    })),1504  });1505}15061507// Android: clear the autofill in-memory store on lock.1508async function clearInMemoryVault(): Promise<void> {1509  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1510  if (!plugin?.clearEntries) return;1511  await plugin.clearEntries();1512}15131514// Returns username use-counts from the vault, sorted by frequency. Each row1515// also carries the entry's email so the popup can suggest the email/username1516// pair the user has actually used together.1517function buildIdentitySuggestions(1518  entries: VaultEntry[],1519): Array<{ email: string; username: string; count: number }> {1520  const usernameCounts = new Map<string, number>();1521  const usernameEmail = new Map<string, string>();1522  for (const entry of entries) {1523    const username = entry.username ?? "";1524    const email = (entry as VaultEntry & { email?: string }).email ?? "";1525    if (!username && !email) continue;1526    const key = username || email;1527    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1528    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1529  }1530  return Array.from(usernameCounts.entries())1531    .sort((a, b) => b[1] - a[1])1532    .map(([username, count]) => ({1533      email: usernameEmail.get(username) ?? "",1534      username,1535      count,1536    }));1537}15381539/** Notify all content scripts that the vault just became available. */1540function broadcastToContentScripts(message: { type: string }): void {1541  if (!chrome.tabs?.query) return;1542  chrome.tabs.query({}, (tabs) => {1543    for (const tab of tabs) {1544      if (tab.id !== undefined) {1545        chrome.tabs.sendMessage(tab.id, message).catch(() => {1546          // Tab may not have a content script — silently ignore1547        });1548      }1549    }1550  });1551}15521553function shouldRefreshAutoLock(type: MessageType): boolean {1554  return (1555    type !== "HAS_VAULT" &&1556    type !== "IS_UNLOCKED" &&1557    type !== "GET_VAULT_STATUS" &&1558    type !== "LOCK" &&1559    type !== "UPDATE_SETTINGS" &&1560    type !== "GET_PENDING_PASSKEY" &&1561    type !== "GET_PASSKEY_PROVIDER_STATE" &&1562    type !== "DECLINE_CARD_SAVE" &&1563    type !== "IS_CARD_DECLINED" &&1564    type !== "SUBMIT_FEEDBACK"1565  );1566}15671568function isAllowedCanaryWebhookUrl(value: string): boolean {1569  try {1570    const url = new URL(value);1571    if (url.protocol !== "https:") return false;15721573    const hostname = url.hostname.toLowerCase();1574    if (1575      hostname === "localhost" ||1576      hostname.endsWith(".localhost") ||1577      isPrivateIpv4(hostname) ||1578      isPrivateIpv6(hostname)1579    ) {1580      return false;1581    }15821583    return true;1584  } catch {1585    return false;1586  }1587}15881589function isPrivateIpv4(hostname: string): boolean {1590  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1591    return true;1592  }15931594  const octets = hostname.split(".").map((part) => Number(part));1595  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1596    return false;1597  }15981599  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1600}16011602function isPrivateIpv6(hostname: string): boolean {1603  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1604  return (1605    normalized === "::1" ||1606    normalized.startsWith("fc") ||1607    normalized.startsWith("fd") ||1608    normalized.startsWith("fe80:")1609  );1610}