messages.ts

98.1 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  getOrCreateDeviceId,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  enterResetRequired,121  resolveGeneration,122} from "./sync-generation";123import { isMessageSenderAllowed } from "./message-policy";124125const SUMMON_CAPABILITY_TTL_MS = 30_000;126type SummonCapability = { tabId: number; frameId: number; origin: string; operation: "inventory" | "fill"; expiresAt: number };127const summonCapabilities = new Map<string, SummonCapability>();128129export function createSummonCapability(tabId: number, origin: string, frameId = 0): string {130  const token = crypto.randomUUID();131  summonCapabilities.set(token, { tabId, frameId, origin, operation: "inventory", expiresAt: Date.now() + SUMMON_CAPABILITY_TTL_MS });132  return token;133}134135function consumeSummonCapability(token: unknown, sender: Partial<chrome.runtime.MessageSender>, operation: "inventory" | "fill"): boolean {136  if (typeof token !== "string") return false;137  const cap = summonCapabilities.get(token);138  if (!cap) return false;139  if (cap.expiresAt <= Date.now()) {140    summonCapabilities.delete(token);141    return false;142  }143  if (sender.tab?.id !== cap.tabId || (sender.frameId ?? 0) !== cap.frameId || attestedSenderOrigin(sender) !== cap.origin) return false;144  if (cap.operation !== operation) return false;145  if (operation === "inventory") cap.operation = "fill";146  else summonCapabilities.delete(token);147  return true;148}149150// Compile-time E2E flag, folded to a literal by Vite's `define` (false in151// every production build — verified in the bundled output). Mirrors the152// create-path bypass in passkey.ts so the Playwright passkey smoke can enable153// the provider without a real Pro licence; the gate is fully intact for users.154declare const __PEACH_E2E_PASSKEYS__: boolean;155const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true;156157function unhexBytes(hex: string): Uint8Array {158  if (hex.length % 2 !== 0) throw new Error("invalid hex");159  const out = new Uint8Array(hex.length / 2);160  for (let i = 0; i < out.length; i++) {161    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);162  }163  return out;164}165166/**167 * The single Pro gate. Every gated handler calls this first; the broadcast168 * lets the popup react (navigate to the License section, highlight the169 * relevant feature). Background never touches the popup view directly —170 * the popup owns navigation. See Projects.md "Pro gate rule".171 */172async function requirePro(173  feature: ProFeature,174  trigger: "user" | "background" = "user"175): Promise<{ allowed: boolean }> {176  if (PASSKEY_E2E_PRO_BYPASS && feature === "passkeys") return { allowed: true };177  if (await isProUser()) return { allowed: true };178179  if (trigger === "user") {180    // User deliberately triggered this feature — redirect the popup immediately.181    chrome.runtime182      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })183      .catch(() => {184        // Popup may be closed — the gate signal is best-effort.185      });186  } else {187    // Background trigger (e.g. passive sync initiation) — no popup is open.188    // Queue a notice so the next popup open shows a soft banner instead of189    // silently failing.190    if (chrome.storage.session) {191      chrome.storage.session192        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })193        .catch(() => {});194    }195  }196197  return { allowed: false };198}199200// LV-3: minimum interval between non-test canary pings per webhook+entry.201const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour202203type CanaryTrigger = "accessed" | "password_copied" | "username_copied" | "autofilled" | "submitted";204const canaryClaims = new Map<string, { at: number; dispatched: boolean; result: Promise<MessageResponse> }>();205206function fireStoredCanary(entry: VaultEntry, trigger: CanaryTrigger): Promise<MessageResponse> {207  if (!entry.canary) return Promise.resolve({ ok: true });208  const canary = entry.canary;209  const webhookUrl = canaryWebhookUrl(canary.webhookUrl);210  if (!webhookUrl) return Promise.resolve({ ok: false, error: "invalid_webhook_url" });211  const epoch = vault.getVaultEpoch();212  const now = Date.now();213  const identity = JSON.stringify([entry.id, webhookUrl]);214  const key = `${epoch}:${identity}`;215  for (const [existingKey, claim] of canaryClaims) {216    if (!existingKey.startsWith(`${epoch}:`) || claim.at > now || now - claim.at >= CANARY_MIN_INTERVAL_MS) canaryClaims.delete(existingKey);217  }218  const prior = canaryClaims.get(key);219  // A dispatched alert stays rate-limited even when its counter write failed.220  if (prior) return prior.result.then(result => result.ok || prior.dispatched ? { ok: true, data: { rateLimited: true } } : result);221  const current = () => vault.isUnlocked() && epoch === vault.getVaultEpoch();222  const unchanged = () => current() && vault.getEntryById(entry.id) === entry;223  // Publish the claim before hashing or storage can yield to another request.224  const result: Promise<MessageResponse> = Promise.resolve().then(async (): Promise<MessageResponse> => {225    const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(identity)));226    const suffix = Array.from(digest, byte => byte.toString(16).padStart(2, "0")).join("");227    const rateKey = `canary-last-fetch:${suffix}`;228    const stored = await chrome.storage.local.get(rateKey);229    if (!unchanged()) return { ok: false, error: current() ? "entry_changed" : "vault_locked" };230    const last = stored[rateKey];231    if (typeof last === "number" && Number.isFinite(last) && last <= now && now - last < CANARY_MIN_INTERVAL_MS) {232      const claim = canaryClaims.get(key);233      if (claim) claim.at = last;234      return { ok: true, data: { rateLimited: true } };235    }236    await chrome.storage.local.remove(`canary-last-fetch:${canary.webhookUrl}:${entry.title}`);237    if (!unchanged()) return { ok: false, error: current() ? "entry_changed" : "vault_locked" };238    // Alerts must not hold credential release hostage to webhook response time.239    claim.dispatched = true;240    try {241      void fetch(webhookUrl, { method: "POST", headers: { "Content-Type": "application/json" },242        body: canaryBody(entry.title, trigger), redirect: "error" })243        .catch(() => console.warn("[Peach] canary alert request failed"));244    } catch { console.warn("[Peach] canary alert request failed"); }245    let rateWriteFailed = false;246    try { await chrome.storage.local.set({ [rateKey]: now }); }247    catch { rateWriteFailed = true; }248    if (!current()) return { ok: false, error: "vault_locked" };249    const latestCanary = vault.getEntryById(entry.id)?.canary;250    if (!latestCanary || canaryWebhookUrl(latestCanary.webhookUrl) !== webhookUrl) return { ok: false, error: "entry_changed" };251    const pingCount = (latestCanary.pingCount ?? 0) + 1;252    await vault.updateEntry(entry.id, { canary: { ...latestCanary, lastPinged: now, pingCount } });253    if (!current()) return { ok: false, error: "vault_locked" };254    const latest = vault.getEntryById(entry.id);255    if (!latest?.canary || canaryWebhookUrl(latest.canary.webhookUrl) !== webhookUrl ||256      latest.canary.pingCount !== pingCount || latest.canary.lastPinged !== now) return { ok: false, error: "entry_changed" };257    return rateWriteFailed ? { ok: false, error: "canary_update_failed" } : { ok: true };258  }).catch((): MessageResponse => ({ ok: false, error: current() ? "canary_update_failed" : "vault_locked" }));259  const claim = { at: now, dispatched: false, result };260  canaryClaims.set(key, claim);261  void result.then(reply => { if (!reply.ok && !claim.dispatched) canaryClaims.delete(key); });262  return result;263}264265function canaryBody(entryTitle: string, trigger: CanaryTrigger | "test"): string {266  return JSON.stringify({ event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed", entry: entryTitle,267    trigger, timestamp: new Date().toISOString(), source: "peach-extension" });268}269270export function setupMessageHandler(): void {271  chrome.runtime.onMessage.addListener(272    (msg: unknown, sender, sendResponse) => {273      if (!isMessage(msg)) {274        sendResponse({ ok: false, error: "invalid_message" });275        return true;276      }277      handleMessage(msg, sender)278        .then(sendResponse)279        .catch((err) =>280          sendResponse({281            ok: false,282            error: err instanceof Error ? err.message : String(err),283          })284        );285      return true;286    }287  );288}289290function isMessage(m: unknown): m is Message {291  return typeof m === "object" && m !== null && "type" in m;292}293294/**295 * The browser-attested origin of the page that originated this message. A web296 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),297 * so every page-driven message arrives via the content-script relay and the298 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a299 * value the page cannot forge. This is the ONLY trustworthy origin for passkey300 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.301 */302function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {303  if (sender.origin) return sender.origin;304  if (sender.url) {305    try { return new URL(sender.url).origin; } catch { return undefined; }306  }307  return undefined;308}309310function isExtensionPageSender(sender: Partial<chrome.runtime.MessageSender>): boolean {311  return sender.url?.startsWith("chrome-extension://") === true ||312    sender.url?.startsWith("moz-extension://") === true;313}314315/** True when the message came from a page frame rather than extension UI. */316function isPageSender(sender: Partial<chrome.runtime.MessageSender>): boolean {317  return !isExtensionPageSender(sender) &&318    (sender.tab !== undefined || sender.url !== undefined);319}320321function entryDomains(url: unknown, additionalUrls: unknown): Set<string> {322  const domains = new Set<string>();323  const primary = typeof url === "string" ? extractDomain(url) : null;324  if (primary) domains.add(primary);325  if (Array.isArray(additionalUrls)) {326    for (const extra of additionalUrls) {327      if (typeof extra !== "string") continue;328      const domain = extractDomain(extra);329      if (domain) domains.add(domain);330    }331  }332  return domains;333}334335const CONTENT_LOGIN_TEXT_FIELDS = new Set(["title", "username", "email", "password", "url"]);336337function normalizeContentEntryUrl(value: string): string | null {338  try {339    const trimmed = value.trim();340    const url = new URL(trimmed);341    if ((url.protocol === "https:" || url.protocol === "http:") && extractDomain(url.href)) {342      // Origin-only saves must keep matching existing duplicate keys.343      return url.pathname === "/" && !url.search && !url.hash && url.href.endsWith("/") && !trimmed.endsWith("/")344        ? url.href.slice(0, -1)345        : url.href;346    }347    return null;348  } catch {349    return null;350  }351}352353function parseContentLoginWrite(354  fields: object,355  operation: "create" | "update",356): { ok: true; fields: Record<string, unknown> } | { ok: false; error: "invalid_payload" | "origin_binding_required" } {357  const normalized: Record<string, unknown> = {};358  for (const [key, value] of Object.entries(fields)) {359    if (key === "type") {360      if (operation !== "create" || value !== "login") return { ok: false, error: "invalid_payload" };361    } else if (key === "additionalUrls") {362      if (!Array.isArray(value)) return { ok: false, error: "invalid_payload" };363      const urls: string[] = [];364      for (const extra of value) {365        if (typeof extra !== "string") return { ok: false, error: "invalid_payload" };366        const url = normalizeContentEntryUrl(extra);367        if (!url) return { ok: false, error: "origin_binding_required" };368        urls.push(url);369      }370      normalized.additionalUrls = urls;371      continue;372    } else if (!CONTENT_LOGIN_TEXT_FIELDS.has(key) ||373      (typeof value !== "string" && !(key === "email" && value === undefined))) {374      return { ok: false, error: "invalid_payload" };375    }376    if (key === "url") {377      const url = normalizeContentEntryUrl(value as string);378      if (!url) return { ok: false, error: "origin_binding_required" };379      normalized.url = url;380    } else normalized[key] = value;381  }382  if (operation === "create") {383    if (typeof normalized.title !== "string") return { ok: false, error: "invalid_payload" };384    if (typeof normalized.url !== "string") return { ok: false, error: "origin_binding_required" };385  }386  return { ok: true, fields: normalized };387}388389/**390 * PB-26-106: the autofill read path re-validates the frame origin against the391 * entry's domains on every request, so an unbound write path would let a392 * content script repoint an entry at its own origin and then read the393 * credential through a read path that is behaving correctly.394 *395 * Creating an entry: a page may only bind it to itself. Mutating one: a page396 * may never GROW the domain set — only shrink it, and never below its own397 * attested origin.398 *399 * Self-binding on mutation was considered and is not enough: the content400 * script on a foreign origin IS the attacker in the reported chain, so letting401 * it attach "its own" origin lets it mint the very capability the read path402 * exists to withhold. The legitimate flow that needs a new domain — the inline403 * "remember this site" toast — therefore asks the popup instead404 * (REQUEST_REMEMBER_SITE), which is an extension page and exempt here.405 *406 * Extension pages are exempt: the popup edits entries for sites it is not on.407 */408function senderMayBindEntryDomains(409  sender: Partial<chrome.runtime.MessageSender>,410  domains: Set<string>,411): boolean {412  if (isExtensionPageSender(sender)) return true;413  const domain = attestedSenderDomain(sender);414  if (domain === null) return false;415  for (const candidate of domains) {416    if (candidate !== domain) return false;417  }418  return true;419}420421function senderMayMutateEntryDomains(422  sender: Partial<chrome.runtime.MessageSender>,423  before: Set<string>,424  after: Set<string>,425): boolean {426  if (isExtensionPageSender(sender)) return true;427  const domain = attestedSenderDomain(sender);428  if (domain === null || !after.has(domain)) return false;429  for (const kept of after) {430    if (!before.has(kept)) return false;431  }432  return true;433}434435/**436 * Null for extension pages (which the callers exempt), for senders with no437 * attested origin at all, and for unparseable frame urls.438 */439function attestedSenderDomain(sender: Partial<chrome.runtime.MessageSender>): string | null {440  if (sender.tab === undefined && sender.url === undefined) return null;441  const origin = attestedSenderOrigin(sender);442  if (!origin) return null;443  try { return extractDomain(new URL(origin).hostname); } catch { return null; }444}445446function patchChangesEntryOrigin(patch: object): boolean {447  return Object.hasOwn(patch, "url") || Object.hasOwn(patch, "additionalUrls");448}449450/** The entry's domain-bearing fields as the patch would leave them. */451function patchedUrlShape(452  patch: object,453  existing: Pick<VaultEntry, "url" | "additionalUrls">,454): { url: unknown; additionalUrls: unknown } {455  const candidate = patch as { url?: unknown; additionalUrls?: unknown };456  return {457    url: Object.hasOwn(patch, "url") ? candidate.url : existing.url,458    additionalUrls: Object.hasOwn(patch, "additionalUrls")459      ? candidate.additionalUrls460      : existing.additionalUrls,461  };462}463// Resolves once restoreFromSession() has run, so handlers see the correct464// post-restore unlock state. entry.ts registers this BEFORE the message465// handler so the onMessage listener is added synchronously at SW startup466// (MV3 requirement) while unlock-dependent handlers still wait for restore.467let restoreReady: Promise<void> = Promise.resolve();468const MAX_ML_BATCH_FIELDS = 128;469const MAX_ML_FIELDS_PER_SECOND = 256;470const mlWorkBySender = new Map<string, { startedAt: number; fields: number }>();471472function claimMLWork(sender: Partial<chrome.runtime.MessageSender>, fields: number): boolean {473  if (fields === 0) return true;474  const now = Date.now();475  for (const [key, value] of mlWorkBySender) {476    if (now - value.startedAt >= 1_000) mlWorkBySender.delete(key);477  }478  const key = `${sender.tab?.id ?? "ui"}:${sender.frameId ?? 0}:${attestedSenderOrigin(sender) ?? "extension"}`;479  const current = mlWorkBySender.get(key);480  if (!current) {481    mlWorkBySender.set(key, { startedAt: now, fields });482    return fields <= MAX_ML_FIELDS_PER_SECOND;483  }484  if (current.fields + fields > MAX_ML_FIELDS_PER_SECOND) return false;485  current.fields += fields;486  return true;487}488489/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */490export function setRestoreReady(p: Promise<unknown>): void {491  restoreReady = p.then(() => undefined, () => undefined);492}493494export async function handleMessage(495  msg: Message,496  sender: Partial<chrome.runtime.MessageSender> = {}497): Promise<MessageResponse> {498  try {499    // Wait for session-restore to finish before reading any unlock/vault state.500    // On a cold SW start the popup's first message arrives while restore is501    // still in flight; without this gate IS_UNLOCKED would report locked (a502    // spurious lock screen) and the storage reads could race. The onMessage503    // listener itself is registered synchronously (entry.ts) so this gate, not504    // listener registration, is what absorbs the cold-start window.505    await restoreReady;506    // Validate sender — only allow messages from our extension pages/scripts.507    // `sender.id` is undefined for messages originating from extension UI508    // (popup/options), which is legitimate; reject only when it is defined509    // and does not match our extension id.510    if (511      sender.id !== undefined &&512      sender.id !== chrome.runtime.id513    ) {514      return { ok: false, error: "invalid_sender" };515    }516517    // PB-26-016: sender authorization is an exhaustive policy, not a518    // hand-maintained privileged denylist. A missing/unknown policy entry or a519    // background-only message fails closed before any handler runs.520    // Extension UI messages may legitimately omit sender.url. Resolve the521    // browser-attested extension origin only when a URL is present; this also522    // keeps test/runtime shims without getURL fail-closed for URL-bearing523    // senders instead of throwing before policy evaluation.524    const extensionOrigin = sender.url && typeof chrome.runtime.getURL === "function"525      ? chrome.runtime.getURL("")526      : "";527    if (!isMessageSenderAllowed(msg.type, sender, chrome.runtime.id, extensionOrigin)) {528      return { ok: false, error: "invalid_sender" };529    }530531    if (shouldRefreshAutoLock(msg.type, sender) && vault.isUnlocked()) {532      touchAutoLock();533    }534535    switch (msg.type) {536      case "CREATE_VAULT": {537        const { password, replacement, purpose } = (msg.payload ?? {}) as { password?: unknown; replacement?: unknown; purpose?: unknown };538        // Refuse to create a vault under an empty master password — the derived539        // key would be publicly known and the at-rest AES-GCM protection void540        // (audit HIGH; the CSV-import path previously passed ""). Length/strength541        // policy lives in the onboarding UI; this is the non-negotiable floor.542        if (typeof password !== "string" || password.length === 0 || (replacement !== undefined && replacement !== "warned-import") ||543          (purpose !== undefined && purpose !== "onboarding") || (purpose === "onboarding" && replacement !== undefined)) {544          return { ok: false, error: "invalid_payload" };545        }546        const created = await vault.createVault(password, replacement);547        if (purpose === "onboarding") await setRecoveryConfirmPending(created.unlocked && vault.isUnlocked());548        if (!created.unlocked) return { ok: true, data: created };549        try {550          await setupAutoLock();551          const unlocked = vault.isUnlocked();552          if (unlocked) {553            broadcastToContentScripts({ type: "VAULT_UNLOCKED" });554            onVaultUnlocked();555          }556          return { ok: true, data: { ...created, unlocked } };557        } catch (error) {558          console.warn("[Peach] vault saved; unlock setup failed:", error);559          await vault.lock().catch((lockError) => console.warn("[Peach] creation cleanup failed:", lockError));560          return { ok: true, data: { ...created, unlocked: false } };561        }562      }563      case "CREATE_VAULT_FROM_ROOT_KEY": {564        const { password, rootKeyHex } = (msg.payload ?? {}) as {565          password?: unknown;566          rootKeyHex?: unknown;567        };568        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {569          return { ok: false, error: "invalid_payload" };570        }571572        try {573          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);574          await setupAutoLock();575          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });576          onVaultUnlocked();577          return { ok: true, vaultId };578        } catch (err) {579          return { ok: false, error: err instanceof Error ? err.message : String(err) };580        }581      }582      case "UNLOCK": {583        const { password } = msg.payload as { password: string };584        const ok = await vault.unlock(password);585        if (ok) {586          // KAT: verify the WebCrypto stack is healthy before the user relies on it.587          // Runs after unlock so latency is hidden behind the vault-load time.588          const kat = await runSelfTest();589          if (!kat.ok) {590            console.error("[Peach] Crypto self-test FAILED:", kat.error);591            await vault.lock();592            return { ok: false, error: "self_test_failed" };593          }594          await vault.updateSettings({ pinPreferred: false });595          await setupAutoLock();596          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });597          onVaultUnlocked();598          return { ok: true };599        }600        // Distinguish corruption from wrong password so the popup can offer601        // a history-restore path instead of falsely accusing the user of602        // mistyping (M7/COR-007).603        const failure = vault.consumeLastUnlockFailureReason();604        if (failure) {605          return {606            ok: false,607            error: "vault_corrupted",608            canRestoreFromHistory: true,609          } as MessageResponse;610        }611        return { ok: false };612      }613      case "UNLOCK_WITH_PIN": {614        const { pin } = (msg.payload ?? {}) as { pin?: unknown };615        if (typeof pin !== "string") return { ok: false, error: "invalid_payload" };616        const ok = await vault.unlockWithPin(pin);617        if (!ok) {618          const status = await vault.getPinUnlockStatus();619          if (status.configured && !status.available) {620            return {621              ok: false,622              error: status.attemptsRemaining === 0623                ? "pin_attempts_exceeded"624                : "pin_session_expired",625            };626          }627          return { ok: false };628        }629        const kat = await runSelfTest();630        if (!kat.ok) {631          await vault.lock();632          return { ok: false, error: "self_test_failed" };633        }634        await vault.updateSettings({ pinPreferred: true });635        await setupAutoLock();636        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });637        onVaultUnlocked();638        return { ok: true };639      }640      case "GET_PIN_STATUS":641        return { ok: true, data: await vault.getPinUnlockStatus() };642      case "VALIDATE_RECOVERY_WORDS": {643        const { words } = msg.payload as { words: string[] };644        const invalid = findInvalidWords(words);645        return { ok: true, data: { valid: invalid.length === 0, invalid } };646      }647      case "GET_RECOVERY_WORDS": {648        // Must be unlocked and have recovery set up (vault must be v2.12+).649        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };650        const epoch = vault.getVaultEpoch();651        const current = () => vault.isUnlocked() && epoch === vault.getVaultEpoch();652        const exempt = await consumeRecoveryReveal();653        if (!current()) return { ok: false, error: "vault_locked" };654        if (!exempt) {655          const { password } = (msg.payload ?? {}) as { password?: string };656          if (typeof password !== "string" || !password) {657            return { ok: false, error: "password_required" };658          }659          const verified = await vault.verifyMainPassword(password);660          if (!current()) return { ok: false, error: "vault_locked" };661          if (!verified) {662            return { ok: false, error: "wrong_password" };663          }664        }665        try {666          const words = await vault.getRecoveryWords();667          if (!current()) return { ok: false, error: "vault_locked" };668          return { ok: true, data: words };669        } catch {670          return { ok: false, error: "recovery_not_setup" };671        }672      }673      case "GET_RECOVERY_CONFIRM_PENDING":674        return { ok: true, data: await isRecoveryConfirmPending() };675      case "CLEAR_RECOVERY_CONFIRM_PENDING":676        await clearRecoveryConfirmPending();677        if (vault.isUnlocked()) touchAutoLock();678        return { ok: true };679      case "RECOVER_WITH_WORDS": {680        // User has lost their password but has their 12 recovery words.681        // We: (1) validate the words, (2) re-encrypt vault with new password.682        if (!msg.payload || typeof msg.payload !== "object" || Array.isArray(msg.payload)) {683          return { ok: false, error: "invalid_recovery_payload" };684        }685        const { words, newPassword } = msg.payload as {686          words: string[];687          newPassword: string;688        };689        if (!Array.isArray(words) || words.some((word) => typeof word !== "string") || typeof newPassword !== "string") {690          return { ok: false, error: "invalid_recovery_payload" };691        }692        const recovered = await vault.recoverWithWords(words, newPassword);693        if (recovered.unlocked) {694          try { await setupAutoLock(); }695          catch (error) {696            console.warn("[Peach] recovery password saved; auto-lock setup failed:", error);697            try { await vault.lock(); }698            catch (lockError) { console.warn("[Peach] recovery session cleanup failed:", lockError); }699          }700        }701        const unlocked = recovered.unlocked && vault.isUnlocked();702        if (unlocked) broadcastToContentScripts({ type: "VAULT_UNLOCKED" });703        return { ok: true, data: { ...recovered, unlocked } };704      }705      case "LOCK":706        await vault.lock();707        return { ok: true };708      case "IS_UNLOCKED":709        return { ok: true, data: vault.isUnlocked() };710      case "GET_VAULT_STATUS":711        return { ok: true, unlocked: vault.isUnlocked() };712      case "HAS_VAULT":713        return { ok: true, data: await vault.hasVault() };714      case "GET_ENTRIES":715        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };716        return { ok: true, data: vault.getEntries() };717      case "EXPORT_ENTRIES": {718        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };719        const { password } = (msg.payload ?? {}) as { password?: unknown };720        if (typeof password !== "string" || !password) {721          return { ok: false, error: "password_required" };722        }723        if (!(await vault.verifyMainPassword(password))) {724          return { ok: false, error: "wrong_password" };725        }726        return { ok: true, data: vault.getEntries() };727      }728      case "ADD_ENTRY": {729        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };730        let payload = msg.payload;731        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {732          return { ok: false, error: "invalid_payload" };733        }734        if (isPageSender(sender)) {735          const parsed = parseContentLoginWrite(payload, "create");736          if (!parsed.ok) return parsed;737          payload = parsed.fields;738          const domains = entryDomains(parsed.fields.url, parsed.fields.additionalUrls);739          if (domains.size === 0 || !senderMayBindEntryDomains(sender, domains)) {740            return { ok: false, error: "origin_binding_required" };741          }742        }743        if (isExtensionPageSender(sender)) {744          const canary = (payload as { canary?: unknown }).canary;745          if (canary !== undefined) {746            if (!canary || typeof canary !== "object" || !canaryWebhookUrl((canary as { webhookUrl?: unknown }).webhookUrl)) return { ok: false, error: "invalid_webhook_url" };747            payload = { ...(payload as object), canary: { ...canary, lastPinged: undefined, pingCount: undefined } };748          }749        }750        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);751        return { ok: true, data: entry };752      }753      case "BATCH_ADD_ENTRIES": {754        const payload = msg.payload as { entries?: unknown } | null | undefined;755        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {756          return { ok: false, error: "invalid_payload" };757        }758        if (!Array.isArray(payload.entries)) {759          return { ok: false, error: "invalid_payload" };760        }761        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);762        return { ok: true, data: added };763      }764      case "RESTORE_ENTRIES": {765        const payload = msg.payload as766          | { entries?: unknown; mode?: unknown; settings?: unknown }767          | null768          | undefined;769        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {770          return { ok: false, error: "invalid_payload" };771        }772        if (!Array.isArray(payload.entries)) {773          return { ok: false, error: "invalid_payload" };774        }775        if (payload.mode !== "replace" && payload.mode !== "merge") {776          return { ok: false, error: "invalid_payload" };777        }778        const summary = await vault.restoreEntries(779          payload.entries as Parameters<typeof vault.restoreEntries>[0],780          payload.mode781        );782        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {783          await vault.updateSettings(payload.settings as vault.VaultSettings);784        }785        return { ok: true, data: summary };786      }787      case "CLEAR_VAULT_ENTRIES": {788        await vault.clearVaultEntries("REPLACE_ALL");789        return { ok: true };790      }791      case "GET_VAULT_HISTORY": {792        // The history store is real-mode state by construction, so a decoy793        // session must not see it — this is where the duress session would794        // otherwise leak the real vault's activity and size (PB-26-915).795        if (vault.isDecoyMode()) return { ok: true, data: [] };796        const snapshots = await vault.getVaultHistory();797        return { ok: true, data: snapshots };798      }799      case "RESTORE_VAULT_SNAPSHOT": {800        // Same guard on the write side: a coerced session must not be able to801        // roll the real vault backwards onto an earlier snapshot.802        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };803        const { snapshotId } = msg.payload as { snapshotId: string };804        const result = await vault.restoreVaultSnapshot(snapshotId);805        if (!result.ok) return { ok: false, error: result.error };806        broadcastToContentScripts({ type: "VAULT_LOCKED" });807        return { ok: true };808      }809      case "COUNT_DUPLICATES": {810        return { ok: true, data: vault.countDuplicates() };811      }812      case "DEDUPLICATE_ENTRIES": {813        const removed = await vault.deduplicateEntries();814        return { ok: true, data: removed };815      }816      case "UPDATE_ENTRY": {817        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;818        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {819          return { ok: false, error: "invalid_payload" };820        }821        const { id, patch: inputPatch } = payload;822        if (typeof id !== "string" || !id || !inputPatch || typeof inputPatch !== "object" || Array.isArray(inputPatch)) {823          return { ok: false, error: "invalid_payload" };824        }825        let patch: object = inputPatch;826        const existingEntry = vault.getEntryById(id);827        if (!existingEntry) return { ok: false, error: "entry_not_found" };828        if (isPageSender(sender)) {829          if ((existingEntry.type ?? "login") !== "login") return { ok: false, error: "login_entries_only" };830          const parsed = parseContentLoginWrite(patch, "update");831          if (!parsed.ok) return parsed;832          patch = parsed.fields;833        }834        if (patchChangesEntryOrigin(patch) || isPageSender(sender)) {835          const before = entryDomains(existingEntry.url, existingEntry.additionalUrls);836          const after = patchedUrlShape(patch, existingEntry);837          if (!senderMayMutateEntryDomains(838            sender,839            before,840            entryDomains(after.url, after.additionalUrls),841          )) {842            return { ok: false, error: "origin_binding_required" };843          }844        }845        // Single enforcement point for the Canary Entries Pro gate. Only846        // gates the transition into a canary entry — clearing/disabling a847        // canary (`canary: undefined`) is always allowed, so existing848        // canary entries remain manageable.849        const incomingCanary = (patch as { canary?: unknown }).canary;850        if (isExtensionPageSender(sender) && incomingCanary !== undefined &&851          (!incomingCanary || typeof incomingCanary !== "object" || !canaryWebhookUrl((incomingCanary as { webhookUrl?: unknown }).webhookUrl))) return { ok: false, error: "invalid_webhook_url" };852        if (incomingCanary && typeof incomingCanary === "object") {853          const existing = vault.getEntryById(id);854          if (!existing?.canary) {855            const gate = await requirePro("canary_entry");856            if (!gate.allowed) return { ok: false, error: "pro_required" };857          }858        }859        if (isExtensionPageSender(sender) && incomingCanary && typeof incomingCanary === "object") {860          const stored = vault.getEntryById(id)?.canary;861          patch = { ...patch, canary: { ...incomingCanary, lastPinged: stored?.lastPinged, pingCount: stored?.pingCount } };862        }863        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);864        return { ok: true };865      }866      case "ADD_ADDITIONAL_URL": {867        const { id, url } = msg.payload as { id: string; url: string };868        const trimmed = typeof url === "string" ? url.trim() : "";869        if (!trimmed) return { ok: false, error: "url_required" };870        const existing = vault.getEntryById(id);871        if (!existing) return { ok: false, error: "entry_not_found" };872        const merged = [...(existing.additionalUrls ?? []), trimmed];873        if (!senderMayMutateEntryDomains(874          sender,875          entryDomains(existing.url, existing.additionalUrls),876          entryDomains(existing.url, merged),877        )) {878          return { ok: false, error: "origin_binding_required" };879        }880        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };881        await vault.updateEntry(id, { additionalUrls: merged });882        return { ok: true };883      }884      case "REQUEST_REMEMBER_SITE": {885        // PB-26-106: growing an entry's domain set needs a decision the page886        // cannot make for itself, so the page asks and the popup confirms. A887        // page may only ask about its own attested origin — otherwise this888        // becomes the same unbound write under a friendlier name.889        const { id, url } = (msg.payload ?? {}) as { id?: unknown; url?: unknown };890        if (typeof id !== "string" || !id) return { ok: false, error: "invalid_payload" };891        const trimmed = typeof url === "string" ? url.trim() : "";892        if (!trimmed) return { ok: false, error: "url_required" };893        if (!senderMayBindEntryDomains(sender, entryDomains(trimmed, undefined))) {894          return { ok: false, error: "origin_binding_required" };895        }896        if (!vault.getEntryById(id)) return { ok: false, error: "entry_not_found" };897        if (chrome.storage.session) {898          await chrome.storage.session.set({ pendingRememberSite: { entryId: id, url: trimmed } });899        }900        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }901        return { ok: true };902      }903      case "DELETE_ENTRY": {904        const { id } = msg.payload as { id: string };905        await vault.deleteEntry(id);906        return { ok: true };907      }908      case "GET_DELETED_ENTRIES":909        return { ok: true, data: vault.getDeletedEntries() };910      case "RESTORE_ENTRY": {911        const { id } = msg.payload as { id: string };912        await vault.restoreEntry(id);913        return { ok: true };914      }915      case "PURGE_ENTRY": {916        const { id } = msg.payload as { id: string };917        await vault.purgeEntry(id);918        return { ok: true };919      }920      case "PURGE_EXPIRED_TRASH": {921        const { retentionMs } = msg.payload as { retentionMs: number };922        const purged = await vault.purgeExpiredTrash(retentionMs);923        return { ok: true, data: purged };924      }925      case "SAVE_NOTE": {926        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };927        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };928        const now = Date.now();929        if (id) {930          const existing = vault.getEntryById(id);931          if (!existing) return { ok: false, error: "not_found" };932          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });933          return { ok: true, data: vault.getEntryById(id) };934        } else {935          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt936          // (EntryDraft omits both), so passing them was the only reason the937          // `as any` cast existed. Dropping them makes the call type-check.938          const entry = await vault.addEntry({939            type: "note",940            title: title || "Untitled",941            notes: body,942          });943          return { ok: true, data: entry };944        }945      }946      case "DELETE_NOTE": {947        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };948        const { id } = msg.payload as { id: string };949        await vault.deleteEntry(id);950        return { ok: true };951      }952      case "GET_NOTES": {953        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };954        const notes = vault.getEntries().filter(955          (e) => e.type === "note" && !e.deletedAt956        );957        return { ok: true, data: notes } as MessageResponse;958      }959      case "SEARCH_VAULT": {960        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };961        // AUD-002: shape-validate the payload before calling string methods.962        // A raw cast lets a malformed message crash the handler with TypeError.963        const { query } = (msg.payload ?? {}) as { query?: unknown };964        if (typeof query !== "string") {965          return { ok: false, error: "invalid_payload" };966        }967        const q = query.toLowerCase();968        const searchResults = vault.getEntries().filter(969          (e) =>970            !e.deletedAt &&971            (e.title.toLowerCase().includes(q) ||972              e.notes?.toLowerCase().includes(q) ||973              e.username?.toLowerCase().includes(q))974        );975        return { ok: true, data: searchResults } as MessageResponse;976      }977      case "CHECK_SAVE_CREDENTIAL": {978        if (!isPageSender(sender) || sender.tab?.id === undefined) return { ok: false, error: "invalid_sender" };979        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };980        const domain = attestedSenderDomain(sender);981        if (!domain) return { ok: false, error: "origin_unverified" };982        const payload = msg.payload;983        if (!payload || typeof payload !== "object" || Array.isArray(payload) ||984          Object.keys(payload).some(key => key !== "username" && key !== "password")) {985          return { ok: false, error: "invalid_payload" };986        }987        const { username, password } = payload as { username?: unknown; password?: unknown };988        if (typeof username !== "string" || typeof password !== "string") return { ok: false, error: "invalid_payload" };989        const identity = username.trim().toLowerCase();990        const matchesIdentity = (entry: VaultEntry) => {991          const names = [entry.username ?? "", entry.email ?? ""].map(name => name.trim().toLowerCase());992          return identity ? names.includes(identity) : names.every(name => !name);993        };994        const isCandidate = (entry: VaultEntry) => !entry.deletedAt &&995          (entry.type === undefined || entry.type === "login") && !isPasskeyOnly(entry) &&996          entryDomains(entry.url, entry.additionalUrls).has(domain);997        const eligible = vault.getEntries().filter(isCandidate);998        const candidates = eligible.filter(matchesIdentity);999        const exact = (identity ? candidates : eligible).filter(entry => entry.password === password);1000        if (exact.length) {1001          const epoch = vault.getVaultEpoch();1002          const alerts = await Promise.all(exact.map(entry => fireStoredCanary(entry, "submitted")));1003          if (!vault.isUnlocked() || epoch !== vault.getVaultEpoch()) return { ok: false, error: "vault_locked" };1004          const failed = alerts.find(alert => !alert.ok);1005          if (failed) return failed;1006          if (exact.some(entry => {1007            const current = vault.getEntryById(entry.id);1008            return !current || !isCandidate(current) || (identity && !matchesIdentity(current)) || current.password !== password;1009          })) return { ok: false, error: "entry_changed" };1010          return { ok: true, data: { status: "same" } };1011        }1012        if (candidates.length === 1) return { ok: true, data: { status: "changed", id: candidates[0].id } };1013        return { ok: true, data: { status: candidates.length ? "ambiguous" : "new" } };1014      }1015      case "AUTOFILL_QUERY": {1016        if (!vault.isUnlocked()) {1017          return { ok: false, error: "vault_locked" };1018        }1019        const { domain, kind, capability } = msg.payload as {1020          domain: string;1021          kind?: "login" | "card" | "totp";1022          capability?: string;1023        };1024        const includeAll = consumeSummonCapability(capability, sender, "inventory");1025        if (capability !== undefined && !includeAll) {1026          return { ok: false, error: "entry_not_found" };1027        }1028        // kind="card": return saved cards as compact summaries for the1029        // inline card silver platter. Cards are not domain-scoped — every1030        // saved card is a candidate on every checkout page — so domain is1031        // ignored when kind === "card".1032        if (kind === "card") {1033          if (!includeAll) return { ok: true, data: [] };1034          const cards = vault.getEntries().filter((e) => e.type === "card");1035          return {1036            ok: true,1037            data: cards.map((e) => ({1038              id: e.id,1039              title: e.cardNickname || e.title,1040              cardholderName: e.cardholderName,1041              last4: e.last4,1042              expMonth: e.expMonth,1043              expYear: e.expYear,1044              network: e.network,1045            })),1046          };1047        }1048        const scopedDomain = isPageSender(sender)1049          ? attestedSenderDomain(sender)1050          : typeof domain === "string"1051            ? extractDomain(domain)1052            : null;1053        if (!includeAll && !scopedDomain) {1054          return isPageSender(sender)1055            ? { ok: false, error: "origin_unverified" }1056            : { ok: true, data: [] };1057        }1058        if (kind === "totp") {1059          const matches = (1060            includeAll1061              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")1062              : vault.queryDomain(scopedDomain!)1063          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));1064          return {1065            ok: true,1066            data: matches.map((e) => ({1067              id: e.id,1068              title: e.title,1069              username: e.username,1070              email: e.email,1071              url: e.url,1072              hasTotp: true,1073            })),1074          };1075        }1076        // The inline selector fills username+password into a form. Passkey-1077        // only entries have no password to fill; sign-in for those goes1078        // through the WebAuthn path instead. Filter them out everywhere so1079        // the user doesn't see four "GitHub" rows that mostly do nothing.1080        // Notes and cards never belonged here either.1081        const matches = (1082          includeAll1083            ? vault1084                .getEntries()1085                .filter((entry) => entry.type !== "note" && entry.type !== "card")1086            : vault.queryDomain(scopedDomain!)1087        ).filter((entry) => !isPasskeyOnly(entry));1088        return {1089          ok: true,1090          data: matches.map((e) =>1091            includeAll1092              ? {1093                  id: e.id,1094                  title: e.title,1095                  // username/email/url shipped so the inline popup's search1096                  // affordance can match on them, not just titles. No secrets1097                  // cross the boundary — same shape as the domain-matched1098                  // response below minus hasTotp (which the search list1099                  // doesn't surface).1100                  username: e.username,1101                  email: e.email,1102                  url: e.url,1103                  hasPasskey: e.passkey !== undefined,1104                }1105              : {1106                  id: e.id,1107                  title: e.title,1108                  username: e.username,1109                  email: e.email,1110                  url: e.url,1111                  hasTotp: Boolean(e.totp),1112                  hasPasskey: e.passkey !== undefined,1113                }1114          ),1115        };1116      }1117      case "GET_ENTRY_FOR_FILL": {1118        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1119        const { id, capability } = msg.payload as {1120          id: string;1121          capability?: string;1122        };1123        const capabilityAuthorized = capability !== undefined && consumeSummonCapability(capability, sender, "fill");1124        const senderDomain = isPageSender(sender) ? attestedSenderDomain(sender) : null;1125        if (isPageSender(sender) && !senderDomain) {1126          return { ok: false, error: "origin_unverified" };1127        }1128        let entry = vault.getEntryById(id);1129        if (!entry) return { ok: false, error: "entry_not_found" };11301131        // MV-1: re-validate the entry against the requesting frame's origin.1132        // sender.url / sender.tab.url are browser-attested — a page cannot1133        // forge them. PB-26-005: the FRAME url (sender.url) is authoritative1134        // for an all_frames content script; the top-frame tab.url would1135        // misattribute a cross-origin iframe's request to the top page. When1136        // the request does not come from a tab at all (popup surfaces use1137        // GET_ENTRY_FOR_EDIT, not this), refuse.1138        if (senderDomain && !capabilityAuthorized) {1139          if (!entryDomains(entry.url, entry.additionalUrls).has(senderDomain)) {1140            // Domain mismatch — refuse silently (no oracle about which ids exist).1141            return { ok: false, error: "entry_not_found" };1142          }1143        }1144        // Passkey-only entries (passkey credential, no password) cannot be1145        // filled into a form — sign-in goes through the WebAuthn path. A1146        // login that ALSO has a passkey is still fillable for its password.1147        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };1148        if (entry.canary) {1149          const requestedCanary = entry.canary;1150          const epoch = vault.getVaultEpoch();1151          const alerted = await fireStoredCanary(entry, "accessed");1152          if (!vault.isUnlocked() || epoch !== vault.getVaultEpoch()) return { ok: false, error: "vault_locked" };1153          if (!alerted.ok) return alerted;1154          entry = vault.getEntryById(id);1155          if (!entry || (senderDomain && !capabilityAuthorized && !entryDomains(entry.url, entry.additionalUrls).has(senderDomain))) {1156            return { ok: false, error: "entry_not_found" };1157          }1158          if (canaryWebhookUrl(entry.canary?.webhookUrl) !== canaryWebhookUrl(requestedCanary.webhookUrl)) {1159            return { ok: false, error: "entry_changed" };1160          }1161          if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };1162        }1163        // Strip the passkey credential AND the raw base32 TOTP seed from the1164        // response. Content scripts never need either: the private key is the1165        // authenticator's, and handing over the TOTP seed would let a1166        // compromised content script mint valid codes indefinitely (SEV-3-C).1167        // Generate the *current* 6-digit code here in the background and send1168        // only that, plus the seconds left so the UI can render a countdown.1169        // Also drop passwordHistory: filling needs only the *current* password.1170        // Handing every past password to a content script during passive1171        // autofill on an arbitrary page would widen the blast radius of a1172        // compromised page far beyond the one credential being filled.1173        const {1174          passkey: _strippedPasskey,1175          totp: seed,1176          totpAlgorithm,1177          totpDigits,1178          totpPeriod,1179          passwordHistory: _ph,1180          ...safeEntry1181        } = entry;1182        let totpCode: string | undefined;1183        let totpRemaining: number | undefined;1184        if (seed) {1185          try {1186            // PCH-01-019: honour stored algorithm/digits/period (defaults apply1187            // when these are undefined, i.e. RFC-default bare-seed entries).1188            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);1189            totpCode = generated.code;1190            totpRemaining = generated.remaining;1191          } catch {1192            totpCode = undefined;1193          }1194        }1195        if (isPageSender(sender) && vault.isUnlocked()) touchAutoLock();1196        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };1197      }1198      // Trusted full-entry fetch for extension-owned edit surfaces. Content1199      // scripts route editing to the popup and cannot call this message.1200      case "GET_ENTRY_FOR_EDIT": {1201        if (isPageSender(sender)) return { ok: false, error: "invalid_sender" };1202        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1203        const { id } = msg.payload as { id: string };1204        const entry = vault.getEntryById(id);1205        if (!entry) return { ok: false, error: "entry_not_found" };12061207        const { passkey: _passkey, ...safeEntry } = entry;1208        return { ok: true, data: safeEntry };1209      }1210      case "COPY": {1211        // Page relays must carry the browser-attested frame origin, as with1212        // SUMMON/fill. The policy admits content scripts; this binds the1213        // admitted page sender before arming clipboard auto-clear.1214        if (isPageSender(sender) && !attestedSenderOrigin(sender)) {1215          return { ok: false, error: "invalid_sender" };1216        }1217        // AUD-002: shape-validate the payload before passing to the clipboard1218        // helper. A raw cast lets a malformed message reach the clipboard API1219        // with a non-string and throw.1220        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {1221          text?: unknown;1222          label?: unknown;1223          alreadyWritten?: unknown;1224        };1225        if (typeof text !== "string" || typeof label !== "string") {1226          return { ok: false, error: "invalid_payload" };1227        }1228        await copyToClipboard(text, label, Boolean(alreadyWritten));1229        return { ok: true, clearSeconds: getEffectiveClearSeconds() };1230      }1231      case "CHECK_ALL_BREACHES": {1232        const allEntries = vault.getEntries();1233        const results: Record<string, number> = {};1234        for (const entry of allEntries) {1235          if (entry.type === "note") continue;1236          if (!entry.password) continue;1237          results[entry.id] = await vault.checkBreach(entry.password);1238          // Small delay — be a good citizen to the HIBP API1239          await new Promise((r) => setTimeout(r, 200));1240        }1241        // Persist any non-zero counts back to entries1242        for (const [id, count] of Object.entries(results)) {1243          const entry = vault.getEntryById(id);1244          if (entry && (entry.breach ?? 0) !== count) {1245            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });1246          }1247        }1248        return { ok: true, data: results };1249      }1250      case "GET_SETTINGS": {1251        const settings = await vault.ensureSettingsLoaded();1252        if (!isPageSender(sender)) return { ok: true, data: settings };12531254        const safeSettings: Pick<vault.VaultSettings, "accentColor" | "theme"> & {1255          manualSummonDomains?: NonNullable<vault.VaultSettings["manualSummonDomains"]>;1256        } = {1257          accentColor: settings.accentColor,1258          theme: settings.theme,1259        };1260        const domain = attestedSenderDomain(sender);1261        const ownSummon = domain ? settings.manualSummonDomains?.[domain] : undefined;1262        if (domain && ownSummon) safeSettings.manualSummonDomains = { [domain]: ownSummon };1263        return { ok: true, data: safeSettings };1264      }1265      case "UPDATE_SETTINGS": {1266        const patch = msg.payload;1267        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {1268          return { ok: false, error: "invalid_payload" };1269        }1270        await vault.updateSettings(patch as vault.VaultSettings);1271        if ((patch as Record<string, unknown>).lockedSyncRequiresUnlock === true) {1272          await clearLockedSyncPrivateKey();1273        }1274        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {1275          await setupAutoLock();1276          if (vault.isUnlocked()) touchAutoLock();1277        }1278        return { ok: true };1279      }1280      case "SETUP_PIN": {1281        const { currentPassword, pin } = (msg.payload ?? {}) as {1282          currentPassword?: unknown;1283          pin?: unknown;1284        };1285        if (typeof currentPassword !== "string" || typeof pin !== "string") {1286          return { ok: false, error: "invalid_payload" };1287        }1288        return (await vault.setupPinUnlock(currentPassword, pin))1289          ? { ok: true }1290          : { ok: false, error: "incorrect_current_password" };1291      }1292      case "DISABLE_PIN": {1293        const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown };1294        if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" };1295        return (await vault.disablePinUnlock(currentPassword))1296          ? { ok: true }1297          : { ok: false, error: "incorrect_current_password" };1298      }1299      case "GET_PENDING_PASSKEY":1300        return { ok: true, data: await getPendingPasskeyRequest() };1301      case "APPROVE_PASSKEY": {1302        const { requestId } = msg.payload as { requestId: number };1303        await resolvePendingPasskeyRequest(requestId, true);1304        return { ok: true };1305      }1306      case "DENY_PASSKEY": {1307        const { requestId } = msg.payload as { requestId: number };1308        await resolvePendingPasskeyRequest(requestId, false);1309        return { ok: true };1310      }1311      case "GET_PASSKEY_PROVIDER_STATE":1312        return { ok: true, data: await getPasskeyProviderState() };1313      case "SET_PASSKEY_PROVIDER_ENABLED": {1314        const { enabled } = msg.payload as { enabled: boolean };1315        // Disabling is always free; gating fires only when a free user is1316        // trying to turn passkey interception on.1317        if (enabled) {1318          const gate = await requirePro("passkeys");1319          if (!gate.allowed) return { ok: false, error: "pro_required" };1320        }1321        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };1322      }1323      case "FIRE_CANARY_PING": {1324        const payload = msg.payload;1325        if (!payload || typeof payload !== "object" || Array.isArray(payload)) return { ok: false, error: "invalid_payload" };1326        const { id, trigger, capability, webhookUrl: draftUrl, entryTitle } = payload as {1327          id?: unknown; trigger?: unknown; capability?: unknown; webhookUrl?: unknown; entryTitle?: unknown;1328        };1329        if (trigger === "test" && !isExtensionPageSender(sender)) return { ok: false, error: "invalid_sender" };1330        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1331        if (trigger === "test") {1332          if (typeof entryTitle !== "string") return { ok: false, error: "invalid_payload" };1333          const webhookUrl = canaryWebhookUrl(draftUrl);1334          if (!webhookUrl) return { ok: false, error: "invalid_webhook_url" };1335          try {1336            const response = await fetch(webhookUrl, { method: "POST", headers: { "Content-Type": "application/json" },1337              body: canaryBody(entryTitle, "test"), redirect: "error" });1338            return { ok: response.ok, error: response.ok ? undefined : `HTTP ${response.status}` };1339          } catch { return { ok: false, error: "network_error" }; }1340        }1341        if (typeof id !== "string" || !id || typeof trigger !== "string" || !["accessed", "password_copied", "username_copied", "autofilled", "submitted"].includes(trigger) ||1342          Object.keys(payload).some(key => !["id", "trigger", "capability"].includes(key))) return { ok: false, error: "invalid_payload" };1343        const capabilityAuthorized = capability !== undefined && consumeSummonCapability(capability, sender, "fill");1344        const domain = isPageSender(sender) ? attestedSenderDomain(sender) : null;1345        if (isPageSender(sender) && !domain) return { ok: false, error: "origin_unverified" };1346        const entry = vault.getEntryById(id);1347        if (!entry || (domain && !capabilityAuthorized && !entryDomains(entry.url, entry.additionalUrls).has(domain))) {1348          return { ok: false, error: "entry_not_found" };1349        }1350        return fireStoredCanary(entry, trigger as CanaryTrigger);1351      }1352      case "ACTIVATE_LICENSE": {1353        const { key } = msg.payload as { key: string };1354        const licenseInfo = await activateLicense(key);1355        return { ok: true, data: licenseInfo };1356      }1357      case "GET_LICENSE": {1358        const licenseInfo = await getLicenseInfo();1359        return { ok: true, data: licenseInfo };1360      }1361      case "GET_LICENSE_KEY": {1362        const key = await getLicenseKey();1363        return { ok: true, data: key };1364      }1365      case "DEACTIVATE_LICENSE": {1366        await deactivateLicense();1367        return { ok: true };1368      }1369      case "SHOULD_PLAY_CELEBRATION": {1370        const should = await shouldPlayCelebration();1371        return { ok: true, data: should };1372      }1373      case "MARK_CELEBRATION_PLAYED": {1374        await markCelebrationPlayed();1375        return { ok: true };1376      }1377      case "GET_CODEX_VAULT_DATA": {1378        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1379        // popup navigates to the License section without further coordination.1380        // Also privileged-page-gated (PB-26-001), and recoveryWords inside the1381        // snapshot additionally require a fresh master-password proof.1382        const gate = await requirePro("codex");1383        if (!gate.allowed) return { ok: false, error: "pro_required" };1384        const { password } = (msg.payload ?? {}) as { password?: string };1385        return await handleGetCodexVaultData(password);1386      }1387      case "ESTIMATE_CODEX_PAGES": {1388        const gate = await requirePro("codex");1389        if (!gate.allowed) return { ok: false, error: "pro_required" };1390        return await handleEstimateCodexPages();1391      }1392      case "RESTORE_FROM_CODEX": {1393        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1394        // be able to restore a vault that was printed by a Pro user.1395        // DO NOT add a Pro gate here.1396        // A decoy session, though, holds no real-mode authority: this path1397        // writes SLOT_A/SLOT_B and snapshots history, so it carries the same1398        // guard its thirteen neighbours do (PB-26-915).1399        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1400        const payload = msg.payload as CodexRestorePayload;1401        return await handleRestoreFromCodex(payload);1402      }1403      case "OPEN_PRO_GATE": {1404        // Content script requests: open popup and navigate to License section.1405        const { feature } = (msg.payload ?? {}) as { feature?: string };1406        if (chrome.storage.session) {1407          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1408        }1409        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1410        return { ok: true };1411      }1412      case "OPEN_POPUP": {1413        // Content script asks to open the trusted extension popup — used by the1414        // inline locked bubble so the master password is entered in the popup,1415        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1416        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1417        // toolbar icon. The badge already signals Peach needs attention.1418        //1419        // Set a session flag so the popup knows it was opened for inline unlock1420        // and should close itself once the vault is unlocked (returning the user1421        // to the inline autofill selector on the page).1422        const { entryId } = (msg.payload ?? {}) as { entryId?: unknown };1423        if (entryId !== undefined && (typeof entryId !== "string" || entryId.length === 0 || entryId.length > 64)) {1424          return { ok: false, error: "invalid_payload" };1425        }1426        if (chrome.storage.session) {1427          if (typeof entryId === "string") {1428            await chrome.storage.session.set({ peach_open_entry: entryId });1429          } else {1430            await chrome.storage.session.set({ peach_inline_unlock: true });1431          }1432        }1433        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1434        return { ok: true };1435      }1436      case "OPEN_DETACHED_POPUP": {1437        // A window created by the action popup and then orphaned with1438        // window.close() is cascaded shut by Chrome, so the file-picker1439        // flows (OS dialogs that dismiss the popup on focus loss) ask the SW1440        // to open the standalone window instead — the SW has no window to be1441        // associated with. The query string is allowlisted so this can never1442        // open an arbitrary URL.1443        const { route } = (msg.payload ?? {}) as { route?: string };1444        const search = route === "peachscript"1445          ? "?restore=peachscript"1446          : route === "csv"1447            ? "?restore=csv"1448            : route === "codex-pdf"1449              ? "?codex=pdf"1450              : null;1451        if (!search) return { ok: false, error: "bad_route" };1452        try {1453          const popupHtml =1454            chrome.runtime.getManifest().action?.default_popup ?? "src/popup/index.html";1455          await chrome.windows.create({1456            url: chrome.runtime.getURL(`${popupHtml}${search}`),1457            type: "popup",1458            width: 320,1459            height: 550,1460          });1461          return { ok: true, data: { detached: true } };1462        } catch {1463          return { ok: false };1464        }1465      }1466      case "GET_IDENTITIES": {1467        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1468        return { ok: true, data: vault.getIdentities() };1469      }1470      case "TOUCH_AUTO_LOCK": {1471        // touchAutoLock() is already called by shouldRefreshAutoLock above;1472        // this case just gives the popup a typed message to keep the session alive.1473        return { ok: true };1474      }1475      case "GET_ADVANCED_HEALTH_REPORT": {1476        const gate = await requirePro("advanced_health");1477        if (!gate.allowed) return { ok: false, error: "pro_required" };1478        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1479        const report = await buildAdvancedHealthReport(vault.getEntries());1480        return { ok: true, data: report };1481      }1482      case "IS_DURESS_ENABLED": {1483        const enabled = await vault.isDuressEnabled();1484        return { ok: true, data: enabled };1485      }1486      case "SETUP_DURESS": {1487        // Single enforcement point for the Duress Vault Pro gate. Free users1488        // who somehow reach this handler are rejected here; the popup also1489        // pre-checks isPro() to avoid showing the setup form to free users,1490        // but server-side is the actual security boundary.1491        const gate = await requirePro("duress_vault");1492        if (!gate.allowed) return { ok: false, error: "pro_required" };1493        // MV3 service workers restart after inactivity, losing the in-memory1494        // derived key. Detect this before calling setupDuress so the popup1495        // can show a meaningful prompt to re-lock and re-unlock.1496        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1497        const { duressPassword } = msg.payload as { duressPassword: string };1498        await vault.setupDuress(duressPassword);1499        return { ok: true };1500      }1501      case "DISABLE_DURESS": {1502        await vault.disableDuress();1503        return { ok: true };1504      }1505      case "VERIFY_MAIN_PASSWORD": {1506        const { password } = msg.payload as { password: string };1507        const ok = await vault.verifyMainPassword(password);1508        return { ok: true, data: ok };1509      }1510      case "CHANGE_PASSWORD": {1511        const { currentPassword, newPassword } = msg.payload as {1512          currentPassword: string;1513          newPassword: string;1514        };1515        const changed = await vault.changePassword(currentPassword, newPassword);1516        return changed1517          ? { ok: true }1518          : { ok: false, error: "incorrect_current_password" };1519      }1520      case "GET_SITE_PASSWORD_POLICY": {1521        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1522        if (!tab?.id) return { ok: true, data: null };1523        try {1524          const response = await chrome.tabs.sendMessage(tab.id, {1525            type: "GET_SITE_PASSWORD_POLICY",1526          });1527          return (response as MessageResponse) ?? { ok: true, data: null };1528        } catch {1529          return { ok: true, data: null };1530        }1531      }1532      case "RECORD_MANUAL_SUMMON": {1533        const { domain } = (msg.payload ?? {}) as { domain?: unknown };1534        const origin = attestedSenderOrigin(sender);1535        let senderDomain: string | null = null;1536        if (origin) {1537          try {1538            const hostname = new URL(origin).hostname;1539            senderDomain = extractDomain(hostname) ?? hostname;1540          } catch {1541            senderDomain = null;1542          }1543        }1544        if (typeof domain !== "string" || domain.length > 253 || domain !== senderDomain) {1545          return { ok: false, error: "invalid_domain" };1546        }1547        const settings = vault.getSettings();1548        const existing = settings.manualSummonDomains?.[domain];1549        const now = Date.now();1550        await vault.updateSettings({1551          manualSummonDomains: {1552            ...settings.manualSummonDomains,1553            [domain]: {1554              firstSummonedAt: existing?.firstSummonedAt ?? now,1555              summonCount: (existing?.summonCount ?? 0) + 1,1556              lastSummonedAt: now,1557            },1558          },1559        });1560        return { ok: true };1561      }1562      case "DECLINE_CARD_SAVE": {1563        // PB-26-108: the declined-card digest is keyed by root-key material, so1564        // a decline cannot be recorded while locked. Offers are not shown while1565        // locked either, so this is unreachable in practice.1566        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1567        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1568        await vault.declineCardSaveOffer(last4, expMonth, expYear);1569        return { ok: true };1570      }1571      case "IS_CARD_DECLINED": {1572        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1573        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1574        return { ok: true, data: declined };1575      }1576      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1577        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1578          rpId?: string;1579          rpName?: string;1580          userName?: string;1581          userDisplayName?: string;1582        };1583        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1584        return await initiateFirefoxPasskeyCreate({1585          rpId,1586          rpName: rpName ?? rpId,1587          userName,1588          userDisplayName,1589        }, attestedSenderOrigin(sender));1590      }15911592      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1593        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1594        if (!payload) return { ok: false, error: "missing_payload" };1595        return await completeFirefoxPasskeyCreate(payload);1596      }15971598      case "PASSKEY_OFFER_DECLINE": {1599        const { domain } = (msg.payload ?? {}) as { domain?: string };1600        const origin = attestedSenderOrigin(sender);1601        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1602        await recordPasskeyOfferDecline(domain);1603        return { ok: true };1604      }16051606      case "GET_PASSKEY_OFFER_DECLINED": {1607        const { domain } = (msg.payload ?? {}) as { domain?: string };1608        const origin = attestedSenderOrigin(sender);1609        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1610        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1611      }16121613      case "PASSKEY_HAS_CREDENTIALS": {1614        const payload = msg.payload as {1615          rpId?: string;1616          allowCredentials?: Array<{ id: string; type?: string }>;1617        } | undefined;1618        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1619        return await handlePasskeyHasCredentials({1620          rpId: payload.rpId,1621          allowCredentials: payload.allowCredentials ?? [],1622        }, attestedSenderOrigin(sender));1623      }16241625      case "PASSKEY_CREATE": {1626        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1627        if (!payload?.rpId || !payload?.userName) {1628          return { ok: false, error: "rpid_and_username_required" };1629        }1630        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1631      }16321633      case "PASSKEY_GET": {1634        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1635        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1636        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1637      }16381639      case "PASSKEY_AUTH_RESPONSE": {1640        const { requestId, approved } = (msg.payload ?? {}) as {1641          requestId?: string | number;1642          approved?: boolean;1643        };1644        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1645          return { ok: false, error: 'requestId and approved required' };1646        }1647        const pending = await getPendingPasskeyRequest();1648        const senderOrigin = attestedSenderOrigin(sender);1649        if (1650          !pending ||1651          pending.tabId === undefined ||1652          pending.crossOrigin === true ||1653          pending.requestId !== Number(requestId) ||1654          sender.tab?.id !== pending.tabId ||1655          senderOrigin !== pending.origin1656        ) {1657          return { ok: false, error: "invalid_passkey_approval_sender" };1658        }1659        await resolvePendingPasskeyRequest(Number(requestId), approved);1660        return { ok: true };1661      }16621663      case "GET_PASSKEY_FOR_DOMAIN": {1664        const { domain } = (msg.payload ?? {}) as { domain?: string };1665        if (!domain) return { ok: false, error: "domain_required" };1666        // Scope to the caller's own origin: a page may only ask about passkeys1667        // for a domain it actually owns, so an arbitrary page cannot enumerate1668        // which sites the user holds passkeys for or read the username (audit MEDIUM).1669        const origin = attestedSenderOrigin(sender);1670        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1671        if (!vault.isUnlocked()) return { ok: true, data: null };1672        const match = vault1673          .getEntries()1674          .find((entry) => entry.passkey?.rpId === domain);1675        if (!match || !match.passkey) return { ok: true, data: null };1676        // Slim shape — only the fields State 11 needs. Never expose private1677        // key material, even though this is locked behind isUnlocked.1678        // bannerShown is the per-domain "already surfaced" flag, kept in1679        // trusted background session storage so content scripts never touch1680        // chrome.storage.session directly (PB-26-203).1681        let bannerShown = false;1682        if (chrome.storage.session) {1683          const flag = await chrome.storage.session.get(`peach_state11_shown:${domain}`);1684          bannerShown = Boolean((flag as Record<string, unknown>)[`peach_state11_shown:${domain}`]);1685        }1686        return {1687          ok: true,1688          data: {1689            rpId: match.passkey.rpId,1690            userName: match.passkey.userName,1691            browser: match.passkey.browser,1692            bannerShown,1693          },1694        };1695      }16961697      case "MARK_PASSKEY_BANNER_SHOWN": {1698        const { domain } = (msg.payload ?? {}) as { domain?: string };1699        if (typeof domain !== "string" || !domain) return { ok: false, error: "domain_required" };1700        // Same origin binding as the read path: a page may only mark its own1701        // domain, and the flag reveals nothing either way.1702        const origin = attestedSenderOrigin(sender);1703        if (!origin || !isValidRpId(domain, origin)) return { ok: true };1704        if (chrome.storage.session) {1705          await chrome.storage.session.set({ [`peach_state11_shown:${domain}`]: Date.now() });1706        }1707        return { ok: true };1708      }17091710      case "DESTROY_VAULT": {1711        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1712        // storage.local.clear() wipes every Peach key (slots, settings, license,1713        // onboarded flag, history, sync state, declined cards, recall, etc.);1714        // session.clear() wipes pending passkey requests + pro-notice queues.1715        // Caller (Panic.tsx) handles UI navigation back to onboarding.1716        //1717        // The Pro license is the one thing that must survive: the user paid for1718        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1719        // Capture it before the clear and restore it after. peach_pro_celebrated1720        // rides along so the Pro celebration doesn't replay on the next unlock.1721        await vault.withVaultRemoval(async () => {1722          const preserved = await chrome.storage.local.get([1723            "peach_license",1724            "peach_pro_celebrated",1725          ]);1726          await storageClear();1727          await vault.clearVaultHistory();1728          const toRestore: Record<string, unknown> = {};1729          if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1730          if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1731          if (Object.keys(toRestore).length > 0) {1732            await chrome.storage.local.set(toRestore);1733          }1734          if (chrome.storage.session) {1735            await chrome.storage.session.clear();1736          }1737          await clearRecoveryConfirmPending();1738        });1739        return { ok: true };1740      }17411742      case "GET_IDENTITY_SUGGESTIONS": {1743        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1744        const entries = vault.getEntries();1745        const suggestions = buildIdentitySuggestions(entries);1746        return { ok: true, data: { suggestions } };1747      }1748      case "ML_INIT":1749        return { ok: true };17501751      case "ML_PREDICT_BATCH": {1752        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1753        if (!isValidMLFeatureBatch(featuresArray, MAX_ML_BATCH_FIELDS)) {1754          return { ok: false, error: "invalid_payload" };1755        }1756        if (!claimMLWork(sender, featuresArray.length)) {1757          return { ok: false, error: "rate_limited" };1758        }1759        return { ok: true, data: mlPredictBatch(featuresArray) };1760      }17611762      // ── Vault sync (v3) ───────────────────────────────────────────────1763      // Returns the public-facing local identity needed by the popup to1764      // drive Phase-1 audio pairing. The private long-term key never1765      // leaves the background.1766      case "GET_LOCAL_IDENTITY": {1767        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1768        // Pro license from an already-Pro peer (at least one device must be Pro).1769        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1770        // The identity is sealed under its own key rather than derived from the1771        // root, so pairing survives a master-password change (SEV-2-B).1772        const identity: LocalDeviceIdentity & { license?: string } = await buildLocalIdentity();1773        // If this device is Pro, advertise the signed license so the peer can1774        // activate it after SAS confirmation — pairing carries Pro across.1775        if (await isProUser()) {1776          const license = await getLicenseKey();1777          if (license) identity.license = license;1778        }1779        return { ok: true, data: identity };1780      }17811782      case "LIST_PAIRED_DEVICES": {1783        if (vault.isDecoyMode()) return { ok: true, data: { devices: [] } };1784        try {1785          const devices = await listPairedDevicesV3();1786          return { ok: true, data: { devices } };1787        } catch (err) {1788          if (err instanceof TrustDataCorruptedError) {1789            return { ok: false, error: "trust_data_corrupted" };1790          }1791          throw err;1792        }1793      }17941795      case "RENAME_PAIRED_DEVICE": {1796        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1797        const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string };1798        if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") {1799          return { ok: false, error: "invalid_payload" };1800        }1801        await renamePairedDeviceV3(deviceId, name);1802        return { ok: true };1803      }18041805      case "UNPAIR_DEVICE": {1806        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1807        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1808        if (typeof deviceId !== "string" || !deviceId) {1809          return { ok: false, error: "invalid_payload" };1810        }1811        // A damaged legacy identity must not prevent the user from evicting a1812        // peer locally. Sync is already blocked until the secure reset repairs1813        // this installation, so the local issuer marker is sufficient for the1814        // tombstone that will be cleared with the archived generation.1815        let revokedByDeviceId: string;1816        try {1817          revokedByDeviceId = await getOrCreateDeviceId();1818        } catch (error) {1819          if (!(error instanceof Error) || error.message !== "identity_migration_required") throw error;1820          revokedByDeviceId = "local";1821        }1822        await revokeDeviceByIdV3(deviceId, revokedByDeviceId);1823        // PB-26-213: forget the secret now so no further dial can use it.1824        // Removals that happen while locked leave orphans for the next1825        // unlock's reconcile to prune.1826        const unpairRootHex = vault.getRootKeyHex();1827        if (unpairRootHex) {1828          const unpairRoot = unhexBytes(unpairRootHex);1829          try {1830            await dropPairSecret(deviceId, unpairRoot);1831          } finally {1832            unpairRoot.fill(0);1833          }1834        } else {1835          await dropPairSecret(deviceId, null);1836        }1837        // Sync against the remaining hosts — the unpaired device no longer1838        // matters but the next alarm tick is up to ten minutes away.1839        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1840        return { ok: true };1841      }18421843      case "RENAME_LOCAL_DEVICE": {1844        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1845        const { name } = (msg.payload ?? {}) as { name?: string };1846        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1847        await setDeviceNameV3(name);1848        return { ok: true };1849      }18501851      // ── Relay pairing ─────────────────────────────────────────────────────1852      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1853      // session runs in the background; the SAS and the terminal result reach1854      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1855      case "START_ADOPTION_SOURCE": {1856        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1857        if (isRelayAdoptionSourceInFlight()) {1858          return { ok: false, error: "adoption_source_in_progress" };1859        }1860        try {1861          return { ok: true, data: await startRelayAdoptionSource() };1862        } catch (error) {1863          return {1864            ok: false,1865            error: error instanceof Error ? error.message : "adoption_source_failed",1866          };1867        }1868      }18691870      // Onboarding receiver — empty extension shows a QR, phone scans and1871      // sends the vault. The popup supplies the local-only password here so1872      // the background can wrap the adopted root key at rest without ever1873      // asking the user to retype it.1874      case "START_ADOPTION_RECEIVER": {1875        if (isRelayAdoptionSourceInFlight()) {1876          return { ok: false, error: "adoption_receiver_in_progress" };1877        }1878        const password = (msg.payload as { password?: unknown } | undefined)?.password;1879        if (typeof password !== "string" || password.length === 0) {1880          return { ok: false, error: "invalid_payload" };1881        }1882        try {1883          return { ok: true, data: await startRelayAdoptionReceiver(password) };1884        } catch (error) {1885          return {1886            ok: false,1887            error: error instanceof Error ? error.message : "adoption_receiver_failed",1888          };1889        }1890      }18911892      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1893      // on the source's SAS screen. The id round-trips the same way so a stale1894      // late response can't approve the wrong session.1895      case "RECEIVER_SAS_DECISION": {1896        const payload = msg.payload as { id?: unknown; sas?: unknown; ok?: unknown } | undefined;1897        if (typeof payload?.id !== "string" || typeof payload.sas !== "string" || typeof payload.ok !== "boolean") {1898          return { ok: false, error: "invalid_payload" };1899        }1900        return { ok: resolveReceiverSasConfirmation(payload.id, payload.sas, payload.ok) };1901      }19021903      case "SOURCE_SAS_DECISION": {1904        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1905        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1906          return { ok: false, error: "invalid_payload" };1907        }1908        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1909      }1910      case "LIST_PENDING_ADOPTION_HOLDERS": {1911        return { ok: true, data: await listPendingAdoptionHolders() };1912      }19131914      case "REMOVE_PENDING_ADOPTION_HOLDER": {1915        await removePendingAdoptionHolder();1916        return { ok: true };1917      }191819191920      case "CANCEL_ADOPTION_SOURCE": {1921        cancelRelayAdoptionSource();1922        return { ok: true };1923      }19241925      case "TRIGGER_SYNC": {1926        if (vault.isDecoyMode()) return { ok: true };1927        const payload = (msg.payload ?? {}) as {1928          reason?: "vault_change" | "foreground" | "manual";1929          force?: boolean;1930        };1931        const reason = payload.reason ?? "foreground";19321933        void triggerSyncIfReachable({ reason, force: payload.force === true });1934        return { ok: true };1935      }19361937      case "GET_SYNC_STATE": {1938        if (vault.isDecoyMode()) return { ok: true, data: { status: "idle" } };1939        return { ok: true, data: getSyncState() };1940      }19411942      // §11. The generation state carries no secret — it is a version and a1943      // state name — so the panel can read it while the vault is locked.1944      case "GET_SYNC_GENERATION": {1945        return { ok: true, data: await resolveGeneration(browserGenerationIo) };1946      }19471948      case "SECURE_RESET": {1949        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1950        const payload = (msg.payload ?? {}) as { password?: unknown };1951        if (typeof payload.password !== "string" || payload.password.length === 0) {1952          return { ok: false, error: "Enter your master password" };1953        }1954        const wasLocked = !vault.isUnlocked();1955        const passwordValid = wasLocked1956          ? await vault.unlock(payload.password)1957          : await vault.verifyMainPassword(payload.password);1958        if (!passwordValid) {1959          return { ok: false, error: "Incorrect master password" };1960        }1961        if (wasLocked) {1962          await setupAutoLock();1963          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });1964          onVaultUnlocked();1965        }1966        // Identity rotation needs the live vault root key. A password check is1967        // deliberately verification-only, so establish the real session first1968        // when Settings is opened after the vault session expired.1969        // Enter the blocking state before the reset steps: a crash after this1970        // point leaves the device refusing sync rather than mid-reset over live1971        // trust. Both are idempotent, so a retry is safe.1972        await enterResetRequired(browserGenerationIo);1973        const result = await confirmSecureReset(browserGenerationIo, {1974          nowMs: Date.now(),1975        });1976        return result === "V2_ANCHOR"1977          ? { ok: true, data: await resolveGeneration(browserGenerationIo) }1978          : {1979              ok: false,1980              error: "The reset did not complete — nothing was lost, try again",1981            };1982      }19831984      case "GET_SYNC_SETTINGS": {1985        if (vault.isDecoyMode()) return { ok: true, data: { mode: "off", relayUrl: "" } };1986        return { ok: true, data: await getSyncSettings() };1987      }19881989      case "SET_SYNC_SETTINGS": {1990        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1991        const payload = (msg.payload ?? {}) as {1992          mode?: unknown;1993          relayUrl?: unknown;1994        };1995        try {1996          // A custom relay URL implies private mode; Peach's own relay stays1997          // public. See setRelayUrl.1998          if (payload.relayUrl !== undefined) {1999            if (typeof payload.relayUrl !== "string") {2000              return { ok: false, error: "invalid_relay_url" };2001            }2002            return { ok: true, data: await setRelayUrl(payload.relayUrl) };2003          }2004          if (payload.mode !== undefined) {2005            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {2006              return { ok: false, error: "invalid_sync_mode" };2007            }2008            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };2009          }2010          return { ok: true, data: await getSyncSettings() };2011        } catch (error) {2012          return {2013            ok: false,2014            error: error instanceof Error ? error.message : "invalid_relay_url",2015          };2016        }2017      }201820192020      case "GET_SYNC_ALERTS": {2021        if (vault.isDecoyMode()) return { ok: true, data: [] };2022        return { ok: true, data: await getPendingSyncAlerts() };2023      }20242025      case "DISMISS_SYNC_ALERTS": {2026        if (vault.isDecoyMode()) return { ok: true };2027        const type = (msg.payload as { type?: unknown } | undefined)?.type;2028        if (type !== "DEVICE_KEY_ROTATED" && type !== "DEVICE_REVOKED") {2029          return { ok: false, error: "invalid_sync_alert_type" };2030        }2031        await dismissPendingSyncAlerts(type);2032        return { ok: true };2033      }20342035      case "GET_PENDING_VOUCHED_DEVICES": {2036        if (vault.isDecoyMode()) return { ok: true, data: [] };2037        return { ok: true, data: await listPendingVouchedDevices() };2038      }2039      case "CONFIRM_VOUCHED_DEVICE": {2040        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };2041        const { deviceId } = msg.payload as { deviceId: string };2042        const pending = await getPendingVouchedDevice(deviceId);2043        if (!pending) return { ok: false, error: "not_pending" };2044        // Last gate before a vouched device becomes a sync peer. A queue entry2045        // can predate the revocation that names it, so revocation is re-checked2046        // here rather than trusted to have swept the queue.2047        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {2048          await removePendingVouchedDevice(deviceId);2049          return { ok: false, error: "device_revoked" };2050        }2051        await upsertPairedDeviceV3({2052          deviceId: pending.deviceId,2053          deviceName: pending.deviceName,2054          deviceType:2055            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],2056          longTermPublicKeyHex: pending.longTermPublicKeyHex,2057          signingPublicKeyHex: pending.signingPublicKeyHex,2058          wsPort: pending.wsPort,2059          pairedAt: pending.pairedAt,2060          trustSource: "vouched",2061        });2062        await removePendingVouchedDevice(deviceId);2063        // Newly confirmed vouched device is now a sync target — kick a round2064        // so the mesh introduction pays off without a 10-minute wait.2065        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);2066        return { ok: true };2067      }2068      case "REJECT_VOUCHED_DEVICE": {2069        if (vault.isDecoyMode()) return { ok: true };2070        const { deviceId } = msg.payload as { deviceId: string };2071        await removePendingVouchedDevice(deviceId);2072        return { ok: true };2073      }20742075      case "ROTATE_SYNC_IDENTITY": {2076        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };2077        const epoch = vault.getVaultEpoch();2078        const { password } = (msg.payload ?? {}) as { password?: unknown };2079        if (typeof password !== "string" || !password) return { ok: false, error: "password_required" };2080        const verified = await vault.verifyMainPassword(password);2081        if (!vault.isUnlocked() || epoch !== vault.getVaultEpoch()) return { ok: false, error: "vault_locked" };2082        if (!verified) return { ok: false, error: "wrong_password" };2083        const result = await vault.rotateSyncIdentity();2084        return result.ok ? { ok: true } : { ok: false, error: result.error };2085      }20862087      default:2088        return { ok: false, error: "unknown_message_type" };2089    }2090  } catch (err) {2091    return {2092      ok: false,2093      error: err instanceof Error ? err.message : "operation_failed",2094    };2095  }2096}20972098// Returns username use-counts from the vault, sorted by frequency. Each row2099// also carries the entry's email so the popup can suggest the email/username2100// pair the user has actually used together.2101function buildIdentitySuggestions(2102  entries: VaultEntry[],2103): Array<{ email: string; username: string; count: number }> {2104  const usernameCounts = new Map<string, number>();2105  const usernameEmail = new Map<string, string>();2106  for (const entry of entries) {2107    const username = entry.username ?? "";2108    const email = (entry as VaultEntry & { email?: string }).email ?? "";2109    if (!username && !email) continue;2110    const key = username || email;2111    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);2112    if (!usernameEmail.has(key)) usernameEmail.set(key, email);2113  }2114  return Array.from(usernameCounts.entries())2115    .sort((a, b) => b[1] - a[1])2116    .map(([username, count]) => ({2117      email: usernameEmail.get(username) ?? "",2118      username,2119      count,2120    }));2121}21222123/** Notify all content scripts that the vault just became available. */2124function broadcastToContentScripts(message: { type: string }): void {2125  if (!chrome.tabs?.query) return;2126  chrome.tabs.query({}, (tabs) => {2127    for (const tab of tabs) {2128      if (tab.id !== undefined) {2129        chrome.tabs.sendMessage(tab.id, message).catch(() => {2130          // Tab may not have a content script — silently ignore2131        });2132      }2133    }2134  });2135}21362137function shouldRefreshAutoLock(2138  type: MessageType,2139  sender: Partial<chrome.runtime.MessageSender>,2140): boolean {2141  if (!isExtensionPageSender(sender)) return false;2142  return (2143    type !== "HAS_VAULT" &&2144    type !== "IS_UNLOCKED" &&2145    type !== "GET_VAULT_STATUS" &&2146    type !== "LOCK" &&2147    type !== "UPDATE_SETTINGS" &&2148    type !== "GET_PENDING_PASSKEY" &&2149    type !== "GET_PASSKEY_PROVIDER_STATE" &&2150    type !== "DECLINE_CARD_SAVE" &&2151    type !== "IS_CARD_DECLINED" &&2152    type !== "AUTOFILL_QUERY" &&2153    type !== "ML_PREDICT_BATCH"2154  );2155}21562157function canaryWebhookUrl(value: unknown): string | null {2158  if (typeof value !== "string") return null;2159  try {2160    const url = new URL(value);2161    if (url.protocol !== "https:" || url.username || url.password) return null;2162    const host = url.hostname.toLowerCase().replace(/\.+$/, "");2163    if (!host || host === "localhost" || host.endsWith(".localhost")) return null;2164    if (host.startsWith("[")) {2165      if (isUnsafeCanaryIpv6(host.slice(1, -1))) return null;2166    } else if (/^\d+(?:\.\d+){3}$/.test(host) && isUnsafeCanaryIpv4(host)) return null;2167    url.hostname = host;2168    return url.href;2169  } catch { return null; }2170}21712172function isUnsafeCanaryIpv4(host: string): boolean {2173  const [a, b, c, d] = host.split(".").map(Number);2174  return a === 0 || a === 10 || a === 127 || a >= 224 ||2175    (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) ||2176    (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) ||2177    (a === 192 && b === 0 && c === 0 && d !== 9 && d !== 10) ||2178    (a === 192 && b === 0 && c === 2) || (a === 192 && b === 88 && c === 99) ||2179    (a === 198 && (b === 18 || b === 19 || (b === 51 && c === 100))) ||2180    (a === 203 && b === 0 && c === 113);2181}21822183function isUnsafeCanaryIpv6(host: string): boolean {2184  const [head, tail = ""] = host.split("::");2185  const left = head ? head.split(":").map(value => Number.parseInt(value, 16)) : [];2186  const right = tail ? tail.split(":").map(value => Number.parseInt(value, 16)) : [];2187  const words = [...left, ...Array<number>(8 - left.length - right.length).fill(0), ...right];2188  if (words.slice(0, 5).every(word => word === 0) && words[5] === 0xffff) {2189    return isUnsafeCanaryIpv4(`${words[6] >>> 8}.${words[6] & 255}.${words[7] >>> 8}.${words[7] & 255}`);2190  }2191  // Native global-unicast literals only; transition formats are conservative exclusions.2192  if ((words[0] & 0xe000) !== 0x2000 || words[0] === 0x2002) return true;2193  if (words[0] === 0x3fff && (words[1] & 0xf000) === 0) return true;2194  if (words[0] !== 0x2001) return false;2195  if (words[1] === 0xdb8) return true;2196  if ((words[1] & 0xfe00) !== 0) return false;2197  const globalAssignment = words[1] === 3 || (words[1] === 4 && words[2] === 0x112) ||2198    (words[1] & 0xfff0) === 0x20 || (words[1] & 0xfff0) === 0x30 ||2199    (words[1] === 1 && words.slice(2, 7).every(word => word === 0) && [1, 2, 3].includes(words[7]));2200  return !globalAssignment;2201}