messages.ts

78.0 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";84// Sync and pairing are imported statically, never with `await import()`.85// `import()` throws `TypeError: import() is disallowed on86// ServiceWorkerGlobalScope` at runtime in MV3, and Vite's preload helper87// reports the failure through `window.dispatchEvent`, which does not exist in88// a worker either — so the real reason was replaced by "window is not defined"89// and the pairing UI just stopped. scripts/check-sw-static-imports.mjs fails90// the build if a runtime import() reappears anywhere in the worker's graph.91import {92  cancelRelayAdoptionSource,93  isRelayAdoptionSourceInFlight,94  resolveSourceSasConfirmation,95  startRelayAdoptionReceiver,96  startRelayAdoptionSource,97} from "./relay-adoption-bg";98import {99  getSyncSettings,100  setRelayUrl,101  setSyncMode,102  type SyncMode,103} from "./sync-settings";104import {105  getSyncState,106  triggerSyncIfReachable,107} from "./sync-trigger";108import { isMessageSenderAllowed } from "./message-policy";109110// Compile-time E2E flag, folded to a literal by Vite's `define` (false in111// every production build — verified in the bundled output). Mirrors the112// create-path bypass in passkey.ts so the Playwright passkey smoke can enable113// the provider without a real Pro licence; the gate is fully intact for users.114declare const __PEACH_E2E_PASSKEYS__: boolean;115const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true;116117function unhexBytes(hex: string): Uint8Array {118  if (hex.length % 2 !== 0) throw new Error("invalid hex");119  const out = new Uint8Array(hex.length / 2);120  for (let i = 0; i < out.length; i++) {121    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);122  }123  return out;124}125126/**127 * The single Pro gate. Every gated handler calls this first; the broadcast128 * lets the popup react (navigate to the License section, highlight the129 * relevant feature). Background never touches the popup view directly —130 * the popup owns navigation. See Projects.md "Pro gate rule".131 */132async function requirePro(133  feature: ProFeature,134  trigger: "user" | "background" = "user"135): Promise<{ allowed: boolean }> {136  if (PASSKEY_E2E_PRO_BYPASS && feature === "passkeys") return { allowed: true };137  if (await isProUser()) return { allowed: true };138139  if (trigger === "user") {140    // User deliberately triggered this feature — redirect the popup immediately.141    chrome.runtime142      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })143      .catch(() => {144        // Popup may be closed — the gate signal is best-effort.145      });146  } else {147    // Background trigger (e.g. passive sync initiation) — no popup is open.148    // Queue a notice so the next popup open shows a soft banner instead of149    // silently failing.150    if (chrome.storage.session) {151      chrome.storage.session152        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })153        .catch(() => {});154    }155  }156157  return { allowed: false };158}159160// LV-3: minimum interval between non-test canary pings per webhook+entry.161const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour162163const PRIVATE_IPV4_RANGES = [164  { prefix: "10." },165  { prefix: "127." },166  { prefix: "169.254." },167  { prefix: "192.168." },168];169170export function setupMessageHandler(): void {171  chrome.runtime.onMessage.addListener(172    (msg: unknown, sender, sendResponse) => {173      if (!isMessage(msg)) {174        sendResponse({ ok: false, error: "invalid_message" });175        return true;176      }177      handleMessage(msg, sender)178        .then(sendResponse)179        .catch((err) =>180          sendResponse({181            ok: false,182            error: err instanceof Error ? err.message : String(err),183          })184        );185      return true;186    }187  );188}189190function isMessage(m: unknown): m is Message {191  return typeof m === "object" && m !== null && "type" in m;192}193194/**195 * The browser-attested origin of the page that originated this message. A web196 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),197 * so every page-driven message arrives via the content-script relay and the198 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a199 * value the page cannot forge. This is the ONLY trustworthy origin for passkey200 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.201 */202function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {203  if (sender.origin) return sender.origin;204  if (sender.url) {205    try { return new URL(sender.url).origin; } catch { return undefined; }206  }207  return undefined;208}209210function isExtensionPageSender(sender: Partial<chrome.runtime.MessageSender>): boolean {211  return sender.url?.startsWith("chrome-extension://") === true ||212    sender.url?.startsWith("moz-extension://") === true;213}214215/** True when the message came from a page frame rather than extension UI. */216function isPageSender(sender: Partial<chrome.runtime.MessageSender>): boolean {217  return !isExtensionPageSender(sender) &&218    (sender.tab !== undefined || sender.url !== undefined);219}220221function entryDomains(url: unknown, additionalUrls: unknown): Set<string> {222  const domains = new Set<string>();223  const primary = typeof url === "string" ? extractDomain(url) : null;224  if (primary) domains.add(primary);225  if (Array.isArray(additionalUrls)) {226    for (const extra of additionalUrls) {227      if (typeof extra !== "string") continue;228      const domain = extractDomain(extra);229      if (domain) domains.add(domain);230    }231  }232  return domains;233}234235/**236 * PB-26-106: the autofill read path re-validates the frame origin against the237 * entry's domains on every request, so an unbound write path would let a238 * content script repoint an entry at its own origin and then read the239 * credential through a read path that is behaving correctly.240 *241 * Creating an entry: a page may only bind it to itself. Mutating one: a page242 * may never GROW the domain set — only shrink it, and never below its own243 * attested origin.244 *245 * Self-binding on mutation was considered and is not enough: the content246 * script on a foreign origin IS the attacker in the reported chain, so letting247 * it attach "its own" origin lets it mint the very capability the read path248 * exists to withhold. The legitimate flow that needs a new domain — the inline249 * "remember this site" toast — therefore asks the popup instead250 * (REQUEST_REMEMBER_SITE), which is an extension page and exempt here.251 *252 * Extension pages are exempt: the popup edits entries for sites it is not on.253 */254function senderMayBindEntryDomains(255  sender: Partial<chrome.runtime.MessageSender>,256  domains: Set<string>,257): boolean {258  if (isExtensionPageSender(sender)) return true;259  const domain = attestedSenderDomain(sender);260  if (domain === null) return false;261  for (const candidate of domains) {262    if (candidate !== domain) return false;263  }264  return true;265}266267function senderMayMutateEntryDomains(268  sender: Partial<chrome.runtime.MessageSender>,269  before: Set<string>,270  after: Set<string>,271): boolean {272  if (isExtensionPageSender(sender)) return true;273  const domain = attestedSenderDomain(sender);274  if (domain === null || !after.has(domain)) return false;275  for (const kept of after) {276    if (!before.has(kept)) return false;277  }278  return true;279}280281/**282 * Null for extension pages (which the callers exempt), for senders with no283 * attested origin at all, and for unparseable frame urls.284 */285function attestedSenderDomain(sender: Partial<chrome.runtime.MessageSender>): string | null {286  if (sender.tab === undefined && sender.url === undefined) return null;287  const origin = attestedSenderOrigin(sender);288  if (!origin) return null;289  try { return extractDomain(new URL(origin).hostname); } catch { return null; }290}291292function patchChangesEntryOrigin(patch: object): boolean {293  return Object.hasOwn(patch, "url") || Object.hasOwn(patch, "additionalUrls");294}295296/** The entry's domain-bearing fields as the patch would leave them. */297function patchedUrlShape(298  patch: object,299  existing: Pick<VaultEntry, "url" | "additionalUrls">,300): { url: unknown; additionalUrls: unknown } {301  const candidate = patch as { url?: unknown; additionalUrls?: unknown };302  return {303    url: Object.hasOwn(patch, "url") ? candidate.url : existing.url,304    additionalUrls: Object.hasOwn(patch, "additionalUrls")305      ? candidate.additionalUrls306      : existing.additionalUrls,307  };308}309// Resolves once restoreFromSession() has run, so handlers see the correct310// post-restore unlock state. entry.ts registers this BEFORE the message311// handler so the onMessage listener is added synchronously at SW startup312// (MV3 requirement) while unlock-dependent handlers still wait for restore.313let restoreReady: Promise<void> = Promise.resolve();314315/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */316export function setRestoreReady(p: Promise<unknown>): void {317  restoreReady = p.then(() => undefined, () => undefined);318}319320export async function handleMessage(321  msg: Message,322  sender: Partial<chrome.runtime.MessageSender> = {}323): Promise<MessageResponse> {324  try {325    // Wait for session-restore to finish before reading any unlock/vault state.326    // On a cold SW start the popup's first message arrives while restore is327    // still in flight; without this gate IS_UNLOCKED would report locked (a328    // spurious lock screen) and the storage reads could race. The onMessage329    // listener itself is registered synchronously (entry.ts) so this gate, not330    // listener registration, is what absorbs the cold-start window.331    await restoreReady;332    // Validate sender — only allow messages from our extension pages/scripts.333    // `sender.id` is undefined for messages originating from extension UI334    // (popup/options), which is legitimate; reject only when it is defined335    // and does not match our extension id.336    if (337      sender.id !== undefined &&338      sender.id !== chrome.runtime.id339    ) {340      return { ok: false, error: "invalid_sender" };341    }342343    // PB-26-016: sender authorization is an exhaustive policy, not a344    // hand-maintained privileged denylist. A missing/unknown policy entry or a345    // background-only message fails closed before any handler runs.346    // Extension UI messages may legitimately omit sender.url. Resolve the347    // browser-attested extension origin only when a URL is present; this also348    // keeps test/runtime shims without getURL fail-closed for URL-bearing349    // senders instead of throwing before policy evaluation.350    const extensionOrigin = sender.url && typeof chrome.runtime.getURL === "function"351      ? chrome.runtime.getURL("")352      : "";353    if (!isMessageSenderAllowed(msg.type, sender, chrome.runtime.id, extensionOrigin)) {354      return { ok: false, error: "invalid_sender" };355    }356357    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {358      touchAutoLock();359    }360361    switch (msg.type) {362      case "CREATE_VAULT": {363        const { password } = msg.payload as { password: string };364        // Refuse to create a vault under an empty master password — the derived365        // key would be publicly known and the at-rest AES-GCM protection void366        // (audit HIGH; the CSV-import path previously passed ""). Length/strength367        // policy lives in the onboarding UI; this is the non-negotiable floor.368        if (typeof password !== "string" || password.length === 0) {369          return { ok: false, error: "invalid_payload" };370        }371        await vault.createVault(password);372        await setupAutoLock();373        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });374        onVaultUnlocked();375        return { ok: true };376      }377      case "CREATE_VAULT_FROM_ROOT_KEY": {378        const { password, rootKeyHex } = (msg.payload ?? {}) as {379          password?: unknown;380          rootKeyHex?: unknown;381        };382        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {383          return { ok: false, error: "invalid_payload" };384        }385386        try {387          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);388          await setupAutoLock();389          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });390          onVaultUnlocked();391          return { ok: true, vaultId };392        } catch (err) {393          return { ok: false, error: err instanceof Error ? err.message : String(err) };394        }395      }396      case "UNLOCK": {397        const { password } = msg.payload as { password: string };398        const ok = await vault.unlock(password);399        if (ok) {400          // KAT: verify the WebCrypto stack is healthy before the user relies on it.401          // Runs after unlock so latency is hidden behind the vault-load time.402          const kat = await runSelfTest();403          if (!kat.ok) {404            console.error("[Peach] Crypto self-test FAILED:", kat.error);405            await vault.lock();406            return { ok: false, error: "self_test_failed" };407          }408          await vault.updateSettings({ pinPreferred: false });409          await setupAutoLock();410          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });411          onVaultUnlocked();412          return { ok: true };413        }414        // Distinguish corruption from wrong password so the popup can offer415        // a history-restore path instead of falsely accusing the user of416        // mistyping (M7/COR-007).417        const failure = vault.consumeLastUnlockFailureReason();418        if (failure) {419          return {420            ok: false,421            error: "vault_corrupted",422            canRestoreFromHistory: true,423          } as MessageResponse;424        }425        return { ok: false };426      }427      case "UNLOCK_WITH_PIN": {428        const { pin } = (msg.payload ?? {}) as { pin?: unknown };429        if (typeof pin !== "string") return { ok: false, error: "invalid_payload" };430        const ok = await vault.unlockWithPin(pin);431        if (!ok) {432          const status = await vault.getPinUnlockStatus();433          if (status.configured && !status.available) {434            return {435              ok: false,436              error: status.attemptsRemaining === 0437                ? "pin_attempts_exceeded"438                : "pin_session_expired",439            };440          }441          return { ok: false };442        }443        const kat = await runSelfTest();444        if (!kat.ok) {445          await vault.lock();446          return { ok: false, error: "self_test_failed" };447        }448        await vault.updateSettings({ pinPreferred: true });449        await setupAutoLock();450        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });451        onVaultUnlocked();452        return { ok: true };453      }454      case "GET_PIN_STATUS":455        return { ok: true, data: await vault.getPinUnlockStatus() };456      case "VALIDATE_RECOVERY_WORDS": {457        const { words } = msg.payload as { words: string[] };458        const invalid = findInvalidWords(words);459        return { ok: true, data: { valid: invalid.length === 0, invalid } };460      }461      case "GET_RECOVERY_WORDS": {462        // Must be unlocked and have recovery set up (vault must be v2.12+).463        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };464        // LV-4: the recovery words re-derive the ROOT KEY — the highest-465        // value secret in the vault. A session unlock (which may be hours466        // old on a shared machine) is not enough; require a fresh password467        // proof, matching the 1Password/Bitwarden pattern for revealing468        // escrow material. EXEMPTION: the create-vault / rotation confirmation469        // window (peach_recovery_pending) shows the words immediately after470        // the user authenticated, and that confirmation UI has no password to471        // resend — skip the re-auth there only.472        if (!(await isRecoveryConfirmPending())) {473          const { password } = (msg.payload ?? {}) as { password?: string };474          if (typeof password !== "string" || !password) {475            return { ok: false, error: "password_required" };476          }477          if (!(await vault.verifyMainPassword(password))) {478            return { ok: false, error: "wrong_password" };479          }480        }481        try {482          const words = await vault.getRecoveryWords();483          return { ok: true, data: words };484        } catch {485          return { ok: false, error: "recovery_not_setup" };486        }487      }488      case "GET_RECOVERY_CONFIRM_PENDING":489        return { ok: true, data: await isRecoveryConfirmPending() };490      case "SET_RECOVERY_CONFIRM_PENDING":491        await setRecoveryConfirmPending();492        return { ok: true };493      case "CLEAR_RECOVERY_CONFIRM_PENDING":494        await clearRecoveryConfirmPending();495        return { ok: true };496      case "RECOVER_WITH_WORDS": {497        // User has lost their password but has their 12 recovery words.498        // We: (1) validate the words, (2) re-encrypt vault with new password.499        const { words, newPassword } = msg.payload as {500          words: string[];501          newPassword: string;502        };503        const stored = await vault.loadSlotA();504        if (!stored) return { ok: false, error: "no_vault" };505        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {506          return { ok: false, error: "recovery_not_setup" };507        }508        // Unwrap the root key from the recovery escrow.509        try {510          await vault.unwrapRootKeyForRecovery(511            stored.recovery_wrapped_root_key,512            stored.recovery_nonce ?? "",513            stored.recovery_tag ?? "",514            stored.recovery_salt,515            words516          );517        } catch {518          return { ok: false, error: "invalid_recovery_words" };519        }520        // Re-key: derive fresh salt + key from new password.521        const newSalt = vault.generateSalt();522        const newKey = await vault.deriveKey(newPassword, newSalt);523        // Re-wrap root key under the new password's derived key so the same524        // recovery words continue to work after the password change.525        await vault.rewrapRootKeyForPassword(newKey, newSalt);526        // Re-encrypt vault entries with the new key.527        await vault.changePasswordWithNewKey(newSalt, newKey);528        await setupAutoLock();529        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });530        return { ok: true };531      }532      case "LOCK":533        vault.lock();534        return { ok: true };535      case "IS_UNLOCKED":536        return { ok: true, data: vault.isUnlocked() };537      case "GET_VAULT_STATUS":538        return { ok: true, unlocked: vault.isUnlocked() };539      case "HAS_VAULT":540        return { ok: true, data: await vault.hasVault() };541      case "GET_ENTRIES":542        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };543        return { ok: true, data: vault.getEntries() };544      case "ADD_ENTRY": {545        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };546        const payload = msg.payload;547        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {548          return { ok: false, error: "invalid_payload" };549        }550        // PB-26-106: a page may only create an entry bound to itself. Entries551        // carrying no url have no domain surface to bind, so they are exempt.552        if (isPageSender(sender)) {553          const draft = payload as { url?: unknown; additionalUrls?: unknown };554          const domains = entryDomains(draft.url, draft.additionalUrls);555          if (domains.size > 0 && !senderMayBindEntryDomains(sender, domains)) {556            return { ok: false, error: "origin_binding_required" };557          }558        }559        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);560        return { ok: true, data: entry };561      }562      case "BATCH_ADD_ENTRIES": {563        const payload = msg.payload as { entries?: unknown } | null | undefined;564        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {565          return { ok: false, error: "invalid_payload" };566        }567        if (!Array.isArray(payload.entries)) {568          return { ok: false, error: "invalid_payload" };569        }570        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);571        return { ok: true, data: added };572      }573      case "RESTORE_ENTRIES": {574        const payload = msg.payload as575          | { entries?: unknown; mode?: unknown; settings?: unknown }576          | null577          | undefined;578        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {579          return { ok: false, error: "invalid_payload" };580        }581        if (!Array.isArray(payload.entries)) {582          return { ok: false, error: "invalid_payload" };583        }584        if (payload.mode !== "replace" && payload.mode !== "merge") {585          return { ok: false, error: "invalid_payload" };586        }587        const summary = await vault.restoreEntries(588          payload.entries as Parameters<typeof vault.restoreEntries>[0],589          payload.mode590        );591        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {592          await vault.updateSettings(payload.settings as vault.VaultSettings);593        }594        return { ok: true, data: summary };595      }596      case "CLEAR_VAULT_ENTRIES": {597        await vault.clearVaultEntries("REPLACE_ALL");598        return { ok: true };599      }600      case "GET_VAULT_HISTORY": {601        const snapshots = await vault.getVaultHistory();602        return { ok: true, data: snapshots };603      }604      case "RESTORE_VAULT_SNAPSHOT": {605        const { snapshotId } = msg.payload as { snapshotId: string };606        const result = await vault.restoreVaultSnapshot(snapshotId);607        if (!result.ok) return { ok: false, error: result.error };608        broadcastToContentScripts({ type: "VAULT_LOCKED" });609        return { ok: true };610      }611      case "COUNT_DUPLICATES": {612        return { ok: true, data: vault.countDuplicates() };613      }614      case "DEDUPLICATE_ENTRIES": {615        const removed = await vault.deduplicateEntries();616        return { ok: true, data: removed };617      }618      case "UPDATE_ENTRY": {619        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;620        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {621          return { ok: false, error: "invalid_payload" };622        }623        const { id, patch } = payload;624        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {625          return { ok: false, error: "invalid_payload" };626        }627        const existingEntry = vault.getEntryById(id);628        if (!existingEntry) return { ok: false, error: "entry_not_found" };629        if (patchChangesEntryOrigin(patch) || isPageSender(sender)) {630          const before = entryDomains(existingEntry.url, existingEntry.additionalUrls);631          const after = patchedUrlShape(patch, existingEntry);632          if (!senderMayMutateEntryDomains(633            sender,634            before,635            entryDomains(after.url, after.additionalUrls),636          )) {637            return { ok: false, error: "origin_binding_required" };638          }639        }640        // Single enforcement point for the Canary Entries Pro gate. Only641        // gates the transition into a canary entry — clearing/disabling a642        // canary (`canary: undefined`) is always allowed, so existing643        // canary entries remain manageable.644        const incomingCanary = (patch as { canary?: unknown }).canary;645        if (incomingCanary && typeof incomingCanary === "object") {646          const existing = vault.getEntryById(id);647          if (!existing?.canary) {648            const gate = await requirePro("canary_entry");649            if (!gate.allowed) return { ok: false, error: "pro_required" };650          }651        }652        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);653        return { ok: true };654      }655      case "ADD_ADDITIONAL_URL": {656        const { id, url } = msg.payload as { id: string; url: string };657        const trimmed = typeof url === "string" ? url.trim() : "";658        if (!trimmed) return { ok: false, error: "url_required" };659        const existing = vault.getEntryById(id);660        if (!existing) return { ok: false, error: "entry_not_found" };661        const merged = [...(existing.additionalUrls ?? []), trimmed];662        if (!senderMayMutateEntryDomains(663          sender,664          entryDomains(existing.url, existing.additionalUrls),665          entryDomains(existing.url, merged),666        )) {667          return { ok: false, error: "origin_binding_required" };668        }669        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };670        await vault.updateEntry(id, { additionalUrls: merged });671        return { ok: true };672      }673      case "REQUEST_REMEMBER_SITE": {674        // PB-26-106: growing an entry's domain set needs a decision the page675        // cannot make for itself, so the page asks and the popup confirms. A676        // page may only ask about its own attested origin — otherwise this677        // becomes the same unbound write under a friendlier name.678        const { id, url } = (msg.payload ?? {}) as { id?: unknown; url?: unknown };679        if (typeof id !== "string" || !id) return { ok: false, error: "invalid_payload" };680        const trimmed = typeof url === "string" ? url.trim() : "";681        if (!trimmed) return { ok: false, error: "url_required" };682        if (!senderMayBindEntryDomains(sender, entryDomains(trimmed, undefined))) {683          return { ok: false, error: "origin_binding_required" };684        }685        if (!vault.getEntryById(id)) return { ok: false, error: "entry_not_found" };686        if (chrome.storage.session) {687          await chrome.storage.session.set({ pendingRememberSite: { entryId: id, url: trimmed } });688        }689        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }690        return { ok: true };691      }692      case "DELETE_ENTRY": {693        const { id } = msg.payload as { id: string };694        await vault.deleteEntry(id);695        return { ok: true };696      }697      case "GET_DELETED_ENTRIES":698        return { ok: true, data: vault.getDeletedEntries() };699      case "RESTORE_ENTRY": {700        const { id } = msg.payload as { id: string };701        await vault.restoreEntry(id);702        return { ok: true };703      }704      case "PURGE_ENTRY": {705        const { id } = msg.payload as { id: string };706        await vault.purgeEntry(id);707        return { ok: true };708      }709      case "PURGE_EXPIRED_TRASH": {710        const { retentionMs } = msg.payload as { retentionMs: number };711        const purged = await vault.purgeExpiredTrash(retentionMs);712        return { ok: true, data: purged };713      }714      case "SAVE_NOTE": {715        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };716        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };717        const now = Date.now();718        if (id) {719          const existing = vault.getEntryById(id);720          if (!existing) return { ok: false, error: "not_found" };721          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });722          return { ok: true, data: vault.getEntryById(id) };723        } else {724          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt725          // (EntryDraft omits both), so passing them was the only reason the726          // `as any` cast existed. Dropping them makes the call type-check.727          const entry = await vault.addEntry({728            type: "note",729            title: title || "Untitled",730            notes: body,731          });732          return { ok: true, data: entry };733        }734      }735      case "DELETE_NOTE": {736        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };737        const { id } = msg.payload as { id: string };738        await vault.deleteEntry(id);739        return { ok: true };740      }741      case "GET_NOTES": {742        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };743        const notes = vault.getEntries().filter(744          (e) => e.type === "note" && !e.deletedAt745        );746        return { ok: true, data: notes } as MessageResponse;747      }748      case "SEARCH_VAULT": {749        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };750        // AUD-002: shape-validate the payload before calling string methods.751        // A raw cast lets a malformed message crash the handler with TypeError.752        const { query } = (msg.payload ?? {}) as { query?: unknown };753        if (typeof query !== "string") {754          return { ok: false, error: "invalid_payload" };755        }756        const q = query.toLowerCase();757        const searchResults = vault.getEntries().filter(758          (e) =>759            !e.deletedAt &&760            (e.title.toLowerCase().includes(q) ||761              e.notes?.toLowerCase().includes(q) ||762              e.username?.toLowerCase().includes(q))763        );764        return { ok: true, data: searchResults } as MessageResponse;765      }766      case "AUTOFILL_QUERY": {767        if (!vault.isUnlocked()) {768          return { ok: false, error: "vault_locked" };769        }770        let { includeAll } = msg.payload as { includeAll?: boolean };771        const { domain, kind, userGesture } = msg.payload as {772          domain: string;773          kind?: "login" | "card" | "totp";774          userGesture?: boolean;775        };776        // MV-2: the vault-wide inventory (every title/username/email/url)777        // may only leave the background on an explicit user gesture — the778        // user opening the search affordance — never on passive form focus.779        // userGesture is self-declared by our own content script; the value780        // of this gate is that PASSIVE code paths (which never set it)781        // cannot ship the inventory, shrinking what a compromised page that782        // merely triggers focus events can observe.783        if (includeAll && userGesture !== true) {784          includeAll = false;785        }786        // kind="card": return saved cards as compact summaries for the787        // inline card silver platter. Cards are not domain-scoped — every788        // saved card is a candidate on every checkout page — so domain is789        // ignored when kind === "card".790        if (kind === "card") {791          const cards = vault.getEntries().filter((e) => e.type === "card");792          return {793            ok: true,794            data: cards.map((e) => ({795              id: e.id,796              title: e.cardNickname || e.title,797              cardholderName: e.cardholderName,798              last4: e.last4,799              expMonth: e.expMonth,800              expYear: e.expYear,801              network: e.network,802            })),803          };804        }805        if (kind === "totp") {806          const matches = (807            includeAll808              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")809              : vault.queryDomain(domain)810          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));811          return {812            ok: true,813            data: matches.map((e) => ({814              id: e.id,815              title: e.title,816              username: e.username,817              email: e.email,818              url: e.url,819              hasTotp: true,820            })),821          };822        }823        // The inline selector fills username+password into a form. Passkey-824        // only entries have no password to fill; sign-in for those goes825        // through the WebAuthn path instead. Filter them out everywhere so826        // the user doesn't see four "GitHub" rows that mostly do nothing.827        // Notes and cards never belonged here either.828        const matches = (829          includeAll830            ? vault831                .getEntries()832                .filter((entry) => entry.type !== "note" && entry.type !== "card")833            : vault.queryDomain(domain)834        ).filter((entry) => !isPasskeyOnly(entry));835        return {836          ok: true,837          data: matches.map((e) =>838            includeAll839              ? {840                  id: e.id,841                  title: e.title,842                  // username/email/url shipped so the inline popup's search843                  // affordance can match on them, not just titles. No secrets844                  // cross the boundary — same shape as the domain-matched845                  // response below minus hasTotp (which the search list846                  // doesn't surface).847                  username: e.username,848                  email: e.email,849                  url: e.url,850                  hasPasskey: e.passkey !== undefined,851                }852              : {853                  id: e.id,854                  title: e.title,855                  username: e.username,856                  email: e.email,857                  url: e.url,858                  hasTotp: Boolean(e.totp),859                  hasPasskey: e.passkey !== undefined,860                }861          ),862        };863      }864      case "GET_ENTRY_FOR_FILL": {865        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };866        const { id, explicitSummon } = msg.payload as {867          id: string;868          explicitSummon?: boolean;869        };870        const entry = vault.getEntryById(id);871        if (!entry) return { ok: false, error: "entry_not_found" };872        // Passkey-only entries (passkey credential, no password) cannot be873        // filled into a form — sign-in goes through the WebAuthn path. A874        // login that ALSO has a passkey is still fillable for its password.875        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };876877        // MV-1: re-validate the entry against the requesting frame's origin.878        // sender.url / sender.tab.url are browser-attested — a page cannot879        // forge them. PB-26-005: the FRAME url (sender.url) is authoritative880        // for an all_frames content script; the top-frame tab.url would881        // misattribute a cross-origin iframe's request to the top page. When882        // the request does not come from a tab at all (popup surfaces use883        // GET_ENTRY_FOR_EDIT, not this), refuse.884        if (sender.tab !== undefined || sender.url !== undefined) {885          let senderDomain: string | null = null;886          try {887            const rawUrl = sender.url ?? sender.tab?.url ?? "";888            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;889          } catch {890            senderDomain = null;891          }892          if (!senderDomain) return { ok: false, error: "origin_unverified" };893894          const entryDomains = new Set<string>();895          const primary = extractDomain(entry.url ?? "");896          if (primary) entryDomains.add(primary);897          for (const extra of entry.additionalUrls ?? []) {898            const d = extractDomain(extra);899            if (d) entryDomains.add(d);900          }901902          // explicitSummon=true means the user actively picked this entry903          // from the cross-domain search affordance — an intentional904          // off-domain fill. Passive fill paths must stay domain-bound.905          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {906            // Domain mismatch — refuse silently (no oracle about which ids exist).907            return { ok: false, error: "entry_not_found" };908          }909        }910        // Strip the passkey credential AND the raw base32 TOTP seed from the911        // response. Content scripts never need either: the private key is the912        // authenticator's, and handing over the TOTP seed would let a913        // compromised content script mint valid codes indefinitely (SEV-3-C).914        // Generate the *current* 6-digit code here in the background and send915        // only that, plus the seconds left so the UI can render a countdown.916        // Also drop passwordHistory: filling needs only the *current* password.917        // Handing every past password to a content script during passive918        // autofill on an arbitrary page would widen the blast radius of a919        // compromised page far beyond the one credential being filled.920        const {921          passkey: _strippedPasskey,922          totp: seed,923          totpAlgorithm,924          totpDigits,925          totpPeriod,926          passwordHistory: _ph,927          ...safeEntry928        } = entry;929        let totpCode: string | undefined;930        let totpRemaining: number | undefined;931        if (seed) {932          try {933            // PCH-01-019: honour stored algorithm/digits/period (defaults apply934            // when these are undefined, i.e. RFC-default bare-seed entries).935            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);936            totpCode = generated.code;937            totpRemaining = generated.remaining;938          } catch {939            totpCode = undefined;940          }941        }942        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };943      }944      // Trusted full-entry fetch for Peach's own inline-popup surfaces that945      // genuinely need the raw TOTP seed: the edit form (which re-saves the946      // seed and would otherwise wipe it) and nothing else. Unlike947      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside948      // the inline popup, never during passive autofill on an arbitrary page.949      // The passkey credential is still stripped — the edit form never touches it.950      case "GET_ENTRY_FOR_EDIT": {951        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };952        const { id, explicitSummon } = msg.payload as {953          id: string;954          explicitSummon?: boolean;955        };956        const entry = vault.getEntryById(id);957        if (!entry) return { ok: false, error: "entry_not_found" };958959        // PCH-01-006: re-validate the browser-attested sender origin, mirroring960        // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and961        // full password history — at least as sensitive as the fill response — so962        // the boundary must be enforced here, not only by UI reachability. Today963        // the sole caller is the popup (no sender.tab, so this is a structural964        // no-op), but a future tab-context caller or an id leak would otherwise965        // inherit a full-credential oracle. Unlike the fill path we SKIP (not966        // refuse) when no sender domain resolves, to keep the popup caller working.967        // PB-26-005: the frame url (sender.url) is authoritative over the968        // top-frame sender.tab.url — mirrors the fill path.969        if (sender.tab !== undefined || sender.url !== undefined) {970          let senderDomain: string | null = null;971          try {972            const rawUrl = sender.url ?? sender.tab?.url ?? "";973            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;974          } catch {975            senderDomain = null;976          }977          if (senderDomain) {978            const entryDomains = new Set<string>();979            const primary = extractDomain(entry.url ?? "");980            if (primary) entryDomains.add(primary);981            for (const extra of entry.additionalUrls ?? []) {982              const d = extractDomain(extra);983              if (d) entryDomains.add(d);984            }985            if (explicitSummon !== true && !entryDomains.has(senderDomain)) {986              return { ok: false, error: "entry_not_found" }; // no id oracle987            }988          }989        }990991        const { passkey: _passkey, ...safeEntry } = entry;992        return { ok: true, data: safeEntry };993      }994      case "COPY": {995        // AUD-002: shape-validate the payload before passing to the clipboard996        // helper. A raw cast lets a malformed message reach the clipboard API997        // with a non-string and throw.998        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {999          text?: unknown;1000          label?: unknown;1001          alreadyWritten?: unknown;1002        };1003        if (typeof text !== "string" || typeof label !== "string") {1004          return { ok: false, error: "invalid_payload" };1005        }1006        await copyToClipboard(text, label, Boolean(alreadyWritten));1007        return { ok: true, clearSeconds: getEffectiveClearSeconds() };1008      }1009      case "CHECK_ALL_BREACHES": {1010        const allEntries = vault.getEntries();1011        const results: Record<string, number> = {};1012        for (const entry of allEntries) {1013          if (entry.type === "note") continue;1014          if (!entry.password) continue;1015          results[entry.id] = await vault.checkBreach(entry.password);1016          // Small delay — be a good citizen to the HIBP API1017          await new Promise((r) => setTimeout(r, 200));1018        }1019        // Persist any non-zero counts back to entries1020        for (const [id, count] of Object.entries(results)) {1021          const entry = vault.getEntryById(id);1022          if (entry && (entry.breach ?? 0) !== count) {1023            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });1024          }1025        }1026        return { ok: true, data: results };1027      }1028      case "GET_SETTINGS":1029        return { ok: true, data: await vault.ensureSettingsLoaded() };1030      case "UPDATE_SETTINGS": {1031        const patch = msg.payload;1032        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {1033          return { ok: false, error: "invalid_payload" };1034        }1035        await vault.updateSettings(patch as vault.VaultSettings);1036        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {1037          await setupAutoLock();1038          if (vault.isUnlocked()) touchAutoLock();1039        }1040        return { ok: true };1041      }1042      case "SETUP_PIN": {1043        const { currentPassword, pin } = (msg.payload ?? {}) as {1044          currentPassword?: unknown;1045          pin?: unknown;1046        };1047        if (typeof currentPassword !== "string" || typeof pin !== "string") {1048          return { ok: false, error: "invalid_payload" };1049        }1050        return (await vault.setupPinUnlock(currentPassword, pin))1051          ? { ok: true }1052          : { ok: false, error: "incorrect_current_password" };1053      }1054      case "DISABLE_PIN": {1055        const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown };1056        if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" };1057        return (await vault.disablePinUnlock(currentPassword))1058          ? { ok: true }1059          : { ok: false, error: "incorrect_current_password" };1060      }1061      case "GET_PENDING_PASSKEY":1062        return { ok: true, data: await getPendingPasskeyRequest() };1063      case "APPROVE_PASSKEY": {1064        const { requestId } = msg.payload as { requestId: number };1065        await resolvePendingPasskeyRequest(requestId, true);1066        return { ok: true };1067      }1068      case "DENY_PASSKEY": {1069        const { requestId } = msg.payload as { requestId: number };1070        await resolvePendingPasskeyRequest(requestId, false);1071        return { ok: true };1072      }1073      case "GET_PASSKEY_PROVIDER_STATE":1074        return { ok: true, data: await getPasskeyProviderState() };1075      case "SET_PASSKEY_PROVIDER_ENABLED": {1076        const { enabled } = msg.payload as { enabled: boolean };1077        // Disabling is always free; gating fires only when a free user is1078        // trying to turn passkey interception on.1079        if (enabled) {1080          const gate = await requirePro("passkeys");1081          if (!gate.allowed) return { ok: false, error: "pro_required" };1082        }1083        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };1084      }1085      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS1086      // endpoint. Intentional product behavior — users configure their own1087      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private1088      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-1089      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to1090      // users that the entry title leaves the device when the canary fires.1091      case "FIRE_CANARY_PING": {1092        // Canary alert fires unconditionally for any entry with canary: true.1093        // The Pro gate only governs creation/flagging of canary entries; once1094        // an entry is flagged, the alert path is a security property and must1095        // never be license-gated.1096        const { webhookUrl, entryTitle, trigger } = msg.payload as {1097          webhookUrl: string;1098          entryTitle: string;1099          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";1100        };1101        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {1102          return { ok: false, error: "invalid_webhook_url" };1103        }1104        // LV-3: debounce non-test pings per (webhook, entry) so a page that1105        // strobes focus/fill events can't turn the canary into a request1106        // firehose at the user's endpoint. Test pings are exempt — they are1107        // explicit user clicks in the settings UI and are awaited for1108        // feedback. The FIRST ping in a window always goes out, so the1109        // dead-man's-switch property (canary fires on access) is preserved;1110        // only repeats within the window are coalesced.1111        if (trigger !== "test") {1112          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;1113          const stored = await chrome.storage.local.get(rlKey);1114          const last = (stored as Record<string, unknown>)[rlKey];1115          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {1116            return { ok: true, data: { rateLimited: true } };1117          }1118          await chrome.storage.local.set({ [rlKey]: Date.now() });1119        }1120        const body = JSON.stringify({1121          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",1122          entry: entryTitle,1123          trigger,1124          timestamp: new Date().toISOString(),1125          source: "peach-extension",1126        });1127        if (trigger === "test") {1128          // Permitted outbound fetch: user-configured canary alert endpoint1129          // (validated by isAllowedCanaryWebhookUrl above). This is the1130          // only non-HIBP outbound call in the extension — see1131          // Projects.md §3.7. Test pings are awaited so the UI can show1132          // success/failure.1133          try {1134            const res = await fetch(webhookUrl, {1135              method: "POST",1136              headers: { "Content-Type": "application/json" },1137              body,1138            });1139            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1140          } catch (err) {1141            return { ok: false, error: err instanceof Error ? err.message : "network_error" };1142          }1143        }1144        // Non-test triggers are fire-and-forget1145        fetch(webhookUrl, {1146          method: "POST",1147          headers: { "Content-Type": "application/json" },1148          body,1149        }).catch(() => {});1150        return { ok: true };1151      }1152      case "ACTIVATE_LICENSE": {1153        const { key } = msg.payload as { key: string };1154        const licenseInfo = await activateLicense(key);1155        return { ok: true, data: licenseInfo };1156      }1157      case "GET_LICENSE": {1158        const licenseInfo = await getLicenseInfo();1159        return { ok: true, data: licenseInfo };1160      }1161      case "GET_LICENSE_KEY": {1162        const key = await getLicenseKey();1163        return { ok: true, data: key };1164      }1165      case "DEACTIVATE_LICENSE": {1166        await deactivateLicense();1167        return { ok: true };1168      }1169      case "SHOULD_PLAY_CELEBRATION": {1170        const should = await shouldPlayCelebration();1171        return { ok: true, data: should };1172      }1173      case "MARK_CELEBRATION_PLAYED": {1174        await markCelebrationPlayed();1175        return { ok: true };1176      }1177      case "GET_CODEX_VAULT_DATA": {1178        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1179        // popup navigates to the License section without further coordination.1180        // Also privileged-page-gated (PB-26-001), and recoveryWords inside the1181        // snapshot additionally require a fresh master-password proof.1182        const gate = await requirePro("codex");1183        if (!gate.allowed) return { ok: false, error: "pro_required" };1184        const { password } = (msg.payload ?? {}) as { password?: string };1185        return await handleGetCodexVaultData(password);1186      }1187      case "ESTIMATE_CODEX_PAGES": {1188        const gate = await requirePro("codex");1189        if (!gate.allowed) return { ok: false, error: "pro_required" };1190        return await handleEstimateCodexPages();1191      }1192      case "RESTORE_FROM_CODEX": {1193        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1194        // be able to restore a vault that was printed by a Pro user.1195        // DO NOT add a Pro gate here.1196        const payload = msg.payload as CodexRestorePayload;1197        return await handleRestoreFromCodex(payload);1198      }1199      case "OPEN_PRO_GATE": {1200        // Content script requests: open popup and navigate to License section.1201        const { feature } = (msg.payload ?? {}) as { feature?: string };1202        if (chrome.storage.session) {1203          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1204        }1205        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1206        return { ok: true };1207      }1208      case "OPEN_POPUP": {1209        // Content script asks to open the trusted extension popup — used by the1210        // inline locked bubble so the master password is entered in the popup,1211        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1212        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1213        // toolbar icon. The badge already signals Peach needs attention.1214        //1215        // Set a session flag so the popup knows it was opened for inline unlock1216        // and should close itself once the vault is unlocked (returning the user1217        // to the inline autofill selector on the page).1218        if (chrome.storage.session) {1219          await chrome.storage.session.set({ peach_inline_unlock: true });1220        }1221        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1222        return { ok: true };1223      }1224      case "OPEN_DETACHED_POPUP": {1225        // A window created by the action popup and then orphaned with1226        // window.close() is cascaded shut by Chrome, so the file-picker1227        // flows (OS dialogs that dismiss the popup on focus loss) ask the SW1228        // to open the standalone window instead — the SW has no window to be1229        // associated with. The query string is allowlisted so this can never1230        // open an arbitrary URL.1231        const { route } = (msg.payload ?? {}) as { route?: string };1232        const search = route === "peachscript"1233          ? "?restore=peachscript"1234          : route === "csv"1235            ? "?restore=csv"1236            : route === "codex-pdf"1237              ? "?codex=pdf"1238              : null;1239        if (!search) return { ok: false, error: "bad_route" };1240        try {1241          const popupHtml =1242            chrome.runtime.getManifest().action?.default_popup ?? "src/popup/index.html";1243          await chrome.windows.create({1244            url: chrome.runtime.getURL(`${popupHtml}${search}`),1245            type: "popup",1246            width: 320,1247            height: 550,1248          });1249          return { ok: true, data: { detached: true } };1250        } catch {1251          return { ok: false };1252        }1253      }1254      case "GET_IDENTITIES": {1255        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1256        return { ok: true, data: vault.getIdentities() };1257      }1258      case "TOUCH_AUTO_LOCK": {1259        // touchAutoLock() is already called by shouldRefreshAutoLock above;1260        // this case just gives the popup a typed message to keep the session alive.1261        return { ok: true };1262      }1263      case "GET_ADVANCED_HEALTH_REPORT": {1264        const gate = await requirePro("advanced_health");1265        if (!gate.allowed) return { ok: false, error: "pro_required" };1266        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1267        const report = await buildAdvancedHealthReport(vault.getEntries());1268        return { ok: true, data: report };1269      }1270      case "IS_DURESS_ENABLED": {1271        const enabled = await vault.isDuressEnabled();1272        return { ok: true, data: enabled };1273      }1274      case "SETUP_DURESS": {1275        // Single enforcement point for the Duress Vault Pro gate. Free users1276        // who somehow reach this handler are rejected here; the popup also1277        // pre-checks isPro() to avoid showing the setup form to free users,1278        // but server-side is the actual security boundary.1279        const gate = await requirePro("duress_vault");1280        if (!gate.allowed) return { ok: false, error: "pro_required" };1281        // MV3 service workers restart after inactivity, losing the in-memory1282        // derived key. Detect this before calling setupDuress so the popup1283        // can show a meaningful prompt to re-lock and re-unlock.1284        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1285        const { duressPassword } = msg.payload as { duressPassword: string };1286        await vault.setupDuress(duressPassword);1287        return { ok: true };1288      }1289      case "DISABLE_DURESS": {1290        await vault.disableDuress();1291        return { ok: true };1292      }1293      case "VERIFY_MAIN_PASSWORD": {1294        const { password } = msg.payload as { password: string };1295        const ok = await vault.verifyMainPassword(password);1296        return { ok: true, data: ok };1297      }1298      case "CHANGE_PASSWORD": {1299        const { currentPassword, newPassword } = msg.payload as {1300          currentPassword: string;1301          newPassword: string;1302        };1303        const changed = await vault.changePassword(currentPassword, newPassword);1304        return changed1305          ? { ok: true }1306          : { ok: false, error: "incorrect_current_password" };1307      }1308      case "GET_SITE_PASSWORD_POLICY": {1309        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1310        if (!tab?.id) return { ok: true, data: null };1311        try {1312          const response = await chrome.tabs.sendMessage(tab.id, {1313            type: "GET_SITE_PASSWORD_POLICY",1314          });1315          return (response as MessageResponse) ?? { ok: true, data: null };1316        } catch {1317          return { ok: true, data: null };1318        }1319      }1320      case "RECORD_MANUAL_SUMMON": {1321        const { domain } = msg.payload as { domain: string };1322        const settings = vault.getSettings();1323        const existing = settings.manualSummonDomains?.[domain];1324        const now = Date.now();1325        await vault.updateSettings({1326          manualSummonDomains: {1327            ...settings.manualSummonDomains,1328            [domain]: {1329              firstSummonedAt: existing?.firstSummonedAt ?? now,1330              summonCount: (existing?.summonCount ?? 0) + 1,1331              lastSummonedAt: now,1332            },1333          },1334        });1335        return { ok: true };1336      }1337      case "DECLINE_CARD_SAVE": {1338        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1339        await vault.declineCardSaveOffer(last4, expMonth, expYear);1340        return { ok: true };1341      }1342      case "IS_CARD_DECLINED": {1343        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1344        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1345        return { ok: true, data: declined };1346      }1347      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1348        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1349          rpId?: string;1350          rpName?: string;1351          userName?: string;1352          userDisplayName?: string;1353        };1354        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1355        return await initiateFirefoxPasskeyCreate({1356          rpId,1357          rpName: rpName ?? rpId,1358          userName,1359          userDisplayName,1360        }, attestedSenderOrigin(sender));1361      }13621363      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1364        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1365        if (!payload) return { ok: false, error: "missing_payload" };1366        return await completeFirefoxPasskeyCreate(payload);1367      }13681369      case "PASSKEY_OFFER_DECLINE": {1370        const { domain } = (msg.payload ?? {}) as { domain?: string };1371        const origin = attestedSenderOrigin(sender);1372        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1373        await recordPasskeyOfferDecline(domain);1374        return { ok: true };1375      }13761377      case "GET_PASSKEY_OFFER_DECLINED": {1378        const { domain } = (msg.payload ?? {}) as { domain?: string };1379        const origin = attestedSenderOrigin(sender);1380        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1381        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1382      }13831384      case "PASSKEY_HAS_CREDENTIALS": {1385        const payload = msg.payload as {1386          rpId?: string;1387          allowCredentials?: Array<{ id: string; type?: string }>;1388        } | undefined;1389        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1390        return await handlePasskeyHasCredentials({1391          rpId: payload.rpId,1392          allowCredentials: payload.allowCredentials ?? [],1393        }, attestedSenderOrigin(sender));1394      }13951396      case "PASSKEY_CREATE": {1397        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1398        if (!payload?.rpId || !payload?.userName) {1399          return { ok: false, error: "rpid_and_username_required" };1400        }1401        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1402      }14031404      case "PASSKEY_GET": {1405        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1406        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1407        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1408      }14091410      case "PASSKEY_AUTH_RESPONSE": {1411        const { requestId, approved } = (msg.payload ?? {}) as {1412          requestId?: string | number;1413          approved?: boolean;1414        };1415        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1416          return { ok: false, error: 'requestId and approved required' };1417        }1418        await resolvePendingPasskeyRequest(Number(requestId), approved);1419        return { ok: true };1420      }14211422      case "GET_PASSKEY_FOR_DOMAIN": {1423        const { domain } = (msg.payload ?? {}) as { domain?: string };1424        if (!domain) return { ok: false, error: "domain_required" };1425        // Scope to the caller's own origin: a page may only ask about passkeys1426        // for a domain it actually owns, so an arbitrary page cannot enumerate1427        // which sites the user holds passkeys for or read the username (audit MEDIUM).1428        const origin = attestedSenderOrigin(sender);1429        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1430        if (!vault.isUnlocked()) return { ok: true, data: null };1431        const match = vault1432          .getEntries()1433          .find((entry) => entry.passkey?.rpId === domain);1434        if (!match || !match.passkey) return { ok: true, data: null };1435        // Slim shape — only the fields State 11 needs. Never expose private1436        // key material, even though this is locked behind isUnlocked.1437        return {1438          ok: true,1439          data: {1440            rpId: match.passkey.rpId,1441            userName: match.passkey.userName,1442            browser: match.passkey.browser,1443          },1444        };1445      }14461447      case "DESTROY_VAULT": {1448        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1449        // storage.local.clear() wipes every Peach key (slots, settings, license,1450        // onboarded flag, history, sync state, declined cards, recall, etc.);1451        // session.clear() wipes pending passkey requests + pro-notice queues.1452        // Caller (Panic.tsx) handles UI navigation back to onboarding.1453        //1454        // The Pro license is the one thing that must survive: the user paid for1455        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1456        // Capture it before the clear and restore it after. peach_pro_celebrated1457        // rides along so the Pro celebration doesn't replay on the next unlock.1458        const preserved = await chrome.storage.local.get([1459          "peach_license",1460          "peach_pro_celebrated",1461        ]);1462        vault.lock();1463        await storageClear();1464        await vault.clearVaultHistory();1465        const toRestore: Record<string, unknown> = {};1466        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1467        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1468        if (Object.keys(toRestore).length > 0) {1469          await chrome.storage.local.set(toRestore);1470        }1471        if (chrome.storage.session) {1472          await chrome.storage.session.clear();1473        }1474        await clearRecoveryConfirmPending();1475        return { ok: true };1476      }14771478      case "GET_IDENTITY_SUGGESTIONS": {1479        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1480        const entries = vault.getEntries();1481        const suggestions = buildIdentitySuggestions(entries);1482        return { ok: true, data: { suggestions } };1483      }1484      case "ML_INIT":1485        return { ok: true };14861487      case "ML_PREDICT_BATCH": {1488        // AUD-002: shape-validate before forwarding to the ML helper.1489        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1490        if (!Array.isArray(featuresArray)) {1491          return { ok: false, error: "invalid_payload" };1492        }1493        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1494      }14951496      // ── Vault sync (v3) ───────────────────────────────────────────────1497      // Returns the public-facing local identity needed by the popup to1498      // drive Phase-1 audio pairing. The private long-term key never1499      // leaves the background.1500      case "GET_LOCAL_IDENTITY": {1501        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1502        // Pro license from an already-Pro peer (at least one device must be Pro).1503        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1504        // Identity derives from the stable root key, not the password-derived1505        // key, so pairing survives a master-password change (SEV-2-B).1506        const masterKeyHex = vault.getRootKeyHex();1507        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1508        const masterKey = unhexBytes(masterKeyHex);1509        try {1510          const identity = await buildLocalIdentity(masterKey);1511          // If this device is Pro, advertise the signed license so the peer can1512          // activate it after SAS confirmation — pairing carries Pro across.1513          if (await isProUser()) {1514            const license = await getLicenseKey();1515            if (license) (identity as { license?: string }).license = license;1516          }1517          return { ok: true, data: identity };1518        } finally {1519          masterKey.fill(0);1520        }1521      }15221523      case "LIST_PAIRED_DEVICES": {1524        const devices = await listPairedDevicesV3();1525        return { ok: true, data: { devices } };1526      }15271528      case "RENAME_PAIRED_DEVICE": {1529        const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string };1530        if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") {1531          return { ok: false, error: "invalid_payload" };1532        }1533        await renamePairedDeviceV3(deviceId, name);1534        return { ok: true };1535      }15361537      case "UNPAIR_DEVICE": {1538        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1539        if (typeof deviceId !== "string" || !deviceId) {1540          return { ok: false, error: "invalid_payload" };1541        }1542        // Removing a device REVOKES it rather than just dropping the local1543        // row: a plain removal is undone the moment any other peer vouches it1544        // back through a manifest, which is exactly what the relay makes easy.1545        await revokeDeviceByIdV3(deviceId, await getOrCreateDeviceId());1546        // Sync against the remaining hosts — the unpaired device no longer1547        // matters but the next alarm tick is up to ten minutes away.1548        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1549        return { ok: true };1550      }15511552      case "RENAME_LOCAL_DEVICE": {1553        const { name } = (msg.payload ?? {}) as { name?: string };1554        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1555        await setDeviceNameV3(name);1556        return { ok: true };1557      }15581559      // ── Relay pairing ─────────────────────────────────────────────────────1560      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1561      // session runs in the background; the SAS and the terminal result reach1562      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1563      case "START_ADOPTION_SOURCE": {1564        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1565        if (isRelayAdoptionSourceInFlight()) {1566          return { ok: false, error: "adoption_source_in_progress" };1567        }1568        try {1569          return { ok: true, data: await startRelayAdoptionSource() };1570        } catch (error) {1571          return {1572            ok: false,1573            error: error instanceof Error ? error.message : "adoption_source_failed",1574          };1575        }1576      }15771578      // Onboarding receiver — empty extension shows a QR, phone scans and1579      // sends the vault. The popup supplies the local-only password here so1580      // the background can wrap the adopted root key at rest without ever1581      // asking the user to retype it.1582      case "START_ADOPTION_RECEIVER": {1583        if (isRelayAdoptionSourceInFlight()) {1584          return { ok: false, error: "adoption_receiver_in_progress" };1585        }1586        const password = (msg.payload as { password?: unknown } | undefined)?.password;1587        if (typeof password !== "string" || password.length === 0) {1588          return { ok: false, error: "invalid_payload" };1589        }1590        try {1591          return { ok: true, data: await startRelayAdoptionReceiver(password) };1592        } catch (error) {1593          return {1594            ok: false,1595            error: error instanceof Error ? error.message : "adoption_receiver_failed",1596          };1597        }1598      }15991600      // Popup→bg counterpart to ADOPTION_SOURCE_SAS (receiver flow).1601      // The receiver now auto-accepts the SAS (both sides derive it from the1602      // same Noise handshake hash, so the codes match by construction) so1603      // the popup never has a SAS screen to tap on. The id round-trips the1604      // same way so a stale late response can't approve the wrong session.1605      // Popup→bg counterpart for the source flow: Confirm/Cancel on the1606      // source's SAS screen.16071608      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1609      // on the source's SAS screen. The id round-trips the same way so a stale1610      // late response can't approve the wrong session.1611      case "SOURCE_SAS_DECISION": {1612        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1613        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1614          return { ok: false, error: "invalid_payload" };1615        }1616        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1617      }16181619      case "CANCEL_ADOPTION_SOURCE": {1620        cancelRelayAdoptionSource();1621        return { ok: true };1622      }16231624      case "TRIGGER_SYNC": {1625        const payload = (msg.payload ?? {}) as {1626          reason?: "vault_change" | "foreground" | "manual";1627          force?: boolean;1628        };1629        const reason = payload.reason ?? "foreground";16301631        void triggerSyncIfReachable({ reason, force: payload.force === true });1632        return { ok: true };1633      }16341635      case "GET_SYNC_STATE": {1636        return { ok: true, data: getSyncState() };1637      }16381639      case "GET_SYNC_SETTINGS": {1640        return { ok: true, data: await getSyncSettings() };1641      }16421643      case "SET_SYNC_SETTINGS": {1644        const payload = (msg.payload ?? {}) as {1645          mode?: unknown;1646          relayUrl?: unknown;1647        };1648        try {1649          // A custom relay URL implies private mode; Peach's own relay stays1650          // public. See setRelayUrl.1651          if (payload.relayUrl !== undefined) {1652            if (typeof payload.relayUrl !== "string") {1653              return { ok: false, error: "invalid_relay_url" };1654            }1655            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1656          }1657          if (payload.mode !== undefined) {1658            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1659              return { ok: false, error: "invalid_sync_mode" };1660            }1661            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1662          }1663          return { ok: true, data: await getSyncSettings() };1664        } catch (error) {1665          return {1666            ok: false,1667            error: error instanceof Error ? error.message : "invalid_relay_url",1668          };1669        }1670      }16711672      case "GET_SYNC_ALERTS": {1673        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1674        const alerts = await getPendingSyncAlerts();1675        // The popup reads on open and acknowledges with consume:true after1676        // rendering, so a popup crash between read and render doesn't lose1677        // the alerts.1678        if (consume) await clearPendingSyncAlerts();1679        return { ok: true, data: alerts };1680      }16811682      case "GET_PENDING_VOUCHED_DEVICES": {1683        return { ok: true, data: await listPendingVouchedDevices() };1684      }1685      case "CONFIRM_VOUCHED_DEVICE": {1686        const { deviceId } = msg.payload as { deviceId: string };1687        const pending = await getPendingVouchedDevice(deviceId);1688        if (!pending) return { ok: false, error: "not_pending" };1689        // Last gate before a vouched device becomes a sync peer. A queue entry1690        // can predate the revocation that names it, so revocation is re-checked1691        // here rather than trusted to have swept the queue.1692        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {1693          await removePendingVouchedDevice(deviceId);1694          return { ok: false, error: "device_revoked" };1695        }1696        await upsertPairedDeviceV3({1697          deviceId: pending.deviceId,1698          deviceName: pending.deviceName,1699          deviceType:1700            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1701          longTermPublicKeyHex: pending.longTermPublicKeyHex,1702          signingPublicKeyHex: pending.signingPublicKeyHex,1703          wsPort: pending.wsPort,1704          pairedAt: pending.pairedAt,1705          trustSource: "vouched",1706        });1707        await removePendingVouchedDevice(deviceId);1708        // Newly confirmed vouched device is now a sync target — kick a round1709        // so the mesh introduction pays off without a 10-minute wait.1710        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1711        return { ok: true };1712      }1713      case "REJECT_VOUCHED_DEVICE": {1714        const { deviceId } = msg.payload as { deviceId: string };1715        await removePendingVouchedDevice(deviceId);1716        return { ok: true };1717      }1718      case "ROTATE_SYNC_IDENTITY": {1719        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1720        const result = await vault.rotateSyncIdentity();1721        return result.ok ? { ok: true } : { ok: false, error: result.error };1722      }17231724      default:1725        return { ok: false, error: "unknown_message_type" };1726    }1727  } catch (err) {1728    return {1729      ok: false,1730      error: err instanceof Error ? err.message : "operation_failed",1731    };1732  }1733}17341735// Returns username use-counts from the vault, sorted by frequency. Each row1736// also carries the entry's email so the popup can suggest the email/username1737// pair the user has actually used together.1738function buildIdentitySuggestions(1739  entries: VaultEntry[],1740): Array<{ email: string; username: string; count: number }> {1741  const usernameCounts = new Map<string, number>();1742  const usernameEmail = new Map<string, string>();1743  for (const entry of entries) {1744    const username = entry.username ?? "";1745    const email = (entry as VaultEntry & { email?: string }).email ?? "";1746    if (!username && !email) continue;1747    const key = username || email;1748    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1749    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1750  }1751  return Array.from(usernameCounts.entries())1752    .sort((a, b) => b[1] - a[1])1753    .map(([username, count]) => ({1754      email: usernameEmail.get(username) ?? "",1755      username,1756      count,1757    }));1758}17591760/** Notify all content scripts that the vault just became available. */1761function broadcastToContentScripts(message: { type: string }): void {1762  if (!chrome.tabs?.query) return;1763  chrome.tabs.query({}, (tabs) => {1764    for (const tab of tabs) {1765      if (tab.id !== undefined) {1766        chrome.tabs.sendMessage(tab.id, message).catch(() => {1767          // Tab may not have a content script — silently ignore1768        });1769      }1770    }1771  });1772}17731774function shouldRefreshAutoLock(type: MessageType): boolean {1775  return (1776    type !== "HAS_VAULT" &&1777    type !== "IS_UNLOCKED" &&1778    type !== "GET_VAULT_STATUS" &&1779    type !== "LOCK" &&1780    type !== "UPDATE_SETTINGS" &&1781    type !== "GET_PENDING_PASSKEY" &&1782    type !== "GET_PASSKEY_PROVIDER_STATE" &&1783    type !== "DECLINE_CARD_SAVE" &&1784    type !== "IS_CARD_DECLINED" &&1785    type !== "AUTOFILL_QUERY" &&1786    type !== "ML_PREDICT_BATCH"1787  );1788}17891790function isAllowedCanaryWebhookUrl(value: string): boolean {1791  try {1792    const url = new URL(value);1793    if (url.protocol !== "https:") return false;17941795    const hostname = url.hostname.toLowerCase();1796    if (1797      hostname === "localhost" ||1798      hostname.endsWith(".localhost") ||1799      isPrivateIpv4(hostname) ||1800      isPrivateIpv6(hostname)1801    ) {1802      return false;1803    }18041805    return true;1806  } catch {1807    return false;1808  }1809}18101811function isPrivateIpv4(hostname: string): boolean {1812  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1813    return true;1814  }18151816  const octets = hostname.split(".").map((part) => Number(part));1817  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1818    return false;1819  }18201821  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1822}18231824function isPrivateIpv6(hostname: string): boolean {1825  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1826  // IPv4-mapped IPv6 literals embed a plain IPv4 address that the prefix1827  // list below can never match (WHATWG URL serializes [::ffff:192.168.0.1]1828  // as ::ffff:c0a8:1). Unwrap and test the embedded IPv4; unparseable mapped1829  // tails fail closed. (Codex Security 2026-08-04 LOW,1830  // ssrf.webhook-url-private-ip-filter.) DNS rebinding is out of scope for a1831  // one-shot host check.1832  const mapped = /^::ffff:(.+)$/.exec(normalized);1833  if (mapped) {1834    const tail = mapped[1] ?? "";1835    if (tail.includes(".")) return isPrivateIpv4(tail);1836    const parts = tail.split(":");1837    const [hi, lo] = parts;1838    if (1839      parts.length !== 2 ||1840      !hi ||1841      !lo ||1842      !/^[0-9a-f]{1,4}$/.test(hi) ||1843      !/^[0-9a-f]{1,4}$/.test(lo)1844    ) {1845      return true;1846    }1847    const octets = [1848      (Number.parseInt(hi, 16) >>> 8) & 0xff,1849      Number.parseInt(hi, 16) & 0xff,1850      (Number.parseInt(lo, 16) >>> 8) & 0xff,1851      Number.parseInt(lo, 16) & 0xff,1852    ];1853    return isPrivateIpv4(octets.join("."));1854  }1855  return (1856    normalized === "::1" ||1857    normalized.startsWith("fc") ||1858    normalized.startsWith("fd") ||1859    normalized.startsWith("fe80:")1860  );1861}