messages.ts

97.4 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 { dismissPendingSyncAlerts, getPendingSyncAlerts } from "./sync-alerts";14import { extractDomain } from "../shared/domain";15import {16  getPendingVouchedDevice,17  listPendingVouchedDevices,18  removePendingVouchedDevice,19} from "./pending-vouched-devices";20import {21  clearRecoveryConfirmPending,22  consumeRecoveryReveal,23  isRecoveryConfirmPending,24  setRecoveryConfirmPending,25} from "./recovery-pending";26import { setupAutoLock, touchAutoLock } from "./alarms";27import { runSelfTest } from "./self-test";28import * as vault from "./vault";29import {30  handleEstimateCodexPages,31  handleGetCodexVaultData,32  handleRestoreFromCodex,33} from "./codex-handlers";34import type { CodexRestorePayload } from "../shared/codex-types";35import {36  activateLicense,37  deactivateLicense,38  getLicenseInfo,39  getLicenseKey,40  isProUser,41  markCelebrationPlayed,42  shouldPlayCelebration,43} from "./license";44import {45  completeFirefoxPasskeyCreate,46  getPasskeyProviderState,47  getPendingPasskeyRequest,48  handleFirefoxPasskeyCreate,49  handleFirefoxPasskeyGet,50  handlePasskeyHasCredentials,51  initiateFirefoxPasskeyCreate,52  isPasskeyOfferDeclined,53  onVaultUnlocked,54  recordPasskeyOfferDecline,55  resolvePendingPasskeyRequest,56  setPasskeyProviderEnabled,57} from "./passkey";58import { buildAdvancedHealthReport } from "./health";59import { storageClear } from "../shared/storage";60import { findInvalidWords } from "../shared/recovery-words";61import type {62  Message,63  MessageResponse,64  MessageType,65  ProFeature,66  VaultEntry,67} from "../shared/types";68import { isPasskeyOnly } from "../shared/types";69import { generateTOTP } from "../crypto/totp";70import { isValidRpId } from "../shared/passkey-utils";71import { isValidMLFeatureBatch, predictBatch as mlPredictBatch } from "./ml";72import {73  buildLocalIdentity,74  getExistingDeviceId,75  setDeviceName as setDeviceNameV3,76  type LocalDeviceIdentity,77} from "./device-identity";78import { clearLockedSyncPrivateKey } from "./locked-sync-spool";79import {80  isDeviceRevoked,81  listPairedDevices as listPairedDevicesV3,82  renamePairedDevice as renamePairedDeviceV3,83  revokeDeviceById as revokeDeviceByIdV3,84  TrustDataCorruptedError,85  upsertPairedDevice as upsertPairedDeviceV3,86} from "./paired-devices";87import { dropPairSecret } from "./pair-secrets";88// Sync and pairing are imported statically, never with `await import()`.89// `import()` throws `TypeError: import() is disallowed on90// ServiceWorkerGlobalScope` at runtime in MV3, and Vite's preload helper91// reports the failure through `window.dispatchEvent`, which does not exist in92// a worker either — so the real reason was replaced by "window is not defined"93// and the pairing UI just stopped. scripts/check-sw-static-imports.mjs fails94// the build if a runtime import() reappears anywhere in the worker's graph.95import {96  cancelRelayAdoptionSource,97  isRelayAdoptionSourceInFlight,98  resolveReceiverSasConfirmation,99  resolveSourceSasConfirmation,100  startRelayAdoptionReceiver,101  startRelayAdoptionSource,102} from "./relay-adoption-bg";103import {104  listPendingAdoptionHolders,105  removePendingAdoptionHolder,106} from "./pending-adoption-holder";107import {108  getSyncSettings,109  setRelayUrl,110  setSyncMode,111  type SyncMode,112} from "./sync-settings";113import {114  getSyncState,115  triggerSyncIfReachable,116} from "./sync-trigger";117import {118  browserGenerationIo,119  confirmSecureReset,120  resolveGeneration,121} from "./sync-generation";122import { isMessageSenderAllowed } from "./message-policy";123124const SUMMON_CAPABILITY_TTL_MS = 30_000;125type SummonCapability = { tabId: number; frameId: number; origin: string; operation: "inventory" | "fill"; expiresAt: number };126const summonCapabilities = new Map<string, SummonCapability>();127128export function createSummonCapability(tabId: number, origin: string, frameId = 0): string {129  const token = crypto.randomUUID();130  summonCapabilities.set(token, { tabId, frameId, origin, operation: "inventory", expiresAt: Date.now() + SUMMON_CAPABILITY_TTL_MS });131  return token;132}133134function consumeSummonCapability(token: unknown, sender: Partial<chrome.runtime.MessageSender>, operation: "inventory" | "fill"): boolean {135  if (typeof token !== "string") return false;136  const cap = summonCapabilities.get(token);137  if (!cap) return false;138  if (cap.expiresAt <= Date.now()) {139    summonCapabilities.delete(token);140    return false;141  }142  if (sender.tab?.id !== cap.tabId || (sender.frameId ?? 0) !== cap.frameId || attestedSenderOrigin(sender) !== cap.origin) return false;143  if (cap.operation !== operation) return false;144  if (operation === "inventory") cap.operation = "fill";145  else summonCapabilities.delete(token);146  return true;147}148149// Compile-time E2E flag, folded to a literal by Vite's `define` (false in150// every production build — verified in the bundled output). Mirrors the151// create-path bypass in passkey.ts so the Playwright passkey smoke can enable152// the provider without a real Pro licence; the gate is fully intact for users.153declare const __PEACH_E2E_PASSKEYS__: boolean;154const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true;155156function unhexBytes(hex: string): Uint8Array {157  if (hex.length % 2 !== 0) throw new Error("invalid hex");158  const out = new Uint8Array(hex.length / 2);159  for (let i = 0; i < out.length; i++) {160    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);161  }162  return out;163}164165/**166 * The single Pro gate. Every gated handler calls this first; the broadcast167 * lets the popup react (navigate to the License section, highlight the168 * relevant feature). Background never touches the popup view directly —169 * the popup owns navigation. See Projects.md "Pro gate rule".170 */171async function requirePro(172  feature: ProFeature,173  trigger: "user" | "background" = "user"174): Promise<{ allowed: boolean }> {175  if (PASSKEY_E2E_PRO_BYPASS && feature === "passkeys") return { allowed: true };176  if (await isProUser()) return { allowed: true };177178  if (trigger === "user") {179    // User deliberately triggered this feature — redirect the popup immediately.180    chrome.runtime181      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })182      .catch(() => {183        // Popup may be closed — the gate signal is best-effort.184      });185  } else {186    // Background trigger (e.g. passive sync initiation) — no popup is open.187    // Queue a notice so the next popup open shows a soft banner instead of188    // silently failing.189    if (chrome.storage.session) {190      chrome.storage.session191        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })192        .catch(() => {});193    }194  }195196  return { allowed: false };197}198199// LV-3: minimum interval between non-test canary pings per webhook+entry.200const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour201202type CanaryTrigger = "accessed" | "password_copied" | "username_copied" | "autofilled" | "submitted";203const canaryClaims = new Map<string, { at: number; dispatched: boolean; result: Promise<MessageResponse> }>();204205function fireStoredCanary(entry: VaultEntry, trigger: CanaryTrigger): Promise<MessageResponse> {206  if (!entry.canary) return Promise.resolve({ ok: true });207  const canary = entry.canary;208  const webhookUrl = canaryWebhookUrl(canary.webhookUrl);209  if (!webhookUrl) return Promise.resolve({ ok: false, error: "invalid_webhook_url" });210  const epoch = vault.getVaultEpoch();211  const now = Date.now();212  const identity = JSON.stringify([entry.id, webhookUrl]);213  const key = `${epoch}:${identity}`;214  for (const [existingKey, claim] of canaryClaims) {215    if (!existingKey.startsWith(`${epoch}:`) || claim.at > now || now - claim.at >= CANARY_MIN_INTERVAL_MS) canaryClaims.delete(existingKey);216  }217  const prior = canaryClaims.get(key);218  // A dispatched alert stays rate-limited even when its counter write failed.219  if (prior) return prior.result.then(result => result.ok || prior.dispatched ? { ok: true, data: { rateLimited: true } } : result);220  const current = () => vault.isUnlocked() && epoch === vault.getVaultEpoch();221  const unchanged = () => current() && vault.getEntryById(entry.id) === entry;222  // Publish the claim before hashing or storage can yield to another request.223  const result: Promise<MessageResponse> = Promise.resolve().then(async (): Promise<MessageResponse> => {224    const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(identity)));225    const suffix = Array.from(digest, byte => byte.toString(16).padStart(2, "0")).join("");226    const rateKey = `canary-last-fetch:${suffix}`;227    const stored = await chrome.storage.local.get(rateKey);228    if (!unchanged()) return { ok: false, error: current() ? "entry_changed" : "vault_locked" };229    const last = stored[rateKey];230    if (typeof last === "number" && Number.isFinite(last) && last <= now && now - last < CANARY_MIN_INTERVAL_MS) {231      const claim = canaryClaims.get(key);232      if (claim) claim.at = last;233      return { ok: true, data: { rateLimited: true } };234    }235    await chrome.storage.local.remove(`canary-last-fetch:${canary.webhookUrl}:${entry.title}`);236    if (!unchanged()) return { ok: false, error: current() ? "entry_changed" : "vault_locked" };237    // Alerts must not hold credential release hostage to webhook response time.238    claim.dispatched = true;239    try {240      void fetch(webhookUrl, { method: "POST", headers: { "Content-Type": "application/json" },241        body: canaryBody(entry.title, trigger), redirect: "error" })242        .catch(() => console.warn("[Peach] canary alert request failed"));243    } catch { console.warn("[Peach] canary alert request failed"); }244    let rateWriteFailed = false;245    try { await chrome.storage.local.set({ [rateKey]: now }); }246    catch { rateWriteFailed = true; }247    if (!current()) return { ok: false, error: "vault_locked" };248    const latestCanary = vault.getEntryById(entry.id)?.canary;249    if (!latestCanary || canaryWebhookUrl(latestCanary.webhookUrl) !== webhookUrl) return { ok: false, error: "entry_changed" };250    const pingCount = (latestCanary.pingCount ?? 0) + 1;251    await vault.updateEntry(entry.id, { canary: { ...latestCanary, lastPinged: now, pingCount } });252    if (!current()) return { ok: false, error: "vault_locked" };253    const latest = vault.getEntryById(entry.id);254    if (!latest?.canary || canaryWebhookUrl(latest.canary.webhookUrl) !== webhookUrl ||255      latest.canary.pingCount !== pingCount || latest.canary.lastPinged !== now) return { ok: false, error: "entry_changed" };256    return rateWriteFailed ? { ok: false, error: "canary_update_failed" } : { ok: true };257  }).catch((): MessageResponse => ({ ok: false, error: current() ? "canary_update_failed" : "vault_locked" }));258  const claim = { at: now, dispatched: false, result };259  canaryClaims.set(key, claim);260  void result.then(reply => { if (!reply.ok && !claim.dispatched) canaryClaims.delete(key); });261  return result;262}263264function canaryBody(entryTitle: string, trigger: CanaryTrigger | "test"): string {265  return JSON.stringify({ event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed", entry: entryTitle,266    trigger, timestamp: new Date().toISOString(), source: "peach-extension" });267}268269export function setupMessageHandler(): void {270  chrome.runtime.onMessage.addListener(271    (msg: unknown, sender, sendResponse) => {272      if (!isMessage(msg)) {273        sendResponse({ ok: false, error: "invalid_message" });274        return true;275      }276      handleMessage(msg, sender)277        .then(sendResponse)278        .catch((err) =>279          sendResponse({280            ok: false,281            error: err instanceof Error ? err.message : String(err),282          })283        );284      return true;285    }286  );287}288289function isMessage(m: unknown): m is Message {290  return typeof m === "object" && m !== null && "type" in m;291}292293/**294 * The browser-attested origin of the page that originated this message. A web295 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),296 * so every page-driven message arrives via the content-script relay and the297 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a298 * value the page cannot forge. This is the ONLY trustworthy origin for passkey299 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.300 */301function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {302  if (sender.origin) return sender.origin;303  if (sender.url) {304    try { return new URL(sender.url).origin; } catch { return undefined; }305  }306  return undefined;307}308309function isExtensionPageSender(sender: Partial<chrome.runtime.MessageSender>): boolean {310  return sender.url?.startsWith("chrome-extension://") === true ||311    sender.url?.startsWith("moz-extension://") === true;312}313314/** True when the message came from a page frame rather than extension UI. */315function isPageSender(sender: Partial<chrome.runtime.MessageSender>): boolean {316  return !isExtensionPageSender(sender) &&317    (sender.tab !== undefined || sender.url !== undefined);318}319320function entryDomains(url: unknown, additionalUrls: unknown): Set<string> {321  const domains = new Set<string>();322  const primary = typeof url === "string" ? extractDomain(url) : null;323  if (primary) domains.add(primary);324  if (Array.isArray(additionalUrls)) {325    for (const extra of additionalUrls) {326      if (typeof extra !== "string") continue;327      const domain = extractDomain(extra);328      if (domain) domains.add(domain);329    }330  }331  return domains;332}333334const CONTENT_LOGIN_TEXT_FIELDS = new Set(["title", "username", "email", "password", "url"]);335336function normalizeContentEntryUrl(value: string): string | null {337  try {338    const trimmed = value.trim();339    const url = new URL(trimmed);340    if ((url.protocol === "https:" || url.protocol === "http:") && extractDomain(url.href)) {341      // Origin-only saves must keep matching existing duplicate keys.342      return url.pathname === "/" && !url.search && !url.hash && url.href.endsWith("/") && !trimmed.endsWith("/")343        ? url.href.slice(0, -1)344        : url.href;345    }346    return null;347  } catch {348    return null;349  }350}351352function parseContentLoginWrite(353  fields: object,354  operation: "create" | "update",355): { ok: true; fields: Record<string, unknown> } | { ok: false; error: "invalid_payload" | "origin_binding_required" } {356  const normalized: Record<string, unknown> = {};357  for (const [key, value] of Object.entries(fields)) {358    if (key === "type") {359      if (operation !== "create" || value !== "login") return { ok: false, error: "invalid_payload" };360    } else if (key === "additionalUrls") {361      if (!Array.isArray(value)) return { ok: false, error: "invalid_payload" };362      const urls: string[] = [];363      for (const extra of value) {364        if (typeof extra !== "string") return { ok: false, error: "invalid_payload" };365        const url = normalizeContentEntryUrl(extra);366        if (!url) return { ok: false, error: "origin_binding_required" };367        urls.push(url);368      }369      normalized.additionalUrls = urls;370      continue;371    } else if (!CONTENT_LOGIN_TEXT_FIELDS.has(key) ||372      (typeof value !== "string" && !(key === "email" && value === undefined))) {373      return { ok: false, error: "invalid_payload" };374    }375    if (key === "url") {376      const url = normalizeContentEntryUrl(value as string);377      if (!url) return { ok: false, error: "origin_binding_required" };378      normalized.url = url;379    } else normalized[key] = value;380  }381  if (operation === "create") {382    if (typeof normalized.title !== "string") return { ok: false, error: "invalid_payload" };383    if (typeof normalized.url !== "string") return { ok: false, error: "origin_binding_required" };384  }385  return { ok: true, fields: normalized };386}387388/**389 * PB-26-106: the autofill read path re-validates the frame origin against the390 * entry's domains on every request, so an unbound write path would let a391 * content script repoint an entry at its own origin and then read the392 * credential through a read path that is behaving correctly.393 *394 * Creating an entry: a page may only bind it to itself. Mutating one: a page395 * may never GROW the domain set — only shrink it, and never below its own396 * attested origin.397 *398 * Self-binding on mutation was considered and is not enough: the content399 * script on a foreign origin IS the attacker in the reported chain, so letting400 * it attach "its own" origin lets it mint the very capability the read path401 * exists to withhold. The legitimate flow that needs a new domain — the inline402 * "remember this site" toast — therefore asks the popup instead403 * (REQUEST_REMEMBER_SITE), which is an extension page and exempt here.404 *405 * Extension pages are exempt: the popup edits entries for sites it is not on.406 */407function senderMayBindEntryDomains(408  sender: Partial<chrome.runtime.MessageSender>,409  domains: Set<string>,410): boolean {411  if (isExtensionPageSender(sender)) return true;412  const domain = attestedSenderDomain(sender);413  if (domain === null) return false;414  for (const candidate of domains) {415    if (candidate !== domain) return false;416  }417  return true;418}419420function senderMayMutateEntryDomains(421  sender: Partial<chrome.runtime.MessageSender>,422  before: Set<string>,423  after: Set<string>,424): boolean {425  if (isExtensionPageSender(sender)) return true;426  const domain = attestedSenderDomain(sender);427  if (domain === null || !after.has(domain)) return false;428  for (const kept of after) {429    if (!before.has(kept)) return false;430  }431  return true;432}433434/**435 * Null for extension pages (which the callers exempt), for senders with no436 * attested origin at all, and for unparseable frame urls.437 */438function attestedSenderDomain(sender: Partial<chrome.runtime.MessageSender>): string | null {439  if (sender.tab === undefined && sender.url === undefined) return null;440  const origin = attestedSenderOrigin(sender);441  if (!origin) return null;442  try { return extractDomain(new URL(origin).hostname); } catch { return null; }443}444445function patchChangesEntryOrigin(patch: object): boolean {446  return Object.hasOwn(patch, "url") || Object.hasOwn(patch, "additionalUrls");447}448449/** The entry's domain-bearing fields as the patch would leave them. */450function patchedUrlShape(451  patch: object,452  existing: Pick<VaultEntry, "url" | "additionalUrls">,453): { url: unknown; additionalUrls: unknown } {454  const candidate = patch as { url?: unknown; additionalUrls?: unknown };455  return {456    url: Object.hasOwn(patch, "url") ? candidate.url : existing.url,457    additionalUrls: Object.hasOwn(patch, "additionalUrls")458      ? candidate.additionalUrls459      : existing.additionalUrls,460  };461}462// Resolves once restoreFromSession() has run, so handlers see the correct463// post-restore unlock state. entry.ts registers this BEFORE the message464// handler so the onMessage listener is added synchronously at SW startup465// (MV3 requirement) while unlock-dependent handlers still wait for restore.466let restoreReady: Promise<void> = Promise.resolve();467const MAX_ML_BATCH_FIELDS = 128;468const MAX_ML_FIELDS_PER_SECOND = 256;469const mlWorkBySender = new Map<string, { startedAt: number; fields: number }>();470471function claimMLWork(sender: Partial<chrome.runtime.MessageSender>, fields: number): boolean {472  if (fields === 0) return true;473  const now = Date.now();474  for (const [key, value] of mlWorkBySender) {475    if (now - value.startedAt >= 1_000) mlWorkBySender.delete(key);476  }477  const key = `${sender.tab?.id ?? "ui"}:${sender.frameId ?? 0}:${attestedSenderOrigin(sender) ?? "extension"}`;478  const current = mlWorkBySender.get(key);479  if (!current) {480    mlWorkBySender.set(key, { startedAt: now, fields });481    return fields <= MAX_ML_FIELDS_PER_SECOND;482  }483  if (current.fields + fields > MAX_ML_FIELDS_PER_SECOND) return false;484  current.fields += fields;485  return true;486}487488/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */489export function setRestoreReady(p: Promise<unknown>): void {490  restoreReady = p.then(() => undefined, () => undefined);491}492493export async function handleMessage(494  msg: Message,495  sender: Partial<chrome.runtime.MessageSender> = {}496): Promise<MessageResponse> {497  try {498    // Wait for session-restore to finish before reading any unlock/vault state.499    // On a cold SW start the popup's first message arrives while restore is500    // still in flight; without this gate IS_UNLOCKED would report locked (a501    // spurious lock screen) and the storage reads could race. The onMessage502    // listener itself is registered synchronously (entry.ts) so this gate, not503    // listener registration, is what absorbs the cold-start window.504    await restoreReady;505    // Validate sender — only allow messages from our extension pages/scripts.506    // `sender.id` is undefined for messages originating from extension UI507    // (popup/options), which is legitimate; reject only when it is defined508    // and does not match our extension id.509    if (510      sender.id !== undefined &&511      sender.id !== chrome.runtime.id512    ) {513      return { ok: false, error: "invalid_sender" };514    }515516    // PB-26-016: sender authorization is an exhaustive policy, not a517    // hand-maintained privileged denylist. A missing/unknown policy entry or a518    // background-only message fails closed before any handler runs.519    // Extension UI messages may legitimately omit sender.url. Resolve the520    // browser-attested extension origin only when a URL is present; this also521    // keeps test/runtime shims without getURL fail-closed for URL-bearing522    // senders instead of throwing before policy evaluation.523    const extensionOrigin = sender.url && typeof chrome.runtime.getURL === "function"524      ? chrome.runtime.getURL("")525      : "";526    if (!isMessageSenderAllowed(msg.type, sender, chrome.runtime.id, extensionOrigin)) {527      return { ok: false, error: "invalid_sender" };528    }529530    if (shouldRefreshAutoLock(msg.type, sender) && vault.isUnlocked()) {531      touchAutoLock();532    }533534    switch (msg.type) {535      case "CREATE_VAULT": {536        const { password, replacement, purpose } = (msg.payload ?? {}) as { password?: unknown; replacement?: unknown; purpose?: unknown };537        // Refuse to create a vault under an empty master password — the derived538        // key would be publicly known and the at-rest AES-GCM protection void539        // (audit HIGH; the CSV-import path previously passed ""). Length/strength540        // policy lives in the onboarding UI; this is the non-negotiable floor.541        if (typeof password !== "string" || password.length === 0 || (replacement !== undefined && replacement !== "warned-import") ||542          (purpose !== undefined && purpose !== "onboarding") || (purpose === "onboarding" && replacement !== undefined)) {543          return { ok: false, error: "invalid_payload" };544        }545        const created = await vault.createVault(password, replacement);546        if (purpose === "onboarding") await setRecoveryConfirmPending(created.unlocked && vault.isUnlocked());547        if (!created.unlocked) return { ok: true, data: created };548        try {549          await setupAutoLock();550          const unlocked = vault.isUnlocked();551          if (unlocked) {552            broadcastToContentScripts({ type: "VAULT_UNLOCKED" });553            onVaultUnlocked();554          }555          return { ok: true, data: { ...created, unlocked } };556        } catch (error) {557          console.warn("[Peach] vault saved; unlock setup failed:", error);558          await vault.lock().catch((lockError) => console.warn("[Peach] creation cleanup failed:", lockError));559          return { ok: true, data: { ...created, unlocked: false } };560        }561      }562      case "CREATE_VAULT_FROM_ROOT_KEY": {563        const { password, rootKeyHex } = (msg.payload ?? {}) as {564          password?: unknown;565          rootKeyHex?: unknown;566        };567        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {568          return { ok: false, error: "invalid_payload" };569        }570571        try {572          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);573          await setupAutoLock();574          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });575          onVaultUnlocked();576          return { ok: true, vaultId };577        } catch (err) {578          return { ok: false, error: err instanceof Error ? err.message : String(err) };579        }580      }581      case "UNLOCK": {582        const { password } = msg.payload as { password: string };583        const ok = await vault.unlock(password);584        if (ok) {585          // KAT: verify the WebCrypto stack is healthy before the user relies on it.586          // Runs after unlock so latency is hidden behind the vault-load time.587          const kat = await runSelfTest();588          if (!kat.ok) {589            console.error("[Peach] Crypto self-test FAILED:", kat.error);590            await vault.lock();591            return { ok: false, error: "self_test_failed" };592          }593          await vault.updateSettings({ pinPreferred: false });594          await setupAutoLock();595          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });596          onVaultUnlocked();597          return { ok: true };598        }599        // Distinguish corruption from wrong password so the popup can offer600        // a history-restore path instead of falsely accusing the user of601        // mistyping (M7/COR-007).602        const failure = vault.consumeLastUnlockFailureReason();603        if (failure) {604          return {605            ok: false,606            error: "vault_corrupted",607            canRestoreFromHistory: true,608          } as MessageResponse;609        }610        return { ok: false };611      }612      case "UNLOCK_WITH_PIN": {613        const { pin } = (msg.payload ?? {}) as { pin?: unknown };614        if (typeof pin !== "string") return { ok: false, error: "invalid_payload" };615        const ok = await vault.unlockWithPin(pin);616        if (!ok) {617          const status = await vault.getPinUnlockStatus();618          if (status.configured && !status.available) {619            return {620              ok: false,621              error: status.attemptsRemaining === 0622                ? "pin_attempts_exceeded"623                : "pin_session_expired",624            };625          }626          return { ok: false };627        }628        const kat = await runSelfTest();629        if (!kat.ok) {630          await vault.lock();631          return { ok: false, error: "self_test_failed" };632        }633        await vault.updateSettings({ pinPreferred: true });634        await setupAutoLock();635        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });636        onVaultUnlocked();637        return { ok: true };638      }639      case "GET_PIN_STATUS":640        return { ok: true, data: await vault.getPinUnlockStatus() };641      case "VALIDATE_RECOVERY_WORDS": {642        const { words } = msg.payload as { words: string[] };643        const invalid = findInvalidWords(words);644        return { ok: true, data: { valid: invalid.length === 0, invalid } };645      }646      case "GET_RECOVERY_WORDS": {647        // Must be unlocked and have recovery set up (vault must be v2.12+).648        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };649        const epoch = vault.getVaultEpoch();650        const current = () => vault.isUnlocked() && epoch === vault.getVaultEpoch();651        const exempt = await consumeRecoveryReveal();652        if (!current()) return { ok: false, error: "vault_locked" };653        if (!exempt) {654          const { password } = (msg.payload ?? {}) as { password?: string };655          if (typeof password !== "string" || !password) {656            return { ok: false, error: "password_required" };657          }658          const verified = await vault.verifyMainPassword(password);659          if (!current()) return { ok: false, error: "vault_locked" };660          if (!verified) {661            return { ok: false, error: "wrong_password" };662          }663        }664        try {665          const words = await vault.getRecoveryWords();666          if (!current()) return { ok: false, error: "vault_locked" };667          return { ok: true, data: words };668        } catch {669          return { ok: false, error: "recovery_not_setup" };670        }671      }672      case "GET_RECOVERY_CONFIRM_PENDING":673        return { ok: true, data: await isRecoveryConfirmPending() };674      case "CLEAR_RECOVERY_CONFIRM_PENDING":675        await clearRecoveryConfirmPending();676        if (vault.isUnlocked()) touchAutoLock();677        return { ok: true };678      case "RECOVER_WITH_WORDS": {679        // User has lost their password but has their 12 recovery words.680        // We: (1) validate the words, (2) re-encrypt vault with new password.681        if (!msg.payload || typeof msg.payload !== "object" || Array.isArray(msg.payload)) {682          return { ok: false, error: "invalid_recovery_payload" };683        }684        const { words, newPassword } = msg.payload as {685          words: string[];686          newPassword: string;687        };688        if (!Array.isArray(words) || words.some((word) => typeof word !== "string") || typeof newPassword !== "string") {689          return { ok: false, error: "invalid_recovery_payload" };690        }691        const recovered = await vault.recoverWithWords(words, newPassword);692        if (recovered.unlocked) {693          try { await setupAutoLock(); }694          catch (error) {695            console.warn("[Peach] recovery password saved; auto-lock setup failed:", error);696            try { await vault.lock(); }697            catch (lockError) { console.warn("[Peach] recovery session cleanup failed:", lockError); }698          }699        }700        const unlocked = recovered.unlocked && vault.isUnlocked();701        if (unlocked) broadcastToContentScripts({ type: "VAULT_UNLOCKED" });702        return { ok: true, data: { ...recovered, unlocked } };703      }704      case "LOCK":705        await vault.lock();706        return { ok: true };707      case "IS_UNLOCKED":708        return { ok: true, data: vault.isUnlocked() };709      case "GET_VAULT_STATUS":710        return { ok: true, unlocked: vault.isUnlocked() };711      case "HAS_VAULT":712        return { ok: true, data: await vault.hasVault() };713      case "GET_ENTRIES":714        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };715        return { ok: true, data: vault.getEntries() };716      case "EXPORT_ENTRIES": {717        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };718        const { password } = (msg.payload ?? {}) as { password?: unknown };719        if (typeof password !== "string" || !password) {720          return { ok: false, error: "password_required" };721        }722        if (!(await vault.verifyMainPassword(password))) {723          return { ok: false, error: "wrong_password" };724        }725        return { ok: true, data: vault.getEntries() };726      }727      case "ADD_ENTRY": {728        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };729        let payload = msg.payload;730        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {731          return { ok: false, error: "invalid_payload" };732        }733        if (isPageSender(sender)) {734          const parsed = parseContentLoginWrite(payload, "create");735          if (!parsed.ok) return parsed;736          payload = parsed.fields;737          const domains = entryDomains(parsed.fields.url, parsed.fields.additionalUrls);738          if (domains.size === 0 || !senderMayBindEntryDomains(sender, domains)) {739            return { ok: false, error: "origin_binding_required" };740          }741        }742        if (isExtensionPageSender(sender)) {743          const canary = (payload as { canary?: unknown }).canary;744          if (canary !== undefined) {745            if (!canary || typeof canary !== "object" || !canaryWebhookUrl((canary as { webhookUrl?: unknown }).webhookUrl)) return { ok: false, error: "invalid_webhook_url" };746            payload = { ...(payload as object), canary: { ...canary, lastPinged: undefined, pingCount: undefined } };747          }748        }749        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);750        return { ok: true, data: entry };751      }752      case "BATCH_ADD_ENTRIES": {753        const payload = msg.payload as { entries?: unknown } | null | undefined;754        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {755          return { ok: false, error: "invalid_payload" };756        }757        if (!Array.isArray(payload.entries)) {758          return { ok: false, error: "invalid_payload" };759        }760        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);761        return { ok: true, data: added };762      }763      case "RESTORE_ENTRIES": {764        const payload = msg.payload as765          | { entries?: unknown; mode?: unknown; settings?: unknown }766          | null767          | undefined;768        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {769          return { ok: false, error: "invalid_payload" };770        }771        if (!Array.isArray(payload.entries)) {772          return { ok: false, error: "invalid_payload" };773        }774        if (payload.mode !== "replace" && payload.mode !== "merge") {775          return { ok: false, error: "invalid_payload" };776        }777        const summary = await vault.restoreEntries(778          payload.entries as Parameters<typeof vault.restoreEntries>[0],779          payload.mode780        );781        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {782          await vault.updateSettings(payload.settings as vault.VaultSettings);783        }784        return { ok: true, data: summary };785      }786      case "CLEAR_VAULT_ENTRIES": {787        await vault.clearVaultEntries("REPLACE_ALL");788        return { ok: true };789      }790      case "GET_VAULT_HISTORY": {791        // The history store is real-mode state by construction, so a decoy792        // session must not see it — this is where the duress session would793        // otherwise leak the real vault's activity and size (PB-26-915).794        if (vault.isDecoyMode()) return { ok: true, data: [] };795        const snapshots = await vault.getVaultHistory();796        return { ok: true, data: snapshots };797      }798      case "RESTORE_VAULT_SNAPSHOT": {799        // Same guard on the write side: a coerced session must not be able to800        // roll the real vault backwards onto an earlier snapshot.801        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };802        const { snapshotId } = msg.payload as { snapshotId: string };803        const result = await vault.restoreVaultSnapshot(snapshotId);804        if (!result.ok) return { ok: false, error: result.error };805        broadcastToContentScripts({ type: "VAULT_LOCKED" });806        return { ok: true };807      }808      case "COUNT_DUPLICATES": {809        return { ok: true, data: vault.countDuplicates() };810      }811      case "DEDUPLICATE_ENTRIES": {812        const removed = await vault.deduplicateEntries();813        return { ok: true, data: removed };814      }815      case "UPDATE_ENTRY": {816        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;817        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {818          return { ok: false, error: "invalid_payload" };819        }820        const { id, patch: inputPatch } = payload;821        if (typeof id !== "string" || !id || !inputPatch || typeof inputPatch !== "object" || Array.isArray(inputPatch)) {822          return { ok: false, error: "invalid_payload" };823        }824        let patch: object = inputPatch;825        const existingEntry = vault.getEntryById(id);826        if (!existingEntry) return { ok: false, error: "entry_not_found" };827        if (isPageSender(sender)) {828          if ((existingEntry.type ?? "login") !== "login") return { ok: false, error: "login_entries_only" };829          const parsed = parseContentLoginWrite(patch, "update");830          if (!parsed.ok) return parsed;831          patch = parsed.fields;832        }833        if (patchChangesEntryOrigin(patch) || isPageSender(sender)) {834          const before = entryDomains(existingEntry.url, existingEntry.additionalUrls);835          const after = patchedUrlShape(patch, existingEntry);836          if (!senderMayMutateEntryDomains(837            sender,838            before,839            entryDomains(after.url, after.additionalUrls),840          )) {841            return { ok: false, error: "origin_binding_required" };842          }843        }844        // Single enforcement point for the Canary Entries Pro gate. Only845        // gates the transition into a canary entry — clearing/disabling a846        // canary (`canary: undefined`) is always allowed, so existing847        // canary entries remain manageable.848        const incomingCanary = (patch as { canary?: unknown }).canary;849        if (isExtensionPageSender(sender) && incomingCanary !== undefined &&850          (!incomingCanary || typeof incomingCanary !== "object" || !canaryWebhookUrl((incomingCanary as { webhookUrl?: unknown }).webhookUrl))) return { ok: false, error: "invalid_webhook_url" };851        if (incomingCanary && typeof incomingCanary === "object") {852          const existing = vault.getEntryById(id);853          if (!existing?.canary) {854            const gate = await requirePro("canary_entry");855            if (!gate.allowed) return { ok: false, error: "pro_required" };856          }857        }858        if (isExtensionPageSender(sender) && incomingCanary && typeof incomingCanary === "object") {859          const stored = vault.getEntryById(id)?.canary;860          patch = { ...patch, canary: { ...incomingCanary, lastPinged: stored?.lastPinged, pingCount: stored?.pingCount } };861        }862        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);863        return { ok: true };864      }865      case "ADD_ADDITIONAL_URL": {866        const { id, url } = msg.payload as { id: string; url: string };867        const trimmed = typeof url === "string" ? url.trim() : "";868        if (!trimmed) return { ok: false, error: "url_required" };869        const existing = vault.getEntryById(id);870        if (!existing) return { ok: false, error: "entry_not_found" };871        const merged = [...(existing.additionalUrls ?? []), trimmed];872        if (!senderMayMutateEntryDomains(873          sender,874          entryDomains(existing.url, existing.additionalUrls),875          entryDomains(existing.url, merged),876        )) {877          return { ok: false, error: "origin_binding_required" };878        }879        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };880        await vault.updateEntry(id, { additionalUrls: merged });881        return { ok: true };882      }883      case "REQUEST_REMEMBER_SITE": {884        // PB-26-106: growing an entry's domain set needs a decision the page885        // cannot make for itself, so the page asks and the popup confirms. A886        // page may only ask about its own attested origin — otherwise this887        // becomes the same unbound write under a friendlier name.888        const { id, url } = (msg.payload ?? {}) as { id?: unknown; url?: unknown };889        if (typeof id !== "string" || !id) return { ok: false, error: "invalid_payload" };890        const trimmed = typeof url === "string" ? url.trim() : "";891        if (!trimmed) return { ok: false, error: "url_required" };892        if (!senderMayBindEntryDomains(sender, entryDomains(trimmed, undefined))) {893          return { ok: false, error: "origin_binding_required" };894        }895        if (!vault.getEntryById(id)) return { ok: false, error: "entry_not_found" };896        if (chrome.storage.session) {897          await chrome.storage.session.set({ pendingRememberSite: { entryId: id, url: trimmed } });898        }899        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }900        return { ok: true };901      }902      case "DELETE_ENTRY": {903        const { id } = msg.payload as { id: string };904        await vault.deleteEntry(id);905        return { ok: true };906      }907      case "GET_DELETED_ENTRIES":908        return { ok: true, data: vault.getDeletedEntries() };909      case "RESTORE_ENTRY": {910        const { id } = msg.payload as { id: string };911        await vault.restoreEntry(id);912        return { ok: true };913      }914      case "PURGE_ENTRY": {915        const { id } = msg.payload as { id: string };916        await vault.purgeEntry(id);917        return { ok: true };918      }919      case "PURGE_EXPIRED_TRASH": {920        const { retentionMs } = msg.payload as { retentionMs: number };921        const purged = await vault.purgeExpiredTrash(retentionMs);922        return { ok: true, data: purged };923      }924      case "SAVE_NOTE": {925        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };926        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };927        const now = Date.now();928        if (id) {929          const existing = vault.getEntryById(id);930          if (!existing) return { ok: false, error: "not_found" };931          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });932          return { ok: true, data: vault.getEntryById(id) };933        } else {934          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt935          // (EntryDraft omits both), so passing them was the only reason the936          // `as any` cast existed. Dropping them makes the call type-check.937          const entry = await vault.addEntry({938            type: "note",939            title: title || "Untitled",940            notes: body,941          });942          return { ok: true, data: entry };943        }944      }945      case "DELETE_NOTE": {946        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };947        const { id } = msg.payload as { id: string };948        await vault.deleteEntry(id);949        return { ok: true };950      }951      case "GET_NOTES": {952        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };953        const notes = vault.getEntries().filter(954          (e) => e.type === "note" && !e.deletedAt955        );956        return { ok: true, data: notes } as MessageResponse;957      }958      case "SEARCH_VAULT": {959        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };960        // AUD-002: shape-validate the payload before calling string methods.961        // A raw cast lets a malformed message crash the handler with TypeError.962        const { query } = (msg.payload ?? {}) as { query?: unknown };963        if (typeof query !== "string") {964          return { ok: false, error: "invalid_payload" };965        }966        const q = query.toLowerCase();967        const searchResults = vault.getEntries().filter(968          (e) =>969            !e.deletedAt &&970            (e.title.toLowerCase().includes(q) ||971              e.notes?.toLowerCase().includes(q) ||972              e.username?.toLowerCase().includes(q))973        );974        return { ok: true, data: searchResults } as MessageResponse;975      }976      case "CHECK_SAVE_CREDENTIAL": {977        if (!isPageSender(sender) || sender.tab?.id === undefined) return { ok: false, error: "invalid_sender" };978        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };979        const domain = attestedSenderDomain(sender);980        if (!domain) return { ok: false, error: "origin_unverified" };981        const payload = msg.payload;982        if (!payload || typeof payload !== "object" || Array.isArray(payload) ||983          Object.keys(payload).some(key => key !== "username" && key !== "password")) {984          return { ok: false, error: "invalid_payload" };985        }986        const { username, password } = payload as { username?: unknown; password?: unknown };987        if (typeof username !== "string" || typeof password !== "string") return { ok: false, error: "invalid_payload" };988        const identity = username.trim().toLowerCase();989        const matchesIdentity = (entry: VaultEntry) => {990          const names = [entry.username ?? "", entry.email ?? ""].map(name => name.trim().toLowerCase());991          return identity ? names.includes(identity) : names.every(name => !name);992        };993        const isCandidate = (entry: VaultEntry) => !entry.deletedAt &&994          (entry.type === undefined || entry.type === "login") && !isPasskeyOnly(entry) &&995          entryDomains(entry.url, entry.additionalUrls).has(domain);996        const eligible = vault.getEntries().filter(isCandidate);997        const candidates = eligible.filter(matchesIdentity);998        const exact = (identity ? candidates : eligible).filter(entry => entry.password === password);999        if (exact.length) {1000          const epoch = vault.getVaultEpoch();1001          const alerts = await Promise.all(exact.map(entry => fireStoredCanary(entry, "submitted")));1002          if (!vault.isUnlocked() || epoch !== vault.getVaultEpoch()) return { ok: false, error: "vault_locked" };1003          const failed = alerts.find(alert => !alert.ok);1004          if (failed) return failed;1005          if (exact.some(entry => {1006            const current = vault.getEntryById(entry.id);1007            return !current || !isCandidate(current) || (identity && !matchesIdentity(current)) || current.password !== password;1008          })) return { ok: false, error: "entry_changed" };1009          return { ok: true, data: { status: "same" } };1010        }1011        if (candidates.length === 1) return { ok: true, data: { status: "changed", id: candidates[0].id } };1012        return { ok: true, data: { status: candidates.length ? "ambiguous" : "new" } };1013      }1014      case "AUTOFILL_QUERY": {1015        if (!vault.isUnlocked()) {1016          return { ok: false, error: "vault_locked" };1017        }1018        const { domain, kind, capability } = msg.payload as {1019          domain: string;1020          kind?: "login" | "card" | "totp";1021          capability?: string;1022        };1023        const includeAll = consumeSummonCapability(capability, sender, "inventory");1024        if (capability !== undefined && !includeAll) {1025          return { ok: false, error: "entry_not_found" };1026        }1027        // kind="card": return saved cards as compact summaries for the1028        // inline card silver platter. Cards are not domain-scoped — every1029        // saved card is a candidate on every checkout page — so domain is1030        // ignored when kind === "card".1031        if (kind === "card") {1032          if (!includeAll) return { ok: true, data: [] };1033          const cards = vault.getEntries().filter((e) => e.type === "card");1034          return {1035            ok: true,1036            data: cards.map((e) => ({1037              id: e.id,1038              title: e.cardNickname || e.title,1039              cardholderName: e.cardholderName,1040              last4: e.last4,1041              expMonth: e.expMonth,1042              expYear: e.expYear,1043              network: e.network,1044            })),1045          };1046        }1047        const scopedDomain = isPageSender(sender)1048          ? attestedSenderDomain(sender)1049          : typeof domain === "string"1050            ? extractDomain(domain)1051            : null;1052        if (!includeAll && !scopedDomain) {1053          return isPageSender(sender)1054            ? { ok: false, error: "origin_unverified" }1055            : { ok: true, data: [] };1056        }1057        if (kind === "totp") {1058          const matches = (1059            includeAll1060              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")1061              : vault.queryDomain(scopedDomain!)1062          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));1063          return {1064            ok: true,1065            data: matches.map((e) => ({1066              id: e.id,1067              title: e.title,1068              username: e.username,1069              email: e.email,1070              url: e.url,1071              hasTotp: true,1072            })),1073          };1074        }1075        // The inline selector fills username+password into a form. Passkey-1076        // only entries have no password to fill; sign-in for those goes1077        // through the WebAuthn path instead. Filter them out everywhere so1078        // the user doesn't see four "GitHub" rows that mostly do nothing.1079        // Notes and cards never belonged here either.1080        const matches = (1081          includeAll1082            ? vault1083                .getEntries()1084                .filter((entry) => entry.type !== "note" && entry.type !== "card")1085            : vault.queryDomain(scopedDomain!)1086        ).filter((entry) => !isPasskeyOnly(entry));1087        return {1088          ok: true,1089          data: matches.map((e) =>1090            includeAll1091              ? {1092                  id: e.id,1093                  title: e.title,1094                  // username/email/url shipped so the inline popup's search1095                  // affordance can match on them, not just titles. No secrets1096                  // cross the boundary — same shape as the domain-matched1097                  // response below minus hasTotp (which the search list1098                  // doesn't surface).1099                  username: e.username,1100                  email: e.email,1101                  url: e.url,1102                  hasPasskey: e.passkey !== undefined,1103                }1104              : {1105                  id: e.id,1106                  title: e.title,1107                  username: e.username,1108                  email: e.email,1109                  url: e.url,1110                  hasTotp: Boolean(e.totp),1111                  hasPasskey: e.passkey !== undefined,1112                }1113          ),1114        };1115      }1116      case "GET_ENTRY_FOR_FILL": {1117        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1118        const { id, capability } = msg.payload as {1119          id: string;1120          capability?: string;1121        };1122        const capabilityAuthorized = capability !== undefined && consumeSummonCapability(capability, sender, "fill");1123        const senderDomain = isPageSender(sender) ? attestedSenderDomain(sender) : null;1124        if (isPageSender(sender) && !senderDomain) {1125          return { ok: false, error: "origin_unverified" };1126        }1127        let entry = vault.getEntryById(id);1128        if (!entry) return { ok: false, error: "entry_not_found" };11291130        // MV-1: re-validate the entry against the requesting frame's origin.1131        // sender.url / sender.tab.url are browser-attested — a page cannot1132        // forge them. PB-26-005: the FRAME url (sender.url) is authoritative1133        // for an all_frames content script; the top-frame tab.url would1134        // misattribute a cross-origin iframe's request to the top page. When1135        // the request does not come from a tab at all (popup surfaces use1136        // GET_ENTRY_FOR_EDIT, not this), refuse.1137        if (senderDomain && !capabilityAuthorized) {1138          if (!entryDomains(entry.url, entry.additionalUrls).has(senderDomain)) {1139            // Domain mismatch — refuse silently (no oracle about which ids exist).1140            return { ok: false, error: "entry_not_found" };1141          }1142        }1143        // Passkey-only entries (passkey credential, no password) cannot be1144        // filled into a form — sign-in goes through the WebAuthn path. A1145        // login that ALSO has a passkey is still fillable for its password.1146        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };1147        if (entry.canary) {1148          const requestedCanary = entry.canary;1149          const epoch = vault.getVaultEpoch();1150          const alerted = await fireStoredCanary(entry, "accessed");1151          if (!vault.isUnlocked() || epoch !== vault.getVaultEpoch()) return { ok: false, error: "vault_locked" };1152          if (!alerted.ok) return alerted;1153          entry = vault.getEntryById(id);1154          if (!entry || (senderDomain && !capabilityAuthorized && !entryDomains(entry.url, entry.additionalUrls).has(senderDomain))) {1155            return { ok: false, error: "entry_not_found" };1156          }1157          if (canaryWebhookUrl(entry.canary?.webhookUrl) !== canaryWebhookUrl(requestedCanary.webhookUrl)) {1158            return { ok: false, error: "entry_changed" };1159          }1160          if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };1161        }1162        // Strip the passkey credential AND the raw base32 TOTP seed from the1163        // response. Content scripts never need either: the private key is the1164        // authenticator's, and handing over the TOTP seed would let a1165        // compromised content script mint valid codes indefinitely (SEV-3-C).1166        // Generate the *current* 6-digit code here in the background and send1167        // only that, plus the seconds left so the UI can render a countdown.1168        // Also drop passwordHistory: filling needs only the *current* password.1169        // Handing every past password to a content script during passive1170        // autofill on an arbitrary page would widen the blast radius of a1171        // compromised page far beyond the one credential being filled.1172        const {1173          passkey: _strippedPasskey,1174          totp: seed,1175          totpAlgorithm,1176          totpDigits,1177          totpPeriod,1178          passwordHistory: _ph,1179          ...safeEntry1180        } = entry;1181        let totpCode: string | undefined;1182        let totpRemaining: number | undefined;1183        if (seed) {1184          try {1185            // PCH-01-019: honour stored algorithm/digits/period (defaults apply1186            // when these are undefined, i.e. RFC-default bare-seed entries).1187            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);1188            totpCode = generated.code;1189            totpRemaining = generated.remaining;1190          } catch {1191            totpCode = undefined;1192          }1193        }1194        if (isPageSender(sender) && vault.isUnlocked()) touchAutoLock();1195        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };1196      }1197      // Trusted full-entry fetch for extension-owned edit surfaces. Content1198      // scripts route editing to the popup and cannot call this message.1199      case "GET_ENTRY_FOR_EDIT": {1200        if (isPageSender(sender)) return { ok: false, error: "invalid_sender" };1201        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1202        const { id } = msg.payload as { id: string };1203        const entry = vault.getEntryById(id);1204        if (!entry) return { ok: false, error: "entry_not_found" };12051206        const { passkey: _passkey, ...safeEntry } = entry;1207        return { ok: true, data: safeEntry };1208      }1209      case "COPY": {1210        // Page relays must carry the browser-attested frame origin, as with1211        // SUMMON/fill. The policy admits content scripts; this binds the1212        // admitted page sender before arming clipboard auto-clear.1213        if (isPageSender(sender) && !attestedSenderOrigin(sender)) {1214          return { ok: false, error: "invalid_sender" };1215        }1216        // AUD-002: shape-validate the payload before passing to the clipboard1217        // helper. A raw cast lets a malformed message reach the clipboard API1218        // with a non-string and throw.1219        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {1220          text?: unknown;1221          label?: unknown;1222          alreadyWritten?: unknown;1223        };1224        if (typeof text !== "string" || typeof label !== "string") {1225          return { ok: false, error: "invalid_payload" };1226        }1227        await copyToClipboard(text, label, Boolean(alreadyWritten));1228        return { ok: true, clearSeconds: getEffectiveClearSeconds() };1229      }1230      case "CHECK_ALL_BREACHES": {1231        return { ok: true, data: vault.startBreachScan() };1232      }1233      case "GET_BREACH_SCAN_STATUS": {1234        return { ok: true, data: vault.getBreachScanStatus() };1235      }1236      case "GET_SETTINGS": {1237        const settings = await vault.ensureSettingsLoaded();1238        if (!isPageSender(sender)) return { ok: true, data: settings };12391240        const safeSettings: Pick<vault.VaultSettings, "accentColor" | "theme"> & {1241          manualSummonDomains?: NonNullable<vault.VaultSettings["manualSummonDomains"]>;1242        } = {1243          accentColor: settings.accentColor,1244          theme: settings.theme,1245        };1246        const domain = attestedSenderDomain(sender);1247        const ownSummon = domain ? settings.manualSummonDomains?.[domain] : undefined;1248        if (domain && ownSummon) safeSettings.manualSummonDomains = { [domain]: ownSummon };1249        return { ok: true, data: safeSettings };1250      }1251      case "UPDATE_SETTINGS": {1252        const patch = msg.payload;1253        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {1254          return { ok: false, error: "invalid_payload" };1255        }1256        await vault.updateSettings(patch as vault.VaultSettings);1257        if ((patch as Record<string, unknown>).lockedSyncRequiresUnlock === true) {1258          await clearLockedSyncPrivateKey();1259        }1260        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {1261          await setupAutoLock();1262          if (vault.isUnlocked()) touchAutoLock();1263        }1264        return { ok: true };1265      }1266      case "SETUP_PIN": {1267        const { currentPassword, pin } = (msg.payload ?? {}) as {1268          currentPassword?: unknown;1269          pin?: unknown;1270        };1271        if (typeof currentPassword !== "string" || typeof pin !== "string") {1272          return { ok: false, error: "invalid_payload" };1273        }1274        return (await vault.setupPinUnlock(currentPassword, pin))1275          ? { ok: true }1276          : { ok: false, error: "incorrect_current_password" };1277      }1278      case "DISABLE_PIN": {1279        const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown };1280        if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" };1281        return (await vault.disablePinUnlock(currentPassword))1282          ? { ok: true }1283          : { ok: false, error: "incorrect_current_password" };1284      }1285      case "GET_PENDING_PASSKEY":1286        return { ok: true, data: await getPendingPasskeyRequest() };1287      case "APPROVE_PASSKEY": {1288        const { requestId } = msg.payload as { requestId: number };1289        await resolvePendingPasskeyRequest(requestId, true);1290        return { ok: true };1291      }1292      case "DENY_PASSKEY": {1293        const { requestId } = msg.payload as { requestId: number };1294        await resolvePendingPasskeyRequest(requestId, false);1295        return { ok: true };1296      }1297      case "GET_PASSKEY_PROVIDER_STATE":1298        return { ok: true, data: await getPasskeyProviderState() };1299      case "SET_PASSKEY_PROVIDER_ENABLED": {1300        const { enabled } = msg.payload as { enabled: boolean };1301        // Disabling is always free; gating fires only when a free user is1302        // trying to turn passkey interception on.1303        if (enabled) {1304          const gate = await requirePro("passkeys");1305          if (!gate.allowed) return { ok: false, error: "pro_required" };1306        }1307        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };1308      }1309      case "FIRE_CANARY_PING": {1310        const payload = msg.payload;1311        if (!payload || typeof payload !== "object" || Array.isArray(payload)) return { ok: false, error: "invalid_payload" };1312        const { id, trigger, capability, webhookUrl: draftUrl, entryTitle } = payload as {1313          id?: unknown; trigger?: unknown; capability?: unknown; webhookUrl?: unknown; entryTitle?: unknown;1314        };1315        if (trigger === "test" && !isExtensionPageSender(sender)) return { ok: false, error: "invalid_sender" };1316        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1317        if (trigger === "test") {1318          if (typeof entryTitle !== "string") return { ok: false, error: "invalid_payload" };1319          const webhookUrl = canaryWebhookUrl(draftUrl);1320          if (!webhookUrl) return { ok: false, error: "invalid_webhook_url" };1321          try {1322            const response = await fetch(webhookUrl, { method: "POST", headers: { "Content-Type": "application/json" },1323              body: canaryBody(entryTitle, "test"), redirect: "error" });1324            return { ok: response.ok, error: response.ok ? undefined : `HTTP ${response.status}` };1325          } catch { return { ok: false, error: "network_error" }; }1326        }1327        if (typeof id !== "string" || !id || typeof trigger !== "string" || !["accessed", "password_copied", "username_copied", "autofilled", "submitted"].includes(trigger) ||1328          Object.keys(payload).some(key => !["id", "trigger", "capability"].includes(key))) return { ok: false, error: "invalid_payload" };1329        const capabilityAuthorized = capability !== undefined && consumeSummonCapability(capability, sender, "fill");1330        const domain = isPageSender(sender) ? attestedSenderDomain(sender) : null;1331        if (isPageSender(sender) && !domain) return { ok: false, error: "origin_unverified" };1332        const entry = vault.getEntryById(id);1333        if (!entry || (domain && !capabilityAuthorized && !entryDomains(entry.url, entry.additionalUrls).has(domain))) {1334          return { ok: false, error: "entry_not_found" };1335        }1336        return fireStoredCanary(entry, trigger as CanaryTrigger);1337      }1338      case "ACTIVATE_LICENSE": {1339        const { key } = msg.payload as { key: string };1340        const licenseInfo = await activateLicense(key);1341        return { ok: true, data: licenseInfo };1342      }1343      case "GET_LICENSE": {1344        const licenseInfo = await getLicenseInfo();1345        return { ok: true, data: licenseInfo };1346      }1347      case "GET_LICENSE_KEY": {1348        const key = await getLicenseKey();1349        return { ok: true, data: key };1350      }1351      case "DEACTIVATE_LICENSE": {1352        await deactivateLicense();1353        return { ok: true };1354      }1355      case "SHOULD_PLAY_CELEBRATION": {1356        const should = await shouldPlayCelebration();1357        return { ok: true, data: should };1358      }1359      case "MARK_CELEBRATION_PLAYED": {1360        await markCelebrationPlayed();1361        return { ok: true };1362      }1363      case "GET_CODEX_VAULT_DATA": {1364        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1365        // popup navigates to the License section without further coordination.1366        // Also privileged-page-gated (PB-26-001), and recoveryWords inside the1367        // snapshot additionally require a fresh master-password proof.1368        const gate = await requirePro("codex");1369        if (!gate.allowed) return { ok: false, error: "pro_required" };1370        const { password } = (msg.payload ?? {}) as { password?: string };1371        return await handleGetCodexVaultData(password);1372      }1373      case "ESTIMATE_CODEX_PAGES": {1374        const gate = await requirePro("codex");1375        if (!gate.allowed) return { ok: false, error: "pro_required" };1376        return await handleEstimateCodexPages();1377      }1378      case "RESTORE_FROM_CODEX": {1379        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1380        // be able to restore a vault that was printed by a Pro user.1381        // DO NOT add a Pro gate here.1382        // A decoy session, though, holds no real-mode authority: this path1383        // writes SLOT_A/SLOT_B and snapshots history, so it carries the same1384        // guard its thirteen neighbours do (PB-26-915).1385        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1386        const payload = msg.payload as CodexRestorePayload;1387        return await handleRestoreFromCodex(payload);1388      }1389      case "OPEN_PRO_GATE": {1390        // Content script requests: open popup and navigate to License section.1391        const { feature } = (msg.payload ?? {}) as { feature?: string };1392        if (chrome.storage.session) {1393          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1394        }1395        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1396        return { ok: true };1397      }1398      case "OPEN_POPUP": {1399        // Content script asks to open the trusted extension popup — used by the1400        // inline locked bubble so the master password is entered in the popup,1401        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1402        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1403        // toolbar icon. The badge already signals Peach needs attention.1404        //1405        // Set a session flag so the popup knows it was opened for inline unlock1406        // and should close itself once the vault is unlocked (returning the user1407        // to the inline autofill selector on the page).1408        const { entryId } = (msg.payload ?? {}) as { entryId?: unknown };1409        if (entryId !== undefined && (typeof entryId !== "string" || entryId.length === 0 || entryId.length > 64)) {1410          return { ok: false, error: "invalid_payload" };1411        }1412        if (chrome.storage.session) {1413          if (typeof entryId === "string") {1414            await chrome.storage.session.set({ peach_open_entry: entryId });1415          } else {1416            await chrome.storage.session.set({ peach_inline_unlock: true });1417          }1418        }1419        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1420        return { ok: true };1421      }1422      case "OPEN_DETACHED_POPUP": {1423        // A window created by the action popup and then orphaned with1424        // window.close() is cascaded shut by Chrome, so the file-picker1425        // flows (OS dialogs that dismiss the popup on focus loss) ask the SW1426        // to open the standalone window instead — the SW has no window to be1427        // associated with. The query string is allowlisted so this can never1428        // open an arbitrary URL.1429        const { route } = (msg.payload ?? {}) as { route?: string };1430        const search = route === "peachscript"1431          ? "?restore=peachscript"1432          : route === "csv"1433            ? "?restore=csv"1434            : route === "codex-pdf"1435              ? "?codex=pdf"1436              : null;1437        if (!search) return { ok: false, error: "bad_route" };1438        try {1439          const popupHtml =1440            chrome.runtime.getManifest().action?.default_popup ?? "src/popup/index.html";1441          await chrome.windows.create({1442            url: chrome.runtime.getURL(`${popupHtml}${search}`),1443            type: "popup",1444            width: 320,1445            height: 550,1446          });1447          return { ok: true, data: { detached: true } };1448        } catch {1449          return { ok: false };1450        }1451      }1452      case "GET_IDENTITIES": {1453        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1454        return { ok: true, data: vault.getIdentities() };1455      }1456      case "TOUCH_AUTO_LOCK": {1457        // touchAutoLock() is already called by shouldRefreshAutoLock above;1458        // this case just gives the popup a typed message to keep the session alive.1459        return { ok: true };1460      }1461      case "GET_ADVANCED_HEALTH_REPORT": {1462        const gate = await requirePro("advanced_health");1463        if (!gate.allowed) return { ok: false, error: "pro_required" };1464        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1465        const report = await buildAdvancedHealthReport(vault.getEntries());1466        return { ok: true, data: report };1467      }1468      case "IS_DURESS_ENABLED": {1469        const enabled = await vault.isDuressEnabled();1470        return { ok: true, data: enabled };1471      }1472      case "SETUP_DURESS": {1473        // Single enforcement point for the Duress Vault Pro gate. Free users1474        // who somehow reach this handler are rejected here; the popup also1475        // pre-checks isPro() to avoid showing the setup form to free users,1476        // but server-side is the actual security boundary.1477        const gate = await requirePro("duress_vault");1478        if (!gate.allowed) return { ok: false, error: "pro_required" };1479        // MV3 service workers restart after inactivity, losing the in-memory1480        // derived key. Detect this before calling setupDuress so the popup1481        // can show a meaningful prompt to re-lock and re-unlock.1482        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1483        const { duressPassword } = msg.payload as { duressPassword: string };1484        await vault.setupDuress(duressPassword);1485        return { ok: true };1486      }1487      case "DISABLE_DURESS": {1488        await vault.disableDuress();1489        return { ok: true };1490      }1491      case "VERIFY_MAIN_PASSWORD": {1492        const { password } = msg.payload as { password: string };1493        const ok = await vault.verifyMainPassword(password);1494        return { ok: true, data: ok };1495      }1496      case "CHANGE_PASSWORD": {1497        const { currentPassword, newPassword } = msg.payload as {1498          currentPassword: string;1499          newPassword: string;1500        };1501        const changed = await vault.changePassword(currentPassword, newPassword);1502        return changed1503          ? { ok: true }1504          : { ok: false, error: "incorrect_current_password" };1505      }1506      case "GET_SITE_PASSWORD_POLICY": {1507        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1508        if (!tab?.id) return { ok: true, data: null };1509        try {1510          const response = await chrome.tabs.sendMessage(tab.id, {1511            type: "GET_SITE_PASSWORD_POLICY",1512          });1513          return (response as MessageResponse) ?? { ok: true, data: null };1514        } catch {1515          return { ok: true, data: null };1516        }1517      }1518      case "RECORD_MANUAL_SUMMON": {1519        const { domain } = (msg.payload ?? {}) as { domain?: unknown };1520        const origin = attestedSenderOrigin(sender);1521        let senderDomain: string | null = null;1522        if (origin) {1523          try {1524            const hostname = new URL(origin).hostname;1525            senderDomain = extractDomain(hostname) ?? hostname;1526          } catch {1527            senderDomain = null;1528          }1529        }1530        if (typeof domain !== "string" || domain.length > 253 || domain !== senderDomain) {1531          return { ok: false, error: "invalid_domain" };1532        }1533        const settings = vault.getSettings();1534        const existing = settings.manualSummonDomains?.[domain];1535        const now = Date.now();1536        await vault.updateSettings({1537          manualSummonDomains: {1538            ...settings.manualSummonDomains,1539            [domain]: {1540              firstSummonedAt: existing?.firstSummonedAt ?? now,1541              summonCount: (existing?.summonCount ?? 0) + 1,1542              lastSummonedAt: now,1543            },1544          },1545        });1546        return { ok: true };1547      }1548      case "DECLINE_CARD_SAVE": {1549        // PB-26-108: the declined-card digest is keyed by root-key material, so1550        // a decline cannot be recorded while locked. Offers are not shown while1551        // locked either, so this is unreachable in practice.1552        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1553        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1554        await vault.declineCardSaveOffer(last4, expMonth, expYear);1555        return { ok: true };1556      }1557      case "IS_CARD_DECLINED": {1558        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1559        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1560        return { ok: true, data: declined };1561      }1562      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1563        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1564          rpId?: string;1565          rpName?: string;1566          userName?: string;1567          userDisplayName?: string;1568        };1569        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1570        return await initiateFirefoxPasskeyCreate({1571          rpId,1572          rpName: rpName ?? rpId,1573          userName,1574          userDisplayName,1575        }, attestedSenderOrigin(sender));1576      }15771578      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1579        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1580        if (!payload) return { ok: false, error: "missing_payload" };1581        return await completeFirefoxPasskeyCreate(payload);1582      }15831584      case "PASSKEY_OFFER_DECLINE": {1585        const { domain } = (msg.payload ?? {}) as { domain?: string };1586        const origin = attestedSenderOrigin(sender);1587        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1588        await recordPasskeyOfferDecline(domain);1589        return { ok: true };1590      }15911592      case "GET_PASSKEY_OFFER_DECLINED": {1593        const { domain } = (msg.payload ?? {}) as { domain?: string };1594        const origin = attestedSenderOrigin(sender);1595        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1596        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1597      }15981599      case "PASSKEY_HAS_CREDENTIALS": {1600        const payload = msg.payload as {1601          rpId?: string;1602          allowCredentials?: Array<{ id: string; type?: string }>;1603        } | undefined;1604        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1605        return await handlePasskeyHasCredentials({1606          rpId: payload.rpId,1607          allowCredentials: payload.allowCredentials ?? [],1608        }, attestedSenderOrigin(sender));1609      }16101611      case "PASSKEY_CREATE": {1612        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1613        if (!payload?.rpId || !payload?.userName) {1614          return { ok: false, error: "rpid_and_username_required" };1615        }1616        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1617      }16181619      case "PASSKEY_GET": {1620        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1621        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1622        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1623      }16241625      case "PASSKEY_AUTH_RESPONSE": {1626        const { requestId, approved } = (msg.payload ?? {}) as {1627          requestId?: string | number;1628          approved?: boolean;1629        };1630        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1631          return { ok: false, error: 'requestId and approved required' };1632        }1633        const pending = await getPendingPasskeyRequest();1634        const senderOrigin = attestedSenderOrigin(sender);1635        if (1636          !pending ||1637          pending.tabId === undefined ||1638          pending.crossOrigin === true ||1639          pending.requestId !== Number(requestId) ||1640          sender.tab?.id !== pending.tabId ||1641          senderOrigin !== pending.origin1642        ) {1643          return { ok: false, error: "invalid_passkey_approval_sender" };1644        }1645        await resolvePendingPasskeyRequest(Number(requestId), approved);1646        return { ok: true };1647      }16481649      case "GET_PASSKEY_FOR_DOMAIN": {1650        const { domain } = (msg.payload ?? {}) as { domain?: string };1651        if (!domain) return { ok: false, error: "domain_required" };1652        // Scope to the caller's own origin: a page may only ask about passkeys1653        // for a domain it actually owns, so an arbitrary page cannot enumerate1654        // which sites the user holds passkeys for or read the username (audit MEDIUM).1655        const origin = attestedSenderOrigin(sender);1656        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1657        if (!vault.isUnlocked()) return { ok: true, data: null };1658        const match = vault1659          .getEntries()1660          .find((entry) => entry.passkey?.rpId === domain);1661        if (!match || !match.passkey) return { ok: true, data: null };1662        // Slim shape — only the fields State 11 needs. Never expose private1663        // key material, even though this is locked behind isUnlocked.1664        // bannerShown is the per-domain "already surfaced" flag, kept in1665        // trusted background session storage so content scripts never touch1666        // chrome.storage.session directly (PB-26-203).1667        let bannerShown = false;1668        if (chrome.storage.session) {1669          const flag = await chrome.storage.session.get(`peach_state11_shown:${domain}`);1670          bannerShown = Boolean((flag as Record<string, unknown>)[`peach_state11_shown:${domain}`]);1671        }1672        return {1673          ok: true,1674          data: {1675            rpId: match.passkey.rpId,1676            userName: match.passkey.userName,1677            browser: match.passkey.browser,1678            bannerShown,1679          },1680        };1681      }16821683      case "MARK_PASSKEY_BANNER_SHOWN": {1684        const { domain } = (msg.payload ?? {}) as { domain?: string };1685        if (typeof domain !== "string" || !domain) return { ok: false, error: "domain_required" };1686        // Same origin binding as the read path: a page may only mark its own1687        // domain, and the flag reveals nothing either way.1688        const origin = attestedSenderOrigin(sender);1689        if (!origin || !isValidRpId(domain, origin)) return { ok: true };1690        if (chrome.storage.session) {1691          await chrome.storage.session.set({ [`peach_state11_shown:${domain}`]: Date.now() });1692        }1693        return { ok: true };1694      }16951696      case "DESTROY_VAULT": {1697        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1698        // storage.local.clear() wipes every Peach key (slots, settings, license,1699        // onboarded flag, history, sync state, declined cards, recall, etc.);1700        // session.clear() wipes pending passkey requests + pro-notice queues.1701        // Caller (Panic.tsx) handles UI navigation back to onboarding.1702        //1703        // The Pro license is the one thing that must survive: the user paid for1704        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1705        // Capture it before the clear and restore it after. peach_pro_celebrated1706        // rides along so the Pro celebration doesn't replay on the next unlock.1707        await vault.withVaultRemoval(async () => {1708          const preserved = await chrome.storage.local.get([1709            "peach_license",1710            "peach_pro_celebrated",1711          ]);1712          await storageClear();1713          await vault.clearVaultHistory();1714          const toRestore: Record<string, unknown> = {};1715          if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1716          if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1717          if (Object.keys(toRestore).length > 0) {1718            await chrome.storage.local.set(toRestore);1719          }1720          if (chrome.storage.session) {1721            await chrome.storage.session.clear();1722          }1723          await clearRecoveryConfirmPending();1724        });1725        return { ok: true };1726      }17271728      case "GET_IDENTITY_SUGGESTIONS": {1729        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1730        const entries = vault.getEntries();1731        const suggestions = buildIdentitySuggestions(entries);1732        return { ok: true, data: { suggestions } };1733      }1734      case "ML_INIT":1735        return { ok: true };17361737      case "ML_PREDICT_BATCH": {1738        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1739        if (!isValidMLFeatureBatch(featuresArray, MAX_ML_BATCH_FIELDS)) {1740          return { ok: false, error: "invalid_payload" };1741        }1742        if (!claimMLWork(sender, featuresArray.length)) {1743          return { ok: false, error: "rate_limited" };1744        }1745        return { ok: true, data: mlPredictBatch(featuresArray) };1746      }17471748      // ── Vault sync (v3) ───────────────────────────────────────────────1749      // Returns the public-facing local identity needed by the popup to1750      // drive Phase-1 audio pairing. The private long-term key never1751      // leaves the background.1752      case "GET_LOCAL_IDENTITY": {1753        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1754        // Pro license from an already-Pro peer (at least one device must be Pro).1755        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1756        // The identity is sealed under its own key rather than derived from the1757        // root, so pairing survives a master-password change (SEV-2-B).1758        const identity: LocalDeviceIdentity & { license?: string } = await buildLocalIdentity();1759        // If this device is Pro, advertise the signed license so the peer can1760        // activate it after SAS confirmation — pairing carries Pro across.1761        if (await isProUser()) {1762          const license = await getLicenseKey();1763          if (license) identity.license = license;1764        }1765        return { ok: true, data: identity };1766      }17671768      case "LIST_PAIRED_DEVICES": {1769        if (vault.isDecoyMode()) return { ok: true, data: { devices: [] } };1770        try {1771          const devices = await listPairedDevicesV3();1772          return { ok: true, data: { devices } };1773        } catch (err) {1774          if (err instanceof TrustDataCorruptedError) {1775            return { ok: false, error: "trust_data_corrupted" };1776          }1777          throw err;1778        }1779      }17801781      case "RENAME_PAIRED_DEVICE": {1782        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1783        const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string };1784        if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") {1785          return { ok: false, error: "invalid_payload" };1786        }1787        await renamePairedDeviceV3(deviceId, name);1788        return { ok: true };1789      }17901791      case "UNPAIR_DEVICE": {1792        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1793        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1794        if (typeof deviceId !== "string" || !deviceId) {1795          return { ok: false, error: "invalid_payload" };1796        }1797        // A damaged legacy identity must not prevent the user from evicting a1798        // peer locally. Sync is already blocked until the secure reset repairs1799        // this installation, so the local issuer marker is sufficient for the1800        // tombstone that will be cleared with the archived generation.1801        await revokeDeviceByIdV3(deviceId, async () => {1802          try {1803            return await getExistingDeviceId();1804          } catch (error) {1805            if (!(error instanceof Error) || error.message !== "identity_migration_required") throw error;1806            return "local";1807          }1808        });1809        // PB-26-213: forget the secret now so no further dial can use it.1810        // Removals that happen while locked leave orphans for the next1811        // unlock's reconcile to prune.1812        const unpairRootHex = vault.getRootKeyHex();1813        if (unpairRootHex) {1814          const unpairRoot = unhexBytes(unpairRootHex);1815          try {1816            await dropPairSecret(deviceId, unpairRoot);1817          } finally {1818            unpairRoot.fill(0);1819          }1820        } else {1821          await dropPairSecret(deviceId, null);1822        }1823        // Sync against the remaining hosts — the unpaired device no longer1824        // matters but the next alarm tick is up to ten minutes away.1825        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1826        return { ok: true };1827      }18281829      case "RENAME_LOCAL_DEVICE": {1830        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1831        const { name } = (msg.payload ?? {}) as { name?: string };1832        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1833        await setDeviceNameV3(name);1834        return { ok: true };1835      }18361837      // ── Relay pairing ─────────────────────────────────────────────────────1838      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1839      // session runs in the background; the SAS and the terminal result reach1840      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1841      case "START_ADOPTION_SOURCE": {1842        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1843        if (isRelayAdoptionSourceInFlight()) {1844          return { ok: false, error: "adoption_source_in_progress" };1845        }1846        try {1847          return { ok: true, data: await startRelayAdoptionSource() };1848        } catch (error) {1849          return {1850            ok: false,1851            error: error instanceof Error ? error.message : "adoption_source_failed",1852          };1853        }1854      }18551856      // Onboarding receiver — empty extension shows a QR, phone scans and1857      // sends the vault. The popup supplies the local-only password here so1858      // the background can wrap the adopted root key at rest without ever1859      // asking the user to retype it.1860      case "START_ADOPTION_RECEIVER": {1861        if (isRelayAdoptionSourceInFlight()) {1862          return { ok: false, error: "adoption_receiver_in_progress" };1863        }1864        const password = (msg.payload as { password?: unknown } | undefined)?.password;1865        if (typeof password !== "string" || password.length === 0) {1866          return { ok: false, error: "invalid_payload" };1867        }1868        try {1869          return { ok: true, data: await startRelayAdoptionReceiver(password) };1870        } catch (error) {1871          return {1872            ok: false,1873            error: error instanceof Error ? error.message : "adoption_receiver_failed",1874          };1875        }1876      }18771878      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1879      // on the source's SAS screen. The id round-trips the same way so a stale1880      // late response can't approve the wrong session.1881      case "RECEIVER_SAS_DECISION": {1882        const payload = msg.payload as { id?: unknown; sas?: unknown; ok?: unknown } | undefined;1883        if (typeof payload?.id !== "string" || typeof payload.sas !== "string" || typeof payload.ok !== "boolean") {1884          return { ok: false, error: "invalid_payload" };1885        }1886        return { ok: resolveReceiverSasConfirmation(payload.id, payload.sas, payload.ok) };1887      }18881889      case "SOURCE_SAS_DECISION": {1890        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1891        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1892          return { ok: false, error: "invalid_payload" };1893        }1894        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1895      }1896      case "LIST_PENDING_ADOPTION_HOLDERS": {1897        return { ok: true, data: await listPendingAdoptionHolders() };1898      }18991900      case "REMOVE_PENDING_ADOPTION_HOLDER": {1901        await removePendingAdoptionHolder();1902        return { ok: true };1903      }190419051906      case "CANCEL_ADOPTION_SOURCE": {1907        cancelRelayAdoptionSource();1908        return { ok: true };1909      }19101911      case "TRIGGER_SYNC": {1912        if (vault.isDecoyMode()) return { ok: true };1913        const payload = (msg.payload ?? {}) as {1914          reason?: "vault_change" | "foreground" | "manual";1915          force?: boolean;1916        };1917        const reason = payload.reason ?? "foreground";19181919        void triggerSyncIfReachable({ reason, force: payload.force === true });1920        return { ok: true };1921      }19221923      case "GET_SYNC_STATE": {1924        if (vault.isDecoyMode()) return { ok: true, data: { status: "idle" } };1925        return { ok: true, data: getSyncState() };1926      }19271928      // §11. The generation state carries no secret — it is a version and a1929      // state name — so the panel can read it while the vault is locked.1930      case "GET_SYNC_GENERATION": {1931        return { ok: true, data: await resolveGeneration(browserGenerationIo) };1932      }19331934      case "SECURE_RESET": {1935        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1936        const payload = (msg.payload ?? {}) as { password?: unknown };1937        if (typeof payload.password !== "string" || payload.password.length === 0) {1938          return { ok: false, error: "Enter your master password" };1939        }1940        const wasLocked = !vault.isUnlocked();1941        const passwordValid = wasLocked1942          ? await vault.unlock(payload.password)1943          : await vault.verifyMainPassword(payload.password);1944        if (!passwordValid) {1945          return { ok: false, error: "Incorrect master password" };1946        }1947        if (wasLocked) {1948          await setupAutoLock();1949          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });1950          onVaultUnlocked();1951        }1952        // Identity rotation needs the live vault root key. A password check is1953        // deliberately verification-only, so establish the real session first1954        // when Settings is opened after the vault session expired.1955        const result = await confirmSecureReset(browserGenerationIo, {1956          nowMs: Date.now(),1957        });1958        if (result === "V2_ANCHOR") return { ok: true, data: await resolveGeneration(browserGenerationIo) };1959        return {1960          ok: false,1961          error: result === "reset_archive_review_required"1962            ? "The saved Sync trust archive needs review before reset can continue. Peach has kept the archive and current trust unchanged. Contact Peach support before retrying."1963            : "The reset did not complete. Try again; if it still fails, contact Peach support.",1964        };1965      }19661967      case "GET_SYNC_SETTINGS": {1968        if (vault.isDecoyMode()) return { ok: true, data: { mode: "off", relayUrl: "" } };1969        return { ok: true, data: await getSyncSettings() };1970      }19711972      case "SET_SYNC_SETTINGS": {1973        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1974        const payload = (msg.payload ?? {}) as {1975          mode?: unknown;1976          relayUrl?: unknown;1977        };1978        try {1979          // A custom relay URL implies private mode; Peach's own relay stays1980          // public. See setRelayUrl.1981          if (payload.relayUrl !== undefined) {1982            if (typeof payload.relayUrl !== "string") {1983              return { ok: false, error: "invalid_relay_url" };1984            }1985            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1986          }1987          if (payload.mode !== undefined) {1988            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1989              return { ok: false, error: "invalid_sync_mode" };1990            }1991            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1992          }1993          return { ok: true, data: await getSyncSettings() };1994        } catch (error) {1995          return {1996            ok: false,1997            error: error instanceof Error ? error.message : "invalid_relay_url",1998          };1999        }2000      }200120022003      case "GET_SYNC_ALERTS": {2004        if (vault.isDecoyMode()) return { ok: true, data: [] };2005        return { ok: true, data: await getPendingSyncAlerts() };2006      }20072008      case "DISMISS_SYNC_ALERTS": {2009        if (vault.isDecoyMode()) return { ok: true };2010        const type = (msg.payload as { type?: unknown } | undefined)?.type;2011        if (type !== "DEVICE_KEY_ROTATED" && type !== "DEVICE_REVOKED") {2012          return { ok: false, error: "invalid_sync_alert_type" };2013        }2014        await dismissPendingSyncAlerts(type);2015        return { ok: true };2016      }20172018      case "GET_PENDING_VOUCHED_DEVICES": {2019        if (vault.isDecoyMode()) return { ok: true, data: [] };2020        return { ok: true, data: await listPendingVouchedDevices() };2021      }2022      case "CONFIRM_VOUCHED_DEVICE": {2023        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };2024        const { deviceId } = msg.payload as { deviceId: string };2025        const pending = await getPendingVouchedDevice(deviceId);2026        if (!pending) return { ok: false, error: "not_pending" };2027        // Last gate before a vouched device becomes a sync peer. A queue entry2028        // can predate the revocation that names it, so revocation is re-checked2029        // here rather than trusted to have swept the queue.2030        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {2031          await removePendingVouchedDevice(deviceId);2032          return { ok: false, error: "device_revoked" };2033        }2034        await upsertPairedDeviceV3({2035          deviceId: pending.deviceId,2036          deviceName: pending.deviceName,2037          deviceType:2038            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],2039          longTermPublicKeyHex: pending.longTermPublicKeyHex,2040          signingPublicKeyHex: pending.signingPublicKeyHex,2041          wsPort: pending.wsPort,2042          pairedAt: pending.pairedAt,2043          trustSource: "vouched",2044        });2045        await removePendingVouchedDevice(deviceId);2046        // Newly confirmed vouched device is now a sync target — kick a round2047        // so the mesh introduction pays off without a 10-minute wait.2048        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);2049        return { ok: true };2050      }2051      case "REJECT_VOUCHED_DEVICE": {2052        if (vault.isDecoyMode()) return { ok: true };2053        const { deviceId } = msg.payload as { deviceId: string };2054        await removePendingVouchedDevice(deviceId);2055        return { ok: true };2056      }20572058      case "ROTATE_SYNC_IDENTITY": {2059        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };2060        const epoch = vault.getVaultEpoch();2061        const { password } = (msg.payload ?? {}) as { password?: unknown };2062        if (typeof password !== "string" || !password) return { ok: false, error: "password_required" };2063        const verified = await vault.verifyMainPassword(password);2064        if (!vault.isUnlocked() || epoch !== vault.getVaultEpoch()) return { ok: false, error: "vault_locked" };2065        if (!verified) return { ok: false, error: "wrong_password" };2066        const result = await vault.rotateSyncIdentity();2067        return result.ok ? { ok: true } : { ok: false, error: result.error };2068      }20692070      default:2071        return { ok: false, error: "unknown_message_type" };2072    }2073  } catch (err) {2074    return {2075      ok: false,2076      error: err instanceof Error ? err.message : "operation_failed",2077    };2078  }2079}20802081// Returns username use-counts from the vault, sorted by frequency. Each row2082// also carries the entry's email so the popup can suggest the email/username2083// pair the user has actually used together.2084function buildIdentitySuggestions(2085  entries: VaultEntry[],2086): Array<{ email: string; username: string; count: number }> {2087  const usernameCounts = new Map<string, number>();2088  const usernameEmail = new Map<string, string>();2089  for (const entry of entries) {2090    const username = entry.username ?? "";2091    const email = (entry as VaultEntry & { email?: string }).email ?? "";2092    if (!username && !email) continue;2093    const key = username || email;2094    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);2095    if (!usernameEmail.has(key)) usernameEmail.set(key, email);2096  }2097  return Array.from(usernameCounts.entries())2098    .sort((a, b) => b[1] - a[1])2099    .map(([username, count]) => ({2100      email: usernameEmail.get(username) ?? "",2101      username,2102      count,2103    }));2104}21052106/** Notify all content scripts that the vault just became available. */2107function broadcastToContentScripts(message: { type: string }): void {2108  if (!chrome.tabs?.query) return;2109  chrome.tabs.query({}, (tabs) => {2110    for (const tab of tabs) {2111      if (tab.id !== undefined) {2112        chrome.tabs.sendMessage(tab.id, message).catch(() => {2113          // Tab may not have a content script — silently ignore2114        });2115      }2116    }2117  });2118}21192120function shouldRefreshAutoLock(2121  type: MessageType,2122  sender: Partial<chrome.runtime.MessageSender>,2123): boolean {2124  if (!isExtensionPageSender(sender)) return false;2125  return (2126    type !== "HAS_VAULT" &&2127    type !== "IS_UNLOCKED" &&2128    type !== "GET_VAULT_STATUS" &&2129    type !== "GET_BREACH_SCAN_STATUS" &&2130    type !== "LOCK" &&2131    type !== "UPDATE_SETTINGS" &&2132    type !== "GET_PENDING_PASSKEY" &&2133    type !== "GET_PASSKEY_PROVIDER_STATE" &&2134    type !== "DECLINE_CARD_SAVE" &&2135    type !== "IS_CARD_DECLINED" &&2136    type !== "AUTOFILL_QUERY" &&2137    type !== "ML_PREDICT_BATCH"2138  );2139}21402141function canaryWebhookUrl(value: unknown): string | null {2142  if (typeof value !== "string") return null;2143  try {2144    const url = new URL(value);2145    if (url.protocol !== "https:" || url.username || url.password) return null;2146    const host = url.hostname.toLowerCase().replace(/\.+$/, "");2147    if (!host || host === "localhost" || host.endsWith(".localhost")) return null;2148    if (host.startsWith("[")) {2149      if (isUnsafeCanaryIpv6(host.slice(1, -1))) return null;2150    } else if (/^\d+(?:\.\d+){3}$/.test(host) && isUnsafeCanaryIpv4(host)) return null;2151    url.hostname = host;2152    return url.href;2153  } catch { return null; }2154}21552156function isUnsafeCanaryIpv4(host: string): boolean {2157  const [a, b, c, d] = host.split(".").map(Number);2158  return a === 0 || a === 10 || a === 127 || a >= 224 ||2159    (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) ||2160    (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) ||2161    (a === 192 && b === 0 && c === 0 && d !== 9 && d !== 10) ||2162    (a === 192 && b === 0 && c === 2) || (a === 192 && b === 88 && c === 99) ||2163    (a === 198 && (b === 18 || b === 19 || (b === 51 && c === 100))) ||2164    (a === 203 && b === 0 && c === 113);2165}21662167function isUnsafeCanaryIpv6(host: string): boolean {2168  const [head, tail = ""] = host.split("::");2169  const left = head ? head.split(":").map(value => Number.parseInt(value, 16)) : [];2170  const right = tail ? tail.split(":").map(value => Number.parseInt(value, 16)) : [];2171  const words = [...left, ...Array<number>(8 - left.length - right.length).fill(0), ...right];2172  if (words.slice(0, 5).every(word => word === 0) && words[5] === 0xffff) {2173    return isUnsafeCanaryIpv4(`${words[6] >>> 8}.${words[6] & 255}.${words[7] >>> 8}.${words[7] & 255}`);2174  }2175  // Native global-unicast literals only; transition formats are conservative exclusions.2176  if ((words[0] & 0xe000) !== 0x2000 || words[0] === 0x2002) return true;2177  if (words[0] === 0x3fff && (words[1] & 0xf000) === 0) return true;2178  if (words[0] !== 0x2001) return false;2179  if (words[1] === 0xdb8) return true;2180  if ((words[1] & 0xfe00) !== 0) return false;2181  const globalAssignment = words[1] === 3 || (words[1] === 4 && words[2] === 0x112) ||2182    (words[1] & 0xfff0) === 0x20 || (words[1] & 0xfff0) === 0x30 ||2183    (words[1] === 1 && words.slice(2, 7).every(word => word === 0) && [1, 2, 3].includes(words[7]));2184  return !globalAssignment;2185}