messages.ts

66.5 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 {738          passkey: _strippedPasskey,739          totp: seed,740          totpAlgorithm,741          totpDigits,742          totpPeriod,743          passwordHistory: _ph,744          ...safeEntry745        } = entry;746        let totpCode: string | undefined;747        let totpRemaining: number | undefined;748        if (seed) {749          try {750            // PCH-01-019: honour stored algorithm/digits/period (defaults apply751            // when these are undefined, i.e. legacy bare-seed entries).752            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);753            totpCode = generated.code;754            totpRemaining = generated.remaining;755          } catch {756            totpCode = undefined;757          }758        }759        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };760      }761      // Trusted full-entry fetch for Peach's own inline-popup surfaces that762      // genuinely need the raw TOTP seed: the edit form (which re-saves the763      // seed and would otherwise wipe it) and nothing else. Unlike764      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside765      // the inline popup, never during passive autofill on an arbitrary page.766      // The passkey credential is still stripped — the edit form never touches it.767      case "GET_ENTRY_FOR_EDIT": {768        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };769        const { id, explicitSummon } = msg.payload as {770          id: string;771          explicitSummon?: boolean;772        };773        const entry = vault.getEntryById(id);774        if (!entry) return { ok: false, error: "entry_not_found" };775776        // PCH-01-006: re-validate the browser-attested sender origin, mirroring777        // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and778        // full password history — at least as sensitive as the fill response — so779        // the boundary must be enforced here, not only by UI reachability. Today780        // the sole caller is the popup (no sender.tab, so this is a structural781        // no-op), but a future tab-context caller or an id leak would otherwise782        // inherit a full-credential oracle. Unlike the fill path we SKIP (not783        // refuse) when no sender domain resolves, to keep the popup caller working.784        if (sender.tab !== undefined || sender.url !== undefined) {785          let senderDomain: string | null = null;786          try {787            const rawUrl = sender.tab?.url ?? sender.url ?? "";788            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;789          } catch {790            senderDomain = null;791          }792          if (senderDomain) {793            const entryDomains = new Set<string>();794            const primary = extractDomain(entry.url ?? "");795            if (primary) entryDomains.add(primary);796            for (const extra of entry.additionalUrls ?? []) {797              const d = extractDomain(extra);798              if (d) entryDomains.add(d);799            }800            if (explicitSummon !== true && !entryDomains.has(senderDomain)) {801              return { ok: false, error: "entry_not_found" }; // no id oracle802            }803          }804        }805806        const { passkey: _passkey, ...safeEntry } = entry;807        return { ok: true, data: safeEntry };808      }809      case "COPY": {810        // AUD-002: shape-validate the payload before passing to the clipboard811        // helper. A raw cast lets a malformed message reach the clipboard API812        // with a non-string and throw.813        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {814          text?: unknown;815          label?: unknown;816          alreadyWritten?: unknown;817        };818        if (typeof text !== "string" || typeof label !== "string") {819          return { ok: false, error: "invalid_payload" };820        }821        await copyToClipboard(text, label, Boolean(alreadyWritten));822        return { ok: true };823      }824      case "CHECK_ALL_BREACHES": {825        const allEntries = vault.getEntries();826        const results: Record<string, number> = {};827        for (const entry of allEntries) {828          if (entry.type === "note") continue;829          if (!entry.password) continue;830          results[entry.id] = await vault.checkBreach(entry.password);831          // Small delay — be a good citizen to the HIBP API832          await new Promise((r) => setTimeout(r, 200));833        }834        // Persist any non-zero counts back to entries835        for (const [id, count] of Object.entries(results)) {836          const entry = vault.getEntryById(id);837          if (entry && (entry.breach ?? 0) !== count) {838            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });839          }840        }841        return { ok: true, data: results };842      }843      case "GET_SETTINGS":844        return { ok: true, data: await vault.ensureSettingsLoaded() };845      case "UPDATE_SETTINGS": {846        const patch = msg.payload;847        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {848          return { ok: false, error: "invalid_payload" };849        }850        await vault.updateSettings(patch as vault.VaultSettings);851        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {852          await setupAutoLock();853          if (vault.isUnlocked()) touchAutoLock();854        }855        return { ok: true };856      }857      case "GET_PENDING_PASSKEY":858        return { ok: true, data: await getPendingPasskeyRequest() };859      case "APPROVE_PASSKEY": {860        const { requestId } = msg.payload as { requestId: number };861        await resolvePendingPasskeyRequest(requestId, true);862        return { ok: true };863      }864      case "DENY_PASSKEY": {865        const { requestId } = msg.payload as { requestId: number };866        await resolvePendingPasskeyRequest(requestId, false);867        return { ok: true };868      }869      case "GET_PASSKEY_PROVIDER_STATE":870        return { ok: true, data: await getPasskeyProviderState() };871      case "SET_PASSKEY_PROVIDER_ENABLED": {872        const { enabled } = msg.payload as { enabled: boolean };873        // Disabling is always free; gating fires only when a free user is874        // trying to turn passkey interception on.875        if (enabled) {876          const gate = await requirePro("passkeys");877          if (!gate.allowed) return { ok: false, error: "pro_required" };878        }879        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };880      }881      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS882      // endpoint. Intentional product behavior — users configure their own883      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private884      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-885      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to886      // users that the entry title leaves the device when the canary fires.887      case "FIRE_CANARY_PING": {888        // Canary alert fires unconditionally for any entry with canary: true.889        // The Pro gate only governs creation/flagging of canary entries; once890        // an entry is flagged, the alert path is a security property and must891        // never be license-gated.892        const { webhookUrl, entryTitle, trigger } = msg.payload as {893          webhookUrl: string;894          entryTitle: string;895          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";896        };897        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {898          return { ok: false, error: "invalid_webhook_url" };899        }900        // LV-3: debounce non-test pings per (webhook, entry) so a page that901        // strobes focus/fill events can't turn the canary into a request902        // firehose at the user's endpoint. Test pings are exempt — they are903        // explicit user clicks in the settings UI and are awaited for904        // feedback. The FIRST ping in a window always goes out, so the905        // dead-man's-switch property (canary fires on access) is preserved;906        // only repeats within the window are coalesced.907        if (trigger !== "test") {908          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;909          const stored = await chrome.storage.local.get(rlKey);910          const last = (stored as Record<string, unknown>)[rlKey];911          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {912            return { ok: true, data: { rateLimited: true } };913          }914          await chrome.storage.local.set({ [rlKey]: Date.now() });915        }916        const body = JSON.stringify({917          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",918          entry: entryTitle,919          trigger,920          timestamp: new Date().toISOString(),921          source: "peach-extension",922        });923        if (trigger === "test") {924          // Permitted outbound fetch: user-configured canary alert endpoint925          // (validated by isAllowedCanaryWebhookUrl above). This is the926          // only non-HIBP outbound call in the extension — see927          // Projects.md §3.7. Test pings are awaited so the UI can show928          // success/failure.929          try {930            const res = await fetch(webhookUrl, {931              method: "POST",932              headers: { "Content-Type": "application/json" },933              body,934            });935            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };936          } catch (err) {937            return { ok: false, error: err instanceof Error ? err.message : "network_error" };938          }939        }940        // Non-test triggers are fire-and-forget941        fetch(webhookUrl, {942          method: "POST",943          headers: { "Content-Type": "application/json" },944          body,945        }).catch(() => {});946        return { ok: true };947      }948      case "ACTIVATE_LICENSE": {949        const { key } = msg.payload as { key: string };950        const licenseInfo = await activateLicense(key);951        return { ok: true, data: licenseInfo };952      }953      case "GET_LICENSE": {954        const licenseInfo = await getLicenseInfo();955        return { ok: true, data: licenseInfo };956      }957      case "GET_LICENSE_KEY": {958        const key = await getLicenseKey();959        return { ok: true, data: key };960      }961      case "DEACTIVATE_LICENSE": {962        await deactivateLicense();963        return { ok: true };964      }965      case "SHOULD_PLAY_CELEBRATION": {966        const should = await shouldPlayCelebration();967        return { ok: true, data: should };968      }969      case "MARK_CELEBRATION_PLAYED": {970        await markCelebrationPlayed();971        return { ok: true };972      }973      case "GET_CODEX_VAULT_DATA": {974        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the975        // popup navigates to the License section without further coordination.976        const gate = await requirePro("codex");977        if (!gate.allowed) return { ok: false, error: "pro_required" };978        return await handleGetCodexVaultData();979      }980      case "ESTIMATE_CODEX_PAGES": {981        const gate = await requirePro("codex");982        if (!gate.allowed) return { ok: false, error: "pro_required" };983        return await handleEstimateCodexPages();984      }985      case "RESTORE_FROM_CODEX": {986        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still987        // be able to restore a vault that was printed by a Pro user.988        // DO NOT add a Pro gate here.989        const payload = msg.payload as CodexRestorePayload;990        return await handleRestoreFromCodex(payload);991      }992      case "OPEN_PRO_GATE": {993        // Content script requests: open popup and navigate to License section.994        const { feature } = (msg.payload ?? {}) as { feature?: string };995        if (chrome.storage.session) {996          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });997        }998        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }999        return { ok: true };1000      }1001      case "OPEN_POPUP": {1002        // Content script asks to open the trusted extension popup — used by the1003        // inline locked bubble so the master password is entered in the popup,1004        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1005        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1006        // toolbar icon. The badge already signals Peach needs attention.1007        //1008        // Set a session flag so the popup knows it was opened for inline unlock1009        // and should close itself once the vault is unlocked (returning the user1010        // to the inline autofill selector on the page).1011        if (chrome.storage.session) {1012          await chrome.storage.session.set({ peach_inline_unlock: true });1013        }1014        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1015        return { ok: true };1016      }1017      case "GET_IDENTITIES": {1018        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1019        return { ok: true, data: vault.getIdentities() };1020      }1021      case "TOUCH_AUTO_LOCK": {1022        // touchAutoLock() is already called by shouldRefreshAutoLock above;1023        // this case just gives the popup a typed message to keep the session alive.1024        return { ok: true };1025      }1026      case "GET_ADVANCED_HEALTH_REPORT": {1027        const gate = await requirePro("advanced_health");1028        if (!gate.allowed) return { ok: false, error: "pro_required" };1029        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1030        const report = await buildAdvancedHealthReport(vault.getEntries());1031        return { ok: true, data: report };1032      }1033      case "IS_DURESS_ENABLED": {1034        const enabled = await vault.isDuressEnabled();1035        return { ok: true, data: enabled };1036      }1037      case "SETUP_DURESS": {1038        // Single enforcement point for the Duress Vault Pro gate. Free users1039        // who somehow reach this handler are rejected here; the popup also1040        // pre-checks isPro() to avoid showing the setup form to free users,1041        // but server-side is the actual security boundary.1042        const gate = await requirePro("duress_vault");1043        if (!gate.allowed) return { ok: false, error: "pro_required" };1044        // MV3 service workers restart after inactivity, losing the in-memory1045        // derived key. Detect this before calling setupDuress so the popup1046        // can show a meaningful prompt to re-lock and re-unlock.1047        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1048        const { duressPassword } = msg.payload as { duressPassword: string };1049        await vault.setupDuress(duressPassword);1050        return { ok: true };1051      }1052      case "DISABLE_DURESS": {1053        await vault.disableDuress();1054        return { ok: true };1055      }1056      case "VERIFY_MAIN_PASSWORD": {1057        const { password } = msg.payload as { password: string };1058        const ok = await vault.verifyMainPassword(password);1059        return { ok: true, data: ok };1060      }1061      case "CHANGE_PASSWORD": {1062        const { currentPassword, newPassword } = msg.payload as {1063          currentPassword: string;1064          newPassword: string;1065        };1066        const changed = await vault.changePassword(currentPassword, newPassword);1067        return changed1068          ? { ok: true }1069          : { ok: false, error: "incorrect_current_password" };1070      }1071      case "GET_SITE_PASSWORD_POLICY": {1072        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1073        if (!tab?.id) return { ok: true, data: null };1074        try {1075          const response = await chrome.tabs.sendMessage(tab.id, {1076            type: "GET_SITE_PASSWORD_POLICY",1077          });1078          return (response as MessageResponse) ?? { ok: true, data: null };1079        } catch {1080          return { ok: true, data: null };1081        }1082      }1083      case "RECORD_MANUAL_SUMMON": {1084        const { domain } = msg.payload as { domain: string };1085        const settings = vault.getSettings();1086        const existing = settings.manualSummonDomains?.[domain];1087        const now = Date.now();1088        await vault.updateSettings({1089          manualSummonDomains: {1090            ...settings.manualSummonDomains,1091            [domain]: {1092              firstSummonedAt: existing?.firstSummonedAt ?? now,1093              summonCount: (existing?.summonCount ?? 0) + 1,1094              lastSummonedAt: now,1095            },1096          },1097        });1098        return { ok: true };1099      }1100      case "DECLINE_CARD_SAVE": {1101        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1102        await vault.declineCardSaveOffer(last4, expMonth, expYear);1103        return { ok: true };1104      }1105      case "IS_CARD_DECLINED": {1106        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1107        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1108        return { ok: true, data: declined };1109      }1110      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1111        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1112          rpId?: string;1113          rpName?: string;1114          userName?: string;1115          userDisplayName?: string;1116        };1117        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1118        return await initiateFirefoxPasskeyCreate({1119          rpId,1120          rpName: rpName ?? rpId,1121          userName,1122          userDisplayName,1123        });1124      }11251126      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1127        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1128        if (!payload) return { ok: false, error: "missing_payload" };1129        return await completeFirefoxPasskeyCreate(payload);1130      }11311132      case "PASSKEY_OFFER_DECLINE": {1133        const { domain } = (msg.payload ?? {}) as { domain?: string };1134        if (!domain) return { ok: false, error: "domain_required" };1135        await recordPasskeyOfferDecline(domain);1136        return { ok: true };1137      }11381139      case "GET_PASSKEY_OFFER_DECLINED": {1140        const { domain } = (msg.payload ?? {}) as { domain?: string };1141        if (!domain) return { ok: false, error: "domain_required" };1142        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1143      }11441145      case "PASSKEY_HAS_CREDENTIALS": {1146        const payload = msg.payload as {1147          rpId?: string;1148          allowCredentials?: Array<{ id: string; type?: string }>;1149        } | undefined;1150        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1151        return await handlePasskeyHasCredentials({1152          rpId: payload.rpId,1153          allowCredentials: payload.allowCredentials ?? [],1154        }, attestedSenderOrigin(sender));1155      }11561157      case "PASSKEY_CREATE": {1158        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1159        if (!payload?.rpId || !payload?.userName) {1160          return { ok: false, error: "rpid_and_username_required" };1161        }1162        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1163      }11641165      case "PASSKEY_GET": {1166        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1167        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1168        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1169      }11701171      case "PASSKEY_AUTH_RESPONSE": {1172        const { requestId, approved } = (msg.payload ?? {}) as {1173          requestId?: string | number;1174          approved?: boolean;1175        };1176        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1177          return { ok: false, error: 'requestId and approved required' };1178        }1179        await resolvePendingPasskeyRequest(Number(requestId), approved);1180        return { ok: true };1181      }11821183      case "GET_PASSKEY_FOR_DOMAIN": {1184        const { domain } = (msg.payload ?? {}) as { domain?: string };1185        if (!domain) return { ok: false, error: "domain_required" };1186        // Scope to the caller's own origin: a page may only ask about passkeys1187        // for a domain it actually owns, so an arbitrary page cannot enumerate1188        // which sites the user holds passkeys for or read the username (audit MEDIUM).1189        const origin = attestedSenderOrigin(sender);1190        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1191        if (!vault.isUnlocked()) return { ok: true, data: null };1192        const match = vault1193          .getEntries()1194          .find((entry) => entry.passkey?.rpId === domain);1195        if (!match || !match.passkey) return { ok: true, data: null };1196        // Slim shape — only the fields State 11 needs. Never expose private1197        // key material, even though this is locked behind isUnlocked.1198        return {1199          ok: true,1200          data: {1201            rpId: match.passkey.rpId,1202            userName: match.passkey.userName,1203            browser: match.passkey.browser,1204          },1205        };1206      }12071208      case "DESTROY_VAULT": {1209        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1210        // storage.local.clear() wipes every Peach key (slots, settings, license,1211        // onboarded flag, history, sync state, declined cards, recall, etc.);1212        // session.clear() wipes pending passkey requests + pro-notice queues.1213        // Caller (Panic.tsx) handles UI navigation back to onboarding.1214        //1215        // The Pro license is the one thing that must survive: the user paid for1216        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1217        // Capture it before the clear and restore it after. peach_pro_celebrated1218        // rides along so the Pro celebration doesn't replay on the next unlock.1219        const preserved = await chrome.storage.local.get([1220          "peach_license",1221          "peach_pro_celebrated",1222        ]);1223        vault.lock();1224        await storageClear();1225        await vault.clearVaultHistory();1226        const toRestore: Record<string, unknown> = {};1227        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1228        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1229        if (Object.keys(toRestore).length > 0) {1230          await chrome.storage.local.set(toRestore);1231        }1232        if (chrome.storage.session) {1233          await chrome.storage.session.clear();1234        }1235        return { ok: true };1236      }12371238      case "SUBMIT_FEEDBACK": {1239        const { category, message, version, browser } = msg.payload as {1240          category: string;1241          message: string;1242          version: string;1243          browser: string;1244        };1245        if (!message.trim()) return { ok: false, error: "message_empty" };1246        if (!FEEDBACK_ENDPOINT) return { ok: true };1247        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1248          return { ok: false, error: "invalid_feedback_endpoint" };1249        }1250        try {1251          const res = await fetch(FEEDBACK_ENDPOINT, {1252            method: "POST",1253            headers: { "Content-Type": "application/json" },1254            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1255          });1256          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1257        } catch (err) {1258          return { ok: false, error: err instanceof Error ? err.message : "network_error" };1259        }1260      }1261      // Android-only: biometric unlock with pre-derived key.1262      case "UNLOCK_WITH_KEY": {1263        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1264        if (!isNativePlatform()) {1265          return { ok: false, error: "desktop_only_uses_password" };1266        }1267        try {1268          const result = await vault.unlockWithKey(masterKeyHex);1269          if (result.ok) {1270            onVaultUnlocked();1271            await publishInMemoryVault(result.entries);1272          }1273          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1274        } catch {1275          return { ok: false, error: "invalid_key" };1276        }1277      }1278      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1279      case "GET_DERIVED_KEY": {1280        if (!isNativePlatform()) {1281          return { ok: false, error: "android_only" };1282        }1283        if (!vault.isUnlocked()) {1284          return { ok: false, error: "vault_locked" };1285        }1286        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1287      }1288      case "GET_IDENTITY_SUGGESTIONS": {1289        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1290        const entries = vault.getEntries();1291        const suggestions = buildIdentitySuggestions(entries);1292        return { ok: true, data: { suggestions } };1293      }1294      case "POPULATE_INLINE_VAULT": {1295        if (!isNativePlatform()) return { ok: false };1296        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1297        const entries = vault.getEntries();1298        await publishInMemoryVault(entries);1299        return { ok: true };1300      }1301      case "ML_INIT":1302        return { ok: true };13031304      case "ML_PREDICT_BATCH": {1305        // AUD-002: shape-validate before forwarding to the ML helper.1306        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1307        if (!Array.isArray(featuresArray)) {1308          return { ok: false, error: "invalid_payload" };1309        }1310        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1311      }13121313      // ── Chirp Sync (v3) ───────────────────────────────────────────────1314      // Returns the public-facing local identity needed by the popup to1315      // drive Phase-1 audio pairing. The private long-term key never1316      // leaves the background.1317      case "CHIRP_GET_LOCAL_IDENTITY": {1318        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1319        const proCheck = await requirePro("sync");1320        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1321        // Identity derives from the stable root key, not the password-derived1322        // key, so pairing survives a master-password change (SEV-2-B).1323        const masterKeyHex = vault.getRootKeyHex();1324        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1325        const masterKey = unhexBytes(masterKeyHex);1326        try {1327          const identity = await buildLocalIdentity(masterKey);1328          return { ok: true, data: identity };1329        } finally {1330          masterKey.fill(0);1331        }1332      }13331334      case "CHIRP_COMPLETE_PAIRING": {1335        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1336        const proCheck = await requirePro("sync");1337        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1338        const paired = (msg.payload as { paired?: unknown })?.paired;1339        if (typeof paired !== "object" || paired === null) {1340          return { ok: false, error: "invalid_payload" };1341        }1342        const candidate = paired as Record<string, unknown>;1343        if (1344          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1345          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1346          typeof candidate.deviceType !== "string" ||1347          typeof candidate.longTermPublicKeyHex !== "string" ||1348          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1349          (1350            candidate.signingPublicKeyHex !== undefined &&1351            (1352              typeof candidate.signingPublicKeyHex !== "string" ||1353              !/^[0-9a-f]{64}$/.test(candidate.signingPublicKeyHex)1354            )1355          ) ||1356          typeof candidate.pairedAt !== "number"1357        ) {1358          return { ok: false, error: "invalid_paired_device" };1359        }1360        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1361        return { ok: true };1362      }13631364      case "CHIRP_LIST_PAIRED_DEVICES": {1365        const devices = await listPairedDevicesV3();1366        return { ok: true, data: { devices } };1367      }13681369      case "CHIRP_UNPAIR_DEVICE": {1370        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1371        if (typeof deviceId !== "string" || !deviceId) {1372          return { ok: false, error: "invalid_payload" };1373        }1374        await removePairedDeviceByIdV3(deviceId);1375        return { ok: true };1376      }13771378      case "CHIRP_RENAME_LOCAL_DEVICE": {1379        const { name } = (msg.payload ?? {}) as { name?: string };1380        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1381        await setDeviceNameV3(name);1382        return { ok: true };1383      }13841385      case "TRIGGER_SYNC": {1386        const payload = (msg.payload ?? {}) as {1387          reason?: "vault_change" | "foreground" | "manual" | "mdns";1388          force?: boolean;1389          deviceId?: string;1390          discoveredIp?: string;1391          discoveredPort?: number;1392        };1393        const reason = payload.reason ?? "foreground";13941395        // mDNS discovery delivers a fresh (ip, port) resolved by the native1396        // side. Update the cached address before the sync runner tries to1397        // connect — avoids a subnet probe on the very next round.1398        if (1399          reason === "mdns" &&1400          typeof payload.deviceId === "string" &&1401          typeof payload.discoveredIp === "string"1402        ) {1403          const { findPairedDeviceById, setLastKnownIp } = await import("./paired-devices");1404          const device = await findPairedDeviceById(payload.deviceId);1405          if (device?.longTermPublicKeyHex) {1406            await setLastKnownIp(device.longTermPublicKeyHex, payload.discoveredIp).catch(() => undefined);1407          }1408        }14091410        const { triggerSyncIfReachable } = await import("./sync-trigger");1411        void triggerSyncIfReachable({ reason, force: payload.force === true });1412        return { ok: true };1413      }14141415      case "GET_SYNC_STATE": {1416        const { getSyncState } = await import("./sync-trigger");1417        return { ok: true, data: getSyncState() };1418      }14191420      case "GET_SYNC_ALERTS": {1421        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1422        const alerts = await getPendingSyncAlerts();1423        // The popup reads on open and acknowledges with consume:true after1424        // rendering, so a popup crash between read and render doesn't lose1425        // the alerts.1426        if (consume) await clearPendingSyncAlerts();1427        return { ok: true, data: alerts };1428      }14291430      case "GET_PENDING_VOUCHED_DEVICES": {1431        return { ok: true, data: await listPendingVouchedDevices() };1432      }1433      case "CONFIRM_VOUCHED_DEVICE": {1434        const { deviceId } = msg.payload as { deviceId: string };1435        const pending = await getPendingVouchedDevice(deviceId);1436        if (!pending) return { ok: false, error: "not_pending" };1437        await upsertPairedDeviceV3({1438          deviceId: pending.deviceId,1439          deviceName: pending.deviceName,1440          deviceType:1441            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1442          longTermPublicKeyHex: pending.longTermPublicKeyHex,1443          signingPublicKeyHex: pending.signingPublicKeyHex,1444          wsPort: pending.wsPort,1445          pairedAt: pending.pairedAt,1446          trustSource: "vouched",1447        });1448        await removePendingVouchedDevice(deviceId);1449        return { ok: true };1450      }1451      case "REJECT_VOUCHED_DEVICE": {1452        const { deviceId } = msg.payload as { deviceId: string };1453        await removePendingVouchedDevice(deviceId);1454        return { ok: true };1455      }1456      case "ROTATE_SYNC_IDENTITY": {1457        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1458        const result = await vault.rotateSyncIdentity();1459        return result.ok ? { ok: true } : { ok: false, error: result.error };1460      }14611462      default:1463        return { ok: false, error: "unknown_message_type" };1464    }1465  } catch (err) {1466    return {1467      ok: false,1468      error: err instanceof Error ? err.message : "operation_failed",1469    };1470  }1471}14721473// --- Mobile platform helpers ---14741475// Android: populates the in-memory vault used by PeachAutofillService.1476async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1477  const plugin = nativePlugin<{1478    setEntries?: (args: {1479      entries: Array<{1480        id: string;1481        title: string;1482        username: string;1483        email: string;1484        password: string;1485        url: string;1486        totp: string;1487        additionalUrls: string[];1488      }>;1489    }) => Promise<void>;1490  }>("InMemoryVaultPlugin");1491  if (!plugin?.setEntries) return;1492  await plugin.setEntries({1493    entries: entries.map((e) => ({1494      id: e.id,1495      title: e.title ?? "",1496      username: e.username ?? "",1497      email: (e as VaultEntry & { email?: string }).email ?? "",1498      password: e.password ?? "",1499      url: e.url ?? "",1500      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1501      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1502    })),1503  });1504}15051506// Android: clear the autofill in-memory store on lock.1507async function clearInMemoryVault(): Promise<void> {1508  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1509  if (!plugin?.clearEntries) return;1510  await plugin.clearEntries();1511}15121513// Returns username use-counts from the vault, sorted by frequency. Each row1514// also carries the entry's email so the popup can suggest the email/username1515// pair the user has actually used together.1516function buildIdentitySuggestions(1517  entries: VaultEntry[],1518): Array<{ email: string; username: string; count: number }> {1519  const usernameCounts = new Map<string, number>();1520  const usernameEmail = new Map<string, string>();1521  for (const entry of entries) {1522    const username = entry.username ?? "";1523    const email = (entry as VaultEntry & { email?: string }).email ?? "";1524    if (!username && !email) continue;1525    const key = username || email;1526    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1527    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1528  }1529  return Array.from(usernameCounts.entries())1530    .sort((a, b) => b[1] - a[1])1531    .map(([username, count]) => ({1532      email: usernameEmail.get(username) ?? "",1533      username,1534      count,1535    }));1536}15371538/** Notify all content scripts that the vault just became available. */1539function broadcastToContentScripts(message: { type: string }): void {1540  if (!chrome.tabs?.query) return;1541  chrome.tabs.query({}, (tabs) => {1542    for (const tab of tabs) {1543      if (tab.id !== undefined) {1544        chrome.tabs.sendMessage(tab.id, message).catch(() => {1545          // Tab may not have a content script — silently ignore1546        });1547      }1548    }1549  });1550}15511552function shouldRefreshAutoLock(type: MessageType): boolean {1553  return (1554    type !== "HAS_VAULT" &&1555    type !== "IS_UNLOCKED" &&1556    type !== "GET_VAULT_STATUS" &&1557    type !== "LOCK" &&1558    type !== "UPDATE_SETTINGS" &&1559    type !== "GET_PENDING_PASSKEY" &&1560    type !== "GET_PASSKEY_PROVIDER_STATE" &&1561    type !== "DECLINE_CARD_SAVE" &&1562    type !== "IS_CARD_DECLINED" &&1563    type !== "SUBMIT_FEEDBACK"1564  );1565}15661567function isAllowedCanaryWebhookUrl(value: string): boolean {1568  try {1569    const url = new URL(value);1570    if (url.protocol !== "https:") return false;15711572    const hostname = url.hostname.toLowerCase();1573    if (1574      hostname === "localhost" ||1575      hostname.endsWith(".localhost") ||1576      isPrivateIpv4(hostname) ||1577      isPrivateIpv6(hostname)1578    ) {1579      return false;1580    }15811582    return true;1583  } catch {1584    return false;1585  }1586}15871588function isPrivateIpv4(hostname: string): boolean {1589  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1590    return true;1591  }15921593  const octets = hostname.split(".").map((part) => Number(part));1594  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1595    return false;1596  }15971598  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1599}16001601function isPrivateIpv6(hostname: string): boolean {1602  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1603  return (1604    normalized === "::1" ||1605    normalized.startsWith("fc") ||1606    normalized.startsWith("fd") ||1607    normalized.startsWith("fe80:")1608  );1609}