messages.ts

98.0 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        const allEntries = vault.getEntries();1232        const results: Record<string, number> = {};1233        for (const entry of allEntries) {1234          if (entry.type === "note") continue;1235          if (!entry.password) continue;1236          results[entry.id] = await vault.checkBreach(entry.password);1237          // Small delay — be a good citizen to the HIBP API1238          await new Promise((r) => setTimeout(r, 200));1239        }1240        // Persist any non-zero counts back to entries1241        for (const [id, count] of Object.entries(results)) {1242          const entry = vault.getEntryById(id);1243          if (entry && (entry.breach ?? 0) !== count) {1244            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });1245          }1246        }1247        return { ok: true, data: results };1248      }1249      case "GET_SETTINGS": {1250        const settings = await vault.ensureSettingsLoaded();1251        if (!isPageSender(sender)) return { ok: true, data: settings };12521253        const safeSettings: Pick<vault.VaultSettings, "accentColor" | "theme"> & {1254          manualSummonDomains?: NonNullable<vault.VaultSettings["manualSummonDomains"]>;1255        } = {1256          accentColor: settings.accentColor,1257          theme: settings.theme,1258        };1259        const domain = attestedSenderDomain(sender);1260        const ownSummon = domain ? settings.manualSummonDomains?.[domain] : undefined;1261        if (domain && ownSummon) safeSettings.manualSummonDomains = { [domain]: ownSummon };1262        return { ok: true, data: safeSettings };1263      }1264      case "UPDATE_SETTINGS": {1265        const patch = msg.payload;1266        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {1267          return { ok: false, error: "invalid_payload" };1268        }1269        await vault.updateSettings(patch as vault.VaultSettings);1270        if ((patch as Record<string, unknown>).lockedSyncRequiresUnlock === true) {1271          await clearLockedSyncPrivateKey();1272        }1273        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {1274          await setupAutoLock();1275          if (vault.isUnlocked()) touchAutoLock();1276        }1277        return { ok: true };1278      }1279      case "SETUP_PIN": {1280        const { currentPassword, pin } = (msg.payload ?? {}) as {1281          currentPassword?: unknown;1282          pin?: unknown;1283        };1284        if (typeof currentPassword !== "string" || typeof pin !== "string") {1285          return { ok: false, error: "invalid_payload" };1286        }1287        return (await vault.setupPinUnlock(currentPassword, pin))1288          ? { ok: true }1289          : { ok: false, error: "incorrect_current_password" };1290      }1291      case "DISABLE_PIN": {1292        const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown };1293        if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" };1294        return (await vault.disablePinUnlock(currentPassword))1295          ? { ok: true }1296          : { ok: false, error: "incorrect_current_password" };1297      }1298      case "GET_PENDING_PASSKEY":1299        return { ok: true, data: await getPendingPasskeyRequest() };1300      case "APPROVE_PASSKEY": {1301        const { requestId } = msg.payload as { requestId: number };1302        await resolvePendingPasskeyRequest(requestId, true);1303        return { ok: true };1304      }1305      case "DENY_PASSKEY": {1306        const { requestId } = msg.payload as { requestId: number };1307        await resolvePendingPasskeyRequest(requestId, false);1308        return { ok: true };1309      }1310      case "GET_PASSKEY_PROVIDER_STATE":1311        return { ok: true, data: await getPasskeyProviderState() };1312      case "SET_PASSKEY_PROVIDER_ENABLED": {1313        const { enabled } = msg.payload as { enabled: boolean };1314        // Disabling is always free; gating fires only when a free user is1315        // trying to turn passkey interception on.1316        if (enabled) {1317          const gate = await requirePro("passkeys");1318          if (!gate.allowed) return { ok: false, error: "pro_required" };1319        }1320        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };1321      }1322      case "FIRE_CANARY_PING": {1323        const payload = msg.payload;1324        if (!payload || typeof payload !== "object" || Array.isArray(payload)) return { ok: false, error: "invalid_payload" };1325        const { id, trigger, capability, webhookUrl: draftUrl, entryTitle } = payload as {1326          id?: unknown; trigger?: unknown; capability?: unknown; webhookUrl?: unknown; entryTitle?: unknown;1327        };1328        if (trigger === "test" && !isExtensionPageSender(sender)) return { ok: false, error: "invalid_sender" };1329        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1330        if (trigger === "test") {1331          if (typeof entryTitle !== "string") return { ok: false, error: "invalid_payload" };1332          const webhookUrl = canaryWebhookUrl(draftUrl);1333          if (!webhookUrl) return { ok: false, error: "invalid_webhook_url" };1334          try {1335            const response = await fetch(webhookUrl, { method: "POST", headers: { "Content-Type": "application/json" },1336              body: canaryBody(entryTitle, "test"), redirect: "error" });1337            return { ok: response.ok, error: response.ok ? undefined : `HTTP ${response.status}` };1338          } catch { return { ok: false, error: "network_error" }; }1339        }1340        if (typeof id !== "string" || !id || typeof trigger !== "string" || !["accessed", "password_copied", "username_copied", "autofilled", "submitted"].includes(trigger) ||1341          Object.keys(payload).some(key => !["id", "trigger", "capability"].includes(key))) return { ok: false, error: "invalid_payload" };1342        const capabilityAuthorized = capability !== undefined && consumeSummonCapability(capability, sender, "fill");1343        const domain = isPageSender(sender) ? attestedSenderDomain(sender) : null;1344        if (isPageSender(sender) && !domain) return { ok: false, error: "origin_unverified" };1345        const entry = vault.getEntryById(id);1346        if (!entry || (domain && !capabilityAuthorized && !entryDomains(entry.url, entry.additionalUrls).has(domain))) {1347          return { ok: false, error: "entry_not_found" };1348        }1349        return fireStoredCanary(entry, trigger as CanaryTrigger);1350      }1351      case "ACTIVATE_LICENSE": {1352        const { key } = msg.payload as { key: string };1353        const licenseInfo = await activateLicense(key);1354        return { ok: true, data: licenseInfo };1355      }1356      case "GET_LICENSE": {1357        const licenseInfo = await getLicenseInfo();1358        return { ok: true, data: licenseInfo };1359      }1360      case "GET_LICENSE_KEY": {1361        const key = await getLicenseKey();1362        return { ok: true, data: key };1363      }1364      case "DEACTIVATE_LICENSE": {1365        await deactivateLicense();1366        return { ok: true };1367      }1368      case "SHOULD_PLAY_CELEBRATION": {1369        const should = await shouldPlayCelebration();1370        return { ok: true, data: should };1371      }1372      case "MARK_CELEBRATION_PLAYED": {1373        await markCelebrationPlayed();1374        return { ok: true };1375      }1376      case "GET_CODEX_VAULT_DATA": {1377        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1378        // popup navigates to the License section without further coordination.1379        // Also privileged-page-gated (PB-26-001), and recoveryWords inside the1380        // snapshot additionally require a fresh master-password proof.1381        const gate = await requirePro("codex");1382        if (!gate.allowed) return { ok: false, error: "pro_required" };1383        const { password } = (msg.payload ?? {}) as { password?: string };1384        return await handleGetCodexVaultData(password);1385      }1386      case "ESTIMATE_CODEX_PAGES": {1387        const gate = await requirePro("codex");1388        if (!gate.allowed) return { ok: false, error: "pro_required" };1389        return await handleEstimateCodexPages();1390      }1391      case "RESTORE_FROM_CODEX": {1392        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1393        // be able to restore a vault that was printed by a Pro user.1394        // DO NOT add a Pro gate here.1395        // A decoy session, though, holds no real-mode authority: this path1396        // writes SLOT_A/SLOT_B and snapshots history, so it carries the same1397        // guard its thirteen neighbours do (PB-26-915).1398        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1399        const payload = msg.payload as CodexRestorePayload;1400        return await handleRestoreFromCodex(payload);1401      }1402      case "OPEN_PRO_GATE": {1403        // Content script requests: open popup and navigate to License section.1404        const { feature } = (msg.payload ?? {}) as { feature?: string };1405        if (chrome.storage.session) {1406          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1407        }1408        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1409        return { ok: true };1410      }1411      case "OPEN_POPUP": {1412        // Content script asks to open the trusted extension popup — used by the1413        // inline locked bubble so the master password is entered in the popup,1414        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1415        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1416        // toolbar icon. The badge already signals Peach needs attention.1417        //1418        // Set a session flag so the popup knows it was opened for inline unlock1419        // and should close itself once the vault is unlocked (returning the user1420        // to the inline autofill selector on the page).1421        const { entryId } = (msg.payload ?? {}) as { entryId?: unknown };1422        if (entryId !== undefined && (typeof entryId !== "string" || entryId.length === 0 || entryId.length > 64)) {1423          return { ok: false, error: "invalid_payload" };1424        }1425        if (chrome.storage.session) {1426          if (typeof entryId === "string") {1427            await chrome.storage.session.set({ peach_open_entry: entryId });1428          } else {1429            await chrome.storage.session.set({ peach_inline_unlock: true });1430          }1431        }1432        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1433        return { ok: true };1434      }1435      case "OPEN_DETACHED_POPUP": {1436        // A window created by the action popup and then orphaned with1437        // window.close() is cascaded shut by Chrome, so the file-picker1438        // flows (OS dialogs that dismiss the popup on focus loss) ask the SW1439        // to open the standalone window instead — the SW has no window to be1440        // associated with. The query string is allowlisted so this can never1441        // open an arbitrary URL.1442        const { route } = (msg.payload ?? {}) as { route?: string };1443        const search = route === "peachscript"1444          ? "?restore=peachscript"1445          : route === "csv"1446            ? "?restore=csv"1447            : route === "codex-pdf"1448              ? "?codex=pdf"1449              : null;1450        if (!search) return { ok: false, error: "bad_route" };1451        try {1452          const popupHtml =1453            chrome.runtime.getManifest().action?.default_popup ?? "src/popup/index.html";1454          await chrome.windows.create({1455            url: chrome.runtime.getURL(`${popupHtml}${search}`),1456            type: "popup",1457            width: 320,1458            height: 550,1459          });1460          return { ok: true, data: { detached: true } };1461        } catch {1462          return { ok: false };1463        }1464      }1465      case "GET_IDENTITIES": {1466        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1467        return { ok: true, data: vault.getIdentities() };1468      }1469      case "TOUCH_AUTO_LOCK": {1470        // touchAutoLock() is already called by shouldRefreshAutoLock above;1471        // this case just gives the popup a typed message to keep the session alive.1472        return { ok: true };1473      }1474      case "GET_ADVANCED_HEALTH_REPORT": {1475        const gate = await requirePro("advanced_health");1476        if (!gate.allowed) return { ok: false, error: "pro_required" };1477        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1478        const report = await buildAdvancedHealthReport(vault.getEntries());1479        return { ok: true, data: report };1480      }1481      case "IS_DURESS_ENABLED": {1482        const enabled = await vault.isDuressEnabled();1483        return { ok: true, data: enabled };1484      }1485      case "SETUP_DURESS": {1486        // Single enforcement point for the Duress Vault Pro gate. Free users1487        // who somehow reach this handler are rejected here; the popup also1488        // pre-checks isPro() to avoid showing the setup form to free users,1489        // but server-side is the actual security boundary.1490        const gate = await requirePro("duress_vault");1491        if (!gate.allowed) return { ok: false, error: "pro_required" };1492        // MV3 service workers restart after inactivity, losing the in-memory1493        // derived key. Detect this before calling setupDuress so the popup1494        // can show a meaningful prompt to re-lock and re-unlock.1495        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1496        const { duressPassword } = msg.payload as { duressPassword: string };1497        await vault.setupDuress(duressPassword);1498        return { ok: true };1499      }1500      case "DISABLE_DURESS": {1501        await vault.disableDuress();1502        return { ok: true };1503      }1504      case "VERIFY_MAIN_PASSWORD": {1505        const { password } = msg.payload as { password: string };1506        const ok = await vault.verifyMainPassword(password);1507        return { ok: true, data: ok };1508      }1509      case "CHANGE_PASSWORD": {1510        const { currentPassword, newPassword } = msg.payload as {1511          currentPassword: string;1512          newPassword: string;1513        };1514        const changed = await vault.changePassword(currentPassword, newPassword);1515        return changed1516          ? { ok: true }1517          : { ok: false, error: "incorrect_current_password" };1518      }1519      case "GET_SITE_PASSWORD_POLICY": {1520        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1521        if (!tab?.id) return { ok: true, data: null };1522        try {1523          const response = await chrome.tabs.sendMessage(tab.id, {1524            type: "GET_SITE_PASSWORD_POLICY",1525          });1526          return (response as MessageResponse) ?? { ok: true, data: null };1527        } catch {1528          return { ok: true, data: null };1529        }1530      }1531      case "RECORD_MANUAL_SUMMON": {1532        const { domain } = (msg.payload ?? {}) as { domain?: unknown };1533        const origin = attestedSenderOrigin(sender);1534        let senderDomain: string | null = null;1535        if (origin) {1536          try {1537            const hostname = new URL(origin).hostname;1538            senderDomain = extractDomain(hostname) ?? hostname;1539          } catch {1540            senderDomain = null;1541          }1542        }1543        if (typeof domain !== "string" || domain.length > 253 || domain !== senderDomain) {1544          return { ok: false, error: "invalid_domain" };1545        }1546        const settings = vault.getSettings();1547        const existing = settings.manualSummonDomains?.[domain];1548        const now = Date.now();1549        await vault.updateSettings({1550          manualSummonDomains: {1551            ...settings.manualSummonDomains,1552            [domain]: {1553              firstSummonedAt: existing?.firstSummonedAt ?? now,1554              summonCount: (existing?.summonCount ?? 0) + 1,1555              lastSummonedAt: now,1556            },1557          },1558        });1559        return { ok: true };1560      }1561      case "DECLINE_CARD_SAVE": {1562        // PB-26-108: the declined-card digest is keyed by root-key material, so1563        // a decline cannot be recorded while locked. Offers are not shown while1564        // locked either, so this is unreachable in practice.1565        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1566        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1567        await vault.declineCardSaveOffer(last4, expMonth, expYear);1568        return { ok: true };1569      }1570      case "IS_CARD_DECLINED": {1571        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1572        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1573        return { ok: true, data: declined };1574      }1575      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1576        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1577          rpId?: string;1578          rpName?: string;1579          userName?: string;1580          userDisplayName?: string;1581        };1582        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1583        return await initiateFirefoxPasskeyCreate({1584          rpId,1585          rpName: rpName ?? rpId,1586          userName,1587          userDisplayName,1588        }, attestedSenderOrigin(sender));1589      }15901591      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1592        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1593        if (!payload) return { ok: false, error: "missing_payload" };1594        return await completeFirefoxPasskeyCreate(payload);1595      }15961597      case "PASSKEY_OFFER_DECLINE": {1598        const { domain } = (msg.payload ?? {}) as { domain?: string };1599        const origin = attestedSenderOrigin(sender);1600        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1601        await recordPasskeyOfferDecline(domain);1602        return { ok: true };1603      }16041605      case "GET_PASSKEY_OFFER_DECLINED": {1606        const { domain } = (msg.payload ?? {}) as { domain?: string };1607        const origin = attestedSenderOrigin(sender);1608        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1609        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1610      }16111612      case "PASSKEY_HAS_CREDENTIALS": {1613        const payload = msg.payload as {1614          rpId?: string;1615          allowCredentials?: Array<{ id: string; type?: string }>;1616        } | undefined;1617        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1618        return await handlePasskeyHasCredentials({1619          rpId: payload.rpId,1620          allowCredentials: payload.allowCredentials ?? [],1621        }, attestedSenderOrigin(sender));1622      }16231624      case "PASSKEY_CREATE": {1625        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1626        if (!payload?.rpId || !payload?.userName) {1627          return { ok: false, error: "rpid_and_username_required" };1628        }1629        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1630      }16311632      case "PASSKEY_GET": {1633        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1634        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1635        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1636      }16371638      case "PASSKEY_AUTH_RESPONSE": {1639        const { requestId, approved } = (msg.payload ?? {}) as {1640          requestId?: string | number;1641          approved?: boolean;1642        };1643        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1644          return { ok: false, error: 'requestId and approved required' };1645        }1646        const pending = await getPendingPasskeyRequest();1647        const senderOrigin = attestedSenderOrigin(sender);1648        if (1649          !pending ||1650          pending.tabId === undefined ||1651          pending.crossOrigin === true ||1652          pending.requestId !== Number(requestId) ||1653          sender.tab?.id !== pending.tabId ||1654          senderOrigin !== pending.origin1655        ) {1656          return { ok: false, error: "invalid_passkey_approval_sender" };1657        }1658        await resolvePendingPasskeyRequest(Number(requestId), approved);1659        return { ok: true };1660      }16611662      case "GET_PASSKEY_FOR_DOMAIN": {1663        const { domain } = (msg.payload ?? {}) as { domain?: string };1664        if (!domain) return { ok: false, error: "domain_required" };1665        // Scope to the caller's own origin: a page may only ask about passkeys1666        // for a domain it actually owns, so an arbitrary page cannot enumerate1667        // which sites the user holds passkeys for or read the username (audit MEDIUM).1668        const origin = attestedSenderOrigin(sender);1669        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1670        if (!vault.isUnlocked()) return { ok: true, data: null };1671        const match = vault1672          .getEntries()1673          .find((entry) => entry.passkey?.rpId === domain);1674        if (!match || !match.passkey) return { ok: true, data: null };1675        // Slim shape — only the fields State 11 needs. Never expose private1676        // key material, even though this is locked behind isUnlocked.1677        // bannerShown is the per-domain "already surfaced" flag, kept in1678        // trusted background session storage so content scripts never touch1679        // chrome.storage.session directly (PB-26-203).1680        let bannerShown = false;1681        if (chrome.storage.session) {1682          const flag = await chrome.storage.session.get(`peach_state11_shown:${domain}`);1683          bannerShown = Boolean((flag as Record<string, unknown>)[`peach_state11_shown:${domain}`]);1684        }1685        return {1686          ok: true,1687          data: {1688            rpId: match.passkey.rpId,1689            userName: match.passkey.userName,1690            browser: match.passkey.browser,1691            bannerShown,1692          },1693        };1694      }16951696      case "MARK_PASSKEY_BANNER_SHOWN": {1697        const { domain } = (msg.payload ?? {}) as { domain?: string };1698        if (typeof domain !== "string" || !domain) return { ok: false, error: "domain_required" };1699        // Same origin binding as the read path: a page may only mark its own1700        // domain, and the flag reveals nothing either way.1701        const origin = attestedSenderOrigin(sender);1702        if (!origin || !isValidRpId(domain, origin)) return { ok: true };1703        if (chrome.storage.session) {1704          await chrome.storage.session.set({ [`peach_state11_shown:${domain}`]: Date.now() });1705        }1706        return { ok: true };1707      }17081709      case "DESTROY_VAULT": {1710        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1711        // storage.local.clear() wipes every Peach key (slots, settings, license,1712        // onboarded flag, history, sync state, declined cards, recall, etc.);1713        // session.clear() wipes pending passkey requests + pro-notice queues.1714        // Caller (Panic.tsx) handles UI navigation back to onboarding.1715        //1716        // The Pro license is the one thing that must survive: the user paid for1717        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1718        // Capture it before the clear and restore it after. peach_pro_celebrated1719        // rides along so the Pro celebration doesn't replay on the next unlock.1720        await vault.withVaultRemoval(async () => {1721          const preserved = await chrome.storage.local.get([1722            "peach_license",1723            "peach_pro_celebrated",1724          ]);1725          await storageClear();1726          await vault.clearVaultHistory();1727          const toRestore: Record<string, unknown> = {};1728          if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1729          if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1730          if (Object.keys(toRestore).length > 0) {1731            await chrome.storage.local.set(toRestore);1732          }1733          if (chrome.storage.session) {1734            await chrome.storage.session.clear();1735          }1736          await clearRecoveryConfirmPending();1737        });1738        return { ok: true };1739      }17401741      case "GET_IDENTITY_SUGGESTIONS": {1742        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1743        const entries = vault.getEntries();1744        const suggestions = buildIdentitySuggestions(entries);1745        return { ok: true, data: { suggestions } };1746      }1747      case "ML_INIT":1748        return { ok: true };17491750      case "ML_PREDICT_BATCH": {1751        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1752        if (!isValidMLFeatureBatch(featuresArray, MAX_ML_BATCH_FIELDS)) {1753          return { ok: false, error: "invalid_payload" };1754        }1755        if (!claimMLWork(sender, featuresArray.length)) {1756          return { ok: false, error: "rate_limited" };1757        }1758        return { ok: true, data: mlPredictBatch(featuresArray) };1759      }17601761      // ── Vault sync (v3) ───────────────────────────────────────────────1762      // Returns the public-facing local identity needed by the popup to1763      // drive Phase-1 audio pairing. The private long-term key never1764      // leaves the background.1765      case "GET_LOCAL_IDENTITY": {1766        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1767        // Pro license from an already-Pro peer (at least one device must be Pro).1768        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1769        // The identity is sealed under its own key rather than derived from the1770        // root, so pairing survives a master-password change (SEV-2-B).1771        const identity: LocalDeviceIdentity & { license?: string } = await buildLocalIdentity();1772        // If this device is Pro, advertise the signed license so the peer can1773        // activate it after SAS confirmation — pairing carries Pro across.1774        if (await isProUser()) {1775          const license = await getLicenseKey();1776          if (license) identity.license = license;1777        }1778        return { ok: true, data: identity };1779      }17801781      case "LIST_PAIRED_DEVICES": {1782        if (vault.isDecoyMode()) return { ok: true, data: { devices: [] } };1783        try {1784          const devices = await listPairedDevicesV3();1785          return { ok: true, data: { devices } };1786        } catch (err) {1787          if (err instanceof TrustDataCorruptedError) {1788            return { ok: false, error: "trust_data_corrupted" };1789          }1790          throw err;1791        }1792      }17931794      case "RENAME_PAIRED_DEVICE": {1795        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1796        const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string };1797        if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") {1798          return { ok: false, error: "invalid_payload" };1799        }1800        await renamePairedDeviceV3(deviceId, name);1801        return { ok: true };1802      }18031804      case "UNPAIR_DEVICE": {1805        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1806        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1807        if (typeof deviceId !== "string" || !deviceId) {1808          return { ok: false, error: "invalid_payload" };1809        }1810        // A damaged legacy identity must not prevent the user from evicting a1811        // peer locally. Sync is already blocked until the secure reset repairs1812        // this installation, so the local issuer marker is sufficient for the1813        // tombstone that will be cleared with the archived generation.1814        await revokeDeviceByIdV3(deviceId, async () => {1815          try {1816            return await getExistingDeviceId();1817          } catch (error) {1818            if (!(error instanceof Error) || error.message !== "identity_migration_required") throw error;1819            return "local";1820          }1821        });1822        // PB-26-213: forget the secret now so no further dial can use it.1823        // Removals that happen while locked leave orphans for the next1824        // unlock's reconcile to prune.1825        const unpairRootHex = vault.getRootKeyHex();1826        if (unpairRootHex) {1827          const unpairRoot = unhexBytes(unpairRootHex);1828          try {1829            await dropPairSecret(deviceId, unpairRoot);1830          } finally {1831            unpairRoot.fill(0);1832          }1833        } else {1834          await dropPairSecret(deviceId, null);1835        }1836        // Sync against the remaining hosts — the unpaired device no longer1837        // matters but the next alarm tick is up to ten minutes away.1838        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1839        return { ok: true };1840      }18411842      case "RENAME_LOCAL_DEVICE": {1843        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1844        const { name } = (msg.payload ?? {}) as { name?: string };1845        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1846        await setDeviceNameV3(name);1847        return { ok: true };1848      }18491850      // ── Relay pairing ─────────────────────────────────────────────────────1851      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1852      // session runs in the background; the SAS and the terminal result reach1853      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1854      case "START_ADOPTION_SOURCE": {1855        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1856        if (isRelayAdoptionSourceInFlight()) {1857          return { ok: false, error: "adoption_source_in_progress" };1858        }1859        try {1860          return { ok: true, data: await startRelayAdoptionSource() };1861        } catch (error) {1862          return {1863            ok: false,1864            error: error instanceof Error ? error.message : "adoption_source_failed",1865          };1866        }1867      }18681869      // Onboarding receiver — empty extension shows a QR, phone scans and1870      // sends the vault. The popup supplies the local-only password here so1871      // the background can wrap the adopted root key at rest without ever1872      // asking the user to retype it.1873      case "START_ADOPTION_RECEIVER": {1874        if (isRelayAdoptionSourceInFlight()) {1875          return { ok: false, error: "adoption_receiver_in_progress" };1876        }1877        const password = (msg.payload as { password?: unknown } | undefined)?.password;1878        if (typeof password !== "string" || password.length === 0) {1879          return { ok: false, error: "invalid_payload" };1880        }1881        try {1882          return { ok: true, data: await startRelayAdoptionReceiver(password) };1883        } catch (error) {1884          return {1885            ok: false,1886            error: error instanceof Error ? error.message : "adoption_receiver_failed",1887          };1888        }1889      }18901891      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1892      // on the source's SAS screen. The id round-trips the same way so a stale1893      // late response can't approve the wrong session.1894      case "RECEIVER_SAS_DECISION": {1895        const payload = msg.payload as { id?: unknown; sas?: unknown; ok?: unknown } | undefined;1896        if (typeof payload?.id !== "string" || typeof payload.sas !== "string" || typeof payload.ok !== "boolean") {1897          return { ok: false, error: "invalid_payload" };1898        }1899        return { ok: resolveReceiverSasConfirmation(payload.id, payload.sas, payload.ok) };1900      }19011902      case "SOURCE_SAS_DECISION": {1903        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1904        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1905          return { ok: false, error: "invalid_payload" };1906        }1907        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1908      }1909      case "LIST_PENDING_ADOPTION_HOLDERS": {1910        return { ok: true, data: await listPendingAdoptionHolders() };1911      }19121913      case "REMOVE_PENDING_ADOPTION_HOLDER": {1914        await removePendingAdoptionHolder();1915        return { ok: true };1916      }191719181919      case "CANCEL_ADOPTION_SOURCE": {1920        cancelRelayAdoptionSource();1921        return { ok: true };1922      }19231924      case "TRIGGER_SYNC": {1925        if (vault.isDecoyMode()) return { ok: true };1926        const payload = (msg.payload ?? {}) as {1927          reason?: "vault_change" | "foreground" | "manual";1928          force?: boolean;1929        };1930        const reason = payload.reason ?? "foreground";19311932        void triggerSyncIfReachable({ reason, force: payload.force === true });1933        return { ok: true };1934      }19351936      case "GET_SYNC_STATE": {1937        if (vault.isDecoyMode()) return { ok: true, data: { status: "idle" } };1938        return { ok: true, data: getSyncState() };1939      }19401941      // §11. The generation state carries no secret — it is a version and a1942      // state name — so the panel can read it while the vault is locked.1943      case "GET_SYNC_GENERATION": {1944        return { ok: true, data: await resolveGeneration(browserGenerationIo) };1945      }19461947      case "SECURE_RESET": {1948        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1949        const payload = (msg.payload ?? {}) as { password?: unknown };1950        if (typeof payload.password !== "string" || payload.password.length === 0) {1951          return { ok: false, error: "Enter your master password" };1952        }1953        const wasLocked = !vault.isUnlocked();1954        const passwordValid = wasLocked1955          ? await vault.unlock(payload.password)1956          : await vault.verifyMainPassword(payload.password);1957        if (!passwordValid) {1958          return { ok: false, error: "Incorrect master password" };1959        }1960        if (wasLocked) {1961          await setupAutoLock();1962          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });1963          onVaultUnlocked();1964        }1965        // Identity rotation needs the live vault root key. A password check is1966        // deliberately verification-only, so establish the real session first1967        // when Settings is opened after the vault session expired.1968        const result = await confirmSecureReset(browserGenerationIo, {1969          nowMs: Date.now(),1970        });1971        if (result === "V2_ANCHOR") return { ok: true, data: await resolveGeneration(browserGenerationIo) };1972        return {1973          ok: false,1974          error: result === "reset_archive_review_required"1975            ? "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."1976            : "The reset did not complete. Try again; if it still fails, contact Peach support.",1977        };1978      }19791980      case "GET_SYNC_SETTINGS": {1981        if (vault.isDecoyMode()) return { ok: true, data: { mode: "off", relayUrl: "" } };1982        return { ok: true, data: await getSyncSettings() };1983      }19841985      case "SET_SYNC_SETTINGS": {1986        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1987        const payload = (msg.payload ?? {}) as {1988          mode?: unknown;1989          relayUrl?: unknown;1990        };1991        try {1992          // A custom relay URL implies private mode; Peach's own relay stays1993          // public. See setRelayUrl.1994          if (payload.relayUrl !== undefined) {1995            if (typeof payload.relayUrl !== "string") {1996              return { ok: false, error: "invalid_relay_url" };1997            }1998            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1999          }2000          if (payload.mode !== undefined) {2001            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {2002              return { ok: false, error: "invalid_sync_mode" };2003            }2004            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };2005          }2006          return { ok: true, data: await getSyncSettings() };2007        } catch (error) {2008          return {2009            ok: false,2010            error: error instanceof Error ? error.message : "invalid_relay_url",2011          };2012        }2013      }201420152016      case "GET_SYNC_ALERTS": {2017        if (vault.isDecoyMode()) return { ok: true, data: [] };2018        return { ok: true, data: await getPendingSyncAlerts() };2019      }20202021      case "DISMISS_SYNC_ALERTS": {2022        if (vault.isDecoyMode()) return { ok: true };2023        const type = (msg.payload as { type?: unknown } | undefined)?.type;2024        if (type !== "DEVICE_KEY_ROTATED" && type !== "DEVICE_REVOKED") {2025          return { ok: false, error: "invalid_sync_alert_type" };2026        }2027        await dismissPendingSyncAlerts(type);2028        return { ok: true };2029      }20302031      case "GET_PENDING_VOUCHED_DEVICES": {2032        if (vault.isDecoyMode()) return { ok: true, data: [] };2033        return { ok: true, data: await listPendingVouchedDevices() };2034      }2035      case "CONFIRM_VOUCHED_DEVICE": {2036        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };2037        const { deviceId } = msg.payload as { deviceId: string };2038        const pending = await getPendingVouchedDevice(deviceId);2039        if (!pending) return { ok: false, error: "not_pending" };2040        // Last gate before a vouched device becomes a sync peer. A queue entry2041        // can predate the revocation that names it, so revocation is re-checked2042        // here rather than trusted to have swept the queue.2043        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {2044          await removePendingVouchedDevice(deviceId);2045          return { ok: false, error: "device_revoked" };2046        }2047        await upsertPairedDeviceV3({2048          deviceId: pending.deviceId,2049          deviceName: pending.deviceName,2050          deviceType:2051            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],2052          longTermPublicKeyHex: pending.longTermPublicKeyHex,2053          signingPublicKeyHex: pending.signingPublicKeyHex,2054          wsPort: pending.wsPort,2055          pairedAt: pending.pairedAt,2056          trustSource: "vouched",2057        });2058        await removePendingVouchedDevice(deviceId);2059        // Newly confirmed vouched device is now a sync target — kick a round2060        // so the mesh introduction pays off without a 10-minute wait.2061        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);2062        return { ok: true };2063      }2064      case "REJECT_VOUCHED_DEVICE": {2065        if (vault.isDecoyMode()) return { ok: true };2066        const { deviceId } = msg.payload as { deviceId: string };2067        await removePendingVouchedDevice(deviceId);2068        return { ok: true };2069      }20702071      case "ROTATE_SYNC_IDENTITY": {2072        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };2073        const epoch = vault.getVaultEpoch();2074        const { password } = (msg.payload ?? {}) as { password?: unknown };2075        if (typeof password !== "string" || !password) return { ok: false, error: "password_required" };2076        const verified = await vault.verifyMainPassword(password);2077        if (!vault.isUnlocked() || epoch !== vault.getVaultEpoch()) return { ok: false, error: "vault_locked" };2078        if (!verified) return { ok: false, error: "wrong_password" };2079        const result = await vault.rotateSyncIdentity();2080        return result.ok ? { ok: true } : { ok: false, error: result.error };2081      }20822083      default:2084        return { ok: false, error: "unknown_message_type" };2085    }2086  } catch (err) {2087    return {2088      ok: false,2089      error: err instanceof Error ? err.message : "operation_failed",2090    };2091  }2092}20932094// Returns username use-counts from the vault, sorted by frequency. Each row2095// also carries the entry's email so the popup can suggest the email/username2096// pair the user has actually used together.2097function buildIdentitySuggestions(2098  entries: VaultEntry[],2099): Array<{ email: string; username: string; count: number }> {2100  const usernameCounts = new Map<string, number>();2101  const usernameEmail = new Map<string, string>();2102  for (const entry of entries) {2103    const username = entry.username ?? "";2104    const email = (entry as VaultEntry & { email?: string }).email ?? "";2105    if (!username && !email) continue;2106    const key = username || email;2107    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);2108    if (!usernameEmail.has(key)) usernameEmail.set(key, email);2109  }2110  return Array.from(usernameCounts.entries())2111    .sort((a, b) => b[1] - a[1])2112    .map(([username, count]) => ({2113      email: usernameEmail.get(username) ?? "",2114      username,2115      count,2116    }));2117}21182119/** Notify all content scripts that the vault just became available. */2120function broadcastToContentScripts(message: { type: string }): void {2121  if (!chrome.tabs?.query) return;2122  chrome.tabs.query({}, (tabs) => {2123    for (const tab of tabs) {2124      if (tab.id !== undefined) {2125        chrome.tabs.sendMessage(tab.id, message).catch(() => {2126          // Tab may not have a content script — silently ignore2127        });2128      }2129    }2130  });2131}21322133function shouldRefreshAutoLock(2134  type: MessageType,2135  sender: Partial<chrome.runtime.MessageSender>,2136): boolean {2137  if (!isExtensionPageSender(sender)) return false;2138  return (2139    type !== "HAS_VAULT" &&2140    type !== "IS_UNLOCKED" &&2141    type !== "GET_VAULT_STATUS" &&2142    type !== "LOCK" &&2143    type !== "UPDATE_SETTINGS" &&2144    type !== "GET_PENDING_PASSKEY" &&2145    type !== "GET_PASSKEY_PROVIDER_STATE" &&2146    type !== "DECLINE_CARD_SAVE" &&2147    type !== "IS_CARD_DECLINED" &&2148    type !== "AUTOFILL_QUERY" &&2149    type !== "ML_PREDICT_BATCH"2150  );2151}21522153function canaryWebhookUrl(value: unknown): string | null {2154  if (typeof value !== "string") return null;2155  try {2156    const url = new URL(value);2157    if (url.protocol !== "https:" || url.username || url.password) return null;2158    const host = url.hostname.toLowerCase().replace(/\.+$/, "");2159    if (!host || host === "localhost" || host.endsWith(".localhost")) return null;2160    if (host.startsWith("[")) {2161      if (isUnsafeCanaryIpv6(host.slice(1, -1))) return null;2162    } else if (/^\d+(?:\.\d+){3}$/.test(host) && isUnsafeCanaryIpv4(host)) return null;2163    url.hostname = host;2164    return url.href;2165  } catch { return null; }2166}21672168function isUnsafeCanaryIpv4(host: string): boolean {2169  const [a, b, c, d] = host.split(".").map(Number);2170  return a === 0 || a === 10 || a === 127 || a >= 224 ||2171    (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) ||2172    (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) ||2173    (a === 192 && b === 0 && c === 0 && d !== 9 && d !== 10) ||2174    (a === 192 && b === 0 && c === 2) || (a === 192 && b === 88 && c === 99) ||2175    (a === 198 && (b === 18 || b === 19 || (b === 51 && c === 100))) ||2176    (a === 203 && b === 0 && c === 113);2177}21782179function isUnsafeCanaryIpv6(host: string): boolean {2180  const [head, tail = ""] = host.split("::");2181  const left = head ? head.split(":").map(value => Number.parseInt(value, 16)) : [];2182  const right = tail ? tail.split(":").map(value => Number.parseInt(value, 16)) : [];2183  const words = [...left, ...Array<number>(8 - left.length - right.length).fill(0), ...right];2184  if (words.slice(0, 5).every(word => word === 0) && words[5] === 0xffff) {2185    return isUnsafeCanaryIpv4(`${words[6] >>> 8}.${words[6] & 255}.${words[7] >>> 8}.${words[7] & 255}`);2186  }2187  // Native global-unicast literals only; transition formats are conservative exclusions.2188  if ((words[0] & 0xe000) !== 0x2000 || words[0] === 0x2002) return true;2189  if (words[0] === 0x3fff && (words[1] & 0xf000) === 0) return true;2190  if (words[0] !== 0x2001) return false;2191  if (words[1] === 0xdb8) return true;2192  if ((words[1] & 0xfe00) !== 0) return false;2193  const globalAssignment = words[1] === 3 || (words[1] === 4 && words[2] === 0x112) ||2194    (words[1] & 0xfff0) === 0x20 || (words[1] & 0xfff0) === 0x30 ||2195    (words[1] === 1 && words.slice(2, 7).every(word => word === 0) && [1, 2, 3].includes(words[7]));2196  return !globalAssignment;2197}