messages.ts

97.6 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard, getEffectiveClearSeconds } from "./clipboard";13import { 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        // PB-26-949: this reply is an allowlist, not the stored entry minus a1163        // few exclusions. Content scripts run in the page's world, so a field1164        // this projection never names cannot leak when VaultEntry grows one.1165        // Every key below is read by a fill or selector path; add a key only1166        // together with the consumer that needs it.1167        const fillProjection = {1168          id: entry.id,1169          title: entry.title, // inject.ts inline edit form1170          username: entry.username, // index.ts handleAutofill, inline edit1171          email: entry.email, // index.ts handleAutofill, inline edit1172          password: entry.password, // fill + copy paths1173          url: entry.url, // inject.ts inline edit, remember-site check1174          additionalUrls: entry.additionalUrls, // remember-site check1175          cardholderName: entry.cardholderName, // card fill1176          cardNumber: entry.cardNumber, // card fill, copy number1177          expMonth: entry.expMonth, // card fill1178          expYear: entry.expYear, // card fill1179          cvc: entry.cvc, // card fill, copy CVC1180        };1181        // The raw base32 TOTP seed never leaves the background (SEV-3-C):1182        // handing it over would let a compromised content script mint valid1183        // codes indefinitely. Generate the *current* 6-digit code here and send1184        // only that, plus the seconds left so the UI can render a countdown.1185        const seed = entry.totp;1186        let totpCode: string | undefined;1187        let totpRemaining: number | undefined;1188        if (seed) {1189          try {1190            // PCH-01-019: honour stored algorithm/digits/period (defaults apply1191            // when these are undefined, i.e. RFC-default bare-seed entries).1192            const generated = generateTOTP(seed, entry.totpAlgorithm, entry.totpDigits, entry.totpPeriod);1193            totpCode = generated.code;1194            totpRemaining = generated.remaining;1195          } catch {1196            totpCode = undefined;1197          }1198        }1199        if (isPageSender(sender) && vault.isUnlocked()) touchAutoLock();1200        return { ok: true, data: { ...fillProjection, totpCode, totpRemaining } };1201      }1202      // Trusted full-entry fetch for extension-owned edit surfaces. Content1203      // scripts route editing to the popup and cannot call this message.1204      case "GET_ENTRY_FOR_EDIT": {1205        if (isPageSender(sender)) return { ok: false, error: "invalid_sender" };1206        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1207        const { id } = msg.payload as { id: string };1208        const entry = vault.getEntryById(id);1209        if (!entry) return { ok: false, error: "entry_not_found" };12101211        const { passkey: _passkey, ...safeEntry } = entry;1212        return { ok: true, data: safeEntry };1213      }1214      case "COPY": {1215        // Page relays must carry the browser-attested frame origin, as with1216        // SUMMON/fill. The policy admits content scripts; this binds the1217        // admitted page sender before arming clipboard auto-clear.1218        if (isPageSender(sender) && !attestedSenderOrigin(sender)) {1219          return { ok: false, error: "invalid_sender" };1220        }1221        // AUD-002: shape-validate the payload before passing to the clipboard1222        // helper. A raw cast lets a malformed message reach the clipboard API1223        // with a non-string and throw.1224        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {1225          text?: unknown;1226          label?: unknown;1227          alreadyWritten?: unknown;1228        };1229        if (typeof text !== "string" || typeof label !== "string") {1230          return { ok: false, error: "invalid_payload" };1231        }1232        await copyToClipboard(text, label, Boolean(alreadyWritten));1233        return { ok: true, clearSeconds: getEffectiveClearSeconds() };1234      }1235      case "CHECK_ALL_BREACHES": {1236        return { ok: true, data: vault.startBreachScan() };1237      }1238      case "GET_BREACH_SCAN_STATUS": {1239        return { ok: true, data: vault.getBreachScanStatus() };1240      }1241      case "GET_SETTINGS": {1242        const settings = await vault.ensureSettingsLoaded();1243        if (!isPageSender(sender)) return { ok: true, data: settings };12441245        const safeSettings: Pick<vault.VaultSettings, "accentColor" | "theme"> & {1246          manualSummonDomains?: NonNullable<vault.VaultSettings["manualSummonDomains"]>;1247        } = {1248          accentColor: settings.accentColor,1249          theme: settings.theme,1250        };1251        const domain = attestedSenderDomain(sender);1252        const ownSummon = domain ? vault.getManualSummonRecord(domain) : undefined;1253        if (domain && ownSummon) safeSettings.manualSummonDomains = { [domain]: ownSummon };1254        return { ok: true, data: safeSettings };1255      }1256      case "UPDATE_SETTINGS": {1257        const patch = msg.payload;1258        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {1259          return { ok: false, error: "invalid_payload" };1260        }1261        await vault.updateSettings(patch as vault.VaultSettings);1262        if ((patch as Record<string, unknown>).lockedSyncRequiresUnlock === true) {1263          await clearLockedSyncPrivateKey();1264        }1265        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {1266          await setupAutoLock();1267          if (vault.isUnlocked()) touchAutoLock();1268        }1269        return { ok: true };1270      }1271      case "SETUP_PIN": {1272        const { currentPassword, pin } = (msg.payload ?? {}) as {1273          currentPassword?: unknown;1274          pin?: unknown;1275        };1276        if (typeof currentPassword !== "string" || typeof pin !== "string") {1277          return { ok: false, error: "invalid_payload" };1278        }1279        return (await vault.setupPinUnlock(currentPassword, pin))1280          ? { ok: true }1281          : { ok: false, error: "incorrect_current_password" };1282      }1283      case "DISABLE_PIN": {1284        const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown };1285        if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" };1286        return (await vault.disablePinUnlock(currentPassword))1287          ? { ok: true }1288          : { ok: false, error: "incorrect_current_password" };1289      }1290      case "GET_PENDING_PASSKEY":1291        return { ok: true, data: await getPendingPasskeyRequest() };1292      case "APPROVE_PASSKEY": {1293        const { requestId } = msg.payload as { requestId: number };1294        await resolvePendingPasskeyRequest(requestId, true);1295        return { ok: true };1296      }1297      case "DENY_PASSKEY": {1298        const { requestId } = msg.payload as { requestId: number };1299        await resolvePendingPasskeyRequest(requestId, false);1300        return { ok: true };1301      }1302      case "GET_PASSKEY_PROVIDER_STATE":1303        return { ok: true, data: await getPasskeyProviderState() };1304      case "SET_PASSKEY_PROVIDER_ENABLED": {1305        const { enabled } = msg.payload as { enabled: boolean };1306        // Disabling is always free; gating fires only when a free user is1307        // trying to turn passkey interception on.1308        if (enabled) {1309          const gate = await requirePro("passkeys");1310          if (!gate.allowed) return { ok: false, error: "pro_required" };1311        }1312        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };1313      }1314      case "FIRE_CANARY_PING": {1315        const payload = msg.payload;1316        if (!payload || typeof payload !== "object" || Array.isArray(payload)) return { ok: false, error: "invalid_payload" };1317        const { id, trigger, capability, webhookUrl: draftUrl, entryTitle } = payload as {1318          id?: unknown; trigger?: unknown; capability?: unknown; webhookUrl?: unknown; entryTitle?: unknown;1319        };1320        if (trigger === "test" && !isExtensionPageSender(sender)) return { ok: false, error: "invalid_sender" };1321        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1322        if (trigger === "test") {1323          if (typeof entryTitle !== "string") return { ok: false, error: "invalid_payload" };1324          const webhookUrl = canaryWebhookUrl(draftUrl);1325          if (!webhookUrl) return { ok: false, error: "invalid_webhook_url" };1326          try {1327            const response = await fetch(webhookUrl, { method: "POST", headers: { "Content-Type": "application/json" },1328              body: canaryBody(entryTitle, "test"), redirect: "error" });1329            return { ok: response.ok, error: response.ok ? undefined : `HTTP ${response.status}` };1330          } catch { return { ok: false, error: "network_error" }; }1331        }1332        if (typeof id !== "string" || !id || typeof trigger !== "string" || !["accessed", "password_copied", "username_copied", "autofilled", "submitted"].includes(trigger) ||1333          Object.keys(payload).some(key => !["id", "trigger", "capability"].includes(key))) return { ok: false, error: "invalid_payload" };1334        const capabilityAuthorized = capability !== undefined && consumeSummonCapability(capability, sender, "fill");1335        const domain = isPageSender(sender) ? attestedSenderDomain(sender) : null;1336        if (isPageSender(sender) && !domain) return { ok: false, error: "origin_unverified" };1337        const entry = vault.getEntryById(id);1338        if (!entry || (domain && !capabilityAuthorized && !entryDomains(entry.url, entry.additionalUrls).has(domain))) {1339          return { ok: false, error: "entry_not_found" };1340        }1341        return fireStoredCanary(entry, trigger as CanaryTrigger);1342      }1343      case "ACTIVATE_LICENSE": {1344        const { key } = msg.payload as { key: string };1345        const licenseInfo = await activateLicense(key);1346        return { ok: true, data: licenseInfo };1347      }1348      case "GET_LICENSE": {1349        const licenseInfo = await getLicenseInfo();1350        return { ok: true, data: licenseInfo };1351      }1352      case "GET_LICENSE_KEY": {1353        const key = await getLicenseKey();1354        return { ok: true, data: key };1355      }1356      case "DEACTIVATE_LICENSE": {1357        await deactivateLicense();1358        return { ok: true };1359      }1360      case "SHOULD_PLAY_CELEBRATION": {1361        const should = await shouldPlayCelebration();1362        return { ok: true, data: should };1363      }1364      case "MARK_CELEBRATION_PLAYED": {1365        await markCelebrationPlayed();1366        return { ok: true };1367      }1368      case "GET_CODEX_VAULT_DATA": {1369        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1370        // popup navigates to the License section without further coordination.1371        // Also privileged-page-gated (PB-26-001), and recoveryWords inside the1372        // snapshot additionally require a fresh master-password proof.1373        const gate = await requirePro("codex");1374        if (!gate.allowed) return { ok: false, error: "pro_required" };1375        const { password } = (msg.payload ?? {}) as { password?: string };1376        return await handleGetCodexVaultData(password);1377      }1378      case "ESTIMATE_CODEX_PAGES": {1379        const gate = await requirePro("codex");1380        if (!gate.allowed) return { ok: false, error: "pro_required" };1381        return await handleEstimateCodexPages();1382      }1383      case "RESTORE_FROM_CODEX": {1384        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1385        // be able to restore a vault that was printed by a Pro user.1386        // DO NOT add a Pro gate here.1387        // A decoy session, though, holds no real-mode authority: this path1388        // writes SLOT_A/SLOT_B and snapshots history, so it carries the same1389        // guard its thirteen neighbours do (PB-26-915).1390        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1391        const payload = msg.payload as CodexRestorePayload;1392        return await handleRestoreFromCodex(payload);1393      }1394      case "OPEN_PRO_GATE": {1395        // Content script requests: open popup and navigate to License section.1396        const { feature } = (msg.payload ?? {}) as { feature?: string };1397        if (chrome.storage.session) {1398          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1399        }1400        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1401        return { ok: true };1402      }1403      case "OPEN_POPUP": {1404        // Content script asks to open the trusted extension popup — used by the1405        // inline locked bubble so the master password is entered in the popup,1406        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1407        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1408        // toolbar icon. The badge already signals Peach needs attention.1409        //1410        // Set a session flag so the popup knows it was opened for inline unlock1411        // and should close itself once the vault is unlocked (returning the user1412        // to the inline autofill selector on the page).1413        const { entryId } = (msg.payload ?? {}) as { entryId?: unknown };1414        if (entryId !== undefined && (typeof entryId !== "string" || entryId.length === 0 || entryId.length > 64)) {1415          return { ok: false, error: "invalid_payload" };1416        }1417        if (chrome.storage.session) {1418          if (typeof entryId === "string") {1419            await chrome.storage.session.set({ peach_open_entry: entryId });1420          } else {1421            await chrome.storage.session.set({ peach_inline_unlock: true });1422          }1423        }1424        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1425        return { ok: true };1426      }1427      case "OPEN_DETACHED_POPUP": {1428        // A window created by the action popup and then orphaned with1429        // window.close() is cascaded shut by Chrome, so the file-picker1430        // flows (OS dialogs that dismiss the popup on focus loss) ask the SW1431        // to open the standalone window instead — the SW has no window to be1432        // associated with. The query string is allowlisted so this can never1433        // open an arbitrary URL.1434        const { route } = (msg.payload ?? {}) as { route?: string };1435        const search = route === "peachscript"1436          ? "?restore=peachscript"1437          : route === "csv"1438            ? "?restore=csv"1439            : route === "codex-pdf"1440              ? "?codex=pdf"1441              : null;1442        if (!search) return { ok: false, error: "bad_route" };1443        try {1444          const popupHtml =1445            chrome.runtime.getManifest().action?.default_popup ?? "src/popup/index.html";1446          await chrome.windows.create({1447            url: chrome.runtime.getURL(`${popupHtml}${search}`),1448            type: "popup",1449            width: 320,1450            height: 550,1451          });1452          return { ok: true, data: { detached: true } };1453        } catch {1454          return { ok: false };1455        }1456      }1457      case "GET_IDENTITIES": {1458        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1459        return { ok: true, data: vault.getIdentities() };1460      }1461      case "TOUCH_AUTO_LOCK": {1462        // touchAutoLock() is already called by shouldRefreshAutoLock above;1463        // this case just gives the popup a typed message to keep the session alive.1464        return { ok: true };1465      }1466      case "GET_ADVANCED_HEALTH_REPORT": {1467        const gate = await requirePro("advanced_health");1468        if (!gate.allowed) return { ok: false, error: "pro_required" };1469        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1470        const report = await buildAdvancedHealthReport(vault.getEntries());1471        return { ok: true, data: report };1472      }1473      case "IS_DURESS_ENABLED": {1474        const enabled = await vault.isDuressEnabled();1475        return { ok: true, data: enabled };1476      }1477      case "SETUP_DURESS": {1478        // Single enforcement point for the Duress Vault Pro gate. Free users1479        // who somehow reach this handler are rejected here; the popup also1480        // pre-checks isPro() to avoid showing the setup form to free users,1481        // but server-side is the actual security boundary.1482        const gate = await requirePro("duress_vault");1483        if (!gate.allowed) return { ok: false, error: "pro_required" };1484        // MV3 service workers restart after inactivity, losing the in-memory1485        // derived key. Detect this before calling setupDuress so the popup1486        // can show a meaningful prompt to re-lock and re-unlock.1487        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1488        const { duressPassword } = msg.payload as { duressPassword: string };1489        await vault.setupDuress(duressPassword);1490        return { ok: true };1491      }1492      case "DISABLE_DURESS": {1493        await vault.disableDuress();1494        return { ok: true };1495      }1496      case "VERIFY_MAIN_PASSWORD": {1497        const { password } = msg.payload as { password: string };1498        const ok = await vault.verifyMainPassword(password);1499        return { ok: true, data: ok };1500      }1501      case "CHANGE_PASSWORD": {1502        const { currentPassword, newPassword } = msg.payload as {1503          currentPassword: string;1504          newPassword: string;1505        };1506        const changed = await vault.changePassword(currentPassword, newPassword);1507        return changed1508          ? { ok: true }1509          : { ok: false, error: "incorrect_current_password" };1510      }1511      case "GET_SITE_PASSWORD_POLICY": {1512        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1513        if (!tab?.id) return { ok: true, data: null };1514        try {1515          const response = await chrome.tabs.sendMessage(tab.id, {1516            type: "GET_SITE_PASSWORD_POLICY",1517          });1518          return (response as MessageResponse) ?? { ok: true, data: null };1519        } catch {1520          return { ok: true, data: null };1521        }1522      }1523      case "RECORD_MANUAL_SUMMON": {1524        const { domain } = (msg.payload ?? {}) as { domain?: unknown };1525        const origin = attestedSenderOrigin(sender);1526        let senderDomain: string | null = null;1527        if (origin) {1528          try {1529            const hostname = new URL(origin).hostname;1530            senderDomain = extractDomain(hostname) ?? hostname;1531          } catch {1532            senderDomain = null;1533          }1534        }1535        if (1536          typeof domain !== "string" ||1537          new TextEncoder().encode(domain).length > 253 ||1538          domain !== senderDomain1539        ) {1540          return { ok: false, error: "invalid_domain" };1541        }1542        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1543        await vault.recordManualSummon(domain);1544        return { ok: true };1545      }1546      case "DECLINE_CARD_SAVE": {1547        // PB-26-108: the declined-card digest is keyed by root-key material, so1548        // a decline cannot be recorded while locked. Offers are not shown while1549        // locked either, so this is unreachable in practice.1550        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1551        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1552        await vault.declineCardSaveOffer(last4, expMonth, expYear);1553        return { ok: true };1554      }1555      case "IS_CARD_DECLINED": {1556        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1557        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1558        return { ok: true, data: declined };1559      }1560      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1561        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1562          rpId?: string;1563          rpName?: string;1564          userName?: string;1565          userDisplayName?: string;1566        };1567        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1568        return await initiateFirefoxPasskeyCreate({1569          rpId,1570          rpName: rpName ?? rpId,1571          userName,1572          userDisplayName,1573        }, attestedSenderOrigin(sender));1574      }15751576      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1577        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1578        if (!payload) return { ok: false, error: "missing_payload" };1579        return await completeFirefoxPasskeyCreate(payload);1580      }15811582      case "PASSKEY_OFFER_DECLINE": {1583        const { domain } = (msg.payload ?? {}) as { domain?: string };1584        const origin = attestedSenderOrigin(sender);1585        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1586        await recordPasskeyOfferDecline(domain);1587        return { ok: true };1588      }15891590      case "GET_PASSKEY_OFFER_DECLINED": {1591        const { domain } = (msg.payload ?? {}) as { domain?: string };1592        const origin = attestedSenderOrigin(sender);1593        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1594        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1595      }15961597      case "PASSKEY_HAS_CREDENTIALS": {1598        const payload = msg.payload as {1599          rpId?: string;1600          allowCredentials?: Array<{ id: string; type?: string }>;1601        } | undefined;1602        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1603        return await handlePasskeyHasCredentials({1604          rpId: payload.rpId,1605          allowCredentials: payload.allowCredentials ?? [],1606        }, attestedSenderOrigin(sender));1607      }16081609      case "PASSKEY_CREATE": {1610        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1611        if (!payload?.rpId || !payload?.userName) {1612          return { ok: false, error: "rpid_and_username_required" };1613        }1614        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1615      }16161617      case "PASSKEY_GET": {1618        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1619        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1620        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1621      }16221623      case "PASSKEY_AUTH_RESPONSE": {1624        const { requestId, approved } = (msg.payload ?? {}) as {1625          requestId?: string | number;1626          approved?: boolean;1627        };1628        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1629          return { ok: false, error: 'requestId and approved required' };1630        }1631        const pending = await getPendingPasskeyRequest();1632        const senderOrigin = attestedSenderOrigin(sender);1633        if (1634          !pending ||1635          pending.tabId === undefined ||1636          pending.crossOrigin === true ||1637          pending.requestId !== Number(requestId) ||1638          sender.tab?.id !== pending.tabId ||1639          senderOrigin !== pending.origin1640        ) {1641          return { ok: false, error: "invalid_passkey_approval_sender" };1642        }1643        await resolvePendingPasskeyRequest(Number(requestId), approved);1644        return { ok: true };1645      }16461647      case "GET_PASSKEY_FOR_DOMAIN": {1648        const { domain } = (msg.payload ?? {}) as { domain?: string };1649        if (!domain) return { ok: false, error: "domain_required" };1650        // Scope to the caller's own origin: a page may only ask about passkeys1651        // for a domain it actually owns, so an arbitrary page cannot enumerate1652        // which sites the user holds passkeys for or read the username (audit MEDIUM).1653        const origin = attestedSenderOrigin(sender);1654        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1655        if (!vault.isUnlocked()) return { ok: true, data: null };1656        const match = vault1657          .getEntries()1658          .find((entry) => entry.passkey?.rpId === domain);1659        if (!match || !match.passkey) return { ok: true, data: null };1660        // Slim shape — only the fields State 11 needs. Never expose private1661        // key material, even though this is locked behind isUnlocked.1662        // bannerShown is the per-domain "already surfaced" flag, kept in1663        // trusted background session storage so content scripts never touch1664        // chrome.storage.session directly (PB-26-203).1665        let bannerShown = false;1666        if (chrome.storage.session) {1667          const flag = await chrome.storage.session.get(`peach_state11_shown:${domain}`);1668          bannerShown = Boolean((flag as Record<string, unknown>)[`peach_state11_shown:${domain}`]);1669        }1670        return {1671          ok: true,1672          data: {1673            rpId: match.passkey.rpId,1674            userName: match.passkey.userName,1675            browser: match.passkey.browser,1676            bannerShown,1677          },1678        };1679      }16801681      case "MARK_PASSKEY_BANNER_SHOWN": {1682        const { domain } = (msg.payload ?? {}) as { domain?: string };1683        if (typeof domain !== "string" || !domain) return { ok: false, error: "domain_required" };1684        // Same origin binding as the read path: a page may only mark its own1685        // domain, and the flag reveals nothing either way.1686        const origin = attestedSenderOrigin(sender);1687        if (!origin || !isValidRpId(domain, origin)) return { ok: true };1688        if (chrome.storage.session) {1689          await chrome.storage.session.set({ [`peach_state11_shown:${domain}`]: Date.now() });1690        }1691        return { ok: true };1692      }16931694      case "DESTROY_VAULT": {1695        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1696        // storage.local.clear() wipes every Peach key (slots, settings, license,1697        // onboarded flag, history, sync state, declined cards, recall, etc.);1698        // session.clear() wipes pending passkey requests + pro-notice queues.1699        // Caller (Panic.tsx) handles UI navigation back to onboarding.1700        //1701        // The Pro license is the one thing that must survive: the user paid for1702        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1703        // Capture it before the clear and restore it after. peach_pro_celebrated1704        // rides along so the Pro celebration doesn't replay on the next unlock.1705        await vault.withVaultRemoval(async () => {1706          const preserved = await chrome.storage.local.get([1707            "peach_license",1708            "peach_pro_celebrated",1709          ]);1710          await storageClear();1711          await vault.clearVaultHistory();1712          const toRestore: Record<string, unknown> = {};1713          if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1714          if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1715          if (Object.keys(toRestore).length > 0) {1716            await chrome.storage.local.set(toRestore);1717          }1718          if (chrome.storage.session) {1719            await chrome.storage.session.clear();1720          }1721          await clearRecoveryConfirmPending();1722        });1723        return { ok: true };1724      }17251726      case "GET_IDENTITY_SUGGESTIONS": {1727        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1728        const entries = vault.getEntries();1729        const suggestions = buildIdentitySuggestions(entries);1730        return { ok: true, data: { suggestions } };1731      }1732      case "ML_INIT":1733        return { ok: true };17341735      case "ML_PREDICT_BATCH": {1736        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1737        if (!isValidMLFeatureBatch(featuresArray, MAX_ML_BATCH_FIELDS)) {1738          return { ok: false, error: "invalid_payload" };1739        }1740        if (!claimMLWork(sender, featuresArray.length)) {1741          return { ok: false, error: "rate_limited" };1742        }1743        return { ok: true, data: mlPredictBatch(featuresArray) };1744      }17451746      // ── Vault sync (v3) ───────────────────────────────────────────────1747      // Returns the public-facing local identity needed by the popup to1748      // drive Phase-1 audio pairing. The private long-term key never1749      // leaves the background.1750      case "GET_LOCAL_IDENTITY": {1751        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1752        // Pro license from an already-Pro peer (at least one device must be Pro).1753        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1754        // The identity is sealed under its own key rather than derived from the1755        // root, so pairing survives a master-password change (SEV-2-B).1756        const identity: LocalDeviceIdentity & { license?: string } = await buildLocalIdentity();1757        // If this device is Pro, advertise the signed license so the peer can1758        // activate it after SAS confirmation — pairing carries Pro across.1759        if (await isProUser()) {1760          const license = await getLicenseKey();1761          if (license) identity.license = license;1762        }1763        return { ok: true, data: identity };1764      }17651766      case "LIST_PAIRED_DEVICES": {1767        if (vault.isDecoyMode()) return { ok: true, data: { devices: [] } };1768        try {1769          const devices = await listPairedDevicesV3();1770          return { ok: true, data: { devices } };1771        } catch (err) {1772          if (err instanceof TrustDataCorruptedError) {1773            return { ok: false, error: "trust_data_corrupted" };1774          }1775          throw err;1776        }1777      }17781779      case "RENAME_PAIRED_DEVICE": {1780        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1781        const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string };1782        if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") {1783          return { ok: false, error: "invalid_payload" };1784        }1785        await renamePairedDeviceV3(deviceId, name);1786        return { ok: true };1787      }17881789      case "UNPAIR_DEVICE": {1790        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1791        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1792        if (typeof deviceId !== "string" || !deviceId) {1793          return { ok: false, error: "invalid_payload" };1794        }1795        // A damaged legacy identity must not prevent the user from evicting a1796        // peer locally. Sync is already blocked until the secure reset repairs1797        // this installation, so the local issuer marker is sufficient for the1798        // tombstone that will be cleared with the archived generation.1799        await revokeDeviceByIdV3(deviceId, async () => {1800          try {1801            return await getExistingDeviceId();1802          } catch (error) {1803            if (!(error instanceof Error) || error.message !== "identity_migration_required") throw error;1804            return "local";1805          }1806        });1807        // PB-26-213: forget the secret now so no further dial can use it.1808        // Removals that happen while locked leave orphans for the next1809        // unlock's reconcile to prune.1810        const unpairRootHex = vault.getRootKeyHex();1811        if (unpairRootHex) {1812          const unpairRoot = unhexBytes(unpairRootHex);1813          try {1814            await dropPairSecret(deviceId, unpairRoot);1815          } finally {1816            unpairRoot.fill(0);1817          }1818        } else {1819          await dropPairSecret(deviceId, null);1820        }1821        // Sync against the remaining hosts — the unpaired device no longer1822        // matters but the next alarm tick is up to ten minutes away.1823        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1824        return { ok: true };1825      }18261827      case "RENAME_LOCAL_DEVICE": {1828        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1829        const { name } = (msg.payload ?? {}) as { name?: string };1830        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1831        await setDeviceNameV3(name);1832        return { ok: true };1833      }18341835      // ── Relay pairing ─────────────────────────────────────────────────────1836      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1837      // session runs in the background; the SAS and the terminal result reach1838      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1839      case "START_ADOPTION_SOURCE": {1840        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1841        if (isRelayAdoptionSourceInFlight()) {1842          return { ok: false, error: "adoption_source_in_progress" };1843        }1844        try {1845          return { ok: true, data: await startRelayAdoptionSource() };1846        } catch (error) {1847          return {1848            ok: false,1849            error: error instanceof Error ? error.message : "adoption_source_failed",1850          };1851        }1852      }18531854      // Onboarding receiver — empty extension shows a QR, phone scans and1855      // sends the vault. The popup supplies the local-only password here so1856      // the background can wrap the adopted root key at rest without ever1857      // asking the user to retype it.1858      case "START_ADOPTION_RECEIVER": {1859        if (isRelayAdoptionSourceInFlight()) {1860          return { ok: false, error: "adoption_receiver_in_progress" };1861        }1862        const password = (msg.payload as { password?: unknown } | undefined)?.password;1863        if (typeof password !== "string" || password.length === 0) {1864          return { ok: false, error: "invalid_payload" };1865        }1866        try {1867          return { ok: true, data: await startRelayAdoptionReceiver(password) };1868        } catch (error) {1869          return {1870            ok: false,1871            error: error instanceof Error ? error.message : "adoption_receiver_failed",1872          };1873        }1874      }18751876      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1877      // on the source's SAS screen. The id round-trips the same way so a stale1878      // late response can't approve the wrong session.1879      case "RECEIVER_SAS_DECISION": {1880        const payload = msg.payload as { id?: unknown; sas?: unknown; ok?: unknown } | undefined;1881        if (typeof payload?.id !== "string" || typeof payload.sas !== "string" || typeof payload.ok !== "boolean") {1882          return { ok: false, error: "invalid_payload" };1883        }1884        return { ok: resolveReceiverSasConfirmation(payload.id, payload.sas, payload.ok) };1885      }18861887      case "SOURCE_SAS_DECISION": {1888        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1889        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1890          return { ok: false, error: "invalid_payload" };1891        }1892        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1893      }1894      case "LIST_PENDING_ADOPTION_HOLDERS": {1895        return { ok: true, data: await listPendingAdoptionHolders() };1896      }18971898      case "REMOVE_PENDING_ADOPTION_HOLDER": {1899        await removePendingAdoptionHolder();1900        return { ok: true };1901      }190219031904      case "CANCEL_ADOPTION_SOURCE": {1905        cancelRelayAdoptionSource();1906        return { ok: true };1907      }19081909      case "TRIGGER_SYNC": {1910        if (vault.isDecoyMode()) return { ok: true };1911        const payload = (msg.payload ?? {}) as {1912          reason?: "vault_change" | "foreground" | "manual";1913          force?: boolean;1914        };1915        const reason = payload.reason ?? "foreground";19161917        void triggerSyncIfReachable({ reason, force: payload.force === true });1918        return { ok: true };1919      }19201921      case "GET_SYNC_STATE": {1922        if (vault.isDecoyMode()) return { ok: true, data: { status: "idle" } };1923        return { ok: true, data: getSyncState() };1924      }19251926      // §11. The generation state carries no secret — it is a version and a1927      // state name — so the panel can read it while the vault is locked.1928      case "GET_SYNC_GENERATION": {1929        return { ok: true, data: await resolveGeneration(browserGenerationIo) };1930      }19311932      case "SECURE_RESET": {1933        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1934        const payload = (msg.payload ?? {}) as { password?: unknown };1935        if (typeof payload.password !== "string" || payload.password.length === 0) {1936          return { ok: false, error: "Enter your master password" };1937        }1938        const wasLocked = !vault.isUnlocked();1939        const passwordValid = wasLocked1940          ? await vault.unlock(payload.password)1941          : await vault.verifyMainPassword(payload.password);1942        if (!passwordValid) {1943          return { ok: false, error: "Incorrect master password" };1944        }1945        if (wasLocked) {1946          await setupAutoLock();1947          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });1948          onVaultUnlocked();1949        }1950        // Identity rotation needs the live vault root key. A password check is1951        // deliberately verification-only, so establish the real session first1952        // when Settings is opened after the vault session expired.1953        const result = await confirmSecureReset(browserGenerationIo, {1954          nowMs: Date.now(),1955        });1956        if (result === "V2_ANCHOR") return { ok: true, data: await resolveGeneration(browserGenerationIo) };1957        return {1958          ok: false,1959          error: result === "reset_archive_review_required"1960            ? "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."1961            : "The reset did not complete. Try again; if it still fails, contact Peach support.",1962        };1963      }19641965      case "GET_SYNC_SETTINGS": {1966        if (vault.isDecoyMode()) return { ok: true, data: { mode: "off", relayUrl: "" } };1967        return { ok: true, data: await getSyncSettings() };1968      }19691970      case "SET_SYNC_SETTINGS": {1971        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1972        const payload = (msg.payload ?? {}) as {1973          mode?: unknown;1974          relayUrl?: unknown;1975        };1976        try {1977          // A custom relay URL implies private mode; Peach's own relay stays1978          // public. See setRelayUrl.1979          if (payload.relayUrl !== undefined) {1980            if (typeof payload.relayUrl !== "string") {1981              return { ok: false, error: "invalid_relay_url" };1982            }1983            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1984          }1985          if (payload.mode !== undefined) {1986            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1987              return { ok: false, error: "invalid_sync_mode" };1988            }1989            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1990          }1991          return { ok: true, data: await getSyncSettings() };1992        } catch (error) {1993          return {1994            ok: false,1995            error: error instanceof Error ? error.message : "invalid_relay_url",1996          };1997        }1998      }199920002001      case "GET_SYNC_ALERTS": {2002        if (vault.isDecoyMode()) return { ok: true, data: [] };2003        return { ok: true, data: await getPendingSyncAlerts() };2004      }20052006      case "DISMISS_SYNC_ALERTS": {2007        if (vault.isDecoyMode()) return { ok: true };2008        const type = (msg.payload as { type?: unknown } | undefined)?.type;2009        if (type !== "DEVICE_KEY_ROTATED" && type !== "DEVICE_REVOKED") {2010          return { ok: false, error: "invalid_sync_alert_type" };2011        }2012        await dismissPendingSyncAlerts(type);2013        return { ok: true };2014      }20152016      case "GET_PENDING_VOUCHED_DEVICES": {2017        if (vault.isDecoyMode()) return { ok: true, data: [] };2018        return { ok: true, data: await listPendingVouchedDevices() };2019      }2020      case "CONFIRM_VOUCHED_DEVICE": {2021        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };2022        const { deviceId } = msg.payload as { deviceId: string };2023        const pending = await getPendingVouchedDevice(deviceId);2024        if (!pending) return { ok: false, error: "not_pending" };2025        // Last gate before a vouched device becomes a sync peer. A queue entry2026        // can predate the revocation that names it, so revocation is re-checked2027        // here rather than trusted to have swept the queue.2028        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {2029          await removePendingVouchedDevice(deviceId);2030          return { ok: false, error: "device_revoked" };2031        }2032        await upsertPairedDeviceV3({2033          deviceId: pending.deviceId,2034          deviceName: pending.deviceName,2035          deviceType:2036            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],2037          longTermPublicKeyHex: pending.longTermPublicKeyHex,2038          signingPublicKeyHex: pending.signingPublicKeyHex,2039          wsPort: pending.wsPort,2040          pairedAt: pending.pairedAt,2041          trustSource: "vouched",2042        });2043        await removePendingVouchedDevice(deviceId);2044        // Newly confirmed vouched device is now a sync target — kick a round2045        // so the mesh introduction pays off without a 10-minute wait.2046        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);2047        return { ok: true };2048      }2049      case "REJECT_VOUCHED_DEVICE": {2050        if (vault.isDecoyMode()) return { ok: true };2051        const { deviceId } = msg.payload as { deviceId: string };2052        await removePendingVouchedDevice(deviceId);2053        return { ok: true };2054      }20552056      case "ROTATE_SYNC_IDENTITY": {2057        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };2058        const epoch = vault.getVaultEpoch();2059        const { password } = (msg.payload ?? {}) as { password?: unknown };2060        if (typeof password !== "string" || !password) return { ok: false, error: "password_required" };2061        const verified = await vault.verifyMainPassword(password);2062        if (!vault.isUnlocked() || epoch !== vault.getVaultEpoch()) return { ok: false, error: "vault_locked" };2063        if (!verified) return { ok: false, error: "wrong_password" };2064        const result = await vault.rotateSyncIdentity();2065        return result.ok ? { ok: true } : { ok: false, error: result.error };2066      }20672068      default:2069        return { ok: false, error: "unknown_message_type" };2070    }2071  } catch (err) {2072    return {2073      ok: false,2074      error: err instanceof Error ? err.message : "operation_failed",2075    };2076  }2077}20782079// Returns username use-counts from the vault, sorted by frequency. Each row2080// also carries the entry's email so the popup can suggest the email/username2081// pair the user has actually used together.2082function buildIdentitySuggestions(2083  entries: VaultEntry[],2084): Array<{ email: string; username: string; count: number }> {2085  const usernameCounts = new Map<string, number>();2086  const usernameEmail = new Map<string, string>();2087  for (const entry of entries) {2088    const username = entry.username ?? "";2089    const email = (entry as VaultEntry & { email?: string }).email ?? "";2090    if (!username && !email) continue;2091    const key = username || email;2092    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);2093    if (!usernameEmail.has(key)) usernameEmail.set(key, email);2094  }2095  return Array.from(usernameCounts.entries())2096    .sort((a, b) => b[1] - a[1])2097    .map(([username, count]) => ({2098      email: usernameEmail.get(username) ?? "",2099      username,2100      count,2101    }));2102}21032104/** Notify all content scripts that the vault just became available. */2105function broadcastToContentScripts(message: { type: string }): void {2106  if (!chrome.tabs?.query) return;2107  chrome.tabs.query({}, (tabs) => {2108    for (const tab of tabs) {2109      if (tab.id !== undefined) {2110        chrome.tabs.sendMessage(tab.id, message).catch(() => {2111          // Tab may not have a content script — silently ignore2112        });2113      }2114    }2115  });2116}21172118function shouldRefreshAutoLock(2119  type: MessageType,2120  sender: Partial<chrome.runtime.MessageSender>,2121): boolean {2122  if (!isExtensionPageSender(sender)) return false;2123  return (2124    type !== "HAS_VAULT" &&2125    type !== "IS_UNLOCKED" &&2126    type !== "GET_VAULT_STATUS" &&2127    type !== "GET_BREACH_SCAN_STATUS" &&2128    type !== "LOCK" &&2129    type !== "UPDATE_SETTINGS" &&2130    type !== "GET_PENDING_PASSKEY" &&2131    type !== "GET_PASSKEY_PROVIDER_STATE" &&2132    type !== "DECLINE_CARD_SAVE" &&2133    type !== "IS_CARD_DECLINED" &&2134    type !== "AUTOFILL_QUERY" &&2135    type !== "ML_PREDICT_BATCH"2136  );2137}21382139function canaryWebhookUrl(value: unknown): string | null {2140  if (typeof value !== "string") return null;2141  try {2142    const url = new URL(value);2143    if (url.protocol !== "https:" || url.username || url.password) return null;2144    const host = url.hostname.toLowerCase().replace(/\.+$/, "");2145    if (!host || host === "localhost" || host.endsWith(".localhost")) return null;2146    if (host.startsWith("[")) {2147      if (isUnsafeCanaryIpv6(host.slice(1, -1))) return null;2148    } else if (/^\d+(?:\.\d+){3}$/.test(host) && isUnsafeCanaryIpv4(host)) return null;2149    url.hostname = host;2150    return url.href;2151  } catch { return null; }2152}21532154function isUnsafeCanaryIpv4(host: string): boolean {2155  const [a, b, c, d] = host.split(".").map(Number);2156  return a === 0 || a === 10 || a === 127 || a >= 224 ||2157    (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) ||2158    (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) ||2159    (a === 192 && b === 0 && c === 0 && d !== 9 && d !== 10) ||2160    (a === 192 && b === 0 && c === 2) || (a === 192 && b === 88 && c === 99) ||2161    (a === 198 && (b === 18 || b === 19 || (b === 51 && c === 100))) ||2162    (a === 203 && b === 0 && c === 113);2163}21642165function isUnsafeCanaryIpv6(host: string): boolean {2166  const [head, tail = ""] = host.split("::");2167  const left = head ? head.split(":").map(value => Number.parseInt(value, 16)) : [];2168  const right = tail ? tail.split(":").map(value => Number.parseInt(value, 16)) : [];2169  const words = [...left, ...Array<number>(8 - left.length - right.length).fill(0), ...right];2170  if (words.slice(0, 5).every(word => word === 0) && words[5] === 0xffff) {2171    return isUnsafeCanaryIpv4(`${words[6] >>> 8}.${words[6] & 255}.${words[7] >>> 8}.${words[7] & 255}`);2172  }2173  // Native global-unicast literals only; transition formats are conservative exclusions.2174  if ((words[0] & 0xe000) !== 0x2000 || words[0] === 0x2002) return true;2175  if (words[0] === 0x3fff && (words[1] & 0xf000) === 0) return true;2176  if (words[0] !== 0x2001) return false;2177  if (words[1] === 0xdb8) return true;2178  if ((words[1] & 0xfe00) !== 0) return false;2179  const globalAssignment = words[1] === 3 || (words[1] === 4 && words[2] === 0x112) ||2180    (words[1] & 0xfff0) === 0x20 || (words[1] & 0xfff0) === 0x30 ||2181    (words[1] === 1 && words.slice(2, 7).every(word => word === 0) && [1, 2, 3].includes(words[7]));2182  return !globalAssignment;2183}