messages.ts

83.8 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 { getPendingSyncAlerts, clearPendingSyncAlerts } from "./sync-alerts";14import { extractDomain } from "../shared/domain";15import {16  getPendingVouchedDevice,17  listPendingVouchedDevices,18  removePendingVouchedDevice,19} from "./pending-vouched-devices";20import {21  clearRecoveryConfirmPending,22  isRecoveryConfirmPending,23  setRecoveryConfirmPending,24} from "./recovery-pending";25import { setupAutoLock, touchAutoLock } from "./alarms";26import { runSelfTest } from "./self-test";27import * as vault from "./vault";28import {29  handleEstimateCodexPages,30  handleGetCodexVaultData,31  handleRestoreFromCodex,32} from "./codex-handlers";33import type { CodexRestorePayload } from "../shared/codex-types";34import {35  activateLicense,36  deactivateLicense,37  getLicenseInfo,38  getLicenseKey,39  isProUser,40  markCelebrationPlayed,41  shouldPlayCelebration,42} from "./license";43import {44  completeFirefoxPasskeyCreate,45  getPasskeyProviderState,46  getPendingPasskeyRequest,47  handleFirefoxPasskeyCreate,48  handleFirefoxPasskeyGet,49  handlePasskeyHasCredentials,50  initiateFirefoxPasskeyCreate,51  isPasskeyOfferDeclined,52  onVaultUnlocked,53  recordPasskeyOfferDecline,54  resolvePendingPasskeyRequest,55  setPasskeyProviderEnabled,56} from "./passkey";57import { buildAdvancedHealthReport } from "./health";58import { storageClear } from "../shared/storage";59import { findInvalidWords } from "../shared/recovery-words";60import type {61  Message,62  MessageResponse,63  MessageType,64  ProFeature,65  VaultEntry,66} from "../shared/types";67import { isPasskeyOnly } from "../shared/types";68import { generateTOTP } from "../crypto/totp";69import { isValidRpId } from "../shared/passkey-utils";70import { isValidMLFeatureBatch, predictBatch as mlPredictBatch } from "./ml";71import {72  buildLocalIdentity,73  getOrCreateDeviceId,74  setDeviceName as setDeviceNameV3,75} from "./device-identity";76import {77  isDeviceRevoked,78  listPairedDevices as listPairedDevicesV3,79  renamePairedDevice as renamePairedDeviceV3,80  revokeDeviceById as revokeDeviceByIdV3,81  upsertPairedDevice as upsertPairedDeviceV3,82} from "./paired-devices";83import { dropPairSecret } from "./pair-secrets";84// Sync and pairing are imported statically, never with `await import()`.85// `import()` throws `TypeError: import() is disallowed on86// ServiceWorkerGlobalScope` at runtime in MV3, and Vite's preload helper87// reports the failure through `window.dispatchEvent`, which does not exist in88// a worker either — so the real reason was replaced by "window is not defined"89// and the pairing UI just stopped. scripts/check-sw-static-imports.mjs fails90// the build if a runtime import() reappears anywhere in the worker's graph.91import {92  cancelRelayAdoptionSource,93  isRelayAdoptionSourceInFlight,94  resolveReceiverSasConfirmation,95  resolveSourceSasConfirmation,96  startRelayAdoptionReceiver,97  startRelayAdoptionSource,98} from "./relay-adoption-bg";99import {100  listPendingAdoptionHolders,101  removePendingAdoptionHolder,102} from "./pending-adoption-holder";103import {104  getSyncSettings,105  setRelayUrl,106  setSyncMode,107  type SyncMode,108} from "./sync-settings";109import {110  getSyncState,111  triggerSyncIfReachable,112} from "./sync-trigger";113import { isMessageSenderAllowed } from "./message-policy";114115const SUMMON_CAPABILITY_TTL_MS = 30_000;116type SummonCapability = { tabId: number; frameId: number; origin: string; operation: "inventory" | "fill"; expiresAt: number };117const summonCapabilities = new Map<string, SummonCapability>();118119export function createSummonCapability(tabId: number, origin: string, frameId = 0): string {120  const token = crypto.randomUUID();121  summonCapabilities.set(token, { tabId, frameId, origin, operation: "inventory", expiresAt: Date.now() + SUMMON_CAPABILITY_TTL_MS });122  return token;123}124125function consumeSummonCapability(token: unknown, sender: Partial<chrome.runtime.MessageSender>, operation: "inventory" | "fill"): boolean {126  if (typeof token !== "string") return false;127  const cap = summonCapabilities.get(token);128  if (!cap) return false;129  if (cap.expiresAt <= Date.now()) {130    summonCapabilities.delete(token);131    return false;132  }133  if (sender.tab?.id !== cap.tabId || (sender.frameId ?? 0) !== cap.frameId || attestedSenderOrigin(sender) !== cap.origin) return false;134  if (cap.operation !== operation) return false;135  if (operation === "inventory") cap.operation = "fill";136  else summonCapabilities.delete(token);137  return true;138}139140// Compile-time E2E flag, folded to a literal by Vite's `define` (false in141// every production build — verified in the bundled output). Mirrors the142// create-path bypass in passkey.ts so the Playwright passkey smoke can enable143// the provider without a real Pro licence; the gate is fully intact for users.144declare const __PEACH_E2E_PASSKEYS__: boolean;145const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true;146147function unhexBytes(hex: string): Uint8Array {148  if (hex.length % 2 !== 0) throw new Error("invalid hex");149  const out = new Uint8Array(hex.length / 2);150  for (let i = 0; i < out.length; i++) {151    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);152  }153  return out;154}155156/**157 * The single Pro gate. Every gated handler calls this first; the broadcast158 * lets the popup react (navigate to the License section, highlight the159 * relevant feature). Background never touches the popup view directly —160 * the popup owns navigation. See Projects.md "Pro gate rule".161 */162async function requirePro(163  feature: ProFeature,164  trigger: "user" | "background" = "user"165): Promise<{ allowed: boolean }> {166  if (PASSKEY_E2E_PRO_BYPASS && feature === "passkeys") return { allowed: true };167  if (await isProUser()) return { allowed: true };168169  if (trigger === "user") {170    // User deliberately triggered this feature — redirect the popup immediately.171    chrome.runtime172      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })173      .catch(() => {174        // Popup may be closed — the gate signal is best-effort.175      });176  } else {177    // Background trigger (e.g. passive sync initiation) — no popup is open.178    // Queue a notice so the next popup open shows a soft banner instead of179    // silently failing.180    if (chrome.storage.session) {181      chrome.storage.session182        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })183        .catch(() => {});184    }185  }186187  return { allowed: false };188}189190// LV-3: minimum interval between non-test canary pings per webhook+entry.191const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour192193const PRIVATE_IPV4_RANGES = [194  { prefix: "10." },195  { prefix: "127." },196  { prefix: "169.254." },197  { prefix: "192.168." },198];199200export function setupMessageHandler(): void {201  chrome.runtime.onMessage.addListener(202    (msg: unknown, sender, sendResponse) => {203      if (!isMessage(msg)) {204        sendResponse({ ok: false, error: "invalid_message" });205        return true;206      }207      handleMessage(msg, sender)208        .then(sendResponse)209        .catch((err) =>210          sendResponse({211            ok: false,212            error: err instanceof Error ? err.message : String(err),213          })214        );215      return true;216    }217  );218}219220function isMessage(m: unknown): m is Message {221  return typeof m === "object" && m !== null && "type" in m;222}223224/**225 * The browser-attested origin of the page that originated this message. A web226 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),227 * so every page-driven message arrives via the content-script relay and the228 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a229 * value the page cannot forge. This is the ONLY trustworthy origin for passkey230 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.231 */232function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {233  if (sender.origin) return sender.origin;234  if (sender.url) {235    try { return new URL(sender.url).origin; } catch { return undefined; }236  }237  return undefined;238}239240function isExtensionPageSender(sender: Partial<chrome.runtime.MessageSender>): boolean {241  return sender.url?.startsWith("chrome-extension://") === true ||242    sender.url?.startsWith("moz-extension://") === true;243}244245/** True when the message came from a page frame rather than extension UI. */246function isPageSender(sender: Partial<chrome.runtime.MessageSender>): boolean {247  return !isExtensionPageSender(sender) &&248    (sender.tab !== undefined || sender.url !== undefined);249}250251function entryDomains(url: unknown, additionalUrls: unknown): Set<string> {252  const domains = new Set<string>();253  const primary = typeof url === "string" ? extractDomain(url) : null;254  if (primary) domains.add(primary);255  if (Array.isArray(additionalUrls)) {256    for (const extra of additionalUrls) {257      if (typeof extra !== "string") continue;258      const domain = extractDomain(extra);259      if (domain) domains.add(domain);260    }261  }262  return domains;263}264265/**266 * PB-26-106: the autofill read path re-validates the frame origin against the267 * entry's domains on every request, so an unbound write path would let a268 * content script repoint an entry at its own origin and then read the269 * credential through a read path that is behaving correctly.270 *271 * Creating an entry: a page may only bind it to itself. Mutating one: a page272 * may never GROW the domain set — only shrink it, and never below its own273 * attested origin.274 *275 * Self-binding on mutation was considered and is not enough: the content276 * script on a foreign origin IS the attacker in the reported chain, so letting277 * it attach "its own" origin lets it mint the very capability the read path278 * exists to withhold. The legitimate flow that needs a new domain — the inline279 * "remember this site" toast — therefore asks the popup instead280 * (REQUEST_REMEMBER_SITE), which is an extension page and exempt here.281 *282 * Extension pages are exempt: the popup edits entries for sites it is not on.283 */284function senderMayBindEntryDomains(285  sender: Partial<chrome.runtime.MessageSender>,286  domains: Set<string>,287): boolean {288  if (isExtensionPageSender(sender)) return true;289  const domain = attestedSenderDomain(sender);290  if (domain === null) return false;291  for (const candidate of domains) {292    if (candidate !== domain) return false;293  }294  return true;295}296297function senderMayMutateEntryDomains(298  sender: Partial<chrome.runtime.MessageSender>,299  before: Set<string>,300  after: Set<string>,301): boolean {302  if (isExtensionPageSender(sender)) return true;303  const domain = attestedSenderDomain(sender);304  if (domain === null || !after.has(domain)) return false;305  for (const kept of after) {306    if (!before.has(kept)) return false;307  }308  return true;309}310311/**312 * Null for extension pages (which the callers exempt), for senders with no313 * attested origin at all, and for unparseable frame urls.314 */315function attestedSenderDomain(sender: Partial<chrome.runtime.MessageSender>): string | null {316  if (sender.tab === undefined && sender.url === undefined) return null;317  const origin = attestedSenderOrigin(sender);318  if (!origin) return null;319  try { return extractDomain(new URL(origin).hostname); } catch { return null; }320}321322function patchChangesEntryOrigin(patch: object): boolean {323  return Object.hasOwn(patch, "url") || Object.hasOwn(patch, "additionalUrls");324}325326/** The entry's domain-bearing fields as the patch would leave them. */327function patchedUrlShape(328  patch: object,329  existing: Pick<VaultEntry, "url" | "additionalUrls">,330): { url: unknown; additionalUrls: unknown } {331  const candidate = patch as { url?: unknown; additionalUrls?: unknown };332  return {333    url: Object.hasOwn(patch, "url") ? candidate.url : existing.url,334    additionalUrls: Object.hasOwn(patch, "additionalUrls")335      ? candidate.additionalUrls336      : existing.additionalUrls,337  };338}339// Resolves once restoreFromSession() has run, so handlers see the correct340// post-restore unlock state. entry.ts registers this BEFORE the message341// handler so the onMessage listener is added synchronously at SW startup342// (MV3 requirement) while unlock-dependent handlers still wait for restore.343let restoreReady: Promise<void> = Promise.resolve();344const MAX_ML_BATCH_FIELDS = 128;345const MAX_ML_FIELDS_PER_SECOND = 256;346const mlWorkBySender = new Map<string, { startedAt: number; fields: number }>();347348function claimMLWork(sender: Partial<chrome.runtime.MessageSender>, fields: number): boolean {349  if (fields === 0) return true;350  const now = Date.now();351  for (const [key, value] of mlWorkBySender) {352    if (now - value.startedAt >= 1_000) mlWorkBySender.delete(key);353  }354  const key = `${sender.tab?.id ?? "ui"}:${sender.frameId ?? 0}:${attestedSenderOrigin(sender) ?? "extension"}`;355  const current = mlWorkBySender.get(key);356  if (!current) {357    mlWorkBySender.set(key, { startedAt: now, fields });358    return fields <= MAX_ML_FIELDS_PER_SECOND;359  }360  if (current.fields + fields > MAX_ML_FIELDS_PER_SECOND) return false;361  current.fields += fields;362  return true;363}364365/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */366export function setRestoreReady(p: Promise<unknown>): void {367  restoreReady = p.then(() => undefined, () => undefined);368}369370export async function handleMessage(371  msg: Message,372  sender: Partial<chrome.runtime.MessageSender> = {}373): Promise<MessageResponse> {374  try {375    // Wait for session-restore to finish before reading any unlock/vault state.376    // On a cold SW start the popup's first message arrives while restore is377    // still in flight; without this gate IS_UNLOCKED would report locked (a378    // spurious lock screen) and the storage reads could race. The onMessage379    // listener itself is registered synchronously (entry.ts) so this gate, not380    // listener registration, is what absorbs the cold-start window.381    await restoreReady;382    // Validate sender — only allow messages from our extension pages/scripts.383    // `sender.id` is undefined for messages originating from extension UI384    // (popup/options), which is legitimate; reject only when it is defined385    // and does not match our extension id.386    if (387      sender.id !== undefined &&388      sender.id !== chrome.runtime.id389    ) {390      return { ok: false, error: "invalid_sender" };391    }392393    // PB-26-016: sender authorization is an exhaustive policy, not a394    // hand-maintained privileged denylist. A missing/unknown policy entry or a395    // background-only message fails closed before any handler runs.396    // Extension UI messages may legitimately omit sender.url. Resolve the397    // browser-attested extension origin only when a URL is present; this also398    // keeps test/runtime shims without getURL fail-closed for URL-bearing399    // senders instead of throwing before policy evaluation.400    const extensionOrigin = sender.url && typeof chrome.runtime.getURL === "function"401      ? chrome.runtime.getURL("")402      : "";403    if (!isMessageSenderAllowed(msg.type, sender, chrome.runtime.id, extensionOrigin)) {404      return { ok: false, error: "invalid_sender" };405    }406407    if (shouldRefreshAutoLock(msg.type, sender) && vault.isUnlocked()) {408      touchAutoLock();409    }410411    switch (msg.type) {412      case "CREATE_VAULT": {413        const { password } = msg.payload as { password: string };414        // Refuse to create a vault under an empty master password — the derived415        // key would be publicly known and the at-rest AES-GCM protection void416        // (audit HIGH; the CSV-import path previously passed ""). Length/strength417        // policy lives in the onboarding UI; this is the non-negotiable floor.418        if (typeof password !== "string" || password.length === 0) {419          return { ok: false, error: "invalid_payload" };420        }421        await vault.createVault(password);422        await setupAutoLock();423        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });424        onVaultUnlocked();425        return { ok: true };426      }427      case "CREATE_VAULT_FROM_ROOT_KEY": {428        const { password, rootKeyHex } = (msg.payload ?? {}) as {429          password?: unknown;430          rootKeyHex?: unknown;431        };432        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {433          return { ok: false, error: "invalid_payload" };434        }435436        try {437          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);438          await setupAutoLock();439          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });440          onVaultUnlocked();441          return { ok: true, vaultId };442        } catch (err) {443          return { ok: false, error: err instanceof Error ? err.message : String(err) };444        }445      }446      case "UNLOCK": {447        const { password } = msg.payload as { password: string };448        const ok = await vault.unlock(password);449        if (ok) {450          // KAT: verify the WebCrypto stack is healthy before the user relies on it.451          // Runs after unlock so latency is hidden behind the vault-load time.452          const kat = await runSelfTest();453          if (!kat.ok) {454            console.error("[Peach] Crypto self-test FAILED:", kat.error);455            await vault.lock();456            return { ok: false, error: "self_test_failed" };457          }458          await vault.updateSettings({ pinPreferred: false });459          await setupAutoLock();460          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });461          onVaultUnlocked();462          return { ok: true };463        }464        // Distinguish corruption from wrong password so the popup can offer465        // a history-restore path instead of falsely accusing the user of466        // mistyping (M7/COR-007).467        const failure = vault.consumeLastUnlockFailureReason();468        if (failure) {469          return {470            ok: false,471            error: "vault_corrupted",472            canRestoreFromHistory: true,473          } as MessageResponse;474        }475        return { ok: false };476      }477      case "UNLOCK_WITH_PIN": {478        const { pin } = (msg.payload ?? {}) as { pin?: unknown };479        if (typeof pin !== "string") return { ok: false, error: "invalid_payload" };480        const ok = await vault.unlockWithPin(pin);481        if (!ok) {482          const status = await vault.getPinUnlockStatus();483          if (status.configured && !status.available) {484            return {485              ok: false,486              error: status.attemptsRemaining === 0487                ? "pin_attempts_exceeded"488                : "pin_session_expired",489            };490          }491          return { ok: false };492        }493        const kat = await runSelfTest();494        if (!kat.ok) {495          await vault.lock();496          return { ok: false, error: "self_test_failed" };497        }498        await vault.updateSettings({ pinPreferred: true });499        await setupAutoLock();500        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });501        onVaultUnlocked();502        return { ok: true };503      }504      case "GET_PIN_STATUS":505        return { ok: true, data: await vault.getPinUnlockStatus() };506      case "VALIDATE_RECOVERY_WORDS": {507        const { words } = msg.payload as { words: string[] };508        const invalid = findInvalidWords(words);509        return { ok: true, data: { valid: invalid.length === 0, invalid } };510      }511      case "GET_RECOVERY_WORDS": {512        // Must be unlocked and have recovery set up (vault must be v2.12+).513        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };514        // LV-4: the recovery words re-derive the ROOT KEY — the highest-515        // value secret in the vault. A session unlock (which may be hours516        // old on a shared machine) is not enough; require a fresh password517        // proof, matching the 1Password/Bitwarden pattern for revealing518        // escrow material. EXEMPTION: the create-vault / rotation confirmation519        // window (peach_recovery_pending) shows the words immediately after520        // the user authenticated, and that confirmation UI has no password to521        // resend — skip the re-auth there only.522        if (!(await isRecoveryConfirmPending())) {523          const { password } = (msg.payload ?? {}) as { password?: string };524          if (typeof password !== "string" || !password) {525            return { ok: false, error: "password_required" };526          }527          if (!(await vault.verifyMainPassword(password))) {528            return { ok: false, error: "wrong_password" };529          }530        }531        try {532          const words = await vault.getRecoveryWords();533          return { ok: true, data: words };534        } catch {535          return { ok: false, error: "recovery_not_setup" };536        }537      }538      case "GET_RECOVERY_CONFIRM_PENDING":539        return { ok: true, data: await isRecoveryConfirmPending() };540      case "SET_RECOVERY_CONFIRM_PENDING":541        await setRecoveryConfirmPending();542        return { ok: true };543      case "CLEAR_RECOVERY_CONFIRM_PENDING":544        await clearRecoveryConfirmPending();545        return { ok: true };546      case "RECOVER_WITH_WORDS": {547        // User has lost their password but has their 12 recovery words.548        // We: (1) validate the words, (2) re-encrypt vault with new password.549        const { words, newPassword } = msg.payload as {550          words: string[];551          newPassword: string;552        };553        const stored = await vault.loadSlotA();554        if (!stored) return { ok: false, error: "no_vault" };555        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {556          return { ok: false, error: "recovery_not_setup" };557        }558        // Unwrap the root key from the recovery escrow.559        try {560          await vault.unwrapRootKeyForRecovery(561            stored.recovery_wrapped_root_key,562            stored.recovery_nonce ?? "",563            stored.recovery_tag ?? "",564            stored.recovery_salt,565            words566          );567        } catch {568          return { ok: false, error: "invalid_recovery_words" };569        }570        // Re-key: derive fresh salt + key from new password.571        const newSalt = vault.generateSalt();572        const newKey = await vault.deriveKey(newPassword, newSalt);573        // Re-wrap root key under the new password's derived key so the same574        // recovery words continue to work after the password change.575        await vault.rewrapRootKeyForPassword(newKey);576        // Re-encrypt vault entries with the new key.577        await vault.changePasswordWithNewKey(newSalt, newKey);578        await setupAutoLock();579        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });580        return { ok: true };581      }582      case "LOCK":583        await vault.lock();584        return { ok: true };585      case "IS_UNLOCKED":586        return { ok: true, data: vault.isUnlocked() };587      case "GET_VAULT_STATUS":588        return { ok: true, unlocked: vault.isUnlocked() };589      case "HAS_VAULT":590        return { ok: true, data: await vault.hasVault() };591      case "GET_ENTRIES":592        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };593        return { ok: true, data: vault.getEntries() };594      case "EXPORT_ENTRIES": {595        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };596        const { password } = (msg.payload ?? {}) as { password?: unknown };597        if (typeof password !== "string" || !password) {598          return { ok: false, error: "password_required" };599        }600        if (!(await vault.verifyMainPassword(password))) {601          return { ok: false, error: "wrong_password" };602        }603        return { ok: true, data: vault.getEntries() };604      }605      case "ADD_ENTRY": {606        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };607        const payload = msg.payload;608        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {609          return { ok: false, error: "invalid_payload" };610        }611        // PB-26-106: a page may only create an entry bound to itself. Entries612        // carrying no url have no domain surface to bind, so they are exempt.613        if (isPageSender(sender)) {614          const draft = payload as { url?: unknown; additionalUrls?: unknown };615          const domains = entryDomains(draft.url, draft.additionalUrls);616          if (domains.size > 0 && !senderMayBindEntryDomains(sender, domains)) {617            return { ok: false, error: "origin_binding_required" };618          }619        }620        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);621        return { ok: true, data: entry };622      }623      case "BATCH_ADD_ENTRIES": {624        const payload = msg.payload as { entries?: unknown } | null | undefined;625        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {626          return { ok: false, error: "invalid_payload" };627        }628        if (!Array.isArray(payload.entries)) {629          return { ok: false, error: "invalid_payload" };630        }631        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);632        return { ok: true, data: added };633      }634      case "RESTORE_ENTRIES": {635        const payload = msg.payload as636          | { entries?: unknown; mode?: unknown; settings?: unknown }637          | null638          | undefined;639        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {640          return { ok: false, error: "invalid_payload" };641        }642        if (!Array.isArray(payload.entries)) {643          return { ok: false, error: "invalid_payload" };644        }645        if (payload.mode !== "replace" && payload.mode !== "merge") {646          return { ok: false, error: "invalid_payload" };647        }648        const summary = await vault.restoreEntries(649          payload.entries as Parameters<typeof vault.restoreEntries>[0],650          payload.mode651        );652        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {653          await vault.updateSettings(payload.settings as vault.VaultSettings);654        }655        return { ok: true, data: summary };656      }657      case "CLEAR_VAULT_ENTRIES": {658        await vault.clearVaultEntries("REPLACE_ALL");659        return { ok: true };660      }661      case "GET_VAULT_HISTORY": {662        const snapshots = await vault.getVaultHistory();663        return { ok: true, data: snapshots };664      }665      case "RESTORE_VAULT_SNAPSHOT": {666        const { snapshotId } = msg.payload as { snapshotId: string };667        const result = await vault.restoreVaultSnapshot(snapshotId);668        if (!result.ok) return { ok: false, error: result.error };669        broadcastToContentScripts({ type: "VAULT_LOCKED" });670        return { ok: true };671      }672      case "COUNT_DUPLICATES": {673        return { ok: true, data: vault.countDuplicates() };674      }675      case "DEDUPLICATE_ENTRIES": {676        const removed = await vault.deduplicateEntries();677        return { ok: true, data: removed };678      }679      case "UPDATE_ENTRY": {680        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;681        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {682          return { ok: false, error: "invalid_payload" };683        }684        const { id, patch } = payload;685        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {686          return { ok: false, error: "invalid_payload" };687        }688        const existingEntry = vault.getEntryById(id);689        if (!existingEntry) return { ok: false, error: "entry_not_found" };690        if (patchChangesEntryOrigin(patch) || isPageSender(sender)) {691          const before = entryDomains(existingEntry.url, existingEntry.additionalUrls);692          const after = patchedUrlShape(patch, existingEntry);693          if (!senderMayMutateEntryDomains(694            sender,695            before,696            entryDomains(after.url, after.additionalUrls),697          )) {698            return { ok: false, error: "origin_binding_required" };699          }700        }701        // Single enforcement point for the Canary Entries Pro gate. Only702        // gates the transition into a canary entry — clearing/disabling a703        // canary (`canary: undefined`) is always allowed, so existing704        // canary entries remain manageable.705        const incomingCanary = (patch as { canary?: unknown }).canary;706        if (incomingCanary && typeof incomingCanary === "object") {707          const existing = vault.getEntryById(id);708          if (!existing?.canary) {709            const gate = await requirePro("canary_entry");710            if (!gate.allowed) return { ok: false, error: "pro_required" };711          }712        }713        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);714        return { ok: true };715      }716      case "ADD_ADDITIONAL_URL": {717        const { id, url } = msg.payload as { id: string; url: string };718        const trimmed = typeof url === "string" ? url.trim() : "";719        if (!trimmed) return { ok: false, error: "url_required" };720        const existing = vault.getEntryById(id);721        if (!existing) return { ok: false, error: "entry_not_found" };722        const merged = [...(existing.additionalUrls ?? []), trimmed];723        if (!senderMayMutateEntryDomains(724          sender,725          entryDomains(existing.url, existing.additionalUrls),726          entryDomains(existing.url, merged),727        )) {728          return { ok: false, error: "origin_binding_required" };729        }730        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };731        await vault.updateEntry(id, { additionalUrls: merged });732        return { ok: true };733      }734      case "REQUEST_REMEMBER_SITE": {735        // PB-26-106: growing an entry's domain set needs a decision the page736        // cannot make for itself, so the page asks and the popup confirms. A737        // page may only ask about its own attested origin — otherwise this738        // becomes the same unbound write under a friendlier name.739        const { id, url } = (msg.payload ?? {}) as { id?: unknown; url?: unknown };740        if (typeof id !== "string" || !id) return { ok: false, error: "invalid_payload" };741        const trimmed = typeof url === "string" ? url.trim() : "";742        if (!trimmed) return { ok: false, error: "url_required" };743        if (!senderMayBindEntryDomains(sender, entryDomains(trimmed, undefined))) {744          return { ok: false, error: "origin_binding_required" };745        }746        if (!vault.getEntryById(id)) return { ok: false, error: "entry_not_found" };747        if (chrome.storage.session) {748          await chrome.storage.session.set({ pendingRememberSite: { entryId: id, url: trimmed } });749        }750        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }751        return { ok: true };752      }753      case "DELETE_ENTRY": {754        const { id } = msg.payload as { id: string };755        await vault.deleteEntry(id);756        return { ok: true };757      }758      case "GET_DELETED_ENTRIES":759        return { ok: true, data: vault.getDeletedEntries() };760      case "RESTORE_ENTRY": {761        const { id } = msg.payload as { id: string };762        await vault.restoreEntry(id);763        return { ok: true };764      }765      case "PURGE_ENTRY": {766        const { id } = msg.payload as { id: string };767        await vault.purgeEntry(id);768        return { ok: true };769      }770      case "PURGE_EXPIRED_TRASH": {771        const { retentionMs } = msg.payload as { retentionMs: number };772        const purged = await vault.purgeExpiredTrash(retentionMs);773        return { ok: true, data: purged };774      }775      case "SAVE_NOTE": {776        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };777        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };778        const now = Date.now();779        if (id) {780          const existing = vault.getEntryById(id);781          if (!existing) return { ok: false, error: "not_found" };782          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });783          return { ok: true, data: vault.getEntryById(id) };784        } else {785          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt786          // (EntryDraft omits both), so passing them was the only reason the787          // `as any` cast existed. Dropping them makes the call type-check.788          const entry = await vault.addEntry({789            type: "note",790            title: title || "Untitled",791            notes: body,792          });793          return { ok: true, data: entry };794        }795      }796      case "DELETE_NOTE": {797        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };798        const { id } = msg.payload as { id: string };799        await vault.deleteEntry(id);800        return { ok: true };801      }802      case "GET_NOTES": {803        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };804        const notes = vault.getEntries().filter(805          (e) => e.type === "note" && !e.deletedAt806        );807        return { ok: true, data: notes } as MessageResponse;808      }809      case "SEARCH_VAULT": {810        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };811        // AUD-002: shape-validate the payload before calling string methods.812        // A raw cast lets a malformed message crash the handler with TypeError.813        const { query } = (msg.payload ?? {}) as { query?: unknown };814        if (typeof query !== "string") {815          return { ok: false, error: "invalid_payload" };816        }817        const q = query.toLowerCase();818        const searchResults = vault.getEntries().filter(819          (e) =>820            !e.deletedAt &&821            (e.title.toLowerCase().includes(q) ||822              e.notes?.toLowerCase().includes(q) ||823              e.username?.toLowerCase().includes(q))824        );825        return { ok: true, data: searchResults } as MessageResponse;826      }827      case "AUTOFILL_QUERY": {828        if (!vault.isUnlocked()) {829          return { ok: false, error: "vault_locked" };830        }831        const { domain, kind, capability } = msg.payload as {832          domain: string;833          kind?: "login" | "card" | "totp";834          capability?: string;835        };836        const includeAll = consumeSummonCapability(capability, sender, "inventory");837        if (capability !== undefined && !includeAll) {838          return { ok: false, error: "entry_not_found" };839        }840        // kind="card": return saved cards as compact summaries for the841        // inline card silver platter. Cards are not domain-scoped — every842        // saved card is a candidate on every checkout page — so domain is843        // ignored when kind === "card".844        if (kind === "card") {845          if (!includeAll) return { ok: true, data: [] };846          const cards = vault.getEntries().filter((e) => e.type === "card");847          return {848            ok: true,849            data: cards.map((e) => ({850              id: e.id,851              title: e.cardNickname || e.title,852              cardholderName: e.cardholderName,853              last4: e.last4,854              expMonth: e.expMonth,855              expYear: e.expYear,856              network: e.network,857            })),858          };859        }860        const scopedDomain = isPageSender(sender)861          ? attestedSenderDomain(sender)862          : typeof domain === "string"863            ? extractDomain(domain)864            : null;865        if (!includeAll && !scopedDomain) {866          return isPageSender(sender)867            ? { ok: false, error: "origin_unverified" }868            : { ok: true, data: [] };869        }870        if (kind === "totp") {871          const matches = (872            includeAll873              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")874              : vault.queryDomain(scopedDomain!)875          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));876          return {877            ok: true,878            data: matches.map((e) => ({879              id: e.id,880              title: e.title,881              username: e.username,882              email: e.email,883              url: e.url,884              hasTotp: true,885            })),886          };887        }888        // The inline selector fills username+password into a form. Passkey-889        // only entries have no password to fill; sign-in for those goes890        // through the WebAuthn path instead. Filter them out everywhere so891        // the user doesn't see four "GitHub" rows that mostly do nothing.892        // Notes and cards never belonged here either.893        const matches = (894          includeAll895            ? vault896                .getEntries()897                .filter((entry) => entry.type !== "note" && entry.type !== "card")898            : vault.queryDomain(scopedDomain!)899        ).filter((entry) => !isPasskeyOnly(entry));900        return {901          ok: true,902          data: matches.map((e) =>903            includeAll904              ? {905                  id: e.id,906                  title: e.title,907                  // username/email/url shipped so the inline popup's search908                  // affordance can match on them, not just titles. No secrets909                  // cross the boundary — same shape as the domain-matched910                  // response below minus hasTotp (which the search list911                  // doesn't surface).912                  username: e.username,913                  email: e.email,914                  url: e.url,915                  hasPasskey: e.passkey !== undefined,916                }917              : {918                  id: e.id,919                  title: e.title,920                  username: e.username,921                  email: e.email,922                  url: e.url,923                  hasTotp: Boolean(e.totp),924                  hasPasskey: e.passkey !== undefined,925                }926          ),927        };928      }929      case "GET_ENTRY_FOR_FILL": {930        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };931        const { id, capability } = msg.payload as {932          id: string;933          capability?: string;934        };935        const capabilityAuthorized = capability !== undefined && consumeSummonCapability(capability, sender, "fill");936        const senderDomain = isPageSender(sender) ? attestedSenderDomain(sender) : null;937        if (isPageSender(sender) && !senderDomain) {938          return { ok: false, error: "origin_unverified" };939        }940        const entry = vault.getEntryById(id);941        if (!entry) return { ok: false, error: "entry_not_found" };942943        // MV-1: re-validate the entry against the requesting frame's origin.944        // sender.url / sender.tab.url are browser-attested — a page cannot945        // forge them. PB-26-005: the FRAME url (sender.url) is authoritative946        // for an all_frames content script; the top-frame tab.url would947        // misattribute a cross-origin iframe's request to the top page. When948        // the request does not come from a tab at all (popup surfaces use949        // GET_ENTRY_FOR_EDIT, not this), refuse.950        if (senderDomain && !capabilityAuthorized) {951          if (!entryDomains(entry.url, entry.additionalUrls).has(senderDomain)) {952            // Domain mismatch — refuse silently (no oracle about which ids exist).953            return { ok: false, error: "entry_not_found" };954          }955        }956        // Passkey-only entries (passkey credential, no password) cannot be957        // filled into a form — sign-in goes through the WebAuthn path. A958        // login that ALSO has a passkey is still fillable for its password.959        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };960        // Strip the passkey credential AND the raw base32 TOTP seed from the961        // response. Content scripts never need either: the private key is the962        // authenticator's, and handing over the TOTP seed would let a963        // compromised content script mint valid codes indefinitely (SEV-3-C).964        // Generate the *current* 6-digit code here in the background and send965        // only that, plus the seconds left so the UI can render a countdown.966        // Also drop passwordHistory: filling needs only the *current* password.967        // Handing every past password to a content script during passive968        // autofill on an arbitrary page would widen the blast radius of a969        // compromised page far beyond the one credential being filled.970        const {971          passkey: _strippedPasskey,972          totp: seed,973          totpAlgorithm,974          totpDigits,975          totpPeriod,976          passwordHistory: _ph,977          ...safeEntry978        } = entry;979        let totpCode: string | undefined;980        let totpRemaining: number | undefined;981        if (seed) {982          try {983            // PCH-01-019: honour stored algorithm/digits/period (defaults apply984            // when these are undefined, i.e. RFC-default bare-seed entries).985            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);986            totpCode = generated.code;987            totpRemaining = generated.remaining;988          } catch {989            totpCode = undefined;990          }991        }992        if (isPageSender(sender) && vault.isUnlocked()) touchAutoLock();993        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };994      }995      // Trusted full-entry fetch for extension-owned edit surfaces. Content996      // scripts route editing to the popup and cannot call this message.997      case "GET_ENTRY_FOR_EDIT": {998        if (isPageSender(sender)) return { ok: false, error: "invalid_sender" };999        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1000        const { id } = msg.payload as { id: string };1001        const entry = vault.getEntryById(id);1002        if (!entry) return { ok: false, error: "entry_not_found" };10031004        const { passkey: _passkey, ...safeEntry } = entry;1005        return { ok: true, data: safeEntry };1006      }1007      case "COPY": {1008        // AUD-002: shape-validate the payload before passing to the clipboard1009        // helper. A raw cast lets a malformed message reach the clipboard API1010        // with a non-string and throw.1011        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {1012          text?: unknown;1013          label?: unknown;1014          alreadyWritten?: unknown;1015        };1016        if (typeof text !== "string" || typeof label !== "string") {1017          return { ok: false, error: "invalid_payload" };1018        }1019        await copyToClipboard(text, label, Boolean(alreadyWritten));1020        return { ok: true, clearSeconds: getEffectiveClearSeconds() };1021      }1022      case "CHECK_ALL_BREACHES": {1023        const allEntries = vault.getEntries();1024        const results: Record<string, number> = {};1025        for (const entry of allEntries) {1026          if (entry.type === "note") continue;1027          if (!entry.password) continue;1028          results[entry.id] = await vault.checkBreach(entry.password);1029          // Small delay — be a good citizen to the HIBP API1030          await new Promise((r) => setTimeout(r, 200));1031        }1032        // Persist any non-zero counts back to entries1033        for (const [id, count] of Object.entries(results)) {1034          const entry = vault.getEntryById(id);1035          if (entry && (entry.breach ?? 0) !== count) {1036            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });1037          }1038        }1039        return { ok: true, data: results };1040      }1041      case "GET_SETTINGS": {1042        const settings = await vault.ensureSettingsLoaded();1043        if (!isPageSender(sender)) return { ok: true, data: settings };10441045        const safeSettings: Pick<vault.VaultSettings, "accentColor" | "theme"> & {1046          manualSummonDomains?: NonNullable<vault.VaultSettings["manualSummonDomains"]>;1047        } = {1048          accentColor: settings.accentColor,1049          theme: settings.theme,1050        };1051        const domain = attestedSenderDomain(sender);1052        const ownSummon = domain ? settings.manualSummonDomains?.[domain] : undefined;1053        if (domain && ownSummon) safeSettings.manualSummonDomains = { [domain]: ownSummon };1054        return { ok: true, data: safeSettings };1055      }1056      case "UPDATE_SETTINGS": {1057        const patch = msg.payload;1058        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {1059          return { ok: false, error: "invalid_payload" };1060        }1061        await vault.updateSettings(patch as vault.VaultSettings);1062        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {1063          await setupAutoLock();1064          if (vault.isUnlocked()) touchAutoLock();1065        }1066        return { ok: true };1067      }1068      case "SETUP_PIN": {1069        const { currentPassword, pin } = (msg.payload ?? {}) as {1070          currentPassword?: unknown;1071          pin?: unknown;1072        };1073        if (typeof currentPassword !== "string" || typeof pin !== "string") {1074          return { ok: false, error: "invalid_payload" };1075        }1076        return (await vault.setupPinUnlock(currentPassword, pin))1077          ? { ok: true }1078          : { ok: false, error: "incorrect_current_password" };1079      }1080      case "DISABLE_PIN": {1081        const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown };1082        if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" };1083        return (await vault.disablePinUnlock(currentPassword))1084          ? { ok: true }1085          : { ok: false, error: "incorrect_current_password" };1086      }1087      case "GET_PENDING_PASSKEY":1088        return { ok: true, data: await getPendingPasskeyRequest() };1089      case "APPROVE_PASSKEY": {1090        const { requestId } = msg.payload as { requestId: number };1091        await resolvePendingPasskeyRequest(requestId, true);1092        return { ok: true };1093      }1094      case "DENY_PASSKEY": {1095        const { requestId } = msg.payload as { requestId: number };1096        await resolvePendingPasskeyRequest(requestId, false);1097        return { ok: true };1098      }1099      case "GET_PASSKEY_PROVIDER_STATE":1100        return { ok: true, data: await getPasskeyProviderState() };1101      case "SET_PASSKEY_PROVIDER_ENABLED": {1102        const { enabled } = msg.payload as { enabled: boolean };1103        // Disabling is always free; gating fires only when a free user is1104        // trying to turn passkey interception on.1105        if (enabled) {1106          const gate = await requirePro("passkeys");1107          if (!gate.allowed) return { ok: false, error: "pro_required" };1108        }1109        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };1110      }1111      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS1112      // endpoint. Intentional product behavior — users configure their own1113      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private1114      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-1115      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to1116      // users that the entry title leaves the device when the canary fires.1117      case "FIRE_CANARY_PING": {1118        // Canary alert fires unconditionally for any entry with canary: true.1119        // The Pro gate only governs creation/flagging of canary entries; once1120        // an entry is flagged, the alert path is a security property and must1121        // never be license-gated.1122        const { webhookUrl, entryTitle, trigger } = msg.payload as {1123          webhookUrl: string;1124          entryTitle: string;1125          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";1126        };1127        if (trigger === "test" && !isExtensionPageSender(sender)) {1128          return { ok: false, error: "invalid_sender" };1129        }1130        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {1131          return { ok: false, error: "invalid_webhook_url" };1132        }1133        // LV-3: debounce non-test pings per (webhook, entry) so a page that1134        // strobes focus/fill events can't turn the canary into a request1135        // firehose at the user's endpoint. Test pings are exempt — they are1136        // explicit user clicks in the settings UI and are awaited for1137        // feedback. The FIRST ping in a window always goes out, so the1138        // dead-man's-switch property (canary fires on access) is preserved;1139        // only repeats within the window are coalesced.1140        if (trigger !== "test") {1141          const keyDigest = new Uint8Array(1142            await crypto.subtle.digest(1143              "SHA-256",1144              new TextEncoder().encode(`${webhookUrl}:${entryTitle}`),1145            ),1146          );1147          const keySuffix = Array.from(keyDigest)1148            .map((byte) => byte.toString(16).padStart(2, "0"))1149            .join("");1150          const rlKey = `canary-last-fetch:${keySuffix}`;1151          const legacyRlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;1152          const stored = await chrome.storage.local.get(rlKey);1153          await chrome.storage.local.remove(legacyRlKey);1154          const last = (stored as Record<string, unknown>)[rlKey];1155          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {1156            return { ok: true, data: { rateLimited: true } };1157          }1158          await chrome.storage.local.set({ [rlKey]: Date.now() });1159        }1160        const body = JSON.stringify({1161          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",1162          entry: entryTitle,1163          trigger,1164          timestamp: new Date().toISOString(),1165          source: "peach-extension",1166        });1167        if (trigger === "test") {1168          // Permitted outbound fetch: user-configured canary alert endpoint1169          // (validated by isAllowedCanaryWebhookUrl above). This is the1170          // only non-HIBP outbound call in the extension — see1171          // Projects.md §3.7. Test pings are awaited so the UI can show1172          // success/failure.1173          try {1174            const res = await fetch(webhookUrl, {1175              method: "POST",1176              headers: { "Content-Type": "application/json" },1177              body,1178            });1179            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1180          } catch (err) {1181            return { ok: false, error: err instanceof Error ? err.message : "network_error" };1182          }1183        }1184        // Non-test triggers are fire-and-forget1185        fetch(webhookUrl, {1186          method: "POST",1187          headers: { "Content-Type": "application/json" },1188          body,1189        }).catch(() => {});1190        return { ok: true };1191      }1192      case "ACTIVATE_LICENSE": {1193        const { key } = msg.payload as { key: string };1194        const licenseInfo = await activateLicense(key);1195        return { ok: true, data: licenseInfo };1196      }1197      case "GET_LICENSE": {1198        const licenseInfo = await getLicenseInfo();1199        return { ok: true, data: licenseInfo };1200      }1201      case "GET_LICENSE_KEY": {1202        const key = await getLicenseKey();1203        return { ok: true, data: key };1204      }1205      case "DEACTIVATE_LICENSE": {1206        await deactivateLicense();1207        return { ok: true };1208      }1209      case "SHOULD_PLAY_CELEBRATION": {1210        const should = await shouldPlayCelebration();1211        return { ok: true, data: should };1212      }1213      case "MARK_CELEBRATION_PLAYED": {1214        await markCelebrationPlayed();1215        return { ok: true };1216      }1217      case "GET_CODEX_VAULT_DATA": {1218        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1219        // popup navigates to the License section without further coordination.1220        // Also privileged-page-gated (PB-26-001), and recoveryWords inside the1221        // snapshot additionally require a fresh master-password proof.1222        const gate = await requirePro("codex");1223        if (!gate.allowed) return { ok: false, error: "pro_required" };1224        const { password } = (msg.payload ?? {}) as { password?: string };1225        return await handleGetCodexVaultData(password);1226      }1227      case "ESTIMATE_CODEX_PAGES": {1228        const gate = await requirePro("codex");1229        if (!gate.allowed) return { ok: false, error: "pro_required" };1230        return await handleEstimateCodexPages();1231      }1232      case "RESTORE_FROM_CODEX": {1233        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1234        // be able to restore a vault that was printed by a Pro user.1235        // DO NOT add a Pro gate here.1236        const payload = msg.payload as CodexRestorePayload;1237        return await handleRestoreFromCodex(payload);1238      }1239      case "OPEN_PRO_GATE": {1240        // Content script requests: open popup and navigate to License section.1241        const { feature } = (msg.payload ?? {}) as { feature?: string };1242        if (chrome.storage.session) {1243          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1244        }1245        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1246        return { ok: true };1247      }1248      case "OPEN_POPUP": {1249        // Content script asks to open the trusted extension popup — used by the1250        // inline locked bubble so the master password is entered in the popup,1251        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1252        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1253        // toolbar icon. The badge already signals Peach needs attention.1254        //1255        // Set a session flag so the popup knows it was opened for inline unlock1256        // and should close itself once the vault is unlocked (returning the user1257        // to the inline autofill selector on the page).1258        const { entryId } = (msg.payload ?? {}) as { entryId?: unknown };1259        if (entryId !== undefined && (typeof entryId !== "string" || entryId.length === 0 || entryId.length > 64)) {1260          return { ok: false, error: "invalid_payload" };1261        }1262        if (chrome.storage.session) {1263          if (typeof entryId === "string") {1264            await chrome.storage.session.set({ peach_open_entry: entryId });1265          } else {1266            await chrome.storage.session.set({ peach_inline_unlock: true });1267          }1268        }1269        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1270        return { ok: true };1271      }1272      case "OPEN_DETACHED_POPUP": {1273        // A window created by the action popup and then orphaned with1274        // window.close() is cascaded shut by Chrome, so the file-picker1275        // flows (OS dialogs that dismiss the popup on focus loss) ask the SW1276        // to open the standalone window instead — the SW has no window to be1277        // associated with. The query string is allowlisted so this can never1278        // open an arbitrary URL.1279        const { route } = (msg.payload ?? {}) as { route?: string };1280        const search = route === "peachscript"1281          ? "?restore=peachscript"1282          : route === "csv"1283            ? "?restore=csv"1284            : route === "codex-pdf"1285              ? "?codex=pdf"1286              : null;1287        if (!search) return { ok: false, error: "bad_route" };1288        try {1289          const popupHtml =1290            chrome.runtime.getManifest().action?.default_popup ?? "src/popup/index.html";1291          await chrome.windows.create({1292            url: chrome.runtime.getURL(`${popupHtml}${search}`),1293            type: "popup",1294            width: 320,1295            height: 550,1296          });1297          return { ok: true, data: { detached: true } };1298        } catch {1299          return { ok: false };1300        }1301      }1302      case "GET_IDENTITIES": {1303        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1304        return { ok: true, data: vault.getIdentities() };1305      }1306      case "TOUCH_AUTO_LOCK": {1307        // touchAutoLock() is already called by shouldRefreshAutoLock above;1308        // this case just gives the popup a typed message to keep the session alive.1309        return { ok: true };1310      }1311      case "GET_ADVANCED_HEALTH_REPORT": {1312        const gate = await requirePro("advanced_health");1313        if (!gate.allowed) return { ok: false, error: "pro_required" };1314        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1315        const report = await buildAdvancedHealthReport(vault.getEntries());1316        return { ok: true, data: report };1317      }1318      case "IS_DURESS_ENABLED": {1319        const enabled = await vault.isDuressEnabled();1320        return { ok: true, data: enabled };1321      }1322      case "SETUP_DURESS": {1323        // Single enforcement point for the Duress Vault Pro gate. Free users1324        // who somehow reach this handler are rejected here; the popup also1325        // pre-checks isPro() to avoid showing the setup form to free users,1326        // but server-side is the actual security boundary.1327        const gate = await requirePro("duress_vault");1328        if (!gate.allowed) return { ok: false, error: "pro_required" };1329        // MV3 service workers restart after inactivity, losing the in-memory1330        // derived key. Detect this before calling setupDuress so the popup1331        // can show a meaningful prompt to re-lock and re-unlock.1332        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1333        const { duressPassword } = msg.payload as { duressPassword: string };1334        await vault.setupDuress(duressPassword);1335        return { ok: true };1336      }1337      case "DISABLE_DURESS": {1338        await vault.disableDuress();1339        return { ok: true };1340      }1341      case "VERIFY_MAIN_PASSWORD": {1342        const { password } = msg.payload as { password: string };1343        const ok = await vault.verifyMainPassword(password);1344        return { ok: true, data: ok };1345      }1346      case "CHANGE_PASSWORD": {1347        const { currentPassword, newPassword } = msg.payload as {1348          currentPassword: string;1349          newPassword: string;1350        };1351        const changed = await vault.changePassword(currentPassword, newPassword);1352        return changed1353          ? { ok: true }1354          : { ok: false, error: "incorrect_current_password" };1355      }1356      case "GET_SITE_PASSWORD_POLICY": {1357        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1358        if (!tab?.id) return { ok: true, data: null };1359        try {1360          const response = await chrome.tabs.sendMessage(tab.id, {1361            type: "GET_SITE_PASSWORD_POLICY",1362          });1363          return (response as MessageResponse) ?? { ok: true, data: null };1364        } catch {1365          return { ok: true, data: null };1366        }1367      }1368      case "RECORD_MANUAL_SUMMON": {1369        const { domain } = (msg.payload ?? {}) as { domain?: unknown };1370        const origin = attestedSenderOrigin(sender);1371        let senderDomain: string | null = null;1372        if (origin) {1373          try {1374            const hostname = new URL(origin).hostname;1375            senderDomain = extractDomain(hostname) ?? hostname;1376          } catch {1377            senderDomain = null;1378          }1379        }1380        if (typeof domain !== "string" || domain.length > 253 || domain !== senderDomain) {1381          return { ok: false, error: "invalid_domain" };1382        }1383        const settings = vault.getSettings();1384        const existing = settings.manualSummonDomains?.[domain];1385        const now = Date.now();1386        await vault.updateSettings({1387          manualSummonDomains: {1388            ...settings.manualSummonDomains,1389            [domain]: {1390              firstSummonedAt: existing?.firstSummonedAt ?? now,1391              summonCount: (existing?.summonCount ?? 0) + 1,1392              lastSummonedAt: now,1393            },1394          },1395        });1396        return { ok: true };1397      }1398      case "DECLINE_CARD_SAVE": {1399        // PB-26-108: the declined-card digest is keyed by root-key material, so1400        // a decline cannot be recorded while locked. Offers are not shown while1401        // locked either, so this is unreachable in practice.1402        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1403        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1404        await vault.declineCardSaveOffer(last4, expMonth, expYear);1405        return { ok: true };1406      }1407      case "IS_CARD_DECLINED": {1408        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1409        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1410        return { ok: true, data: declined };1411      }1412      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1413        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1414          rpId?: string;1415          rpName?: string;1416          userName?: string;1417          userDisplayName?: string;1418        };1419        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1420        return await initiateFirefoxPasskeyCreate({1421          rpId,1422          rpName: rpName ?? rpId,1423          userName,1424          userDisplayName,1425        }, attestedSenderOrigin(sender));1426      }14271428      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1429        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1430        if (!payload) return { ok: false, error: "missing_payload" };1431        return await completeFirefoxPasskeyCreate(payload);1432      }14331434      case "PASSKEY_OFFER_DECLINE": {1435        const { domain } = (msg.payload ?? {}) as { domain?: string };1436        const origin = attestedSenderOrigin(sender);1437        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1438        await recordPasskeyOfferDecline(domain);1439        return { ok: true };1440      }14411442      case "GET_PASSKEY_OFFER_DECLINED": {1443        const { domain } = (msg.payload ?? {}) as { domain?: string };1444        const origin = attestedSenderOrigin(sender);1445        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1446        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1447      }14481449      case "PASSKEY_HAS_CREDENTIALS": {1450        const payload = msg.payload as {1451          rpId?: string;1452          allowCredentials?: Array<{ id: string; type?: string }>;1453        } | undefined;1454        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1455        return await handlePasskeyHasCredentials({1456          rpId: payload.rpId,1457          allowCredentials: payload.allowCredentials ?? [],1458        }, attestedSenderOrigin(sender));1459      }14601461      case "PASSKEY_CREATE": {1462        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1463        if (!payload?.rpId || !payload?.userName) {1464          return { ok: false, error: "rpid_and_username_required" };1465        }1466        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1467      }14681469      case "PASSKEY_GET": {1470        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1471        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1472        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1473      }14741475      case "PASSKEY_AUTH_RESPONSE": {1476        const { requestId, approved } = (msg.payload ?? {}) as {1477          requestId?: string | number;1478          approved?: boolean;1479        };1480        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1481          return { ok: false, error: 'requestId and approved required' };1482        }1483        const pending = await getPendingPasskeyRequest();1484        const senderOrigin = attestedSenderOrigin(sender);1485        if (1486          (pending && pending.requestId !== Number(requestId)) ||1487          (pending?.tabId !== undefined && sender.tab?.id !== pending.tabId) ||1488          (pending?.origin !== undefined && senderOrigin !== pending.origin)1489        ) {1490          return { ok: false, error: "invalid_passkey_approval_sender" };1491        }1492        await resolvePendingPasskeyRequest(Number(requestId), approved);1493        return { ok: true };1494      }14951496      case "GET_PASSKEY_FOR_DOMAIN": {1497        const { domain } = (msg.payload ?? {}) as { domain?: string };1498        if (!domain) return { ok: false, error: "domain_required" };1499        // Scope to the caller's own origin: a page may only ask about passkeys1500        // for a domain it actually owns, so an arbitrary page cannot enumerate1501        // which sites the user holds passkeys for or read the username (audit MEDIUM).1502        const origin = attestedSenderOrigin(sender);1503        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1504        if (!vault.isUnlocked()) return { ok: true, data: null };1505        const match = vault1506          .getEntries()1507          .find((entry) => entry.passkey?.rpId === domain);1508        if (!match || !match.passkey) return { ok: true, data: null };1509        // Slim shape — only the fields State 11 needs. Never expose private1510        // key material, even though this is locked behind isUnlocked.1511        // bannerShown is the per-domain "already surfaced" flag, kept in1512        // trusted background session storage so content scripts never touch1513        // chrome.storage.session directly (PB-26-203).1514        let bannerShown = false;1515        if (chrome.storage.session) {1516          const flag = await chrome.storage.session.get(`peach_state11_shown:${domain}`);1517          bannerShown = Boolean((flag as Record<string, unknown>)[`peach_state11_shown:${domain}`]);1518        }1519        return {1520          ok: true,1521          data: {1522            rpId: match.passkey.rpId,1523            userName: match.passkey.userName,1524            browser: match.passkey.browser,1525            bannerShown,1526          },1527        };1528      }15291530      case "MARK_PASSKEY_BANNER_SHOWN": {1531        const { domain } = (msg.payload ?? {}) as { domain?: string };1532        if (typeof domain !== "string" || !domain) return { ok: false, error: "domain_required" };1533        // Same origin binding as the read path: a page may only mark its own1534        // domain, and the flag reveals nothing either way.1535        const origin = attestedSenderOrigin(sender);1536        if (!origin || !isValidRpId(domain, origin)) return { ok: true };1537        if (chrome.storage.session) {1538          await chrome.storage.session.set({ [`peach_state11_shown:${domain}`]: Date.now() });1539        }1540        return { ok: true };1541      }15421543      case "DESTROY_VAULT": {1544        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1545        // storage.local.clear() wipes every Peach key (slots, settings, license,1546        // onboarded flag, history, sync state, declined cards, recall, etc.);1547        // session.clear() wipes pending passkey requests + pro-notice queues.1548        // Caller (Panic.tsx) handles UI navigation back to onboarding.1549        //1550        // The Pro license is the one thing that must survive: the user paid for1551        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1552        // Capture it before the clear and restore it after. peach_pro_celebrated1553        // rides along so the Pro celebration doesn't replay on the next unlock.1554        const preserved = await chrome.storage.local.get([1555          "peach_license",1556          "peach_pro_celebrated",1557        ]);1558        await vault.lock();1559        await storageClear();1560        await vault.clearVaultHistory();1561        const toRestore: Record<string, unknown> = {};1562        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1563        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1564        if (Object.keys(toRestore).length > 0) {1565          await chrome.storage.local.set(toRestore);1566        }1567        if (chrome.storage.session) {1568          await chrome.storage.session.clear();1569        }1570        await clearRecoveryConfirmPending();1571        return { ok: true };1572      }15731574      case "GET_IDENTITY_SUGGESTIONS": {1575        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1576        const entries = vault.getEntries();1577        const suggestions = buildIdentitySuggestions(entries);1578        return { ok: true, data: { suggestions } };1579      }1580      case "ML_INIT":1581        return { ok: true };15821583      case "ML_PREDICT_BATCH": {1584        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1585        if (!isValidMLFeatureBatch(featuresArray, MAX_ML_BATCH_FIELDS)) {1586          return { ok: false, error: "invalid_payload" };1587        }1588        if (!claimMLWork(sender, featuresArray.length)) {1589          return { ok: false, error: "rate_limited" };1590        }1591        return { ok: true, data: mlPredictBatch(featuresArray) };1592      }15931594      // ── Vault sync (v3) ───────────────────────────────────────────────1595      // Returns the public-facing local identity needed by the popup to1596      // drive Phase-1 audio pairing. The private long-term key never1597      // leaves the background.1598      case "GET_LOCAL_IDENTITY": {1599        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1600        // Pro license from an already-Pro peer (at least one device must be Pro).1601        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1602        // Identity derives from the stable root key, not the password-derived1603        // key, so pairing survives a master-password change (SEV-2-B).1604        const masterKeyHex = vault.getRootKeyHex();1605        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1606        const masterKey = unhexBytes(masterKeyHex);1607        try {1608          const identity = await buildLocalIdentity(masterKey);1609          // If this device is Pro, advertise the signed license so the peer can1610          // activate it after SAS confirmation — pairing carries Pro across.1611          if (await isProUser()) {1612            const license = await getLicenseKey();1613            if (license) (identity as { license?: string }).license = license;1614          }1615          return { ok: true, data: identity };1616        } finally {1617          masterKey.fill(0);1618        }1619      }16201621      case "LIST_PAIRED_DEVICES": {1622        if (vault.isDecoyMode()) return { ok: true, data: { devices: [] } };1623        const devices = await listPairedDevicesV3();1624        return { ok: true, data: { devices } };1625      }16261627      case "RENAME_PAIRED_DEVICE": {1628        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1629        const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string };1630        if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") {1631          return { ok: false, error: "invalid_payload" };1632        }1633        await renamePairedDeviceV3(deviceId, name);1634        return { ok: true };1635      }16361637      case "UNPAIR_DEVICE": {1638        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1639        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1640        if (typeof deviceId !== "string" || !deviceId) {1641          return { ok: false, error: "invalid_payload" };1642        }1643        // Removing a device REVOKES it rather than just dropping the local1644        // row: a plain removal is undone the moment any other peer vouches it1645        // back through a manifest, which is exactly what the relay makes easy.1646        await revokeDeviceByIdV3(deviceId, await getOrCreateDeviceId());1647        // PB-26-213: forget the secret now so no further dial can use it.1648        // Removals that happen while locked leave orphans for the next1649        // unlock's reconcile to prune.1650        const unpairRootHex = vault.getRootKeyHex();1651        if (unpairRootHex) {1652          const unpairRoot = unhexBytes(unpairRootHex);1653          try {1654            await dropPairSecret(deviceId, unpairRoot);1655          } finally {1656            unpairRoot.fill(0);1657          }1658        } else {1659          await dropPairSecret(deviceId, null);1660        }1661        // Sync against the remaining hosts — the unpaired device no longer1662        // matters but the next alarm tick is up to ten minutes away.1663        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1664        return { ok: true };1665      }16661667      case "RENAME_LOCAL_DEVICE": {1668        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1669        const { name } = (msg.payload ?? {}) as { name?: string };1670        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1671        await setDeviceNameV3(name);1672        return { ok: true };1673      }16741675      // ── Relay pairing ─────────────────────────────────────────────────────1676      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1677      // session runs in the background; the SAS and the terminal result reach1678      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1679      case "START_ADOPTION_SOURCE": {1680        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1681        if (isRelayAdoptionSourceInFlight()) {1682          return { ok: false, error: "adoption_source_in_progress" };1683        }1684        try {1685          return { ok: true, data: await startRelayAdoptionSource() };1686        } catch (error) {1687          return {1688            ok: false,1689            error: error instanceof Error ? error.message : "adoption_source_failed",1690          };1691        }1692      }16931694      // Onboarding receiver — empty extension shows a QR, phone scans and1695      // sends the vault. The popup supplies the local-only password here so1696      // the background can wrap the adopted root key at rest without ever1697      // asking the user to retype it.1698      case "START_ADOPTION_RECEIVER": {1699        if (isRelayAdoptionSourceInFlight()) {1700          return { ok: false, error: "adoption_receiver_in_progress" };1701        }1702        const password = (msg.payload as { password?: unknown } | undefined)?.password;1703        if (typeof password !== "string" || password.length === 0) {1704          return { ok: false, error: "invalid_payload" };1705        }1706        try {1707          return { ok: true, data: await startRelayAdoptionReceiver(password) };1708        } catch (error) {1709          return {1710            ok: false,1711            error: error instanceof Error ? error.message : "adoption_receiver_failed",1712          };1713        }1714      }17151716      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1717      // on the source's SAS screen. The id round-trips the same way so a stale1718      // late response can't approve the wrong session.1719      case "RECEIVER_SAS_DECISION": {1720        const payload = msg.payload as { id?: unknown; sas?: unknown; ok?: unknown } | undefined;1721        if (typeof payload?.id !== "string" || typeof payload.sas !== "string" || typeof payload.ok !== "boolean") {1722          return { ok: false, error: "invalid_payload" };1723        }1724        return { ok: resolveReceiverSasConfirmation(payload.id, payload.sas, payload.ok) };1725      }17261727      case "SOURCE_SAS_DECISION": {1728        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1729        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1730          return { ok: false, error: "invalid_payload" };1731        }1732        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1733      }1734      case "LIST_PENDING_ADOPTION_HOLDERS": {1735        return { ok: true, data: await listPendingAdoptionHolders() };1736      }17371738      case "REMOVE_PENDING_ADOPTION_HOLDER": {1739        await removePendingAdoptionHolder();1740        return { ok: true };1741      }174217431744      case "CANCEL_ADOPTION_SOURCE": {1745        cancelRelayAdoptionSource();1746        return { ok: true };1747      }17481749      case "TRIGGER_SYNC": {1750        if (vault.isDecoyMode()) return { ok: true };1751        const payload = (msg.payload ?? {}) as {1752          reason?: "vault_change" | "foreground" | "manual";1753          force?: boolean;1754        };1755        const reason = payload.reason ?? "foreground";17561757        void triggerSyncIfReachable({ reason, force: payload.force === true });1758        return { ok: true };1759      }17601761      case "GET_SYNC_STATE": {1762        if (vault.isDecoyMode()) return { ok: true, data: { status: "idle" } };1763        return { ok: true, data: getSyncState() };1764      }17651766      case "GET_SYNC_SETTINGS": {1767        if (vault.isDecoyMode()) return { ok: true, data: { mode: "off", relayUrl: "" } };1768        return { ok: true, data: await getSyncSettings() };1769      }17701771      case "SET_SYNC_SETTINGS": {1772        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1773        const payload = (msg.payload ?? {}) as {1774          mode?: unknown;1775          relayUrl?: unknown;1776        };1777        try {1778          // A custom relay URL implies private mode; Peach's own relay stays1779          // public. See setRelayUrl.1780          if (payload.relayUrl !== undefined) {1781            if (typeof payload.relayUrl !== "string") {1782              return { ok: false, error: "invalid_relay_url" };1783            }1784            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1785          }1786          if (payload.mode !== undefined) {1787            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1788              return { ok: false, error: "invalid_sync_mode" };1789            }1790            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1791          }1792          return { ok: true, data: await getSyncSettings() };1793        } catch (error) {1794          return {1795            ok: false,1796            error: error instanceof Error ? error.message : "invalid_relay_url",1797          };1798        }1799      }180018011802      case "GET_SYNC_ALERTS": {1803        if (vault.isDecoyMode()) return { ok: true, data: [] };1804        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1805        const alerts = await getPendingSyncAlerts();1806        // The popup reads on open and acknowledges with consume:true after1807        // rendering, so a popup crash between read and render doesn't lose1808        // the alerts.1809        if (consume) await clearPendingSyncAlerts();1810        return { ok: true, data: alerts };1811      }18121813      case "GET_PENDING_VOUCHED_DEVICES": {1814        if (vault.isDecoyMode()) return { ok: true, data: [] };1815        return { ok: true, data: await listPendingVouchedDevices() };1816      }1817      case "CONFIRM_VOUCHED_DEVICE": {1818        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1819        const { deviceId } = msg.payload as { deviceId: string };1820        const pending = await getPendingVouchedDevice(deviceId);1821        if (!pending) return { ok: false, error: "not_pending" };1822        // Last gate before a vouched device becomes a sync peer. A queue entry1823        // can predate the revocation that names it, so revocation is re-checked1824        // here rather than trusted to have swept the queue.1825        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {1826          await removePendingVouchedDevice(deviceId);1827          return { ok: false, error: "device_revoked" };1828        }1829        await upsertPairedDeviceV3({1830          deviceId: pending.deviceId,1831          deviceName: pending.deviceName,1832          deviceType:1833            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1834          longTermPublicKeyHex: pending.longTermPublicKeyHex,1835          signingPublicKeyHex: pending.signingPublicKeyHex,1836          wsPort: pending.wsPort,1837          pairedAt: pending.pairedAt,1838          trustSource: "vouched",1839        });1840        await removePendingVouchedDevice(deviceId);1841        // Newly confirmed vouched device is now a sync target — kick a round1842        // so the mesh introduction pays off without a 10-minute wait.1843        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1844        return { ok: true };1845      }1846      case "REJECT_VOUCHED_DEVICE": {1847        if (vault.isDecoyMode()) return { ok: true };1848        const { deviceId } = msg.payload as { deviceId: string };1849        await removePendingVouchedDevice(deviceId);1850        return { ok: true };1851      }18521853      case "ROTATE_SYNC_IDENTITY": {1854        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1855        const result = await vault.rotateSyncIdentity();1856        return result.ok ? { ok: true } : { ok: false, error: result.error };1857      }18581859      default:1860        return { ok: false, error: "unknown_message_type" };1861    }1862  } catch (err) {1863    return {1864      ok: false,1865      error: err instanceof Error ? err.message : "operation_failed",1866    };1867  }1868}18691870// Returns username use-counts from the vault, sorted by frequency. Each row1871// also carries the entry's email so the popup can suggest the email/username1872// pair the user has actually used together.1873function buildIdentitySuggestions(1874  entries: VaultEntry[],1875): Array<{ email: string; username: string; count: number }> {1876  const usernameCounts = new Map<string, number>();1877  const usernameEmail = new Map<string, string>();1878  for (const entry of entries) {1879    const username = entry.username ?? "";1880    const email = (entry as VaultEntry & { email?: string }).email ?? "";1881    if (!username && !email) continue;1882    const key = username || email;1883    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1884    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1885  }1886  return Array.from(usernameCounts.entries())1887    .sort((a, b) => b[1] - a[1])1888    .map(([username, count]) => ({1889      email: usernameEmail.get(username) ?? "",1890      username,1891      count,1892    }));1893}18941895/** Notify all content scripts that the vault just became available. */1896function broadcastToContentScripts(message: { type: string }): void {1897  if (!chrome.tabs?.query) return;1898  chrome.tabs.query({}, (tabs) => {1899    for (const tab of tabs) {1900      if (tab.id !== undefined) {1901        chrome.tabs.sendMessage(tab.id, message).catch(() => {1902          // Tab may not have a content script — silently ignore1903        });1904      }1905    }1906  });1907}19081909function shouldRefreshAutoLock(1910  type: MessageType,1911  sender: Partial<chrome.runtime.MessageSender>,1912): boolean {1913  if (!isExtensionPageSender(sender)) return false;1914  return (1915    type !== "HAS_VAULT" &&1916    type !== "IS_UNLOCKED" &&1917    type !== "GET_VAULT_STATUS" &&1918    type !== "LOCK" &&1919    type !== "UPDATE_SETTINGS" &&1920    type !== "GET_PENDING_PASSKEY" &&1921    type !== "GET_PASSKEY_PROVIDER_STATE" &&1922    type !== "DECLINE_CARD_SAVE" &&1923    type !== "IS_CARD_DECLINED" &&1924    type !== "AUTOFILL_QUERY" &&1925    type !== "ML_PREDICT_BATCH"1926  );1927}19281929function isAllowedCanaryWebhookUrl(value: string): boolean {1930  try {1931    const url = new URL(value);1932    if (url.protocol !== "https:") return false;19331934    const hostname = url.hostname.toLowerCase();1935    if (1936      hostname === "localhost" ||1937      hostname.endsWith(".localhost") ||1938      isPrivateIpv4(hostname) ||1939      isPrivateIpv6(hostname)1940    ) {1941      return false;1942    }19431944    return true;1945  } catch {1946    return false;1947  }1948}19491950function isPrivateIpv4(hostname: string): boolean {1951  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1952    return true;1953  }19541955  const octets = hostname.split(".").map((part) => Number(part));1956  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1957    return false;1958  }19591960  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1961}19621963function isPrivateIpv6(hostname: string): boolean {1964  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1965  // IPv4-mapped IPv6 literals embed a plain IPv4 address that the prefix1966  // list below can never match (WHATWG URL serializes [::ffff:192.168.0.1]1967  // as ::ffff:c0a8:1). Unwrap and test the embedded IPv4; unparseable mapped1968  // tails fail closed. (Codex Security 2026-08-04 LOW,1969  // ssrf.webhook-url-private-ip-filter.) DNS rebinding is out of scope for a1970  // one-shot host check.1971  const mapped = /^::ffff:(.+)$/.exec(normalized);1972  if (mapped) {1973    const tail = mapped[1] ?? "";1974    if (tail.includes(".")) return isPrivateIpv4(tail);1975    const parts = tail.split(":");1976    const [hi, lo] = parts;1977    if (1978      parts.length !== 2 ||1979      !hi ||1980      !lo ||1981      !/^[0-9a-f]{1,4}$/.test(hi) ||1982      !/^[0-9a-f]{1,4}$/.test(lo)1983    ) {1984      return true;1985    }1986    const octets = [1987      (Number.parseInt(hi, 16) >>> 8) & 0xff,1988      Number.parseInt(hi, 16) & 0xff,1989      (Number.parseInt(lo, 16) >>> 8) & 0xff,1990      Number.parseInt(lo, 16) & 0xff,1991    ];1992    return isPrivateIpv4(octets.join("."));1993  }1994  return (1995    normalized === "::1" ||1996    normalized.startsWith("fc") ||1997    normalized.startsWith("fd") ||1998    normalized.startsWith("fe80:")1999  );2000}