messages.ts

71.6 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard, getEffectiveClearSeconds } from "./clipboard";13import { getPendingSyncAlerts, clearPendingSyncAlerts } from "./sync-alerts";14import { extractDomain } from "../shared/domain";15import { computeVaultId } from "../shared/sync-identity";16import {17  getPendingVouchedDevice,18  listPendingVouchedDevices,19  removePendingVouchedDevice,20} from "./pending-vouched-devices";21import { isRecoveryConfirmPending } from "./recovery-pending";22import { setupAutoLock, touchAutoLock } from "./alarms";23import { runSelfTest } from "./self-test";24import * as vault from "./vault";25import {26  handleEstimateCodexPages,27  handleGetCodexVaultData,28  handleRestoreFromCodex,29} from "./codex-handlers";30import type { CodexRestorePayload } from "../shared/codex-types";31import {32  activateLicense,33  deactivateLicense,34  getLicenseInfo,35  getLicenseKey,36  isProUser,37  markCelebrationPlayed,38  shouldPlayCelebration,39} from "./license";40import {41  completeFirefoxPasskeyCreate,42  getPasskeyProviderState,43  getPendingPasskeyRequest,44  handleFirefoxPasskeyCreate,45  handleFirefoxPasskeyGet,46  handlePasskeyHasCredentials,47  initiateFirefoxPasskeyCreate,48  isPasskeyOfferDeclined,49  onVaultUnlocked,50  recordPasskeyOfferDecline,51  resolvePendingPasskeyRequest,52  setPasskeyProviderEnabled,53} from "./passkey";54import { buildAdvancedHealthReport } from "./health";55import { storageClear } from "../shared/storage";56import { findInvalidWords } from "../shared/recovery-words";57import type {58  Message,59  MessageResponse,60  MessageType,61  ProFeature,62  VaultEntry,63} from "../shared/types";64import { isPasskeyOnly } from "../shared/types";65import { generateTOTP } from "../crypto/totp";66import { isValidRpId } from "../shared/passkey-utils";67import { isNativePlatform, nativePlugin } from "../shared/native";68import { predictBatch as mlPredictBatch } from "./ml";69import type { MLFieldFeatures } from "../shared/ml";70import {71  buildLocalIdentity,72  getOrCreateDeviceId,73  setDeviceName as setDeviceNameV3,74} from "./device-identity";75import {76  clearDeviceRevocation,77  isDeviceRevoked,78  listPairedDevices as listPairedDevicesV3,79  revokeDeviceById as revokeDeviceByIdV3,80  upsertPairedDevice as upsertPairedDeviceV3,81} from "./paired-devices";82// Sync and pairing are imported statically, never with `await import()`.83// `import()` throws `TypeError: import() is disallowed on84// ServiceWorkerGlobalScope` at runtime in MV3, and Vite's preload helper85// reports the failure through `window.dispatchEvent`, which does not exist in86// a worker either — so the real reason was replaced by "window is not defined"87// and the pairing UI just stopped. scripts/check-sw-static-imports.mjs fails88// the build if a runtime import() reappears anywhere in the worker's graph.89import {90  cancelRelayAdoptionSource,91  confirmRelayAdoptionSource,92  isRelayAdoptionSourceInFlight,93  startRelayAdoptionSource,94} from "./relay-adoption-source-bg";95import {96  getSyncSettings,97  setRelayUrl,98  setSyncMode,99  type SyncMode,100} from "./sync-settings";101import {102  getSyncState,103  hydratePersistedSyncState,104  setSyncRunner,105  triggerSyncIfReachable,106} from "./sync-trigger";107import { productionSyncRunner } from "./sync-runner";108109// Compile-time E2E flag, folded to a literal by Vite's `define` (false in110// every production build — verified in the bundled output). Mirrors the111// create-path bypass in passkey.ts so the Playwright passkey smoke can enable112// the provider without a real Pro licence; the gate is fully intact for users.113declare const __PEACH_E2E_PASSKEYS__: boolean;114const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true;115116let nativeSyncRunnerBootstrapped = false;117118function unhexBytes(hex: string): Uint8Array {119  if (hex.length % 2 !== 0) throw new Error("invalid hex");120  const out = new Uint8Array(hex.length / 2);121  for (let i = 0; i < out.length; i++) {122    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);123  }124  return out;125}126127/**128 * The single Pro gate. Every gated handler calls this first; the broadcast129 * lets the popup react (navigate to the License section, highlight the130 * relevant feature). Background never touches the popup view directly —131 * the popup owns navigation. See Projects.md "Pro gate rule".132 */133async function requirePro(134  feature: ProFeature,135  trigger: "user" | "background" = "user"136): Promise<{ allowed: boolean }> {137  if (PASSKEY_E2E_PRO_BYPASS && feature === "passkeys") return { allowed: true };138  if (await isProUser()) return { allowed: true };139140  if (trigger === "user") {141    // User deliberately triggered this feature — redirect the popup immediately.142    chrome.runtime143      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })144      .catch(() => {145        // Popup may be closed — the gate signal is best-effort.146      });147  } else {148    // Background trigger (e.g. passive sync initiation) — no popup is open.149    // Queue a notice so the next popup open shows a soft banner instead of150    // silently failing.151    if (chrome.storage.session) {152      chrome.storage.session153        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })154        .catch(() => {});155    }156  }157158  return { allowed: false };159}160161// ---------------------------------------------------------------------------162// PCH-01-018: operations that irreversibly destroy or replace vault contents.163// These are gated to trusted extension-page senders in handleMessage; the164// confirmation UX otherwise lives only in the popup. Keep this in sync when165// adding new destructive handlers.166const DESTRUCTIVE_MESSAGE_TYPES: ReadonlySet<string> = new Set([167  "DESTROY_VAULT",168  "CLEAR_VAULT_ENTRIES",169  "RESTORE_VAULT_SNAPSHOT",170  "RESTORE_FROM_CODEX",171]);172173// LV-3: minimum interval between non-test canary pings per webhook+entry.174const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour175176const PRIVATE_IPV4_RANGES = [177  { prefix: "10." },178  { prefix: "127." },179  { prefix: "169.254." },180  { prefix: "192.168." },181];182183export function setupMessageHandler(): void {184  chrome.runtime.onMessage.addListener(185    (msg: unknown, sender, sendResponse) => {186      if (!isMessage(msg)) {187        sendResponse({ ok: false, error: "invalid_message" });188        return true;189      }190      handleMessage(msg, sender)191        .then(sendResponse)192        .catch((err) =>193          sendResponse({194            ok: false,195            error: err instanceof Error ? err.message : String(err),196          })197        );198      return true;199    }200  );201202  // Android: the chrome shim queues sendMessage calls until this handler is203  // registered. Without this hookup, every message hangs on Capacitor builds.204  // eslint-disable-next-line @typescript-eslint/no-explicit-any205  const reg = (globalThis as any).__peachRegisterMessageHandler;206  if (typeof reg === "function") {207    reg(async (m: unknown) => {208      if (!isMessage(m)) return { ok: false, error: "invalid_message" };209      try {210        return await handleMessage(m);211      } catch (err) {212        return {213          ok: false,214          error: err instanceof Error ? err.message : String(err),215        };216      }217    });218  }219  if (isNativePlatform()) {220    void bootstrapNativeSyncRunner();221  }222}223224async function bootstrapNativeSyncRunner(): Promise<void> {225  if (nativeSyncRunnerBootstrapped) return;226  nativeSyncRunnerBootstrapped = true;227  try {228    setSyncRunner(productionSyncRunner);229    await hydratePersistedSyncState();230  } catch (err) {231    nativeSyncRunnerBootstrapped = false;232    console.warn("[Peach] failed to bootstrap native sync runner:", err);233  }234}235236function isMessage(m: unknown): m is Message {237  return typeof m === "object" && m !== null && "type" in m;238}239240/**241 * The browser-attested origin of the page that originated this message. A web242 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),243 * so every page-driven message arrives via the content-script relay and the244 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a245 * value the page cannot forge. This is the ONLY trustworthy origin for passkey246 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.247 */248function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {249  if (sender.origin) return sender.origin;250  if (sender.url) {251    try { return new URL(sender.url).origin; } catch { return undefined; }252  }253  return undefined;254}255256// Resolves once restoreFromSession() has run, so handlers see the correct257// post-restore unlock state. entry.ts registers this BEFORE the message258// handler so the onMessage listener is added synchronously at SW startup259// (MV3 requirement) while unlock-dependent handlers still wait for restore.260let restoreReady: Promise<void> = Promise.resolve();261262/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */263export function setRestoreReady(p: Promise<unknown>): void {264  restoreReady = p.then(() => undefined, () => undefined);265}266267export async function handleMessage(268  msg: Message,269  sender: Partial<chrome.runtime.MessageSender> = {}270): Promise<MessageResponse> {271  try {272    // Wait for session-restore to finish before reading any unlock/vault state.273    // On a cold SW start the popup's first message arrives while restore is274    // still in flight; without this gate IS_UNLOCKED would report locked (a275    // spurious lock screen) and the storage reads could race. The onMessage276    // listener itself is registered synchronously (entry.ts) so this gate, not277    // listener registration, is what absorbs the cold-start window.278    await restoreReady;279    // Validate sender — only allow messages from our extension pages/scripts.280    // `sender.id` is undefined for messages originating from extension UI281    // (popup/options), which is legitimate; reject only when it is defined282    // and does not match our extension id.283    if (284      sender.id !== undefined &&285      sender.id !== chrome.runtime.id286    ) {287      return { ok: false, error: "invalid_sender" };288    }289290    // PCH-01-018: irreversible operations must originate from a trusted extension291    // page (popup/options), never from a content script. The sender.id check above292    // only proves the message came from *our* extension — a content script injected293    // into an attacker page passes it. A single XSS-class bug in the injected UI294    // would otherwise escalate to vault destruction. Extension pages carry an295    // extension-origin sender.url; content scripts carry a page URL.296    if (DESTRUCTIVE_MESSAGE_TYPES.has(msg.type)) {297      const extensionOrigin = chrome.runtime.getURL("");298      if (!sender.url?.startsWith(extensionOrigin)) {299        return { ok: false, error: "invalid_sender" };300      }301    }302303    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {304      touchAutoLock();305    }306307    switch (msg.type) {308      case "CREATE_VAULT": {309        const { password } = msg.payload as { password: string };310        // Refuse to create a vault under an empty master password — the derived311        // key would be publicly known and the at-rest AES-GCM protection void312        // (audit HIGH; the CSV-import path previously passed ""). Length/strength313        // policy lives in the onboarding UI; this is the non-negotiable floor.314        if (typeof password !== "string" || password.length === 0) {315          return { ok: false, error: "invalid_payload" };316        }317        await vault.createVault(password);318        await setupAutoLock();319        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });320        onVaultUnlocked();321        return { ok: true };322      }323      case "CREATE_VAULT_FROM_ROOT_KEY": {324        const { password, rootKeyHex } = (msg.payload ?? {}) as {325          password?: unknown;326          rootKeyHex?: unknown;327        };328        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {329          return { ok: false, error: "invalid_payload" };330        }331332        try {333          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);334          await setupAutoLock();335          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });336          onVaultUnlocked();337          return { ok: true, vaultId };338        } catch (err) {339          return { ok: false, error: err instanceof Error ? err.message : String(err) };340        }341      }342      case "UNLOCK": {343        const { password } = msg.payload as { password: string };344        const ok = await vault.unlock(password);345        if (ok) {346          // KAT: verify the WebCrypto stack is healthy before the user relies on it.347          // Runs after unlock so latency is hidden behind the vault-load time.348          const kat = await runSelfTest();349          if (!kat.ok) {350            console.error("[Peach] Crypto self-test FAILED:", kat.error);351            await vault.lock();352            return { ok: false, error: "self_test_failed" };353          }354          await setupAutoLock();355          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });356          onVaultUnlocked();357          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());358          return { ok: true };359        }360        // Distinguish corruption from wrong password so the popup can offer361        // a history-restore path instead of falsely accusing the user of362        // mistyping (M7/COR-007).363        const failure = vault.consumeLastUnlockFailureReason();364        if (failure) {365          return {366            ok: false,367            error: "vault_corrupted",368            canRestoreFromHistory: true,369          } as MessageResponse;370        }371        return { ok: false };372      }373      case "VALIDATE_RECOVERY_WORDS": {374        const { words } = msg.payload as { words: string[] };375        const invalid = findInvalidWords(words);376        return { ok: true, data: { valid: invalid.length === 0, invalid } };377      }378      case "GET_RECOVERY_WORDS": {379        // Must be unlocked and have recovery set up (vault must be v2.12+).380        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };381        // LV-4: the recovery words re-derive the ROOT KEY — the highest-382        // value secret in the vault. A session unlock (which may be hours383        // old on a shared machine) is not enough; require a fresh password384        // proof, matching the 1Password/Bitwarden pattern for revealing385        // escrow material. EXEMPTION: the create-vault / rotation confirmation386        // window (peach_recovery_pending) shows the words immediately after387        // the user authenticated, and that confirmation UI has no password to388        // resend — skip the re-auth there only.389        if (!(await isRecoveryConfirmPending())) {390          const { password } = (msg.payload ?? {}) as { password?: string };391          if (typeof password !== "string" || !password) {392            return { ok: false, error: "password_required" };393          }394          if (!(await vault.verifyMainPassword(password))) {395            return { ok: false, error: "wrong_password" };396          }397        }398        try {399          const words = await vault.getRecoveryWords();400          return { ok: true, data: words };401        } catch (e) {402          // pre-v2.12 vault that hasn't migrated403          return { ok: false, error: "recovery_not_setup" };404        }405      }406      case "RECOVER_WITH_WORDS": {407        // User has lost their password but has their 12 recovery words.408        // We: (1) validate the words, (2) re-encrypt vault with new password.409        const { words, newPassword } = msg.payload as {410          words: string[];411          newPassword: string;412        };413        const stored = await vault.loadSlotA();414        if (!stored) return { ok: false, error: "no_vault" };415        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {416          return { ok: false, error: "recovery_not_setup" };417        }418        // Unwrap the root key from the recovery escrow.419        try {420          await vault.unwrapRootKeyForRecovery(421            stored.recovery_wrapped_root_key,422            stored.recovery_nonce ?? "",423            stored.recovery_tag ?? "",424            stored.recovery_salt,425            words426          );427        } catch {428          return { ok: false, error: "invalid_recovery_words" };429        }430        // Re-key: derive fresh salt + key from new password.431        const newSalt = vault.generateSalt();432        const newKey = await vault.deriveKey(newPassword, newSalt);433        // Re-wrap root key under the new password's derived key so the same434        // recovery words continue to work after the password change.435        await vault.rewrapRootKeyForPassword(newKey, newSalt);436        // Re-encrypt vault entries with the new key.437        await vault.changePasswordWithNewKey(newSalt, newKey);438        await setupAutoLock();439        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });440        return { ok: true };441      }442      case "LOCK":443        vault.lock();444        if (isNativePlatform()) await clearInMemoryVault();445        return { ok: true };446      case "IS_UNLOCKED":447        return { ok: true, data: vault.isUnlocked() };448      case "GET_VAULT_STATUS":449        return { ok: true, unlocked: vault.isUnlocked() };450      case "HAS_VAULT":451        return { ok: true, data: await vault.hasVault() };452      case "GET_ENTRIES":453        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };454        return { ok: true, data: vault.getEntries() };455      case "ADD_ENTRY": {456        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };457        const payload = msg.payload;458        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {459          return { ok: false, error: "invalid_payload" };460        }461        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);462        return { ok: true, data: entry };463      }464      case "BATCH_ADD_ENTRIES": {465        const payload = msg.payload as { entries?: unknown } | null | undefined;466        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {467          return { ok: false, error: "invalid_payload" };468        }469        if (!Array.isArray(payload.entries)) {470          return { ok: false, error: "invalid_payload" };471        }472        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);473        return { ok: true, data: added };474      }475      case "RESTORE_ENTRIES": {476        const payload = msg.payload as477          | { entries?: unknown; mode?: unknown; settings?: unknown }478          | null479          | undefined;480        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {481          return { ok: false, error: "invalid_payload" };482        }483        if (!Array.isArray(payload.entries)) {484          return { ok: false, error: "invalid_payload" };485        }486        if (payload.mode !== "replace" && payload.mode !== "merge") {487          return { ok: false, error: "invalid_payload" };488        }489        const summary = await vault.restoreEntries(490          payload.entries as Parameters<typeof vault.restoreEntries>[0],491          payload.mode492        );493        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {494          await vault.updateSettings(payload.settings as vault.VaultSettings);495        }496        return { ok: true, data: summary };497      }498      case "CLEAR_VAULT_ENTRIES": {499        await vault.clearVaultEntries("REPLACE_ALL");500        return { ok: true };501      }502      case "GET_VAULT_HISTORY": {503        const snapshots = await vault.getVaultHistory();504        return { ok: true, data: snapshots };505      }506      case "RESTORE_VAULT_SNAPSHOT": {507        const { snapshotId } = msg.payload as { snapshotId: string };508        const result = await vault.restoreVaultSnapshot(snapshotId);509        if (!result.ok) return { ok: false, error: result.error };510        broadcastToContentScripts({ type: "VAULT_LOCKED" });511        return { ok: true };512      }513      case "COUNT_DUPLICATES": {514        return { ok: true, data: vault.countDuplicates() };515      }516      case "DEDUPLICATE_ENTRIES": {517        const removed = await vault.deduplicateEntries();518        return { ok: true, data: removed };519      }520      case "UPDATE_ENTRY": {521        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;522        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {523          return { ok: false, error: "invalid_payload" };524        }525        const { id, patch } = payload;526        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {527          return { ok: false, error: "invalid_payload" };528        }529        // Single enforcement point for the Canary Entries Pro gate. Only530        // gates the transition into a canary entry — clearing/disabling a531        // canary (`canary: undefined`) is always allowed, so existing532        // canary entries remain manageable.533        const incomingCanary = (patch as { canary?: unknown }).canary;534        if (incomingCanary && typeof incomingCanary === "object") {535          const existing = vault.getEntryById(id);536          if (!existing?.canary) {537            const gate = await requirePro("canary_entry");538            if (!gate.allowed) return { ok: false, error: "pro_required" };539          }540        }541        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);542        return { ok: true };543      }544      case "ADD_ADDITIONAL_URL": {545        const { id, url } = msg.payload as { id: string; url: string };546        const trimmed = typeof url === "string" ? url.trim() : "";547        if (!trimmed) return { ok: false, error: "url_required" };548        const existing = vault.getEntryById(id);549        if (!existing) return { ok: false, error: "entry_not_found" };550        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };551        const merged = [...(existing.additionalUrls ?? []), trimmed];552        await vault.updateEntry(id, { additionalUrls: merged });553        return { ok: true };554      }555      case "DELETE_ENTRY": {556        const { id } = msg.payload as { id: string };557        await vault.deleteEntry(id);558        return { ok: true };559      }560      case "GET_DELETED_ENTRIES":561        return { ok: true, data: vault.getDeletedEntries() };562      case "RESTORE_ENTRY": {563        const { id } = msg.payload as { id: string };564        await vault.restoreEntry(id);565        return { ok: true };566      }567      case "PURGE_ENTRY": {568        const { id } = msg.payload as { id: string };569        await vault.purgeEntry(id);570        return { ok: true };571      }572      case "PURGE_EXPIRED_TRASH": {573        const { retentionMs } = msg.payload as { retentionMs: number };574        const purged = await vault.purgeExpiredTrash(retentionMs);575        return { ok: true, data: purged };576      }577      case "SAVE_NOTE": {578        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };579        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };580        const now = Date.now();581        if (id) {582          const existing = vault.getEntryById(id);583          if (!existing) return { ok: false, error: "not_found" };584          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });585          return { ok: true, data: vault.getEntryById(id) };586        } else {587          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt588          // (EntryDraft omits both), so passing them was the only reason the589          // `as any` cast existed. Dropping them makes the call type-check.590          const entry = await vault.addEntry({591            type: "note",592            title: title || "Untitled",593            notes: body,594          });595          return { ok: true, data: entry };596        }597      }598      case "DELETE_NOTE": {599        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };600        const { id } = msg.payload as { id: string };601        await vault.deleteEntry(id);602        return { ok: true };603      }604      case "GET_NOTES": {605        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };606        const notes = vault.getEntries().filter(607          (e) => e.type === "note" && !e.deletedAt608        );609        return { ok: true, data: notes } as MessageResponse;610      }611      case "SEARCH_VAULT": {612        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };613        // AUD-002: shape-validate the payload before calling string methods.614        // A raw cast lets a malformed message crash the handler with TypeError.615        const { query } = (msg.payload ?? {}) as { query?: unknown };616        if (typeof query !== "string") {617          return { ok: false, error: "invalid_payload" };618        }619        const q = query.toLowerCase();620        const searchResults = vault.getEntries().filter(621          (e) =>622            !e.deletedAt &&623            (e.title.toLowerCase().includes(q) ||624              e.notes?.toLowerCase().includes(q) ||625              e.username?.toLowerCase().includes(q))626        );627        return { ok: true, data: searchResults } as MessageResponse;628      }629      case "AUTOFILL_QUERY": {630        if (!vault.isUnlocked()) {631          return { ok: false, error: "vault_locked" };632        }633        let { includeAll } = msg.payload as { includeAll?: boolean };634        const { domain, kind, userGesture } = msg.payload as {635          domain: string;636          kind?: "login" | "card" | "totp";637          userGesture?: boolean;638        };639        // MV-2: the vault-wide inventory (every title/username/email/url)640        // may only leave the background on an explicit user gesture — the641        // user opening the search affordance — never on passive form focus.642        // userGesture is self-declared by our own content script; the value643        // of this gate is that PASSIVE code paths (which never set it)644        // cannot ship the inventory, shrinking what a compromised page that645        // merely triggers focus events can observe.646        if (includeAll && userGesture !== true) {647          includeAll = false;648        }649        // kind="card": return saved cards as compact summaries for the650        // inline card silver platter. Cards are not domain-scoped — every651        // saved card is a candidate on every checkout page — so domain is652        // ignored when kind === "card".653        if (kind === "card") {654          const cards = vault.getEntries().filter((e) => e.type === "card");655          return {656            ok: true,657            data: cards.map((e) => ({658              id: e.id,659              title: e.cardNickname || e.title,660              cardholderName: e.cardholderName,661              last4: e.last4,662              expMonth: e.expMonth,663              expYear: e.expYear,664              network: e.network,665            })),666          };667        }668        if (kind === "totp") {669          const matches = (670            includeAll671              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")672              : vault.queryDomain(domain)673          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));674          return {675            ok: true,676            data: matches.map((e) => ({677              id: e.id,678              title: e.title,679              username: e.username,680              email: e.email,681              url: e.url,682              hasTotp: true,683            })),684          };685        }686        // The inline selector fills username+password into a form. Passkey-687        // only entries have no password to fill; sign-in for those goes688        // through the WebAuthn path instead. Filter them out everywhere so689        // the user doesn't see four "GitHub" rows that mostly do nothing.690        // Notes and cards never belonged here either.691        const matches = (692          includeAll693            ? vault694                .getEntries()695                .filter((entry) => entry.type !== "note" && entry.type !== "card")696            : vault.queryDomain(domain)697        ).filter((entry) => !isPasskeyOnly(entry));698        return {699          ok: true,700          data: matches.map((e) =>701            includeAll702              ? {703                  id: e.id,704                  title: e.title,705                  // username/email/url shipped so the inline popup's search706                  // affordance can match on them, not just titles. No secrets707                  // cross the boundary — same shape as the domain-matched708                  // response below minus hasTotp (which the search list709                  // doesn't surface).710                  username: e.username,711                  email: e.email,712                  url: e.url,713                  hasPasskey: e.passkey !== undefined,714                }715              : {716                  id: e.id,717                  title: e.title,718                  username: e.username,719                  email: e.email,720                  url: e.url,721                  hasTotp: Boolean(e.totp),722                  hasPasskey: e.passkey !== undefined,723                }724          ),725        };726      }727      case "GET_ENTRY_FOR_FILL": {728        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };729        const { id, explicitSummon } = msg.payload as {730          id: string;731          explicitSummon?: boolean;732        };733        const entry = vault.getEntryById(id);734        if (!entry) return { ok: false, error: "entry_not_found" };735        // Passkey-only entries (passkey credential, no password) cannot be736        // filled into a form — sign-in goes through the WebAuthn path. A737        // login that ALSO has a passkey is still fillable for its password.738        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };739740        // MV-1: re-validate the entry against the requesting tab's origin.741        // sender.tab.url is browser-attested — a page cannot forge it. When742        // the request does not come from a tab at all (popup surfaces use743        // GET_ENTRY_FOR_EDIT, not this), refuse.744        if (sender.tab !== undefined || sender.url !== undefined) {745          let senderDomain: string | null = null;746          try {747            const rawUrl = sender.tab?.url ?? sender.url ?? "";748            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;749          } catch {750            senderDomain = null;751          }752          if (!senderDomain) return { ok: false, error: "origin_unverified" };753754          const entryDomains = new Set<string>();755          const primary = extractDomain(entry.url ?? "");756          if (primary) entryDomains.add(primary);757          for (const extra of entry.additionalUrls ?? []) {758            const d = extractDomain(extra);759            if (d) entryDomains.add(d);760          }761762          // explicitSummon=true means the user actively picked this entry763          // from the cross-domain search affordance — an intentional764          // off-domain fill. Passive fill paths must stay domain-bound.765          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {766            // Domain mismatch — refuse silently (no oracle about which ids exist).767            return { ok: false, error: "entry_not_found" };768          }769        }770        // Strip the passkey credential AND the raw base32 TOTP seed from the771        // response. Content scripts never need either: the private key is the772        // authenticator's, and handing over the TOTP seed would let a773        // compromised content script mint valid codes indefinitely (SEV-3-C).774        // Generate the *current* 6-digit code here in the background and send775        // only that, plus the seconds left so the UI can render a countdown.776        // Also drop passwordHistory: filling needs only the *current* password.777        // Handing every past password to a content script during passive778        // autofill on an arbitrary page would widen the blast radius of a779        // compromised page far beyond the one credential being filled.780        const {781          passkey: _strippedPasskey,782          totp: seed,783          totpAlgorithm,784          totpDigits,785          totpPeriod,786          passwordHistory: _ph,787          ...safeEntry788        } = entry;789        let totpCode: string | undefined;790        let totpRemaining: number | undefined;791        if (seed) {792          try {793            // PCH-01-019: honour stored algorithm/digits/period (defaults apply794            // when these are undefined, i.e. legacy bare-seed entries).795            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);796            totpCode = generated.code;797            totpRemaining = generated.remaining;798          } catch {799            totpCode = undefined;800          }801        }802        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };803      }804      // Trusted full-entry fetch for Peach's own inline-popup surfaces that805      // genuinely need the raw TOTP seed: the edit form (which re-saves the806      // seed and would otherwise wipe it) and nothing else. Unlike807      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside808      // the inline popup, never during passive autofill on an arbitrary page.809      // The passkey credential is still stripped — the edit form never touches it.810      case "GET_ENTRY_FOR_EDIT": {811        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };812        const { id, explicitSummon } = msg.payload as {813          id: string;814          explicitSummon?: boolean;815        };816        const entry = vault.getEntryById(id);817        if (!entry) return { ok: false, error: "entry_not_found" };818819        // PCH-01-006: re-validate the browser-attested sender origin, mirroring820        // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and821        // full password history — at least as sensitive as the fill response — so822        // the boundary must be enforced here, not only by UI reachability. Today823        // the sole caller is the popup (no sender.tab, so this is a structural824        // no-op), but a future tab-context caller or an id leak would otherwise825        // inherit a full-credential oracle. Unlike the fill path we SKIP (not826        // refuse) when no sender domain resolves, to keep the popup caller working.827        if (sender.tab !== undefined || sender.url !== undefined) {828          let senderDomain: string | null = null;829          try {830            const rawUrl = sender.tab?.url ?? sender.url ?? "";831            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;832          } catch {833            senderDomain = null;834          }835          if (senderDomain) {836            const entryDomains = new Set<string>();837            const primary = extractDomain(entry.url ?? "");838            if (primary) entryDomains.add(primary);839            for (const extra of entry.additionalUrls ?? []) {840              const d = extractDomain(extra);841              if (d) entryDomains.add(d);842            }843            if (explicitSummon !== true && !entryDomains.has(senderDomain)) {844              return { ok: false, error: "entry_not_found" }; // no id oracle845            }846          }847        }848849        const { passkey: _passkey, ...safeEntry } = entry;850        return { ok: true, data: safeEntry };851      }852      case "COPY": {853        // AUD-002: shape-validate the payload before passing to the clipboard854        // helper. A raw cast lets a malformed message reach the clipboard API855        // with a non-string and throw.856        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {857          text?: unknown;858          label?: unknown;859          alreadyWritten?: unknown;860        };861        if (typeof text !== "string" || typeof label !== "string") {862          return { ok: false, error: "invalid_payload" };863        }864        await copyToClipboard(text, label, Boolean(alreadyWritten));865        return { ok: true, clearSeconds: getEffectiveClearSeconds() };866      }867      case "CHECK_ALL_BREACHES": {868        const allEntries = vault.getEntries();869        const results: Record<string, number> = {};870        for (const entry of allEntries) {871          if (entry.type === "note") continue;872          if (!entry.password) continue;873          results[entry.id] = await vault.checkBreach(entry.password);874          // Small delay — be a good citizen to the HIBP API875          await new Promise((r) => setTimeout(r, 200));876        }877        // Persist any non-zero counts back to entries878        for (const [id, count] of Object.entries(results)) {879          const entry = vault.getEntryById(id);880          if (entry && (entry.breach ?? 0) !== count) {881            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });882          }883        }884        return { ok: true, data: results };885      }886      case "GET_SETTINGS":887        return { ok: true, data: await vault.ensureSettingsLoaded() };888      case "UPDATE_SETTINGS": {889        const patch = msg.payload;890        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {891          return { ok: false, error: "invalid_payload" };892        }893        await vault.updateSettings(patch as vault.VaultSettings);894        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {895          await setupAutoLock();896          if (vault.isUnlocked()) touchAutoLock();897        }898        return { ok: true };899      }900      case "GET_PENDING_PASSKEY":901        return { ok: true, data: await getPendingPasskeyRequest() };902      case "APPROVE_PASSKEY": {903        const { requestId } = msg.payload as { requestId: number };904        await resolvePendingPasskeyRequest(requestId, true);905        return { ok: true };906      }907      case "DENY_PASSKEY": {908        const { requestId } = msg.payload as { requestId: number };909        await resolvePendingPasskeyRequest(requestId, false);910        return { ok: true };911      }912      case "GET_PASSKEY_PROVIDER_STATE":913        return { ok: true, data: await getPasskeyProviderState() };914      case "SET_PASSKEY_PROVIDER_ENABLED": {915        const { enabled } = msg.payload as { enabled: boolean };916        // Disabling is always free; gating fires only when a free user is917        // trying to turn passkey interception on.918        if (enabled) {919          const gate = await requirePro("passkeys");920          if (!gate.allowed) return { ok: false, error: "pro_required" };921        }922        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };923      }924      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS925      // endpoint. Intentional product behavior — users configure their own926      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private927      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-928      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to929      // users that the entry title leaves the device when the canary fires.930      case "FIRE_CANARY_PING": {931        // Canary alert fires unconditionally for any entry with canary: true.932        // The Pro gate only governs creation/flagging of canary entries; once933        // an entry is flagged, the alert path is a security property and must934        // never be license-gated.935        const { webhookUrl, entryTitle, trigger } = msg.payload as {936          webhookUrl: string;937          entryTitle: string;938          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";939        };940        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {941          return { ok: false, error: "invalid_webhook_url" };942        }943        // LV-3: debounce non-test pings per (webhook, entry) so a page that944        // strobes focus/fill events can't turn the canary into a request945        // firehose at the user's endpoint. Test pings are exempt — they are946        // explicit user clicks in the settings UI and are awaited for947        // feedback. The FIRST ping in a window always goes out, so the948        // dead-man's-switch property (canary fires on access) is preserved;949        // only repeats within the window are coalesced.950        if (trigger !== "test") {951          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;952          const stored = await chrome.storage.local.get(rlKey);953          const last = (stored as Record<string, unknown>)[rlKey];954          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {955            return { ok: true, data: { rateLimited: true } };956          }957          await chrome.storage.local.set({ [rlKey]: Date.now() });958        }959        const body = JSON.stringify({960          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",961          entry: entryTitle,962          trigger,963          timestamp: new Date().toISOString(),964          source: "peach-extension",965        });966        if (trigger === "test") {967          // Permitted outbound fetch: user-configured canary alert endpoint968          // (validated by isAllowedCanaryWebhookUrl above). This is the969          // only non-HIBP outbound call in the extension — see970          // Projects.md §3.7. Test pings are awaited so the UI can show971          // success/failure.972          try {973            const res = await fetch(webhookUrl, {974              method: "POST",975              headers: { "Content-Type": "application/json" },976              body,977            });978            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };979          } catch (err) {980            return { ok: false, error: err instanceof Error ? err.message : "network_error" };981          }982        }983        // Non-test triggers are fire-and-forget984        fetch(webhookUrl, {985          method: "POST",986          headers: { "Content-Type": "application/json" },987          body,988        }).catch(() => {});989        return { ok: true };990      }991      case "ACTIVATE_LICENSE": {992        const { key } = msg.payload as { key: string };993        const licenseInfo = await activateLicense(key);994        return { ok: true, data: licenseInfo };995      }996      case "GET_LICENSE": {997        const licenseInfo = await getLicenseInfo();998        return { ok: true, data: licenseInfo };999      }1000      case "GET_LICENSE_KEY": {1001        const key = await getLicenseKey();1002        return { ok: true, data: key };1003      }1004      case "DEACTIVATE_LICENSE": {1005        await deactivateLicense();1006        return { ok: true };1007      }1008      case "SHOULD_PLAY_CELEBRATION": {1009        const should = await shouldPlayCelebration();1010        return { ok: true, data: should };1011      }1012      case "MARK_CELEBRATION_PLAYED": {1013        await markCelebrationPlayed();1014        return { ok: true };1015      }1016      case "GET_CODEX_VAULT_DATA": {1017        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1018        // popup navigates to the License section without further coordination.1019        const gate = await requirePro("codex");1020        if (!gate.allowed) return { ok: false, error: "pro_required" };1021        return await handleGetCodexVaultData();1022      }1023      case "ESTIMATE_CODEX_PAGES": {1024        const gate = await requirePro("codex");1025        if (!gate.allowed) return { ok: false, error: "pro_required" };1026        return await handleEstimateCodexPages();1027      }1028      case "RESTORE_FROM_CODEX": {1029        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1030        // be able to restore a vault that was printed by a Pro user.1031        // DO NOT add a Pro gate here.1032        const payload = msg.payload as CodexRestorePayload;1033        return await handleRestoreFromCodex(payload);1034      }1035      case "OPEN_PRO_GATE": {1036        // Content script requests: open popup and navigate to License section.1037        const { feature } = (msg.payload ?? {}) as { feature?: string };1038        if (chrome.storage.session) {1039          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1040        }1041        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1042        return { ok: true };1043      }1044      case "OPEN_POPUP": {1045        // Content script asks to open the trusted extension popup — used by the1046        // inline locked bubble so the master password is entered in the popup,1047        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1048        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1049        // toolbar icon. The badge already signals Peach needs attention.1050        //1051        // Set a session flag so the popup knows it was opened for inline unlock1052        // and should close itself once the vault is unlocked (returning the user1053        // to the inline autofill selector on the page).1054        if (chrome.storage.session) {1055          await chrome.storage.session.set({ peach_inline_unlock: true });1056        }1057        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1058        return { ok: true };1059      }1060      case "GET_IDENTITIES": {1061        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1062        return { ok: true, data: vault.getIdentities() };1063      }1064      case "TOUCH_AUTO_LOCK": {1065        // touchAutoLock() is already called by shouldRefreshAutoLock above;1066        // this case just gives the popup a typed message to keep the session alive.1067        return { ok: true };1068      }1069      case "GET_ADVANCED_HEALTH_REPORT": {1070        const gate = await requirePro("advanced_health");1071        if (!gate.allowed) return { ok: false, error: "pro_required" };1072        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1073        const report = await buildAdvancedHealthReport(vault.getEntries());1074        return { ok: true, data: report };1075      }1076      case "IS_DURESS_ENABLED": {1077        const enabled = await vault.isDuressEnabled();1078        return { ok: true, data: enabled };1079      }1080      case "SETUP_DURESS": {1081        // Single enforcement point for the Duress Vault Pro gate. Free users1082        // who somehow reach this handler are rejected here; the popup also1083        // pre-checks isPro() to avoid showing the setup form to free users,1084        // but server-side is the actual security boundary.1085        const gate = await requirePro("duress_vault");1086        if (!gate.allowed) return { ok: false, error: "pro_required" };1087        // MV3 service workers restart after inactivity, losing the in-memory1088        // derived key. Detect this before calling setupDuress so the popup1089        // can show a meaningful prompt to re-lock and re-unlock.1090        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1091        const { duressPassword } = msg.payload as { duressPassword: string };1092        await vault.setupDuress(duressPassword);1093        return { ok: true };1094      }1095      case "DISABLE_DURESS": {1096        await vault.disableDuress();1097        return { ok: true };1098      }1099      case "VERIFY_MAIN_PASSWORD": {1100        const { password } = msg.payload as { password: string };1101        const ok = await vault.verifyMainPassword(password);1102        return { ok: true, data: ok };1103      }1104      case "CHANGE_PASSWORD": {1105        const { currentPassword, newPassword } = msg.payload as {1106          currentPassword: string;1107          newPassword: string;1108        };1109        const changed = await vault.changePassword(currentPassword, newPassword);1110        return changed1111          ? { ok: true }1112          : { ok: false, error: "incorrect_current_password" };1113      }1114      case "GET_SITE_PASSWORD_POLICY": {1115        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1116        if (!tab?.id) return { ok: true, data: null };1117        try {1118          const response = await chrome.tabs.sendMessage(tab.id, {1119            type: "GET_SITE_PASSWORD_POLICY",1120          });1121          return (response as MessageResponse) ?? { ok: true, data: null };1122        } catch {1123          return { ok: true, data: null };1124        }1125      }1126      case "RECORD_MANUAL_SUMMON": {1127        const { domain } = msg.payload as { domain: string };1128        const settings = vault.getSettings();1129        const existing = settings.manualSummonDomains?.[domain];1130        const now = Date.now();1131        await vault.updateSettings({1132          manualSummonDomains: {1133            ...settings.manualSummonDomains,1134            [domain]: {1135              firstSummonedAt: existing?.firstSummonedAt ?? now,1136              summonCount: (existing?.summonCount ?? 0) + 1,1137              lastSummonedAt: now,1138            },1139          },1140        });1141        return { ok: true };1142      }1143      case "DECLINE_CARD_SAVE": {1144        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1145        await vault.declineCardSaveOffer(last4, expMonth, expYear);1146        return { ok: true };1147      }1148      case "IS_CARD_DECLINED": {1149        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1150        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1151        return { ok: true, data: declined };1152      }1153      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1154        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1155          rpId?: string;1156          rpName?: string;1157          userName?: string;1158          userDisplayName?: string;1159        };1160        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1161        return await initiateFirefoxPasskeyCreate({1162          rpId,1163          rpName: rpName ?? rpId,1164          userName,1165          userDisplayName,1166        });1167      }11681169      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1170        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1171        if (!payload) return { ok: false, error: "missing_payload" };1172        return await completeFirefoxPasskeyCreate(payload);1173      }11741175      case "PASSKEY_OFFER_DECLINE": {1176        const { domain } = (msg.payload ?? {}) as { domain?: string };1177        if (!domain) return { ok: false, error: "domain_required" };1178        await recordPasskeyOfferDecline(domain);1179        return { ok: true };1180      }11811182      case "GET_PASSKEY_OFFER_DECLINED": {1183        const { domain } = (msg.payload ?? {}) as { domain?: string };1184        if (!domain) return { ok: false, error: "domain_required" };1185        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1186      }11871188      case "PASSKEY_HAS_CREDENTIALS": {1189        const payload = msg.payload as {1190          rpId?: string;1191          allowCredentials?: Array<{ id: string; type?: string }>;1192        } | undefined;1193        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1194        return await handlePasskeyHasCredentials({1195          rpId: payload.rpId,1196          allowCredentials: payload.allowCredentials ?? [],1197        }, attestedSenderOrigin(sender));1198      }11991200      case "PASSKEY_CREATE": {1201        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1202        if (!payload?.rpId || !payload?.userName) {1203          return { ok: false, error: "rpid_and_username_required" };1204        }1205        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1206      }12071208      case "PASSKEY_GET": {1209        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1210        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1211        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1212      }12131214      case "PASSKEY_AUTH_RESPONSE": {1215        const { requestId, approved } = (msg.payload ?? {}) as {1216          requestId?: string | number;1217          approved?: boolean;1218        };1219        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1220          return { ok: false, error: 'requestId and approved required' };1221        }1222        await resolvePendingPasskeyRequest(Number(requestId), approved);1223        return { ok: true };1224      }12251226      case "GET_PASSKEY_FOR_DOMAIN": {1227        const { domain } = (msg.payload ?? {}) as { domain?: string };1228        if (!domain) return { ok: false, error: "domain_required" };1229        // Scope to the caller's own origin: a page may only ask about passkeys1230        // for a domain it actually owns, so an arbitrary page cannot enumerate1231        // which sites the user holds passkeys for or read the username (audit MEDIUM).1232        const origin = attestedSenderOrigin(sender);1233        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1234        if (!vault.isUnlocked()) return { ok: true, data: null };1235        const match = vault1236          .getEntries()1237          .find((entry) => entry.passkey?.rpId === domain);1238        if (!match || !match.passkey) return { ok: true, data: null };1239        // Slim shape — only the fields State 11 needs. Never expose private1240        // key material, even though this is locked behind isUnlocked.1241        return {1242          ok: true,1243          data: {1244            rpId: match.passkey.rpId,1245            userName: match.passkey.userName,1246            browser: match.passkey.browser,1247          },1248        };1249      }12501251      case "DESTROY_VAULT": {1252        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1253        // storage.local.clear() wipes every Peach key (slots, settings, license,1254        // onboarded flag, history, sync state, declined cards, recall, etc.);1255        // session.clear() wipes pending passkey requests + pro-notice queues.1256        // Caller (Panic.tsx) handles UI navigation back to onboarding.1257        //1258        // The Pro license is the one thing that must survive: the user paid for1259        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1260        // Capture it before the clear and restore it after. peach_pro_celebrated1261        // rides along so the Pro celebration doesn't replay on the next unlock.1262        const preserved = await chrome.storage.local.get([1263          "peach_license",1264          "peach_pro_celebrated",1265        ]);1266        vault.lock();1267        await storageClear();1268        await vault.clearVaultHistory();1269        const toRestore: Record<string, unknown> = {};1270        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1271        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1272        if (Object.keys(toRestore).length > 0) {1273          await chrome.storage.local.set(toRestore);1274        }1275        if (chrome.storage.session) {1276          await chrome.storage.session.clear();1277        }1278        return { ok: true };1279      }12801281      // Android-only: biometric unlock with pre-derived key.1282      case "UNLOCK_WITH_KEY": {1283        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1284        if (!isNativePlatform()) {1285          return { ok: false, error: "desktop_only_uses_password" };1286        }1287        try {1288          const result = await vault.unlockWithKey(masterKeyHex);1289          if (result.ok) {1290            onVaultUnlocked();1291            await publishInMemoryVault(result.entries);1292          }1293          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1294        } catch {1295          return { ok: false, error: "invalid_key" };1296        }1297      }1298      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1299      case "GET_DERIVED_KEY": {1300        if (!isNativePlatform()) {1301          return { ok: false, error: "android_only" };1302        }1303        if (!vault.isUnlocked()) {1304          return { ok: false, error: "vault_locked" };1305        }1306        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1307      }1308      case "GET_IDENTITY_SUGGESTIONS": {1309        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1310        const entries = vault.getEntries();1311        const suggestions = buildIdentitySuggestions(entries);1312        return { ok: true, data: { suggestions } };1313      }1314      case "POPULATE_INLINE_VAULT": {1315        if (!isNativePlatform()) return { ok: false };1316        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1317        const entries = vault.getEntries();1318        await publishInMemoryVault(entries);1319        return { ok: true };1320      }1321      case "ML_INIT":1322        return { ok: true };13231324      case "ML_PREDICT_BATCH": {1325        // AUD-002: shape-validate before forwarding to the ML helper.1326        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1327        if (!Array.isArray(featuresArray)) {1328          return { ok: false, error: "invalid_payload" };1329        }1330        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1331      }13321333      // ── Vault sync (v3) ───────────────────────────────────────────────1334      // Returns the public-facing local identity needed by the popup to1335      // drive Phase-1 audio pairing. The private long-term key never1336      // leaves the background.1337      case "GET_LOCAL_IDENTITY": {1338        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1339        // Pro license from an already-Pro peer (at least one device must be Pro).1340        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1341        // Identity derives from the stable root key, not the password-derived1342        // key, so pairing survives a master-password change (SEV-2-B).1343        const masterKeyHex = vault.getRootKeyHex();1344        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1345        const masterKey = unhexBytes(masterKeyHex);1346        try {1347          const identity = await buildLocalIdentity(masterKey);1348          // If this device is Pro, advertise the signed license so the peer can1349          // activate it after SAS confirmation — pairing carries Pro across.1350          if (await isProUser()) {1351            const license = await getLicenseKey();1352            if (license) (identity as { license?: string }).license = license;1353          }1354          return { ok: true, data: identity };1355        } finally {1356          masterKey.fill(0);1357        }1358      }13591360      case "GET_ADOPTION_MATERIAL": {1361        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1362        const rootKeyHex = vault.getRootKeyHex();1363        if (!rootKeyHex) return { ok: false, error: "vault_locked" };1364        const rootKeyBytes = unhexBytes(rootKeyHex);1365        try {1366          const data: { rootKeyHex: string; vaultId: string; license?: string } = {1367            rootKeyHex,1368            vaultId: await computeVaultId(rootKeyBytes),1369          };1370          if (await isProUser()) {1371            const license = await getLicenseKey();1372            if (license) data.license = license;1373          }1374          return { ok: true, data };1375        } finally {1376          rootKeyBytes.fill(0);1377        }1378      }13791380      case "COMPLETE_PAIRING": {1381        // Not Pro-gated — see GET_LOCAL_IDENTITY.1382        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1383        const paired = (msg.payload as { paired?: unknown })?.paired;1384        if (typeof paired !== "object" || paired === null) {1385          return { ok: false, error: "invalid_payload" };1386        }1387        const candidate = paired as Record<string, unknown>;1388        if (1389          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1390          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1391          typeof candidate.deviceType !== "string" ||1392          typeof candidate.longTermPublicKeyHex !== "string" ||1393          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1394          (1395            candidate.signingPublicKeyHex !== undefined &&1396            (1397              typeof candidate.signingPublicKeyHex !== "string" ||1398              !/^[0-9a-f]{64}$/.test(candidate.signingPublicKeyHex)1399            )1400          ) ||1401          typeof candidate.pairedAt !== "number"1402        ) {1403          return { ok: false, error: "invalid_paired_device" };1404        }1405        // A fresh SAS-confirmed direct pairing is the one operation allowed to1406        // lift an old terminal revocation. Without this, re-pairing recreated1407        // an impossible state where the same device was both paired and1408        // revoked, and a later Remove became a permanent no-op.1409        await clearDeviceRevocation(candidate.deviceId);1410        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1411        // Newly paired device → kick a sync so it gets its first round1412        // without waiting for the next 10-minute alarm tick. Fire-and-forget;1413        // the in-flight guard handles overlap with any other trigger.1414        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1415        return { ok: true };1416      }14171418      case "LIST_PAIRED_DEVICES": {1419        const devices = await listPairedDevicesV3();1420        return { ok: true, data: { devices } };1421      }14221423      case "UNPAIR_DEVICE": {1424        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1425        if (typeof deviceId !== "string" || !deviceId) {1426          return { ok: false, error: "invalid_payload" };1427        }1428        // Removing a device REVOKES it rather than just dropping the local1429        // row: a plain removal is undone the moment any other peer vouches it1430        // back through a manifest, which is exactly what the relay makes easy.1431        await revokeDeviceByIdV3(deviceId, await getOrCreateDeviceId());1432        // Sync against the remaining hosts — the unpaired device no longer1433        // matters but the next alarm tick is up to ten minutes away.1434        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1435        return { ok: true };1436      }14371438      case "RENAME_LOCAL_DEVICE": {1439        const { name } = (msg.payload ?? {}) as { name?: string };1440        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1441        await setDeviceNameV3(name);1442        return { ok: true };1443      }14441445      // ── Relay pairing ─────────────────────────────────────────────────────1446      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1447      // session runs in the background; the SAS and the terminal result reach1448      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1449      case "START_ADOPTION_SOURCE": {1450        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1451        if (isRelayAdoptionSourceInFlight()) {1452          return { ok: false, error: "adoption_source_in_progress" };1453        }1454        try {1455          return { ok: true, data: await startRelayAdoptionSource() };1456        } catch (error) {1457          return {1458            ok: false,1459            error: error instanceof Error ? error.message : "adoption_source_failed",1460          };1461        }1462      }14631464      case "ADOPTION_SOURCE_CONFIRM": {1465        const { password, cancel } = (msg.payload ?? {}) as {1466          password?: unknown;1467          cancel?: unknown;1468        };1469        if (cancel === true) {1470          return {1471            ok: true,1472            data: await confirmRelayAdoptionSource(null),1473          };1474        }1475        if (typeof password !== "string" || password.length === 0) {1476          return { ok: false, error: "invalid_payload" };1477        }1478        return {1479          ok: true,1480          data: await confirmRelayAdoptionSource(password),1481        };1482      }14831484      case "CANCEL_ADOPTION_SOURCE": {1485        cancelRelayAdoptionSource();1486        return { ok: true };1487      }14881489      case "TRIGGER_SYNC": {1490        const payload = (msg.payload ?? {}) as {1491          reason?: "vault_change" | "foreground" | "manual";1492          force?: boolean;1493        };1494        const reason = payload.reason ?? "foreground";14951496        void triggerSyncIfReachable({ reason, force: payload.force === true });1497        return { ok: true };1498      }14991500      case "GET_SYNC_STATE": {1501        return { ok: true, data: getSyncState() };1502      }15031504      case "GET_SYNC_SETTINGS": {1505        return { ok: true, data: await getSyncSettings() };1506      }15071508      case "SET_SYNC_SETTINGS": {1509        const payload = (msg.payload ?? {}) as {1510          mode?: unknown;1511          relayUrl?: unknown;1512        };1513        try {1514          // A custom relay URL implies private mode; Peach's own relay stays1515          // public. See setRelayUrl.1516          if (payload.relayUrl !== undefined) {1517            if (typeof payload.relayUrl !== "string") {1518              return { ok: false, error: "invalid_relay_url" };1519            }1520            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1521          }1522          if (payload.mode !== undefined) {1523            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1524              return { ok: false, error: "invalid_sync_mode" };1525            }1526            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1527          }1528          return { ok: true, data: await getSyncSettings() };1529        } catch (error) {1530          return {1531            ok: false,1532            error: error instanceof Error ? error.message : "invalid_relay_url",1533          };1534        }1535      }15361537      case "GET_SYNC_ALERTS": {1538        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1539        const alerts = await getPendingSyncAlerts();1540        // The popup reads on open and acknowledges with consume:true after1541        // rendering, so a popup crash between read and render doesn't lose1542        // the alerts.1543        if (consume) await clearPendingSyncAlerts();1544        return { ok: true, data: alerts };1545      }15461547      case "GET_PENDING_VOUCHED_DEVICES": {1548        return { ok: true, data: await listPendingVouchedDevices() };1549      }1550      case "CONFIRM_VOUCHED_DEVICE": {1551        const { deviceId } = msg.payload as { deviceId: string };1552        const pending = await getPendingVouchedDevice(deviceId);1553        if (!pending) return { ok: false, error: "not_pending" };1554        // Last gate before a vouched device becomes a sync peer. A queue entry1555        // can predate the revocation that names it, so revocation is re-checked1556        // here rather than trusted to have swept the queue.1557        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {1558          await removePendingVouchedDevice(deviceId);1559          return { ok: false, error: "device_revoked" };1560        }1561        await upsertPairedDeviceV3({1562          deviceId: pending.deviceId,1563          deviceName: pending.deviceName,1564          deviceType:1565            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1566          longTermPublicKeyHex: pending.longTermPublicKeyHex,1567          signingPublicKeyHex: pending.signingPublicKeyHex,1568          wsPort: pending.wsPort,1569          pairedAt: pending.pairedAt,1570          trustSource: "vouched",1571        });1572        await removePendingVouchedDevice(deviceId);1573        // Newly confirmed vouched device is now a sync target — kick a round1574        // so the mesh introduction pays off without a 10-minute wait.1575        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1576        return { ok: true };1577      }1578      case "REJECT_VOUCHED_DEVICE": {1579        const { deviceId } = msg.payload as { deviceId: string };1580        await removePendingVouchedDevice(deviceId);1581        return { ok: true };1582      }1583      case "ROTATE_SYNC_IDENTITY": {1584        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1585        const result = await vault.rotateSyncIdentity();1586        return result.ok ? { ok: true } : { ok: false, error: result.error };1587      }15881589      default:1590        return { ok: false, error: "unknown_message_type" };1591    }1592  } catch (err) {1593    return {1594      ok: false,1595      error: err instanceof Error ? err.message : "operation_failed",1596    };1597  }1598}15991600// --- Mobile platform helpers ---16011602// Android: populates the in-memory vault used by PeachAutofillService.1603async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1604  const plugin = nativePlugin<{1605    setEntries?: (args: {1606      entries: Array<{1607        id: string;1608        title: string;1609        username: string;1610        email: string;1611        password: string;1612        url: string;1613        totp: string;1614        additionalUrls: string[];1615      }>;1616    }) => Promise<void>;1617  }>("InMemoryVaultPlugin");1618  if (!plugin?.setEntries) return;1619  await plugin.setEntries({1620    entries: entries.map((e) => ({1621      id: e.id,1622      title: e.title ?? "",1623      username: e.username ?? "",1624      email: (e as VaultEntry & { email?: string }).email ?? "",1625      password: e.password ?? "",1626      url: e.url ?? "",1627      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1628      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1629    })),1630  });1631}16321633// Android: clear the autofill in-memory store on lock.1634async function clearInMemoryVault(): Promise<void> {1635  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1636  if (!plugin?.clearEntries) return;1637  await plugin.clearEntries();1638}16391640// Returns username use-counts from the vault, sorted by frequency. Each row1641// also carries the entry's email so the popup can suggest the email/username1642// pair the user has actually used together.1643function buildIdentitySuggestions(1644  entries: VaultEntry[],1645): Array<{ email: string; username: string; count: number }> {1646  const usernameCounts = new Map<string, number>();1647  const usernameEmail = new Map<string, string>();1648  for (const entry of entries) {1649    const username = entry.username ?? "";1650    const email = (entry as VaultEntry & { email?: string }).email ?? "";1651    if (!username && !email) continue;1652    const key = username || email;1653    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1654    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1655  }1656  return Array.from(usernameCounts.entries())1657    .sort((a, b) => b[1] - a[1])1658    .map(([username, count]) => ({1659      email: usernameEmail.get(username) ?? "",1660      username,1661      count,1662    }));1663}16641665/** Notify all content scripts that the vault just became available. */1666function broadcastToContentScripts(message: { type: string }): void {1667  if (!chrome.tabs?.query) return;1668  chrome.tabs.query({}, (tabs) => {1669    for (const tab of tabs) {1670      if (tab.id !== undefined) {1671        chrome.tabs.sendMessage(tab.id, message).catch(() => {1672          // Tab may not have a content script — silently ignore1673        });1674      }1675    }1676  });1677}16781679function shouldRefreshAutoLock(type: MessageType): boolean {1680  return (1681    type !== "HAS_VAULT" &&1682    type !== "IS_UNLOCKED" &&1683    type !== "GET_VAULT_STATUS" &&1684    type !== "LOCK" &&1685    type !== "UPDATE_SETTINGS" &&1686    type !== "GET_PENDING_PASSKEY" &&1687    type !== "GET_PASSKEY_PROVIDER_STATE" &&1688    type !== "DECLINE_CARD_SAVE" &&1689    type !== "IS_CARD_DECLINED"1690  );1691}16921693function isAllowedCanaryWebhookUrl(value: string): boolean {1694  try {1695    const url = new URL(value);1696    if (url.protocol !== "https:") return false;16971698    const hostname = url.hostname.toLowerCase();1699    if (1700      hostname === "localhost" ||1701      hostname.endsWith(".localhost") ||1702      isPrivateIpv4(hostname) ||1703      isPrivateIpv6(hostname)1704    ) {1705      return false;1706    }17071708    return true;1709  } catch {1710    return false;1711  }1712}17131714function isPrivateIpv4(hostname: string): boolean {1715  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1716    return true;1717  }17181719  const octets = hostname.split(".").map((part) => Number(part));1720  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1721    return false;1722  }17231724  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1725}17261727function isPrivateIpv6(hostname: string): boolean {1728  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1729  return (1730    normalized === "::1" ||1731    normalized.startsWith("fc") ||1732    normalized.startsWith("fd") ||1733    normalized.startsWith("fe80:")1734  );1735}