messages.ts

80.3 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard, getEffectiveClearSeconds } from "./clipboard";13import { getPendingSyncAlerts, clearPendingSyncAlerts } from "./sync-alerts";14import { extractDomain } from "../shared/domain";15import {16  getPendingVouchedDevice,17  listPendingVouchedDevices,18  removePendingVouchedDevice,19} from "./pending-vouched-devices";20import {21  clearRecoveryConfirmPending,22  isRecoveryConfirmPending,23  setRecoveryConfirmPending,24} from "./recovery-pending";25import { setupAutoLock, touchAutoLock } from "./alarms";26import { runSelfTest } from "./self-test";27import * as vault from "./vault";28import {29  handleEstimateCodexPages,30  handleGetCodexVaultData,31  handleRestoreFromCodex,32} from "./codex-handlers";33import type { CodexRestorePayload } from "../shared/codex-types";34import {35  activateLicense,36  deactivateLicense,37  getLicenseInfo,38  getLicenseKey,39  isProUser,40  markCelebrationPlayed,41  shouldPlayCelebration,42} from "./license";43import {44  completeFirefoxPasskeyCreate,45  getPasskeyProviderState,46  getPendingPasskeyRequest,47  handleFirefoxPasskeyCreate,48  handleFirefoxPasskeyGet,49  handlePasskeyHasCredentials,50  initiateFirefoxPasskeyCreate,51  isPasskeyOfferDeclined,52  onVaultUnlocked,53  recordPasskeyOfferDecline,54  resolvePendingPasskeyRequest,55  setPasskeyProviderEnabled,56} from "./passkey";57import { buildAdvancedHealthReport } from "./health";58import { storageClear } from "../shared/storage";59import { findInvalidWords } from "../shared/recovery-words";60import type {61  Message,62  MessageResponse,63  MessageType,64  ProFeature,65  VaultEntry,66} from "../shared/types";67import { isPasskeyOnly } from "../shared/types";68import { generateTOTP } from "../crypto/totp";69import { isValidRpId } from "../shared/passkey-utils";70import { predictBatch as mlPredictBatch } from "./ml";71import type { MLFieldFeatures } from "../shared/ml";72import {73  buildLocalIdentity,74  getOrCreateDeviceId,75  setDeviceName as setDeviceNameV3,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  resolveSourceSasConfirmation,96  startRelayAdoptionReceiver,97  startRelayAdoptionSource,98} from "./relay-adoption-bg";99import {100  getSyncSettings,101  setRelayUrl,102  setSyncMode,103  type SyncMode,104} from "./sync-settings";105import {106  getSyncState,107  triggerSyncIfReachable,108} from "./sync-trigger";109import { isMessageSenderAllowed } from "./message-policy";110111const SUMMON_CAPABILITY_TTL_MS = 30_000;112type SummonCapability = { tabId: number; frameId: number; origin: string; operation: "inventory" | "fill"; expiresAt: number };113const summonCapabilities = new Map<string, SummonCapability>();114115export function createSummonCapability(tabId: number, origin: string, frameId = 0): string {116  const token = crypto.randomUUID();117  summonCapabilities.set(token, { tabId, frameId, origin, operation: "inventory", expiresAt: Date.now() + SUMMON_CAPABILITY_TTL_MS });118  return token;119}120121function consumeSummonCapability(token: unknown, sender: Partial<chrome.runtime.MessageSender>, operation: "inventory" | "fill"): boolean {122  if (typeof token !== "string") return false;123  const cap = summonCapabilities.get(token);124  if (!cap) return false;125  if (cap.expiresAt <= Date.now()) {126    summonCapabilities.delete(token);127    return false;128  }129  if (sender.tab?.id !== cap.tabId || (sender.frameId ?? 0) !== cap.frameId || attestedSenderOrigin(sender) !== cap.origin) return false;130  if (cap.operation !== operation) return false;131  if (operation === "inventory") cap.operation = "fill";132  else summonCapabilities.delete(token);133  return true;134}135136// Compile-time E2E flag, folded to a literal by Vite's `define` (false in137// every production build — verified in the bundled output). Mirrors the138// create-path bypass in passkey.ts so the Playwright passkey smoke can enable139// the provider without a real Pro licence; the gate is fully intact for users.140declare const __PEACH_E2E_PASSKEYS__: boolean;141const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true;142143function unhexBytes(hex: string): Uint8Array {144  if (hex.length % 2 !== 0) throw new Error("invalid hex");145  const out = new Uint8Array(hex.length / 2);146  for (let i = 0; i < out.length; i++) {147    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);148  }149  return out;150}151152/**153 * The single Pro gate. Every gated handler calls this first; the broadcast154 * lets the popup react (navigate to the License section, highlight the155 * relevant feature). Background never touches the popup view directly —156 * the popup owns navigation. See Projects.md "Pro gate rule".157 */158async function requirePro(159  feature: ProFeature,160  trigger: "user" | "background" = "user"161): Promise<{ allowed: boolean }> {162  if (PASSKEY_E2E_PRO_BYPASS && feature === "passkeys") return { allowed: true };163  if (await isProUser()) return { allowed: true };164165  if (trigger === "user") {166    // User deliberately triggered this feature — redirect the popup immediately.167    chrome.runtime168      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })169      .catch(() => {170        // Popup may be closed — the gate signal is best-effort.171      });172  } else {173    // Background trigger (e.g. passive sync initiation) — no popup is open.174    // Queue a notice so the next popup open shows a soft banner instead of175    // silently failing.176    if (chrome.storage.session) {177      chrome.storage.session178        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })179        .catch(() => {});180    }181  }182183  return { allowed: false };184}185186// LV-3: minimum interval between non-test canary pings per webhook+entry.187const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour188189const PRIVATE_IPV4_RANGES = [190  { prefix: "10." },191  { prefix: "127." },192  { prefix: "169.254." },193  { prefix: "192.168." },194];195196export function setupMessageHandler(): void {197  chrome.runtime.onMessage.addListener(198    (msg: unknown, sender, sendResponse) => {199      if (!isMessage(msg)) {200        sendResponse({ ok: false, error: "invalid_message" });201        return true;202      }203      handleMessage(msg, sender)204        .then(sendResponse)205        .catch((err) =>206          sendResponse({207            ok: false,208            error: err instanceof Error ? err.message : String(err),209          })210        );211      return true;212    }213  );214}215216function isMessage(m: unknown): m is Message {217  return typeof m === "object" && m !== null && "type" in m;218}219220/**221 * The browser-attested origin of the page that originated this message. A web222 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),223 * so every page-driven message arrives via the content-script relay and the224 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a225 * value the page cannot forge. This is the ONLY trustworthy origin for passkey226 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.227 */228function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {229  if (sender.origin) return sender.origin;230  if (sender.url) {231    try { return new URL(sender.url).origin; } catch { return undefined; }232  }233  return undefined;234}235236function isExtensionPageSender(sender: Partial<chrome.runtime.MessageSender>): boolean {237  return sender.url?.startsWith("chrome-extension://") === true ||238    sender.url?.startsWith("moz-extension://") === true;239}240241/** True when the message came from a page frame rather than extension UI. */242function isPageSender(sender: Partial<chrome.runtime.MessageSender>): boolean {243  return !isExtensionPageSender(sender) &&244    (sender.tab !== undefined || sender.url !== undefined);245}246247function entryDomains(url: unknown, additionalUrls: unknown): Set<string> {248  const domains = new Set<string>();249  const primary = typeof url === "string" ? extractDomain(url) : null;250  if (primary) domains.add(primary);251  if (Array.isArray(additionalUrls)) {252    for (const extra of additionalUrls) {253      if (typeof extra !== "string") continue;254      const domain = extractDomain(extra);255      if (domain) domains.add(domain);256    }257  }258  return domains;259}260261/**262 * PB-26-106: the autofill read path re-validates the frame origin against the263 * entry's domains on every request, so an unbound write path would let a264 * content script repoint an entry at its own origin and then read the265 * credential through a read path that is behaving correctly.266 *267 * Creating an entry: a page may only bind it to itself. Mutating one: a page268 * may never GROW the domain set — only shrink it, and never below its own269 * attested origin.270 *271 * Self-binding on mutation was considered and is not enough: the content272 * script on a foreign origin IS the attacker in the reported chain, so letting273 * it attach "its own" origin lets it mint the very capability the read path274 * exists to withhold. The legitimate flow that needs a new domain — the inline275 * "remember this site" toast — therefore asks the popup instead276 * (REQUEST_REMEMBER_SITE), which is an extension page and exempt here.277 *278 * Extension pages are exempt: the popup edits entries for sites it is not on.279 */280function senderMayBindEntryDomains(281  sender: Partial<chrome.runtime.MessageSender>,282  domains: Set<string>,283): boolean {284  if (isExtensionPageSender(sender)) return true;285  const domain = attestedSenderDomain(sender);286  if (domain === null) return false;287  for (const candidate of domains) {288    if (candidate !== domain) return false;289  }290  return true;291}292293function senderMayMutateEntryDomains(294  sender: Partial<chrome.runtime.MessageSender>,295  before: Set<string>,296  after: Set<string>,297): boolean {298  if (isExtensionPageSender(sender)) return true;299  const domain = attestedSenderDomain(sender);300  if (domain === null || !after.has(domain)) return false;301  for (const kept of after) {302    if (!before.has(kept)) return false;303  }304  return true;305}306307/**308 * Null for extension pages (which the callers exempt), for senders with no309 * attested origin at all, and for unparseable frame urls.310 */311function attestedSenderDomain(sender: Partial<chrome.runtime.MessageSender>): string | null {312  if (sender.tab === undefined && sender.url === undefined) return null;313  const origin = attestedSenderOrigin(sender);314  if (!origin) return null;315  try { return extractDomain(new URL(origin).hostname); } catch { return null; }316}317318function patchChangesEntryOrigin(patch: object): boolean {319  return Object.hasOwn(patch, "url") || Object.hasOwn(patch, "additionalUrls");320}321322/** The entry's domain-bearing fields as the patch would leave them. */323function patchedUrlShape(324  patch: object,325  existing: Pick<VaultEntry, "url" | "additionalUrls">,326): { url: unknown; additionalUrls: unknown } {327  const candidate = patch as { url?: unknown; additionalUrls?: unknown };328  return {329    url: Object.hasOwn(patch, "url") ? candidate.url : existing.url,330    additionalUrls: Object.hasOwn(patch, "additionalUrls")331      ? candidate.additionalUrls332      : existing.additionalUrls,333  };334}335// Resolves once restoreFromSession() has run, so handlers see the correct336// post-restore unlock state. entry.ts registers this BEFORE the message337// handler so the onMessage listener is added synchronously at SW startup338// (MV3 requirement) while unlock-dependent handlers still wait for restore.339let restoreReady: Promise<void> = Promise.resolve();340341/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */342export function setRestoreReady(p: Promise<unknown>): void {343  restoreReady = p.then(() => undefined, () => undefined);344}345346export async function handleMessage(347  msg: Message,348  sender: Partial<chrome.runtime.MessageSender> = {}349): Promise<MessageResponse> {350  try {351    // Wait for session-restore to finish before reading any unlock/vault state.352    // On a cold SW start the popup's first message arrives while restore is353    // still in flight; without this gate IS_UNLOCKED would report locked (a354    // spurious lock screen) and the storage reads could race. The onMessage355    // listener itself is registered synchronously (entry.ts) so this gate, not356    // listener registration, is what absorbs the cold-start window.357    await restoreReady;358    // Validate sender — only allow messages from our extension pages/scripts.359    // `sender.id` is undefined for messages originating from extension UI360    // (popup/options), which is legitimate; reject only when it is defined361    // and does not match our extension id.362    if (363      sender.id !== undefined &&364      sender.id !== chrome.runtime.id365    ) {366      return { ok: false, error: "invalid_sender" };367    }368369    // PB-26-016: sender authorization is an exhaustive policy, not a370    // hand-maintained privileged denylist. A missing/unknown policy entry or a371    // background-only message fails closed before any handler runs.372    // Extension UI messages may legitimately omit sender.url. Resolve the373    // browser-attested extension origin only when a URL is present; this also374    // keeps test/runtime shims without getURL fail-closed for URL-bearing375    // senders instead of throwing before policy evaluation.376    const extensionOrigin = sender.url && typeof chrome.runtime.getURL === "function"377      ? chrome.runtime.getURL("")378      : "";379    if (!isMessageSenderAllowed(msg.type, sender, chrome.runtime.id, extensionOrigin)) {380      return { ok: false, error: "invalid_sender" };381    }382383    if (shouldRefreshAutoLock(msg.type, sender) && vault.isUnlocked()) {384      touchAutoLock();385    }386387    switch (msg.type) {388      case "CREATE_VAULT": {389        const { password } = msg.payload as { password: string };390        // Refuse to create a vault under an empty master password — the derived391        // key would be publicly known and the at-rest AES-GCM protection void392        // (audit HIGH; the CSV-import path previously passed ""). Length/strength393        // policy lives in the onboarding UI; this is the non-negotiable floor.394        if (typeof password !== "string" || password.length === 0) {395          return { ok: false, error: "invalid_payload" };396        }397        await vault.createVault(password);398        await setupAutoLock();399        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });400        onVaultUnlocked();401        return { ok: true };402      }403      case "CREATE_VAULT_FROM_ROOT_KEY": {404        const { password, rootKeyHex } = (msg.payload ?? {}) as {405          password?: unknown;406          rootKeyHex?: unknown;407        };408        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {409          return { ok: false, error: "invalid_payload" };410        }411412        try {413          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);414          await setupAutoLock();415          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });416          onVaultUnlocked();417          return { ok: true, vaultId };418        } catch (err) {419          return { ok: false, error: err instanceof Error ? err.message : String(err) };420        }421      }422      case "UNLOCK": {423        const { password } = msg.payload as { password: string };424        const ok = await vault.unlock(password);425        if (ok) {426          // KAT: verify the WebCrypto stack is healthy before the user relies on it.427          // Runs after unlock so latency is hidden behind the vault-load time.428          const kat = await runSelfTest();429          if (!kat.ok) {430            console.error("[Peach] Crypto self-test FAILED:", kat.error);431            await vault.lock();432            return { ok: false, error: "self_test_failed" };433          }434          await vault.updateSettings({ pinPreferred: false });435          await setupAutoLock();436          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });437          onVaultUnlocked();438          return { ok: true };439        }440        // Distinguish corruption from wrong password so the popup can offer441        // a history-restore path instead of falsely accusing the user of442        // mistyping (M7/COR-007).443        const failure = vault.consumeLastUnlockFailureReason();444        if (failure) {445          return {446            ok: false,447            error: "vault_corrupted",448            canRestoreFromHistory: true,449          } as MessageResponse;450        }451        return { ok: false };452      }453      case "UNLOCK_WITH_PIN": {454        const { pin } = (msg.payload ?? {}) as { pin?: unknown };455        if (typeof pin !== "string") return { ok: false, error: "invalid_payload" };456        const ok = await vault.unlockWithPin(pin);457        if (!ok) {458          const status = await vault.getPinUnlockStatus();459          if (status.configured && !status.available) {460            return {461              ok: false,462              error: status.attemptsRemaining === 0463                ? "pin_attempts_exceeded"464                : "pin_session_expired",465            };466          }467          return { ok: false };468        }469        const kat = await runSelfTest();470        if (!kat.ok) {471          await vault.lock();472          return { ok: false, error: "self_test_failed" };473        }474        await vault.updateSettings({ pinPreferred: true });475        await setupAutoLock();476        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });477        onVaultUnlocked();478        return { ok: true };479      }480      case "GET_PIN_STATUS":481        return { ok: true, data: await vault.getPinUnlockStatus() };482      case "VALIDATE_RECOVERY_WORDS": {483        const { words } = msg.payload as { words: string[] };484        const invalid = findInvalidWords(words);485        return { ok: true, data: { valid: invalid.length === 0, invalid } };486      }487      case "GET_RECOVERY_WORDS": {488        // Must be unlocked and have recovery set up (vault must be v2.12+).489        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };490        // LV-4: the recovery words re-derive the ROOT KEY — the highest-491        // value secret in the vault. A session unlock (which may be hours492        // old on a shared machine) is not enough; require a fresh password493        // proof, matching the 1Password/Bitwarden pattern for revealing494        // escrow material. EXEMPTION: the create-vault / rotation confirmation495        // window (peach_recovery_pending) shows the words immediately after496        // the user authenticated, and that confirmation UI has no password to497        // resend — skip the re-auth there only.498        if (!(await isRecoveryConfirmPending())) {499          const { password } = (msg.payload ?? {}) as { password?: string };500          if (typeof password !== "string" || !password) {501            return { ok: false, error: "password_required" };502          }503          if (!(await vault.verifyMainPassword(password))) {504            return { ok: false, error: "wrong_password" };505          }506        }507        try {508          const words = await vault.getRecoveryWords();509          return { ok: true, data: words };510        } catch {511          return { ok: false, error: "recovery_not_setup" };512        }513      }514      case "GET_RECOVERY_CONFIRM_PENDING":515        return { ok: true, data: await isRecoveryConfirmPending() };516      case "SET_RECOVERY_CONFIRM_PENDING":517        await setRecoveryConfirmPending();518        return { ok: true };519      case "CLEAR_RECOVERY_CONFIRM_PENDING":520        await clearRecoveryConfirmPending();521        return { ok: true };522      case "RECOVER_WITH_WORDS": {523        // User has lost their password but has their 12 recovery words.524        // We: (1) validate the words, (2) re-encrypt vault with new password.525        const { words, newPassword } = msg.payload as {526          words: string[];527          newPassword: string;528        };529        const stored = await vault.loadSlotA();530        if (!stored) return { ok: false, error: "no_vault" };531        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {532          return { ok: false, error: "recovery_not_setup" };533        }534        // Unwrap the root key from the recovery escrow.535        try {536          await vault.unwrapRootKeyForRecovery(537            stored.recovery_wrapped_root_key,538            stored.recovery_nonce ?? "",539            stored.recovery_tag ?? "",540            stored.recovery_salt,541            words542          );543        } catch {544          return { ok: false, error: "invalid_recovery_words" };545        }546        // Re-key: derive fresh salt + key from new password.547        const newSalt = vault.generateSalt();548        const newKey = await vault.deriveKey(newPassword, newSalt);549        // Re-wrap root key under the new password's derived key so the same550        // recovery words continue to work after the password change.551        await vault.rewrapRootKeyForPassword(newKey, newSalt);552        // Re-encrypt vault entries with the new key.553        await vault.changePasswordWithNewKey(newSalt, newKey);554        await setupAutoLock();555        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });556        return { ok: true };557      }558      case "LOCK":559        await vault.lock();560        return { ok: true };561      case "IS_UNLOCKED":562        return { ok: true, data: vault.isUnlocked() };563      case "GET_VAULT_STATUS":564        return { ok: true, unlocked: vault.isUnlocked() };565      case "HAS_VAULT":566        return { ok: true, data: await vault.hasVault() };567      case "GET_ENTRIES":568        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };569        return { ok: true, data: vault.getEntries() };570      case "ADD_ENTRY": {571        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };572        const payload = msg.payload;573        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {574          return { ok: false, error: "invalid_payload" };575        }576        // PB-26-106: a page may only create an entry bound to itself. Entries577        // carrying no url have no domain surface to bind, so they are exempt.578        if (isPageSender(sender)) {579          const draft = payload as { url?: unknown; additionalUrls?: unknown };580          const domains = entryDomains(draft.url, draft.additionalUrls);581          if (domains.size > 0 && !senderMayBindEntryDomains(sender, domains)) {582            return { ok: false, error: "origin_binding_required" };583          }584        }585        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);586        return { ok: true, data: entry };587      }588      case "BATCH_ADD_ENTRIES": {589        const payload = msg.payload as { entries?: unknown } | null | undefined;590        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {591          return { ok: false, error: "invalid_payload" };592        }593        if (!Array.isArray(payload.entries)) {594          return { ok: false, error: "invalid_payload" };595        }596        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);597        return { ok: true, data: added };598      }599      case "RESTORE_ENTRIES": {600        const payload = msg.payload as601          | { entries?: unknown; mode?: unknown; settings?: unknown }602          | null603          | undefined;604        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {605          return { ok: false, error: "invalid_payload" };606        }607        if (!Array.isArray(payload.entries)) {608          return { ok: false, error: "invalid_payload" };609        }610        if (payload.mode !== "replace" && payload.mode !== "merge") {611          return { ok: false, error: "invalid_payload" };612        }613        const summary = await vault.restoreEntries(614          payload.entries as Parameters<typeof vault.restoreEntries>[0],615          payload.mode616        );617        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {618          await vault.updateSettings(payload.settings as vault.VaultSettings);619        }620        return { ok: true, data: summary };621      }622      case "CLEAR_VAULT_ENTRIES": {623        await vault.clearVaultEntries("REPLACE_ALL");624        return { ok: true };625      }626      case "GET_VAULT_HISTORY": {627        const snapshots = await vault.getVaultHistory();628        return { ok: true, data: snapshots };629      }630      case "RESTORE_VAULT_SNAPSHOT": {631        const { snapshotId } = msg.payload as { snapshotId: string };632        const result = await vault.restoreVaultSnapshot(snapshotId);633        if (!result.ok) return { ok: false, error: result.error };634        broadcastToContentScripts({ type: "VAULT_LOCKED" });635        return { ok: true };636      }637      case "COUNT_DUPLICATES": {638        return { ok: true, data: vault.countDuplicates() };639      }640      case "DEDUPLICATE_ENTRIES": {641        const removed = await vault.deduplicateEntries();642        return { ok: true, data: removed };643      }644      case "UPDATE_ENTRY": {645        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;646        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {647          return { ok: false, error: "invalid_payload" };648        }649        const { id, patch } = payload;650        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {651          return { ok: false, error: "invalid_payload" };652        }653        const existingEntry = vault.getEntryById(id);654        if (!existingEntry) return { ok: false, error: "entry_not_found" };655        if (patchChangesEntryOrigin(patch) || isPageSender(sender)) {656          const before = entryDomains(existingEntry.url, existingEntry.additionalUrls);657          const after = patchedUrlShape(patch, existingEntry);658          if (!senderMayMutateEntryDomains(659            sender,660            before,661            entryDomains(after.url, after.additionalUrls),662          )) {663            return { ok: false, error: "origin_binding_required" };664          }665        }666        // Single enforcement point for the Canary Entries Pro gate. Only667        // gates the transition into a canary entry — clearing/disabling a668        // canary (`canary: undefined`) is always allowed, so existing669        // canary entries remain manageable.670        const incomingCanary = (patch as { canary?: unknown }).canary;671        if (incomingCanary && typeof incomingCanary === "object") {672          const existing = vault.getEntryById(id);673          if (!existing?.canary) {674            const gate = await requirePro("canary_entry");675            if (!gate.allowed) return { ok: false, error: "pro_required" };676          }677        }678        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);679        return { ok: true };680      }681      case "ADD_ADDITIONAL_URL": {682        const { id, url } = msg.payload as { id: string; url: string };683        const trimmed = typeof url === "string" ? url.trim() : "";684        if (!trimmed) return { ok: false, error: "url_required" };685        const existing = vault.getEntryById(id);686        if (!existing) return { ok: false, error: "entry_not_found" };687        const merged = [...(existing.additionalUrls ?? []), trimmed];688        if (!senderMayMutateEntryDomains(689          sender,690          entryDomains(existing.url, existing.additionalUrls),691          entryDomains(existing.url, merged),692        )) {693          return { ok: false, error: "origin_binding_required" };694        }695        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };696        await vault.updateEntry(id, { additionalUrls: merged });697        return { ok: true };698      }699      case "REQUEST_REMEMBER_SITE": {700        // PB-26-106: growing an entry's domain set needs a decision the page701        // cannot make for itself, so the page asks and the popup confirms. A702        // page may only ask about its own attested origin — otherwise this703        // becomes the same unbound write under a friendlier name.704        const { id, url } = (msg.payload ?? {}) as { id?: unknown; url?: unknown };705        if (typeof id !== "string" || !id) return { ok: false, error: "invalid_payload" };706        const trimmed = typeof url === "string" ? url.trim() : "";707        if (!trimmed) return { ok: false, error: "url_required" };708        if (!senderMayBindEntryDomains(sender, entryDomains(trimmed, undefined))) {709          return { ok: false, error: "origin_binding_required" };710        }711        if (!vault.getEntryById(id)) return { ok: false, error: "entry_not_found" };712        if (chrome.storage.session) {713          await chrome.storage.session.set({ pendingRememberSite: { entryId: id, url: trimmed } });714        }715        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }716        return { ok: true };717      }718      case "DELETE_ENTRY": {719        const { id } = msg.payload as { id: string };720        await vault.deleteEntry(id);721        return { ok: true };722      }723      case "GET_DELETED_ENTRIES":724        return { ok: true, data: vault.getDeletedEntries() };725      case "RESTORE_ENTRY": {726        const { id } = msg.payload as { id: string };727        await vault.restoreEntry(id);728        return { ok: true };729      }730      case "PURGE_ENTRY": {731        const { id } = msg.payload as { id: string };732        await vault.purgeEntry(id);733        return { ok: true };734      }735      case "PURGE_EXPIRED_TRASH": {736        const { retentionMs } = msg.payload as { retentionMs: number };737        const purged = await vault.purgeExpiredTrash(retentionMs);738        return { ok: true, data: purged };739      }740      case "SAVE_NOTE": {741        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };742        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };743        const now = Date.now();744        if (id) {745          const existing = vault.getEntryById(id);746          if (!existing) return { ok: false, error: "not_found" };747          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });748          return { ok: true, data: vault.getEntryById(id) };749        } else {750          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt751          // (EntryDraft omits both), so passing them was the only reason the752          // `as any` cast existed. Dropping them makes the call type-check.753          const entry = await vault.addEntry({754            type: "note",755            title: title || "Untitled",756            notes: body,757          });758          return { ok: true, data: entry };759        }760      }761      case "DELETE_NOTE": {762        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };763        const { id } = msg.payload as { id: string };764        await vault.deleteEntry(id);765        return { ok: true };766      }767      case "GET_NOTES": {768        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };769        const notes = vault.getEntries().filter(770          (e) => e.type === "note" && !e.deletedAt771        );772        return { ok: true, data: notes } as MessageResponse;773      }774      case "SEARCH_VAULT": {775        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };776        // AUD-002: shape-validate the payload before calling string methods.777        // A raw cast lets a malformed message crash the handler with TypeError.778        const { query } = (msg.payload ?? {}) as { query?: unknown };779        if (typeof query !== "string") {780          return { ok: false, error: "invalid_payload" };781        }782        const q = query.toLowerCase();783        const searchResults = vault.getEntries().filter(784          (e) =>785            !e.deletedAt &&786            (e.title.toLowerCase().includes(q) ||787              e.notes?.toLowerCase().includes(q) ||788              e.username?.toLowerCase().includes(q))789        );790        return { ok: true, data: searchResults } as MessageResponse;791      }792      case "AUTOFILL_QUERY": {793        if (!vault.isUnlocked()) {794          return { ok: false, error: "vault_locked" };795        }796        const { domain, kind, capability } = msg.payload as {797          domain: string;798          kind?: "login" | "card" | "totp";799          capability?: string;800        };801        const includeAll = consumeSummonCapability(capability, sender, "inventory");802        if (capability !== undefined && !includeAll) {803          return { ok: false, error: "entry_not_found" };804        }805        // kind="card": return saved cards as compact summaries for the806        // inline card silver platter. Cards are not domain-scoped — every807        // saved card is a candidate on every checkout page — so domain is808        // ignored when kind === "card".809        if (kind === "card") {810          if (!includeAll) return { ok: true, data: [] };811          const cards = vault.getEntries().filter((e) => e.type === "card");812          return {813            ok: true,814            data: cards.map((e) => ({815              id: e.id,816              title: e.cardNickname || e.title,817              cardholderName: e.cardholderName,818              last4: e.last4,819              expMonth: e.expMonth,820              expYear: e.expYear,821              network: e.network,822            })),823          };824        }825        const scopedDomain = isPageSender(sender)826          ? attestedSenderDomain(sender)827          : typeof domain === "string"828            ? extractDomain(domain)829            : null;830        if (!includeAll && !scopedDomain) {831          return isPageSender(sender)832            ? { ok: false, error: "origin_unverified" }833            : { ok: true, data: [] };834        }835        if (kind === "totp") {836          const matches = (837            includeAll838              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")839              : vault.queryDomain(scopedDomain!)840          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));841          return {842            ok: true,843            data: matches.map((e) => ({844              id: e.id,845              title: e.title,846              username: e.username,847              email: e.email,848              url: e.url,849              hasTotp: true,850            })),851          };852        }853        // The inline selector fills username+password into a form. Passkey-854        // only entries have no password to fill; sign-in for those goes855        // through the WebAuthn path instead. Filter them out everywhere so856        // the user doesn't see four "GitHub" rows that mostly do nothing.857        // Notes and cards never belonged here either.858        const matches = (859          includeAll860            ? vault861                .getEntries()862                .filter((entry) => entry.type !== "note" && entry.type !== "card")863            : vault.queryDomain(scopedDomain!)864        ).filter((entry) => !isPasskeyOnly(entry));865        return {866          ok: true,867          data: matches.map((e) =>868            includeAll869              ? {870                  id: e.id,871                  title: e.title,872                  // username/email/url shipped so the inline popup's search873                  // affordance can match on them, not just titles. No secrets874                  // cross the boundary — same shape as the domain-matched875                  // response below minus hasTotp (which the search list876                  // doesn't surface).877                  username: e.username,878                  email: e.email,879                  url: e.url,880                  hasPasskey: e.passkey !== undefined,881                }882              : {883                  id: e.id,884                  title: e.title,885                  username: e.username,886                  email: e.email,887                  url: e.url,888                  hasTotp: Boolean(e.totp),889                  hasPasskey: e.passkey !== undefined,890                }891          ),892        };893      }894      case "GET_ENTRY_FOR_FILL": {895        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };896        const { id, capability } = msg.payload as {897          id: string;898          capability?: string;899        };900        const capabilityAuthorized = capability !== undefined && consumeSummonCapability(capability, sender, "fill");901        const senderDomain = isPageSender(sender) ? attestedSenderDomain(sender) : null;902        if (isPageSender(sender) && !senderDomain) {903          return { ok: false, error: "origin_unverified" };904        }905        const entry = vault.getEntryById(id);906        if (!entry) return { ok: false, error: "entry_not_found" };907908        // MV-1: re-validate the entry against the requesting frame's origin.909        // sender.url / sender.tab.url are browser-attested — a page cannot910        // forge them. PB-26-005: the FRAME url (sender.url) is authoritative911        // for an all_frames content script; the top-frame tab.url would912        // misattribute a cross-origin iframe's request to the top page. When913        // the request does not come from a tab at all (popup surfaces use914        // GET_ENTRY_FOR_EDIT, not this), refuse.915        if (senderDomain && !capabilityAuthorized) {916          if (!entryDomains(entry.url, entry.additionalUrls).has(senderDomain)) {917            // Domain mismatch — refuse silently (no oracle about which ids exist).918            return { ok: false, error: "entry_not_found" };919          }920        }921        // Passkey-only entries (passkey credential, no password) cannot be922        // filled into a form — sign-in goes through the WebAuthn path. A923        // login that ALSO has a passkey is still fillable for its password.924        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };925        // Strip the passkey credential AND the raw base32 TOTP seed from the926        // response. Content scripts never need either: the private key is the927        // authenticator's, and handing over the TOTP seed would let a928        // compromised content script mint valid codes indefinitely (SEV-3-C).929        // Generate the *current* 6-digit code here in the background and send930        // only that, plus the seconds left so the UI can render a countdown.931        // Also drop passwordHistory: filling needs only the *current* password.932        // Handing every past password to a content script during passive933        // autofill on an arbitrary page would widen the blast radius of a934        // compromised page far beyond the one credential being filled.935        const {936          passkey: _strippedPasskey,937          totp: seed,938          totpAlgorithm,939          totpDigits,940          totpPeriod,941          passwordHistory: _ph,942          ...safeEntry943        } = entry;944        let totpCode: string | undefined;945        let totpRemaining: number | undefined;946        if (seed) {947          try {948            // PCH-01-019: honour stored algorithm/digits/period (defaults apply949            // when these are undefined, i.e. RFC-default bare-seed entries).950            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);951            totpCode = generated.code;952            totpRemaining = generated.remaining;953          } catch {954            totpCode = undefined;955          }956        }957        if (isPageSender(sender) && vault.isUnlocked()) touchAutoLock();958        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };959      }960      // Trusted full-entry fetch for extension-owned edit surfaces. Content961      // scripts route editing to the popup and cannot call this message.962      case "GET_ENTRY_FOR_EDIT": {963        if (isPageSender(sender)) return { ok: false, error: "invalid_sender" };964        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };965        const { id } = msg.payload as { id: string };966        const entry = vault.getEntryById(id);967        if (!entry) return { ok: false, error: "entry_not_found" };968969        const { passkey: _passkey, ...safeEntry } = entry;970        return { ok: true, data: safeEntry };971      }972      case "COPY": {973        // AUD-002: shape-validate the payload before passing to the clipboard974        // helper. A raw cast lets a malformed message reach the clipboard API975        // with a non-string and throw.976        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {977          text?: unknown;978          label?: unknown;979          alreadyWritten?: unknown;980        };981        if (typeof text !== "string" || typeof label !== "string") {982          return { ok: false, error: "invalid_payload" };983        }984        await copyToClipboard(text, label, Boolean(alreadyWritten));985        return { ok: true, clearSeconds: getEffectiveClearSeconds() };986      }987      case "CHECK_ALL_BREACHES": {988        const allEntries = vault.getEntries();989        const results: Record<string, number> = {};990        for (const entry of allEntries) {991          if (entry.type === "note") continue;992          if (!entry.password) continue;993          results[entry.id] = await vault.checkBreach(entry.password);994          // Small delay — be a good citizen to the HIBP API995          await new Promise((r) => setTimeout(r, 200));996        }997        // Persist any non-zero counts back to entries998        for (const [id, count] of Object.entries(results)) {999          const entry = vault.getEntryById(id);1000          if (entry && (entry.breach ?? 0) !== count) {1001            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });1002          }1003        }1004        return { ok: true, data: results };1005      }1006      case "GET_SETTINGS": {1007        const settings = await vault.ensureSettingsLoaded();1008        if (!isPageSender(sender)) return { ok: true, data: settings };10091010        const safeSettings: Pick<vault.VaultSettings, "accentColor" | "theme"> & {1011          manualSummonDomains?: NonNullable<vault.VaultSettings["manualSummonDomains"]>;1012        } = {1013          accentColor: settings.accentColor,1014          theme: settings.theme,1015        };1016        const domain = attestedSenderDomain(sender);1017        const ownSummon = domain ? settings.manualSummonDomains?.[domain] : undefined;1018        if (domain && ownSummon) safeSettings.manualSummonDomains = { [domain]: ownSummon };1019        return { ok: true, data: safeSettings };1020      }1021      case "UPDATE_SETTINGS": {1022        const patch = msg.payload;1023        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {1024          return { ok: false, error: "invalid_payload" };1025        }1026        await vault.updateSettings(patch as vault.VaultSettings);1027        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {1028          await setupAutoLock();1029          if (vault.isUnlocked()) touchAutoLock();1030        }1031        return { ok: true };1032      }1033      case "SETUP_PIN": {1034        const { currentPassword, pin } = (msg.payload ?? {}) as {1035          currentPassword?: unknown;1036          pin?: unknown;1037        };1038        if (typeof currentPassword !== "string" || typeof pin !== "string") {1039          return { ok: false, error: "invalid_payload" };1040        }1041        return (await vault.setupPinUnlock(currentPassword, pin))1042          ? { ok: true }1043          : { ok: false, error: "incorrect_current_password" };1044      }1045      case "DISABLE_PIN": {1046        const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown };1047        if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" };1048        return (await vault.disablePinUnlock(currentPassword))1049          ? { ok: true }1050          : { ok: false, error: "incorrect_current_password" };1051      }1052      case "GET_PENDING_PASSKEY":1053        return { ok: true, data: await getPendingPasskeyRequest() };1054      case "APPROVE_PASSKEY": {1055        const { requestId } = msg.payload as { requestId: number };1056        await resolvePendingPasskeyRequest(requestId, true);1057        return { ok: true };1058      }1059      case "DENY_PASSKEY": {1060        const { requestId } = msg.payload as { requestId: number };1061        await resolvePendingPasskeyRequest(requestId, false);1062        return { ok: true };1063      }1064      case "GET_PASSKEY_PROVIDER_STATE":1065        return { ok: true, data: await getPasskeyProviderState() };1066      case "SET_PASSKEY_PROVIDER_ENABLED": {1067        const { enabled } = msg.payload as { enabled: boolean };1068        // Disabling is always free; gating fires only when a free user is1069        // trying to turn passkey interception on.1070        if (enabled) {1071          const gate = await requirePro("passkeys");1072          if (!gate.allowed) return { ok: false, error: "pro_required" };1073        }1074        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };1075      }1076      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS1077      // endpoint. Intentional product behavior — users configure their own1078      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private1079      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-1080      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to1081      // users that the entry title leaves the device when the canary fires.1082      case "FIRE_CANARY_PING": {1083        // Canary alert fires unconditionally for any entry with canary: true.1084        // The Pro gate only governs creation/flagging of canary entries; once1085        // an entry is flagged, the alert path is a security property and must1086        // never be license-gated.1087        const { webhookUrl, entryTitle, trigger } = msg.payload as {1088          webhookUrl: string;1089          entryTitle: string;1090          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";1091        };1092        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {1093          return { ok: false, error: "invalid_webhook_url" };1094        }1095        // LV-3: debounce non-test pings per (webhook, entry) so a page that1096        // strobes focus/fill events can't turn the canary into a request1097        // firehose at the user's endpoint. Test pings are exempt — they are1098        // explicit user clicks in the settings UI and are awaited for1099        // feedback. The FIRST ping in a window always goes out, so the1100        // dead-man's-switch property (canary fires on access) is preserved;1101        // only repeats within the window are coalesced.1102        if (trigger !== "test") {1103          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;1104          const stored = await chrome.storage.local.get(rlKey);1105          const last = (stored as Record<string, unknown>)[rlKey];1106          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {1107            return { ok: true, data: { rateLimited: true } };1108          }1109          await chrome.storage.local.set({ [rlKey]: Date.now() });1110        }1111        const body = JSON.stringify({1112          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",1113          entry: entryTitle,1114          trigger,1115          timestamp: new Date().toISOString(),1116          source: "peach-extension",1117        });1118        if (trigger === "test") {1119          // Permitted outbound fetch: user-configured canary alert endpoint1120          // (validated by isAllowedCanaryWebhookUrl above). This is the1121          // only non-HIBP outbound call in the extension — see1122          // Projects.md §3.7. Test pings are awaited so the UI can show1123          // success/failure.1124          try {1125            const res = await fetch(webhookUrl, {1126              method: "POST",1127              headers: { "Content-Type": "application/json" },1128              body,1129            });1130            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1131          } catch (err) {1132            return { ok: false, error: err instanceof Error ? err.message : "network_error" };1133          }1134        }1135        // Non-test triggers are fire-and-forget1136        fetch(webhookUrl, {1137          method: "POST",1138          headers: { "Content-Type": "application/json" },1139          body,1140        }).catch(() => {});1141        return { ok: true };1142      }1143      case "ACTIVATE_LICENSE": {1144        const { key } = msg.payload as { key: string };1145        const licenseInfo = await activateLicense(key);1146        return { ok: true, data: licenseInfo };1147      }1148      case "GET_LICENSE": {1149        const licenseInfo = await getLicenseInfo();1150        return { ok: true, data: licenseInfo };1151      }1152      case "GET_LICENSE_KEY": {1153        const key = await getLicenseKey();1154        return { ok: true, data: key };1155      }1156      case "DEACTIVATE_LICENSE": {1157        await deactivateLicense();1158        return { ok: true };1159      }1160      case "SHOULD_PLAY_CELEBRATION": {1161        const should = await shouldPlayCelebration();1162        return { ok: true, data: should };1163      }1164      case "MARK_CELEBRATION_PLAYED": {1165        await markCelebrationPlayed();1166        return { ok: true };1167      }1168      case "GET_CODEX_VAULT_DATA": {1169        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1170        // popup navigates to the License section without further coordination.1171        // Also privileged-page-gated (PB-26-001), and recoveryWords inside the1172        // snapshot additionally require a fresh master-password proof.1173        const gate = await requirePro("codex");1174        if (!gate.allowed) return { ok: false, error: "pro_required" };1175        const { password } = (msg.payload ?? {}) as { password?: string };1176        return await handleGetCodexVaultData(password);1177      }1178      case "ESTIMATE_CODEX_PAGES": {1179        const gate = await requirePro("codex");1180        if (!gate.allowed) return { ok: false, error: "pro_required" };1181        return await handleEstimateCodexPages();1182      }1183      case "RESTORE_FROM_CODEX": {1184        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1185        // be able to restore a vault that was printed by a Pro user.1186        // DO NOT add a Pro gate here.1187        const payload = msg.payload as CodexRestorePayload;1188        return await handleRestoreFromCodex(payload);1189      }1190      case "OPEN_PRO_GATE": {1191        // Content script requests: open popup and navigate to License section.1192        const { feature } = (msg.payload ?? {}) as { feature?: string };1193        if (chrome.storage.session) {1194          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1195        }1196        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1197        return { ok: true };1198      }1199      case "OPEN_POPUP": {1200        // Content script asks to open the trusted extension popup — used by the1201        // inline locked bubble so the master password is entered in the popup,1202        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1203        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1204        // toolbar icon. The badge already signals Peach needs attention.1205        //1206        // Set a session flag so the popup knows it was opened for inline unlock1207        // and should close itself once the vault is unlocked (returning the user1208        // to the inline autofill selector on the page).1209        const { entryId } = (msg.payload ?? {}) as { entryId?: unknown };1210        if (entryId !== undefined && (typeof entryId !== "string" || entryId.length === 0 || entryId.length > 64)) {1211          return { ok: false, error: "invalid_payload" };1212        }1213        if (chrome.storage.session) {1214          if (typeof entryId === "string") {1215            await chrome.storage.session.set({ peach_open_entry: entryId });1216          } else {1217            await chrome.storage.session.set({ peach_inline_unlock: true });1218          }1219        }1220        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1221        return { ok: true };1222      }1223      case "OPEN_DETACHED_POPUP": {1224        // A window created by the action popup and then orphaned with1225        // window.close() is cascaded shut by Chrome, so the file-picker1226        // flows (OS dialogs that dismiss the popup on focus loss) ask the SW1227        // to open the standalone window instead — the SW has no window to be1228        // associated with. The query string is allowlisted so this can never1229        // open an arbitrary URL.1230        const { route } = (msg.payload ?? {}) as { route?: string };1231        const search = route === "peachscript"1232          ? "?restore=peachscript"1233          : route === "csv"1234            ? "?restore=csv"1235            : route === "codex-pdf"1236              ? "?codex=pdf"1237              : null;1238        if (!search) return { ok: false, error: "bad_route" };1239        try {1240          const popupHtml =1241            chrome.runtime.getManifest().action?.default_popup ?? "src/popup/index.html";1242          await chrome.windows.create({1243            url: chrome.runtime.getURL(`${popupHtml}${search}`),1244            type: "popup",1245            width: 320,1246            height: 550,1247          });1248          return { ok: true, data: { detached: true } };1249        } catch {1250          return { ok: false };1251        }1252      }1253      case "GET_IDENTITIES": {1254        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1255        return { ok: true, data: vault.getIdentities() };1256      }1257      case "TOUCH_AUTO_LOCK": {1258        // touchAutoLock() is already called by shouldRefreshAutoLock above;1259        // this case just gives the popup a typed message to keep the session alive.1260        return { ok: true };1261      }1262      case "GET_ADVANCED_HEALTH_REPORT": {1263        const gate = await requirePro("advanced_health");1264        if (!gate.allowed) return { ok: false, error: "pro_required" };1265        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1266        const report = await buildAdvancedHealthReport(vault.getEntries());1267        return { ok: true, data: report };1268      }1269      case "IS_DURESS_ENABLED": {1270        const enabled = await vault.isDuressEnabled();1271        return { ok: true, data: enabled };1272      }1273      case "SETUP_DURESS": {1274        // Single enforcement point for the Duress Vault Pro gate. Free users1275        // who somehow reach this handler are rejected here; the popup also1276        // pre-checks isPro() to avoid showing the setup form to free users,1277        // but server-side is the actual security boundary.1278        const gate = await requirePro("duress_vault");1279        if (!gate.allowed) return { ok: false, error: "pro_required" };1280        // MV3 service workers restart after inactivity, losing the in-memory1281        // derived key. Detect this before calling setupDuress so the popup1282        // can show a meaningful prompt to re-lock and re-unlock.1283        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1284        const { duressPassword } = msg.payload as { duressPassword: string };1285        await vault.setupDuress(duressPassword);1286        return { ok: true };1287      }1288      case "DISABLE_DURESS": {1289        await vault.disableDuress();1290        return { ok: true };1291      }1292      case "VERIFY_MAIN_PASSWORD": {1293        const { password } = msg.payload as { password: string };1294        const ok = await vault.verifyMainPassword(password);1295        return { ok: true, data: ok };1296      }1297      case "CHANGE_PASSWORD": {1298        const { currentPassword, newPassword } = msg.payload as {1299          currentPassword: string;1300          newPassword: string;1301        };1302        const changed = await vault.changePassword(currentPassword, newPassword);1303        return changed1304          ? { ok: true }1305          : { ok: false, error: "incorrect_current_password" };1306      }1307      case "GET_SITE_PASSWORD_POLICY": {1308        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1309        if (!tab?.id) return { ok: true, data: null };1310        try {1311          const response = await chrome.tabs.sendMessage(tab.id, {1312            type: "GET_SITE_PASSWORD_POLICY",1313          });1314          return (response as MessageResponse) ?? { ok: true, data: null };1315        } catch {1316          return { ok: true, data: null };1317        }1318      }1319      case "RECORD_MANUAL_SUMMON": {1320        const { domain } = msg.payload as { domain: string };1321        const settings = vault.getSettings();1322        const existing = settings.manualSummonDomains?.[domain];1323        const now = Date.now();1324        await vault.updateSettings({1325          manualSummonDomains: {1326            ...settings.manualSummonDomains,1327            [domain]: {1328              firstSummonedAt: existing?.firstSummonedAt ?? now,1329              summonCount: (existing?.summonCount ?? 0) + 1,1330              lastSummonedAt: now,1331            },1332          },1333        });1334        return { ok: true };1335      }1336      case "DECLINE_CARD_SAVE": {1337        // PB-26-108: the declined-card digest is keyed by root-key material, so1338        // a decline cannot be recorded while locked. Offers are not shown while1339        // locked either, so this is unreachable in practice.1340        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1341        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1342        await vault.declineCardSaveOffer(last4, expMonth, expYear);1343        return { ok: true };1344      }1345      case "IS_CARD_DECLINED": {1346        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1347        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1348        return { ok: true, data: declined };1349      }1350      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1351        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1352          rpId?: string;1353          rpName?: string;1354          userName?: string;1355          userDisplayName?: string;1356        };1357        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1358        return await initiateFirefoxPasskeyCreate({1359          rpId,1360          rpName: rpName ?? rpId,1361          userName,1362          userDisplayName,1363        }, attestedSenderOrigin(sender));1364      }13651366      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1367        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1368        if (!payload) return { ok: false, error: "missing_payload" };1369        return await completeFirefoxPasskeyCreate(payload);1370      }13711372      case "PASSKEY_OFFER_DECLINE": {1373        const { domain } = (msg.payload ?? {}) as { domain?: string };1374        const origin = attestedSenderOrigin(sender);1375        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1376        await recordPasskeyOfferDecline(domain);1377        return { ok: true };1378      }13791380      case "GET_PASSKEY_OFFER_DECLINED": {1381        const { domain } = (msg.payload ?? {}) as { domain?: string };1382        const origin = attestedSenderOrigin(sender);1383        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1384        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1385      }13861387      case "PASSKEY_HAS_CREDENTIALS": {1388        const payload = msg.payload as {1389          rpId?: string;1390          allowCredentials?: Array<{ id: string; type?: string }>;1391        } | undefined;1392        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1393        return await handlePasskeyHasCredentials({1394          rpId: payload.rpId,1395          allowCredentials: payload.allowCredentials ?? [],1396        }, attestedSenderOrigin(sender));1397      }13981399      case "PASSKEY_CREATE": {1400        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1401        if (!payload?.rpId || !payload?.userName) {1402          return { ok: false, error: "rpid_and_username_required" };1403        }1404        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1405      }14061407      case "PASSKEY_GET": {1408        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1409        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1410        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1411      }14121413      case "PASSKEY_AUTH_RESPONSE": {1414        const { requestId, approved } = (msg.payload ?? {}) as {1415          requestId?: string | number;1416          approved?: boolean;1417        };1418        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1419          return { ok: false, error: 'requestId and approved required' };1420        }1421        const pending = await getPendingPasskeyRequest();1422        const senderOrigin = attestedSenderOrigin(sender);1423        if (1424          (pending && pending.requestId !== Number(requestId)) ||1425          (pending?.tabId !== undefined && sender.tab?.id !== pending.tabId) ||1426          (pending?.origin !== undefined && senderOrigin !== pending.origin)1427        ) {1428          return { ok: false, error: "invalid_passkey_approval_sender" };1429        }1430        await resolvePendingPasskeyRequest(Number(requestId), approved);1431        return { ok: true };1432      }14331434      case "GET_PASSKEY_FOR_DOMAIN": {1435        const { domain } = (msg.payload ?? {}) as { domain?: string };1436        if (!domain) return { ok: false, error: "domain_required" };1437        // Scope to the caller's own origin: a page may only ask about passkeys1438        // for a domain it actually owns, so an arbitrary page cannot enumerate1439        // which sites the user holds passkeys for or read the username (audit MEDIUM).1440        const origin = attestedSenderOrigin(sender);1441        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1442        if (!vault.isUnlocked()) return { ok: true, data: null };1443        const match = vault1444          .getEntries()1445          .find((entry) => entry.passkey?.rpId === domain);1446        if (!match || !match.passkey) return { ok: true, data: null };1447        // Slim shape — only the fields State 11 needs. Never expose private1448        // key material, even though this is locked behind isUnlocked.1449        // bannerShown is the per-domain "already surfaced" flag, kept in1450        // trusted background session storage so content scripts never touch1451        // chrome.storage.session directly (PB-26-203).1452        let bannerShown = false;1453        if (chrome.storage.session) {1454          const flag = await chrome.storage.session.get(`peach_state11_shown:${domain}`);1455          bannerShown = Boolean((flag as Record<string, unknown>)[`peach_state11_shown:${domain}`]);1456        }1457        return {1458          ok: true,1459          data: {1460            rpId: match.passkey.rpId,1461            userName: match.passkey.userName,1462            browser: match.passkey.browser,1463            bannerShown,1464          },1465        };1466      }14671468      case "MARK_PASSKEY_BANNER_SHOWN": {1469        const { domain } = (msg.payload ?? {}) as { domain?: string };1470        if (typeof domain !== "string" || !domain) return { ok: false, error: "domain_required" };1471        // Same origin binding as the read path: a page may only mark its own1472        // domain, and the flag reveals nothing either way.1473        const origin = attestedSenderOrigin(sender);1474        if (!origin || !isValidRpId(domain, origin)) return { ok: true };1475        if (chrome.storage.session) {1476          await chrome.storage.session.set({ [`peach_state11_shown:${domain}`]: Date.now() });1477        }1478        return { ok: true };1479      }14801481      case "DESTROY_VAULT": {1482        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1483        // storage.local.clear() wipes every Peach key (slots, settings, license,1484        // onboarded flag, history, sync state, declined cards, recall, etc.);1485        // session.clear() wipes pending passkey requests + pro-notice queues.1486        // Caller (Panic.tsx) handles UI navigation back to onboarding.1487        //1488        // The Pro license is the one thing that must survive: the user paid for1489        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1490        // Capture it before the clear and restore it after. peach_pro_celebrated1491        // rides along so the Pro celebration doesn't replay on the next unlock.1492        const preserved = await chrome.storage.local.get([1493          "peach_license",1494          "peach_pro_celebrated",1495        ]);1496        await vault.lock();1497        await storageClear();1498        await vault.clearVaultHistory();1499        const toRestore: Record<string, unknown> = {};1500        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1501        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1502        if (Object.keys(toRestore).length > 0) {1503          await chrome.storage.local.set(toRestore);1504        }1505        if (chrome.storage.session) {1506          await chrome.storage.session.clear();1507        }1508        await clearRecoveryConfirmPending();1509        return { ok: true };1510      }15111512      case "GET_IDENTITY_SUGGESTIONS": {1513        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1514        const entries = vault.getEntries();1515        const suggestions = buildIdentitySuggestions(entries);1516        return { ok: true, data: { suggestions } };1517      }1518      case "ML_INIT":1519        return { ok: true };15201521      case "ML_PREDICT_BATCH": {1522        // AUD-002: shape-validate before forwarding to the ML helper.1523        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1524        if (!Array.isArray(featuresArray)) {1525          return { ok: false, error: "invalid_payload" };1526        }1527        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1528      }15291530      // ── Vault sync (v3) ───────────────────────────────────────────────1531      // Returns the public-facing local identity needed by the popup to1532      // drive Phase-1 audio pairing. The private long-term key never1533      // leaves the background.1534      case "GET_LOCAL_IDENTITY": {1535        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1536        // Pro license from an already-Pro peer (at least one device must be Pro).1537        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1538        // Identity derives from the stable root key, not the password-derived1539        // key, so pairing survives a master-password change (SEV-2-B).1540        const masterKeyHex = vault.getRootKeyHex();1541        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1542        const masterKey = unhexBytes(masterKeyHex);1543        try {1544          const identity = await buildLocalIdentity(masterKey);1545          // If this device is Pro, advertise the signed license so the peer can1546          // activate it after SAS confirmation — pairing carries Pro across.1547          if (await isProUser()) {1548            const license = await getLicenseKey();1549            if (license) (identity as { license?: string }).license = license;1550          }1551          return { ok: true, data: identity };1552        } finally {1553          masterKey.fill(0);1554        }1555      }15561557      case "LIST_PAIRED_DEVICES": {1558        const devices = await listPairedDevicesV3();1559        return { ok: true, data: { devices } };1560      }15611562      case "RENAME_PAIRED_DEVICE": {1563        const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string };1564        if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") {1565          return { ok: false, error: "invalid_payload" };1566        }1567        await renamePairedDeviceV3(deviceId, name);1568        return { ok: true };1569      }15701571      case "UNPAIR_DEVICE": {1572        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1573        if (typeof deviceId !== "string" || !deviceId) {1574          return { ok: false, error: "invalid_payload" };1575        }1576        // Removing a device REVOKES it rather than just dropping the local1577        // row: a plain removal is undone the moment any other peer vouches it1578        // back through a manifest, which is exactly what the relay makes easy.1579        await revokeDeviceByIdV3(deviceId, await getOrCreateDeviceId());1580        // PB-26-213: forget the secret now so no further dial can use it.1581        // Removals that happen while locked leave orphans for the next1582        // unlock's reconcile to prune.1583        const unpairRootHex = vault.getRootKeyHex();1584        if (unpairRootHex) {1585          const unpairRoot = unhexBytes(unpairRootHex);1586          try {1587            await dropPairSecret(deviceId, unpairRoot);1588          } finally {1589            unpairRoot.fill(0);1590          }1591        } else {1592          await dropPairSecret(deviceId, null);1593        }1594        // Sync against the remaining hosts — the unpaired device no longer1595        // matters but the next alarm tick is up to ten minutes away.1596        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1597        return { ok: true };1598      }15991600      case "RENAME_LOCAL_DEVICE": {1601        const { name } = (msg.payload ?? {}) as { name?: string };1602        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1603        await setDeviceNameV3(name);1604        return { ok: true };1605      }16061607      // ── Relay pairing ─────────────────────────────────────────────────────1608      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1609      // session runs in the background; the SAS and the terminal result reach1610      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1611      case "START_ADOPTION_SOURCE": {1612        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1613        if (isRelayAdoptionSourceInFlight()) {1614          return { ok: false, error: "adoption_source_in_progress" };1615        }1616        try {1617          return { ok: true, data: await startRelayAdoptionSource() };1618        } catch (error) {1619          return {1620            ok: false,1621            error: error instanceof Error ? error.message : "adoption_source_failed",1622          };1623        }1624      }16251626      // Onboarding receiver — empty extension shows a QR, phone scans and1627      // sends the vault. The popup supplies the local-only password here so1628      // the background can wrap the adopted root key at rest without ever1629      // asking the user to retype it.1630      case "START_ADOPTION_RECEIVER": {1631        if (isRelayAdoptionSourceInFlight()) {1632          return { ok: false, error: "adoption_receiver_in_progress" };1633        }1634        const password = (msg.payload as { password?: unknown } | undefined)?.password;1635        if (typeof password !== "string" || password.length === 0) {1636          return { ok: false, error: "invalid_payload" };1637        }1638        try {1639          return { ok: true, data: await startRelayAdoptionReceiver(password) };1640        } catch (error) {1641          return {1642            ok: false,1643            error: error instanceof Error ? error.message : "adoption_receiver_failed",1644          };1645        }1646      }16471648      // Popup→bg counterpart to ADOPTION_SOURCE_SAS (receiver flow).1649      // The receiver now auto-accepts the SAS (both sides derive it from the1650      // same Noise handshake hash, so the codes match by construction) so1651      // the popup never has a SAS screen to tap on. The id round-trips the1652      // same way so a stale late response can't approve the wrong session.1653      // Popup→bg counterpart for the source flow: Confirm/Cancel on the1654      // source's SAS screen.16551656      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1657      // on the source's SAS screen. The id round-trips the same way so a stale1658      // late response can't approve the wrong session.1659      case "SOURCE_SAS_DECISION": {1660        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1661        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1662          return { ok: false, error: "invalid_payload" };1663        }1664        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1665      }16661667      case "CANCEL_ADOPTION_SOURCE": {1668        cancelRelayAdoptionSource();1669        return { ok: true };1670      }16711672      case "TRIGGER_SYNC": {1673        const payload = (msg.payload ?? {}) as {1674          reason?: "vault_change" | "foreground" | "manual";1675          force?: boolean;1676        };1677        const reason = payload.reason ?? "foreground";16781679        void triggerSyncIfReachable({ reason, force: payload.force === true });1680        return { ok: true };1681      }16821683      case "GET_SYNC_STATE": {1684        return { ok: true, data: getSyncState() };1685      }16861687      case "GET_SYNC_SETTINGS": {1688        return { ok: true, data: await getSyncSettings() };1689      }16901691      case "SET_SYNC_SETTINGS": {1692        const payload = (msg.payload ?? {}) as {1693          mode?: unknown;1694          relayUrl?: unknown;1695        };1696        try {1697          // A custom relay URL implies private mode; Peach's own relay stays1698          // public. See setRelayUrl.1699          if (payload.relayUrl !== undefined) {1700            if (typeof payload.relayUrl !== "string") {1701              return { ok: false, error: "invalid_relay_url" };1702            }1703            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1704          }1705          if (payload.mode !== undefined) {1706            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1707              return { ok: false, error: "invalid_sync_mode" };1708            }1709            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1710          }1711          return { ok: true, data: await getSyncSettings() };1712        } catch (error) {1713          return {1714            ok: false,1715            error: error instanceof Error ? error.message : "invalid_relay_url",1716          };1717        }1718      }17191720      case "GET_SYNC_ALERTS": {1721        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1722        const alerts = await getPendingSyncAlerts();1723        // The popup reads on open and acknowledges with consume:true after1724        // rendering, so a popup crash between read and render doesn't lose1725        // the alerts.1726        if (consume) await clearPendingSyncAlerts();1727        return { ok: true, data: alerts };1728      }17291730      case "GET_PENDING_VOUCHED_DEVICES": {1731        return { ok: true, data: await listPendingVouchedDevices() };1732      }1733      case "CONFIRM_VOUCHED_DEVICE": {1734        const { deviceId } = msg.payload as { deviceId: string };1735        const pending = await getPendingVouchedDevice(deviceId);1736        if (!pending) return { ok: false, error: "not_pending" };1737        // Last gate before a vouched device becomes a sync peer. A queue entry1738        // can predate the revocation that names it, so revocation is re-checked1739        // here rather than trusted to have swept the queue.1740        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {1741          await removePendingVouchedDevice(deviceId);1742          return { ok: false, error: "device_revoked" };1743        }1744        await upsertPairedDeviceV3({1745          deviceId: pending.deviceId,1746          deviceName: pending.deviceName,1747          deviceType:1748            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1749          longTermPublicKeyHex: pending.longTermPublicKeyHex,1750          signingPublicKeyHex: pending.signingPublicKeyHex,1751          wsPort: pending.wsPort,1752          pairedAt: pending.pairedAt,1753          trustSource: "vouched",1754        });1755        await removePendingVouchedDevice(deviceId);1756        // Newly confirmed vouched device is now a sync target — kick a round1757        // so the mesh introduction pays off without a 10-minute wait.1758        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1759        return { ok: true };1760      }1761      case "REJECT_VOUCHED_DEVICE": {1762        const { deviceId } = msg.payload as { deviceId: string };1763        await removePendingVouchedDevice(deviceId);1764        return { ok: true };1765      }1766      case "ROTATE_SYNC_IDENTITY": {1767        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1768        const result = await vault.rotateSyncIdentity();1769        return result.ok ? { ok: true } : { ok: false, error: result.error };1770      }17711772      default:1773        return { ok: false, error: "unknown_message_type" };1774    }1775  } catch (err) {1776    return {1777      ok: false,1778      error: err instanceof Error ? err.message : "operation_failed",1779    };1780  }1781}17821783// Returns username use-counts from the vault, sorted by frequency. Each row1784// also carries the entry's email so the popup can suggest the email/username1785// pair the user has actually used together.1786function buildIdentitySuggestions(1787  entries: VaultEntry[],1788): Array<{ email: string; username: string; count: number }> {1789  const usernameCounts = new Map<string, number>();1790  const usernameEmail = new Map<string, string>();1791  for (const entry of entries) {1792    const username = entry.username ?? "";1793    const email = (entry as VaultEntry & { email?: string }).email ?? "";1794    if (!username && !email) continue;1795    const key = username || email;1796    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1797    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1798  }1799  return Array.from(usernameCounts.entries())1800    .sort((a, b) => b[1] - a[1])1801    .map(([username, count]) => ({1802      email: usernameEmail.get(username) ?? "",1803      username,1804      count,1805    }));1806}18071808/** Notify all content scripts that the vault just became available. */1809function broadcastToContentScripts(message: { type: string }): void {1810  if (!chrome.tabs?.query) return;1811  chrome.tabs.query({}, (tabs) => {1812    for (const tab of tabs) {1813      if (tab.id !== undefined) {1814        chrome.tabs.sendMessage(tab.id, message).catch(() => {1815          // Tab may not have a content script — silently ignore1816        });1817      }1818    }1819  });1820}18211822function shouldRefreshAutoLock(1823  type: MessageType,1824  sender: Partial<chrome.runtime.MessageSender>,1825): boolean {1826  if (!isExtensionPageSender(sender)) return false;1827  return (1828    type !== "HAS_VAULT" &&1829    type !== "IS_UNLOCKED" &&1830    type !== "GET_VAULT_STATUS" &&1831    type !== "LOCK" &&1832    type !== "UPDATE_SETTINGS" &&1833    type !== "GET_PENDING_PASSKEY" &&1834    type !== "GET_PASSKEY_PROVIDER_STATE" &&1835    type !== "DECLINE_CARD_SAVE" &&1836    type !== "IS_CARD_DECLINED" &&1837    type !== "AUTOFILL_QUERY" &&1838    type !== "ML_PREDICT_BATCH"1839  );1840}18411842function isAllowedCanaryWebhookUrl(value: string): boolean {1843  try {1844    const url = new URL(value);1845    if (url.protocol !== "https:") return false;18461847    const hostname = url.hostname.toLowerCase();1848    if (1849      hostname === "localhost" ||1850      hostname.endsWith(".localhost") ||1851      isPrivateIpv4(hostname) ||1852      isPrivateIpv6(hostname)1853    ) {1854      return false;1855    }18561857    return true;1858  } catch {1859    return false;1860  }1861}18621863function isPrivateIpv4(hostname: string): boolean {1864  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1865    return true;1866  }18671868  const octets = hostname.split(".").map((part) => Number(part));1869  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1870    return false;1871  }18721873  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1874}18751876function isPrivateIpv6(hostname: string): boolean {1877  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1878  // IPv4-mapped IPv6 literals embed a plain IPv4 address that the prefix1879  // list below can never match (WHATWG URL serializes [::ffff:192.168.0.1]1880  // as ::ffff:c0a8:1). Unwrap and test the embedded IPv4; unparseable mapped1881  // tails fail closed. (Codex Security 2026-08-04 LOW,1882  // ssrf.webhook-url-private-ip-filter.) DNS rebinding is out of scope for a1883  // one-shot host check.1884  const mapped = /^::ffff:(.+)$/.exec(normalized);1885  if (mapped) {1886    const tail = mapped[1] ?? "";1887    if (tail.includes(".")) return isPrivateIpv4(tail);1888    const parts = tail.split(":");1889    const [hi, lo] = parts;1890    if (1891      parts.length !== 2 ||1892      !hi ||1893      !lo ||1894      !/^[0-9a-f]{1,4}$/.test(hi) ||1895      !/^[0-9a-f]{1,4}$/.test(lo)1896    ) {1897      return true;1898    }1899    const octets = [1900      (Number.parseInt(hi, 16) >>> 8) & 0xff,1901      Number.parseInt(hi, 16) & 0xff,1902      (Number.parseInt(lo, 16) >>> 8) & 0xff,1903      Number.parseInt(lo, 16) & 0xff,1904    ];1905    return isPrivateIpv4(octets.join("."));1906  }1907  return (1908    normalized === "::1" ||1909    normalized.startsWith("fc") ||1910    normalized.startsWith("fd") ||1911    normalized.startsWith("fe80:")1912  );1913}