messages.ts

66.2 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard } 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          const entry = await vault.addEntry({546            type: "note",547            title: title || "Untitled",548            notes: body,549            createdAt: now,550            modifiedAt: now,551          } as any);552          return { ok: true, data: entry };553        }554      }555      case "DELETE_NOTE": {556        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };557        const { id } = msg.payload as { id: string };558        await vault.deleteEntry(id);559        return { ok: true };560      }561      case "GET_NOTES": {562        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };563        const notes = vault.getEntries().filter(564          (e) => e.type === "note" && !e.deletedAt565        );566        return { ok: true, data: notes } as MessageResponse;567      }568      case "SEARCH_VAULT": {569        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };570        // AUD-002: shape-validate the payload before calling string methods.571        // A raw cast lets a malformed message crash the handler with TypeError.572        const { query } = (msg.payload ?? {}) as { query?: unknown };573        if (typeof query !== "string") {574          return { ok: false, error: "invalid_payload" };575        }576        const q = query.toLowerCase();577        const searchResults = vault.getEntries().filter(578          (e) =>579            !e.deletedAt &&580            (e.title.toLowerCase().includes(q) ||581              e.notes?.toLowerCase().includes(q) ||582              e.username?.toLowerCase().includes(q))583        );584        return { ok: true, data: searchResults } as MessageResponse;585      }586      case "AUTOFILL_QUERY": {587        if (!vault.isUnlocked()) {588          return { ok: false, error: "vault_locked" };589        }590        let { includeAll } = msg.payload as { includeAll?: boolean };591        const { domain, kind, userGesture } = msg.payload as {592          domain: string;593          kind?: "login" | "card" | "totp";594          userGesture?: boolean;595        };596        // MV-2: the vault-wide inventory (every title/username/email/url)597        // may only leave the background on an explicit user gesture — the598        // user opening the search affordance — never on passive form focus.599        // userGesture is self-declared by our own content script; the value600        // of this gate is that PASSIVE code paths (which never set it)601        // cannot ship the inventory, shrinking what a compromised page that602        // merely triggers focus events can observe.603        if (includeAll && userGesture !== true) {604          includeAll = false;605        }606        // kind="card": return saved cards as compact summaries for the607        // inline card silver platter. Cards are not domain-scoped — every608        // saved card is a candidate on every checkout page — so domain is609        // ignored when kind === "card".610        if (kind === "card") {611          const cards = vault.getEntries().filter((e) => e.type === "card");612          return {613            ok: true,614            data: cards.map((e) => ({615              id: e.id,616              title: e.cardNickname || e.title,617              cardholderName: e.cardholderName,618              last4: e.last4,619              expMonth: e.expMonth,620              expYear: e.expYear,621              network: e.network,622            })),623          };624        }625        if (kind === "totp") {626          const matches = (627            includeAll628              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")629              : vault.queryDomain(domain)630          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));631          return {632            ok: true,633            data: matches.map((e) => ({634              id: e.id,635              title: e.title,636              username: e.username,637              email: e.email,638              url: e.url,639              hasTotp: true,640            })),641          };642        }643        // The inline selector fills username+password into a form. Passkey-644        // only entries have no password to fill; sign-in for those goes645        // through the WebAuthn path instead. Filter them out everywhere so646        // the user doesn't see four "GitHub" rows that mostly do nothing.647        // Notes and cards never belonged here either.648        const matches = (649          includeAll650            ? vault651                .getEntries()652                .filter((entry) => entry.type !== "note" && entry.type !== "card")653            : vault.queryDomain(domain)654        ).filter((entry) => !isPasskeyOnly(entry));655        return {656          ok: true,657          data: matches.map((e) =>658            includeAll659              ? {660                  id: e.id,661                  title: e.title,662                  // username/email/url shipped so the inline popup's search663                  // affordance can match on them, not just titles. No secrets664                  // cross the boundary — same shape as the domain-matched665                  // response below minus hasTotp (which the search list666                  // doesn't surface).667                  username: e.username,668                  email: e.email,669                  url: e.url,670                  hasPasskey: e.passkey !== undefined,671                }672              : {673                  id: e.id,674                  title: e.title,675                  username: e.username,676                  email: e.email,677                  url: e.url,678                  hasTotp: Boolean(e.totp),679                  hasPasskey: e.passkey !== undefined,680                }681          ),682        };683      }684      case "GET_ENTRY_FOR_FILL": {685        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };686        const { id, explicitSummon } = msg.payload as {687          id: string;688          explicitSummon?: boolean;689        };690        const entry = vault.getEntryById(id);691        if (!entry) return { ok: false, error: "entry_not_found" };692        // Passkey-only entries (passkey credential, no password) cannot be693        // filled into a form — sign-in goes through the WebAuthn path. A694        // login that ALSO has a passkey is still fillable for its password.695        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };696697        // MV-1: re-validate the entry against the requesting tab's origin.698        // sender.tab.url is browser-attested — a page cannot forge it. When699        // the request does not come from a tab at all (popup surfaces use700        // GET_ENTRY_FOR_EDIT, not this), refuse.701        if (sender.tab !== undefined || sender.url !== undefined) {702          let senderDomain: string | null = null;703          try {704            const rawUrl = sender.tab?.url ?? sender.url ?? "";705            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;706          } catch {707            senderDomain = null;708          }709          if (!senderDomain) return { ok: false, error: "origin_unverified" };710711          const entryDomains = new Set<string>();712          const primary = extractDomain(entry.url ?? "");713          if (primary) entryDomains.add(primary);714          for (const extra of entry.additionalUrls ?? []) {715            const d = extractDomain(extra);716            if (d) entryDomains.add(d);717          }718719          // explicitSummon=true means the user actively picked this entry720          // from the cross-domain search affordance — an intentional721          // off-domain fill. Passive fill paths must stay domain-bound.722          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {723            // Domain mismatch — refuse silently (no oracle about which ids exist).724            return { ok: false, error: "entry_not_found" };725          }726        }727        // Strip the passkey credential AND the raw base32 TOTP seed from the728        // response. Content scripts never need either: the private key is the729        // authenticator's, and handing over the TOTP seed would let a730        // compromised content script mint valid codes indefinitely (SEV-3-C).731        // Generate the *current* 6-digit code here in the background and send732        // only that, plus the seconds left so the UI can render a countdown.733        // Also drop passwordHistory: filling needs only the *current* password.734        // Handing every past password to a content script during passive735        // autofill on an arbitrary page would widen the blast radius of a736        // compromised page far beyond the one credential being filled.737        const { passkey: _strippedPasskey, totp: seed, passwordHistory: _ph, ...safeEntry } = entry;738        let totpCode: string | undefined;739        let totpRemaining: number | undefined;740        if (seed) {741          try {742            const generated = generateTOTP(seed);743            totpCode = generated.code;744            totpRemaining = generated.remaining;745          } catch {746            totpCode = undefined;747          }748        }749        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };750      }751      // Trusted full-entry fetch for Peach's own inline-popup surfaces that752      // genuinely need the raw TOTP seed: the edit form (which re-saves the753      // seed and would otherwise wipe it) and nothing else. Unlike754      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside755      // the inline popup, never during passive autofill on an arbitrary page.756      // The passkey credential is still stripped — the edit form never touches it.757      case "GET_ENTRY_FOR_EDIT": {758        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };759        const { id, explicitSummon } = msg.payload as {760          id: string;761          explicitSummon?: boolean;762        };763        const entry = vault.getEntryById(id);764        if (!entry) return { ok: false, error: "entry_not_found" };765766        // PCH-01-006: re-validate the browser-attested sender origin, mirroring767        // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and768        // full password history — at least as sensitive as the fill response — so769        // the boundary must be enforced here, not only by UI reachability. Today770        // the sole caller is the popup (no sender.tab, so this is a structural771        // no-op), but a future tab-context caller or an id leak would otherwise772        // inherit a full-credential oracle. Unlike the fill path we SKIP (not773        // refuse) when no sender domain resolves, to keep the popup caller working.774        if (sender.tab !== undefined || sender.url !== undefined) {775          let senderDomain: string | null = null;776          try {777            const rawUrl = sender.tab?.url ?? sender.url ?? "";778            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;779          } catch {780            senderDomain = null;781          }782          if (senderDomain) {783            const entryDomains = new Set<string>();784            const primary = extractDomain(entry.url ?? "");785            if (primary) entryDomains.add(primary);786            for (const extra of entry.additionalUrls ?? []) {787              const d = extractDomain(extra);788              if (d) entryDomains.add(d);789            }790            if (explicitSummon !== true && !entryDomains.has(senderDomain)) {791              return { ok: false, error: "entry_not_found" }; // no id oracle792            }793          }794        }795796        const { passkey: _passkey, ...safeEntry } = entry;797        return { ok: true, data: safeEntry };798      }799      case "COPY": {800        // AUD-002: shape-validate the payload before passing to the clipboard801        // helper. A raw cast lets a malformed message reach the clipboard API802        // with a non-string and throw.803        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {804          text?: unknown;805          label?: unknown;806          alreadyWritten?: unknown;807        };808        if (typeof text !== "string" || typeof label !== "string") {809          return { ok: false, error: "invalid_payload" };810        }811        await copyToClipboard(text, label, Boolean(alreadyWritten));812        return { ok: true };813      }814      case "CHECK_ALL_BREACHES": {815        const allEntries = vault.getEntries();816        const results: Record<string, number> = {};817        for (const entry of allEntries) {818          if (entry.type === "note") continue;819          if (!entry.password) continue;820          results[entry.id] = await vault.checkBreach(entry.password);821          // Small delay — be a good citizen to the HIBP API822          await new Promise((r) => setTimeout(r, 200));823        }824        // Persist any non-zero counts back to entries825        for (const [id, count] of Object.entries(results)) {826          const entry = vault.getEntryById(id);827          if (entry && (entry.breach ?? 0) !== count) {828            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });829          }830        }831        return { ok: true, data: results };832      }833      case "GET_SETTINGS":834        return { ok: true, data: await vault.ensureSettingsLoaded() };835      case "UPDATE_SETTINGS": {836        const patch = msg.payload;837        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {838          return { ok: false, error: "invalid_payload" };839        }840        await vault.updateSettings(patch as vault.VaultSettings);841        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {842          await setupAutoLock();843          if (vault.isUnlocked()) touchAutoLock();844        }845        return { ok: true };846      }847      case "GET_PENDING_PASSKEY":848        return { ok: true, data: await getPendingPasskeyRequest() };849      case "APPROVE_PASSKEY": {850        const { requestId } = msg.payload as { requestId: number };851        await resolvePendingPasskeyRequest(requestId, true);852        return { ok: true };853      }854      case "DENY_PASSKEY": {855        const { requestId } = msg.payload as { requestId: number };856        await resolvePendingPasskeyRequest(requestId, false);857        return { ok: true };858      }859      case "GET_PASSKEY_PROVIDER_STATE":860        return { ok: true, data: await getPasskeyProviderState() };861      case "SET_PASSKEY_PROVIDER_ENABLED": {862        const { enabled } = msg.payload as { enabled: boolean };863        // Disabling is always free; gating fires only when a free user is864        // trying to turn passkey interception on.865        if (enabled) {866          const gate = await requirePro("passkeys");867          if (!gate.allowed) return { ok: false, error: "pro_required" };868        }869        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };870      }871      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS872      // endpoint. Intentional product behavior — users configure their own873      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private874      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-875      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to876      // users that the entry title leaves the device when the canary fires.877      case "FIRE_CANARY_PING": {878        // Canary alert fires unconditionally for any entry with canary: true.879        // The Pro gate only governs creation/flagging of canary entries; once880        // an entry is flagged, the alert path is a security property and must881        // never be license-gated.882        const { webhookUrl, entryTitle, trigger } = msg.payload as {883          webhookUrl: string;884          entryTitle: string;885          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";886        };887        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {888          return { ok: false, error: "invalid_webhook_url" };889        }890        // LV-3: debounce non-test pings per (webhook, entry) so a page that891        // strobes focus/fill events can't turn the canary into a request892        // firehose at the user's endpoint. Test pings are exempt — they are893        // explicit user clicks in the settings UI and are awaited for894        // feedback. The FIRST ping in a window always goes out, so the895        // dead-man's-switch property (canary fires on access) is preserved;896        // only repeats within the window are coalesced.897        if (trigger !== "test") {898          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;899          const stored = await chrome.storage.local.get(rlKey);900          const last = (stored as Record<string, unknown>)[rlKey];901          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {902            return { ok: true, data: { rateLimited: true } };903          }904          await chrome.storage.local.set({ [rlKey]: Date.now() });905        }906        const body = JSON.stringify({907          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",908          entry: entryTitle,909          trigger,910          timestamp: new Date().toISOString(),911          source: "peach-extension",912        });913        if (trigger === "test") {914          // Permitted outbound fetch: user-configured canary alert endpoint915          // (validated by isAllowedCanaryWebhookUrl above). This is the916          // only non-HIBP outbound call in the extension — see917          // Projects.md §3.7. Test pings are awaited so the UI can show918          // success/failure.919          try {920            const res = await fetch(webhookUrl, {921              method: "POST",922              headers: { "Content-Type": "application/json" },923              body,924            });925            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };926          } catch (err) {927            return { ok: false, error: err instanceof Error ? err.message : "network_error" };928          }929        }930        // Non-test triggers are fire-and-forget931        fetch(webhookUrl, {932          method: "POST",933          headers: { "Content-Type": "application/json" },934          body,935        }).catch(() => {});936        return { ok: true };937      }938      case "ACTIVATE_LICENSE": {939        const { key } = msg.payload as { key: string };940        const licenseInfo = await activateLicense(key);941        return { ok: true, data: licenseInfo };942      }943      case "GET_LICENSE": {944        const licenseInfo = await getLicenseInfo();945        return { ok: true, data: licenseInfo };946      }947      case "GET_LICENSE_KEY": {948        const key = await getLicenseKey();949        return { ok: true, data: key };950      }951      case "DEACTIVATE_LICENSE": {952        await deactivateLicense();953        return { ok: true };954      }955      case "SHOULD_PLAY_CELEBRATION": {956        const should = await shouldPlayCelebration();957        return { ok: true, data: should };958      }959      case "MARK_CELEBRATION_PLAYED": {960        await markCelebrationPlayed();961        return { ok: true };962      }963      case "GET_CODEX_VAULT_DATA": {964        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the965        // popup navigates to the License section without further coordination.966        const gate = await requirePro("codex");967        if (!gate.allowed) return { ok: false, error: "pro_required" };968        return await handleGetCodexVaultData();969      }970      case "ESTIMATE_CODEX_PAGES": {971        const gate = await requirePro("codex");972        if (!gate.allowed) return { ok: false, error: "pro_required" };973        return await handleEstimateCodexPages();974      }975      case "RESTORE_FROM_CODEX": {976        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still977        // be able to restore a vault that was printed by a Pro user.978        // DO NOT add a Pro gate here.979        const payload = msg.payload as CodexRestorePayload;980        return await handleRestoreFromCodex(payload);981      }982      case "OPEN_PRO_GATE": {983        // Content script requests: open popup and navigate to License section.984        const { feature } = (msg.payload ?? {}) as { feature?: string };985        if (chrome.storage.session) {986          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });987        }988        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }989        return { ok: true };990      }991      case "OPEN_POPUP": {992        // Content script asks to open the trusted extension popup — used by the993        // inline locked bubble so the master password is entered in the popup,994        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a995        // user gesture + Chrome 127+/Firefox; on failure the user clicks the996        // toolbar icon. The badge already signals Peach needs attention.997        //998        // Set a session flag so the popup knows it was opened for inline unlock999        // and should close itself once the vault is unlocked (returning the user1000        // to the inline autofill selector on the page).1001        if (chrome.storage.session) {1002          await chrome.storage.session.set({ peach_inline_unlock: true });1003        }1004        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1005        return { ok: true };1006      }1007      case "GET_IDENTITIES": {1008        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1009        return { ok: true, data: vault.getIdentities() };1010      }1011      case "TOUCH_AUTO_LOCK": {1012        // touchAutoLock() is already called by shouldRefreshAutoLock above;1013        // this case just gives the popup a typed message to keep the session alive.1014        return { ok: true };1015      }1016      case "GET_ADVANCED_HEALTH_REPORT": {1017        const gate = await requirePro("advanced_health");1018        if (!gate.allowed) return { ok: false, error: "pro_required" };1019        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1020        const report = await buildAdvancedHealthReport(vault.getEntries());1021        return { ok: true, data: report };1022      }1023      case "IS_DURESS_ENABLED": {1024        const enabled = await vault.isDuressEnabled();1025        return { ok: true, data: enabled };1026      }1027      case "SETUP_DURESS": {1028        // Single enforcement point for the Duress Vault Pro gate. Free users1029        // who somehow reach this handler are rejected here; the popup also1030        // pre-checks isPro() to avoid showing the setup form to free users,1031        // but server-side is the actual security boundary.1032        const gate = await requirePro("duress_vault");1033        if (!gate.allowed) return { ok: false, error: "pro_required" };1034        // MV3 service workers restart after inactivity, losing the in-memory1035        // derived key. Detect this before calling setupDuress so the popup1036        // can show a meaningful prompt to re-lock and re-unlock.1037        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1038        const { duressPassword } = msg.payload as { duressPassword: string };1039        await vault.setupDuress(duressPassword);1040        return { ok: true };1041      }1042      case "DISABLE_DURESS": {1043        await vault.disableDuress();1044        return { ok: true };1045      }1046      case "VERIFY_MAIN_PASSWORD": {1047        const { password } = msg.payload as { password: string };1048        const ok = await vault.verifyMainPassword(password);1049        return { ok: true, data: ok };1050      }1051      case "CHANGE_PASSWORD": {1052        const { currentPassword, newPassword } = msg.payload as {1053          currentPassword: string;1054          newPassword: string;1055        };1056        const changed = await vault.changePassword(currentPassword, newPassword);1057        return changed1058          ? { ok: true }1059          : { ok: false, error: "incorrect_current_password" };1060      }1061      case "GET_SITE_PASSWORD_POLICY": {1062        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1063        if (!tab?.id) return { ok: true, data: null };1064        try {1065          const response = await chrome.tabs.sendMessage(tab.id, {1066            type: "GET_SITE_PASSWORD_POLICY",1067          });1068          return (response as MessageResponse) ?? { ok: true, data: null };1069        } catch {1070          return { ok: true, data: null };1071        }1072      }1073      case "RECORD_MANUAL_SUMMON": {1074        const { domain } = msg.payload as { domain: string };1075        const settings = vault.getSettings();1076        const existing = settings.manualSummonDomains?.[domain];1077        const now = Date.now();1078        await vault.updateSettings({1079          manualSummonDomains: {1080            ...settings.manualSummonDomains,1081            [domain]: {1082              firstSummonedAt: existing?.firstSummonedAt ?? now,1083              summonCount: (existing?.summonCount ?? 0) + 1,1084              lastSummonedAt: now,1085            },1086          },1087        });1088        return { ok: true };1089      }1090      case "DECLINE_CARD_SAVE": {1091        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1092        await vault.declineCardSaveOffer(last4, expMonth, expYear);1093        return { ok: true };1094      }1095      case "IS_CARD_DECLINED": {1096        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1097        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1098        return { ok: true, data: declined };1099      }1100      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1101        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1102          rpId?: string;1103          rpName?: string;1104          userName?: string;1105          userDisplayName?: string;1106        };1107        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1108        return await initiateFirefoxPasskeyCreate({1109          rpId,1110          rpName: rpName ?? rpId,1111          userName,1112          userDisplayName,1113        });1114      }11151116      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1117        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1118        if (!payload) return { ok: false, error: "missing_payload" };1119        return await completeFirefoxPasskeyCreate(payload);1120      }11211122      case "PASSKEY_OFFER_DECLINE": {1123        const { domain } = (msg.payload ?? {}) as { domain?: string };1124        if (!domain) return { ok: false, error: "domain_required" };1125        await recordPasskeyOfferDecline(domain);1126        return { ok: true };1127      }11281129      case "GET_PASSKEY_OFFER_DECLINED": {1130        const { domain } = (msg.payload ?? {}) as { domain?: string };1131        if (!domain) return { ok: false, error: "domain_required" };1132        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1133      }11341135      case "PASSKEY_HAS_CREDENTIALS": {1136        const payload = msg.payload as {1137          rpId?: string;1138          allowCredentials?: Array<{ id: string; type?: string }>;1139        } | undefined;1140        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1141        return await handlePasskeyHasCredentials({1142          rpId: payload.rpId,1143          allowCredentials: payload.allowCredentials ?? [],1144        }, attestedSenderOrigin(sender));1145      }11461147      case "PASSKEY_CREATE": {1148        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1149        if (!payload?.rpId || !payload?.userName) {1150          return { ok: false, error: "rpid_and_username_required" };1151        }1152        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1153      }11541155      case "PASSKEY_GET": {1156        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1157        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1158        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1159      }11601161      case "PASSKEY_AUTH_RESPONSE": {1162        const { requestId, approved } = (msg.payload ?? {}) as {1163          requestId?: string | number;1164          approved?: boolean;1165        };1166        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1167          return { ok: false, error: 'requestId and approved required' };1168        }1169        await resolvePendingPasskeyRequest(Number(requestId), approved);1170        return { ok: true };1171      }11721173      case "GET_PASSKEY_FOR_DOMAIN": {1174        const { domain } = (msg.payload ?? {}) as { domain?: string };1175        if (!domain) return { ok: false, error: "domain_required" };1176        // Scope to the caller's own origin: a page may only ask about passkeys1177        // for a domain it actually owns, so an arbitrary page cannot enumerate1178        // which sites the user holds passkeys for or read the username (audit MEDIUM).1179        const origin = attestedSenderOrigin(sender);1180        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1181        if (!vault.isUnlocked()) return { ok: true, data: null };1182        const match = vault1183          .getEntries()1184          .find((entry) => entry.passkey?.rpId === domain);1185        if (!match || !match.passkey) return { ok: true, data: null };1186        // Slim shape — only the fields State 11 needs. Never expose private1187        // key material, even though this is locked behind isUnlocked.1188        return {1189          ok: true,1190          data: {1191            rpId: match.passkey.rpId,1192            userName: match.passkey.userName,1193            browser: match.passkey.browser,1194          },1195        };1196      }11971198      case "DESTROY_VAULT": {1199        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1200        // storage.local.clear() wipes every Peach key (slots, settings, license,1201        // onboarded flag, history, sync state, declined cards, recall, etc.);1202        // session.clear() wipes pending passkey requests + pro-notice queues.1203        // Caller (Panic.tsx) handles UI navigation back to onboarding.1204        //1205        // The Pro license is the one thing that must survive: the user paid for1206        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1207        // Capture it before the clear and restore it after. peach_pro_celebrated1208        // rides along so the Pro celebration doesn't replay on the next unlock.1209        const preserved = await chrome.storage.local.get([1210          "peach_license",1211          "peach_pro_celebrated",1212        ]);1213        vault.lock();1214        await storageClear();1215        await vault.clearVaultHistory();1216        const toRestore: Record<string, unknown> = {};1217        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1218        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1219        if (Object.keys(toRestore).length > 0) {1220          await chrome.storage.local.set(toRestore);1221        }1222        if (chrome.storage.session) {1223          await chrome.storage.session.clear();1224        }1225        return { ok: true };1226      }12271228      case "SUBMIT_FEEDBACK": {1229        const { category, message, version, browser } = msg.payload as {1230          category: string;1231          message: string;1232          version: string;1233          browser: string;1234        };1235        if (!message.trim()) return { ok: false, error: "message_empty" };1236        if (!FEEDBACK_ENDPOINT) return { ok: true };1237        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1238          return { ok: false, error: "invalid_feedback_endpoint" };1239        }1240        try {1241          const res = await fetch(FEEDBACK_ENDPOINT, {1242            method: "POST",1243            headers: { "Content-Type": "application/json" },1244            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1245          });1246          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1247        } catch (err) {1248          return { ok: false, error: err instanceof Error ? err.message : "network_error" };1249        }1250      }1251      // Android-only: biometric unlock with pre-derived key.1252      case "UNLOCK_WITH_KEY": {1253        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1254        if (!isNativePlatform()) {1255          return { ok: false, error: "desktop_only_uses_password" };1256        }1257        try {1258          const result = await vault.unlockWithKey(masterKeyHex);1259          if (result.ok) {1260            onVaultUnlocked();1261            await publishInMemoryVault(result.entries);1262          }1263          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1264        } catch {1265          return { ok: false, error: "invalid_key" };1266        }1267      }1268      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1269      case "GET_DERIVED_KEY": {1270        if (!isNativePlatform()) {1271          return { ok: false, error: "android_only" };1272        }1273        if (!vault.isUnlocked()) {1274          return { ok: false, error: "vault_locked" };1275        }1276        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1277      }1278      case "GET_IDENTITY_SUGGESTIONS": {1279        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1280        const entries = vault.getEntries();1281        const suggestions = buildIdentitySuggestions(entries);1282        return { ok: true, data: { suggestions } };1283      }1284      case "POPULATE_INLINE_VAULT": {1285        if (!isNativePlatform()) return { ok: false };1286        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1287        const entries = vault.getEntries();1288        await publishInMemoryVault(entries);1289        return { ok: true };1290      }1291      case "ML_INIT":1292        return { ok: true };12931294      case "ML_PREDICT_BATCH": {1295        // AUD-002: shape-validate before forwarding to the ML helper.1296        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1297        if (!Array.isArray(featuresArray)) {1298          return { ok: false, error: "invalid_payload" };1299        }1300        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1301      }13021303      // ── Chirp Sync (v3) ───────────────────────────────────────────────1304      // Returns the public-facing local identity needed by the popup to1305      // drive Phase-1 audio pairing. The private long-term key never1306      // leaves the background.1307      case "CHIRP_GET_LOCAL_IDENTITY": {1308        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1309        const proCheck = await requirePro("sync");1310        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1311        // Identity derives from the stable root key, not the password-derived1312        // key, so pairing survives a master-password change (SEV-2-B).1313        const masterKeyHex = vault.getRootKeyHex();1314        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1315        const masterKey = unhexBytes(masterKeyHex);1316        try {1317          const identity = await buildLocalIdentity(masterKey);1318          return { ok: true, data: identity };1319        } finally {1320          masterKey.fill(0);1321        }1322      }13231324      case "CHIRP_COMPLETE_PAIRING": {1325        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1326        const proCheck = await requirePro("sync");1327        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1328        const paired = (msg.payload as { paired?: unknown })?.paired;1329        if (typeof paired !== "object" || paired === null) {1330          return { ok: false, error: "invalid_payload" };1331        }1332        const candidate = paired as Record<string, unknown>;1333        if (1334          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1335          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1336          typeof candidate.deviceType !== "string" ||1337          typeof candidate.longTermPublicKeyHex !== "string" ||1338          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1339          (1340            candidate.signingPublicKeyHex !== undefined &&1341            (1342              typeof candidate.signingPublicKeyHex !== "string" ||1343              !/^[0-9a-f]{64}$/.test(candidate.signingPublicKeyHex)1344            )1345          ) ||1346          typeof candidate.pairedAt !== "number"1347        ) {1348          return { ok: false, error: "invalid_paired_device" };1349        }1350        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1351        return { ok: true };1352      }13531354      case "CHIRP_LIST_PAIRED_DEVICES": {1355        const devices = await listPairedDevicesV3();1356        return { ok: true, data: { devices } };1357      }13581359      case "CHIRP_UNPAIR_DEVICE": {1360        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1361        if (typeof deviceId !== "string" || !deviceId) {1362          return { ok: false, error: "invalid_payload" };1363        }1364        await removePairedDeviceByIdV3(deviceId);1365        return { ok: true };1366      }13671368      case "CHIRP_RENAME_LOCAL_DEVICE": {1369        const { name } = (msg.payload ?? {}) as { name?: string };1370        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1371        await setDeviceNameV3(name);1372        return { ok: true };1373      }13741375      case "TRIGGER_SYNC": {1376        const payload = (msg.payload ?? {}) as {1377          reason?: "vault_change" | "foreground" | "manual" | "mdns";1378          force?: boolean;1379          deviceId?: string;1380          discoveredIp?: string;1381          discoveredPort?: number;1382        };1383        const reason = payload.reason ?? "foreground";13841385        // mDNS discovery delivers a fresh (ip, port) resolved by the native1386        // side. Update the cached address before the sync runner tries to1387        // connect — avoids a subnet probe on the very next round.1388        if (1389          reason === "mdns" &&1390          typeof payload.deviceId === "string" &&1391          typeof payload.discoveredIp === "string"1392        ) {1393          const { findPairedDeviceById, setLastKnownIp } = await import("./paired-devices");1394          const device = await findPairedDeviceById(payload.deviceId);1395          if (device?.longTermPublicKeyHex) {1396            await setLastKnownIp(device.longTermPublicKeyHex, payload.discoveredIp).catch(() => undefined);1397          }1398        }13991400        const { triggerSyncIfReachable } = await import("./sync-trigger");1401        void triggerSyncIfReachable({ reason, force: payload.force === true });1402        return { ok: true };1403      }14041405      case "GET_SYNC_STATE": {1406        const { getSyncState } = await import("./sync-trigger");1407        return { ok: true, data: getSyncState() };1408      }14091410      case "GET_SYNC_ALERTS": {1411        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1412        const alerts = await getPendingSyncAlerts();1413        // The popup reads on open and acknowledges with consume:true after1414        // rendering, so a popup crash between read and render doesn't lose1415        // the alerts.1416        if (consume) await clearPendingSyncAlerts();1417        return { ok: true, data: alerts };1418      }14191420      case "GET_PENDING_VOUCHED_DEVICES": {1421        return { ok: true, data: await listPendingVouchedDevices() };1422      }1423      case "CONFIRM_VOUCHED_DEVICE": {1424        const { deviceId } = msg.payload as { deviceId: string };1425        const pending = await getPendingVouchedDevice(deviceId);1426        if (!pending) return { ok: false, error: "not_pending" };1427        await upsertPairedDeviceV3({1428          deviceId: pending.deviceId,1429          deviceName: pending.deviceName,1430          deviceType:1431            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1432          longTermPublicKeyHex: pending.longTermPublicKeyHex,1433          signingPublicKeyHex: pending.signingPublicKeyHex,1434          wsPort: pending.wsPort,1435          pairedAt: pending.pairedAt,1436          trustSource: "vouched",1437        });1438        await removePendingVouchedDevice(deviceId);1439        return { ok: true };1440      }1441      case "REJECT_VOUCHED_DEVICE": {1442        const { deviceId } = msg.payload as { deviceId: string };1443        await removePendingVouchedDevice(deviceId);1444        return { ok: true };1445      }1446      case "ROTATE_SYNC_IDENTITY": {1447        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1448        const result = await vault.rotateSyncIdentity();1449        return result.ok ? { ok: true } : { ok: false, error: result.error };1450      }14511452      default:1453        return { ok: false, error: "unknown_message_type" };1454    }1455  } catch (err) {1456    return {1457      ok: false,1458      error: err instanceof Error ? err.message : "operation_failed",1459    };1460  }1461}14621463// --- Mobile platform helpers ---14641465// Android: populates the in-memory vault used by PeachAutofillService.1466async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1467  const plugin = nativePlugin<{1468    setEntries?: (args: {1469      entries: Array<{1470        id: string;1471        title: string;1472        username: string;1473        email: string;1474        password: string;1475        url: string;1476        totp: string;1477        additionalUrls: string[];1478      }>;1479    }) => Promise<void>;1480  }>("InMemoryVaultPlugin");1481  if (!plugin?.setEntries) return;1482  await plugin.setEntries({1483    entries: entries.map((e) => ({1484      id: e.id,1485      title: e.title ?? "",1486      username: e.username ?? "",1487      email: (e as VaultEntry & { email?: string }).email ?? "",1488      password: e.password ?? "",1489      url: e.url ?? "",1490      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1491      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1492    })),1493  });1494}14951496// Android: clear the autofill in-memory store on lock.1497async function clearInMemoryVault(): Promise<void> {1498  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1499  if (!plugin?.clearEntries) return;1500  await plugin.clearEntries();1501}15021503// Returns username use-counts from the vault, sorted by frequency. Each row1504// also carries the entry's email so the popup can suggest the email/username1505// pair the user has actually used together.1506function buildIdentitySuggestions(1507  entries: VaultEntry[],1508): Array<{ email: string; username: string; count: number }> {1509  const usernameCounts = new Map<string, number>();1510  const usernameEmail = new Map<string, string>();1511  for (const entry of entries) {1512    const username = entry.username ?? "";1513    const email = (entry as VaultEntry & { email?: string }).email ?? "";1514    if (!username && !email) continue;1515    const key = username || email;1516    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1517    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1518  }1519  return Array.from(usernameCounts.entries())1520    .sort((a, b) => b[1] - a[1])1521    .map(([username, count]) => ({1522      email: usernameEmail.get(username) ?? "",1523      username,1524      count,1525    }));1526}15271528/** Notify all content scripts that the vault just became available. */1529function broadcastToContentScripts(message: { type: string }): void {1530  if (!chrome.tabs?.query) return;1531  chrome.tabs.query({}, (tabs) => {1532    for (const tab of tabs) {1533      if (tab.id !== undefined) {1534        chrome.tabs.sendMessage(tab.id, message).catch(() => {1535          // Tab may not have a content script — silently ignore1536        });1537      }1538    }1539  });1540}15411542function shouldRefreshAutoLock(type: MessageType): boolean {1543  return (1544    type !== "HAS_VAULT" &&1545    type !== "IS_UNLOCKED" &&1546    type !== "GET_VAULT_STATUS" &&1547    type !== "LOCK" &&1548    type !== "UPDATE_SETTINGS" &&1549    type !== "GET_PENDING_PASSKEY" &&1550    type !== "GET_PASSKEY_PROVIDER_STATE" &&1551    type !== "DECLINE_CARD_SAVE" &&1552    type !== "IS_CARD_DECLINED" &&1553    type !== "SUBMIT_FEEDBACK"1554  );1555}15561557function isAllowedCanaryWebhookUrl(value: string): boolean {1558  try {1559    const url = new URL(value);1560    if (url.protocol !== "https:") return false;15611562    const hostname = url.hostname.toLowerCase();1563    if (1564      hostname === "localhost" ||1565      hostname.endsWith(".localhost") ||1566      isPrivateIpv4(hostname) ||1567      isPrivateIpv6(hostname)1568    ) {1569      return false;1570    }15711572    return true;1573  } catch {1574    return false;1575  }1576}15771578function isPrivateIpv4(hostname: string): boolean {1579  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1580    return true;1581  }15821583  const octets = hostname.split(".").map((part) => Number(part));1584  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1585    return false;1586  }15871588  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1589}15901591function isPrivateIpv6(hostname: string): boolean {1592  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1593  return (1594    normalized === "::1" ||1595    normalized.startsWith("fc") ||1596    normalized.startsWith("fd") ||1597    normalized.startsWith("fe80:")1598  );1599}