messages.ts

79.5 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) && 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        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };958      }959      // Trusted full-entry fetch for extension-owned edit surfaces. Content960      // scripts route editing to the popup and cannot call this message.961      case "GET_ENTRY_FOR_EDIT": {962        if (isPageSender(sender)) return { ok: false, error: "invalid_sender" };963        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };964        const { id } = msg.payload as { id: string };965        const entry = vault.getEntryById(id);966        if (!entry) return { ok: false, error: "entry_not_found" };967968        const { passkey: _passkey, ...safeEntry } = entry;969        return { ok: true, data: safeEntry };970      }971      case "COPY": {972        // AUD-002: shape-validate the payload before passing to the clipboard973        // helper. A raw cast lets a malformed message reach the clipboard API974        // with a non-string and throw.975        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {976          text?: unknown;977          label?: unknown;978          alreadyWritten?: unknown;979        };980        if (typeof text !== "string" || typeof label !== "string") {981          return { ok: false, error: "invalid_payload" };982        }983        await copyToClipboard(text, label, Boolean(alreadyWritten));984        return { ok: true, clearSeconds: getEffectiveClearSeconds() };985      }986      case "CHECK_ALL_BREACHES": {987        const allEntries = vault.getEntries();988        const results: Record<string, number> = {};989        for (const entry of allEntries) {990          if (entry.type === "note") continue;991          if (!entry.password) continue;992          results[entry.id] = await vault.checkBreach(entry.password);993          // Small delay — be a good citizen to the HIBP API994          await new Promise((r) => setTimeout(r, 200));995        }996        // Persist any non-zero counts back to entries997        for (const [id, count] of Object.entries(results)) {998          const entry = vault.getEntryById(id);999          if (entry && (entry.breach ?? 0) !== count) {1000            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });1001          }1002        }1003        return { ok: true, data: results };1004      }1005      case "GET_SETTINGS":1006        return { ok: true, data: await vault.ensureSettingsLoaded() };1007      case "UPDATE_SETTINGS": {1008        const patch = msg.payload;1009        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {1010          return { ok: false, error: "invalid_payload" };1011        }1012        await vault.updateSettings(patch as vault.VaultSettings);1013        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {1014          await setupAutoLock();1015          if (vault.isUnlocked()) touchAutoLock();1016        }1017        return { ok: true };1018      }1019      case "SETUP_PIN": {1020        const { currentPassword, pin } = (msg.payload ?? {}) as {1021          currentPassword?: unknown;1022          pin?: unknown;1023        };1024        if (typeof currentPassword !== "string" || typeof pin !== "string") {1025          return { ok: false, error: "invalid_payload" };1026        }1027        return (await vault.setupPinUnlock(currentPassword, pin))1028          ? { ok: true }1029          : { ok: false, error: "incorrect_current_password" };1030      }1031      case "DISABLE_PIN": {1032        const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown };1033        if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" };1034        return (await vault.disablePinUnlock(currentPassword))1035          ? { ok: true }1036          : { ok: false, error: "incorrect_current_password" };1037      }1038      case "GET_PENDING_PASSKEY":1039        return { ok: true, data: await getPendingPasskeyRequest() };1040      case "APPROVE_PASSKEY": {1041        const { requestId } = msg.payload as { requestId: number };1042        await resolvePendingPasskeyRequest(requestId, true);1043        return { ok: true };1044      }1045      case "DENY_PASSKEY": {1046        const { requestId } = msg.payload as { requestId: number };1047        await resolvePendingPasskeyRequest(requestId, false);1048        return { ok: true };1049      }1050      case "GET_PASSKEY_PROVIDER_STATE":1051        return { ok: true, data: await getPasskeyProviderState() };1052      case "SET_PASSKEY_PROVIDER_ENABLED": {1053        const { enabled } = msg.payload as { enabled: boolean };1054        // Disabling is always free; gating fires only when a free user is1055        // trying to turn passkey interception on.1056        if (enabled) {1057          const gate = await requirePro("passkeys");1058          if (!gate.allowed) return { ok: false, error: "pro_required" };1059        }1060        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };1061      }1062      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS1063      // endpoint. Intentional product behavior — users configure their own1064      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private1065      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-1066      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to1067      // users that the entry title leaves the device when the canary fires.1068      case "FIRE_CANARY_PING": {1069        // Canary alert fires unconditionally for any entry with canary: true.1070        // The Pro gate only governs creation/flagging of canary entries; once1071        // an entry is flagged, the alert path is a security property and must1072        // never be license-gated.1073        const { webhookUrl, entryTitle, trigger } = msg.payload as {1074          webhookUrl: string;1075          entryTitle: string;1076          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";1077        };1078        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {1079          return { ok: false, error: "invalid_webhook_url" };1080        }1081        // LV-3: debounce non-test pings per (webhook, entry) so a page that1082        // strobes focus/fill events can't turn the canary into a request1083        // firehose at the user's endpoint. Test pings are exempt — they are1084        // explicit user clicks in the settings UI and are awaited for1085        // feedback. The FIRST ping in a window always goes out, so the1086        // dead-man's-switch property (canary fires on access) is preserved;1087        // only repeats within the window are coalesced.1088        if (trigger !== "test") {1089          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;1090          const stored = await chrome.storage.local.get(rlKey);1091          const last = (stored as Record<string, unknown>)[rlKey];1092          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {1093            return { ok: true, data: { rateLimited: true } };1094          }1095          await chrome.storage.local.set({ [rlKey]: Date.now() });1096        }1097        const body = JSON.stringify({1098          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",1099          entry: entryTitle,1100          trigger,1101          timestamp: new Date().toISOString(),1102          source: "peach-extension",1103        });1104        if (trigger === "test") {1105          // Permitted outbound fetch: user-configured canary alert endpoint1106          // (validated by isAllowedCanaryWebhookUrl above). This is the1107          // only non-HIBP outbound call in the extension — see1108          // Projects.md §3.7. Test pings are awaited so the UI can show1109          // success/failure.1110          try {1111            const res = await fetch(webhookUrl, {1112              method: "POST",1113              headers: { "Content-Type": "application/json" },1114              body,1115            });1116            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1117          } catch (err) {1118            return { ok: false, error: err instanceof Error ? err.message : "network_error" };1119          }1120        }1121        // Non-test triggers are fire-and-forget1122        fetch(webhookUrl, {1123          method: "POST",1124          headers: { "Content-Type": "application/json" },1125          body,1126        }).catch(() => {});1127        return { ok: true };1128      }1129      case "ACTIVATE_LICENSE": {1130        const { key } = msg.payload as { key: string };1131        const licenseInfo = await activateLicense(key);1132        return { ok: true, data: licenseInfo };1133      }1134      case "GET_LICENSE": {1135        const licenseInfo = await getLicenseInfo();1136        return { ok: true, data: licenseInfo };1137      }1138      case "GET_LICENSE_KEY": {1139        const key = await getLicenseKey();1140        return { ok: true, data: key };1141      }1142      case "DEACTIVATE_LICENSE": {1143        await deactivateLicense();1144        return { ok: true };1145      }1146      case "SHOULD_PLAY_CELEBRATION": {1147        const should = await shouldPlayCelebration();1148        return { ok: true, data: should };1149      }1150      case "MARK_CELEBRATION_PLAYED": {1151        await markCelebrationPlayed();1152        return { ok: true };1153      }1154      case "GET_CODEX_VAULT_DATA": {1155        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1156        // popup navigates to the License section without further coordination.1157        // Also privileged-page-gated (PB-26-001), and recoveryWords inside the1158        // snapshot additionally require a fresh master-password proof.1159        const gate = await requirePro("codex");1160        if (!gate.allowed) return { ok: false, error: "pro_required" };1161        const { password } = (msg.payload ?? {}) as { password?: string };1162        return await handleGetCodexVaultData(password);1163      }1164      case "ESTIMATE_CODEX_PAGES": {1165        const gate = await requirePro("codex");1166        if (!gate.allowed) return { ok: false, error: "pro_required" };1167        return await handleEstimateCodexPages();1168      }1169      case "RESTORE_FROM_CODEX": {1170        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1171        // be able to restore a vault that was printed by a Pro user.1172        // DO NOT add a Pro gate here.1173        const payload = msg.payload as CodexRestorePayload;1174        return await handleRestoreFromCodex(payload);1175      }1176      case "OPEN_PRO_GATE": {1177        // Content script requests: open popup and navigate to License section.1178        const { feature } = (msg.payload ?? {}) as { feature?: string };1179        if (chrome.storage.session) {1180          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1181        }1182        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1183        return { ok: true };1184      }1185      case "OPEN_POPUP": {1186        // Content script asks to open the trusted extension popup — used by the1187        // inline locked bubble so the master password is entered in the popup,1188        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1189        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1190        // toolbar icon. The badge already signals Peach needs attention.1191        //1192        // Set a session flag so the popup knows it was opened for inline unlock1193        // and should close itself once the vault is unlocked (returning the user1194        // to the inline autofill selector on the page).1195        const { entryId } = (msg.payload ?? {}) as { entryId?: unknown };1196        if (entryId !== undefined && (typeof entryId !== "string" || entryId.length === 0 || entryId.length > 64)) {1197          return { ok: false, error: "invalid_payload" };1198        }1199        if (chrome.storage.session) {1200          if (typeof entryId === "string") {1201            await chrome.storage.session.set({ peach_open_entry: entryId });1202          } else {1203            await chrome.storage.session.set({ peach_inline_unlock: true });1204          }1205        }1206        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1207        return { ok: true };1208      }1209      case "OPEN_DETACHED_POPUP": {1210        // A window created by the action popup and then orphaned with1211        // window.close() is cascaded shut by Chrome, so the file-picker1212        // flows (OS dialogs that dismiss the popup on focus loss) ask the SW1213        // to open the standalone window instead — the SW has no window to be1214        // associated with. The query string is allowlisted so this can never1215        // open an arbitrary URL.1216        const { route } = (msg.payload ?? {}) as { route?: string };1217        const search = route === "peachscript"1218          ? "?restore=peachscript"1219          : route === "csv"1220            ? "?restore=csv"1221            : route === "codex-pdf"1222              ? "?codex=pdf"1223              : null;1224        if (!search) return { ok: false, error: "bad_route" };1225        try {1226          const popupHtml =1227            chrome.runtime.getManifest().action?.default_popup ?? "src/popup/index.html";1228          await chrome.windows.create({1229            url: chrome.runtime.getURL(`${popupHtml}${search}`),1230            type: "popup",1231            width: 320,1232            height: 550,1233          });1234          return { ok: true, data: { detached: true } };1235        } catch {1236          return { ok: false };1237        }1238      }1239      case "GET_IDENTITIES": {1240        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1241        return { ok: true, data: vault.getIdentities() };1242      }1243      case "TOUCH_AUTO_LOCK": {1244        // touchAutoLock() is already called by shouldRefreshAutoLock above;1245        // this case just gives the popup a typed message to keep the session alive.1246        return { ok: true };1247      }1248      case "GET_ADVANCED_HEALTH_REPORT": {1249        const gate = await requirePro("advanced_health");1250        if (!gate.allowed) return { ok: false, error: "pro_required" };1251        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1252        const report = await buildAdvancedHealthReport(vault.getEntries());1253        return { ok: true, data: report };1254      }1255      case "IS_DURESS_ENABLED": {1256        const enabled = await vault.isDuressEnabled();1257        return { ok: true, data: enabled };1258      }1259      case "SETUP_DURESS": {1260        // Single enforcement point for the Duress Vault Pro gate. Free users1261        // who somehow reach this handler are rejected here; the popup also1262        // pre-checks isPro() to avoid showing the setup form to free users,1263        // but server-side is the actual security boundary.1264        const gate = await requirePro("duress_vault");1265        if (!gate.allowed) return { ok: false, error: "pro_required" };1266        // MV3 service workers restart after inactivity, losing the in-memory1267        // derived key. Detect this before calling setupDuress so the popup1268        // can show a meaningful prompt to re-lock and re-unlock.1269        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1270        const { duressPassword } = msg.payload as { duressPassword: string };1271        await vault.setupDuress(duressPassword);1272        return { ok: true };1273      }1274      case "DISABLE_DURESS": {1275        await vault.disableDuress();1276        return { ok: true };1277      }1278      case "VERIFY_MAIN_PASSWORD": {1279        const { password } = msg.payload as { password: string };1280        const ok = await vault.verifyMainPassword(password);1281        return { ok: true, data: ok };1282      }1283      case "CHANGE_PASSWORD": {1284        const { currentPassword, newPassword } = msg.payload as {1285          currentPassword: string;1286          newPassword: string;1287        };1288        const changed = await vault.changePassword(currentPassword, newPassword);1289        return changed1290          ? { ok: true }1291          : { ok: false, error: "incorrect_current_password" };1292      }1293      case "GET_SITE_PASSWORD_POLICY": {1294        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1295        if (!tab?.id) return { ok: true, data: null };1296        try {1297          const response = await chrome.tabs.sendMessage(tab.id, {1298            type: "GET_SITE_PASSWORD_POLICY",1299          });1300          return (response as MessageResponse) ?? { ok: true, data: null };1301        } catch {1302          return { ok: true, data: null };1303        }1304      }1305      case "RECORD_MANUAL_SUMMON": {1306        const { domain } = msg.payload as { domain: string };1307        const settings = vault.getSettings();1308        const existing = settings.manualSummonDomains?.[domain];1309        const now = Date.now();1310        await vault.updateSettings({1311          manualSummonDomains: {1312            ...settings.manualSummonDomains,1313            [domain]: {1314              firstSummonedAt: existing?.firstSummonedAt ?? now,1315              summonCount: (existing?.summonCount ?? 0) + 1,1316              lastSummonedAt: now,1317            },1318          },1319        });1320        return { ok: true };1321      }1322      case "DECLINE_CARD_SAVE": {1323        // PB-26-108: the declined-card digest is keyed by root-key material, so1324        // a decline cannot be recorded while locked. Offers are not shown while1325        // locked either, so this is unreachable in practice.1326        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1327        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1328        await vault.declineCardSaveOffer(last4, expMonth, expYear);1329        return { ok: true };1330      }1331      case "IS_CARD_DECLINED": {1332        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1333        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1334        return { ok: true, data: declined };1335      }1336      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1337        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1338          rpId?: string;1339          rpName?: string;1340          userName?: string;1341          userDisplayName?: string;1342        };1343        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1344        return await initiateFirefoxPasskeyCreate({1345          rpId,1346          rpName: rpName ?? rpId,1347          userName,1348          userDisplayName,1349        }, attestedSenderOrigin(sender));1350      }13511352      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1353        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1354        if (!payload) return { ok: false, error: "missing_payload" };1355        return await completeFirefoxPasskeyCreate(payload);1356      }13571358      case "PASSKEY_OFFER_DECLINE": {1359        const { domain } = (msg.payload ?? {}) as { domain?: string };1360        const origin = attestedSenderOrigin(sender);1361        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1362        await recordPasskeyOfferDecline(domain);1363        return { ok: true };1364      }13651366      case "GET_PASSKEY_OFFER_DECLINED": {1367        const { domain } = (msg.payload ?? {}) as { domain?: string };1368        const origin = attestedSenderOrigin(sender);1369        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1370        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1371      }13721373      case "PASSKEY_HAS_CREDENTIALS": {1374        const payload = msg.payload as {1375          rpId?: string;1376          allowCredentials?: Array<{ id: string; type?: string }>;1377        } | undefined;1378        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1379        return await handlePasskeyHasCredentials({1380          rpId: payload.rpId,1381          allowCredentials: payload.allowCredentials ?? [],1382        }, attestedSenderOrigin(sender));1383      }13841385      case "PASSKEY_CREATE": {1386        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1387        if (!payload?.rpId || !payload?.userName) {1388          return { ok: false, error: "rpid_and_username_required" };1389        }1390        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1391      }13921393      case "PASSKEY_GET": {1394        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1395        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1396        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1397      }13981399      case "PASSKEY_AUTH_RESPONSE": {1400        const { requestId, approved } = (msg.payload ?? {}) as {1401          requestId?: string | number;1402          approved?: boolean;1403        };1404        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1405          return { ok: false, error: 'requestId and approved required' };1406        }1407        const pending = await getPendingPasskeyRequest();1408        const senderOrigin = attestedSenderOrigin(sender);1409        if (1410          (pending && pending.requestId !== Number(requestId)) ||1411          (pending?.tabId !== undefined && sender.tab?.id !== pending.tabId) ||1412          (pending?.origin !== undefined && senderOrigin !== pending.origin)1413        ) {1414          return { ok: false, error: "invalid_passkey_approval_sender" };1415        }1416        await resolvePendingPasskeyRequest(Number(requestId), approved);1417        return { ok: true };1418      }14191420      case "GET_PASSKEY_FOR_DOMAIN": {1421        const { domain } = (msg.payload ?? {}) as { domain?: string };1422        if (!domain) return { ok: false, error: "domain_required" };1423        // Scope to the caller's own origin: a page may only ask about passkeys1424        // for a domain it actually owns, so an arbitrary page cannot enumerate1425        // which sites the user holds passkeys for or read the username (audit MEDIUM).1426        const origin = attestedSenderOrigin(sender);1427        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1428        if (!vault.isUnlocked()) return { ok: true, data: null };1429        const match = vault1430          .getEntries()1431          .find((entry) => entry.passkey?.rpId === domain);1432        if (!match || !match.passkey) return { ok: true, data: null };1433        // Slim shape — only the fields State 11 needs. Never expose private1434        // key material, even though this is locked behind isUnlocked.1435        // bannerShown is the per-domain "already surfaced" flag, kept in1436        // trusted background session storage so content scripts never touch1437        // chrome.storage.session directly (PB-26-203).1438        let bannerShown = false;1439        if (chrome.storage.session) {1440          const flag = await chrome.storage.session.get(`peach_state11_shown:${domain}`);1441          bannerShown = Boolean((flag as Record<string, unknown>)[`peach_state11_shown:${domain}`]);1442        }1443        return {1444          ok: true,1445          data: {1446            rpId: match.passkey.rpId,1447            userName: match.passkey.userName,1448            browser: match.passkey.browser,1449            bannerShown,1450          },1451        };1452      }14531454      case "MARK_PASSKEY_BANNER_SHOWN": {1455        const { domain } = (msg.payload ?? {}) as { domain?: string };1456        if (typeof domain !== "string" || !domain) return { ok: false, error: "domain_required" };1457        // Same origin binding as the read path: a page may only mark its own1458        // domain, and the flag reveals nothing either way.1459        const origin = attestedSenderOrigin(sender);1460        if (!origin || !isValidRpId(domain, origin)) return { ok: true };1461        if (chrome.storage.session) {1462          await chrome.storage.session.set({ [`peach_state11_shown:${domain}`]: Date.now() });1463        }1464        return { ok: true };1465      }14661467      case "DESTROY_VAULT": {1468        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1469        // storage.local.clear() wipes every Peach key (slots, settings, license,1470        // onboarded flag, history, sync state, declined cards, recall, etc.);1471        // session.clear() wipes pending passkey requests + pro-notice queues.1472        // Caller (Panic.tsx) handles UI navigation back to onboarding.1473        //1474        // The Pro license is the one thing that must survive: the user paid for1475        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1476        // Capture it before the clear and restore it after. peach_pro_celebrated1477        // rides along so the Pro celebration doesn't replay on the next unlock.1478        const preserved = await chrome.storage.local.get([1479          "peach_license",1480          "peach_pro_celebrated",1481        ]);1482        await vault.lock();1483        await storageClear();1484        await vault.clearVaultHistory();1485        const toRestore: Record<string, unknown> = {};1486        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1487        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1488        if (Object.keys(toRestore).length > 0) {1489          await chrome.storage.local.set(toRestore);1490        }1491        if (chrome.storage.session) {1492          await chrome.storage.session.clear();1493        }1494        await clearRecoveryConfirmPending();1495        return { ok: true };1496      }14971498      case "GET_IDENTITY_SUGGESTIONS": {1499        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1500        const entries = vault.getEntries();1501        const suggestions = buildIdentitySuggestions(entries);1502        return { ok: true, data: { suggestions } };1503      }1504      case "ML_INIT":1505        return { ok: true };15061507      case "ML_PREDICT_BATCH": {1508        // AUD-002: shape-validate before forwarding to the ML helper.1509        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1510        if (!Array.isArray(featuresArray)) {1511          return { ok: false, error: "invalid_payload" };1512        }1513        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1514      }15151516      // ── Vault sync (v3) ───────────────────────────────────────────────1517      // Returns the public-facing local identity needed by the popup to1518      // drive Phase-1 audio pairing. The private long-term key never1519      // leaves the background.1520      case "GET_LOCAL_IDENTITY": {1521        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1522        // Pro license from an already-Pro peer (at least one device must be Pro).1523        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1524        // Identity derives from the stable root key, not the password-derived1525        // key, so pairing survives a master-password change (SEV-2-B).1526        const masterKeyHex = vault.getRootKeyHex();1527        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1528        const masterKey = unhexBytes(masterKeyHex);1529        try {1530          const identity = await buildLocalIdentity(masterKey);1531          // If this device is Pro, advertise the signed license so the peer can1532          // activate it after SAS confirmation — pairing carries Pro across.1533          if (await isProUser()) {1534            const license = await getLicenseKey();1535            if (license) (identity as { license?: string }).license = license;1536          }1537          return { ok: true, data: identity };1538        } finally {1539          masterKey.fill(0);1540        }1541      }15421543      case "LIST_PAIRED_DEVICES": {1544        const devices = await listPairedDevicesV3();1545        return { ok: true, data: { devices } };1546      }15471548      case "RENAME_PAIRED_DEVICE": {1549        const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string };1550        if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") {1551          return { ok: false, error: "invalid_payload" };1552        }1553        await renamePairedDeviceV3(deviceId, name);1554        return { ok: true };1555      }15561557      case "UNPAIR_DEVICE": {1558        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1559        if (typeof deviceId !== "string" || !deviceId) {1560          return { ok: false, error: "invalid_payload" };1561        }1562        // Removing a device REVOKES it rather than just dropping the local1563        // row: a plain removal is undone the moment any other peer vouches it1564        // back through a manifest, which is exactly what the relay makes easy.1565        await revokeDeviceByIdV3(deviceId, await getOrCreateDeviceId());1566        // PB-26-213: forget the secret now so no further dial can use it.1567        // Removals that happen while locked leave orphans for the next1568        // unlock's reconcile to prune.1569        const unpairRootHex = vault.getRootKeyHex();1570        if (unpairRootHex) {1571          const unpairRoot = unhexBytes(unpairRootHex);1572          try {1573            await dropPairSecret(deviceId, unpairRoot);1574          } finally {1575            unpairRoot.fill(0);1576          }1577        } else {1578          await dropPairSecret(deviceId, null);1579        }1580        // Sync against the remaining hosts — the unpaired device no longer1581        // matters but the next alarm tick is up to ten minutes away.1582        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1583        return { ok: true };1584      }15851586      case "RENAME_LOCAL_DEVICE": {1587        const { name } = (msg.payload ?? {}) as { name?: string };1588        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1589        await setDeviceNameV3(name);1590        return { ok: true };1591      }15921593      // ── Relay pairing ─────────────────────────────────────────────────────1594      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1595      // session runs in the background; the SAS and the terminal result reach1596      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1597      case "START_ADOPTION_SOURCE": {1598        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1599        if (isRelayAdoptionSourceInFlight()) {1600          return { ok: false, error: "adoption_source_in_progress" };1601        }1602        try {1603          return { ok: true, data: await startRelayAdoptionSource() };1604        } catch (error) {1605          return {1606            ok: false,1607            error: error instanceof Error ? error.message : "adoption_source_failed",1608          };1609        }1610      }16111612      // Onboarding receiver — empty extension shows a QR, phone scans and1613      // sends the vault. The popup supplies the local-only password here so1614      // the background can wrap the adopted root key at rest without ever1615      // asking the user to retype it.1616      case "START_ADOPTION_RECEIVER": {1617        if (isRelayAdoptionSourceInFlight()) {1618          return { ok: false, error: "adoption_receiver_in_progress" };1619        }1620        const password = (msg.payload as { password?: unknown } | undefined)?.password;1621        if (typeof password !== "string" || password.length === 0) {1622          return { ok: false, error: "invalid_payload" };1623        }1624        try {1625          return { ok: true, data: await startRelayAdoptionReceiver(password) };1626        } catch (error) {1627          return {1628            ok: false,1629            error: error instanceof Error ? error.message : "adoption_receiver_failed",1630          };1631        }1632      }16331634      // Popup→bg counterpart to ADOPTION_SOURCE_SAS (receiver flow).1635      // The receiver now auto-accepts the SAS (both sides derive it from the1636      // same Noise handshake hash, so the codes match by construction) so1637      // the popup never has a SAS screen to tap on. The id round-trips the1638      // same way so a stale late response can't approve the wrong session.1639      // Popup→bg counterpart for the source flow: Confirm/Cancel on the1640      // source's SAS screen.16411642      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1643      // on the source's SAS screen. The id round-trips the same way so a stale1644      // late response can't approve the wrong session.1645      case "SOURCE_SAS_DECISION": {1646        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1647        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1648          return { ok: false, error: "invalid_payload" };1649        }1650        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1651      }16521653      case "CANCEL_ADOPTION_SOURCE": {1654        cancelRelayAdoptionSource();1655        return { ok: true };1656      }16571658      case "TRIGGER_SYNC": {1659        const payload = (msg.payload ?? {}) as {1660          reason?: "vault_change" | "foreground" | "manual";1661          force?: boolean;1662        };1663        const reason = payload.reason ?? "foreground";16641665        void triggerSyncIfReachable({ reason, force: payload.force === true });1666        return { ok: true };1667      }16681669      case "GET_SYNC_STATE": {1670        return { ok: true, data: getSyncState() };1671      }16721673      case "GET_SYNC_SETTINGS": {1674        return { ok: true, data: await getSyncSettings() };1675      }16761677      case "SET_SYNC_SETTINGS": {1678        const payload = (msg.payload ?? {}) as {1679          mode?: unknown;1680          relayUrl?: unknown;1681        };1682        try {1683          // A custom relay URL implies private mode; Peach's own relay stays1684          // public. See setRelayUrl.1685          if (payload.relayUrl !== undefined) {1686            if (typeof payload.relayUrl !== "string") {1687              return { ok: false, error: "invalid_relay_url" };1688            }1689            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1690          }1691          if (payload.mode !== undefined) {1692            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1693              return { ok: false, error: "invalid_sync_mode" };1694            }1695            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1696          }1697          return { ok: true, data: await getSyncSettings() };1698        } catch (error) {1699          return {1700            ok: false,1701            error: error instanceof Error ? error.message : "invalid_relay_url",1702          };1703        }1704      }17051706      case "GET_SYNC_ALERTS": {1707        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1708        const alerts = await getPendingSyncAlerts();1709        // The popup reads on open and acknowledges with consume:true after1710        // rendering, so a popup crash between read and render doesn't lose1711        // the alerts.1712        if (consume) await clearPendingSyncAlerts();1713        return { ok: true, data: alerts };1714      }17151716      case "GET_PENDING_VOUCHED_DEVICES": {1717        return { ok: true, data: await listPendingVouchedDevices() };1718      }1719      case "CONFIRM_VOUCHED_DEVICE": {1720        const { deviceId } = msg.payload as { deviceId: string };1721        const pending = await getPendingVouchedDevice(deviceId);1722        if (!pending) return { ok: false, error: "not_pending" };1723        // Last gate before a vouched device becomes a sync peer. A queue entry1724        // can predate the revocation that names it, so revocation is re-checked1725        // here rather than trusted to have swept the queue.1726        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {1727          await removePendingVouchedDevice(deviceId);1728          return { ok: false, error: "device_revoked" };1729        }1730        await upsertPairedDeviceV3({1731          deviceId: pending.deviceId,1732          deviceName: pending.deviceName,1733          deviceType:1734            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1735          longTermPublicKeyHex: pending.longTermPublicKeyHex,1736          signingPublicKeyHex: pending.signingPublicKeyHex,1737          wsPort: pending.wsPort,1738          pairedAt: pending.pairedAt,1739          trustSource: "vouched",1740        });1741        await removePendingVouchedDevice(deviceId);1742        // Newly confirmed vouched device is now a sync target — kick a round1743        // so the mesh introduction pays off without a 10-minute wait.1744        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1745        return { ok: true };1746      }1747      case "REJECT_VOUCHED_DEVICE": {1748        const { deviceId } = msg.payload as { deviceId: string };1749        await removePendingVouchedDevice(deviceId);1750        return { ok: true };1751      }1752      case "ROTATE_SYNC_IDENTITY": {1753        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1754        const result = await vault.rotateSyncIdentity();1755        return result.ok ? { ok: true } : { ok: false, error: result.error };1756      }17571758      default:1759        return { ok: false, error: "unknown_message_type" };1760    }1761  } catch (err) {1762    return {1763      ok: false,1764      error: err instanceof Error ? err.message : "operation_failed",1765    };1766  }1767}17681769// Returns username use-counts from the vault, sorted by frequency. Each row1770// also carries the entry's email so the popup can suggest the email/username1771// pair the user has actually used together.1772function buildIdentitySuggestions(1773  entries: VaultEntry[],1774): Array<{ email: string; username: string; count: number }> {1775  const usernameCounts = new Map<string, number>();1776  const usernameEmail = new Map<string, string>();1777  for (const entry of entries) {1778    const username = entry.username ?? "";1779    const email = (entry as VaultEntry & { email?: string }).email ?? "";1780    if (!username && !email) continue;1781    const key = username || email;1782    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1783    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1784  }1785  return Array.from(usernameCounts.entries())1786    .sort((a, b) => b[1] - a[1])1787    .map(([username, count]) => ({1788      email: usernameEmail.get(username) ?? "",1789      username,1790      count,1791    }));1792}17931794/** Notify all content scripts that the vault just became available. */1795function broadcastToContentScripts(message: { type: string }): void {1796  if (!chrome.tabs?.query) return;1797  chrome.tabs.query({}, (tabs) => {1798    for (const tab of tabs) {1799      if (tab.id !== undefined) {1800        chrome.tabs.sendMessage(tab.id, message).catch(() => {1801          // Tab may not have a content script — silently ignore1802        });1803      }1804    }1805  });1806}18071808function shouldRefreshAutoLock(type: MessageType): boolean {1809  return (1810    type !== "HAS_VAULT" &&1811    type !== "IS_UNLOCKED" &&1812    type !== "GET_VAULT_STATUS" &&1813    type !== "LOCK" &&1814    type !== "UPDATE_SETTINGS" &&1815    type !== "GET_PENDING_PASSKEY" &&1816    type !== "GET_PASSKEY_PROVIDER_STATE" &&1817    type !== "DECLINE_CARD_SAVE" &&1818    type !== "IS_CARD_DECLINED" &&1819    type !== "AUTOFILL_QUERY" &&1820    type !== "ML_PREDICT_BATCH"1821  );1822}18231824function isAllowedCanaryWebhookUrl(value: string): boolean {1825  try {1826    const url = new URL(value);1827    if (url.protocol !== "https:") return false;18281829    const hostname = url.hostname.toLowerCase();1830    if (1831      hostname === "localhost" ||1832      hostname.endsWith(".localhost") ||1833      isPrivateIpv4(hostname) ||1834      isPrivateIpv6(hostname)1835    ) {1836      return false;1837    }18381839    return true;1840  } catch {1841    return false;1842  }1843}18441845function isPrivateIpv4(hostname: string): boolean {1846  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1847    return true;1848  }18491850  const octets = hostname.split(".").map((part) => Number(part));1851  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1852    return false;1853  }18541855  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1856}18571858function isPrivateIpv6(hostname: string): boolean {1859  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1860  // IPv4-mapped IPv6 literals embed a plain IPv4 address that the prefix1861  // list below can never match (WHATWG URL serializes [::ffff:192.168.0.1]1862  // as ::ffff:c0a8:1). Unwrap and test the embedded IPv4; unparseable mapped1863  // tails fail closed. (Codex Security 2026-08-04 LOW,1864  // ssrf.webhook-url-private-ip-filter.) DNS rebinding is out of scope for a1865  // one-shot host check.1866  const mapped = /^::ffff:(.+)$/.exec(normalized);1867  if (mapped) {1868    const tail = mapped[1] ?? "";1869    if (tail.includes(".")) return isPrivateIpv4(tail);1870    const parts = tail.split(":");1871    const [hi, lo] = parts;1872    if (1873      parts.length !== 2 ||1874      !hi ||1875      !lo ||1876      !/^[0-9a-f]{1,4}$/.test(hi) ||1877      !/^[0-9a-f]{1,4}$/.test(lo)1878    ) {1879      return true;1880    }1881    const octets = [1882      (Number.parseInt(hi, 16) >>> 8) & 0xff,1883      Number.parseInt(hi, 16) & 0xff,1884      (Number.parseInt(lo, 16) >>> 8) & 0xff,1885      Number.parseInt(lo, 16) & 0xff,1886    ];1887    return isPrivateIpv4(octets.join("."));1888  }1889  return (1890    normalized === "::1" ||1891    normalized.startsWith("fc") ||1892    normalized.startsWith("fd") ||1893    normalized.startsWith("fe80:")1894  );1895}