messages.ts

83.6 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard, getEffectiveClearSeconds } from "./clipboard";13import { getPendingSyncAlerts, clearPendingSyncAlerts } from "./sync-alerts";14import { extractDomain } from "../shared/domain";15import {16  getPendingVouchedDevice,17  listPendingVouchedDevices,18  removePendingVouchedDevice,19} from "./pending-vouched-devices";20import {21  clearRecoveryConfirmPending,22  isRecoveryConfirmPending,23  setRecoveryConfirmPending,24} from "./recovery-pending";25import { setupAutoLock, touchAutoLock } from "./alarms";26import { runSelfTest } from "./self-test";27import * as vault from "./vault";28import {29  handleEstimateCodexPages,30  handleGetCodexVaultData,31  handleRestoreFromCodex,32} from "./codex-handlers";33import type { CodexRestorePayload } from "../shared/codex-types";34import {35  activateLicense,36  deactivateLicense,37  getLicenseInfo,38  getLicenseKey,39  isProUser,40  markCelebrationPlayed,41  shouldPlayCelebration,42} from "./license";43import {44  completeFirefoxPasskeyCreate,45  getPasskeyProviderState,46  getPendingPasskeyRequest,47  handleFirefoxPasskeyCreate,48  handleFirefoxPasskeyGet,49  handlePasskeyHasCredentials,50  initiateFirefoxPasskeyCreate,51  isPasskeyOfferDeclined,52  onVaultUnlocked,53  recordPasskeyOfferDecline,54  resolvePendingPasskeyRequest,55  setPasskeyProviderEnabled,56} from "./passkey";57import { buildAdvancedHealthReport } from "./health";58import { storageClear } from "../shared/storage";59import { findInvalidWords } from "../shared/recovery-words";60import type {61  Message,62  MessageResponse,63  MessageType,64  ProFeature,65  VaultEntry,66} from "../shared/types";67import { isPasskeyOnly } from "../shared/types";68import { generateTOTP } from "../crypto/totp";69import { isValidRpId } from "../shared/passkey-utils";70import { isValidMLFeatureBatch, predictBatch as mlPredictBatch } from "./ml";71import {72  buildLocalIdentity,73  getOrCreateDeviceId,74  setDeviceName as setDeviceNameV3,75  type LocalDeviceIdentity,76} from "./device-identity";77import {78  isDeviceRevoked,79  listPairedDevices as listPairedDevicesV3,80  renamePairedDevice as renamePairedDeviceV3,81  revokeDeviceById as revokeDeviceByIdV3,82  upsertPairedDevice as upsertPairedDeviceV3,83} from "./paired-devices";84import { dropPairSecret } from "./pair-secrets";85// Sync and pairing are imported statically, never with `await import()`.86// `import()` throws `TypeError: import() is disallowed on87// ServiceWorkerGlobalScope` at runtime in MV3, and Vite's preload helper88// reports the failure through `window.dispatchEvent`, which does not exist in89// a worker either — so the real reason was replaced by "window is not defined"90// and the pairing UI just stopped. scripts/check-sw-static-imports.mjs fails91// the build if a runtime import() reappears anywhere in the worker's graph.92import {93  cancelRelayAdoptionSource,94  isRelayAdoptionSourceInFlight,95  resolveReceiverSasConfirmation,96  resolveSourceSasConfirmation,97  startRelayAdoptionReceiver,98  startRelayAdoptionSource,99} from "./relay-adoption-bg";100import {101  listPendingAdoptionHolders,102  removePendingAdoptionHolder,103} from "./pending-adoption-holder";104import {105  getSyncSettings,106  setRelayUrl,107  setSyncMode,108  type SyncMode,109} from "./sync-settings";110import {111  getSyncState,112  triggerSyncIfReachable,113} from "./sync-trigger";114import { isMessageSenderAllowed } from "./message-policy";115116const SUMMON_CAPABILITY_TTL_MS = 30_000;117type SummonCapability = { tabId: number; frameId: number; origin: string; operation: "inventory" | "fill"; expiresAt: number };118const summonCapabilities = new Map<string, SummonCapability>();119120export function createSummonCapability(tabId: number, origin: string, frameId = 0): string {121  const token = crypto.randomUUID();122  summonCapabilities.set(token, { tabId, frameId, origin, operation: "inventory", expiresAt: Date.now() + SUMMON_CAPABILITY_TTL_MS });123  return token;124}125126function consumeSummonCapability(token: unknown, sender: Partial<chrome.runtime.MessageSender>, operation: "inventory" | "fill"): boolean {127  if (typeof token !== "string") return false;128  const cap = summonCapabilities.get(token);129  if (!cap) return false;130  if (cap.expiresAt <= Date.now()) {131    summonCapabilities.delete(token);132    return false;133  }134  if (sender.tab?.id !== cap.tabId || (sender.frameId ?? 0) !== cap.frameId || attestedSenderOrigin(sender) !== cap.origin) return false;135  if (cap.operation !== operation) return false;136  if (operation === "inventory") cap.operation = "fill";137  else summonCapabilities.delete(token);138  return true;139}140141// Compile-time E2E flag, folded to a literal by Vite's `define` (false in142// every production build — verified in the bundled output). Mirrors the143// create-path bypass in passkey.ts so the Playwright passkey smoke can enable144// the provider without a real Pro licence; the gate is fully intact for users.145declare const __PEACH_E2E_PASSKEYS__: boolean;146const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true;147148function unhexBytes(hex: string): Uint8Array {149  if (hex.length % 2 !== 0) throw new Error("invalid hex");150  const out = new Uint8Array(hex.length / 2);151  for (let i = 0; i < out.length; i++) {152    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);153  }154  return out;155}156157/**158 * The single Pro gate. Every gated handler calls this first; the broadcast159 * lets the popup react (navigate to the License section, highlight the160 * relevant feature). Background never touches the popup view directly —161 * the popup owns navigation. See Projects.md "Pro gate rule".162 */163async function requirePro(164  feature: ProFeature,165  trigger: "user" | "background" = "user"166): Promise<{ allowed: boolean }> {167  if (PASSKEY_E2E_PRO_BYPASS && feature === "passkeys") return { allowed: true };168  if (await isProUser()) return { allowed: true };169170  if (trigger === "user") {171    // User deliberately triggered this feature — redirect the popup immediately.172    chrome.runtime173      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })174      .catch(() => {175        // Popup may be closed — the gate signal is best-effort.176      });177  } else {178    // Background trigger (e.g. passive sync initiation) — no popup is open.179    // Queue a notice so the next popup open shows a soft banner instead of180    // silently failing.181    if (chrome.storage.session) {182      chrome.storage.session183        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })184        .catch(() => {});185    }186  }187188  return { allowed: false };189}190191// LV-3: minimum interval between non-test canary pings per webhook+entry.192const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour193194const PRIVATE_IPV4_RANGES = [195  { prefix: "10." },196  { prefix: "127." },197  { prefix: "169.254." },198  { prefix: "192.168." },199];200201export function setupMessageHandler(): void {202  chrome.runtime.onMessage.addListener(203    (msg: unknown, sender, sendResponse) => {204      if (!isMessage(msg)) {205        sendResponse({ ok: false, error: "invalid_message" });206        return true;207      }208      handleMessage(msg, sender)209        .then(sendResponse)210        .catch((err) =>211          sendResponse({212            ok: false,213            error: err instanceof Error ? err.message : String(err),214          })215        );216      return true;217    }218  );219}220221function isMessage(m: unknown): m is Message {222  return typeof m === "object" && m !== null && "type" in m;223}224225/**226 * The browser-attested origin of the page that originated this message. A web227 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),228 * so every page-driven message arrives via the content-script relay and the229 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a230 * value the page cannot forge. This is the ONLY trustworthy origin for passkey231 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.232 */233function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {234  if (sender.origin) return sender.origin;235  if (sender.url) {236    try { return new URL(sender.url).origin; } catch { return undefined; }237  }238  return undefined;239}240241function isExtensionPageSender(sender: Partial<chrome.runtime.MessageSender>): boolean {242  return sender.url?.startsWith("chrome-extension://") === true ||243    sender.url?.startsWith("moz-extension://") === true;244}245246/** True when the message came from a page frame rather than extension UI. */247function isPageSender(sender: Partial<chrome.runtime.MessageSender>): boolean {248  return !isExtensionPageSender(sender) &&249    (sender.tab !== undefined || sender.url !== undefined);250}251252function entryDomains(url: unknown, additionalUrls: unknown): Set<string> {253  const domains = new Set<string>();254  const primary = typeof url === "string" ? extractDomain(url) : null;255  if (primary) domains.add(primary);256  if (Array.isArray(additionalUrls)) {257    for (const extra of additionalUrls) {258      if (typeof extra !== "string") continue;259      const domain = extractDomain(extra);260      if (domain) domains.add(domain);261    }262  }263  return domains;264}265266/**267 * PB-26-106: the autofill read path re-validates the frame origin against the268 * entry's domains on every request, so an unbound write path would let a269 * content script repoint an entry at its own origin and then read the270 * credential through a read path that is behaving correctly.271 *272 * Creating an entry: a page may only bind it to itself. Mutating one: a page273 * may never GROW the domain set — only shrink it, and never below its own274 * attested origin.275 *276 * Self-binding on mutation was considered and is not enough: the content277 * script on a foreign origin IS the attacker in the reported chain, so letting278 * it attach "its own" origin lets it mint the very capability the read path279 * exists to withhold. The legitimate flow that needs a new domain — the inline280 * "remember this site" toast — therefore asks the popup instead281 * (REQUEST_REMEMBER_SITE), which is an extension page and exempt here.282 *283 * Extension pages are exempt: the popup edits entries for sites it is not on.284 */285function senderMayBindEntryDomains(286  sender: Partial<chrome.runtime.MessageSender>,287  domains: Set<string>,288): boolean {289  if (isExtensionPageSender(sender)) return true;290  const domain = attestedSenderDomain(sender);291  if (domain === null) return false;292  for (const candidate of domains) {293    if (candidate !== domain) return false;294  }295  return true;296}297298function senderMayMutateEntryDomains(299  sender: Partial<chrome.runtime.MessageSender>,300  before: Set<string>,301  after: Set<string>,302): boolean {303  if (isExtensionPageSender(sender)) return true;304  const domain = attestedSenderDomain(sender);305  if (domain === null || !after.has(domain)) return false;306  for (const kept of after) {307    if (!before.has(kept)) return false;308  }309  return true;310}311312/**313 * Null for extension pages (which the callers exempt), for senders with no314 * attested origin at all, and for unparseable frame urls.315 */316function attestedSenderDomain(sender: Partial<chrome.runtime.MessageSender>): string | null {317  if (sender.tab === undefined && sender.url === undefined) return null;318  const origin = attestedSenderOrigin(sender);319  if (!origin) return null;320  try { return extractDomain(new URL(origin).hostname); } catch { return null; }321}322323function patchChangesEntryOrigin(patch: object): boolean {324  return Object.hasOwn(patch, "url") || Object.hasOwn(patch, "additionalUrls");325}326327/** The entry's domain-bearing fields as the patch would leave them. */328function patchedUrlShape(329  patch: object,330  existing: Pick<VaultEntry, "url" | "additionalUrls">,331): { url: unknown; additionalUrls: unknown } {332  const candidate = patch as { url?: unknown; additionalUrls?: unknown };333  return {334    url: Object.hasOwn(patch, "url") ? candidate.url : existing.url,335    additionalUrls: Object.hasOwn(patch, "additionalUrls")336      ? candidate.additionalUrls337      : existing.additionalUrls,338  };339}340// Resolves once restoreFromSession() has run, so handlers see the correct341// post-restore unlock state. entry.ts registers this BEFORE the message342// handler so the onMessage listener is added synchronously at SW startup343// (MV3 requirement) while unlock-dependent handlers still wait for restore.344let restoreReady: Promise<void> = Promise.resolve();345const MAX_ML_BATCH_FIELDS = 128;346const MAX_ML_FIELDS_PER_SECOND = 256;347const mlWorkBySender = new Map<string, { startedAt: number; fields: number }>();348349function claimMLWork(sender: Partial<chrome.runtime.MessageSender>, fields: number): boolean {350  if (fields === 0) return true;351  const now = Date.now();352  for (const [key, value] of mlWorkBySender) {353    if (now - value.startedAt >= 1_000) mlWorkBySender.delete(key);354  }355  const key = `${sender.tab?.id ?? "ui"}:${sender.frameId ?? 0}:${attestedSenderOrigin(sender) ?? "extension"}`;356  const current = mlWorkBySender.get(key);357  if (!current) {358    mlWorkBySender.set(key, { startedAt: now, fields });359    return fields <= MAX_ML_FIELDS_PER_SECOND;360  }361  if (current.fields + fields > MAX_ML_FIELDS_PER_SECOND) return false;362  current.fields += fields;363  return true;364}365366/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */367export function setRestoreReady(p: Promise<unknown>): void {368  restoreReady = p.then(() => undefined, () => undefined);369}370371export async function handleMessage(372  msg: Message,373  sender: Partial<chrome.runtime.MessageSender> = {}374): Promise<MessageResponse> {375  try {376    // Wait for session-restore to finish before reading any unlock/vault state.377    // On a cold SW start the popup's first message arrives while restore is378    // still in flight; without this gate IS_UNLOCKED would report locked (a379    // spurious lock screen) and the storage reads could race. The onMessage380    // listener itself is registered synchronously (entry.ts) so this gate, not381    // listener registration, is what absorbs the cold-start window.382    await restoreReady;383    // Validate sender — only allow messages from our extension pages/scripts.384    // `sender.id` is undefined for messages originating from extension UI385    // (popup/options), which is legitimate; reject only when it is defined386    // and does not match our extension id.387    if (388      sender.id !== undefined &&389      sender.id !== chrome.runtime.id390    ) {391      return { ok: false, error: "invalid_sender" };392    }393394    // PB-26-016: sender authorization is an exhaustive policy, not a395    // hand-maintained privileged denylist. A missing/unknown policy entry or a396    // background-only message fails closed before any handler runs.397    // Extension UI messages may legitimately omit sender.url. Resolve the398    // browser-attested extension origin only when a URL is present; this also399    // keeps test/runtime shims without getURL fail-closed for URL-bearing400    // senders instead of throwing before policy evaluation.401    const extensionOrigin = sender.url && typeof chrome.runtime.getURL === "function"402      ? chrome.runtime.getURL("")403      : "";404    if (!isMessageSenderAllowed(msg.type, sender, chrome.runtime.id, extensionOrigin)) {405      return { ok: false, error: "invalid_sender" };406    }407408    if (shouldRefreshAutoLock(msg.type, sender) && vault.isUnlocked()) {409      touchAutoLock();410    }411412    switch (msg.type) {413      case "CREATE_VAULT": {414        const { password } = msg.payload as { password: string };415        // Refuse to create a vault under an empty master password — the derived416        // key would be publicly known and the at-rest AES-GCM protection void417        // (audit HIGH; the CSV-import path previously passed ""). Length/strength418        // policy lives in the onboarding UI; this is the non-negotiable floor.419        if (typeof password !== "string" || password.length === 0) {420          return { ok: false, error: "invalid_payload" };421        }422        await vault.createVault(password);423        await setupAutoLock();424        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });425        onVaultUnlocked();426        return { ok: true };427      }428      case "CREATE_VAULT_FROM_ROOT_KEY": {429        const { password, rootKeyHex } = (msg.payload ?? {}) as {430          password?: unknown;431          rootKeyHex?: unknown;432        };433        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {434          return { ok: false, error: "invalid_payload" };435        }436437        try {438          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);439          await setupAutoLock();440          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });441          onVaultUnlocked();442          return { ok: true, vaultId };443        } catch (err) {444          return { ok: false, error: err instanceof Error ? err.message : String(err) };445        }446      }447      case "UNLOCK": {448        const { password } = msg.payload as { password: string };449        const ok = await vault.unlock(password);450        if (ok) {451          // KAT: verify the WebCrypto stack is healthy before the user relies on it.452          // Runs after unlock so latency is hidden behind the vault-load time.453          const kat = await runSelfTest();454          if (!kat.ok) {455            console.error("[Peach] Crypto self-test FAILED:", kat.error);456            await vault.lock();457            return { ok: false, error: "self_test_failed" };458          }459          await vault.updateSettings({ pinPreferred: false });460          await setupAutoLock();461          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });462          onVaultUnlocked();463          return { ok: true };464        }465        // Distinguish corruption from wrong password so the popup can offer466        // a history-restore path instead of falsely accusing the user of467        // mistyping (M7/COR-007).468        const failure = vault.consumeLastUnlockFailureReason();469        if (failure) {470          return {471            ok: false,472            error: "vault_corrupted",473            canRestoreFromHistory: true,474          } as MessageResponse;475        }476        return { ok: false };477      }478      case "UNLOCK_WITH_PIN": {479        const { pin } = (msg.payload ?? {}) as { pin?: unknown };480        if (typeof pin !== "string") return { ok: false, error: "invalid_payload" };481        const ok = await vault.unlockWithPin(pin);482        if (!ok) {483          const status = await vault.getPinUnlockStatus();484          if (status.configured && !status.available) {485            return {486              ok: false,487              error: status.attemptsRemaining === 0488                ? "pin_attempts_exceeded"489                : "pin_session_expired",490            };491          }492          return { ok: false };493        }494        const kat = await runSelfTest();495        if (!kat.ok) {496          await vault.lock();497          return { ok: false, error: "self_test_failed" };498        }499        await vault.updateSettings({ pinPreferred: true });500        await setupAutoLock();501        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });502        onVaultUnlocked();503        return { ok: true };504      }505      case "GET_PIN_STATUS":506        return { ok: true, data: await vault.getPinUnlockStatus() };507      case "VALIDATE_RECOVERY_WORDS": {508        const { words } = msg.payload as { words: string[] };509        const invalid = findInvalidWords(words);510        return { ok: true, data: { valid: invalid.length === 0, invalid } };511      }512      case "GET_RECOVERY_WORDS": {513        // Must be unlocked and have recovery set up (vault must be v2.12+).514        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };515        // LV-4: the recovery words re-derive the ROOT KEY — the highest-516        // value secret in the vault. A session unlock (which may be hours517        // old on a shared machine) is not enough; require a fresh password518        // proof, matching the 1Password/Bitwarden pattern for revealing519        // escrow material. EXEMPTION: the create-vault / rotation confirmation520        // window (peach_recovery_pending) shows the words immediately after521        // the user authenticated, and that confirmation UI has no password to522        // resend — skip the re-auth there only.523        if (!(await isRecoveryConfirmPending())) {524          const { password } = (msg.payload ?? {}) as { password?: string };525          if (typeof password !== "string" || !password) {526            return { ok: false, error: "password_required" };527          }528          if (!(await vault.verifyMainPassword(password))) {529            return { ok: false, error: "wrong_password" };530          }531        }532        try {533          const words = await vault.getRecoveryWords();534          return { ok: true, data: words };535        } catch {536          return { ok: false, error: "recovery_not_setup" };537        }538      }539      case "GET_RECOVERY_CONFIRM_PENDING":540        return { ok: true, data: await isRecoveryConfirmPending() };541      case "SET_RECOVERY_CONFIRM_PENDING":542        await setRecoveryConfirmPending();543        return { ok: true };544      case "CLEAR_RECOVERY_CONFIRM_PENDING":545        await clearRecoveryConfirmPending();546        return { ok: true };547      case "RECOVER_WITH_WORDS": {548        // User has lost their password but has their 12 recovery words.549        // We: (1) validate the words, (2) re-encrypt vault with new password.550        const { words, newPassword } = msg.payload as {551          words: string[];552          newPassword: string;553        };554        const stored = await vault.loadSlotA();555        if (!stored) return { ok: false, error: "no_vault" };556        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {557          return { ok: false, error: "recovery_not_setup" };558        }559        // Unwrap the root key from the recovery escrow.560        try {561          await vault.unwrapRootKeyForRecovery(562            stored.recovery_wrapped_root_key,563            stored.recovery_nonce ?? "",564            stored.recovery_tag ?? "",565            stored.recovery_salt,566            words567          );568        } catch {569          return { ok: false, error: "invalid_recovery_words" };570        }571        // Re-key: derive fresh salt + key from new password.572        const newSalt = vault.generateSalt();573        const newKey = await vault.deriveKey(newPassword, newSalt);574        // Re-wrap root key under the new password's derived key so the same575        // recovery words continue to work after the password change.576        await vault.rewrapRootKeyForPassword(newKey);577        // Re-encrypt vault entries with the new key.578        await vault.changePasswordWithNewKey(newSalt, newKey);579        await setupAutoLock();580        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });581        return { ok: true };582      }583      case "LOCK":584        await vault.lock();585        return { ok: true };586      case "IS_UNLOCKED":587        return { ok: true, data: vault.isUnlocked() };588      case "GET_VAULT_STATUS":589        return { ok: true, unlocked: vault.isUnlocked() };590      case "HAS_VAULT":591        return { ok: true, data: await vault.hasVault() };592      case "GET_ENTRIES":593        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };594        return { ok: true, data: vault.getEntries() };595      case "EXPORT_ENTRIES": {596        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };597        const { password } = (msg.payload ?? {}) as { password?: unknown };598        if (typeof password !== "string" || !password) {599          return { ok: false, error: "password_required" };600        }601        if (!(await vault.verifyMainPassword(password))) {602          return { ok: false, error: "wrong_password" };603        }604        return { ok: true, data: vault.getEntries() };605      }606      case "ADD_ENTRY": {607        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };608        const payload = msg.payload;609        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {610          return { ok: false, error: "invalid_payload" };611        }612        // PB-26-106: a page may only create an entry bound to itself. Entries613        // carrying no url have no domain surface to bind, so they are exempt.614        if (isPageSender(sender)) {615          const draft = payload as { url?: unknown; additionalUrls?: unknown };616          const domains = entryDomains(draft.url, draft.additionalUrls);617          if (domains.size > 0 && !senderMayBindEntryDomains(sender, domains)) {618            return { ok: false, error: "origin_binding_required" };619          }620        }621        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);622        return { ok: true, data: entry };623      }624      case "BATCH_ADD_ENTRIES": {625        const payload = msg.payload as { entries?: unknown } | null | undefined;626        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {627          return { ok: false, error: "invalid_payload" };628        }629        if (!Array.isArray(payload.entries)) {630          return { ok: false, error: "invalid_payload" };631        }632        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);633        return { ok: true, data: added };634      }635      case "RESTORE_ENTRIES": {636        const payload = msg.payload as637          | { entries?: unknown; mode?: unknown; settings?: unknown }638          | null639          | undefined;640        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {641          return { ok: false, error: "invalid_payload" };642        }643        if (!Array.isArray(payload.entries)) {644          return { ok: false, error: "invalid_payload" };645        }646        if (payload.mode !== "replace" && payload.mode !== "merge") {647          return { ok: false, error: "invalid_payload" };648        }649        const summary = await vault.restoreEntries(650          payload.entries as Parameters<typeof vault.restoreEntries>[0],651          payload.mode652        );653        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {654          await vault.updateSettings(payload.settings as vault.VaultSettings);655        }656        return { ok: true, data: summary };657      }658      case "CLEAR_VAULT_ENTRIES": {659        await vault.clearVaultEntries("REPLACE_ALL");660        return { ok: true };661      }662      case "GET_VAULT_HISTORY": {663        const snapshots = await vault.getVaultHistory();664        return { ok: true, data: snapshots };665      }666      case "RESTORE_VAULT_SNAPSHOT": {667        const { snapshotId } = msg.payload as { snapshotId: string };668        const result = await vault.restoreVaultSnapshot(snapshotId);669        if (!result.ok) return { ok: false, error: result.error };670        broadcastToContentScripts({ type: "VAULT_LOCKED" });671        return { ok: true };672      }673      case "COUNT_DUPLICATES": {674        return { ok: true, data: vault.countDuplicates() };675      }676      case "DEDUPLICATE_ENTRIES": {677        const removed = await vault.deduplicateEntries();678        return { ok: true, data: removed };679      }680      case "UPDATE_ENTRY": {681        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;682        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {683          return { ok: false, error: "invalid_payload" };684        }685        const { id, patch } = payload;686        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {687          return { ok: false, error: "invalid_payload" };688        }689        const existingEntry = vault.getEntryById(id);690        if (!existingEntry) return { ok: false, error: "entry_not_found" };691        if (patchChangesEntryOrigin(patch) || isPageSender(sender)) {692          const before = entryDomains(existingEntry.url, existingEntry.additionalUrls);693          const after = patchedUrlShape(patch, existingEntry);694          if (!senderMayMutateEntryDomains(695            sender,696            before,697            entryDomains(after.url, after.additionalUrls),698          )) {699            return { ok: false, error: "origin_binding_required" };700          }701        }702        // Single enforcement point for the Canary Entries Pro gate. Only703        // gates the transition into a canary entry — clearing/disabling a704        // canary (`canary: undefined`) is always allowed, so existing705        // canary entries remain manageable.706        const incomingCanary = (patch as { canary?: unknown }).canary;707        if (incomingCanary && typeof incomingCanary === "object") {708          const existing = vault.getEntryById(id);709          if (!existing?.canary) {710            const gate = await requirePro("canary_entry");711            if (!gate.allowed) return { ok: false, error: "pro_required" };712          }713        }714        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);715        return { ok: true };716      }717      case "ADD_ADDITIONAL_URL": {718        const { id, url } = msg.payload as { id: string; url: string };719        const trimmed = typeof url === "string" ? url.trim() : "";720        if (!trimmed) return { ok: false, error: "url_required" };721        const existing = vault.getEntryById(id);722        if (!existing) return { ok: false, error: "entry_not_found" };723        const merged = [...(existing.additionalUrls ?? []), trimmed];724        if (!senderMayMutateEntryDomains(725          sender,726          entryDomains(existing.url, existing.additionalUrls),727          entryDomains(existing.url, merged),728        )) {729          return { ok: false, error: "origin_binding_required" };730        }731        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };732        await vault.updateEntry(id, { additionalUrls: merged });733        return { ok: true };734      }735      case "REQUEST_REMEMBER_SITE": {736        // PB-26-106: growing an entry's domain set needs a decision the page737        // cannot make for itself, so the page asks and the popup confirms. A738        // page may only ask about its own attested origin — otherwise this739        // becomes the same unbound write under a friendlier name.740        const { id, url } = (msg.payload ?? {}) as { id?: unknown; url?: unknown };741        if (typeof id !== "string" || !id) return { ok: false, error: "invalid_payload" };742        const trimmed = typeof url === "string" ? url.trim() : "";743        if (!trimmed) return { ok: false, error: "url_required" };744        if (!senderMayBindEntryDomains(sender, entryDomains(trimmed, undefined))) {745          return { ok: false, error: "origin_binding_required" };746        }747        if (!vault.getEntryById(id)) return { ok: false, error: "entry_not_found" };748        if (chrome.storage.session) {749          await chrome.storage.session.set({ pendingRememberSite: { entryId: id, url: trimmed } });750        }751        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }752        return { ok: true };753      }754      case "DELETE_ENTRY": {755        const { id } = msg.payload as { id: string };756        await vault.deleteEntry(id);757        return { ok: true };758      }759      case "GET_DELETED_ENTRIES":760        return { ok: true, data: vault.getDeletedEntries() };761      case "RESTORE_ENTRY": {762        const { id } = msg.payload as { id: string };763        await vault.restoreEntry(id);764        return { ok: true };765      }766      case "PURGE_ENTRY": {767        const { id } = msg.payload as { id: string };768        await vault.purgeEntry(id);769        return { ok: true };770      }771      case "PURGE_EXPIRED_TRASH": {772        const { retentionMs } = msg.payload as { retentionMs: number };773        const purged = await vault.purgeExpiredTrash(retentionMs);774        return { ok: true, data: purged };775      }776      case "SAVE_NOTE": {777        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };778        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };779        const now = Date.now();780        if (id) {781          const existing = vault.getEntryById(id);782          if (!existing) return { ok: false, error: "not_found" };783          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });784          return { ok: true, data: vault.getEntryById(id) };785        } else {786          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt787          // (EntryDraft omits both), so passing them was the only reason the788          // `as any` cast existed. Dropping them makes the call type-check.789          const entry = await vault.addEntry({790            type: "note",791            title: title || "Untitled",792            notes: body,793          });794          return { ok: true, data: entry };795        }796      }797      case "DELETE_NOTE": {798        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };799        const { id } = msg.payload as { id: string };800        await vault.deleteEntry(id);801        return { ok: true };802      }803      case "GET_NOTES": {804        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };805        const notes = vault.getEntries().filter(806          (e) => e.type === "note" && !e.deletedAt807        );808        return { ok: true, data: notes } as MessageResponse;809      }810      case "SEARCH_VAULT": {811        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };812        // AUD-002: shape-validate the payload before calling string methods.813        // A raw cast lets a malformed message crash the handler with TypeError.814        const { query } = (msg.payload ?? {}) as { query?: unknown };815        if (typeof query !== "string") {816          return { ok: false, error: "invalid_payload" };817        }818        const q = query.toLowerCase();819        const searchResults = vault.getEntries().filter(820          (e) =>821            !e.deletedAt &&822            (e.title.toLowerCase().includes(q) ||823              e.notes?.toLowerCase().includes(q) ||824              e.username?.toLowerCase().includes(q))825        );826        return { ok: true, data: searchResults } as MessageResponse;827      }828      case "AUTOFILL_QUERY": {829        if (!vault.isUnlocked()) {830          return { ok: false, error: "vault_locked" };831        }832        const { domain, kind, capability } = msg.payload as {833          domain: string;834          kind?: "login" | "card" | "totp";835          capability?: string;836        };837        const includeAll = consumeSummonCapability(capability, sender, "inventory");838        if (capability !== undefined && !includeAll) {839          return { ok: false, error: "entry_not_found" };840        }841        // kind="card": return saved cards as compact summaries for the842        // inline card silver platter. Cards are not domain-scoped — every843        // saved card is a candidate on every checkout page — so domain is844        // ignored when kind === "card".845        if (kind === "card") {846          if (!includeAll) return { ok: true, data: [] };847          const cards = vault.getEntries().filter((e) => e.type === "card");848          return {849            ok: true,850            data: cards.map((e) => ({851              id: e.id,852              title: e.cardNickname || e.title,853              cardholderName: e.cardholderName,854              last4: e.last4,855              expMonth: e.expMonth,856              expYear: e.expYear,857              network: e.network,858            })),859          };860        }861        const scopedDomain = isPageSender(sender)862          ? attestedSenderDomain(sender)863          : typeof domain === "string"864            ? extractDomain(domain)865            : null;866        if (!includeAll && !scopedDomain) {867          return isPageSender(sender)868            ? { ok: false, error: "origin_unverified" }869            : { ok: true, data: [] };870        }871        if (kind === "totp") {872          const matches = (873            includeAll874              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")875              : vault.queryDomain(scopedDomain!)876          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));877          return {878            ok: true,879            data: matches.map((e) => ({880              id: e.id,881              title: e.title,882              username: e.username,883              email: e.email,884              url: e.url,885              hasTotp: true,886            })),887          };888        }889        // The inline selector fills username+password into a form. Passkey-890        // only entries have no password to fill; sign-in for those goes891        // through the WebAuthn path instead. Filter them out everywhere so892        // the user doesn't see four "GitHub" rows that mostly do nothing.893        // Notes and cards never belonged here either.894        const matches = (895          includeAll896            ? vault897                .getEntries()898                .filter((entry) => entry.type !== "note" && entry.type !== "card")899            : vault.queryDomain(scopedDomain!)900        ).filter((entry) => !isPasskeyOnly(entry));901        return {902          ok: true,903          data: matches.map((e) =>904            includeAll905              ? {906                  id: e.id,907                  title: e.title,908                  // username/email/url shipped so the inline popup's search909                  // affordance can match on them, not just titles. No secrets910                  // cross the boundary — same shape as the domain-matched911                  // response below minus hasTotp (which the search list912                  // doesn't surface).913                  username: e.username,914                  email: e.email,915                  url: e.url,916                  hasPasskey: e.passkey !== undefined,917                }918              : {919                  id: e.id,920                  title: e.title,921                  username: e.username,922                  email: e.email,923                  url: e.url,924                  hasTotp: Boolean(e.totp),925                  hasPasskey: e.passkey !== undefined,926                }927          ),928        };929      }930      case "GET_ENTRY_FOR_FILL": {931        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };932        const { id, capability } = msg.payload as {933          id: string;934          capability?: string;935        };936        const capabilityAuthorized = capability !== undefined && consumeSummonCapability(capability, sender, "fill");937        const senderDomain = isPageSender(sender) ? attestedSenderDomain(sender) : null;938        if (isPageSender(sender) && !senderDomain) {939          return { ok: false, error: "origin_unverified" };940        }941        const entry = vault.getEntryById(id);942        if (!entry) return { ok: false, error: "entry_not_found" };943944        // MV-1: re-validate the entry against the requesting frame's origin.945        // sender.url / sender.tab.url are browser-attested — a page cannot946        // forge them. PB-26-005: the FRAME url (sender.url) is authoritative947        // for an all_frames content script; the top-frame tab.url would948        // misattribute a cross-origin iframe's request to the top page. When949        // the request does not come from a tab at all (popup surfaces use950        // GET_ENTRY_FOR_EDIT, not this), refuse.951        if (senderDomain && !capabilityAuthorized) {952          if (!entryDomains(entry.url, entry.additionalUrls).has(senderDomain)) {953            // Domain mismatch — refuse silently (no oracle about which ids exist).954            return { ok: false, error: "entry_not_found" };955          }956        }957        // Passkey-only entries (passkey credential, no password) cannot be958        // filled into a form — sign-in goes through the WebAuthn path. A959        // login that ALSO has a passkey is still fillable for its password.960        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };961        // Strip the passkey credential AND the raw base32 TOTP seed from the962        // response. Content scripts never need either: the private key is the963        // authenticator's, and handing over the TOTP seed would let a964        // compromised content script mint valid codes indefinitely (SEV-3-C).965        // Generate the *current* 6-digit code here in the background and send966        // only that, plus the seconds left so the UI can render a countdown.967        // Also drop passwordHistory: filling needs only the *current* password.968        // Handing every past password to a content script during passive969        // autofill on an arbitrary page would widen the blast radius of a970        // compromised page far beyond the one credential being filled.971        const {972          passkey: _strippedPasskey,973          totp: seed,974          totpAlgorithm,975          totpDigits,976          totpPeriod,977          passwordHistory: _ph,978          ...safeEntry979        } = entry;980        let totpCode: string | undefined;981        let totpRemaining: number | undefined;982        if (seed) {983          try {984            // PCH-01-019: honour stored algorithm/digits/period (defaults apply985            // when these are undefined, i.e. RFC-default bare-seed entries).986            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);987            totpCode = generated.code;988            totpRemaining = generated.remaining;989          } catch {990            totpCode = undefined;991          }992        }993        if (isPageSender(sender) && vault.isUnlocked()) touchAutoLock();994        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };995      }996      // Trusted full-entry fetch for extension-owned edit surfaces. Content997      // scripts route editing to the popup and cannot call this message.998      case "GET_ENTRY_FOR_EDIT": {999        if (isPageSender(sender)) return { ok: false, error: "invalid_sender" };1000        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1001        const { id } = msg.payload as { id: string };1002        const entry = vault.getEntryById(id);1003        if (!entry) return { ok: false, error: "entry_not_found" };10041005        const { passkey: _passkey, ...safeEntry } = entry;1006        return { ok: true, data: safeEntry };1007      }1008      case "COPY": {1009        // AUD-002: shape-validate the payload before passing to the clipboard1010        // helper. A raw cast lets a malformed message reach the clipboard API1011        // with a non-string and throw.1012        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {1013          text?: unknown;1014          label?: unknown;1015          alreadyWritten?: unknown;1016        };1017        if (typeof text !== "string" || typeof label !== "string") {1018          return { ok: false, error: "invalid_payload" };1019        }1020        await copyToClipboard(text, label, Boolean(alreadyWritten));1021        return { ok: true, clearSeconds: getEffectiveClearSeconds() };1022      }1023      case "CHECK_ALL_BREACHES": {1024        const allEntries = vault.getEntries();1025        const results: Record<string, number> = {};1026        for (const entry of allEntries) {1027          if (entry.type === "note") continue;1028          if (!entry.password) continue;1029          results[entry.id] = await vault.checkBreach(entry.password);1030          // Small delay — be a good citizen to the HIBP API1031          await new Promise((r) => setTimeout(r, 200));1032        }1033        // Persist any non-zero counts back to entries1034        for (const [id, count] of Object.entries(results)) {1035          const entry = vault.getEntryById(id);1036          if (entry && (entry.breach ?? 0) !== count) {1037            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });1038          }1039        }1040        return { ok: true, data: results };1041      }1042      case "GET_SETTINGS": {1043        const settings = await vault.ensureSettingsLoaded();1044        if (!isPageSender(sender)) return { ok: true, data: settings };10451046        const safeSettings: Pick<vault.VaultSettings, "accentColor" | "theme"> & {1047          manualSummonDomains?: NonNullable<vault.VaultSettings["manualSummonDomains"]>;1048        } = {1049          accentColor: settings.accentColor,1050          theme: settings.theme,1051        };1052        const domain = attestedSenderDomain(sender);1053        const ownSummon = domain ? settings.manualSummonDomains?.[domain] : undefined;1054        if (domain && ownSummon) safeSettings.manualSummonDomains = { [domain]: ownSummon };1055        return { ok: true, data: safeSettings };1056      }1057      case "UPDATE_SETTINGS": {1058        const patch = msg.payload;1059        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {1060          return { ok: false, error: "invalid_payload" };1061        }1062        await vault.updateSettings(patch as vault.VaultSettings);1063        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {1064          await setupAutoLock();1065          if (vault.isUnlocked()) touchAutoLock();1066        }1067        return { ok: true };1068      }1069      case "SETUP_PIN": {1070        const { currentPassword, pin } = (msg.payload ?? {}) as {1071          currentPassword?: unknown;1072          pin?: unknown;1073        };1074        if (typeof currentPassword !== "string" || typeof pin !== "string") {1075          return { ok: false, error: "invalid_payload" };1076        }1077        return (await vault.setupPinUnlock(currentPassword, pin))1078          ? { ok: true }1079          : { ok: false, error: "incorrect_current_password" };1080      }1081      case "DISABLE_PIN": {1082        const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown };1083        if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" };1084        return (await vault.disablePinUnlock(currentPassword))1085          ? { ok: true }1086          : { ok: false, error: "incorrect_current_password" };1087      }1088      case "GET_PENDING_PASSKEY":1089        return { ok: true, data: await getPendingPasskeyRequest() };1090      case "APPROVE_PASSKEY": {1091        const { requestId } = msg.payload as { requestId: number };1092        await resolvePendingPasskeyRequest(requestId, true);1093        return { ok: true };1094      }1095      case "DENY_PASSKEY": {1096        const { requestId } = msg.payload as { requestId: number };1097        await resolvePendingPasskeyRequest(requestId, false);1098        return { ok: true };1099      }1100      case "GET_PASSKEY_PROVIDER_STATE":1101        return { ok: true, data: await getPasskeyProviderState() };1102      case "SET_PASSKEY_PROVIDER_ENABLED": {1103        const { enabled } = msg.payload as { enabled: boolean };1104        // Disabling is always free; gating fires only when a free user is1105        // trying to turn passkey interception on.1106        if (enabled) {1107          const gate = await requirePro("passkeys");1108          if (!gate.allowed) return { ok: false, error: "pro_required" };1109        }1110        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };1111      }1112      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS1113      // endpoint. Intentional product behavior — users configure their own1114      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private1115      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-1116      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to1117      // users that the entry title leaves the device when the canary fires.1118      case "FIRE_CANARY_PING": {1119        // Canary alert fires unconditionally for any entry with canary: true.1120        // The Pro gate only governs creation/flagging of canary entries; once1121        // an entry is flagged, the alert path is a security property and must1122        // never be license-gated.1123        const { webhookUrl, entryTitle, trigger } = msg.payload as {1124          webhookUrl: string;1125          entryTitle: string;1126          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";1127        };1128        if (trigger === "test" && !isExtensionPageSender(sender)) {1129          return { ok: false, error: "invalid_sender" };1130        }1131        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {1132          return { ok: false, error: "invalid_webhook_url" };1133        }1134        // LV-3: debounce non-test pings per (webhook, entry) so a page that1135        // strobes focus/fill events can't turn the canary into a request1136        // firehose at the user's endpoint. Test pings are exempt — they are1137        // explicit user clicks in the settings UI and are awaited for1138        // feedback. The FIRST ping in a window always goes out, so the1139        // dead-man's-switch property (canary fires on access) is preserved;1140        // only repeats within the window are coalesced.1141        if (trigger !== "test") {1142          const keyDigest = new Uint8Array(1143            await crypto.subtle.digest(1144              "SHA-256",1145              new TextEncoder().encode(`${webhookUrl}:${entryTitle}`),1146            ),1147          );1148          const keySuffix = Array.from(keyDigest)1149            .map((byte) => byte.toString(16).padStart(2, "0"))1150            .join("");1151          const rlKey = `canary-last-fetch:${keySuffix}`;1152          const legacyRlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;1153          const stored = await chrome.storage.local.get(rlKey);1154          await chrome.storage.local.remove(legacyRlKey);1155          const last = (stored as Record<string, unknown>)[rlKey];1156          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {1157            return { ok: true, data: { rateLimited: true } };1158          }1159          await chrome.storage.local.set({ [rlKey]: Date.now() });1160        }1161        const body = JSON.stringify({1162          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",1163          entry: entryTitle,1164          trigger,1165          timestamp: new Date().toISOString(),1166          source: "peach-extension",1167        });1168        if (trigger === "test") {1169          // Permitted outbound fetch: user-configured canary alert endpoint1170          // (validated by isAllowedCanaryWebhookUrl above). This is the1171          // only non-HIBP outbound call in the extension — see1172          // Projects.md §3.7. Test pings are awaited so the UI can show1173          // success/failure.1174          try {1175            const res = await fetch(webhookUrl, {1176              method: "POST",1177              headers: { "Content-Type": "application/json" },1178              body,1179            });1180            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1181          } catch (err) {1182            return { ok: false, error: err instanceof Error ? err.message : "network_error" };1183          }1184        }1185        // Non-test triggers are fire-and-forget1186        fetch(webhookUrl, {1187          method: "POST",1188          headers: { "Content-Type": "application/json" },1189          body,1190        }).catch(() => {});1191        return { ok: true };1192      }1193      case "ACTIVATE_LICENSE": {1194        const { key } = msg.payload as { key: string };1195        const licenseInfo = await activateLicense(key);1196        return { ok: true, data: licenseInfo };1197      }1198      case "GET_LICENSE": {1199        const licenseInfo = await getLicenseInfo();1200        return { ok: true, data: licenseInfo };1201      }1202      case "GET_LICENSE_KEY": {1203        const key = await getLicenseKey();1204        return { ok: true, data: key };1205      }1206      case "DEACTIVATE_LICENSE": {1207        await deactivateLicense();1208        return { ok: true };1209      }1210      case "SHOULD_PLAY_CELEBRATION": {1211        const should = await shouldPlayCelebration();1212        return { ok: true, data: should };1213      }1214      case "MARK_CELEBRATION_PLAYED": {1215        await markCelebrationPlayed();1216        return { ok: true };1217      }1218      case "GET_CODEX_VAULT_DATA": {1219        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1220        // popup navigates to the License section without further coordination.1221        // Also privileged-page-gated (PB-26-001), and recoveryWords inside the1222        // snapshot additionally require a fresh master-password proof.1223        const gate = await requirePro("codex");1224        if (!gate.allowed) return { ok: false, error: "pro_required" };1225        const { password } = (msg.payload ?? {}) as { password?: string };1226        return await handleGetCodexVaultData(password);1227      }1228      case "ESTIMATE_CODEX_PAGES": {1229        const gate = await requirePro("codex");1230        if (!gate.allowed) return { ok: false, error: "pro_required" };1231        return await handleEstimateCodexPages();1232      }1233      case "RESTORE_FROM_CODEX": {1234        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1235        // be able to restore a vault that was printed by a Pro user.1236        // DO NOT add a Pro gate here.1237        const payload = msg.payload as CodexRestorePayload;1238        return await handleRestoreFromCodex(payload);1239      }1240      case "OPEN_PRO_GATE": {1241        // Content script requests: open popup and navigate to License section.1242        const { feature } = (msg.payload ?? {}) as { feature?: string };1243        if (chrome.storage.session) {1244          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1245        }1246        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1247        return { ok: true };1248      }1249      case "OPEN_POPUP": {1250        // Content script asks to open the trusted extension popup — used by the1251        // inline locked bubble so the master password is entered in the popup,1252        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1253        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1254        // toolbar icon. The badge already signals Peach needs attention.1255        //1256        // Set a session flag so the popup knows it was opened for inline unlock1257        // and should close itself once the vault is unlocked (returning the user1258        // to the inline autofill selector on the page).1259        const { entryId } = (msg.payload ?? {}) as { entryId?: unknown };1260        if (entryId !== undefined && (typeof entryId !== "string" || entryId.length === 0 || entryId.length > 64)) {1261          return { ok: false, error: "invalid_payload" };1262        }1263        if (chrome.storage.session) {1264          if (typeof entryId === "string") {1265            await chrome.storage.session.set({ peach_open_entry: entryId });1266          } else {1267            await chrome.storage.session.set({ peach_inline_unlock: true });1268          }1269        }1270        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1271        return { ok: true };1272      }1273      case "OPEN_DETACHED_POPUP": {1274        // A window created by the action popup and then orphaned with1275        // window.close() is cascaded shut by Chrome, so the file-picker1276        // flows (OS dialogs that dismiss the popup on focus loss) ask the SW1277        // to open the standalone window instead — the SW has no window to be1278        // associated with. The query string is allowlisted so this can never1279        // open an arbitrary URL.1280        const { route } = (msg.payload ?? {}) as { route?: string };1281        const search = route === "peachscript"1282          ? "?restore=peachscript"1283          : route === "csv"1284            ? "?restore=csv"1285            : route === "codex-pdf"1286              ? "?codex=pdf"1287              : null;1288        if (!search) return { ok: false, error: "bad_route" };1289        try {1290          const popupHtml =1291            chrome.runtime.getManifest().action?.default_popup ?? "src/popup/index.html";1292          await chrome.windows.create({1293            url: chrome.runtime.getURL(`${popupHtml}${search}`),1294            type: "popup",1295            width: 320,1296            height: 550,1297          });1298          return { ok: true, data: { detached: true } };1299        } catch {1300          return { ok: false };1301        }1302      }1303      case "GET_IDENTITIES": {1304        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1305        return { ok: true, data: vault.getIdentities() };1306      }1307      case "TOUCH_AUTO_LOCK": {1308        // touchAutoLock() is already called by shouldRefreshAutoLock above;1309        // this case just gives the popup a typed message to keep the session alive.1310        return { ok: true };1311      }1312      case "GET_ADVANCED_HEALTH_REPORT": {1313        const gate = await requirePro("advanced_health");1314        if (!gate.allowed) return { ok: false, error: "pro_required" };1315        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1316        const report = await buildAdvancedHealthReport(vault.getEntries());1317        return { ok: true, data: report };1318      }1319      case "IS_DURESS_ENABLED": {1320        const enabled = await vault.isDuressEnabled();1321        return { ok: true, data: enabled };1322      }1323      case "SETUP_DURESS": {1324        // Single enforcement point for the Duress Vault Pro gate. Free users1325        // who somehow reach this handler are rejected here; the popup also1326        // pre-checks isPro() to avoid showing the setup form to free users,1327        // but server-side is the actual security boundary.1328        const gate = await requirePro("duress_vault");1329        if (!gate.allowed) return { ok: false, error: "pro_required" };1330        // MV3 service workers restart after inactivity, losing the in-memory1331        // derived key. Detect this before calling setupDuress so the popup1332        // can show a meaningful prompt to re-lock and re-unlock.1333        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1334        const { duressPassword } = msg.payload as { duressPassword: string };1335        await vault.setupDuress(duressPassword);1336        return { ok: true };1337      }1338      case "DISABLE_DURESS": {1339        await vault.disableDuress();1340        return { ok: true };1341      }1342      case "VERIFY_MAIN_PASSWORD": {1343        const { password } = msg.payload as { password: string };1344        const ok = await vault.verifyMainPassword(password);1345        return { ok: true, data: ok };1346      }1347      case "CHANGE_PASSWORD": {1348        const { currentPassword, newPassword } = msg.payload as {1349          currentPassword: string;1350          newPassword: string;1351        };1352        const changed = await vault.changePassword(currentPassword, newPassword);1353        return changed1354          ? { ok: true }1355          : { ok: false, error: "incorrect_current_password" };1356      }1357      case "GET_SITE_PASSWORD_POLICY": {1358        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1359        if (!tab?.id) return { ok: true, data: null };1360        try {1361          const response = await chrome.tabs.sendMessage(tab.id, {1362            type: "GET_SITE_PASSWORD_POLICY",1363          });1364          return (response as MessageResponse) ?? { ok: true, data: null };1365        } catch {1366          return { ok: true, data: null };1367        }1368      }1369      case "RECORD_MANUAL_SUMMON": {1370        const { domain } = (msg.payload ?? {}) as { domain?: unknown };1371        const origin = attestedSenderOrigin(sender);1372        let senderDomain: string | null = null;1373        if (origin) {1374          try {1375            const hostname = new URL(origin).hostname;1376            senderDomain = extractDomain(hostname) ?? hostname;1377          } catch {1378            senderDomain = null;1379          }1380        }1381        if (typeof domain !== "string" || domain.length > 253 || domain !== senderDomain) {1382          return { ok: false, error: "invalid_domain" };1383        }1384        const settings = vault.getSettings();1385        const existing = settings.manualSummonDomains?.[domain];1386        const now = Date.now();1387        await vault.updateSettings({1388          manualSummonDomains: {1389            ...settings.manualSummonDomains,1390            [domain]: {1391              firstSummonedAt: existing?.firstSummonedAt ?? now,1392              summonCount: (existing?.summonCount ?? 0) + 1,1393              lastSummonedAt: now,1394            },1395          },1396        });1397        return { ok: true };1398      }1399      case "DECLINE_CARD_SAVE": {1400        // PB-26-108: the declined-card digest is keyed by root-key material, so1401        // a decline cannot be recorded while locked. Offers are not shown while1402        // locked either, so this is unreachable in practice.1403        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1404        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1405        await vault.declineCardSaveOffer(last4, expMonth, expYear);1406        return { ok: true };1407      }1408      case "IS_CARD_DECLINED": {1409        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1410        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1411        return { ok: true, data: declined };1412      }1413      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1414        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1415          rpId?: string;1416          rpName?: string;1417          userName?: string;1418          userDisplayName?: string;1419        };1420        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1421        return await initiateFirefoxPasskeyCreate({1422          rpId,1423          rpName: rpName ?? rpId,1424          userName,1425          userDisplayName,1426        }, attestedSenderOrigin(sender));1427      }14281429      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1430        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1431        if (!payload) return { ok: false, error: "missing_payload" };1432        return await completeFirefoxPasskeyCreate(payload);1433      }14341435      case "PASSKEY_OFFER_DECLINE": {1436        const { domain } = (msg.payload ?? {}) as { domain?: string };1437        const origin = attestedSenderOrigin(sender);1438        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1439        await recordPasskeyOfferDecline(domain);1440        return { ok: true };1441      }14421443      case "GET_PASSKEY_OFFER_DECLINED": {1444        const { domain } = (msg.payload ?? {}) as { domain?: string };1445        const origin = attestedSenderOrigin(sender);1446        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1447        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1448      }14491450      case "PASSKEY_HAS_CREDENTIALS": {1451        const payload = msg.payload as {1452          rpId?: string;1453          allowCredentials?: Array<{ id: string; type?: string }>;1454        } | undefined;1455        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1456        return await handlePasskeyHasCredentials({1457          rpId: payload.rpId,1458          allowCredentials: payload.allowCredentials ?? [],1459        }, attestedSenderOrigin(sender));1460      }14611462      case "PASSKEY_CREATE": {1463        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1464        if (!payload?.rpId || !payload?.userName) {1465          return { ok: false, error: "rpid_and_username_required" };1466        }1467        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1468      }14691470      case "PASSKEY_GET": {1471        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1472        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1473        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1474      }14751476      case "PASSKEY_AUTH_RESPONSE": {1477        const { requestId, approved } = (msg.payload ?? {}) as {1478          requestId?: string | number;1479          approved?: boolean;1480        };1481        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1482          return { ok: false, error: 'requestId and approved required' };1483        }1484        const pending = await getPendingPasskeyRequest();1485        const senderOrigin = attestedSenderOrigin(sender);1486        if (1487          (pending && pending.requestId !== Number(requestId)) ||1488          (pending?.tabId !== undefined && sender.tab?.id !== pending.tabId) ||1489          (pending?.origin !== undefined && senderOrigin !== pending.origin)1490        ) {1491          return { ok: false, error: "invalid_passkey_approval_sender" };1492        }1493        await resolvePendingPasskeyRequest(Number(requestId), approved);1494        return { ok: true };1495      }14961497      case "GET_PASSKEY_FOR_DOMAIN": {1498        const { domain } = (msg.payload ?? {}) as { domain?: string };1499        if (!domain) return { ok: false, error: "domain_required" };1500        // Scope to the caller's own origin: a page may only ask about passkeys1501        // for a domain it actually owns, so an arbitrary page cannot enumerate1502        // which sites the user holds passkeys for or read the username (audit MEDIUM).1503        const origin = attestedSenderOrigin(sender);1504        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1505        if (!vault.isUnlocked()) return { ok: true, data: null };1506        const match = vault1507          .getEntries()1508          .find((entry) => entry.passkey?.rpId === domain);1509        if (!match || !match.passkey) return { ok: true, data: null };1510        // Slim shape — only the fields State 11 needs. Never expose private1511        // key material, even though this is locked behind isUnlocked.1512        // bannerShown is the per-domain "already surfaced" flag, kept in1513        // trusted background session storage so content scripts never touch1514        // chrome.storage.session directly (PB-26-203).1515        let bannerShown = false;1516        if (chrome.storage.session) {1517          const flag = await chrome.storage.session.get(`peach_state11_shown:${domain}`);1518          bannerShown = Boolean((flag as Record<string, unknown>)[`peach_state11_shown:${domain}`]);1519        }1520        return {1521          ok: true,1522          data: {1523            rpId: match.passkey.rpId,1524            userName: match.passkey.userName,1525            browser: match.passkey.browser,1526            bannerShown,1527          },1528        };1529      }15301531      case "MARK_PASSKEY_BANNER_SHOWN": {1532        const { domain } = (msg.payload ?? {}) as { domain?: string };1533        if (typeof domain !== "string" || !domain) return { ok: false, error: "domain_required" };1534        // Same origin binding as the read path: a page may only mark its own1535        // domain, and the flag reveals nothing either way.1536        const origin = attestedSenderOrigin(sender);1537        if (!origin || !isValidRpId(domain, origin)) return { ok: true };1538        if (chrome.storage.session) {1539          await chrome.storage.session.set({ [`peach_state11_shown:${domain}`]: Date.now() });1540        }1541        return { ok: true };1542      }15431544      case "DESTROY_VAULT": {1545        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1546        // storage.local.clear() wipes every Peach key (slots, settings, license,1547        // onboarded flag, history, sync state, declined cards, recall, etc.);1548        // session.clear() wipes pending passkey requests + pro-notice queues.1549        // Caller (Panic.tsx) handles UI navigation back to onboarding.1550        //1551        // The Pro license is the one thing that must survive: the user paid for1552        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1553        // Capture it before the clear and restore it after. peach_pro_celebrated1554        // rides along so the Pro celebration doesn't replay on the next unlock.1555        const preserved = await chrome.storage.local.get([1556          "peach_license",1557          "peach_pro_celebrated",1558        ]);1559        await vault.lock();1560        await storageClear();1561        await vault.clearVaultHistory();1562        const toRestore: Record<string, unknown> = {};1563        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1564        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1565        if (Object.keys(toRestore).length > 0) {1566          await chrome.storage.local.set(toRestore);1567        }1568        if (chrome.storage.session) {1569          await chrome.storage.session.clear();1570        }1571        await clearRecoveryConfirmPending();1572        return { ok: true };1573      }15741575      case "GET_IDENTITY_SUGGESTIONS": {1576        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1577        const entries = vault.getEntries();1578        const suggestions = buildIdentitySuggestions(entries);1579        return { ok: true, data: { suggestions } };1580      }1581      case "ML_INIT":1582        return { ok: true };15831584      case "ML_PREDICT_BATCH": {1585        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1586        if (!isValidMLFeatureBatch(featuresArray, MAX_ML_BATCH_FIELDS)) {1587          return { ok: false, error: "invalid_payload" };1588        }1589        if (!claimMLWork(sender, featuresArray.length)) {1590          return { ok: false, error: "rate_limited" };1591        }1592        return { ok: true, data: mlPredictBatch(featuresArray) };1593      }15941595      // ── Vault sync (v3) ───────────────────────────────────────────────1596      // Returns the public-facing local identity needed by the popup to1597      // drive Phase-1 audio pairing. The private long-term key never1598      // leaves the background.1599      case "GET_LOCAL_IDENTITY": {1600        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1601        // Pro license from an already-Pro peer (at least one device must be Pro).1602        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1603        // The identity is sealed under its own key rather than derived from the1604        // root, so pairing survives a master-password change (SEV-2-B).1605        const identity: LocalDeviceIdentity & { license?: string } = await buildLocalIdentity();1606        // If this device is Pro, advertise the signed license so the peer can1607        // activate it after SAS confirmation — pairing carries Pro across.1608        if (await isProUser()) {1609          const license = await getLicenseKey();1610          if (license) identity.license = license;1611        }1612        return { ok: true, data: identity };1613      }16141615      case "LIST_PAIRED_DEVICES": {1616        if (vault.isDecoyMode()) return { ok: true, data: { devices: [] } };1617        const devices = await listPairedDevicesV3();1618        return { ok: true, data: { devices } };1619      }16201621      case "RENAME_PAIRED_DEVICE": {1622        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1623        const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string };1624        if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") {1625          return { ok: false, error: "invalid_payload" };1626        }1627        await renamePairedDeviceV3(deviceId, name);1628        return { ok: true };1629      }16301631      case "UNPAIR_DEVICE": {1632        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1633        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1634        if (typeof deviceId !== "string" || !deviceId) {1635          return { ok: false, error: "invalid_payload" };1636        }1637        // Removing a device REVOKES it rather than just dropping the local1638        // row: a plain removal is undone the moment any other peer vouches it1639        // back through a manifest, which is exactly what the relay makes easy.1640        await revokeDeviceByIdV3(deviceId, await getOrCreateDeviceId());1641        // PB-26-213: forget the secret now so no further dial can use it.1642        // Removals that happen while locked leave orphans for the next1643        // unlock's reconcile to prune.1644        const unpairRootHex = vault.getRootKeyHex();1645        if (unpairRootHex) {1646          const unpairRoot = unhexBytes(unpairRootHex);1647          try {1648            await dropPairSecret(deviceId, unpairRoot);1649          } finally {1650            unpairRoot.fill(0);1651          }1652        } else {1653          await dropPairSecret(deviceId, null);1654        }1655        // Sync against the remaining hosts — the unpaired device no longer1656        // matters but the next alarm tick is up to ten minutes away.1657        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1658        return { ok: true };1659      }16601661      case "RENAME_LOCAL_DEVICE": {1662        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1663        const { name } = (msg.payload ?? {}) as { name?: string };1664        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1665        await setDeviceNameV3(name);1666        return { ok: true };1667      }16681669      // ── Relay pairing ─────────────────────────────────────────────────────1670      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1671      // session runs in the background; the SAS and the terminal result reach1672      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1673      case "START_ADOPTION_SOURCE": {1674        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1675        if (isRelayAdoptionSourceInFlight()) {1676          return { ok: false, error: "adoption_source_in_progress" };1677        }1678        try {1679          return { ok: true, data: await startRelayAdoptionSource() };1680        } catch (error) {1681          return {1682            ok: false,1683            error: error instanceof Error ? error.message : "adoption_source_failed",1684          };1685        }1686      }16871688      // Onboarding receiver — empty extension shows a QR, phone scans and1689      // sends the vault. The popup supplies the local-only password here so1690      // the background can wrap the adopted root key at rest without ever1691      // asking the user to retype it.1692      case "START_ADOPTION_RECEIVER": {1693        if (isRelayAdoptionSourceInFlight()) {1694          return { ok: false, error: "adoption_receiver_in_progress" };1695        }1696        const password = (msg.payload as { password?: unknown } | undefined)?.password;1697        if (typeof password !== "string" || password.length === 0) {1698          return { ok: false, error: "invalid_payload" };1699        }1700        try {1701          return { ok: true, data: await startRelayAdoptionReceiver(password) };1702        } catch (error) {1703          return {1704            ok: false,1705            error: error instanceof Error ? error.message : "adoption_receiver_failed",1706          };1707        }1708      }17091710      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1711      // on the source's SAS screen. The id round-trips the same way so a stale1712      // late response can't approve the wrong session.1713      case "RECEIVER_SAS_DECISION": {1714        const payload = msg.payload as { id?: unknown; sas?: unknown; ok?: unknown } | undefined;1715        if (typeof payload?.id !== "string" || typeof payload.sas !== "string" || typeof payload.ok !== "boolean") {1716          return { ok: false, error: "invalid_payload" };1717        }1718        return { ok: resolveReceiverSasConfirmation(payload.id, payload.sas, payload.ok) };1719      }17201721      case "SOURCE_SAS_DECISION": {1722        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1723        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1724          return { ok: false, error: "invalid_payload" };1725        }1726        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1727      }1728      case "LIST_PENDING_ADOPTION_HOLDERS": {1729        return { ok: true, data: await listPendingAdoptionHolders() };1730      }17311732      case "REMOVE_PENDING_ADOPTION_HOLDER": {1733        await removePendingAdoptionHolder();1734        return { ok: true };1735      }173617371738      case "CANCEL_ADOPTION_SOURCE": {1739        cancelRelayAdoptionSource();1740        return { ok: true };1741      }17421743      case "TRIGGER_SYNC": {1744        if (vault.isDecoyMode()) return { ok: true };1745        const payload = (msg.payload ?? {}) as {1746          reason?: "vault_change" | "foreground" | "manual";1747          force?: boolean;1748        };1749        const reason = payload.reason ?? "foreground";17501751        void triggerSyncIfReachable({ reason, force: payload.force === true });1752        return { ok: true };1753      }17541755      case "GET_SYNC_STATE": {1756        if (vault.isDecoyMode()) return { ok: true, data: { status: "idle" } };1757        return { ok: true, data: getSyncState() };1758      }17591760      case "GET_SYNC_SETTINGS": {1761        if (vault.isDecoyMode()) return { ok: true, data: { mode: "off", relayUrl: "" } };1762        return { ok: true, data: await getSyncSettings() };1763      }17641765      case "SET_SYNC_SETTINGS": {1766        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1767        const payload = (msg.payload ?? {}) as {1768          mode?: unknown;1769          relayUrl?: unknown;1770        };1771        try {1772          // A custom relay URL implies private mode; Peach's own relay stays1773          // public. See setRelayUrl.1774          if (payload.relayUrl !== undefined) {1775            if (typeof payload.relayUrl !== "string") {1776              return { ok: false, error: "invalid_relay_url" };1777            }1778            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1779          }1780          if (payload.mode !== undefined) {1781            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1782              return { ok: false, error: "invalid_sync_mode" };1783            }1784            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1785          }1786          return { ok: true, data: await getSyncSettings() };1787        } catch (error) {1788          return {1789            ok: false,1790            error: error instanceof Error ? error.message : "invalid_relay_url",1791          };1792        }1793      }179417951796      case "GET_SYNC_ALERTS": {1797        if (vault.isDecoyMode()) return { ok: true, data: [] };1798        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1799        const alerts = await getPendingSyncAlerts();1800        // The popup reads on open and acknowledges with consume:true after1801        // rendering, so a popup crash between read and render doesn't lose1802        // the alerts.1803        if (consume) await clearPendingSyncAlerts();1804        return { ok: true, data: alerts };1805      }18061807      case "GET_PENDING_VOUCHED_DEVICES": {1808        if (vault.isDecoyMode()) return { ok: true, data: [] };1809        return { ok: true, data: await listPendingVouchedDevices() };1810      }1811      case "CONFIRM_VOUCHED_DEVICE": {1812        if (vault.isDecoyMode()) return { ok: false, error: "vault_locked" };1813        const { deviceId } = msg.payload as { deviceId: string };1814        const pending = await getPendingVouchedDevice(deviceId);1815        if (!pending) return { ok: false, error: "not_pending" };1816        // Last gate before a vouched device becomes a sync peer. A queue entry1817        // can predate the revocation that names it, so revocation is re-checked1818        // here rather than trusted to have swept the queue.1819        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {1820          await removePendingVouchedDevice(deviceId);1821          return { ok: false, error: "device_revoked" };1822        }1823        await upsertPairedDeviceV3({1824          deviceId: pending.deviceId,1825          deviceName: pending.deviceName,1826          deviceType:1827            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1828          longTermPublicKeyHex: pending.longTermPublicKeyHex,1829          signingPublicKeyHex: pending.signingPublicKeyHex,1830          wsPort: pending.wsPort,1831          pairedAt: pending.pairedAt,1832          trustSource: "vouched",1833        });1834        await removePendingVouchedDevice(deviceId);1835        // Newly confirmed vouched device is now a sync target — kick a round1836        // so the mesh introduction pays off without a 10-minute wait.1837        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1838        return { ok: true };1839      }1840      case "REJECT_VOUCHED_DEVICE": {1841        if (vault.isDecoyMode()) return { ok: true };1842        const { deviceId } = msg.payload as { deviceId: string };1843        await removePendingVouchedDevice(deviceId);1844        return { ok: true };1845      }18461847      case "ROTATE_SYNC_IDENTITY": {1848        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1849        const result = await vault.rotateSyncIdentity();1850        return result.ok ? { ok: true } : { ok: false, error: result.error };1851      }18521853      default:1854        return { ok: false, error: "unknown_message_type" };1855    }1856  } catch (err) {1857    return {1858      ok: false,1859      error: err instanceof Error ? err.message : "operation_failed",1860    };1861  }1862}18631864// Returns username use-counts from the vault, sorted by frequency. Each row1865// also carries the entry's email so the popup can suggest the email/username1866// pair the user has actually used together.1867function buildIdentitySuggestions(1868  entries: VaultEntry[],1869): Array<{ email: string; username: string; count: number }> {1870  const usernameCounts = new Map<string, number>();1871  const usernameEmail = new Map<string, string>();1872  for (const entry of entries) {1873    const username = entry.username ?? "";1874    const email = (entry as VaultEntry & { email?: string }).email ?? "";1875    if (!username && !email) continue;1876    const key = username || email;1877    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1878    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1879  }1880  return Array.from(usernameCounts.entries())1881    .sort((a, b) => b[1] - a[1])1882    .map(([username, count]) => ({1883      email: usernameEmail.get(username) ?? "",1884      username,1885      count,1886    }));1887}18881889/** Notify all content scripts that the vault just became available. */1890function broadcastToContentScripts(message: { type: string }): void {1891  if (!chrome.tabs?.query) return;1892  chrome.tabs.query({}, (tabs) => {1893    for (const tab of tabs) {1894      if (tab.id !== undefined) {1895        chrome.tabs.sendMessage(tab.id, message).catch(() => {1896          // Tab may not have a content script — silently ignore1897        });1898      }1899    }1900  });1901}19021903function shouldRefreshAutoLock(1904  type: MessageType,1905  sender: Partial<chrome.runtime.MessageSender>,1906): boolean {1907  if (!isExtensionPageSender(sender)) return false;1908  return (1909    type !== "HAS_VAULT" &&1910    type !== "IS_UNLOCKED" &&1911    type !== "GET_VAULT_STATUS" &&1912    type !== "LOCK" &&1913    type !== "UPDATE_SETTINGS" &&1914    type !== "GET_PENDING_PASSKEY" &&1915    type !== "GET_PASSKEY_PROVIDER_STATE" &&1916    type !== "DECLINE_CARD_SAVE" &&1917    type !== "IS_CARD_DECLINED" &&1918    type !== "AUTOFILL_QUERY" &&1919    type !== "ML_PREDICT_BATCH"1920  );1921}19221923function isAllowedCanaryWebhookUrl(value: string): boolean {1924  try {1925    const url = new URL(value);1926    if (url.protocol !== "https:") return false;19271928    const hostname = url.hostname.toLowerCase();1929    if (1930      hostname === "localhost" ||1931      hostname.endsWith(".localhost") ||1932      isPrivateIpv4(hostname) ||1933      isPrivateIpv6(hostname)1934    ) {1935      return false;1936    }19371938    return true;1939  } catch {1940    return false;1941  }1942}19431944function isPrivateIpv4(hostname: string): boolean {1945  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1946    return true;1947  }19481949  const octets = hostname.split(".").map((part) => Number(part));1950  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1951    return false;1952  }19531954  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1955}19561957function isPrivateIpv6(hostname: string): boolean {1958  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1959  // IPv4-mapped IPv6 literals embed a plain IPv4 address that the prefix1960  // list below can never match (WHATWG URL serializes [::ffff:192.168.0.1]1961  // as ::ffff:c0a8:1). Unwrap and test the embedded IPv4; unparseable mapped1962  // tails fail closed. (Codex Security 2026-08-04 LOW,1963  // ssrf.webhook-url-private-ip-filter.) DNS rebinding is out of scope for a1964  // one-shot host check.1965  const mapped = /^::ffff:(.+)$/.exec(normalized);1966  if (mapped) {1967    const tail = mapped[1] ?? "";1968    if (tail.includes(".")) return isPrivateIpv4(tail);1969    const parts = tail.split(":");1970    const [hi, lo] = parts;1971    if (1972      parts.length !== 2 ||1973      !hi ||1974      !lo ||1975      !/^[0-9a-f]{1,4}$/.test(hi) ||1976      !/^[0-9a-f]{1,4}$/.test(lo)1977    ) {1978      return true;1979    }1980    const octets = [1981      (Number.parseInt(hi, 16) >>> 8) & 0xff,1982      Number.parseInt(hi, 16) & 0xff,1983      (Number.parseInt(lo, 16) >>> 8) & 0xff,1984      Number.parseInt(lo, 16) & 0xff,1985    ];1986    return isPrivateIpv4(octets.join("."));1987  }1988  return (1989    normalized === "::1" ||1990    normalized.startsWith("fc") ||1991    normalized.startsWith("fd") ||1992    normalized.startsWith("fe80:")1993  );1994}