messages.ts

91.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 hour202203const PRIVATE_IPV4_RANGES = [204  { prefix: "10." },205  { prefix: "127." },206  { prefix: "169.254." },207  { prefix: "192.168." },208];209210export function setupMessageHandler(): void {211  chrome.runtime.onMessage.addListener(212    (msg: unknown, sender, sendResponse) => {213      if (!isMessage(msg)) {214        sendResponse({ ok: false, error: "invalid_message" });215        return true;216      }217      handleMessage(msg, sender)218        .then(sendResponse)219        .catch((err) =>220          sendResponse({221            ok: false,222            error: err instanceof Error ? err.message : String(err),223          })224        );225      return true;226    }227  );228}229230function isMessage(m: unknown): m is Message {231  return typeof m === "object" && m !== null && "type" in m;232}233234/**235 * The browser-attested origin of the page that originated this message. A web236 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),237 * so every page-driven message arrives via the content-script relay and the238 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a239 * value the page cannot forge. This is the ONLY trustworthy origin for passkey240 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.241 */242function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {243  if (sender.origin) return sender.origin;244  if (sender.url) {245    try { return new URL(sender.url).origin; } catch { return undefined; }246  }247  return undefined;248}249250function isExtensionPageSender(sender: Partial<chrome.runtime.MessageSender>): boolean {251  return sender.url?.startsWith("chrome-extension://") === true ||252    sender.url?.startsWith("moz-extension://") === true;253}254255/** True when the message came from a page frame rather than extension UI. */256function isPageSender(sender: Partial<chrome.runtime.MessageSender>): boolean {257  return !isExtensionPageSender(sender) &&258    (sender.tab !== undefined || sender.url !== undefined);259}260261function entryDomains(url: unknown, additionalUrls: unknown): Set<string> {262  const domains = new Set<string>();263  const primary = typeof url === "string" ? extractDomain(url) : null;264  if (primary) domains.add(primary);265  if (Array.isArray(additionalUrls)) {266    for (const extra of additionalUrls) {267      if (typeof extra !== "string") continue;268      const domain = extractDomain(extra);269      if (domain) domains.add(domain);270    }271  }272  return domains;273}274275const CONTENT_LOGIN_TEXT_FIELDS = new Set(["title", "username", "email", "password", "url"]);276277function normalizeContentEntryUrl(value: string): string | null {278  try {279    const trimmed = value.trim();280    const url = new URL(trimmed);281    if ((url.protocol === "https:" || url.protocol === "http:") && extractDomain(url.href)) {282      // Origin-only saves must keep matching existing duplicate keys.283      return url.pathname === "/" && !url.search && !url.hash && url.href.endsWith("/") && !trimmed.endsWith("/")284        ? url.href.slice(0, -1)285        : url.href;286    }287    return null;288  } catch {289    return null;290  }291}292293function parseContentLoginWrite(294  fields: object,295  operation: "create" | "update",296): { ok: true; fields: Record<string, unknown> } | { ok: false; error: "invalid_payload" | "origin_binding_required" } {297  const normalized: Record<string, unknown> = {};298  for (const [key, value] of Object.entries(fields)) {299    if (key === "type") {300      if (operation !== "create" || value !== "login") return { ok: false, error: "invalid_payload" };301    } else if (key === "additionalUrls") {302      if (!Array.isArray(value)) return { ok: false, error: "invalid_payload" };303      const urls: string[] = [];304      for (const extra of value) {305        if (typeof extra !== "string") return { ok: false, error: "invalid_payload" };306        const url = normalizeContentEntryUrl(extra);307        if (!url) return { ok: false, error: "origin_binding_required" };308        urls.push(url);309      }310      normalized.additionalUrls = urls;311      continue;312    } else if (!CONTENT_LOGIN_TEXT_FIELDS.has(key) ||313      (typeof value !== "string" && !(key === "email" && value === undefined))) {314      return { ok: false, error: "invalid_payload" };315    }316    if (key === "url") {317      const url = normalizeContentEntryUrl(value as string);318      if (!url) return { ok: false, error: "origin_binding_required" };319      normalized.url = url;320    } else normalized[key] = value;321  }322  if (operation === "create") {323    if (typeof normalized.title !== "string") return { ok: false, error: "invalid_payload" };324    if (typeof normalized.url !== "string") return { ok: false, error: "origin_binding_required" };325  }326  return { ok: true, fields: normalized };327}328329/**330 * PB-26-106: the autofill read path re-validates the frame origin against the331 * entry's domains on every request, so an unbound write path would let a332 * content script repoint an entry at its own origin and then read the333 * credential through a read path that is behaving correctly.334 *335 * Creating an entry: a page may only bind it to itself. Mutating one: a page336 * may never GROW the domain set — only shrink it, and never below its own337 * attested origin.338 *339 * Self-binding on mutation was considered and is not enough: the content340 * script on a foreign origin IS the attacker in the reported chain, so letting341 * it attach "its own" origin lets it mint the very capability the read path342 * exists to withhold. The legitimate flow that needs a new domain — the inline343 * "remember this site" toast — therefore asks the popup instead344 * (REQUEST_REMEMBER_SITE), which is an extension page and exempt here.345 *346 * Extension pages are exempt: the popup edits entries for sites it is not on.347 */348function senderMayBindEntryDomains(349  sender: Partial<chrome.runtime.MessageSender>,350  domains: Set<string>,351): boolean {352  if (isExtensionPageSender(sender)) return true;353  const domain = attestedSenderDomain(sender);354  if (domain === null) return false;355  for (const candidate of domains) {356    if (candidate !== domain) return false;357  }358  return true;359}360361function senderMayMutateEntryDomains(362  sender: Partial<chrome.runtime.MessageSender>,363  before: Set<string>,364  after: Set<string>,365): boolean {366  if (isExtensionPageSender(sender)) return true;367  const domain = attestedSenderDomain(sender);368  if (domain === null || !after.has(domain)) return false;369  for (const kept of after) {370    if (!before.has(kept)) return false;371  }372  return true;373}374375/**376 * Null for extension pages (which the callers exempt), for senders with no377 * attested origin at all, and for unparseable frame urls.378 */379function attestedSenderDomain(sender: Partial<chrome.runtime.MessageSender>): string | null {380  if (sender.tab === undefined && sender.url === undefined) return null;381  const origin = attestedSenderOrigin(sender);382  if (!origin) return null;383  try { return extractDomain(new URL(origin).hostname); } catch { return null; }384}385386function patchChangesEntryOrigin(patch: object): boolean {387  return Object.hasOwn(patch, "url") || Object.hasOwn(patch, "additionalUrls");388}389390/** The entry's domain-bearing fields as the patch would leave them. */391function patchedUrlShape(392  patch: object,393  existing: Pick<VaultEntry, "url" | "additionalUrls">,394): { url: unknown; additionalUrls: unknown } {395  const candidate = patch as { url?: unknown; additionalUrls?: unknown };396  return {397    url: Object.hasOwn(patch, "url") ? candidate.url : existing.url,398    additionalUrls: Object.hasOwn(patch, "additionalUrls")399      ? candidate.additionalUrls400      : existing.additionalUrls,401  };402}403// Resolves once restoreFromSession() has run, so handlers see the correct404// post-restore unlock state. entry.ts registers this BEFORE the message405// handler so the onMessage listener is added synchronously at SW startup406// (MV3 requirement) while unlock-dependent handlers still wait for restore.407let restoreReady: Promise<void> = Promise.resolve();408const MAX_ML_BATCH_FIELDS = 128;409const MAX_ML_FIELDS_PER_SECOND = 256;410const mlWorkBySender = new Map<string, { startedAt: number; fields: number }>();411412function claimMLWork(sender: Partial<chrome.runtime.MessageSender>, fields: number): boolean {413  if (fields === 0) return true;414  const now = Date.now();415  for (const [key, value] of mlWorkBySender) {416    if (now - value.startedAt >= 1_000) mlWorkBySender.delete(key);417  }418  const key = `${sender.tab?.id ?? "ui"}:${sender.frameId ?? 0}:${attestedSenderOrigin(sender) ?? "extension"}`;419  const current = mlWorkBySender.get(key);420  if (!current) {421    mlWorkBySender.set(key, { startedAt: now, fields });422    return fields <= MAX_ML_FIELDS_PER_SECOND;423  }424  if (current.fields + fields > MAX_ML_FIELDS_PER_SECOND) return false;425  current.fields += fields;426  return true;427}428429/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */430export function setRestoreReady(p: Promise<unknown>): void {431  restoreReady = p.then(() => undefined, () => undefined);432}433434export async function handleMessage(435  msg: Message,436  sender: Partial<chrome.runtime.MessageSender> = {}437): Promise<MessageResponse> {438  try {439    // Wait for session-restore to finish before reading any unlock/vault state.440    // On a cold SW start the popup's first message arrives while restore is441    // still in flight; without this gate IS_UNLOCKED would report locked (a442    // spurious lock screen) and the storage reads could race. The onMessage443    // listener itself is registered synchronously (entry.ts) so this gate, not444    // listener registration, is what absorbs the cold-start window.445    await restoreReady;446    // Validate sender — only allow messages from our extension pages/scripts.447    // `sender.id` is undefined for messages originating from extension UI448    // (popup/options), which is legitimate; reject only when it is defined449    // and does not match our extension id.450    if (451      sender.id !== undefined &&452      sender.id !== chrome.runtime.id453    ) {454      return { ok: false, error: "invalid_sender" };455    }456457    // PB-26-016: sender authorization is an exhaustive policy, not a458    // hand-maintained privileged denylist. A missing/unknown policy entry or a459    // background-only message fails closed before any handler runs.460    // Extension UI messages may legitimately omit sender.url. Resolve the461    // browser-attested extension origin only when a URL is present; this also462    // keeps test/runtime shims without getURL fail-closed for URL-bearing463    // senders instead of throwing before policy evaluation.464    const extensionOrigin = sender.url && typeof chrome.runtime.getURL === "function"465      ? chrome.runtime.getURL("")466      : "";467    if (!isMessageSenderAllowed(msg.type, sender, chrome.runtime.id, extensionOrigin)) {468      return { ok: false, error: "invalid_sender" };469    }470471    if (shouldRefreshAutoLock(msg.type, sender) && vault.isUnlocked()) {472      touchAutoLock();473    }474475    switch (msg.type) {476      case "CREATE_VAULT": {477        const { password, replacement, purpose } = (msg.payload ?? {}) as { password?: unknown; replacement?: unknown; purpose?: unknown };478        // Refuse to create a vault under an empty master password — the derived479        // key would be publicly known and the at-rest AES-GCM protection void480        // (audit HIGH; the CSV-import path previously passed ""). Length/strength481        // policy lives in the onboarding UI; this is the non-negotiable floor.482        if (typeof password !== "string" || password.length === 0 || (replacement !== undefined && replacement !== "warned-import") ||483          (purpose !== undefined && purpose !== "onboarding") || (purpose === "onboarding" && replacement !== undefined)) {484          return { ok: false, error: "invalid_payload" };485        }486        const created = await vault.createVault(password, replacement);487        if (purpose === "onboarding") await setRecoveryConfirmPending(created.unlocked && vault.isUnlocked());488        if (!created.unlocked) return { ok: true, data: created };489        try {490          await setupAutoLock();491          const unlocked = vault.isUnlocked();492          if (unlocked) {493            broadcastToContentScripts({ type: "VAULT_UNLOCKED" });494            onVaultUnlocked();495          }496          return { ok: true, data: { ...created, unlocked } };497        } catch (error) {498          console.warn("[Peach] vault saved; unlock setup failed:", error);499          await vault.lock().catch((lockError) => console.warn("[Peach] creation cleanup failed:", lockError));500          return { ok: true, data: { ...created, unlocked: false } };501        }502      }503      case "CREATE_VAULT_FROM_ROOT_KEY": {504        const { password, rootKeyHex } = (msg.payload ?? {}) as {505          password?: unknown;506          rootKeyHex?: unknown;507        };508        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {509          return { ok: false, error: "invalid_payload" };510        }511512        try {513          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);514          await setupAutoLock();515          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });516          onVaultUnlocked();517          return { ok: true, vaultId };518        } catch (err) {519          return { ok: false, error: err instanceof Error ? err.message : String(err) };520        }521      }522      case "UNLOCK": {523        const { password } = msg.payload as { password: string };524        const ok = await vault.unlock(password);525        if (ok) {526          // KAT: verify the WebCrypto stack is healthy before the user relies on it.527          // Runs after unlock so latency is hidden behind the vault-load time.528          const kat = await runSelfTest();529          if (!kat.ok) {530            console.error("[Peach] Crypto self-test FAILED:", kat.error);531            await vault.lock();532            return { ok: false, error: "self_test_failed" };533          }534          await vault.updateSettings({ pinPreferred: false });535          await setupAutoLock();536          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });537          onVaultUnlocked();538          return { ok: true };539        }540        // Distinguish corruption from wrong password so the popup can offer541        // a history-restore path instead of falsely accusing the user of542        // mistyping (M7/COR-007).543        const failure = vault.consumeLastUnlockFailureReason();544        if (failure) {545          return {546            ok: false,547            error: "vault_corrupted",548            canRestoreFromHistory: true,549          } as MessageResponse;550        }551        return { ok: false };552      }553      case "UNLOCK_WITH_PIN": {554        const { pin } = (msg.payload ?? {}) as { pin?: unknown };555        if (typeof pin !== "string") return { ok: false, error: "invalid_payload" };556        const ok = await vault.unlockWithPin(pin);557        if (!ok) {558          const status = await vault.getPinUnlockStatus();559          if (status.configured && !status.available) {560            return {561              ok: false,562              error: status.attemptsRemaining === 0563                ? "pin_attempts_exceeded"564                : "pin_session_expired",565            };566          }567          return { ok: false };568        }569        const kat = await runSelfTest();570        if (!kat.ok) {571          await vault.lock();572          return { ok: false, error: "self_test_failed" };573        }574        await vault.updateSettings({ pinPreferred: true });575        await setupAutoLock();576        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });577        onVaultUnlocked();578        return { ok: true };579      }580      case "GET_PIN_STATUS":581        return { ok: true, data: await vault.getPinUnlockStatus() };582      case "VALIDATE_RECOVERY_WORDS": {583        const { words } = msg.payload as { words: string[] };584        const invalid = findInvalidWords(words);585        return { ok: true, data: { valid: invalid.length === 0, invalid } };586      }587      case "GET_RECOVERY_WORDS": {588        // Must be unlocked and have recovery set up (vault must be v2.12+).589        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };590        const epoch = vault.getVaultEpoch();591        const current = () => vault.isUnlocked() && epoch === vault.getVaultEpoch();592        const exempt = await consumeRecoveryReveal();593        if (!current()) return { ok: false, error: "vault_locked" };594        if (!exempt) {595          const { password } = (msg.payload ?? {}) as { password?: string };596          if (typeof password !== "string" || !password) {597            return { ok: false, error: "password_required" };598          }599          const verified = await vault.verifyMainPassword(password);600          if (!current()) return { ok: false, error: "vault_locked" };601          if (!verified) {602            return { ok: false, error: "wrong_password" };603          }604        }605        try {606          const words = await vault.getRecoveryWords();607          if (!current()) return { ok: false, error: "vault_locked" };608          return { ok: true, data: words };609        } catch {610          return { ok: false, error: "recovery_not_setup" };611        }612      }613      case "GET_RECOVERY_CONFIRM_PENDING":614        return { ok: true, data: await isRecoveryConfirmPending() };615      case "CLEAR_RECOVERY_CONFIRM_PENDING":616        await clearRecoveryConfirmPending();617        if (vault.isUnlocked()) touchAutoLock();618        return { ok: true };619      case "RECOVER_WITH_WORDS": {620        // User has lost their password but has their 12 recovery words.621        // We: (1) validate the words, (2) re-encrypt vault with new password.622        if (!msg.payload || typeof msg.payload !== "object" || Array.isArray(msg.payload)) {623          return { ok: false, error: "invalid_recovery_payload" };624        }625        const { words, newPassword } = msg.payload as {626          words: string[];627          newPassword: string;628        };629        if (!Array.isArray(words) || words.some((word) => typeof word !== "string") || typeof newPassword !== "string") {630          return { ok: false, error: "invalid_recovery_payload" };631        }632        const recovered = await vault.recoverWithWords(words, newPassword);633        if (recovered.unlocked) {634          try { await setupAutoLock(); }635          catch (error) {636            console.warn("[Peach] recovery password saved; auto-lock setup failed:", error);637            try { await vault.lock(); }638            catch (lockError) { console.warn("[Peach] recovery session cleanup failed:", lockError); }639          }640        }641        const unlocked = recovered.unlocked && vault.isUnlocked();642        if (unlocked) broadcastToContentScripts({ type: "VAULT_UNLOCKED" });643        return { ok: true, data: { ...recovered, unlocked } };644      }645      case "LOCK":646        await vault.lock();647        return { ok: true };648      case "IS_UNLOCKED":649        return { ok: true, data: vault.isUnlocked() };650      case "GET_VAULT_STATUS":651        return { ok: true, unlocked: vault.isUnlocked() };652      case "HAS_VAULT":653        return { ok: true, data: await vault.hasVault() };654      case "GET_ENTRIES":655        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };656        return { ok: true, data: vault.getEntries() };657      case "EXPORT_ENTRIES": {658        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };659        const { password } = (msg.payload ?? {}) as { password?: unknown };660        if (typeof password !== "string" || !password) {661          return { ok: false, error: "password_required" };662        }663        if (!(await vault.verifyMainPassword(password))) {664          return { ok: false, error: "wrong_password" };665        }666        return { ok: true, data: vault.getEntries() };667      }668      case "ADD_ENTRY": {669        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };670        let payload = msg.payload;671        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {672          return { ok: false, error: "invalid_payload" };673        }674        if (isPageSender(sender)) {675          const parsed = parseContentLoginWrite(payload, "create");676          if (!parsed.ok) return parsed;677          payload = parsed.fields;678          const domains = entryDomains(parsed.fields.url, parsed.fields.additionalUrls);679          if (domains.size === 0 || !senderMayBindEntryDomains(sender, domains)) {680            return { ok: false, error: "origin_binding_required" };681          }682        }683        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);684        return { ok: true, data: entry };685      }686      case "BATCH_ADD_ENTRIES": {687        const payload = msg.payload as { entries?: unknown } | null | undefined;688        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {689          return { ok: false, error: "invalid_payload" };690        }691        if (!Array.isArray(payload.entries)) {692          return { ok: false, error: "invalid_payload" };693        }694        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);695        return { ok: true, data: added };696      }697      case "RESTORE_ENTRIES": {698        const payload = msg.payload as699          | { entries?: unknown; mode?: unknown; settings?: unknown }700          | null701          | undefined;702        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {703          return { ok: false, error: "invalid_payload" };704        }705        if (!Array.isArray(payload.entries)) {706          return { ok: false, error: "invalid_payload" };707        }708        if (payload.mode !== "replace" && payload.mode !== "merge") {709          return { ok: false, error: "invalid_payload" };710        }711        const summary = await vault.restoreEntries(712          payload.entries as Parameters<typeof vault.restoreEntries>[0],713          payload.mode714        );715        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {716          await vault.updateSettings(payload.settings as vault.VaultSettings);717        }718        return { ok: true, data: summary };719      }720      case "CLEAR_VAULT_ENTRIES": {721        await vault.clearVaultEntries("REPLACE_ALL");722        return { ok: true };723      }724      case "GET_VAULT_HISTORY": {725        // The history store is real-mode state by construction, so a decoy726        // session must not see it — this is where the duress session would727        // otherwise leak the real vault's activity and size (PB-26-915).728        if (vault.isDecoyMode()) return { ok: true, data: [] };729        const snapshots = await vault.getVaultHistory();730        return { ok: true, data: snapshots };731      }732      case "RESTORE_VAULT_SNAPSHOT": {733        // Same guard on the write side: a coerced session must not be able to734        // roll the real vault backwards onto an earlier snapshot.735        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };736        const { snapshotId } = msg.payload as { snapshotId: string };737        const result = await vault.restoreVaultSnapshot(snapshotId);738        if (!result.ok) return { ok: false, error: result.error };739        broadcastToContentScripts({ type: "VAULT_LOCKED" });740        return { ok: true };741      }742      case "COUNT_DUPLICATES": {743        return { ok: true, data: vault.countDuplicates() };744      }745      case "DEDUPLICATE_ENTRIES": {746        const removed = await vault.deduplicateEntries();747        return { ok: true, data: removed };748      }749      case "UPDATE_ENTRY": {750        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;751        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {752          return { ok: false, error: "invalid_payload" };753        }754        const { id, patch: inputPatch } = payload;755        if (typeof id !== "string" || !id || !inputPatch || typeof inputPatch !== "object" || Array.isArray(inputPatch)) {756          return { ok: false, error: "invalid_payload" };757        }758        let patch: object = inputPatch;759        const existingEntry = vault.getEntryById(id);760        if (!existingEntry) return { ok: false, error: "entry_not_found" };761        if (isPageSender(sender)) {762          if ((existingEntry.type ?? "login") !== "login") return { ok: false, error: "login_entries_only" };763          const parsed = parseContentLoginWrite(patch, "update");764          if (!parsed.ok) return parsed;765          patch = parsed.fields;766        }767        if (patchChangesEntryOrigin(patch) || isPageSender(sender)) {768          const before = entryDomains(existingEntry.url, existingEntry.additionalUrls);769          const after = patchedUrlShape(patch, existingEntry);770          if (!senderMayMutateEntryDomains(771            sender,772            before,773            entryDomains(after.url, after.additionalUrls),774          )) {775            return { ok: false, error: "origin_binding_required" };776          }777        }778        // Single enforcement point for the Canary Entries Pro gate. Only779        // gates the transition into a canary entry — clearing/disabling a780        // canary (`canary: undefined`) is always allowed, so existing781        // canary entries remain manageable.782        const incomingCanary = (patch as { canary?: unknown }).canary;783        if (incomingCanary && typeof incomingCanary === "object") {784          const existing = vault.getEntryById(id);785          if (!existing?.canary) {786            const gate = await requirePro("canary_entry");787            if (!gate.allowed) return { ok: false, error: "pro_required" };788          }789        }790        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);791        return { ok: true };792      }793      case "ADD_ADDITIONAL_URL": {794        const { id, url } = msg.payload as { id: string; url: string };795        const trimmed = typeof url === "string" ? url.trim() : "";796        if (!trimmed) return { ok: false, error: "url_required" };797        const existing = vault.getEntryById(id);798        if (!existing) return { ok: false, error: "entry_not_found" };799        const merged = [...(existing.additionalUrls ?? []), trimmed];800        if (!senderMayMutateEntryDomains(801          sender,802          entryDomains(existing.url, existing.additionalUrls),803          entryDomains(existing.url, merged),804        )) {805          return { ok: false, error: "origin_binding_required" };806        }807        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };808        await vault.updateEntry(id, { additionalUrls: merged });809        return { ok: true };810      }811      case "REQUEST_REMEMBER_SITE": {812        // PB-26-106: growing an entry's domain set needs a decision the page813        // cannot make for itself, so the page asks and the popup confirms. A814        // page may only ask about its own attested origin — otherwise this815        // becomes the same unbound write under a friendlier name.816        const { id, url } = (msg.payload ?? {}) as { id?: unknown; url?: unknown };817        if (typeof id !== "string" || !id) return { ok: false, error: "invalid_payload" };818        const trimmed = typeof url === "string" ? url.trim() : "";819        if (!trimmed) return { ok: false, error: "url_required" };820        if (!senderMayBindEntryDomains(sender, entryDomains(trimmed, undefined))) {821          return { ok: false, error: "origin_binding_required" };822        }823        if (!vault.getEntryById(id)) return { ok: false, error: "entry_not_found" };824        if (chrome.storage.session) {825          await chrome.storage.session.set({ pendingRememberSite: { entryId: id, url: trimmed } });826        }827        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }828        return { ok: true };829      }830      case "DELETE_ENTRY": {831        const { id } = msg.payload as { id: string };832        await vault.deleteEntry(id);833        return { ok: true };834      }835      case "GET_DELETED_ENTRIES":836        return { ok: true, data: vault.getDeletedEntries() };837      case "RESTORE_ENTRY": {838        const { id } = msg.payload as { id: string };839        await vault.restoreEntry(id);840        return { ok: true };841      }842      case "PURGE_ENTRY": {843        const { id } = msg.payload as { id: string };844        await vault.purgeEntry(id);845        return { ok: true };846      }847      case "PURGE_EXPIRED_TRASH": {848        const { retentionMs } = msg.payload as { retentionMs: number };849        const purged = await vault.purgeExpiredTrash(retentionMs);850        return { ok: true, data: purged };851      }852      case "SAVE_NOTE": {853        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };854        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };855        const now = Date.now();856        if (id) {857          const existing = vault.getEntryById(id);858          if (!existing) return { ok: false, error: "not_found" };859          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });860          return { ok: true, data: vault.getEntryById(id) };861        } else {862          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt863          // (EntryDraft omits both), so passing them was the only reason the864          // `as any` cast existed. Dropping them makes the call type-check.865          const entry = await vault.addEntry({866            type: "note",867            title: title || "Untitled",868            notes: body,869          });870          return { ok: true, data: entry };871        }872      }873      case "DELETE_NOTE": {874        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };875        const { id } = msg.payload as { id: string };876        await vault.deleteEntry(id);877        return { ok: true };878      }879      case "GET_NOTES": {880        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };881        const notes = vault.getEntries().filter(882          (e) => e.type === "note" && !e.deletedAt883        );884        return { ok: true, data: notes } as MessageResponse;885      }886      case "SEARCH_VAULT": {887        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };888        // AUD-002: shape-validate the payload before calling string methods.889        // A raw cast lets a malformed message crash the handler with TypeError.890        const { query } = (msg.payload ?? {}) as { query?: unknown };891        if (typeof query !== "string") {892          return { ok: false, error: "invalid_payload" };893        }894        const q = query.toLowerCase();895        const searchResults = vault.getEntries().filter(896          (e) =>897            !e.deletedAt &&898            (e.title.toLowerCase().includes(q) ||899              e.notes?.toLowerCase().includes(q) ||900              e.username?.toLowerCase().includes(q))901        );902        return { ok: true, data: searchResults } as MessageResponse;903      }904      case "AUTOFILL_QUERY": {905        if (!vault.isUnlocked()) {906          return { ok: false, error: "vault_locked" };907        }908        const { domain, kind, capability } = msg.payload as {909          domain: string;910          kind?: "login" | "card" | "totp";911          capability?: string;912        };913        const includeAll = consumeSummonCapability(capability, sender, "inventory");914        if (capability !== undefined && !includeAll) {915          return { ok: false, error: "entry_not_found" };916        }917        // kind="card": return saved cards as compact summaries for the918        // inline card silver platter. Cards are not domain-scoped — every919        // saved card is a candidate on every checkout page — so domain is920        // ignored when kind === "card".921        if (kind === "card") {922          if (!includeAll) return { ok: true, data: [] };923          const cards = vault.getEntries().filter((e) => e.type === "card");924          return {925            ok: true,926            data: cards.map((e) => ({927              id: e.id,928              title: e.cardNickname || e.title,929              cardholderName: e.cardholderName,930              last4: e.last4,931              expMonth: e.expMonth,932              expYear: e.expYear,933              network: e.network,934            })),935          };936        }937        const scopedDomain = isPageSender(sender)938          ? attestedSenderDomain(sender)939          : typeof domain === "string"940            ? extractDomain(domain)941            : null;942        if (!includeAll && !scopedDomain) {943          return isPageSender(sender)944            ? { ok: false, error: "origin_unverified" }945            : { ok: true, data: [] };946        }947        if (kind === "totp") {948          const matches = (949            includeAll950              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")951              : vault.queryDomain(scopedDomain!)952          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));953          return {954            ok: true,955            data: matches.map((e) => ({956              id: e.id,957              title: e.title,958              username: e.username,959              email: e.email,960              url: e.url,961              hasTotp: true,962            })),963          };964        }965        // The inline selector fills username+password into a form. Passkey-966        // only entries have no password to fill; sign-in for those goes967        // through the WebAuthn path instead. Filter them out everywhere so968        // the user doesn't see four "GitHub" rows that mostly do nothing.969        // Notes and cards never belonged here either.970        const matches = (971          includeAll972            ? vault973                .getEntries()974                .filter((entry) => entry.type !== "note" && entry.type !== "card")975            : vault.queryDomain(scopedDomain!)976        ).filter((entry) => !isPasskeyOnly(entry));977        return {978          ok: true,979          data: matches.map((e) =>980            includeAll981              ? {982                  id: e.id,983                  title: e.title,984                  // username/email/url shipped so the inline popup's search985                  // affordance can match on them, not just titles. No secrets986                  // cross the boundary — same shape as the domain-matched987                  // response below minus hasTotp (which the search list988                  // doesn't surface).989                  username: e.username,990                  email: e.email,991                  url: e.url,992                  hasPasskey: e.passkey !== undefined,993                }994              : {995                  id: e.id,996                  title: e.title,997                  username: e.username,998                  email: e.email,999                  url: e.url,1000                  hasTotp: Boolean(e.totp),1001                  hasPasskey: e.passkey !== undefined,1002                }1003          ),1004        };1005      }1006      case "GET_ENTRY_FOR_FILL": {1007        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1008        const { id, capability } = msg.payload as {1009          id: string;1010          capability?: string;1011        };1012        const capabilityAuthorized = capability !== undefined && consumeSummonCapability(capability, sender, "fill");1013        const senderDomain = isPageSender(sender) ? attestedSenderDomain(sender) : null;1014        if (isPageSender(sender) && !senderDomain) {1015          return { ok: false, error: "origin_unverified" };1016        }1017        const entry = vault.getEntryById(id);1018        if (!entry) return { ok: false, error: "entry_not_found" };10191020        // MV-1: re-validate the entry against the requesting frame's origin.1021        // sender.url / sender.tab.url are browser-attested — a page cannot1022        // forge them. PB-26-005: the FRAME url (sender.url) is authoritative1023        // for an all_frames content script; the top-frame tab.url would1024        // misattribute a cross-origin iframe's request to the top page. When1025        // the request does not come from a tab at all (popup surfaces use1026        // GET_ENTRY_FOR_EDIT, not this), refuse.1027        if (senderDomain && !capabilityAuthorized) {1028          if (!entryDomains(entry.url, entry.additionalUrls).has(senderDomain)) {1029            // Domain mismatch — refuse silently (no oracle about which ids exist).1030            return { ok: false, error: "entry_not_found" };1031          }1032        }1033        // Passkey-only entries (passkey credential, no password) cannot be1034        // filled into a form — sign-in goes through the WebAuthn path. A1035        // login that ALSO has a passkey is still fillable for its password.1036        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };1037        // Strip the passkey credential AND the raw base32 TOTP seed from the1038        // response. Content scripts never need either: the private key is the1039        // authenticator's, and handing over the TOTP seed would let a1040        // compromised content script mint valid codes indefinitely (SEV-3-C).1041        // Generate the *current* 6-digit code here in the background and send1042        // only that, plus the seconds left so the UI can render a countdown.1043        // Also drop passwordHistory: filling needs only the *current* password.1044        // Handing every past password to a content script during passive1045        // autofill on an arbitrary page would widen the blast radius of a1046        // compromised page far beyond the one credential being filled.1047        const {1048          passkey: _strippedPasskey,1049          totp: seed,1050          totpAlgorithm,1051          totpDigits,1052          totpPeriod,1053          passwordHistory: _ph,1054          ...safeEntry1055        } = entry;1056        let totpCode: string | undefined;1057        let totpRemaining: number | undefined;1058        if (seed) {1059          try {1060            // PCH-01-019: honour stored algorithm/digits/period (defaults apply1061            // when these are undefined, i.e. RFC-default bare-seed entries).1062            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);1063            totpCode = generated.code;1064            totpRemaining = generated.remaining;1065          } catch {1066            totpCode = undefined;1067          }1068        }1069        if (isPageSender(sender) && vault.isUnlocked()) touchAutoLock();1070        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };1071      }1072      // Trusted full-entry fetch for extension-owned edit surfaces. Content1073      // scripts route editing to the popup and cannot call this message.1074      case "GET_ENTRY_FOR_EDIT": {1075        if (isPageSender(sender)) return { ok: false, error: "invalid_sender" };1076        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1077        const { id } = msg.payload as { id: string };1078        const entry = vault.getEntryById(id);1079        if (!entry) return { ok: false, error: "entry_not_found" };10801081        const { passkey: _passkey, ...safeEntry } = entry;1082        return { ok: true, data: safeEntry };1083      }1084      case "COPY": {1085        // Page relays must carry the browser-attested frame origin, as with1086        // SUMMON/fill. The policy admits content scripts; this binds the1087        // admitted page sender before arming clipboard auto-clear.1088        if (isPageSender(sender) && !attestedSenderOrigin(sender)) {1089          return { ok: false, error: "invalid_sender" };1090        }1091        // AUD-002: shape-validate the payload before passing to the clipboard1092        // helper. A raw cast lets a malformed message reach the clipboard API1093        // with a non-string and throw.1094        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {1095          text?: unknown;1096          label?: unknown;1097          alreadyWritten?: unknown;1098        };1099        if (typeof text !== "string" || typeof label !== "string") {1100          return { ok: false, error: "invalid_payload" };1101        }1102        await copyToClipboard(text, label, Boolean(alreadyWritten));1103        return { ok: true, clearSeconds: getEffectiveClearSeconds() };1104      }1105      case "CHECK_ALL_BREACHES": {1106        const allEntries = vault.getEntries();1107        const results: Record<string, number> = {};1108        for (const entry of allEntries) {1109          if (entry.type === "note") continue;1110          if (!entry.password) continue;1111          results[entry.id] = await vault.checkBreach(entry.password);1112          // Small delay — be a good citizen to the HIBP API1113          await new Promise((r) => setTimeout(r, 200));1114        }1115        // Persist any non-zero counts back to entries1116        for (const [id, count] of Object.entries(results)) {1117          const entry = vault.getEntryById(id);1118          if (entry && (entry.breach ?? 0) !== count) {1119            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });1120          }1121        }1122        return { ok: true, data: results };1123      }1124      case "GET_SETTINGS": {1125        const settings = await vault.ensureSettingsLoaded();1126        if (!isPageSender(sender)) return { ok: true, data: settings };11271128        const safeSettings: Pick<vault.VaultSettings, "accentColor" | "theme"> & {1129          manualSummonDomains?: NonNullable<vault.VaultSettings["manualSummonDomains"]>;1130        } = {1131          accentColor: settings.accentColor,1132          theme: settings.theme,1133        };1134        const domain = attestedSenderDomain(sender);1135        const ownSummon = domain ? settings.manualSummonDomains?.[domain] : undefined;1136        if (domain && ownSummon) safeSettings.manualSummonDomains = { [domain]: ownSummon };1137        return { ok: true, data: safeSettings };1138      }1139      case "UPDATE_SETTINGS": {1140        const patch = msg.payload;1141        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {1142          return { ok: false, error: "invalid_payload" };1143        }1144        await vault.updateSettings(patch as vault.VaultSettings);1145        if ((patch as Record<string, unknown>).lockedSyncRequiresUnlock === true) {1146          await clearLockedSyncPrivateKey();1147        }1148        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {1149          await setupAutoLock();1150          if (vault.isUnlocked()) touchAutoLock();1151        }1152        return { ok: true };1153      }1154      case "SETUP_PIN": {1155        const { currentPassword, pin } = (msg.payload ?? {}) as {1156          currentPassword?: unknown;1157          pin?: unknown;1158        };1159        if (typeof currentPassword !== "string" || typeof pin !== "string") {1160          return { ok: false, error: "invalid_payload" };1161        }1162        return (await vault.setupPinUnlock(currentPassword, pin))1163          ? { ok: true }1164          : { ok: false, error: "incorrect_current_password" };1165      }1166      case "DISABLE_PIN": {1167        const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown };1168        if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" };1169        return (await vault.disablePinUnlock(currentPassword))1170          ? { ok: true }1171          : { ok: false, error: "incorrect_current_password" };1172      }1173      case "GET_PENDING_PASSKEY":1174        return { ok: true, data: await getPendingPasskeyRequest() };1175      case "APPROVE_PASSKEY": {1176        const { requestId } = msg.payload as { requestId: number };1177        await resolvePendingPasskeyRequest(requestId, true);1178        return { ok: true };1179      }1180      case "DENY_PASSKEY": {1181        const { requestId } = msg.payload as { requestId: number };1182        await resolvePendingPasskeyRequest(requestId, false);1183        return { ok: true };1184      }1185      case "GET_PASSKEY_PROVIDER_STATE":1186        return { ok: true, data: await getPasskeyProviderState() };1187      case "SET_PASSKEY_PROVIDER_ENABLED": {1188        const { enabled } = msg.payload as { enabled: boolean };1189        // Disabling is always free; gating fires only when a free user is1190        // trying to turn passkey interception on.1191        if (enabled) {1192          const gate = await requirePro("passkeys");1193          if (!gate.allowed) return { ok: false, error: "pro_required" };1194        }1195        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };1196      }1197      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS1198      // endpoint. Intentional product behavior — users configure their own1199      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private1200      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-1201      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to1202      // users that the entry title leaves the device when the canary fires.1203      case "FIRE_CANARY_PING": {1204        // Canary alert fires unconditionally for any entry with canary: true.1205        // The Pro gate only governs creation/flagging of canary entries; once1206        // an entry is flagged, the alert path is a security property and must1207        // never be license-gated.1208        const { webhookUrl, entryTitle, trigger } = msg.payload as {1209          webhookUrl: string;1210          entryTitle: string;1211          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";1212        };1213        if (trigger === "test" && !isExtensionPageSender(sender)) {1214          return { ok: false, error: "invalid_sender" };1215        }1216        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {1217          return { ok: false, error: "invalid_webhook_url" };1218        }1219        // LV-3: debounce non-test pings per (webhook, entry) so a page that1220        // strobes focus/fill events can't turn the canary into a request1221        // firehose at the user's endpoint. Test pings are exempt — they are1222        // explicit user clicks in the settings UI and are awaited for1223        // feedback. The FIRST ping in a window always goes out, so the1224        // dead-man's-switch property (canary fires on access) is preserved;1225        // only repeats within the window are coalesced.1226        if (trigger !== "test") {1227          const keyDigest = new Uint8Array(1228            await crypto.subtle.digest(1229              "SHA-256",1230              new TextEncoder().encode(`${webhookUrl}:${entryTitle}`),1231            ),1232          );1233          const keySuffix = Array.from(keyDigest)1234            .map((byte) => byte.toString(16).padStart(2, "0"))1235            .join("");1236          const rlKey = `canary-last-fetch:${keySuffix}`;1237          const legacyRlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;1238          const stored = await chrome.storage.local.get(rlKey);1239          await chrome.storage.local.remove(legacyRlKey);1240          const last = (stored as Record<string, unknown>)[rlKey];1241          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {1242            return { ok: true, data: { rateLimited: true } };1243          }1244          await chrome.storage.local.set({ [rlKey]: Date.now() });1245        }1246        const body = JSON.stringify({1247          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",1248          entry: entryTitle,1249          trigger,1250          timestamp: new Date().toISOString(),1251          source: "peach-extension",1252        });1253        if (trigger === "test") {1254          // Permitted outbound fetch: user-configured canary alert endpoint1255          // (validated by isAllowedCanaryWebhookUrl above). This is the1256          // only non-HIBP outbound call in the extension — see1257          // Projects.md §3.7. Test pings are awaited so the UI can show1258          // success/failure.1259          try {1260            const res = await fetch(webhookUrl, {1261              method: "POST",1262              headers: { "Content-Type": "application/json" },1263              body,1264            });1265            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1266          } catch (err) {1267            return { ok: false, error: err instanceof Error ? err.message : "network_error" };1268          }1269        }1270        // Non-test triggers are fire-and-forget1271        fetch(webhookUrl, {1272          method: "POST",1273          headers: { "Content-Type": "application/json" },1274          body,1275        }).catch(() => {});1276        return { ok: true };1277      }1278      case "ACTIVATE_LICENSE": {1279        const { key } = msg.payload as { key: string };1280        const licenseInfo = await activateLicense(key);1281        return { ok: true, data: licenseInfo };1282      }1283      case "GET_LICENSE": {1284        const licenseInfo = await getLicenseInfo();1285        return { ok: true, data: licenseInfo };1286      }1287      case "GET_LICENSE_KEY": {1288        const key = await getLicenseKey();1289        return { ok: true, data: key };1290      }1291      case "DEACTIVATE_LICENSE": {1292        await deactivateLicense();1293        return { ok: true };1294      }1295      case "SHOULD_PLAY_CELEBRATION": {1296        const should = await shouldPlayCelebration();1297        return { ok: true, data: should };1298      }1299      case "MARK_CELEBRATION_PLAYED": {1300        await markCelebrationPlayed();1301        return { ok: true };1302      }1303      case "GET_CODEX_VAULT_DATA": {1304        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1305        // popup navigates to the License section without further coordination.1306        // Also privileged-page-gated (PB-26-001), and recoveryWords inside the1307        // snapshot additionally require a fresh master-password proof.1308        const gate = await requirePro("codex");1309        if (!gate.allowed) return { ok: false, error: "pro_required" };1310        const { password } = (msg.payload ?? {}) as { password?: string };1311        return await handleGetCodexVaultData(password);1312      }1313      case "ESTIMATE_CODEX_PAGES": {1314        const gate = await requirePro("codex");1315        if (!gate.allowed) return { ok: false, error: "pro_required" };1316        return await handleEstimateCodexPages();1317      }1318      case "RESTORE_FROM_CODEX": {1319        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1320        // be able to restore a vault that was printed by a Pro user.1321        // DO NOT add a Pro gate here.1322        // A decoy session, though, holds no real-mode authority: this path1323        // writes SLOT_A/SLOT_B and snapshots history, so it carries the same1324        // guard its thirteen neighbours do (PB-26-915).1325        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1326        const payload = msg.payload as CodexRestorePayload;1327        return await handleRestoreFromCodex(payload);1328      }1329      case "OPEN_PRO_GATE": {1330        // Content script requests: open popup and navigate to License section.1331        const { feature } = (msg.payload ?? {}) as { feature?: string };1332        if (chrome.storage.session) {1333          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1334        }1335        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1336        return { ok: true };1337      }1338      case "OPEN_POPUP": {1339        // Content script asks to open the trusted extension popup — used by the1340        // inline locked bubble so the master password is entered in the popup,1341        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1342        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1343        // toolbar icon. The badge already signals Peach needs attention.1344        //1345        // Set a session flag so the popup knows it was opened for inline unlock1346        // and should close itself once the vault is unlocked (returning the user1347        // to the inline autofill selector on the page).1348        const { entryId } = (msg.payload ?? {}) as { entryId?: unknown };1349        if (entryId !== undefined && (typeof entryId !== "string" || entryId.length === 0 || entryId.length > 64)) {1350          return { ok: false, error: "invalid_payload" };1351        }1352        if (chrome.storage.session) {1353          if (typeof entryId === "string") {1354            await chrome.storage.session.set({ peach_open_entry: entryId });1355          } else {1356            await chrome.storage.session.set({ peach_inline_unlock: true });1357          }1358        }1359        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1360        return { ok: true };1361      }1362      case "OPEN_DETACHED_POPUP": {1363        // A window created by the action popup and then orphaned with1364        // window.close() is cascaded shut by Chrome, so the file-picker1365        // flows (OS dialogs that dismiss the popup on focus loss) ask the SW1366        // to open the standalone window instead — the SW has no window to be1367        // associated with. The query string is allowlisted so this can never1368        // open an arbitrary URL.1369        const { route } = (msg.payload ?? {}) as { route?: string };1370        const search = route === "peachscript"1371          ? "?restore=peachscript"1372          : route === "csv"1373            ? "?restore=csv"1374            : route === "codex-pdf"1375              ? "?codex=pdf"1376              : null;1377        if (!search) return { ok: false, error: "bad_route" };1378        try {1379          const popupHtml =1380            chrome.runtime.getManifest().action?.default_popup ?? "src/popup/index.html";1381          await chrome.windows.create({1382            url: chrome.runtime.getURL(`${popupHtml}${search}`),1383            type: "popup",1384            width: 320,1385            height: 550,1386          });1387          return { ok: true, data: { detached: true } };1388        } catch {1389          return { ok: false };1390        }1391      }1392      case "GET_IDENTITIES": {1393        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1394        return { ok: true, data: vault.getIdentities() };1395      }1396      case "TOUCH_AUTO_LOCK": {1397        // touchAutoLock() is already called by shouldRefreshAutoLock above;1398        // this case just gives the popup a typed message to keep the session alive.1399        return { ok: true };1400      }1401      case "GET_ADVANCED_HEALTH_REPORT": {1402        const gate = await requirePro("advanced_health");1403        if (!gate.allowed) return { ok: false, error: "pro_required" };1404        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1405        const report = await buildAdvancedHealthReport(vault.getEntries());1406        return { ok: true, data: report };1407      }1408      case "IS_DURESS_ENABLED": {1409        const enabled = await vault.isDuressEnabled();1410        return { ok: true, data: enabled };1411      }1412      case "SETUP_DURESS": {1413        // Single enforcement point for the Duress Vault Pro gate. Free users1414        // who somehow reach this handler are rejected here; the popup also1415        // pre-checks isPro() to avoid showing the setup form to free users,1416        // but server-side is the actual security boundary.1417        const gate = await requirePro("duress_vault");1418        if (!gate.allowed) return { ok: false, error: "pro_required" };1419        // MV3 service workers restart after inactivity, losing the in-memory1420        // derived key. Detect this before calling setupDuress so the popup1421        // can show a meaningful prompt to re-lock and re-unlock.1422        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1423        const { duressPassword } = msg.payload as { duressPassword: string };1424        await vault.setupDuress(duressPassword);1425        return { ok: true };1426      }1427      case "DISABLE_DURESS": {1428        await vault.disableDuress();1429        return { ok: true };1430      }1431      case "VERIFY_MAIN_PASSWORD": {1432        const { password } = msg.payload as { password: string };1433        const ok = await vault.verifyMainPassword(password);1434        return { ok: true, data: ok };1435      }1436      case "CHANGE_PASSWORD": {1437        const { currentPassword, newPassword } = msg.payload as {1438          currentPassword: string;1439          newPassword: string;1440        };1441        const changed = await vault.changePassword(currentPassword, newPassword);1442        return changed1443          ? { ok: true }1444          : { ok: false, error: "incorrect_current_password" };1445      }1446      case "GET_SITE_PASSWORD_POLICY": {1447        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1448        if (!tab?.id) return { ok: true, data: null };1449        try {1450          const response = await chrome.tabs.sendMessage(tab.id, {1451            type: "GET_SITE_PASSWORD_POLICY",1452          });1453          return (response as MessageResponse) ?? { ok: true, data: null };1454        } catch {1455          return { ok: true, data: null };1456        }1457      }1458      case "RECORD_MANUAL_SUMMON": {1459        const { domain } = (msg.payload ?? {}) as { domain?: unknown };1460        const origin = attestedSenderOrigin(sender);1461        let senderDomain: string | null = null;1462        if (origin) {1463          try {1464            const hostname = new URL(origin).hostname;1465            senderDomain = extractDomain(hostname) ?? hostname;1466          } catch {1467            senderDomain = null;1468          }1469        }1470        if (typeof domain !== "string" || domain.length > 253 || domain !== senderDomain) {1471          return { ok: false, error: "invalid_domain" };1472        }1473        const settings = vault.getSettings();1474        const existing = settings.manualSummonDomains?.[domain];1475        const now = Date.now();1476        await vault.updateSettings({1477          manualSummonDomains: {1478            ...settings.manualSummonDomains,1479            [domain]: {1480              firstSummonedAt: existing?.firstSummonedAt ?? now,1481              summonCount: (existing?.summonCount ?? 0) + 1,1482              lastSummonedAt: now,1483            },1484          },1485        });1486        return { ok: true };1487      }1488      case "DECLINE_CARD_SAVE": {1489        // PB-26-108: the declined-card digest is keyed by root-key material, so1490        // a decline cannot be recorded while locked. Offers are not shown while1491        // locked either, so this is unreachable in practice.1492        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1493        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1494        await vault.declineCardSaveOffer(last4, expMonth, expYear);1495        return { ok: true };1496      }1497      case "IS_CARD_DECLINED": {1498        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1499        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1500        return { ok: true, data: declined };1501      }1502      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1503        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1504          rpId?: string;1505          rpName?: string;1506          userName?: string;1507          userDisplayName?: string;1508        };1509        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1510        return await initiateFirefoxPasskeyCreate({1511          rpId,1512          rpName: rpName ?? rpId,1513          userName,1514          userDisplayName,1515        }, attestedSenderOrigin(sender));1516      }15171518      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1519        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1520        if (!payload) return { ok: false, error: "missing_payload" };1521        return await completeFirefoxPasskeyCreate(payload);1522      }15231524      case "PASSKEY_OFFER_DECLINE": {1525        const { domain } = (msg.payload ?? {}) as { domain?: string };1526        const origin = attestedSenderOrigin(sender);1527        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1528        await recordPasskeyOfferDecline(domain);1529        return { ok: true };1530      }15311532      case "GET_PASSKEY_OFFER_DECLINED": {1533        const { domain } = (msg.payload ?? {}) as { domain?: string };1534        const origin = attestedSenderOrigin(sender);1535        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1536        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1537      }15381539      case "PASSKEY_HAS_CREDENTIALS": {1540        const payload = msg.payload as {1541          rpId?: string;1542          allowCredentials?: Array<{ id: string; type?: string }>;1543        } | undefined;1544        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1545        return await handlePasskeyHasCredentials({1546          rpId: payload.rpId,1547          allowCredentials: payload.allowCredentials ?? [],1548        }, attestedSenderOrigin(sender));1549      }15501551      case "PASSKEY_CREATE": {1552        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1553        if (!payload?.rpId || !payload?.userName) {1554          return { ok: false, error: "rpid_and_username_required" };1555        }1556        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1557      }15581559      case "PASSKEY_GET": {1560        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1561        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1562        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1563      }15641565      case "PASSKEY_AUTH_RESPONSE": {1566        const { requestId, approved } = (msg.payload ?? {}) as {1567          requestId?: string | number;1568          approved?: boolean;1569        };1570        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1571          return { ok: false, error: 'requestId and approved required' };1572        }1573        const pending = await getPendingPasskeyRequest();1574        const senderOrigin = attestedSenderOrigin(sender);1575        if (1576          !pending ||1577          pending.tabId === undefined ||1578          pending.crossOrigin === true ||1579          pending.requestId !== Number(requestId) ||1580          sender.tab?.id !== pending.tabId ||1581          senderOrigin !== pending.origin1582        ) {1583          return { ok: false, error: "invalid_passkey_approval_sender" };1584        }1585        await resolvePendingPasskeyRequest(Number(requestId), approved);1586        return { ok: true };1587      }15881589      case "GET_PASSKEY_FOR_DOMAIN": {1590        const { domain } = (msg.payload ?? {}) as { domain?: string };1591        if (!domain) return { ok: false, error: "domain_required" };1592        // Scope to the caller's own origin: a page may only ask about passkeys1593        // for a domain it actually owns, so an arbitrary page cannot enumerate1594        // which sites the user holds passkeys for or read the username (audit MEDIUM).1595        const origin = attestedSenderOrigin(sender);1596        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1597        if (!vault.isUnlocked()) return { ok: true, data: null };1598        const match = vault1599          .getEntries()1600          .find((entry) => entry.passkey?.rpId === domain);1601        if (!match || !match.passkey) return { ok: true, data: null };1602        // Slim shape — only the fields State 11 needs. Never expose private1603        // key material, even though this is locked behind isUnlocked.1604        // bannerShown is the per-domain "already surfaced" flag, kept in1605        // trusted background session storage so content scripts never touch1606        // chrome.storage.session directly (PB-26-203).1607        let bannerShown = false;1608        if (chrome.storage.session) {1609          const flag = await chrome.storage.session.get(`peach_state11_shown:${domain}`);1610          bannerShown = Boolean((flag as Record<string, unknown>)[`peach_state11_shown:${domain}`]);1611        }1612        return {1613          ok: true,1614          data: {1615            rpId: match.passkey.rpId,1616            userName: match.passkey.userName,1617            browser: match.passkey.browser,1618            bannerShown,1619          },1620        };1621      }16221623      case "MARK_PASSKEY_BANNER_SHOWN": {1624        const { domain } = (msg.payload ?? {}) as { domain?: string };1625        if (typeof domain !== "string" || !domain) return { ok: false, error: "domain_required" };1626        // Same origin binding as the read path: a page may only mark its own1627        // domain, and the flag reveals nothing either way.1628        const origin = attestedSenderOrigin(sender);1629        if (!origin || !isValidRpId(domain, origin)) return { ok: true };1630        if (chrome.storage.session) {1631          await chrome.storage.session.set({ [`peach_state11_shown:${domain}`]: Date.now() });1632        }1633        return { ok: true };1634      }16351636      case "DESTROY_VAULT": {1637        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1638        // storage.local.clear() wipes every Peach key (slots, settings, license,1639        // onboarded flag, history, sync state, declined cards, recall, etc.);1640        // session.clear() wipes pending passkey requests + pro-notice queues.1641        // Caller (Panic.tsx) handles UI navigation back to onboarding.1642        //1643        // The Pro license is the one thing that must survive: the user paid for1644        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1645        // Capture it before the clear and restore it after. peach_pro_celebrated1646        // rides along so the Pro celebration doesn't replay on the next unlock.1647        await vault.withVaultRemoval(async () => {1648          const preserved = await chrome.storage.local.get([1649            "peach_license",1650            "peach_pro_celebrated",1651          ]);1652          await storageClear();1653          await vault.clearVaultHistory();1654          const toRestore: Record<string, unknown> = {};1655          if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1656          if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1657          if (Object.keys(toRestore).length > 0) {1658            await chrome.storage.local.set(toRestore);1659          }1660          if (chrome.storage.session) {1661            await chrome.storage.session.clear();1662          }1663          await clearRecoveryConfirmPending();1664        });1665        return { ok: true };1666      }16671668      case "GET_IDENTITY_SUGGESTIONS": {1669        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1670        const entries = vault.getEntries();1671        const suggestions = buildIdentitySuggestions(entries);1672        return { ok: true, data: { suggestions } };1673      }1674      case "ML_INIT":1675        return { ok: true };16761677      case "ML_PREDICT_BATCH": {1678        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1679        if (!isValidMLFeatureBatch(featuresArray, MAX_ML_BATCH_FIELDS)) {1680          return { ok: false, error: "invalid_payload" };1681        }1682        if (!claimMLWork(sender, featuresArray.length)) {1683          return { ok: false, error: "rate_limited" };1684        }1685        return { ok: true, data: mlPredictBatch(featuresArray) };1686      }16871688      // ── Vault sync (v3) ───────────────────────────────────────────────1689      // Returns the public-facing local identity needed by the popup to1690      // drive Phase-1 audio pairing. The private long-term key never1691      // leaves the background.1692      case "GET_LOCAL_IDENTITY": {1693        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1694        // Pro license from an already-Pro peer (at least one device must be Pro).1695        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1696        // The identity is sealed under its own key rather than derived from the1697        // root, so pairing survives a master-password change (SEV-2-B).1698        const identity: LocalDeviceIdentity & { license?: string } = await buildLocalIdentity();1699        // If this device is Pro, advertise the signed license so the peer can1700        // activate it after SAS confirmation — pairing carries Pro across.1701        if (await isProUser()) {1702          const license = await getLicenseKey();1703          if (license) identity.license = license;1704        }1705        return { ok: true, data: identity };1706      }17071708      case "LIST_PAIRED_DEVICES": {1709        if (vault.isDecoyMode()) return { ok: true, data: { devices: [] } };1710        try {1711          const devices = await listPairedDevicesV3();1712          return { ok: true, data: { devices } };1713        } catch (err) {1714          if (err instanceof TrustDataCorruptedError) {1715            return { ok: false, error: "trust_data_corrupted" };1716          }1717          throw err;1718        }1719      }17201721      case "RENAME_PAIRED_DEVICE": {1722        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1723        const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string };1724        if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") {1725          return { ok: false, error: "invalid_payload" };1726        }1727        await renamePairedDeviceV3(deviceId, name);1728        return { ok: true };1729      }17301731      case "UNPAIR_DEVICE": {1732        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1733        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1734        if (typeof deviceId !== "string" || !deviceId) {1735          return { ok: false, error: "invalid_payload" };1736        }1737        // A damaged legacy identity must not prevent the user from evicting a1738        // peer locally. Sync is already blocked until the secure reset repairs1739        // this installation, so the local issuer marker is sufficient for the1740        // tombstone that will be cleared with the archived generation.1741        let revokedByDeviceId: string;1742        try {1743          revokedByDeviceId = await getOrCreateDeviceId();1744        } catch (error) {1745          if (!(error instanceof Error) || error.message !== "identity_migration_required") throw error;1746          revokedByDeviceId = "local";1747        }1748        await revokeDeviceByIdV3(deviceId, revokedByDeviceId);1749        // PB-26-213: forget the secret now so no further dial can use it.1750        // Removals that happen while locked leave orphans for the next1751        // unlock's reconcile to prune.1752        const unpairRootHex = vault.getRootKeyHex();1753        if (unpairRootHex) {1754          const unpairRoot = unhexBytes(unpairRootHex);1755          try {1756            await dropPairSecret(deviceId, unpairRoot);1757          } finally {1758            unpairRoot.fill(0);1759          }1760        } else {1761          await dropPairSecret(deviceId, null);1762        }1763        // Sync against the remaining hosts — the unpaired device no longer1764        // matters but the next alarm tick is up to ten minutes away.1765        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1766        return { ok: true };1767      }17681769      case "RENAME_LOCAL_DEVICE": {1770        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1771        const { name } = (msg.payload ?? {}) as { name?: string };1772        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1773        await setDeviceNameV3(name);1774        return { ok: true };1775      }17761777      // ── Relay pairing ─────────────────────────────────────────────────────1778      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1779      // session runs in the background; the SAS and the terminal result reach1780      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1781      case "START_ADOPTION_SOURCE": {1782        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1783        if (isRelayAdoptionSourceInFlight()) {1784          return { ok: false, error: "adoption_source_in_progress" };1785        }1786        try {1787          return { ok: true, data: await startRelayAdoptionSource() };1788        } catch (error) {1789          return {1790            ok: false,1791            error: error instanceof Error ? error.message : "adoption_source_failed",1792          };1793        }1794      }17951796      // Onboarding receiver — empty extension shows a QR, phone scans and1797      // sends the vault. The popup supplies the local-only password here so1798      // the background can wrap the adopted root key at rest without ever1799      // asking the user to retype it.1800      case "START_ADOPTION_RECEIVER": {1801        if (isRelayAdoptionSourceInFlight()) {1802          return { ok: false, error: "adoption_receiver_in_progress" };1803        }1804        const password = (msg.payload as { password?: unknown } | undefined)?.password;1805        if (typeof password !== "string" || password.length === 0) {1806          return { ok: false, error: "invalid_payload" };1807        }1808        try {1809          return { ok: true, data: await startRelayAdoptionReceiver(password) };1810        } catch (error) {1811          return {1812            ok: false,1813            error: error instanceof Error ? error.message : "adoption_receiver_failed",1814          };1815        }1816      }18171818      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1819      // on the source's SAS screen. The id round-trips the same way so a stale1820      // late response can't approve the wrong session.1821      case "RECEIVER_SAS_DECISION": {1822        const payload = msg.payload as { id?: unknown; sas?: unknown; ok?: unknown } | undefined;1823        if (typeof payload?.id !== "string" || typeof payload.sas !== "string" || typeof payload.ok !== "boolean") {1824          return { ok: false, error: "invalid_payload" };1825        }1826        return { ok: resolveReceiverSasConfirmation(payload.id, payload.sas, payload.ok) };1827      }18281829      case "SOURCE_SAS_DECISION": {1830        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1831        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1832          return { ok: false, error: "invalid_payload" };1833        }1834        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1835      }1836      case "LIST_PENDING_ADOPTION_HOLDERS": {1837        return { ok: true, data: await listPendingAdoptionHolders() };1838      }18391840      case "REMOVE_PENDING_ADOPTION_HOLDER": {1841        await removePendingAdoptionHolder();1842        return { ok: true };1843      }184418451846      case "CANCEL_ADOPTION_SOURCE": {1847        cancelRelayAdoptionSource();1848        return { ok: true };1849      }18501851      case "TRIGGER_SYNC": {1852        if (vault.isDecoyMode()) return { ok: true };1853        const payload = (msg.payload ?? {}) as {1854          reason?: "vault_change" | "foreground" | "manual";1855          force?: boolean;1856        };1857        const reason = payload.reason ?? "foreground";18581859        void triggerSyncIfReachable({ reason, force: payload.force === true });1860        return { ok: true };1861      }18621863      case "GET_SYNC_STATE": {1864        if (vault.isDecoyMode()) return { ok: true, data: { status: "idle" } };1865        return { ok: true, data: getSyncState() };1866      }18671868      // §11. The generation state carries no secret — it is a version and a1869      // state name — so the panel can read it while the vault is locked.1870      case "GET_SYNC_GENERATION": {1871        return { ok: true, data: await resolveGeneration(browserGenerationIo) };1872      }18731874      case "SECURE_RESET": {1875        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1876        const payload = (msg.payload ?? {}) as { password?: unknown };1877        if (typeof payload.password !== "string" || payload.password.length === 0) {1878          return { ok: false, error: "Enter your master password" };1879        }1880        const wasLocked = !vault.isUnlocked();1881        const passwordValid = wasLocked1882          ? await vault.unlock(payload.password)1883          : await vault.verifyMainPassword(payload.password);1884        if (!passwordValid) {1885          return { ok: false, error: "Incorrect master password" };1886        }1887        if (wasLocked) {1888          await setupAutoLock();1889          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });1890          onVaultUnlocked();1891        }1892        // Identity rotation needs the live vault root key. A password check is1893        // deliberately verification-only, so establish the real session first1894        // when Settings is opened after the vault session expired.1895        // Enter the blocking state before the reset steps: a crash after this1896        // point leaves the device refusing sync rather than mid-reset over live1897        // trust. Both are idempotent, so a retry is safe.1898        await enterResetRequired(browserGenerationIo);1899        const result = await confirmSecureReset(browserGenerationIo, {1900          nowMs: Date.now(),1901        });1902        return result === "V2_ANCHOR"1903          ? { ok: true, data: await resolveGeneration(browserGenerationIo) }1904          : {1905              ok: false,1906              error: "The reset did not complete — nothing was lost, try again",1907            };1908      }19091910      case "GET_SYNC_SETTINGS": {1911        if (vault.isDecoyMode()) return { ok: true, data: { mode: "off", relayUrl: "" } };1912        return { ok: true, data: await getSyncSettings() };1913      }19141915      case "SET_SYNC_SETTINGS": {1916        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1917        const payload = (msg.payload ?? {}) as {1918          mode?: unknown;1919          relayUrl?: unknown;1920        };1921        try {1922          // A custom relay URL implies private mode; Peach's own relay stays1923          // public. See setRelayUrl.1924          if (payload.relayUrl !== undefined) {1925            if (typeof payload.relayUrl !== "string") {1926              return { ok: false, error: "invalid_relay_url" };1927            }1928            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1929          }1930          if (payload.mode !== undefined) {1931            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1932              return { ok: false, error: "invalid_sync_mode" };1933            }1934            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1935          }1936          return { ok: true, data: await getSyncSettings() };1937        } catch (error) {1938          return {1939            ok: false,1940            error: error instanceof Error ? error.message : "invalid_relay_url",1941          };1942        }1943      }194419451946      case "GET_SYNC_ALERTS": {1947        if (vault.isDecoyMode()) return { ok: true, data: [] };1948        return { ok: true, data: await getPendingSyncAlerts() };1949      }19501951      case "DISMISS_SYNC_ALERTS": {1952        if (vault.isDecoyMode()) return { ok: true };1953        const type = (msg.payload as { type?: unknown } | undefined)?.type;1954        if (type !== "DEVICE_KEY_ROTATED" && type !== "DEVICE_REVOKED") {1955          return { ok: false, error: "invalid_sync_alert_type" };1956        }1957        await dismissPendingSyncAlerts(type);1958        return { ok: true };1959      }19601961      case "GET_PENDING_VOUCHED_DEVICES": {1962        if (vault.isDecoyMode()) return { ok: true, data: [] };1963        return { ok: true, data: await listPendingVouchedDevices() };1964      }1965      case "CONFIRM_VOUCHED_DEVICE": {1966        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1967        const { deviceId } = msg.payload as { deviceId: string };1968        const pending = await getPendingVouchedDevice(deviceId);1969        if (!pending) return { ok: false, error: "not_pending" };1970        // Last gate before a vouched device becomes a sync peer. A queue entry1971        // can predate the revocation that names it, so revocation is re-checked1972        // here rather than trusted to have swept the queue.1973        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {1974          await removePendingVouchedDevice(deviceId);1975          return { ok: false, error: "device_revoked" };1976        }1977        await upsertPairedDeviceV3({1978          deviceId: pending.deviceId,1979          deviceName: pending.deviceName,1980          deviceType:1981            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1982          longTermPublicKeyHex: pending.longTermPublicKeyHex,1983          signingPublicKeyHex: pending.signingPublicKeyHex,1984          wsPort: pending.wsPort,1985          pairedAt: pending.pairedAt,1986          trustSource: "vouched",1987        });1988        await removePendingVouchedDevice(deviceId);1989        // Newly confirmed vouched device is now a sync target — kick a round1990        // so the mesh introduction pays off without a 10-minute wait.1991        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1992        return { ok: true };1993      }1994      case "REJECT_VOUCHED_DEVICE": {1995        if (vault.isDecoyMode()) return { ok: true };1996        const { deviceId } = msg.payload as { deviceId: string };1997        await removePendingVouchedDevice(deviceId);1998        return { ok: true };1999      }20002001      case "ROTATE_SYNC_IDENTITY": {2002        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };2003        const epoch = vault.getVaultEpoch();2004        const { password } = (msg.payload ?? {}) as { password?: unknown };2005        if (typeof password !== "string" || !password) return { ok: false, error: "password_required" };2006        const verified = await vault.verifyMainPassword(password);2007        if (!vault.isUnlocked() || epoch !== vault.getVaultEpoch()) return { ok: false, error: "vault_locked" };2008        if (!verified) return { ok: false, error: "wrong_password" };2009        const result = await vault.rotateSyncIdentity();2010        return result.ok ? { ok: true } : { ok: false, error: result.error };2011      }20122013      default:2014        return { ok: false, error: "unknown_message_type" };2015    }2016  } catch (err) {2017    return {2018      ok: false,2019      error: err instanceof Error ? err.message : "operation_failed",2020    };2021  }2022}20232024// Returns username use-counts from the vault, sorted by frequency. Each row2025// also carries the entry's email so the popup can suggest the email/username2026// pair the user has actually used together.2027function buildIdentitySuggestions(2028  entries: VaultEntry[],2029): Array<{ email: string; username: string; count: number }> {2030  const usernameCounts = new Map<string, number>();2031  const usernameEmail = new Map<string, string>();2032  for (const entry of entries) {2033    const username = entry.username ?? "";2034    const email = (entry as VaultEntry & { email?: string }).email ?? "";2035    if (!username && !email) continue;2036    const key = username || email;2037    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);2038    if (!usernameEmail.has(key)) usernameEmail.set(key, email);2039  }2040  return Array.from(usernameCounts.entries())2041    .sort((a, b) => b[1] - a[1])2042    .map(([username, count]) => ({2043      email: usernameEmail.get(username) ?? "",2044      username,2045      count,2046    }));2047}20482049/** Notify all content scripts that the vault just became available. */2050function broadcastToContentScripts(message: { type: string }): void {2051  if (!chrome.tabs?.query) return;2052  chrome.tabs.query({}, (tabs) => {2053    for (const tab of tabs) {2054      if (tab.id !== undefined) {2055        chrome.tabs.sendMessage(tab.id, message).catch(() => {2056          // Tab may not have a content script — silently ignore2057        });2058      }2059    }2060  });2061}20622063function shouldRefreshAutoLock(2064  type: MessageType,2065  sender: Partial<chrome.runtime.MessageSender>,2066): boolean {2067  if (!isExtensionPageSender(sender)) return false;2068  return (2069    type !== "HAS_VAULT" &&2070    type !== "IS_UNLOCKED" &&2071    type !== "GET_VAULT_STATUS" &&2072    type !== "LOCK" &&2073    type !== "UPDATE_SETTINGS" &&2074    type !== "GET_PENDING_PASSKEY" &&2075    type !== "GET_PASSKEY_PROVIDER_STATE" &&2076    type !== "DECLINE_CARD_SAVE" &&2077    type !== "IS_CARD_DECLINED" &&2078    type !== "AUTOFILL_QUERY" &&2079    type !== "ML_PREDICT_BATCH"2080  );2081}20822083function isAllowedCanaryWebhookUrl(value: string): boolean {2084  try {2085    const url = new URL(value);2086    if (url.protocol !== "https:") return false;20872088    const hostname = url.hostname.toLowerCase();2089    if (2090      hostname === "localhost" ||2091      hostname.endsWith(".localhost") ||2092      isPrivateIpv4(hostname) ||2093      isPrivateIpv6(hostname)2094    ) {2095      return false;2096    }20972098    return true;2099  } catch {2100    return false;2101  }2102}21032104function isPrivateIpv4(hostname: string): boolean {2105  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {2106    return true;2107  }21082109  const octets = hostname.split(".").map((part) => Number(part));2110  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {2111    return false;2112  }21132114  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;2115}21162117function isPrivateIpv6(hostname: string): boolean {2118  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();2119  // IPv4-mapped IPv6 literals embed a plain IPv4 address that the prefix2120  // list below can never match (WHATWG URL serializes [::ffff:192.168.0.1]2121  // as ::ffff:c0a8:1). Unwrap and test the embedded IPv4; unparseable mapped2122  // tails fail closed. (Codex Security 2026-08-04 LOW,2123  // ssrf.webhook-url-private-ip-filter.) DNS rebinding is out of scope for a2124  // one-shot host check.2125  const mapped = /^::ffff:(.+)$/.exec(normalized);2126  if (mapped) {2127    const tail = mapped[1] ?? "";2128    if (tail.includes(".")) return isPrivateIpv4(tail);2129    const parts = tail.split(":");2130    const [hi, lo] = parts;2131    if (2132      parts.length !== 2 ||2133      !hi ||2134      !lo ||2135      !/^[0-9a-f]{1,4}$/.test(hi) ||2136      !/^[0-9a-f]{1,4}$/.test(lo)2137    ) {2138      return true;2139    }2140    const octets = [2141      (Number.parseInt(hi, 16) >>> 8) & 0xff,2142      Number.parseInt(hi, 16) & 0xff,2143      (Number.parseInt(lo, 16) >>> 8) & 0xff,2144      Number.parseInt(lo, 16) & 0xff,2145    ];2146    return isPrivateIpv4(octets.join("."));2147  }2148  return (2149    normalized === "::1" ||2150    normalized.startsWith("fc") ||2151    normalized.startsWith("fd") ||2152    normalized.startsWith("fe80:")2153  );2154}