messages.ts

85.3 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  type LocalDeviceIdentity,76} from "./device-identity";77import {78  isDeviceRevoked,79  listPairedDevices as listPairedDevicesV3,80  renamePairedDevice as renamePairedDeviceV3,81  revokeDeviceById as revokeDeviceByIdV3,82  TrustDataCorruptedError,83  upsertPairedDevice as upsertPairedDeviceV3,84} from "./paired-devices";85import { dropPairSecret } from "./pair-secrets";86// Sync and pairing are imported statically, never with `await import()`.87// `import()` throws `TypeError: import() is disallowed on88// ServiceWorkerGlobalScope` at runtime in MV3, and Vite's preload helper89// reports the failure through `window.dispatchEvent`, which does not exist in90// a worker either — so the real reason was replaced by "window is not defined"91// and the pairing UI just stopped. scripts/check-sw-static-imports.mjs fails92// the build if a runtime import() reappears anywhere in the worker's graph.93import {94  cancelRelayAdoptionSource,95  isRelayAdoptionSourceInFlight,96  resolveReceiverSasConfirmation,97  resolveSourceSasConfirmation,98  startRelayAdoptionReceiver,99  startRelayAdoptionSource,100} from "./relay-adoption-bg";101import {102  listPendingAdoptionHolders,103  removePendingAdoptionHolder,104} from "./pending-adoption-holder";105import {106  getSyncSettings,107  setRelayUrl,108  setSyncMode,109  type SyncMode,110} from "./sync-settings";111import {112  getSyncState,113  triggerSyncIfReachable,114} from "./sync-trigger";115import {116  browserGenerationIo,117  confirmSecureReset,118  enterResetRequired,119  resolveGeneration,120} from "./sync-generation";121import { isMessageSenderAllowed } from "./message-policy";122123const SUMMON_CAPABILITY_TTL_MS = 30_000;124type SummonCapability = { tabId: number; frameId: number; origin: string; operation: "inventory" | "fill"; expiresAt: number };125const summonCapabilities = new Map<string, SummonCapability>();126127export function createSummonCapability(tabId: number, origin: string, frameId = 0): string {128  const token = crypto.randomUUID();129  summonCapabilities.set(token, { tabId, frameId, origin, operation: "inventory", expiresAt: Date.now() + SUMMON_CAPABILITY_TTL_MS });130  return token;131}132133function consumeSummonCapability(token: unknown, sender: Partial<chrome.runtime.MessageSender>, operation: "inventory" | "fill"): boolean {134  if (typeof token !== "string") return false;135  const cap = summonCapabilities.get(token);136  if (!cap) return false;137  if (cap.expiresAt <= Date.now()) {138    summonCapabilities.delete(token);139    return false;140  }141  if (sender.tab?.id !== cap.tabId || (sender.frameId ?? 0) !== cap.frameId || attestedSenderOrigin(sender) !== cap.origin) return false;142  if (cap.operation !== operation) return false;143  if (operation === "inventory") cap.operation = "fill";144  else summonCapabilities.delete(token);145  return true;146}147148// Compile-time E2E flag, folded to a literal by Vite's `define` (false in149// every production build — verified in the bundled output). Mirrors the150// create-path bypass in passkey.ts so the Playwright passkey smoke can enable151// the provider without a real Pro licence; the gate is fully intact for users.152declare const __PEACH_E2E_PASSKEYS__: boolean;153const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true;154155function unhexBytes(hex: string): Uint8Array {156  if (hex.length % 2 !== 0) throw new Error("invalid hex");157  const out = new Uint8Array(hex.length / 2);158  for (let i = 0; i < out.length; i++) {159    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);160  }161  return out;162}163164/**165 * The single Pro gate. Every gated handler calls this first; the broadcast166 * lets the popup react (navigate to the License section, highlight the167 * relevant feature). Background never touches the popup view directly —168 * the popup owns navigation. See Projects.md "Pro gate rule".169 */170async function requirePro(171  feature: ProFeature,172  trigger: "user" | "background" = "user"173): Promise<{ allowed: boolean }> {174  if (PASSKEY_E2E_PRO_BYPASS && feature === "passkeys") return { allowed: true };175  if (await isProUser()) return { allowed: true };176177  if (trigger === "user") {178    // User deliberately triggered this feature — redirect the popup immediately.179    chrome.runtime180      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })181      .catch(() => {182        // Popup may be closed — the gate signal is best-effort.183      });184  } else {185    // Background trigger (e.g. passive sync initiation) — no popup is open.186    // Queue a notice so the next popup open shows a soft banner instead of187    // silently failing.188    if (chrome.storage.session) {189      chrome.storage.session190        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })191        .catch(() => {});192    }193  }194195  return { allowed: false };196}197198// LV-3: minimum interval between non-test canary pings per webhook+entry.199const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour200201const PRIVATE_IPV4_RANGES = [202  { prefix: "10." },203  { prefix: "127." },204  { prefix: "169.254." },205  { prefix: "192.168." },206];207208export function setupMessageHandler(): void {209  chrome.runtime.onMessage.addListener(210    (msg: unknown, sender, sendResponse) => {211      if (!isMessage(msg)) {212        sendResponse({ ok: false, error: "invalid_message" });213        return true;214      }215      handleMessage(msg, sender)216        .then(sendResponse)217        .catch((err) =>218          sendResponse({219            ok: false,220            error: err instanceof Error ? err.message : String(err),221          })222        );223      return true;224    }225  );226}227228function isMessage(m: unknown): m is Message {229  return typeof m === "object" && m !== null && "type" in m;230}231232/**233 * The browser-attested origin of the page that originated this message. A web234 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),235 * so every page-driven message arrives via the content-script relay and the236 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a237 * value the page cannot forge. This is the ONLY trustworthy origin for passkey238 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.239 */240function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {241  if (sender.origin) return sender.origin;242  if (sender.url) {243    try { return new URL(sender.url).origin; } catch { return undefined; }244  }245  return undefined;246}247248function isExtensionPageSender(sender: Partial<chrome.runtime.MessageSender>): boolean {249  return sender.url?.startsWith("chrome-extension://") === true ||250    sender.url?.startsWith("moz-extension://") === true;251}252253/** True when the message came from a page frame rather than extension UI. */254function isPageSender(sender: Partial<chrome.runtime.MessageSender>): boolean {255  return !isExtensionPageSender(sender) &&256    (sender.tab !== undefined || sender.url !== undefined);257}258259function entryDomains(url: unknown, additionalUrls: unknown): Set<string> {260  const domains = new Set<string>();261  const primary = typeof url === "string" ? extractDomain(url) : null;262  if (primary) domains.add(primary);263  if (Array.isArray(additionalUrls)) {264    for (const extra of additionalUrls) {265      if (typeof extra !== "string") continue;266      const domain = extractDomain(extra);267      if (domain) domains.add(domain);268    }269  }270  return domains;271}272273/**274 * PB-26-106: the autofill read path re-validates the frame origin against the275 * entry's domains on every request, so an unbound write path would let a276 * content script repoint an entry at its own origin and then read the277 * credential through a read path that is behaving correctly.278 *279 * Creating an entry: a page may only bind it to itself. Mutating one: a page280 * may never GROW the domain set — only shrink it, and never below its own281 * attested origin.282 *283 * Self-binding on mutation was considered and is not enough: the content284 * script on a foreign origin IS the attacker in the reported chain, so letting285 * it attach "its own" origin lets it mint the very capability the read path286 * exists to withhold. The legitimate flow that needs a new domain — the inline287 * "remember this site" toast — therefore asks the popup instead288 * (REQUEST_REMEMBER_SITE), which is an extension page and exempt here.289 *290 * Extension pages are exempt: the popup edits entries for sites it is not on.291 */292function senderMayBindEntryDomains(293  sender: Partial<chrome.runtime.MessageSender>,294  domains: Set<string>,295): boolean {296  if (isExtensionPageSender(sender)) return true;297  const domain = attestedSenderDomain(sender);298  if (domain === null) return false;299  for (const candidate of domains) {300    if (candidate !== domain) return false;301  }302  return true;303}304305function senderMayMutateEntryDomains(306  sender: Partial<chrome.runtime.MessageSender>,307  before: Set<string>,308  after: Set<string>,309): boolean {310  if (isExtensionPageSender(sender)) return true;311  const domain = attestedSenderDomain(sender);312  if (domain === null || !after.has(domain)) return false;313  for (const kept of after) {314    if (!before.has(kept)) return false;315  }316  return true;317}318319/**320 * Null for extension pages (which the callers exempt), for senders with no321 * attested origin at all, and for unparseable frame urls.322 */323function attestedSenderDomain(sender: Partial<chrome.runtime.MessageSender>): string | null {324  if (sender.tab === undefined && sender.url === undefined) return null;325  const origin = attestedSenderOrigin(sender);326  if (!origin) return null;327  try { return extractDomain(new URL(origin).hostname); } catch { return null; }328}329330function patchChangesEntryOrigin(patch: object): boolean {331  return Object.hasOwn(patch, "url") || Object.hasOwn(patch, "additionalUrls");332}333334/** The entry's domain-bearing fields as the patch would leave them. */335function patchedUrlShape(336  patch: object,337  existing: Pick<VaultEntry, "url" | "additionalUrls">,338): { url: unknown; additionalUrls: unknown } {339  const candidate = patch as { url?: unknown; additionalUrls?: unknown };340  return {341    url: Object.hasOwn(patch, "url") ? candidate.url : existing.url,342    additionalUrls: Object.hasOwn(patch, "additionalUrls")343      ? candidate.additionalUrls344      : existing.additionalUrls,345  };346}347// Resolves once restoreFromSession() has run, so handlers see the correct348// post-restore unlock state. entry.ts registers this BEFORE the message349// handler so the onMessage listener is added synchronously at SW startup350// (MV3 requirement) while unlock-dependent handlers still wait for restore.351let restoreReady: Promise<void> = Promise.resolve();352const MAX_ML_BATCH_FIELDS = 128;353const MAX_ML_FIELDS_PER_SECOND = 256;354const mlWorkBySender = new Map<string, { startedAt: number; fields: number }>();355356function claimMLWork(sender: Partial<chrome.runtime.MessageSender>, fields: number): boolean {357  if (fields === 0) return true;358  const now = Date.now();359  for (const [key, value] of mlWorkBySender) {360    if (now - value.startedAt >= 1_000) mlWorkBySender.delete(key);361  }362  const key = `${sender.tab?.id ?? "ui"}:${sender.frameId ?? 0}:${attestedSenderOrigin(sender) ?? "extension"}`;363  const current = mlWorkBySender.get(key);364  if (!current) {365    mlWorkBySender.set(key, { startedAt: now, fields });366    return fields <= MAX_ML_FIELDS_PER_SECOND;367  }368  if (current.fields + fields > MAX_ML_FIELDS_PER_SECOND) return false;369  current.fields += fields;370  return true;371}372373/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */374export function setRestoreReady(p: Promise<unknown>): void {375  restoreReady = p.then(() => undefined, () => undefined);376}377378export async function handleMessage(379  msg: Message,380  sender: Partial<chrome.runtime.MessageSender> = {}381): Promise<MessageResponse> {382  try {383    // Wait for session-restore to finish before reading any unlock/vault state.384    // On a cold SW start the popup's first message arrives while restore is385    // still in flight; without this gate IS_UNLOCKED would report locked (a386    // spurious lock screen) and the storage reads could race. The onMessage387    // listener itself is registered synchronously (entry.ts) so this gate, not388    // listener registration, is what absorbs the cold-start window.389    await restoreReady;390    // Validate sender — only allow messages from our extension pages/scripts.391    // `sender.id` is undefined for messages originating from extension UI392    // (popup/options), which is legitimate; reject only when it is defined393    // and does not match our extension id.394    if (395      sender.id !== undefined &&396      sender.id !== chrome.runtime.id397    ) {398      return { ok: false, error: "invalid_sender" };399    }400401    // PB-26-016: sender authorization is an exhaustive policy, not a402    // hand-maintained privileged denylist. A missing/unknown policy entry or a403    // background-only message fails closed before any handler runs.404    // Extension UI messages may legitimately omit sender.url. Resolve the405    // browser-attested extension origin only when a URL is present; this also406    // keeps test/runtime shims without getURL fail-closed for URL-bearing407    // senders instead of throwing before policy evaluation.408    const extensionOrigin = sender.url && typeof chrome.runtime.getURL === "function"409      ? chrome.runtime.getURL("")410      : "";411    if (!isMessageSenderAllowed(msg.type, sender, chrome.runtime.id, extensionOrigin)) {412      return { ok: false, error: "invalid_sender" };413    }414415    if (shouldRefreshAutoLock(msg.type, sender) && vault.isUnlocked()) {416      touchAutoLock();417    }418419    switch (msg.type) {420      case "CREATE_VAULT": {421        const { password } = msg.payload as { password: string };422        // Refuse to create a vault under an empty master password — the derived423        // key would be publicly known and the at-rest AES-GCM protection void424        // (audit HIGH; the CSV-import path previously passed ""). Length/strength425        // policy lives in the onboarding UI; this is the non-negotiable floor.426        if (typeof password !== "string" || password.length === 0) {427          return { ok: false, error: "invalid_payload" };428        }429        await vault.createVault(password);430        await setupAutoLock();431        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });432        onVaultUnlocked();433        return { ok: true };434      }435      case "CREATE_VAULT_FROM_ROOT_KEY": {436        const { password, rootKeyHex } = (msg.payload ?? {}) as {437          password?: unknown;438          rootKeyHex?: unknown;439        };440        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {441          return { ok: false, error: "invalid_payload" };442        }443444        try {445          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);446          await setupAutoLock();447          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });448          onVaultUnlocked();449          return { ok: true, vaultId };450        } catch (err) {451          return { ok: false, error: err instanceof Error ? err.message : String(err) };452        }453      }454      case "UNLOCK": {455        const { password } = msg.payload as { password: string };456        const ok = await vault.unlock(password);457        if (ok) {458          // KAT: verify the WebCrypto stack is healthy before the user relies on it.459          // Runs after unlock so latency is hidden behind the vault-load time.460          const kat = await runSelfTest();461          if (!kat.ok) {462            console.error("[Peach] Crypto self-test FAILED:", kat.error);463            await vault.lock();464            return { ok: false, error: "self_test_failed" };465          }466          await vault.updateSettings({ pinPreferred: false });467          await setupAutoLock();468          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });469          onVaultUnlocked();470          return { ok: true };471        }472        // Distinguish corruption from wrong password so the popup can offer473        // a history-restore path instead of falsely accusing the user of474        // mistyping (M7/COR-007).475        const failure = vault.consumeLastUnlockFailureReason();476        if (failure) {477          return {478            ok: false,479            error: "vault_corrupted",480            canRestoreFromHistory: true,481          } as MessageResponse;482        }483        return { ok: false };484      }485      case "UNLOCK_WITH_PIN": {486        const { pin } = (msg.payload ?? {}) as { pin?: unknown };487        if (typeof pin !== "string") return { ok: false, error: "invalid_payload" };488        const ok = await vault.unlockWithPin(pin);489        if (!ok) {490          const status = await vault.getPinUnlockStatus();491          if (status.configured && !status.available) {492            return {493              ok: false,494              error: status.attemptsRemaining === 0495                ? "pin_attempts_exceeded"496                : "pin_session_expired",497            };498          }499          return { ok: false };500        }501        const kat = await runSelfTest();502        if (!kat.ok) {503          await vault.lock();504          return { ok: false, error: "self_test_failed" };505        }506        await vault.updateSettings({ pinPreferred: true });507        await setupAutoLock();508        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });509        onVaultUnlocked();510        return { ok: true };511      }512      case "GET_PIN_STATUS":513        return { ok: true, data: await vault.getPinUnlockStatus() };514      case "VALIDATE_RECOVERY_WORDS": {515        const { words } = msg.payload as { words: string[] };516        const invalid = findInvalidWords(words);517        return { ok: true, data: { valid: invalid.length === 0, invalid } };518      }519      case "GET_RECOVERY_WORDS": {520        // Must be unlocked and have recovery set up (vault must be v2.12+).521        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };522        // LV-4: the recovery words re-derive the ROOT KEY — the highest-523        // value secret in the vault. A session unlock (which may be hours524        // old on a shared machine) is not enough; require a fresh password525        // proof, matching the 1Password/Bitwarden pattern for revealing526        // escrow material. EXEMPTION: the create-vault / rotation confirmation527        // window (peach_recovery_pending) shows the words immediately after528        // the user authenticated, and that confirmation UI has no password to529        // resend — skip the re-auth there only.530        if (!(await isRecoveryConfirmPending())) {531          const { password } = (msg.payload ?? {}) as { password?: string };532          if (typeof password !== "string" || !password) {533            return { ok: false, error: "password_required" };534          }535          if (!(await vault.verifyMainPassword(password))) {536            return { ok: false, error: "wrong_password" };537          }538        }539        try {540          const words = await vault.getRecoveryWords();541          return { ok: true, data: words };542        } catch {543          return { ok: false, error: "recovery_not_setup" };544        }545      }546      case "GET_RECOVERY_CONFIRM_PENDING":547        return { ok: true, data: await isRecoveryConfirmPending() };548      case "SET_RECOVERY_CONFIRM_PENDING":549        await setRecoveryConfirmPending();550        return { ok: true };551      case "CLEAR_RECOVERY_CONFIRM_PENDING":552        await clearRecoveryConfirmPending();553        return { ok: true };554      case "RECOVER_WITH_WORDS": {555        // User has lost their password but has their 12 recovery words.556        // We: (1) validate the words, (2) re-encrypt vault with new password.557        const { words, newPassword } = msg.payload as {558          words: string[];559          newPassword: string;560        };561        const stored = await vault.loadSlotA();562        if (!stored) return { ok: false, error: "no_vault" };563        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {564          return { ok: false, error: "recovery_not_setup" };565        }566        // Unwrap the root key from the recovery escrow.567        try {568          await vault.unwrapRootKeyForRecovery(569            stored.recovery_wrapped_root_key,570            stored.recovery_nonce ?? "",571            stored.recovery_tag ?? "",572            stored.recovery_salt,573            words574          );575        } catch {576          return { ok: false, error: "invalid_recovery_words" };577        }578        // Re-key: derive fresh salt + key from new password.579        const newSalt = vault.generateSalt();580        const newKey = await vault.deriveKey(newPassword, newSalt);581        // Re-wrap root key under the new password's derived key so the same582        // recovery words continue to work after the password change.583        await vault.rewrapRootKeyForPassword(newKey);584        // Re-encrypt vault entries with the new key.585        await vault.changePasswordWithNewKey(newSalt, newKey);586        await setupAutoLock();587        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });588        return { ok: true };589      }590      case "LOCK":591        await vault.lock();592        return { ok: true };593      case "IS_UNLOCKED":594        return { ok: true, data: vault.isUnlocked() };595      case "GET_VAULT_STATUS":596        return { ok: true, unlocked: vault.isUnlocked() };597      case "HAS_VAULT":598        return { ok: true, data: await vault.hasVault() };599      case "GET_ENTRIES":600        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };601        return { ok: true, data: vault.getEntries() };602      case "EXPORT_ENTRIES": {603        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };604        const { password } = (msg.payload ?? {}) as { password?: unknown };605        if (typeof password !== "string" || !password) {606          return { ok: false, error: "password_required" };607        }608        if (!(await vault.verifyMainPassword(password))) {609          return { ok: false, error: "wrong_password" };610        }611        return { ok: true, data: vault.getEntries() };612      }613      case "ADD_ENTRY": {614        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };615        const payload = msg.payload;616        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {617          return { ok: false, error: "invalid_payload" };618        }619        // PB-26-106: a page may only create an entry bound to itself. Entries620        // carrying no url have no domain surface to bind, so they are exempt.621        if (isPageSender(sender)) {622          const draft = payload as { url?: unknown; additionalUrls?: unknown };623          const domains = entryDomains(draft.url, draft.additionalUrls);624          if (domains.size > 0 && !senderMayBindEntryDomains(sender, domains)) {625            return { ok: false, error: "origin_binding_required" };626          }627        }628        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);629        return { ok: true, data: entry };630      }631      case "BATCH_ADD_ENTRIES": {632        const payload = msg.payload as { entries?: unknown } | null | undefined;633        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {634          return { ok: false, error: "invalid_payload" };635        }636        if (!Array.isArray(payload.entries)) {637          return { ok: false, error: "invalid_payload" };638        }639        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);640        return { ok: true, data: added };641      }642      case "RESTORE_ENTRIES": {643        const payload = msg.payload as644          | { entries?: unknown; mode?: unknown; settings?: unknown }645          | null646          | undefined;647        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {648          return { ok: false, error: "invalid_payload" };649        }650        if (!Array.isArray(payload.entries)) {651          return { ok: false, error: "invalid_payload" };652        }653        if (payload.mode !== "replace" && payload.mode !== "merge") {654          return { ok: false, error: "invalid_payload" };655        }656        const summary = await vault.restoreEntries(657          payload.entries as Parameters<typeof vault.restoreEntries>[0],658          payload.mode659        );660        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {661          await vault.updateSettings(payload.settings as vault.VaultSettings);662        }663        return { ok: true, data: summary };664      }665      case "CLEAR_VAULT_ENTRIES": {666        await vault.clearVaultEntries("REPLACE_ALL");667        return { ok: true };668      }669      case "GET_VAULT_HISTORY": {670        const snapshots = await vault.getVaultHistory();671        return { ok: true, data: snapshots };672      }673      case "RESTORE_VAULT_SNAPSHOT": {674        const { snapshotId } = msg.payload as { snapshotId: string };675        const result = await vault.restoreVaultSnapshot(snapshotId);676        if (!result.ok) return { ok: false, error: result.error };677        broadcastToContentScripts({ type: "VAULT_LOCKED" });678        return { ok: true };679      }680      case "COUNT_DUPLICATES": {681        return { ok: true, data: vault.countDuplicates() };682      }683      case "DEDUPLICATE_ENTRIES": {684        const removed = await vault.deduplicateEntries();685        return { ok: true, data: removed };686      }687      case "UPDATE_ENTRY": {688        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;689        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {690          return { ok: false, error: "invalid_payload" };691        }692        const { id, patch } = payload;693        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {694          return { ok: false, error: "invalid_payload" };695        }696        const existingEntry = vault.getEntryById(id);697        if (!existingEntry) return { ok: false, error: "entry_not_found" };698        if (patchChangesEntryOrigin(patch) || isPageSender(sender)) {699          const before = entryDomains(existingEntry.url, existingEntry.additionalUrls);700          const after = patchedUrlShape(patch, existingEntry);701          if (!senderMayMutateEntryDomains(702            sender,703            before,704            entryDomains(after.url, after.additionalUrls),705          )) {706            return { ok: false, error: "origin_binding_required" };707          }708        }709        // Single enforcement point for the Canary Entries Pro gate. Only710        // gates the transition into a canary entry — clearing/disabling a711        // canary (`canary: undefined`) is always allowed, so existing712        // canary entries remain manageable.713        const incomingCanary = (patch as { canary?: unknown }).canary;714        if (incomingCanary && typeof incomingCanary === "object") {715          const existing = vault.getEntryById(id);716          if (!existing?.canary) {717            const gate = await requirePro("canary_entry");718            if (!gate.allowed) return { ok: false, error: "pro_required" };719          }720        }721        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);722        return { ok: true };723      }724      case "ADD_ADDITIONAL_URL": {725        const { id, url } = msg.payload as { id: string; url: string };726        const trimmed = typeof url === "string" ? url.trim() : "";727        if (!trimmed) return { ok: false, error: "url_required" };728        const existing = vault.getEntryById(id);729        if (!existing) return { ok: false, error: "entry_not_found" };730        const merged = [...(existing.additionalUrls ?? []), trimmed];731        if (!senderMayMutateEntryDomains(732          sender,733          entryDomains(existing.url, existing.additionalUrls),734          entryDomains(existing.url, merged),735        )) {736          return { ok: false, error: "origin_binding_required" };737        }738        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };739        await vault.updateEntry(id, { additionalUrls: merged });740        return { ok: true };741      }742      case "REQUEST_REMEMBER_SITE": {743        // PB-26-106: growing an entry's domain set needs a decision the page744        // cannot make for itself, so the page asks and the popup confirms. A745        // page may only ask about its own attested origin — otherwise this746        // becomes the same unbound write under a friendlier name.747        const { id, url } = (msg.payload ?? {}) as { id?: unknown; url?: unknown };748        if (typeof id !== "string" || !id) return { ok: false, error: "invalid_payload" };749        const trimmed = typeof url === "string" ? url.trim() : "";750        if (!trimmed) return { ok: false, error: "url_required" };751        if (!senderMayBindEntryDomains(sender, entryDomains(trimmed, undefined))) {752          return { ok: false, error: "origin_binding_required" };753        }754        if (!vault.getEntryById(id)) return { ok: false, error: "entry_not_found" };755        if (chrome.storage.session) {756          await chrome.storage.session.set({ pendingRememberSite: { entryId: id, url: trimmed } });757        }758        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }759        return { ok: true };760      }761      case "DELETE_ENTRY": {762        const { id } = msg.payload as { id: string };763        await vault.deleteEntry(id);764        return { ok: true };765      }766      case "GET_DELETED_ENTRIES":767        return { ok: true, data: vault.getDeletedEntries() };768      case "RESTORE_ENTRY": {769        const { id } = msg.payload as { id: string };770        await vault.restoreEntry(id);771        return { ok: true };772      }773      case "PURGE_ENTRY": {774        const { id } = msg.payload as { id: string };775        await vault.purgeEntry(id);776        return { ok: true };777      }778      case "PURGE_EXPIRED_TRASH": {779        const { retentionMs } = msg.payload as { retentionMs: number };780        const purged = await vault.purgeExpiredTrash(retentionMs);781        return { ok: true, data: purged };782      }783      case "SAVE_NOTE": {784        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };785        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };786        const now = Date.now();787        if (id) {788          const existing = vault.getEntryById(id);789          if (!existing) return { ok: false, error: "not_found" };790          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });791          return { ok: true, data: vault.getEntryById(id) };792        } else {793          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt794          // (EntryDraft omits both), so passing them was the only reason the795          // `as any` cast existed. Dropping them makes the call type-check.796          const entry = await vault.addEntry({797            type: "note",798            title: title || "Untitled",799            notes: body,800          });801          return { ok: true, data: entry };802        }803      }804      case "DELETE_NOTE": {805        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };806        const { id } = msg.payload as { id: string };807        await vault.deleteEntry(id);808        return { ok: true };809      }810      case "GET_NOTES": {811        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };812        const notes = vault.getEntries().filter(813          (e) => e.type === "note" && !e.deletedAt814        );815        return { ok: true, data: notes } as MessageResponse;816      }817      case "SEARCH_VAULT": {818        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };819        // AUD-002: shape-validate the payload before calling string methods.820        // A raw cast lets a malformed message crash the handler with TypeError.821        const { query } = (msg.payload ?? {}) as { query?: unknown };822        if (typeof query !== "string") {823          return { ok: false, error: "invalid_payload" };824        }825        const q = query.toLowerCase();826        const searchResults = vault.getEntries().filter(827          (e) =>828            !e.deletedAt &&829            (e.title.toLowerCase().includes(q) ||830              e.notes?.toLowerCase().includes(q) ||831              e.username?.toLowerCase().includes(q))832        );833        return { ok: true, data: searchResults } as MessageResponse;834      }835      case "AUTOFILL_QUERY": {836        if (!vault.isUnlocked()) {837          return { ok: false, error: "vault_locked" };838        }839        const { domain, kind, capability } = msg.payload as {840          domain: string;841          kind?: "login" | "card" | "totp";842          capability?: string;843        };844        const includeAll = consumeSummonCapability(capability, sender, "inventory");845        if (capability !== undefined && !includeAll) {846          return { ok: false, error: "entry_not_found" };847        }848        // kind="card": return saved cards as compact summaries for the849        // inline card silver platter. Cards are not domain-scoped — every850        // saved card is a candidate on every checkout page — so domain is851        // ignored when kind === "card".852        if (kind === "card") {853          if (!includeAll) return { ok: true, data: [] };854          const cards = vault.getEntries().filter((e) => e.type === "card");855          return {856            ok: true,857            data: cards.map((e) => ({858              id: e.id,859              title: e.cardNickname || e.title,860              cardholderName: e.cardholderName,861              last4: e.last4,862              expMonth: e.expMonth,863              expYear: e.expYear,864              network: e.network,865            })),866          };867        }868        const scopedDomain = isPageSender(sender)869          ? attestedSenderDomain(sender)870          : typeof domain === "string"871            ? extractDomain(domain)872            : null;873        if (!includeAll && !scopedDomain) {874          return isPageSender(sender)875            ? { ok: false, error: "origin_unverified" }876            : { ok: true, data: [] };877        }878        if (kind === "totp") {879          const matches = (880            includeAll881              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")882              : vault.queryDomain(scopedDomain!)883          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));884          return {885            ok: true,886            data: matches.map((e) => ({887              id: e.id,888              title: e.title,889              username: e.username,890              email: e.email,891              url: e.url,892              hasTotp: true,893            })),894          };895        }896        // The inline selector fills username+password into a form. Passkey-897        // only entries have no password to fill; sign-in for those goes898        // through the WebAuthn path instead. Filter them out everywhere so899        // the user doesn't see four "GitHub" rows that mostly do nothing.900        // Notes and cards never belonged here either.901        const matches = (902          includeAll903            ? vault904                .getEntries()905                .filter((entry) => entry.type !== "note" && entry.type !== "card")906            : vault.queryDomain(scopedDomain!)907        ).filter((entry) => !isPasskeyOnly(entry));908        return {909          ok: true,910          data: matches.map((e) =>911            includeAll912              ? {913                  id: e.id,914                  title: e.title,915                  // username/email/url shipped so the inline popup's search916                  // affordance can match on them, not just titles. No secrets917                  // cross the boundary — same shape as the domain-matched918                  // response below minus hasTotp (which the search list919                  // doesn't surface).920                  username: e.username,921                  email: e.email,922                  url: e.url,923                  hasPasskey: e.passkey !== undefined,924                }925              : {926                  id: e.id,927                  title: e.title,928                  username: e.username,929                  email: e.email,930                  url: e.url,931                  hasTotp: Boolean(e.totp),932                  hasPasskey: e.passkey !== undefined,933                }934          ),935        };936      }937      case "GET_ENTRY_FOR_FILL": {938        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };939        const { id, capability } = msg.payload as {940          id: string;941          capability?: string;942        };943        const capabilityAuthorized = capability !== undefined && consumeSummonCapability(capability, sender, "fill");944        const senderDomain = isPageSender(sender) ? attestedSenderDomain(sender) : null;945        if (isPageSender(sender) && !senderDomain) {946          return { ok: false, error: "origin_unverified" };947        }948        const entry = vault.getEntryById(id);949        if (!entry) return { ok: false, error: "entry_not_found" };950951        // MV-1: re-validate the entry against the requesting frame's origin.952        // sender.url / sender.tab.url are browser-attested — a page cannot953        // forge them. PB-26-005: the FRAME url (sender.url) is authoritative954        // for an all_frames content script; the top-frame tab.url would955        // misattribute a cross-origin iframe's request to the top page. When956        // the request does not come from a tab at all (popup surfaces use957        // GET_ENTRY_FOR_EDIT, not this), refuse.958        if (senderDomain && !capabilityAuthorized) {959          if (!entryDomains(entry.url, entry.additionalUrls).has(senderDomain)) {960            // Domain mismatch — refuse silently (no oracle about which ids exist).961            return { ok: false, error: "entry_not_found" };962          }963        }964        // Passkey-only entries (passkey credential, no password) cannot be965        // filled into a form — sign-in goes through the WebAuthn path. A966        // login that ALSO has a passkey is still fillable for its password.967        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };968        // Strip the passkey credential AND the raw base32 TOTP seed from the969        // response. Content scripts never need either: the private key is the970        // authenticator's, and handing over the TOTP seed would let a971        // compromised content script mint valid codes indefinitely (SEV-3-C).972        // Generate the *current* 6-digit code here in the background and send973        // only that, plus the seconds left so the UI can render a countdown.974        // Also drop passwordHistory: filling needs only the *current* password.975        // Handing every past password to a content script during passive976        // autofill on an arbitrary page would widen the blast radius of a977        // compromised page far beyond the one credential being filled.978        const {979          passkey: _strippedPasskey,980          totp: seed,981          totpAlgorithm,982          totpDigits,983          totpPeriod,984          passwordHistory: _ph,985          ...safeEntry986        } = entry;987        let totpCode: string | undefined;988        let totpRemaining: number | undefined;989        if (seed) {990          try {991            // PCH-01-019: honour stored algorithm/digits/period (defaults apply992            // when these are undefined, i.e. RFC-default bare-seed entries).993            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);994            totpCode = generated.code;995            totpRemaining = generated.remaining;996          } catch {997            totpCode = undefined;998          }999        }1000        if (isPageSender(sender) && vault.isUnlocked()) touchAutoLock();1001        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };1002      }1003      // Trusted full-entry fetch for extension-owned edit surfaces. Content1004      // scripts route editing to the popup and cannot call this message.1005      case "GET_ENTRY_FOR_EDIT": {1006        if (isPageSender(sender)) return { ok: false, error: "invalid_sender" };1007        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1008        const { id } = msg.payload as { id: string };1009        const entry = vault.getEntryById(id);1010        if (!entry) return { ok: false, error: "entry_not_found" };10111012        const { passkey: _passkey, ...safeEntry } = entry;1013        return { ok: true, data: safeEntry };1014      }1015      case "COPY": {1016        // AUD-002: shape-validate the payload before passing to the clipboard1017        // helper. A raw cast lets a malformed message reach the clipboard API1018        // with a non-string and throw.1019        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {1020          text?: unknown;1021          label?: unknown;1022          alreadyWritten?: unknown;1023        };1024        if (typeof text !== "string" || typeof label !== "string") {1025          return { ok: false, error: "invalid_payload" };1026        }1027        await copyToClipboard(text, label, Boolean(alreadyWritten));1028        return { ok: true, clearSeconds: getEffectiveClearSeconds() };1029      }1030      case "CHECK_ALL_BREACHES": {1031        const allEntries = vault.getEntries();1032        const results: Record<string, number> = {};1033        for (const entry of allEntries) {1034          if (entry.type === "note") continue;1035          if (!entry.password) continue;1036          results[entry.id] = await vault.checkBreach(entry.password);1037          // Small delay — be a good citizen to the HIBP API1038          await new Promise((r) => setTimeout(r, 200));1039        }1040        // Persist any non-zero counts back to entries1041        for (const [id, count] of Object.entries(results)) {1042          const entry = vault.getEntryById(id);1043          if (entry && (entry.breach ?? 0) !== count) {1044            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });1045          }1046        }1047        return { ok: true, data: results };1048      }1049      case "GET_SETTINGS": {1050        const settings = await vault.ensureSettingsLoaded();1051        if (!isPageSender(sender)) return { ok: true, data: settings };10521053        const safeSettings: Pick<vault.VaultSettings, "accentColor" | "theme"> & {1054          manualSummonDomains?: NonNullable<vault.VaultSettings["manualSummonDomains"]>;1055        } = {1056          accentColor: settings.accentColor,1057          theme: settings.theme,1058        };1059        const domain = attestedSenderDomain(sender);1060        const ownSummon = domain ? settings.manualSummonDomains?.[domain] : undefined;1061        if (domain && ownSummon) safeSettings.manualSummonDomains = { [domain]: ownSummon };1062        return { ok: true, data: safeSettings };1063      }1064      case "UPDATE_SETTINGS": {1065        const patch = msg.payload;1066        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {1067          return { ok: false, error: "invalid_payload" };1068        }1069        await vault.updateSettings(patch as vault.VaultSettings);1070        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {1071          await setupAutoLock();1072          if (vault.isUnlocked()) touchAutoLock();1073        }1074        return { ok: true };1075      }1076      case "SETUP_PIN": {1077        const { currentPassword, pin } = (msg.payload ?? {}) as {1078          currentPassword?: unknown;1079          pin?: unknown;1080        };1081        if (typeof currentPassword !== "string" || typeof pin !== "string") {1082          return { ok: false, error: "invalid_payload" };1083        }1084        return (await vault.setupPinUnlock(currentPassword, pin))1085          ? { ok: true }1086          : { ok: false, error: "incorrect_current_password" };1087      }1088      case "DISABLE_PIN": {1089        const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown };1090        if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" };1091        return (await vault.disablePinUnlock(currentPassword))1092          ? { ok: true }1093          : { ok: false, error: "incorrect_current_password" };1094      }1095      case "GET_PENDING_PASSKEY":1096        return { ok: true, data: await getPendingPasskeyRequest() };1097      case "APPROVE_PASSKEY": {1098        const { requestId } = msg.payload as { requestId: number };1099        await resolvePendingPasskeyRequest(requestId, true);1100        return { ok: true };1101      }1102      case "DENY_PASSKEY": {1103        const { requestId } = msg.payload as { requestId: number };1104        await resolvePendingPasskeyRequest(requestId, false);1105        return { ok: true };1106      }1107      case "GET_PASSKEY_PROVIDER_STATE":1108        return { ok: true, data: await getPasskeyProviderState() };1109      case "SET_PASSKEY_PROVIDER_ENABLED": {1110        const { enabled } = msg.payload as { enabled: boolean };1111        // Disabling is always free; gating fires only when a free user is1112        // trying to turn passkey interception on.1113        if (enabled) {1114          const gate = await requirePro("passkeys");1115          if (!gate.allowed) return { ok: false, error: "pro_required" };1116        }1117        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };1118      }1119      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS1120      // endpoint. Intentional product behavior — users configure their own1121      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private1122      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-1123      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to1124      // users that the entry title leaves the device when the canary fires.1125      case "FIRE_CANARY_PING": {1126        // Canary alert fires unconditionally for any entry with canary: true.1127        // The Pro gate only governs creation/flagging of canary entries; once1128        // an entry is flagged, the alert path is a security property and must1129        // never be license-gated.1130        const { webhookUrl, entryTitle, trigger } = msg.payload as {1131          webhookUrl: string;1132          entryTitle: string;1133          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";1134        };1135        if (trigger === "test" && !isExtensionPageSender(sender)) {1136          return { ok: false, error: "invalid_sender" };1137        }1138        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {1139          return { ok: false, error: "invalid_webhook_url" };1140        }1141        // LV-3: debounce non-test pings per (webhook, entry) so a page that1142        // strobes focus/fill events can't turn the canary into a request1143        // firehose at the user's endpoint. Test pings are exempt — they are1144        // explicit user clicks in the settings UI and are awaited for1145        // feedback. The FIRST ping in a window always goes out, so the1146        // dead-man's-switch property (canary fires on access) is preserved;1147        // only repeats within the window are coalesced.1148        if (trigger !== "test") {1149          const keyDigest = new Uint8Array(1150            await crypto.subtle.digest(1151              "SHA-256",1152              new TextEncoder().encode(`${webhookUrl}:${entryTitle}`),1153            ),1154          );1155          const keySuffix = Array.from(keyDigest)1156            .map((byte) => byte.toString(16).padStart(2, "0"))1157            .join("");1158          const rlKey = `canary-last-fetch:${keySuffix}`;1159          const legacyRlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;1160          const stored = await chrome.storage.local.get(rlKey);1161          await chrome.storage.local.remove(legacyRlKey);1162          const last = (stored as Record<string, unknown>)[rlKey];1163          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {1164            return { ok: true, data: { rateLimited: true } };1165          }1166          await chrome.storage.local.set({ [rlKey]: Date.now() });1167        }1168        const body = JSON.stringify({1169          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",1170          entry: entryTitle,1171          trigger,1172          timestamp: new Date().toISOString(),1173          source: "peach-extension",1174        });1175        if (trigger === "test") {1176          // Permitted outbound fetch: user-configured canary alert endpoint1177          // (validated by isAllowedCanaryWebhookUrl above). This is the1178          // only non-HIBP outbound call in the extension — see1179          // Projects.md §3.7. Test pings are awaited so the UI can show1180          // success/failure.1181          try {1182            const res = await fetch(webhookUrl, {1183              method: "POST",1184              headers: { "Content-Type": "application/json" },1185              body,1186            });1187            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1188          } catch (err) {1189            return { ok: false, error: err instanceof Error ? err.message : "network_error" };1190          }1191        }1192        // Non-test triggers are fire-and-forget1193        fetch(webhookUrl, {1194          method: "POST",1195          headers: { "Content-Type": "application/json" },1196          body,1197        }).catch(() => {});1198        return { ok: true };1199      }1200      case "ACTIVATE_LICENSE": {1201        const { key } = msg.payload as { key: string };1202        const licenseInfo = await activateLicense(key);1203        return { ok: true, data: licenseInfo };1204      }1205      case "GET_LICENSE": {1206        const licenseInfo = await getLicenseInfo();1207        return { ok: true, data: licenseInfo };1208      }1209      case "GET_LICENSE_KEY": {1210        const key = await getLicenseKey();1211        return { ok: true, data: key };1212      }1213      case "DEACTIVATE_LICENSE": {1214        await deactivateLicense();1215        return { ok: true };1216      }1217      case "SHOULD_PLAY_CELEBRATION": {1218        const should = await shouldPlayCelebration();1219        return { ok: true, data: should };1220      }1221      case "MARK_CELEBRATION_PLAYED": {1222        await markCelebrationPlayed();1223        return { ok: true };1224      }1225      case "GET_CODEX_VAULT_DATA": {1226        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1227        // popup navigates to the License section without further coordination.1228        // Also privileged-page-gated (PB-26-001), and recoveryWords inside the1229        // snapshot additionally require a fresh master-password proof.1230        const gate = await requirePro("codex");1231        if (!gate.allowed) return { ok: false, error: "pro_required" };1232        const { password } = (msg.payload ?? {}) as { password?: string };1233        return await handleGetCodexVaultData(password);1234      }1235      case "ESTIMATE_CODEX_PAGES": {1236        const gate = await requirePro("codex");1237        if (!gate.allowed) return { ok: false, error: "pro_required" };1238        return await handleEstimateCodexPages();1239      }1240      case "RESTORE_FROM_CODEX": {1241        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1242        // be able to restore a vault that was printed by a Pro user.1243        // DO NOT add a Pro gate here.1244        const payload = msg.payload as CodexRestorePayload;1245        return await handleRestoreFromCodex(payload);1246      }1247      case "OPEN_PRO_GATE": {1248        // Content script requests: open popup and navigate to License section.1249        const { feature } = (msg.payload ?? {}) as { feature?: string };1250        if (chrome.storage.session) {1251          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1252        }1253        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1254        return { ok: true };1255      }1256      case "OPEN_POPUP": {1257        // Content script asks to open the trusted extension popup — used by the1258        // inline locked bubble so the master password is entered in the popup,1259        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1260        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1261        // toolbar icon. The badge already signals Peach needs attention.1262        //1263        // Set a session flag so the popup knows it was opened for inline unlock1264        // and should close itself once the vault is unlocked (returning the user1265        // to the inline autofill selector on the page).1266        const { entryId } = (msg.payload ?? {}) as { entryId?: unknown };1267        if (entryId !== undefined && (typeof entryId !== "string" || entryId.length === 0 || entryId.length > 64)) {1268          return { ok: false, error: "invalid_payload" };1269        }1270        if (chrome.storage.session) {1271          if (typeof entryId === "string") {1272            await chrome.storage.session.set({ peach_open_entry: entryId });1273          } else {1274            await chrome.storage.session.set({ peach_inline_unlock: true });1275          }1276        }1277        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1278        return { ok: true };1279      }1280      case "OPEN_DETACHED_POPUP": {1281        // A window created by the action popup and then orphaned with1282        // window.close() is cascaded shut by Chrome, so the file-picker1283        // flows (OS dialogs that dismiss the popup on focus loss) ask the SW1284        // to open the standalone window instead — the SW has no window to be1285        // associated with. The query string is allowlisted so this can never1286        // open an arbitrary URL.1287        const { route } = (msg.payload ?? {}) as { route?: string };1288        const search = route === "peachscript"1289          ? "?restore=peachscript"1290          : route === "csv"1291            ? "?restore=csv"1292            : route === "codex-pdf"1293              ? "?codex=pdf"1294              : null;1295        if (!search) return { ok: false, error: "bad_route" };1296        try {1297          const popupHtml =1298            chrome.runtime.getManifest().action?.default_popup ?? "src/popup/index.html";1299          await chrome.windows.create({1300            url: chrome.runtime.getURL(`${popupHtml}${search}`),1301            type: "popup",1302            width: 320,1303            height: 550,1304          });1305          return { ok: true, data: { detached: true } };1306        } catch {1307          return { ok: false };1308        }1309      }1310      case "GET_IDENTITIES": {1311        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1312        return { ok: true, data: vault.getIdentities() };1313      }1314      case "TOUCH_AUTO_LOCK": {1315        // touchAutoLock() is already called by shouldRefreshAutoLock above;1316        // this case just gives the popup a typed message to keep the session alive.1317        return { ok: true };1318      }1319      case "GET_ADVANCED_HEALTH_REPORT": {1320        const gate = await requirePro("advanced_health");1321        if (!gate.allowed) return { ok: false, error: "pro_required" };1322        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1323        const report = await buildAdvancedHealthReport(vault.getEntries());1324        return { ok: true, data: report };1325      }1326      case "IS_DURESS_ENABLED": {1327        const enabled = await vault.isDuressEnabled();1328        return { ok: true, data: enabled };1329      }1330      case "SETUP_DURESS": {1331        // Single enforcement point for the Duress Vault Pro gate. Free users1332        // who somehow reach this handler are rejected here; the popup also1333        // pre-checks isPro() to avoid showing the setup form to free users,1334        // but server-side is the actual security boundary.1335        const gate = await requirePro("duress_vault");1336        if (!gate.allowed) return { ok: false, error: "pro_required" };1337        // MV3 service workers restart after inactivity, losing the in-memory1338        // derived key. Detect this before calling setupDuress so the popup1339        // can show a meaningful prompt to re-lock and re-unlock.1340        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1341        const { duressPassword } = msg.payload as { duressPassword: string };1342        await vault.setupDuress(duressPassword);1343        return { ok: true };1344      }1345      case "DISABLE_DURESS": {1346        await vault.disableDuress();1347        return { ok: true };1348      }1349      case "VERIFY_MAIN_PASSWORD": {1350        const { password } = msg.payload as { password: string };1351        const ok = await vault.verifyMainPassword(password);1352        return { ok: true, data: ok };1353      }1354      case "CHANGE_PASSWORD": {1355        const { currentPassword, newPassword } = msg.payload as {1356          currentPassword: string;1357          newPassword: string;1358        };1359        const changed = await vault.changePassword(currentPassword, newPassword);1360        return changed1361          ? { ok: true }1362          : { ok: false, error: "incorrect_current_password" };1363      }1364      case "GET_SITE_PASSWORD_POLICY": {1365        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1366        if (!tab?.id) return { ok: true, data: null };1367        try {1368          const response = await chrome.tabs.sendMessage(tab.id, {1369            type: "GET_SITE_PASSWORD_POLICY",1370          });1371          return (response as MessageResponse) ?? { ok: true, data: null };1372        } catch {1373          return { ok: true, data: null };1374        }1375      }1376      case "RECORD_MANUAL_SUMMON": {1377        const { domain } = (msg.payload ?? {}) as { domain?: unknown };1378        const origin = attestedSenderOrigin(sender);1379        let senderDomain: string | null = null;1380        if (origin) {1381          try {1382            const hostname = new URL(origin).hostname;1383            senderDomain = extractDomain(hostname) ?? hostname;1384          } catch {1385            senderDomain = null;1386          }1387        }1388        if (typeof domain !== "string" || domain.length > 253 || domain !== senderDomain) {1389          return { ok: false, error: "invalid_domain" };1390        }1391        const settings = vault.getSettings();1392        const existing = settings.manualSummonDomains?.[domain];1393        const now = Date.now();1394        await vault.updateSettings({1395          manualSummonDomains: {1396            ...settings.manualSummonDomains,1397            [domain]: {1398              firstSummonedAt: existing?.firstSummonedAt ?? now,1399              summonCount: (existing?.summonCount ?? 0) + 1,1400              lastSummonedAt: now,1401            },1402          },1403        });1404        return { ok: true };1405      }1406      case "DECLINE_CARD_SAVE": {1407        // PB-26-108: the declined-card digest is keyed by root-key material, so1408        // a decline cannot be recorded while locked. Offers are not shown while1409        // locked either, so this is unreachable in practice.1410        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1411        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1412        await vault.declineCardSaveOffer(last4, expMonth, expYear);1413        return { ok: true };1414      }1415      case "IS_CARD_DECLINED": {1416        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1417        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1418        return { ok: true, data: declined };1419      }1420      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1421        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1422          rpId?: string;1423          rpName?: string;1424          userName?: string;1425          userDisplayName?: string;1426        };1427        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1428        return await initiateFirefoxPasskeyCreate({1429          rpId,1430          rpName: rpName ?? rpId,1431          userName,1432          userDisplayName,1433        }, attestedSenderOrigin(sender));1434      }14351436      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1437        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1438        if (!payload) return { ok: false, error: "missing_payload" };1439        return await completeFirefoxPasskeyCreate(payload);1440      }14411442      case "PASSKEY_OFFER_DECLINE": {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        await recordPasskeyOfferDecline(domain);1447        return { ok: true };1448      }14491450      case "GET_PASSKEY_OFFER_DECLINED": {1451        const { domain } = (msg.payload ?? {}) as { domain?: string };1452        const origin = attestedSenderOrigin(sender);1453        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1454        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1455      }14561457      case "PASSKEY_HAS_CREDENTIALS": {1458        const payload = msg.payload as {1459          rpId?: string;1460          allowCredentials?: Array<{ id: string; type?: string }>;1461        } | undefined;1462        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1463        return await handlePasskeyHasCredentials({1464          rpId: payload.rpId,1465          allowCredentials: payload.allowCredentials ?? [],1466        }, attestedSenderOrigin(sender));1467      }14681469      case "PASSKEY_CREATE": {1470        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1471        if (!payload?.rpId || !payload?.userName) {1472          return { ok: false, error: "rpid_and_username_required" };1473        }1474        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1475      }14761477      case "PASSKEY_GET": {1478        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1479        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1480        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1481      }14821483      case "PASSKEY_AUTH_RESPONSE": {1484        const { requestId, approved } = (msg.payload ?? {}) as {1485          requestId?: string | number;1486          approved?: boolean;1487        };1488        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1489          return { ok: false, error: 'requestId and approved required' };1490        }1491        const pending = await getPendingPasskeyRequest();1492        const senderOrigin = attestedSenderOrigin(sender);1493        if (1494          (pending && pending.requestId !== Number(requestId)) ||1495          (pending?.tabId !== undefined && sender.tab?.id !== pending.tabId) ||1496          (pending?.origin !== undefined && senderOrigin !== pending.origin)1497        ) {1498          return { ok: false, error: "invalid_passkey_approval_sender" };1499        }1500        await resolvePendingPasskeyRequest(Number(requestId), approved);1501        return { ok: true };1502      }15031504      case "GET_PASSKEY_FOR_DOMAIN": {1505        const { domain } = (msg.payload ?? {}) as { domain?: string };1506        if (!domain) return { ok: false, error: "domain_required" };1507        // Scope to the caller's own origin: a page may only ask about passkeys1508        // for a domain it actually owns, so an arbitrary page cannot enumerate1509        // which sites the user holds passkeys for or read the username (audit MEDIUM).1510        const origin = attestedSenderOrigin(sender);1511        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1512        if (!vault.isUnlocked()) return { ok: true, data: null };1513        const match = vault1514          .getEntries()1515          .find((entry) => entry.passkey?.rpId === domain);1516        if (!match || !match.passkey) return { ok: true, data: null };1517        // Slim shape — only the fields State 11 needs. Never expose private1518        // key material, even though this is locked behind isUnlocked.1519        // bannerShown is the per-domain "already surfaced" flag, kept in1520        // trusted background session storage so content scripts never touch1521        // chrome.storage.session directly (PB-26-203).1522        let bannerShown = false;1523        if (chrome.storage.session) {1524          const flag = await chrome.storage.session.get(`peach_state11_shown:${domain}`);1525          bannerShown = Boolean((flag as Record<string, unknown>)[`peach_state11_shown:${domain}`]);1526        }1527        return {1528          ok: true,1529          data: {1530            rpId: match.passkey.rpId,1531            userName: match.passkey.userName,1532            browser: match.passkey.browser,1533            bannerShown,1534          },1535        };1536      }15371538      case "MARK_PASSKEY_BANNER_SHOWN": {1539        const { domain } = (msg.payload ?? {}) as { domain?: string };1540        if (typeof domain !== "string" || !domain) return { ok: false, error: "domain_required" };1541        // Same origin binding as the read path: a page may only mark its own1542        // domain, and the flag reveals nothing either way.1543        const origin = attestedSenderOrigin(sender);1544        if (!origin || !isValidRpId(domain, origin)) return { ok: true };1545        if (chrome.storage.session) {1546          await chrome.storage.session.set({ [`peach_state11_shown:${domain}`]: Date.now() });1547        }1548        return { ok: true };1549      }15501551      case "DESTROY_VAULT": {1552        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1553        // storage.local.clear() wipes every Peach key (slots, settings, license,1554        // onboarded flag, history, sync state, declined cards, recall, etc.);1555        // session.clear() wipes pending passkey requests + pro-notice queues.1556        // Caller (Panic.tsx) handles UI navigation back to onboarding.1557        //1558        // The Pro license is the one thing that must survive: the user paid for1559        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1560        // Capture it before the clear and restore it after. peach_pro_celebrated1561        // rides along so the Pro celebration doesn't replay on the next unlock.1562        const preserved = await chrome.storage.local.get([1563          "peach_license",1564          "peach_pro_celebrated",1565        ]);1566        await vault.lock();1567        await storageClear();1568        await vault.clearVaultHistory();1569        const toRestore: Record<string, unknown> = {};1570        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1571        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1572        if (Object.keys(toRestore).length > 0) {1573          await chrome.storage.local.set(toRestore);1574        }1575        if (chrome.storage.session) {1576          await chrome.storage.session.clear();1577        }1578        await clearRecoveryConfirmPending();1579        return { ok: true };1580      }15811582      case "GET_IDENTITY_SUGGESTIONS": {1583        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1584        const entries = vault.getEntries();1585        const suggestions = buildIdentitySuggestions(entries);1586        return { ok: true, data: { suggestions } };1587      }1588      case "ML_INIT":1589        return { ok: true };15901591      case "ML_PREDICT_BATCH": {1592        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1593        if (!isValidMLFeatureBatch(featuresArray, MAX_ML_BATCH_FIELDS)) {1594          return { ok: false, error: "invalid_payload" };1595        }1596        if (!claimMLWork(sender, featuresArray.length)) {1597          return { ok: false, error: "rate_limited" };1598        }1599        return { ok: true, data: mlPredictBatch(featuresArray) };1600      }16011602      // ── Vault sync (v3) ───────────────────────────────────────────────1603      // Returns the public-facing local identity needed by the popup to1604      // drive Phase-1 audio pairing. The private long-term key never1605      // leaves the background.1606      case "GET_LOCAL_IDENTITY": {1607        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1608        // Pro license from an already-Pro peer (at least one device must be Pro).1609        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1610        // The identity is sealed under its own key rather than derived from the1611        // root, so pairing survives a master-password change (SEV-2-B).1612        const identity: LocalDeviceIdentity & { license?: string } = await buildLocalIdentity();1613        // If this device is Pro, advertise the signed license so the peer can1614        // activate it after SAS confirmation — pairing carries Pro across.1615        if (await isProUser()) {1616          const license = await getLicenseKey();1617          if (license) identity.license = license;1618        }1619        return { ok: true, data: identity };1620      }16211622      case "LIST_PAIRED_DEVICES": {1623        if (vault.isDecoyMode()) return { ok: true, data: { devices: [] } };1624        try {1625          const devices = await listPairedDevicesV3();1626          return { ok: true, data: { devices } };1627        } catch (err) {1628          if (err instanceof TrustDataCorruptedError) {1629            return { ok: false, error: "trust_data_corrupted" };1630          }1631          throw err;1632        }1633      }16341635      case "RENAME_PAIRED_DEVICE": {1636        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1637        const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string };1638        if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") {1639          return { ok: false, error: "invalid_payload" };1640        }1641        await renamePairedDeviceV3(deviceId, name);1642        return { ok: true };1643      }16441645      case "UNPAIR_DEVICE": {1646        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1647        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1648        if (typeof deviceId !== "string" || !deviceId) {1649          return { ok: false, error: "invalid_payload" };1650        }1651        // Removing a device REVOKES it rather than just dropping the local1652        // row: a plain removal is undone the moment any other peer vouches it1653        // back through a manifest, which is exactly what the relay makes easy.1654        await revokeDeviceByIdV3(deviceId, await getOrCreateDeviceId());1655        // PB-26-213: forget the secret now so no further dial can use it.1656        // Removals that happen while locked leave orphans for the next1657        // unlock's reconcile to prune.1658        const unpairRootHex = vault.getRootKeyHex();1659        if (unpairRootHex) {1660          const unpairRoot = unhexBytes(unpairRootHex);1661          try {1662            await dropPairSecret(deviceId, unpairRoot);1663          } finally {1664            unpairRoot.fill(0);1665          }1666        } else {1667          await dropPairSecret(deviceId, null);1668        }1669        // Sync against the remaining hosts — the unpaired device no longer1670        // matters but the next alarm tick is up to ten minutes away.1671        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1672        return { ok: true };1673      }16741675      case "RENAME_LOCAL_DEVICE": {1676        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1677        const { name } = (msg.payload ?? {}) as { name?: string };1678        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1679        await setDeviceNameV3(name);1680        return { ok: true };1681      }16821683      // ── Relay pairing ─────────────────────────────────────────────────────1684      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1685      // session runs in the background; the SAS and the terminal result reach1686      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1687      case "START_ADOPTION_SOURCE": {1688        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1689        if (isRelayAdoptionSourceInFlight()) {1690          return { ok: false, error: "adoption_source_in_progress" };1691        }1692        try {1693          return { ok: true, data: await startRelayAdoptionSource() };1694        } catch (error) {1695          return {1696            ok: false,1697            error: error instanceof Error ? error.message : "adoption_source_failed",1698          };1699        }1700      }17011702      // Onboarding receiver — empty extension shows a QR, phone scans and1703      // sends the vault. The popup supplies the local-only password here so1704      // the background can wrap the adopted root key at rest without ever1705      // asking the user to retype it.1706      case "START_ADOPTION_RECEIVER": {1707        if (isRelayAdoptionSourceInFlight()) {1708          return { ok: false, error: "adoption_receiver_in_progress" };1709        }1710        const password = (msg.payload as { password?: unknown } | undefined)?.password;1711        if (typeof password !== "string" || password.length === 0) {1712          return { ok: false, error: "invalid_payload" };1713        }1714        try {1715          return { ok: true, data: await startRelayAdoptionReceiver(password) };1716        } catch (error) {1717          return {1718            ok: false,1719            error: error instanceof Error ? error.message : "adoption_receiver_failed",1720          };1721        }1722      }17231724      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1725      // on the source's SAS screen. The id round-trips the same way so a stale1726      // late response can't approve the wrong session.1727      case "RECEIVER_SAS_DECISION": {1728        const payload = msg.payload as { id?: unknown; sas?: unknown; ok?: unknown } | undefined;1729        if (typeof payload?.id !== "string" || typeof payload.sas !== "string" || typeof payload.ok !== "boolean") {1730          return { ok: false, error: "invalid_payload" };1731        }1732        return { ok: resolveReceiverSasConfirmation(payload.id, payload.sas, payload.ok) };1733      }17341735      case "SOURCE_SAS_DECISION": {1736        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1737        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1738          return { ok: false, error: "invalid_payload" };1739        }1740        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1741      }1742      case "LIST_PENDING_ADOPTION_HOLDERS": {1743        return { ok: true, data: await listPendingAdoptionHolders() };1744      }17451746      case "REMOVE_PENDING_ADOPTION_HOLDER": {1747        await removePendingAdoptionHolder();1748        return { ok: true };1749      }175017511752      case "CANCEL_ADOPTION_SOURCE": {1753        cancelRelayAdoptionSource();1754        return { ok: true };1755      }17561757      case "TRIGGER_SYNC": {1758        if (vault.isDecoyMode()) return { ok: true };1759        const payload = (msg.payload ?? {}) as {1760          reason?: "vault_change" | "foreground" | "manual";1761          force?: boolean;1762        };1763        const reason = payload.reason ?? "foreground";17641765        void triggerSyncIfReachable({ reason, force: payload.force === true });1766        return { ok: true };1767      }17681769      case "GET_SYNC_STATE": {1770        if (vault.isDecoyMode()) return { ok: true, data: { status: "idle" } };1771        return { ok: true, data: getSyncState() };1772      }17731774      // §11. The generation state carries no secret — it is a version and a1775      // state name — so the panel can read it while the vault is locked.1776      case "GET_SYNC_GENERATION": {1777        return { ok: true, data: await resolveGeneration(browserGenerationIo) };1778      }17791780      case "SECURE_RESET": {1781        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1782        const payload = (msg.payload ?? {}) as { password?: unknown };1783        if (typeof payload.password !== "string" || payload.password.length === 0) {1784          return { ok: false, error: "Enter your master password" };1785        }1786        if (!(await vault.verifyMainPassword(payload.password))) {1787          return { ok: false, error: "Incorrect master password" };1788        }1789        // Enter the blocking state first: a crash between these two calls then1790        // leaves the device refusing sync rather than mid-reset over live1791        // trust. Both are idempotent, so a retry is safe.1792        await enterResetRequired(browserGenerationIo);1793        const result = await confirmSecureReset(browserGenerationIo, {1794          nowMs: Date.now(),1795        });1796        return result === "V2_ANCHOR"1797          ? { ok: true, data: await resolveGeneration(browserGenerationIo) }1798          : {1799              ok: false,1800              error: "The reset did not complete — nothing was lost, try again",1801            };1802      }18031804      case "GET_SYNC_SETTINGS": {1805        if (vault.isDecoyMode()) return { ok: true, data: { mode: "off", relayUrl: "" } };1806        return { ok: true, data: await getSyncSettings() };1807      }18081809      case "SET_SYNC_SETTINGS": {1810        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1811        const payload = (msg.payload ?? {}) as {1812          mode?: unknown;1813          relayUrl?: unknown;1814        };1815        try {1816          // A custom relay URL implies private mode; Peach's own relay stays1817          // public. See setRelayUrl.1818          if (payload.relayUrl !== undefined) {1819            if (typeof payload.relayUrl !== "string") {1820              return { ok: false, error: "invalid_relay_url" };1821            }1822            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1823          }1824          if (payload.mode !== undefined) {1825            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1826              return { ok: false, error: "invalid_sync_mode" };1827            }1828            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1829          }1830          return { ok: true, data: await getSyncSettings() };1831        } catch (error) {1832          return {1833            ok: false,1834            error: error instanceof Error ? error.message : "invalid_relay_url",1835          };1836        }1837      }183818391840      case "GET_SYNC_ALERTS": {1841        if (vault.isDecoyMode()) return { ok: true, data: [] };1842        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1843        const alerts = await getPendingSyncAlerts();1844        // The popup reads on open and acknowledges with consume:true after1845        // rendering, so a popup crash between read and render doesn't lose1846        // the alerts.1847        if (consume) await clearPendingSyncAlerts();1848        return { ok: true, data: alerts };1849      }18501851      case "GET_PENDING_VOUCHED_DEVICES": {1852        if (vault.isDecoyMode()) return { ok: true, data: [] };1853        return { ok: true, data: await listPendingVouchedDevices() };1854      }1855      case "CONFIRM_VOUCHED_DEVICE": {1856        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1857        const { deviceId } = msg.payload as { deviceId: string };1858        const pending = await getPendingVouchedDevice(deviceId);1859        if (!pending) return { ok: false, error: "not_pending" };1860        // Last gate before a vouched device becomes a sync peer. A queue entry1861        // can predate the revocation that names it, so revocation is re-checked1862        // here rather than trusted to have swept the queue.1863        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {1864          await removePendingVouchedDevice(deviceId);1865          return { ok: false, error: "device_revoked" };1866        }1867        await upsertPairedDeviceV3({1868          deviceId: pending.deviceId,1869          deviceName: pending.deviceName,1870          deviceType:1871            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1872          longTermPublicKeyHex: pending.longTermPublicKeyHex,1873          signingPublicKeyHex: pending.signingPublicKeyHex,1874          wsPort: pending.wsPort,1875          pairedAt: pending.pairedAt,1876          trustSource: "vouched",1877        });1878        await removePendingVouchedDevice(deviceId);1879        // Newly confirmed vouched device is now a sync target — kick a round1880        // so the mesh introduction pays off without a 10-minute wait.1881        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1882        return { ok: true };1883      }1884      case "REJECT_VOUCHED_DEVICE": {1885        if (vault.isDecoyMode()) return { ok: true };1886        const { deviceId } = msg.payload as { deviceId: string };1887        await removePendingVouchedDevice(deviceId);1888        return { ok: true };1889      }18901891      case "ROTATE_SYNC_IDENTITY": {1892        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1893        const result = await vault.rotateSyncIdentity();1894        return result.ok ? { ok: true } : { ok: false, error: result.error };1895      }18961897      default:1898        return { ok: false, error: "unknown_message_type" };1899    }1900  } catch (err) {1901    return {1902      ok: false,1903      error: err instanceof Error ? err.message : "operation_failed",1904    };1905  }1906}19071908// Returns username use-counts from the vault, sorted by frequency. Each row1909// also carries the entry's email so the popup can suggest the email/username1910// pair the user has actually used together.1911function buildIdentitySuggestions(1912  entries: VaultEntry[],1913): Array<{ email: string; username: string; count: number }> {1914  const usernameCounts = new Map<string, number>();1915  const usernameEmail = new Map<string, string>();1916  for (const entry of entries) {1917    const username = entry.username ?? "";1918    const email = (entry as VaultEntry & { email?: string }).email ?? "";1919    if (!username && !email) continue;1920    const key = username || email;1921    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1922    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1923  }1924  return Array.from(usernameCounts.entries())1925    .sort((a, b) => b[1] - a[1])1926    .map(([username, count]) => ({1927      email: usernameEmail.get(username) ?? "",1928      username,1929      count,1930    }));1931}19321933/** Notify all content scripts that the vault just became available. */1934function broadcastToContentScripts(message: { type: string }): void {1935  if (!chrome.tabs?.query) return;1936  chrome.tabs.query({}, (tabs) => {1937    for (const tab of tabs) {1938      if (tab.id !== undefined) {1939        chrome.tabs.sendMessage(tab.id, message).catch(() => {1940          // Tab may not have a content script — silently ignore1941        });1942      }1943    }1944  });1945}19461947function shouldRefreshAutoLock(1948  type: MessageType,1949  sender: Partial<chrome.runtime.MessageSender>,1950): boolean {1951  if (!isExtensionPageSender(sender)) return false;1952  return (1953    type !== "HAS_VAULT" &&1954    type !== "IS_UNLOCKED" &&1955    type !== "GET_VAULT_STATUS" &&1956    type !== "LOCK" &&1957    type !== "UPDATE_SETTINGS" &&1958    type !== "GET_PENDING_PASSKEY" &&1959    type !== "GET_PASSKEY_PROVIDER_STATE" &&1960    type !== "DECLINE_CARD_SAVE" &&1961    type !== "IS_CARD_DECLINED" &&1962    type !== "AUTOFILL_QUERY" &&1963    type !== "ML_PREDICT_BATCH"1964  );1965}19661967function isAllowedCanaryWebhookUrl(value: string): boolean {1968  try {1969    const url = new URL(value);1970    if (url.protocol !== "https:") return false;19711972    const hostname = url.hostname.toLowerCase();1973    if (1974      hostname === "localhost" ||1975      hostname.endsWith(".localhost") ||1976      isPrivateIpv4(hostname) ||1977      isPrivateIpv6(hostname)1978    ) {1979      return false;1980    }19811982    return true;1983  } catch {1984    return false;1985  }1986}19871988function isPrivateIpv4(hostname: string): boolean {1989  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1990    return true;1991  }19921993  const octets = hostname.split(".").map((part) => Number(part));1994  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1995    return false;1996  }19971998  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1999}20002001function isPrivateIpv6(hostname: string): boolean {2002  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();2003  // IPv4-mapped IPv6 literals embed a plain IPv4 address that the prefix2004  // list below can never match (WHATWG URL serializes [::ffff:192.168.0.1]2005  // as ::ffff:c0a8:1). Unwrap and test the embedded IPv4; unparseable mapped2006  // tails fail closed. (Codex Security 2026-08-04 LOW,2007  // ssrf.webhook-url-private-ip-filter.) DNS rebinding is out of scope for a2008  // one-shot host check.2009  const mapped = /^::ffff:(.+)$/.exec(normalized);2010  if (mapped) {2011    const tail = mapped[1] ?? "";2012    if (tail.includes(".")) return isPrivateIpv4(tail);2013    const parts = tail.split(":");2014    const [hi, lo] = parts;2015    if (2016      parts.length !== 2 ||2017      !hi ||2018      !lo ||2019      !/^[0-9a-f]{1,4}$/.test(hi) ||2020      !/^[0-9a-f]{1,4}$/.test(lo)2021    ) {2022      return true;2023    }2024    const octets = [2025      (Number.parseInt(hi, 16) >>> 8) & 0xff,2026      Number.parseInt(hi, 16) & 0xff,2027      (Number.parseInt(lo, 16) >>> 8) & 0xff,2028      Number.parseInt(lo, 16) & 0xff,2029    ];2030    return isPrivateIpv4(octets.join("."));2031  }2032  return (2033    normalized === "::1" ||2034    normalized.startsWith("fc") ||2035    normalized.startsWith("fd") ||2036    normalized.startsWith("fe80:")2037  );2038}