messages.ts

87.4 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard, getEffectiveClearSeconds } from "./clipboard";13import { dismissPendingSyncAlerts, getPendingSyncAlerts } from "./sync-alerts";14import { extractDomain } from "../shared/domain";15import {16  getPendingVouchedDevice,17  listPendingVouchedDevices,18  removePendingVouchedDevice,19} from "./pending-vouched-devices";20import {21  clearRecoveryConfirmPending,22  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 { clearLockedSyncPrivateKey } from "./locked-sync-spool";78import {79  isDeviceRevoked,80  listPairedDevices as listPairedDevicesV3,81  renamePairedDevice as renamePairedDeviceV3,82  revokeDeviceById as revokeDeviceByIdV3,83  TrustDataCorruptedError,84  upsertPairedDevice as upsertPairedDeviceV3,85} from "./paired-devices";86import { dropPairSecret } from "./pair-secrets";87// Sync and pairing are imported statically, never with `await import()`.88// `import()` throws `TypeError: import() is disallowed on89// ServiceWorkerGlobalScope` at runtime in MV3, and Vite's preload helper90// reports the failure through `window.dispatchEvent`, which does not exist in91// a worker either — so the real reason was replaced by "window is not defined"92// and the pairing UI just stopped. scripts/check-sw-static-imports.mjs fails93// the build if a runtime import() reappears anywhere in the worker's graph.94import {95  cancelRelayAdoptionSource,96  isRelayAdoptionSourceInFlight,97  resolveReceiverSasConfirmation,98  resolveSourceSasConfirmation,99  startRelayAdoptionReceiver,100  startRelayAdoptionSource,101} from "./relay-adoption-bg";102import {103  listPendingAdoptionHolders,104  removePendingAdoptionHolder,105} from "./pending-adoption-holder";106import {107  getSyncSettings,108  setRelayUrl,109  setSyncMode,110  type SyncMode,111} from "./sync-settings";112import {113  getSyncState,114  triggerSyncIfReachable,115} from "./sync-trigger";116import {117  browserGenerationIo,118  confirmSecureReset,119  enterResetRequired,120  resolveGeneration,121} from "./sync-generation";122import { isMessageSenderAllowed } from "./message-policy";123124const SUMMON_CAPABILITY_TTL_MS = 30_000;125type SummonCapability = { tabId: number; frameId: number; origin: string; operation: "inventory" | "fill"; expiresAt: number };126const summonCapabilities = new Map<string, SummonCapability>();127128export function createSummonCapability(tabId: number, origin: string, frameId = 0): string {129  const token = crypto.randomUUID();130  summonCapabilities.set(token, { tabId, frameId, origin, operation: "inventory", expiresAt: Date.now() + SUMMON_CAPABILITY_TTL_MS });131  return token;132}133134function consumeSummonCapability(token: unknown, sender: Partial<chrome.runtime.MessageSender>, operation: "inventory" | "fill"): boolean {135  if (typeof token !== "string") return false;136  const cap = summonCapabilities.get(token);137  if (!cap) return false;138  if (cap.expiresAt <= Date.now()) {139    summonCapabilities.delete(token);140    return false;141  }142  if (sender.tab?.id !== cap.tabId || (sender.frameId ?? 0) !== cap.frameId || attestedSenderOrigin(sender) !== cap.origin) return false;143  if (cap.operation !== operation) return false;144  if (operation === "inventory") cap.operation = "fill";145  else summonCapabilities.delete(token);146  return true;147}148149// Compile-time E2E flag, folded to a literal by Vite's `define` (false in150// every production build — verified in the bundled output). Mirrors the151// create-path bypass in passkey.ts so the Playwright passkey smoke can enable152// the provider without a real Pro licence; the gate is fully intact for users.153declare const __PEACH_E2E_PASSKEYS__: boolean;154const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true;155156function unhexBytes(hex: string): Uint8Array {157  if (hex.length % 2 !== 0) throw new Error("invalid hex");158  const out = new Uint8Array(hex.length / 2);159  for (let i = 0; i < out.length; i++) {160    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);161  }162  return out;163}164165/**166 * The single Pro gate. Every gated handler calls this first; the broadcast167 * lets the popup react (navigate to the License section, highlight the168 * relevant feature). Background never touches the popup view directly —169 * the popup owns navigation. See Projects.md "Pro gate rule".170 */171async function requirePro(172  feature: ProFeature,173  trigger: "user" | "background" = "user"174): Promise<{ allowed: boolean }> {175  if (PASSKEY_E2E_PRO_BYPASS && feature === "passkeys") return { allowed: true };176  if (await isProUser()) return { allowed: true };177178  if (trigger === "user") {179    // User deliberately triggered this feature — redirect the popup immediately.180    chrome.runtime181      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })182      .catch(() => {183        // Popup may be closed — the gate signal is best-effort.184      });185  } else {186    // Background trigger (e.g. passive sync initiation) — no popup is open.187    // Queue a notice so the next popup open shows a soft banner instead of188    // silently failing.189    if (chrome.storage.session) {190      chrome.storage.session191        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })192        .catch(() => {});193    }194  }195196  return { allowed: false };197}198199// LV-3: minimum interval between non-test canary pings per webhook+entry.200const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour201202const PRIVATE_IPV4_RANGES = [203  { prefix: "10." },204  { prefix: "127." },205  { prefix: "169.254." },206  { prefix: "192.168." },207];208209export function setupMessageHandler(): void {210  chrome.runtime.onMessage.addListener(211    (msg: unknown, sender, sendResponse) => {212      if (!isMessage(msg)) {213        sendResponse({ ok: false, error: "invalid_message" });214        return true;215      }216      handleMessage(msg, sender)217        .then(sendResponse)218        .catch((err) =>219          sendResponse({220            ok: false,221            error: err instanceof Error ? err.message : String(err),222          })223        );224      return true;225    }226  );227}228229function isMessage(m: unknown): m is Message {230  return typeof m === "object" && m !== null && "type" in m;231}232233/**234 * The browser-attested origin of the page that originated this message. A web235 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),236 * so every page-driven message arrives via the content-script relay and the237 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a238 * value the page cannot forge. This is the ONLY trustworthy origin for passkey239 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.240 */241function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {242  if (sender.origin) return sender.origin;243  if (sender.url) {244    try { return new URL(sender.url).origin; } catch { return undefined; }245  }246  return undefined;247}248249function isExtensionPageSender(sender: Partial<chrome.runtime.MessageSender>): boolean {250  return sender.url?.startsWith("chrome-extension://") === true ||251    sender.url?.startsWith("moz-extension://") === true;252}253254/** True when the message came from a page frame rather than extension UI. */255function isPageSender(sender: Partial<chrome.runtime.MessageSender>): boolean {256  return !isExtensionPageSender(sender) &&257    (sender.tab !== undefined || sender.url !== undefined);258}259260function entryDomains(url: unknown, additionalUrls: unknown): Set<string> {261  const domains = new Set<string>();262  const primary = typeof url === "string" ? extractDomain(url) : null;263  if (primary) domains.add(primary);264  if (Array.isArray(additionalUrls)) {265    for (const extra of additionalUrls) {266      if (typeof extra !== "string") continue;267      const domain = extractDomain(extra);268      if (domain) domains.add(domain);269    }270  }271  return domains;272}273274/**275 * PB-26-106: the autofill read path re-validates the frame origin against the276 * entry's domains on every request, so an unbound write path would let a277 * content script repoint an entry at its own origin and then read the278 * credential through a read path that is behaving correctly.279 *280 * Creating an entry: a page may only bind it to itself. Mutating one: a page281 * may never GROW the domain set — only shrink it, and never below its own282 * attested origin.283 *284 * Self-binding on mutation was considered and is not enough: the content285 * script on a foreign origin IS the attacker in the reported chain, so letting286 * it attach "its own" origin lets it mint the very capability the read path287 * exists to withhold. The legitimate flow that needs a new domain — the inline288 * "remember this site" toast — therefore asks the popup instead289 * (REQUEST_REMEMBER_SITE), which is an extension page and exempt here.290 *291 * Extension pages are exempt: the popup edits entries for sites it is not on.292 */293function senderMayBindEntryDomains(294  sender: Partial<chrome.runtime.MessageSender>,295  domains: Set<string>,296): boolean {297  if (isExtensionPageSender(sender)) return true;298  const domain = attestedSenderDomain(sender);299  if (domain === null) return false;300  for (const candidate of domains) {301    if (candidate !== domain) return false;302  }303  return true;304}305306function senderMayMutateEntryDomains(307  sender: Partial<chrome.runtime.MessageSender>,308  before: Set<string>,309  after: Set<string>,310): boolean {311  if (isExtensionPageSender(sender)) return true;312  const domain = attestedSenderDomain(sender);313  if (domain === null || !after.has(domain)) return false;314  for (const kept of after) {315    if (!before.has(kept)) return false;316  }317  return true;318}319320/**321 * Null for extension pages (which the callers exempt), for senders with no322 * attested origin at all, and for unparseable frame urls.323 */324function attestedSenderDomain(sender: Partial<chrome.runtime.MessageSender>): string | null {325  if (sender.tab === undefined && sender.url === undefined) return null;326  const origin = attestedSenderOrigin(sender);327  if (!origin) return null;328  try { return extractDomain(new URL(origin).hostname); } catch { return null; }329}330331function patchChangesEntryOrigin(patch: object): boolean {332  return Object.hasOwn(patch, "url") || Object.hasOwn(patch, "additionalUrls");333}334335/** The entry's domain-bearing fields as the patch would leave them. */336function patchedUrlShape(337  patch: object,338  existing: Pick<VaultEntry, "url" | "additionalUrls">,339): { url: unknown; additionalUrls: unknown } {340  const candidate = patch as { url?: unknown; additionalUrls?: unknown };341  return {342    url: Object.hasOwn(patch, "url") ? candidate.url : existing.url,343    additionalUrls: Object.hasOwn(patch, "additionalUrls")344      ? candidate.additionalUrls345      : existing.additionalUrls,346  };347}348// Resolves once restoreFromSession() has run, so handlers see the correct349// post-restore unlock state. entry.ts registers this BEFORE the message350// handler so the onMessage listener is added synchronously at SW startup351// (MV3 requirement) while unlock-dependent handlers still wait for restore.352let restoreReady: Promise<void> = Promise.resolve();353const MAX_ML_BATCH_FIELDS = 128;354const MAX_ML_FIELDS_PER_SECOND = 256;355const mlWorkBySender = new Map<string, { startedAt: number; fields: number }>();356357function claimMLWork(sender: Partial<chrome.runtime.MessageSender>, fields: number): boolean {358  if (fields === 0) return true;359  const now = Date.now();360  for (const [key, value] of mlWorkBySender) {361    if (now - value.startedAt >= 1_000) mlWorkBySender.delete(key);362  }363  const key = `${sender.tab?.id ?? "ui"}:${sender.frameId ?? 0}:${attestedSenderOrigin(sender) ?? "extension"}`;364  const current = mlWorkBySender.get(key);365  if (!current) {366    mlWorkBySender.set(key, { startedAt: now, fields });367    return fields <= MAX_ML_FIELDS_PER_SECOND;368  }369  if (current.fields + fields > MAX_ML_FIELDS_PER_SECOND) return false;370  current.fields += fields;371  return true;372}373374/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */375export function setRestoreReady(p: Promise<unknown>): void {376  restoreReady = p.then(() => undefined, () => undefined);377}378379export async function handleMessage(380  msg: Message,381  sender: Partial<chrome.runtime.MessageSender> = {}382): Promise<MessageResponse> {383  try {384    // Wait for session-restore to finish before reading any unlock/vault state.385    // On a cold SW start the popup's first message arrives while restore is386    // still in flight; without this gate IS_UNLOCKED would report locked (a387    // spurious lock screen) and the storage reads could race. The onMessage388    // listener itself is registered synchronously (entry.ts) so this gate, not389    // listener registration, is what absorbs the cold-start window.390    await restoreReady;391    // Validate sender — only allow messages from our extension pages/scripts.392    // `sender.id` is undefined for messages originating from extension UI393    // (popup/options), which is legitimate; reject only when it is defined394    // and does not match our extension id.395    if (396      sender.id !== undefined &&397      sender.id !== chrome.runtime.id398    ) {399      return { ok: false, error: "invalid_sender" };400    }401402    // PB-26-016: sender authorization is an exhaustive policy, not a403    // hand-maintained privileged denylist. A missing/unknown policy entry or a404    // background-only message fails closed before any handler runs.405    // Extension UI messages may legitimately omit sender.url. Resolve the406    // browser-attested extension origin only when a URL is present; this also407    // keeps test/runtime shims without getURL fail-closed for URL-bearing408    // senders instead of throwing before policy evaluation.409    const extensionOrigin = sender.url && typeof chrome.runtime.getURL === "function"410      ? chrome.runtime.getURL("")411      : "";412    if (!isMessageSenderAllowed(msg.type, sender, chrome.runtime.id, extensionOrigin)) {413      return { ok: false, error: "invalid_sender" };414    }415416    if (shouldRefreshAutoLock(msg.type, sender) && vault.isUnlocked()) {417      touchAutoLock();418    }419420    switch (msg.type) {421      case "CREATE_VAULT": {422        const { password } = msg.payload as { password: string };423        // Refuse to create a vault under an empty master password — the derived424        // key would be publicly known and the at-rest AES-GCM protection void425        // (audit HIGH; the CSV-import path previously passed ""). Length/strength426        // policy lives in the onboarding UI; this is the non-negotiable floor.427        if (typeof password !== "string" || password.length === 0) {428          return { ok: false, error: "invalid_payload" };429        }430        await vault.createVault(password);431        await setupAutoLock();432        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });433        onVaultUnlocked();434        return { ok: true };435      }436      case "CREATE_VAULT_FROM_ROOT_KEY": {437        const { password, rootKeyHex } = (msg.payload ?? {}) as {438          password?: unknown;439          rootKeyHex?: unknown;440        };441        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {442          return { ok: false, error: "invalid_payload" };443        }444445        try {446          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);447          await setupAutoLock();448          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });449          onVaultUnlocked();450          return { ok: true, vaultId };451        } catch (err) {452          return { ok: false, error: err instanceof Error ? err.message : String(err) };453        }454      }455      case "UNLOCK": {456        const { password } = msg.payload as { password: string };457        const ok = await vault.unlock(password);458        if (ok) {459          // KAT: verify the WebCrypto stack is healthy before the user relies on it.460          // Runs after unlock so latency is hidden behind the vault-load time.461          const kat = await runSelfTest();462          if (!kat.ok) {463            console.error("[Peach] Crypto self-test FAILED:", kat.error);464            await vault.lock();465            return { ok: false, error: "self_test_failed" };466          }467          await vault.updateSettings({ pinPreferred: false });468          await setupAutoLock();469          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });470          onVaultUnlocked();471          return { ok: true };472        }473        // Distinguish corruption from wrong password so the popup can offer474        // a history-restore path instead of falsely accusing the user of475        // mistyping (M7/COR-007).476        const failure = vault.consumeLastUnlockFailureReason();477        if (failure) {478          return {479            ok: false,480            error: "vault_corrupted",481            canRestoreFromHistory: true,482          } as MessageResponse;483        }484        return { ok: false };485      }486      case "UNLOCK_WITH_PIN": {487        const { pin } = (msg.payload ?? {}) as { pin?: unknown };488        if (typeof pin !== "string") return { ok: false, error: "invalid_payload" };489        const ok = await vault.unlockWithPin(pin);490        if (!ok) {491          const status = await vault.getPinUnlockStatus();492          if (status.configured && !status.available) {493            return {494              ok: false,495              error: status.attemptsRemaining === 0496                ? "pin_attempts_exceeded"497                : "pin_session_expired",498            };499          }500          return { ok: false };501        }502        const kat = await runSelfTest();503        if (!kat.ok) {504          await vault.lock();505          return { ok: false, error: "self_test_failed" };506        }507        await vault.updateSettings({ pinPreferred: true });508        await setupAutoLock();509        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });510        onVaultUnlocked();511        return { ok: true };512      }513      case "GET_PIN_STATUS":514        return { ok: true, data: await vault.getPinUnlockStatus() };515      case "VALIDATE_RECOVERY_WORDS": {516        const { words } = msg.payload as { words: string[] };517        const invalid = findInvalidWords(words);518        return { ok: true, data: { valid: invalid.length === 0, invalid } };519      }520      case "GET_RECOVERY_WORDS": {521        // Must be unlocked and have recovery set up (vault must be v2.12+).522        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };523        // LV-4: the recovery words re-derive the ROOT KEY — the highest-524        // value secret in the vault. A session unlock (which may be hours525        // old on a shared machine) is not enough; require a fresh password526        // proof, matching the 1Password/Bitwarden pattern for revealing527        // escrow material. EXEMPTION: the create-vault / rotation confirmation528        // window (peach_recovery_pending) shows the words immediately after529        // the user authenticated, and that confirmation UI has no password to530        // resend — skip the re-auth there only.531        if (!(await isRecoveryConfirmPending())) {532          const { password } = (msg.payload ?? {}) as { password?: string };533          if (typeof password !== "string" || !password) {534            return { ok: false, error: "password_required" };535          }536          if (!(await vault.verifyMainPassword(password))) {537            return { ok: false, error: "wrong_password" };538          }539        }540        try {541          const words = await vault.getRecoveryWords();542          return { ok: true, data: words };543        } catch {544          return { ok: false, error: "recovery_not_setup" };545        }546      }547      case "GET_RECOVERY_CONFIRM_PENDING":548        return { ok: true, data: await isRecoveryConfirmPending() };549      case "SET_RECOVERY_CONFIRM_PENDING":550        await setRecoveryConfirmPending();551        return { ok: true };552      case "CLEAR_RECOVERY_CONFIRM_PENDING":553        await clearRecoveryConfirmPending();554        return { ok: true };555      case "RECOVER_WITH_WORDS": {556        // User has lost their password but has their 12 recovery words.557        // We: (1) validate the words, (2) re-encrypt vault with new password.558        if (!msg.payload || typeof msg.payload !== "object" || Array.isArray(msg.payload)) {559          return { ok: false, error: "invalid_recovery_payload" };560        }561        const { words, newPassword } = msg.payload as {562          words: string[];563          newPassword: string;564        };565        if (!Array.isArray(words) || words.some((word) => typeof word !== "string") || typeof newPassword !== "string") {566          return { ok: false, error: "invalid_recovery_payload" };567        }568        const recovered = await vault.recoverWithWords(words, newPassword);569        if (recovered.unlocked) {570          try { await setupAutoLock(); }571          catch (error) {572            console.warn("[Peach] recovery password saved; auto-lock setup failed:", error);573            try { await vault.lock(); }574            catch (lockError) { console.warn("[Peach] recovery session cleanup failed:", lockError); }575          }576        }577        const unlocked = recovered.unlocked && vault.isUnlocked();578        if (unlocked) broadcastToContentScripts({ type: "VAULT_UNLOCKED" });579        return { ok: true, data: { ...recovered, unlocked } };580      }581      case "LOCK":582        await vault.lock();583        return { ok: true };584      case "IS_UNLOCKED":585        return { ok: true, data: vault.isUnlocked() };586      case "GET_VAULT_STATUS":587        return { ok: true, unlocked: vault.isUnlocked() };588      case "HAS_VAULT":589        return { ok: true, data: await vault.hasVault() };590      case "GET_ENTRIES":591        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };592        return { ok: true, data: vault.getEntries() };593      case "EXPORT_ENTRIES": {594        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };595        const { password } = (msg.payload ?? {}) as { password?: unknown };596        if (typeof password !== "string" || !password) {597          return { ok: false, error: "password_required" };598        }599        if (!(await vault.verifyMainPassword(password))) {600          return { ok: false, error: "wrong_password" };601        }602        return { ok: true, data: vault.getEntries() };603      }604      case "ADD_ENTRY": {605        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };606        const payload = msg.payload;607        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {608          return { ok: false, error: "invalid_payload" };609        }610        // PB-26-106: a page may only create an entry bound to itself. Entries611        // carrying no url have no domain surface to bind, so they are exempt.612        if (isPageSender(sender)) {613          const draft = payload as { url?: unknown; additionalUrls?: unknown };614          const domains = entryDomains(draft.url, draft.additionalUrls);615          if (domains.size > 0 && !senderMayBindEntryDomains(sender, domains)) {616            return { ok: false, error: "origin_binding_required" };617          }618        }619        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);620        return { ok: true, data: entry };621      }622      case "BATCH_ADD_ENTRIES": {623        const payload = msg.payload as { entries?: unknown } | null | undefined;624        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {625          return { ok: false, error: "invalid_payload" };626        }627        if (!Array.isArray(payload.entries)) {628          return { ok: false, error: "invalid_payload" };629        }630        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);631        return { ok: true, data: added };632      }633      case "RESTORE_ENTRIES": {634        const payload = msg.payload as635          | { entries?: unknown; mode?: unknown; settings?: unknown }636          | null637          | undefined;638        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {639          return { ok: false, error: "invalid_payload" };640        }641        if (!Array.isArray(payload.entries)) {642          return { ok: false, error: "invalid_payload" };643        }644        if (payload.mode !== "replace" && payload.mode !== "merge") {645          return { ok: false, error: "invalid_payload" };646        }647        const summary = await vault.restoreEntries(648          payload.entries as Parameters<typeof vault.restoreEntries>[0],649          payload.mode650        );651        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {652          await vault.updateSettings(payload.settings as vault.VaultSettings);653        }654        return { ok: true, data: summary };655      }656      case "CLEAR_VAULT_ENTRIES": {657        await vault.clearVaultEntries("REPLACE_ALL");658        return { ok: true };659      }660      case "GET_VAULT_HISTORY": {661        // The history store is real-mode state by construction, so a decoy662        // session must not see it — this is where the duress session would663        // otherwise leak the real vault's activity and size (PB-26-915).664        if (vault.isDecoyMode()) return { ok: true, data: [] };665        const snapshots = await vault.getVaultHistory();666        return { ok: true, data: snapshots };667      }668      case "RESTORE_VAULT_SNAPSHOT": {669        // Same guard on the write side: a coerced session must not be able to670        // roll the real vault backwards onto an earlier snapshot.671        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };672        const { snapshotId } = msg.payload as { snapshotId: string };673        const result = await vault.restoreVaultSnapshot(snapshotId);674        if (!result.ok) return { ok: false, error: result.error };675        broadcastToContentScripts({ type: "VAULT_LOCKED" });676        return { ok: true };677      }678      case "COUNT_DUPLICATES": {679        return { ok: true, data: vault.countDuplicates() };680      }681      case "DEDUPLICATE_ENTRIES": {682        const removed = await vault.deduplicateEntries();683        return { ok: true, data: removed };684      }685      case "UPDATE_ENTRY": {686        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;687        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {688          return { ok: false, error: "invalid_payload" };689        }690        const { id, patch } = payload;691        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {692          return { ok: false, error: "invalid_payload" };693        }694        const existingEntry = vault.getEntryById(id);695        if (!existingEntry) return { ok: false, error: "entry_not_found" };696        if (patchChangesEntryOrigin(patch) || isPageSender(sender)) {697          const before = entryDomains(existingEntry.url, existingEntry.additionalUrls);698          const after = patchedUrlShape(patch, existingEntry);699          if (!senderMayMutateEntryDomains(700            sender,701            before,702            entryDomains(after.url, after.additionalUrls),703          )) {704            return { ok: false, error: "origin_binding_required" };705          }706        }707        // Single enforcement point for the Canary Entries Pro gate. Only708        // gates the transition into a canary entry — clearing/disabling a709        // canary (`canary: undefined`) is always allowed, so existing710        // canary entries remain manageable.711        const incomingCanary = (patch as { canary?: unknown }).canary;712        if (incomingCanary && typeof incomingCanary === "object") {713          const existing = vault.getEntryById(id);714          if (!existing?.canary) {715            const gate = await requirePro("canary_entry");716            if (!gate.allowed) return { ok: false, error: "pro_required" };717          }718        }719        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);720        return { ok: true };721      }722      case "ADD_ADDITIONAL_URL": {723        const { id, url } = msg.payload as { id: string; url: string };724        const trimmed = typeof url === "string" ? url.trim() : "";725        if (!trimmed) return { ok: false, error: "url_required" };726        const existing = vault.getEntryById(id);727        if (!existing) return { ok: false, error: "entry_not_found" };728        const merged = [...(existing.additionalUrls ?? []), trimmed];729        if (!senderMayMutateEntryDomains(730          sender,731          entryDomains(existing.url, existing.additionalUrls),732          entryDomains(existing.url, merged),733        )) {734          return { ok: false, error: "origin_binding_required" };735        }736        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };737        await vault.updateEntry(id, { additionalUrls: merged });738        return { ok: true };739      }740      case "REQUEST_REMEMBER_SITE": {741        // PB-26-106: growing an entry's domain set needs a decision the page742        // cannot make for itself, so the page asks and the popup confirms. A743        // page may only ask about its own attested origin — otherwise this744        // becomes the same unbound write under a friendlier name.745        const { id, url } = (msg.payload ?? {}) as { id?: unknown; url?: unknown };746        if (typeof id !== "string" || !id) return { ok: false, error: "invalid_payload" };747        const trimmed = typeof url === "string" ? url.trim() : "";748        if (!trimmed) return { ok: false, error: "url_required" };749        if (!senderMayBindEntryDomains(sender, entryDomains(trimmed, undefined))) {750          return { ok: false, error: "origin_binding_required" };751        }752        if (!vault.getEntryById(id)) return { ok: false, error: "entry_not_found" };753        if (chrome.storage.session) {754          await chrome.storage.session.set({ pendingRememberSite: { entryId: id, url: trimmed } });755        }756        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }757        return { ok: true };758      }759      case "DELETE_ENTRY": {760        const { id } = msg.payload as { id: string };761        await vault.deleteEntry(id);762        return { ok: true };763      }764      case "GET_DELETED_ENTRIES":765        return { ok: true, data: vault.getDeletedEntries() };766      case "RESTORE_ENTRY": {767        const { id } = msg.payload as { id: string };768        await vault.restoreEntry(id);769        return { ok: true };770      }771      case "PURGE_ENTRY": {772        const { id } = msg.payload as { id: string };773        await vault.purgeEntry(id);774        return { ok: true };775      }776      case "PURGE_EXPIRED_TRASH": {777        const { retentionMs } = msg.payload as { retentionMs: number };778        const purged = await vault.purgeExpiredTrash(retentionMs);779        return { ok: true, data: purged };780      }781      case "SAVE_NOTE": {782        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };783        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };784        const now = Date.now();785        if (id) {786          const existing = vault.getEntryById(id);787          if (!existing) return { ok: false, error: "not_found" };788          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });789          return { ok: true, data: vault.getEntryById(id) };790        } else {791          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt792          // (EntryDraft omits both), so passing them was the only reason the793          // `as any` cast existed. Dropping them makes the call type-check.794          const entry = await vault.addEntry({795            type: "note",796            title: title || "Untitled",797            notes: body,798          });799          return { ok: true, data: entry };800        }801      }802      case "DELETE_NOTE": {803        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };804        const { id } = msg.payload as { id: string };805        await vault.deleteEntry(id);806        return { ok: true };807      }808      case "GET_NOTES": {809        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };810        const notes = vault.getEntries().filter(811          (e) => e.type === "note" && !e.deletedAt812        );813        return { ok: true, data: notes } as MessageResponse;814      }815      case "SEARCH_VAULT": {816        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };817        // AUD-002: shape-validate the payload before calling string methods.818        // A raw cast lets a malformed message crash the handler with TypeError.819        const { query } = (msg.payload ?? {}) as { query?: unknown };820        if (typeof query !== "string") {821          return { ok: false, error: "invalid_payload" };822        }823        const q = query.toLowerCase();824        const searchResults = vault.getEntries().filter(825          (e) =>826            !e.deletedAt &&827            (e.title.toLowerCase().includes(q) ||828              e.notes?.toLowerCase().includes(q) ||829              e.username?.toLowerCase().includes(q))830        );831        return { ok: true, data: searchResults } as MessageResponse;832      }833      case "AUTOFILL_QUERY": {834        if (!vault.isUnlocked()) {835          return { ok: false, error: "vault_locked" };836        }837        const { domain, kind, capability } = msg.payload as {838          domain: string;839          kind?: "login" | "card" | "totp";840          capability?: string;841        };842        const includeAll = consumeSummonCapability(capability, sender, "inventory");843        if (capability !== undefined && !includeAll) {844          return { ok: false, error: "entry_not_found" };845        }846        // kind="card": return saved cards as compact summaries for the847        // inline card silver platter. Cards are not domain-scoped — every848        // saved card is a candidate on every checkout page — so domain is849        // ignored when kind === "card".850        if (kind === "card") {851          if (!includeAll) return { ok: true, data: [] };852          const cards = vault.getEntries().filter((e) => e.type === "card");853          return {854            ok: true,855            data: cards.map((e) => ({856              id: e.id,857              title: e.cardNickname || e.title,858              cardholderName: e.cardholderName,859              last4: e.last4,860              expMonth: e.expMonth,861              expYear: e.expYear,862              network: e.network,863            })),864          };865        }866        const scopedDomain = isPageSender(sender)867          ? attestedSenderDomain(sender)868          : typeof domain === "string"869            ? extractDomain(domain)870            : null;871        if (!includeAll && !scopedDomain) {872          return isPageSender(sender)873            ? { ok: false, error: "origin_unverified" }874            : { ok: true, data: [] };875        }876        if (kind === "totp") {877          const matches = (878            includeAll879              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")880              : vault.queryDomain(scopedDomain!)881          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));882          return {883            ok: true,884            data: matches.map((e) => ({885              id: e.id,886              title: e.title,887              username: e.username,888              email: e.email,889              url: e.url,890              hasTotp: true,891            })),892          };893        }894        // The inline selector fills username+password into a form. Passkey-895        // only entries have no password to fill; sign-in for those goes896        // through the WebAuthn path instead. Filter them out everywhere so897        // the user doesn't see four "GitHub" rows that mostly do nothing.898        // Notes and cards never belonged here either.899        const matches = (900          includeAll901            ? vault902                .getEntries()903                .filter((entry) => entry.type !== "note" && entry.type !== "card")904            : vault.queryDomain(scopedDomain!)905        ).filter((entry) => !isPasskeyOnly(entry));906        return {907          ok: true,908          data: matches.map((e) =>909            includeAll910              ? {911                  id: e.id,912                  title: e.title,913                  // username/email/url shipped so the inline popup's search914                  // affordance can match on them, not just titles. No secrets915                  // cross the boundary — same shape as the domain-matched916                  // response below minus hasTotp (which the search list917                  // doesn't surface).918                  username: e.username,919                  email: e.email,920                  url: e.url,921                  hasPasskey: e.passkey !== undefined,922                }923              : {924                  id: e.id,925                  title: e.title,926                  username: e.username,927                  email: e.email,928                  url: e.url,929                  hasTotp: Boolean(e.totp),930                  hasPasskey: e.passkey !== undefined,931                }932          ),933        };934      }935      case "GET_ENTRY_FOR_FILL": {936        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };937        const { id, capability } = msg.payload as {938          id: string;939          capability?: string;940        };941        const capabilityAuthorized = capability !== undefined && consumeSummonCapability(capability, sender, "fill");942        const senderDomain = isPageSender(sender) ? attestedSenderDomain(sender) : null;943        if (isPageSender(sender) && !senderDomain) {944          return { ok: false, error: "origin_unverified" };945        }946        const entry = vault.getEntryById(id);947        if (!entry) return { ok: false, error: "entry_not_found" };948949        // MV-1: re-validate the entry against the requesting frame's origin.950        // sender.url / sender.tab.url are browser-attested — a page cannot951        // forge them. PB-26-005: the FRAME url (sender.url) is authoritative952        // for an all_frames content script; the top-frame tab.url would953        // misattribute a cross-origin iframe's request to the top page. When954        // the request does not come from a tab at all (popup surfaces use955        // GET_ENTRY_FOR_EDIT, not this), refuse.956        if (senderDomain && !capabilityAuthorized) {957          if (!entryDomains(entry.url, entry.additionalUrls).has(senderDomain)) {958            // Domain mismatch — refuse silently (no oracle about which ids exist).959            return { ok: false, error: "entry_not_found" };960          }961        }962        // Passkey-only entries (passkey credential, no password) cannot be963        // filled into a form — sign-in goes through the WebAuthn path. A964        // login that ALSO has a passkey is still fillable for its password.965        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };966        // Strip the passkey credential AND the raw base32 TOTP seed from the967        // response. Content scripts never need either: the private key is the968        // authenticator's, and handing over the TOTP seed would let a969        // compromised content script mint valid codes indefinitely (SEV-3-C).970        // Generate the *current* 6-digit code here in the background and send971        // only that, plus the seconds left so the UI can render a countdown.972        // Also drop passwordHistory: filling needs only the *current* password.973        // Handing every past password to a content script during passive974        // autofill on an arbitrary page would widen the blast radius of a975        // compromised page far beyond the one credential being filled.976        const {977          passkey: _strippedPasskey,978          totp: seed,979          totpAlgorithm,980          totpDigits,981          totpPeriod,982          passwordHistory: _ph,983          ...safeEntry984        } = entry;985        let totpCode: string | undefined;986        let totpRemaining: number | undefined;987        if (seed) {988          try {989            // PCH-01-019: honour stored algorithm/digits/period (defaults apply990            // when these are undefined, i.e. RFC-default bare-seed entries).991            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);992            totpCode = generated.code;993            totpRemaining = generated.remaining;994          } catch {995            totpCode = undefined;996          }997        }998        if (isPageSender(sender) && vault.isUnlocked()) touchAutoLock();999        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };1000      }1001      // Trusted full-entry fetch for extension-owned edit surfaces. Content1002      // scripts route editing to the popup and cannot call this message.1003      case "GET_ENTRY_FOR_EDIT": {1004        if (isPageSender(sender)) return { ok: false, error: "invalid_sender" };1005        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1006        const { id } = msg.payload as { id: string };1007        const entry = vault.getEntryById(id);1008        if (!entry) return { ok: false, error: "entry_not_found" };10091010        const { passkey: _passkey, ...safeEntry } = entry;1011        return { ok: true, data: safeEntry };1012      }1013      case "COPY": {1014        // Page relays must carry the browser-attested frame origin, as with1015        // SUMMON/fill. The policy admits content scripts; this binds the1016        // admitted page sender before arming clipboard auto-clear.1017        if (isPageSender(sender) && !attestedSenderOrigin(sender)) {1018          return { ok: false, error: "invalid_sender" };1019        }1020        // AUD-002: shape-validate the payload before passing to the clipboard1021        // helper. A raw cast lets a malformed message reach the clipboard API1022        // with a non-string and throw.1023        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {1024          text?: unknown;1025          label?: unknown;1026          alreadyWritten?: unknown;1027        };1028        if (typeof text !== "string" || typeof label !== "string") {1029          return { ok: false, error: "invalid_payload" };1030        }1031        await copyToClipboard(text, label, Boolean(alreadyWritten));1032        return { ok: true, clearSeconds: getEffectiveClearSeconds() };1033      }1034      case "CHECK_ALL_BREACHES": {1035        const allEntries = vault.getEntries();1036        const results: Record<string, number> = {};1037        for (const entry of allEntries) {1038          if (entry.type === "note") continue;1039          if (!entry.password) continue;1040          results[entry.id] = await vault.checkBreach(entry.password);1041          // Small delay — be a good citizen to the HIBP API1042          await new Promise((r) => setTimeout(r, 200));1043        }1044        // Persist any non-zero counts back to entries1045        for (const [id, count] of Object.entries(results)) {1046          const entry = vault.getEntryById(id);1047          if (entry && (entry.breach ?? 0) !== count) {1048            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });1049          }1050        }1051        return { ok: true, data: results };1052      }1053      case "GET_SETTINGS": {1054        const settings = await vault.ensureSettingsLoaded();1055        if (!isPageSender(sender)) return { ok: true, data: settings };10561057        const safeSettings: Pick<vault.VaultSettings, "accentColor" | "theme"> & {1058          manualSummonDomains?: NonNullable<vault.VaultSettings["manualSummonDomains"]>;1059        } = {1060          accentColor: settings.accentColor,1061          theme: settings.theme,1062        };1063        const domain = attestedSenderDomain(sender);1064        const ownSummon = domain ? settings.manualSummonDomains?.[domain] : undefined;1065        if (domain && ownSummon) safeSettings.manualSummonDomains = { [domain]: ownSummon };1066        return { ok: true, data: safeSettings };1067      }1068      case "UPDATE_SETTINGS": {1069        const patch = msg.payload;1070        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {1071          return { ok: false, error: "invalid_payload" };1072        }1073        await vault.updateSettings(patch as vault.VaultSettings);1074        if ((patch as Record<string, unknown>).lockedSyncRequiresUnlock === true) {1075          await clearLockedSyncPrivateKey();1076        }1077        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {1078          await setupAutoLock();1079          if (vault.isUnlocked()) touchAutoLock();1080        }1081        return { ok: true };1082      }1083      case "SETUP_PIN": {1084        const { currentPassword, pin } = (msg.payload ?? {}) as {1085          currentPassword?: unknown;1086          pin?: unknown;1087        };1088        if (typeof currentPassword !== "string" || typeof pin !== "string") {1089          return { ok: false, error: "invalid_payload" };1090        }1091        return (await vault.setupPinUnlock(currentPassword, pin))1092          ? { ok: true }1093          : { ok: false, error: "incorrect_current_password" };1094      }1095      case "DISABLE_PIN": {1096        const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown };1097        if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" };1098        return (await vault.disablePinUnlock(currentPassword))1099          ? { ok: true }1100          : { ok: false, error: "incorrect_current_password" };1101      }1102      case "GET_PENDING_PASSKEY":1103        return { ok: true, data: await getPendingPasskeyRequest() };1104      case "APPROVE_PASSKEY": {1105        const { requestId } = msg.payload as { requestId: number };1106        await resolvePendingPasskeyRequest(requestId, true);1107        return { ok: true };1108      }1109      case "DENY_PASSKEY": {1110        const { requestId } = msg.payload as { requestId: number };1111        await resolvePendingPasskeyRequest(requestId, false);1112        return { ok: true };1113      }1114      case "GET_PASSKEY_PROVIDER_STATE":1115        return { ok: true, data: await getPasskeyProviderState() };1116      case "SET_PASSKEY_PROVIDER_ENABLED": {1117        const { enabled } = msg.payload as { enabled: boolean };1118        // Disabling is always free; gating fires only when a free user is1119        // trying to turn passkey interception on.1120        if (enabled) {1121          const gate = await requirePro("passkeys");1122          if (!gate.allowed) return { ok: false, error: "pro_required" };1123        }1124        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };1125      }1126      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS1127      // endpoint. Intentional product behavior — users configure their own1128      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private1129      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-1130      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to1131      // users that the entry title leaves the device when the canary fires.1132      case "FIRE_CANARY_PING": {1133        // Canary alert fires unconditionally for any entry with canary: true.1134        // The Pro gate only governs creation/flagging of canary entries; once1135        // an entry is flagged, the alert path is a security property and must1136        // never be license-gated.1137        const { webhookUrl, entryTitle, trigger } = msg.payload as {1138          webhookUrl: string;1139          entryTitle: string;1140          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";1141        };1142        if (trigger === "test" && !isExtensionPageSender(sender)) {1143          return { ok: false, error: "invalid_sender" };1144        }1145        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {1146          return { ok: false, error: "invalid_webhook_url" };1147        }1148        // LV-3: debounce non-test pings per (webhook, entry) so a page that1149        // strobes focus/fill events can't turn the canary into a request1150        // firehose at the user's endpoint. Test pings are exempt — they are1151        // explicit user clicks in the settings UI and are awaited for1152        // feedback. The FIRST ping in a window always goes out, so the1153        // dead-man's-switch property (canary fires on access) is preserved;1154        // only repeats within the window are coalesced.1155        if (trigger !== "test") {1156          const keyDigest = new Uint8Array(1157            await crypto.subtle.digest(1158              "SHA-256",1159              new TextEncoder().encode(`${webhookUrl}:${entryTitle}`),1160            ),1161          );1162          const keySuffix = Array.from(keyDigest)1163            .map((byte) => byte.toString(16).padStart(2, "0"))1164            .join("");1165          const rlKey = `canary-last-fetch:${keySuffix}`;1166          const legacyRlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;1167          const stored = await chrome.storage.local.get(rlKey);1168          await chrome.storage.local.remove(legacyRlKey);1169          const last = (stored as Record<string, unknown>)[rlKey];1170          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {1171            return { ok: true, data: { rateLimited: true } };1172          }1173          await chrome.storage.local.set({ [rlKey]: Date.now() });1174        }1175        const body = JSON.stringify({1176          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",1177          entry: entryTitle,1178          trigger,1179          timestamp: new Date().toISOString(),1180          source: "peach-extension",1181        });1182        if (trigger === "test") {1183          // Permitted outbound fetch: user-configured canary alert endpoint1184          // (validated by isAllowedCanaryWebhookUrl above). This is the1185          // only non-HIBP outbound call in the extension — see1186          // Projects.md §3.7. Test pings are awaited so the UI can show1187          // success/failure.1188          try {1189            const res = await fetch(webhookUrl, {1190              method: "POST",1191              headers: { "Content-Type": "application/json" },1192              body,1193            });1194            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1195          } catch (err) {1196            return { ok: false, error: err instanceof Error ? err.message : "network_error" };1197          }1198        }1199        // Non-test triggers are fire-and-forget1200        fetch(webhookUrl, {1201          method: "POST",1202          headers: { "Content-Type": "application/json" },1203          body,1204        }).catch(() => {});1205        return { ok: true };1206      }1207      case "ACTIVATE_LICENSE": {1208        const { key } = msg.payload as { key: string };1209        const licenseInfo = await activateLicense(key);1210        return { ok: true, data: licenseInfo };1211      }1212      case "GET_LICENSE": {1213        const licenseInfo = await getLicenseInfo();1214        return { ok: true, data: licenseInfo };1215      }1216      case "GET_LICENSE_KEY": {1217        const key = await getLicenseKey();1218        return { ok: true, data: key };1219      }1220      case "DEACTIVATE_LICENSE": {1221        await deactivateLicense();1222        return { ok: true };1223      }1224      case "SHOULD_PLAY_CELEBRATION": {1225        const should = await shouldPlayCelebration();1226        return { ok: true, data: should };1227      }1228      case "MARK_CELEBRATION_PLAYED": {1229        await markCelebrationPlayed();1230        return { ok: true };1231      }1232      case "GET_CODEX_VAULT_DATA": {1233        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1234        // popup navigates to the License section without further coordination.1235        // Also privileged-page-gated (PB-26-001), and recoveryWords inside the1236        // snapshot additionally require a fresh master-password proof.1237        const gate = await requirePro("codex");1238        if (!gate.allowed) return { ok: false, error: "pro_required" };1239        const { password } = (msg.payload ?? {}) as { password?: string };1240        return await handleGetCodexVaultData(password);1241      }1242      case "ESTIMATE_CODEX_PAGES": {1243        const gate = await requirePro("codex");1244        if (!gate.allowed) return { ok: false, error: "pro_required" };1245        return await handleEstimateCodexPages();1246      }1247      case "RESTORE_FROM_CODEX": {1248        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1249        // be able to restore a vault that was printed by a Pro user.1250        // DO NOT add a Pro gate here.1251        // A decoy session, though, holds no real-mode authority: this path1252        // writes SLOT_A/SLOT_B and snapshots history, so it carries the same1253        // guard its thirteen neighbours do (PB-26-915).1254        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1255        const payload = msg.payload as CodexRestorePayload;1256        return await handleRestoreFromCodex(payload);1257      }1258      case "OPEN_PRO_GATE": {1259        // Content script requests: open popup and navigate to License section.1260        const { feature } = (msg.payload ?? {}) as { feature?: string };1261        if (chrome.storage.session) {1262          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1263        }1264        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1265        return { ok: true };1266      }1267      case "OPEN_POPUP": {1268        // Content script asks to open the trusted extension popup — used by the1269        // inline locked bubble so the master password is entered in the popup,1270        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1271        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1272        // toolbar icon. The badge already signals Peach needs attention.1273        //1274        // Set a session flag so the popup knows it was opened for inline unlock1275        // and should close itself once the vault is unlocked (returning the user1276        // to the inline autofill selector on the page).1277        const { entryId } = (msg.payload ?? {}) as { entryId?: unknown };1278        if (entryId !== undefined && (typeof entryId !== "string" || entryId.length === 0 || entryId.length > 64)) {1279          return { ok: false, error: "invalid_payload" };1280        }1281        if (chrome.storage.session) {1282          if (typeof entryId === "string") {1283            await chrome.storage.session.set({ peach_open_entry: entryId });1284          } else {1285            await chrome.storage.session.set({ peach_inline_unlock: true });1286          }1287        }1288        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1289        return { ok: true };1290      }1291      case "OPEN_DETACHED_POPUP": {1292        // A window created by the action popup and then orphaned with1293        // window.close() is cascaded shut by Chrome, so the file-picker1294        // flows (OS dialogs that dismiss the popup on focus loss) ask the SW1295        // to open the standalone window instead — the SW has no window to be1296        // associated with. The query string is allowlisted so this can never1297        // open an arbitrary URL.1298        const { route } = (msg.payload ?? {}) as { route?: string };1299        const search = route === "peachscript"1300          ? "?restore=peachscript"1301          : route === "csv"1302            ? "?restore=csv"1303            : route === "codex-pdf"1304              ? "?codex=pdf"1305              : null;1306        if (!search) return { ok: false, error: "bad_route" };1307        try {1308          const popupHtml =1309            chrome.runtime.getManifest().action?.default_popup ?? "src/popup/index.html";1310          await chrome.windows.create({1311            url: chrome.runtime.getURL(`${popupHtml}${search}`),1312            type: "popup",1313            width: 320,1314            height: 550,1315          });1316          return { ok: true, data: { detached: true } };1317        } catch {1318          return { ok: false };1319        }1320      }1321      case "GET_IDENTITIES": {1322        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1323        return { ok: true, data: vault.getIdentities() };1324      }1325      case "TOUCH_AUTO_LOCK": {1326        // touchAutoLock() is already called by shouldRefreshAutoLock above;1327        // this case just gives the popup a typed message to keep the session alive.1328        return { ok: true };1329      }1330      case "GET_ADVANCED_HEALTH_REPORT": {1331        const gate = await requirePro("advanced_health");1332        if (!gate.allowed) return { ok: false, error: "pro_required" };1333        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1334        const report = await buildAdvancedHealthReport(vault.getEntries());1335        return { ok: true, data: report };1336      }1337      case "IS_DURESS_ENABLED": {1338        const enabled = await vault.isDuressEnabled();1339        return { ok: true, data: enabled };1340      }1341      case "SETUP_DURESS": {1342        // Single enforcement point for the Duress Vault Pro gate. Free users1343        // who somehow reach this handler are rejected here; the popup also1344        // pre-checks isPro() to avoid showing the setup form to free users,1345        // but server-side is the actual security boundary.1346        const gate = await requirePro("duress_vault");1347        if (!gate.allowed) return { ok: false, error: "pro_required" };1348        // MV3 service workers restart after inactivity, losing the in-memory1349        // derived key. Detect this before calling setupDuress so the popup1350        // can show a meaningful prompt to re-lock and re-unlock.1351        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1352        const { duressPassword } = msg.payload as { duressPassword: string };1353        await vault.setupDuress(duressPassword);1354        return { ok: true };1355      }1356      case "DISABLE_DURESS": {1357        await vault.disableDuress();1358        return { ok: true };1359      }1360      case "VERIFY_MAIN_PASSWORD": {1361        const { password } = msg.payload as { password: string };1362        const ok = await vault.verifyMainPassword(password);1363        return { ok: true, data: ok };1364      }1365      case "CHANGE_PASSWORD": {1366        const { currentPassword, newPassword } = msg.payload as {1367          currentPassword: string;1368          newPassword: string;1369        };1370        const changed = await vault.changePassword(currentPassword, newPassword);1371        return changed1372          ? { ok: true }1373          : { ok: false, error: "incorrect_current_password" };1374      }1375      case "GET_SITE_PASSWORD_POLICY": {1376        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1377        if (!tab?.id) return { ok: true, data: null };1378        try {1379          const response = await chrome.tabs.sendMessage(tab.id, {1380            type: "GET_SITE_PASSWORD_POLICY",1381          });1382          return (response as MessageResponse) ?? { ok: true, data: null };1383        } catch {1384          return { ok: true, data: null };1385        }1386      }1387      case "RECORD_MANUAL_SUMMON": {1388        const { domain } = (msg.payload ?? {}) as { domain?: unknown };1389        const origin = attestedSenderOrigin(sender);1390        let senderDomain: string | null = null;1391        if (origin) {1392          try {1393            const hostname = new URL(origin).hostname;1394            senderDomain = extractDomain(hostname) ?? hostname;1395          } catch {1396            senderDomain = null;1397          }1398        }1399        if (typeof domain !== "string" || domain.length > 253 || domain !== senderDomain) {1400          return { ok: false, error: "invalid_domain" };1401        }1402        const settings = vault.getSettings();1403        const existing = settings.manualSummonDomains?.[domain];1404        const now = Date.now();1405        await vault.updateSettings({1406          manualSummonDomains: {1407            ...settings.manualSummonDomains,1408            [domain]: {1409              firstSummonedAt: existing?.firstSummonedAt ?? now,1410              summonCount: (existing?.summonCount ?? 0) + 1,1411              lastSummonedAt: now,1412            },1413          },1414        });1415        return { ok: true };1416      }1417      case "DECLINE_CARD_SAVE": {1418        // PB-26-108: the declined-card digest is keyed by root-key material, so1419        // a decline cannot be recorded while locked. Offers are not shown while1420        // locked either, so this is unreachable in practice.1421        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1422        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1423        await vault.declineCardSaveOffer(last4, expMonth, expYear);1424        return { ok: true };1425      }1426      case "IS_CARD_DECLINED": {1427        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1428        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1429        return { ok: true, data: declined };1430      }1431      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1432        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1433          rpId?: string;1434          rpName?: string;1435          userName?: string;1436          userDisplayName?: string;1437        };1438        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1439        return await initiateFirefoxPasskeyCreate({1440          rpId,1441          rpName: rpName ?? rpId,1442          userName,1443          userDisplayName,1444        }, attestedSenderOrigin(sender));1445      }14461447      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1448        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1449        if (!payload) return { ok: false, error: "missing_payload" };1450        return await completeFirefoxPasskeyCreate(payload);1451      }14521453      case "PASSKEY_OFFER_DECLINE": {1454        const { domain } = (msg.payload ?? {}) as { domain?: string };1455        const origin = attestedSenderOrigin(sender);1456        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1457        await recordPasskeyOfferDecline(domain);1458        return { ok: true };1459      }14601461      case "GET_PASSKEY_OFFER_DECLINED": {1462        const { domain } = (msg.payload ?? {}) as { domain?: string };1463        const origin = attestedSenderOrigin(sender);1464        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1465        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1466      }14671468      case "PASSKEY_HAS_CREDENTIALS": {1469        const payload = msg.payload as {1470          rpId?: string;1471          allowCredentials?: Array<{ id: string; type?: string }>;1472        } | undefined;1473        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1474        return await handlePasskeyHasCredentials({1475          rpId: payload.rpId,1476          allowCredentials: payload.allowCredentials ?? [],1477        }, attestedSenderOrigin(sender));1478      }14791480      case "PASSKEY_CREATE": {1481        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1482        if (!payload?.rpId || !payload?.userName) {1483          return { ok: false, error: "rpid_and_username_required" };1484        }1485        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1486      }14871488      case "PASSKEY_GET": {1489        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1490        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1491        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1492      }14931494      case "PASSKEY_AUTH_RESPONSE": {1495        const { requestId, approved } = (msg.payload ?? {}) as {1496          requestId?: string | number;1497          approved?: boolean;1498        };1499        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1500          return { ok: false, error: 'requestId and approved required' };1501        }1502        const pending = await getPendingPasskeyRequest();1503        const senderOrigin = attestedSenderOrigin(sender);1504        if (1505          (pending && pending.requestId !== Number(requestId)) ||1506          (pending?.tabId !== undefined && sender.tab?.id !== pending.tabId) ||1507          (pending?.origin !== undefined && senderOrigin !== pending.origin)1508        ) {1509          return { ok: false, error: "invalid_passkey_approval_sender" };1510        }1511        await resolvePendingPasskeyRequest(Number(requestId), approved);1512        return { ok: true };1513      }15141515      case "GET_PASSKEY_FOR_DOMAIN": {1516        const { domain } = (msg.payload ?? {}) as { domain?: string };1517        if (!domain) return { ok: false, error: "domain_required" };1518        // Scope to the caller's own origin: a page may only ask about passkeys1519        // for a domain it actually owns, so an arbitrary page cannot enumerate1520        // which sites the user holds passkeys for or read the username (audit MEDIUM).1521        const origin = attestedSenderOrigin(sender);1522        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1523        if (!vault.isUnlocked()) return { ok: true, data: null };1524        const match = vault1525          .getEntries()1526          .find((entry) => entry.passkey?.rpId === domain);1527        if (!match || !match.passkey) return { ok: true, data: null };1528        // Slim shape — only the fields State 11 needs. Never expose private1529        // key material, even though this is locked behind isUnlocked.1530        // bannerShown is the per-domain "already surfaced" flag, kept in1531        // trusted background session storage so content scripts never touch1532        // chrome.storage.session directly (PB-26-203).1533        let bannerShown = false;1534        if (chrome.storage.session) {1535          const flag = await chrome.storage.session.get(`peach_state11_shown:${domain}`);1536          bannerShown = Boolean((flag as Record<string, unknown>)[`peach_state11_shown:${domain}`]);1537        }1538        return {1539          ok: true,1540          data: {1541            rpId: match.passkey.rpId,1542            userName: match.passkey.userName,1543            browser: match.passkey.browser,1544            bannerShown,1545          },1546        };1547      }15481549      case "MARK_PASSKEY_BANNER_SHOWN": {1550        const { domain } = (msg.payload ?? {}) as { domain?: string };1551        if (typeof domain !== "string" || !domain) return { ok: false, error: "domain_required" };1552        // Same origin binding as the read path: a page may only mark its own1553        // domain, and the flag reveals nothing either way.1554        const origin = attestedSenderOrigin(sender);1555        if (!origin || !isValidRpId(domain, origin)) return { ok: true };1556        if (chrome.storage.session) {1557          await chrome.storage.session.set({ [`peach_state11_shown:${domain}`]: Date.now() });1558        }1559        return { ok: true };1560      }15611562      case "DESTROY_VAULT": {1563        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1564        // storage.local.clear() wipes every Peach key (slots, settings, license,1565        // onboarded flag, history, sync state, declined cards, recall, etc.);1566        // session.clear() wipes pending passkey requests + pro-notice queues.1567        // Caller (Panic.tsx) handles UI navigation back to onboarding.1568        //1569        // The Pro license is the one thing that must survive: the user paid for1570        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1571        // Capture it before the clear and restore it after. peach_pro_celebrated1572        // rides along so the Pro celebration doesn't replay on the next unlock.1573        await vault.withVaultRemoval(async () => {1574          const preserved = await chrome.storage.local.get([1575            "peach_license",1576            "peach_pro_celebrated",1577          ]);1578          await storageClear();1579          await vault.clearVaultHistory();1580          const toRestore: Record<string, unknown> = {};1581          if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1582          if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1583          if (Object.keys(toRestore).length > 0) {1584            await chrome.storage.local.set(toRestore);1585          }1586          if (chrome.storage.session) {1587            await chrome.storage.session.clear();1588          }1589          await clearRecoveryConfirmPending();1590        });1591        return { ok: true };1592      }15931594      case "GET_IDENTITY_SUGGESTIONS": {1595        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1596        const entries = vault.getEntries();1597        const suggestions = buildIdentitySuggestions(entries);1598        return { ok: true, data: { suggestions } };1599      }1600      case "ML_INIT":1601        return { ok: true };16021603      case "ML_PREDICT_BATCH": {1604        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1605        if (!isValidMLFeatureBatch(featuresArray, MAX_ML_BATCH_FIELDS)) {1606          return { ok: false, error: "invalid_payload" };1607        }1608        if (!claimMLWork(sender, featuresArray.length)) {1609          return { ok: false, error: "rate_limited" };1610        }1611        return { ok: true, data: mlPredictBatch(featuresArray) };1612      }16131614      // ── Vault sync (v3) ───────────────────────────────────────────────1615      // Returns the public-facing local identity needed by the popup to1616      // drive Phase-1 audio pairing. The private long-term key never1617      // leaves the background.1618      case "GET_LOCAL_IDENTITY": {1619        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1620        // Pro license from an already-Pro peer (at least one device must be Pro).1621        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1622        // The identity is sealed under its own key rather than derived from the1623        // root, so pairing survives a master-password change (SEV-2-B).1624        const identity: LocalDeviceIdentity & { license?: string } = await buildLocalIdentity();1625        // If this device is Pro, advertise the signed license so the peer can1626        // activate it after SAS confirmation — pairing carries Pro across.1627        if (await isProUser()) {1628          const license = await getLicenseKey();1629          if (license) identity.license = license;1630        }1631        return { ok: true, data: identity };1632      }16331634      case "LIST_PAIRED_DEVICES": {1635        if (vault.isDecoyMode()) return { ok: true, data: { devices: [] } };1636        try {1637          const devices = await listPairedDevicesV3();1638          return { ok: true, data: { devices } };1639        } catch (err) {1640          if (err instanceof TrustDataCorruptedError) {1641            return { ok: false, error: "trust_data_corrupted" };1642          }1643          throw err;1644        }1645      }16461647      case "RENAME_PAIRED_DEVICE": {1648        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1649        const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string };1650        if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") {1651          return { ok: false, error: "invalid_payload" };1652        }1653        await renamePairedDeviceV3(deviceId, name);1654        return { ok: true };1655      }16561657      case "UNPAIR_DEVICE": {1658        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1659        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1660        if (typeof deviceId !== "string" || !deviceId) {1661          return { ok: false, error: "invalid_payload" };1662        }1663        // A damaged legacy identity must not prevent the user from evicting a1664        // peer locally. Sync is already blocked until the secure reset repairs1665        // this installation, so the local issuer marker is sufficient for the1666        // tombstone that will be cleared with the archived generation.1667        let revokedByDeviceId: string;1668        try {1669          revokedByDeviceId = await getOrCreateDeviceId();1670        } catch (error) {1671          if (!(error instanceof Error) || error.message !== "identity_migration_required") throw error;1672          revokedByDeviceId = "local";1673        }1674        await revokeDeviceByIdV3(deviceId, revokedByDeviceId);1675        // PB-26-213: forget the secret now so no further dial can use it.1676        // Removals that happen while locked leave orphans for the next1677        // unlock's reconcile to prune.1678        const unpairRootHex = vault.getRootKeyHex();1679        if (unpairRootHex) {1680          const unpairRoot = unhexBytes(unpairRootHex);1681          try {1682            await dropPairSecret(deviceId, unpairRoot);1683          } finally {1684            unpairRoot.fill(0);1685          }1686        } else {1687          await dropPairSecret(deviceId, null);1688        }1689        // Sync against the remaining hosts — the unpaired device no longer1690        // matters but the next alarm tick is up to ten minutes away.1691        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1692        return { ok: true };1693      }16941695      case "RENAME_LOCAL_DEVICE": {1696        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1697        const { name } = (msg.payload ?? {}) as { name?: string };1698        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1699        await setDeviceNameV3(name);1700        return { ok: true };1701      }17021703      // ── Relay pairing ─────────────────────────────────────────────────────1704      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1705      // session runs in the background; the SAS and the terminal result reach1706      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1707      case "START_ADOPTION_SOURCE": {1708        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1709        if (isRelayAdoptionSourceInFlight()) {1710          return { ok: false, error: "adoption_source_in_progress" };1711        }1712        try {1713          return { ok: true, data: await startRelayAdoptionSource() };1714        } catch (error) {1715          return {1716            ok: false,1717            error: error instanceof Error ? error.message : "adoption_source_failed",1718          };1719        }1720      }17211722      // Onboarding receiver — empty extension shows a QR, phone scans and1723      // sends the vault. The popup supplies the local-only password here so1724      // the background can wrap the adopted root key at rest without ever1725      // asking the user to retype it.1726      case "START_ADOPTION_RECEIVER": {1727        if (isRelayAdoptionSourceInFlight()) {1728          return { ok: false, error: "adoption_receiver_in_progress" };1729        }1730        const password = (msg.payload as { password?: unknown } | undefined)?.password;1731        if (typeof password !== "string" || password.length === 0) {1732          return { ok: false, error: "invalid_payload" };1733        }1734        try {1735          return { ok: true, data: await startRelayAdoptionReceiver(password) };1736        } catch (error) {1737          return {1738            ok: false,1739            error: error instanceof Error ? error.message : "adoption_receiver_failed",1740          };1741        }1742      }17431744      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1745      // on the source's SAS screen. The id round-trips the same way so a stale1746      // late response can't approve the wrong session.1747      case "RECEIVER_SAS_DECISION": {1748        const payload = msg.payload as { id?: unknown; sas?: unknown; ok?: unknown } | undefined;1749        if (typeof payload?.id !== "string" || typeof payload.sas !== "string" || typeof payload.ok !== "boolean") {1750          return { ok: false, error: "invalid_payload" };1751        }1752        return { ok: resolveReceiverSasConfirmation(payload.id, payload.sas, payload.ok) };1753      }17541755      case "SOURCE_SAS_DECISION": {1756        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1757        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1758          return { ok: false, error: "invalid_payload" };1759        }1760        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1761      }1762      case "LIST_PENDING_ADOPTION_HOLDERS": {1763        return { ok: true, data: await listPendingAdoptionHolders() };1764      }17651766      case "REMOVE_PENDING_ADOPTION_HOLDER": {1767        await removePendingAdoptionHolder();1768        return { ok: true };1769      }177017711772      case "CANCEL_ADOPTION_SOURCE": {1773        cancelRelayAdoptionSource();1774        return { ok: true };1775      }17761777      case "TRIGGER_SYNC": {1778        if (vault.isDecoyMode()) return { ok: true };1779        const payload = (msg.payload ?? {}) as {1780          reason?: "vault_change" | "foreground" | "manual";1781          force?: boolean;1782        };1783        const reason = payload.reason ?? "foreground";17841785        void triggerSyncIfReachable({ reason, force: payload.force === true });1786        return { ok: true };1787      }17881789      case "GET_SYNC_STATE": {1790        if (vault.isDecoyMode()) return { ok: true, data: { status: "idle" } };1791        return { ok: true, data: getSyncState() };1792      }17931794      // §11. The generation state carries no secret — it is a version and a1795      // state name — so the panel can read it while the vault is locked.1796      case "GET_SYNC_GENERATION": {1797        return { ok: true, data: await resolveGeneration(browserGenerationIo) };1798      }17991800      case "SECURE_RESET": {1801        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1802        const payload = (msg.payload ?? {}) as { password?: unknown };1803        if (typeof payload.password !== "string" || payload.password.length === 0) {1804          return { ok: false, error: "Enter your master password" };1805        }1806        const wasLocked = !vault.isUnlocked();1807        const passwordValid = wasLocked1808          ? await vault.unlock(payload.password)1809          : await vault.verifyMainPassword(payload.password);1810        if (!passwordValid) {1811          return { ok: false, error: "Incorrect master password" };1812        }1813        if (wasLocked) {1814          await setupAutoLock();1815          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });1816          onVaultUnlocked();1817        }1818        // Identity rotation needs the live vault root key. A password check is1819        // deliberately verification-only, so establish the real session first1820        // when Settings is opened after the vault session expired.1821        // Enter the blocking state before the reset steps: a crash after this1822        // point leaves the device refusing sync rather than mid-reset over live1823        // trust. Both are idempotent, so a retry is safe.1824        await enterResetRequired(browserGenerationIo);1825        const result = await confirmSecureReset(browserGenerationIo, {1826          nowMs: Date.now(),1827        });1828        return result === "V2_ANCHOR"1829          ? { ok: true, data: await resolveGeneration(browserGenerationIo) }1830          : {1831              ok: false,1832              error: "The reset did not complete — nothing was lost, try again",1833            };1834      }18351836      case "GET_SYNC_SETTINGS": {1837        if (vault.isDecoyMode()) return { ok: true, data: { mode: "off", relayUrl: "" } };1838        return { ok: true, data: await getSyncSettings() };1839      }18401841      case "SET_SYNC_SETTINGS": {1842        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1843        const payload = (msg.payload ?? {}) as {1844          mode?: unknown;1845          relayUrl?: unknown;1846        };1847        try {1848          // A custom relay URL implies private mode; Peach's own relay stays1849          // public. See setRelayUrl.1850          if (payload.relayUrl !== undefined) {1851            if (typeof payload.relayUrl !== "string") {1852              return { ok: false, error: "invalid_relay_url" };1853            }1854            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1855          }1856          if (payload.mode !== undefined) {1857            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1858              return { ok: false, error: "invalid_sync_mode" };1859            }1860            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1861          }1862          return { ok: true, data: await getSyncSettings() };1863        } catch (error) {1864          return {1865            ok: false,1866            error: error instanceof Error ? error.message : "invalid_relay_url",1867          };1868        }1869      }187018711872      case "GET_SYNC_ALERTS": {1873        if (vault.isDecoyMode()) return { ok: true, data: [] };1874        return { ok: true, data: await getPendingSyncAlerts() };1875      }18761877      case "DISMISS_SYNC_ALERTS": {1878        if (vault.isDecoyMode()) return { ok: true };1879        const type = (msg.payload as { type?: unknown } | undefined)?.type;1880        if (type !== "DEVICE_KEY_ROTATED" && type !== "DEVICE_REVOKED") {1881          return { ok: false, error: "invalid_sync_alert_type" };1882        }1883        await dismissPendingSyncAlerts(type);1884        return { ok: true };1885      }18861887      case "GET_PENDING_VOUCHED_DEVICES": {1888        if (vault.isDecoyMode()) return { ok: true, data: [] };1889        return { ok: true, data: await listPendingVouchedDevices() };1890      }1891      case "CONFIRM_VOUCHED_DEVICE": {1892        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1893        const { deviceId } = msg.payload as { deviceId: string };1894        const pending = await getPendingVouchedDevice(deviceId);1895        if (!pending) return { ok: false, error: "not_pending" };1896        // Last gate before a vouched device becomes a sync peer. A queue entry1897        // can predate the revocation that names it, so revocation is re-checked1898        // here rather than trusted to have swept the queue.1899        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {1900          await removePendingVouchedDevice(deviceId);1901          return { ok: false, error: "device_revoked" };1902        }1903        await upsertPairedDeviceV3({1904          deviceId: pending.deviceId,1905          deviceName: pending.deviceName,1906          deviceType:1907            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1908          longTermPublicKeyHex: pending.longTermPublicKeyHex,1909          signingPublicKeyHex: pending.signingPublicKeyHex,1910          wsPort: pending.wsPort,1911          pairedAt: pending.pairedAt,1912          trustSource: "vouched",1913        });1914        await removePendingVouchedDevice(deviceId);1915        // Newly confirmed vouched device is now a sync target — kick a round1916        // so the mesh introduction pays off without a 10-minute wait.1917        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1918        return { ok: true };1919      }1920      case "REJECT_VOUCHED_DEVICE": {1921        if (vault.isDecoyMode()) return { ok: true };1922        const { deviceId } = msg.payload as { deviceId: string };1923        await removePendingVouchedDevice(deviceId);1924        return { ok: true };1925      }19261927      case "ROTATE_SYNC_IDENTITY": {1928        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1929        const result = await vault.rotateSyncIdentity();1930        return result.ok ? { ok: true } : { ok: false, error: result.error };1931      }19321933      default:1934        return { ok: false, error: "unknown_message_type" };1935    }1936  } catch (err) {1937    return {1938      ok: false,1939      error: err instanceof Error ? err.message : "operation_failed",1940    };1941  }1942}19431944// Returns username use-counts from the vault, sorted by frequency. Each row1945// also carries the entry's email so the popup can suggest the email/username1946// pair the user has actually used together.1947function buildIdentitySuggestions(1948  entries: VaultEntry[],1949): Array<{ email: string; username: string; count: number }> {1950  const usernameCounts = new Map<string, number>();1951  const usernameEmail = new Map<string, string>();1952  for (const entry of entries) {1953    const username = entry.username ?? "";1954    const email = (entry as VaultEntry & { email?: string }).email ?? "";1955    if (!username && !email) continue;1956    const key = username || email;1957    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1958    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1959  }1960  return Array.from(usernameCounts.entries())1961    .sort((a, b) => b[1] - a[1])1962    .map(([username, count]) => ({1963      email: usernameEmail.get(username) ?? "",1964      username,1965      count,1966    }));1967}19681969/** Notify all content scripts that the vault just became available. */1970function broadcastToContentScripts(message: { type: string }): void {1971  if (!chrome.tabs?.query) return;1972  chrome.tabs.query({}, (tabs) => {1973    for (const tab of tabs) {1974      if (tab.id !== undefined) {1975        chrome.tabs.sendMessage(tab.id, message).catch(() => {1976          // Tab may not have a content script — silently ignore1977        });1978      }1979    }1980  });1981}19821983function shouldRefreshAutoLock(1984  type: MessageType,1985  sender: Partial<chrome.runtime.MessageSender>,1986): boolean {1987  if (!isExtensionPageSender(sender)) return false;1988  return (1989    type !== "HAS_VAULT" &&1990    type !== "IS_UNLOCKED" &&1991    type !== "GET_VAULT_STATUS" &&1992    type !== "LOCK" &&1993    type !== "UPDATE_SETTINGS" &&1994    type !== "GET_PENDING_PASSKEY" &&1995    type !== "GET_PASSKEY_PROVIDER_STATE" &&1996    type !== "DECLINE_CARD_SAVE" &&1997    type !== "IS_CARD_DECLINED" &&1998    type !== "AUTOFILL_QUERY" &&1999    type !== "ML_PREDICT_BATCH"2000  );2001}20022003function isAllowedCanaryWebhookUrl(value: string): boolean {2004  try {2005    const url = new URL(value);2006    if (url.protocol !== "https:") return false;20072008    const hostname = url.hostname.toLowerCase();2009    if (2010      hostname === "localhost" ||2011      hostname.endsWith(".localhost") ||2012      isPrivateIpv4(hostname) ||2013      isPrivateIpv6(hostname)2014    ) {2015      return false;2016    }20172018    return true;2019  } catch {2020    return false;2021  }2022}20232024function isPrivateIpv4(hostname: string): boolean {2025  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {2026    return true;2027  }20282029  const octets = hostname.split(".").map((part) => Number(part));2030  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {2031    return false;2032  }20332034  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;2035}20362037function isPrivateIpv6(hostname: string): boolean {2038  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();2039  // IPv4-mapped IPv6 literals embed a plain IPv4 address that the prefix2040  // list below can never match (WHATWG URL serializes [::ffff:192.168.0.1]2041  // as ::ffff:c0a8:1). Unwrap and test the embedded IPv4; unparseable mapped2042  // tails fail closed. (Codex Security 2026-08-04 LOW,2043  // ssrf.webhook-url-private-ip-filter.) DNS rebinding is out of scope for a2044  // one-shot host check.2045  const mapped = /^::ffff:(.+)$/.exec(normalized);2046  if (mapped) {2047    const tail = mapped[1] ?? "";2048    if (tail.includes(".")) return isPrivateIpv4(tail);2049    const parts = tail.split(":");2050    const [hi, lo] = parts;2051    if (2052      parts.length !== 2 ||2053      !hi ||2054      !lo ||2055      !/^[0-9a-f]{1,4}$/.test(hi) ||2056      !/^[0-9a-f]{1,4}$/.test(lo)2057    ) {2058      return true;2059    }2060    const octets = [2061      (Number.parseInt(hi, 16) >>> 8) & 0xff,2062      Number.parseInt(hi, 16) & 0xff,2063      (Number.parseInt(lo, 16) >>> 8) & 0xff,2064      Number.parseInt(lo, 16) & 0xff,2065    ];2066    return isPrivateIpv4(octets.join("."));2067  }2068  return (2069    normalized === "::1" ||2070    normalized.startsWith("fc") ||2071    normalized.startsWith("fd") ||2072    normalized.startsWith("fe80:")2073  );2074}