messages.ts

52.8 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 } from "./clipboard";13import { setupAutoLock, touchAutoLock } from "./alarms";14import { runSelfTest } from "./self-test";15import * as vault from "./vault";16import {17  handleEstimateCodexPages,18  handleGetCodexVaultData,19  handleRestoreFromCodex,20} from "./codex-handlers";21import type { CodexRestorePayload } from "../shared/codex-types";22import {23  activateLicense,24  deactivateLicense,25  getLicenseInfo,26  getLicenseKey,27  isProUser,28  markCelebrationPlayed,29  shouldPlayCelebration,30} from "./license";31import {32  completeFirefoxPasskeyCreate,33  getPasskeyProviderState,34  getPendingPasskeyRequest,35  handleFirefoxPasskeyCreate,36  handleFirefoxPasskeyGet,37  handlePasskeyHasCredentials,38  initiateFirefoxPasskeyCreate,39  isPasskeyOfferDeclined,40  onVaultUnlocked,41  recordPasskeyOfferDecline,42  resolvePendingPasskeyRequest,43  setPasskeyProviderEnabled,44} from "./passkey";45import { buildAdvancedHealthReport } from "./health";46import { storageClear } from "../shared/storage";47import { findInvalidWords } from "../shared/recovery-words";48import type {49  Message,50  MessageResponse,51  MessageType,52  ProFeature,53  VaultEntry,54} from "../shared/types";55import { isPasskeyOnly } from "../shared/types";56import { generateTOTP } from "../crypto/totp";57import { isNativePlatform, nativePlugin } from "../shared/native";58import { predictBatch as mlPredictBatch } from "./ml";59import type { MLFieldFeatures } from "../shared/ml";60import { buildLocalIdentity, setDeviceName as setDeviceNameV3 } from "./chirp-identity";61import {62  listPairedDevices as listPairedDevicesV3,63  removePairedDeviceById as removePairedDeviceByIdV3,64  upsertPairedDevice as upsertPairedDeviceV3,65} from "./paired-devices";6667let nativeSyncRunnerBootstrapped = false;6869function unhexBytes(hex: string): Uint8Array {70  if (hex.length % 2 !== 0) throw new Error("invalid hex");71  const out = new Uint8Array(hex.length / 2);72  for (let i = 0; i < out.length; i++) {73    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);74  }75  return out;76}7778/**79 * The single Pro gate. Every gated handler calls this first; the broadcast80 * lets the popup react (navigate to the License section, highlight the81 * relevant feature). Background never touches the popup view directly —82 * the popup owns navigation. See Projects.md "Pro gate rule".83 */84async function requirePro(85  feature: ProFeature,86  trigger: "user" | "background" = "user"87): Promise<{ allowed: boolean }> {88  if (await isProUser()) return { allowed: true };8990  if (trigger === "user") {91    // User deliberately triggered this feature — redirect the popup immediately.92    chrome.runtime93      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })94      .catch(() => {95        // Popup may be closed — the gate signal is best-effort.96      });97  } else {98    // Background trigger (e.g. passive sync initiation) — no popup is open.99    // Queue a notice so the next popup open shows a soft banner instead of100    // silently failing.101    if (chrome.storage.session) {102      chrome.storage.session103        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })104        .catch(() => {});105    }106  }107108  return { allowed: false };109}110111// ---------------------------------------------------------------------------112// Feedback submission target. Empty disables network submission while the UI113// continues to function as a no-op (the handler returns ok:true without114// calling fetch). When set, the URL is validated by115// `isAllowedCanaryWebhookUrl` before any request.116// ---------------------------------------------------------------------------117118const FEEDBACK_ENDPOINT = "";119120const PRIVATE_IPV4_RANGES = [121  { prefix: "10." },122  { prefix: "127." },123  { prefix: "169.254." },124  { prefix: "192.168." },125];126127export function setupMessageHandler(): void {128  chrome.runtime.onMessage.addListener(129    (msg: unknown, sender, sendResponse) => {130      if (!isMessage(msg)) {131        sendResponse({ ok: false, error: "invalid_message" });132        return true;133      }134      handleMessage(msg, sender)135        .then(sendResponse)136        .catch((err) =>137          sendResponse({138            ok: false,139            error: err instanceof Error ? err.message : String(err),140          })141        );142      return true;143    }144  );145146  // Android: the chrome shim queues sendMessage calls until this handler is147  // registered. Without this hookup, every message hangs on Capacitor builds.148  // eslint-disable-next-line @typescript-eslint/no-explicit-any149  const reg = (globalThis as any).__peachRegisterMessageHandler;150  if (typeof reg === "function") {151    reg(async (m: unknown) => {152      if (!isMessage(m)) return { ok: false, error: "invalid_message" };153      try {154        return await handleMessage(m);155      } catch (err) {156        return {157          ok: false,158          error: err instanceof Error ? err.message : String(err),159        };160      }161    });162  }163  if (isNativePlatform()) {164    void bootstrapNativeSyncRunner();165  }166}167168async function bootstrapNativeSyncRunner(): Promise<void> {169  if (nativeSyncRunnerBootstrapped) return;170  nativeSyncRunnerBootstrapped = true;171  try {172    const { setSyncRunner, hydratePersistedSyncState } = await import("./sync-trigger");173    const { productionSyncRunner } = await import("./chirp-sync-runner");174    setSyncRunner(productionSyncRunner);175    await hydratePersistedSyncState();176  } catch (err) {177    nativeSyncRunnerBootstrapped = false;178    console.warn("[Peach] failed to bootstrap native sync runner:", err);179  }180}181182function isMessage(m: unknown): m is Message {183  return typeof m === "object" && m !== null && "type" in m;184}185186export async function handleMessage(187  msg: Message,188  sender: Partial<chrome.runtime.MessageSender> = {}189): Promise<MessageResponse> {190  try {191    // Validate sender — only allow messages from our extension pages/scripts.192    // `sender.id` is undefined for messages originating from extension UI193    // (popup/options), which is legitimate; reject only when it is defined194    // and does not match our extension id.195    if (196      sender.id !== undefined &&197      sender.id !== chrome.runtime.id198    ) {199      return { ok: false, error: "invalid_sender" };200    }201202    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {203      touchAutoLock();204    }205206    switch (msg.type) {207      case "CREATE_VAULT": {208        const { password } = msg.payload as { password: string };209        await vault.createVault(password);210        await setupAutoLock();211        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });212        onVaultUnlocked();213        return { ok: true };214      }215      case "UNLOCK": {216        const { password } = msg.payload as { password: string };217        const ok = await vault.unlock(password);218        if (ok) {219          // KAT: verify the WebCrypto stack is healthy before the user relies on it.220          // Runs after unlock so latency is hidden behind the vault-load time.221          const kat = await runSelfTest();222          if (!kat.ok) {223            console.error("[Peach] Crypto self-test FAILED:", kat.error);224            await vault.lock();225            return { ok: false, error: "self_test_failed" };226          }227          await setupAutoLock();228          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });229          onVaultUnlocked();230          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());231          return { ok: true };232        }233        // Distinguish corruption from wrong password so the popup can offer234        // a history-restore path instead of falsely accusing the user of235        // mistyping (M7/COR-007).236        const failure = vault.consumeLastUnlockFailureReason();237        if (failure) {238          return {239            ok: false,240            error: "vault_corrupted",241            canRestoreFromHistory: true,242          } as MessageResponse;243        }244        return { ok: false };245      }246      case "VALIDATE_RECOVERY_WORDS": {247        const { words } = msg.payload as { words: string[] };248        const invalid = findInvalidWords(words);249        return { ok: true, data: { valid: invalid.length === 0, invalid } };250      }251      case "GET_RECOVERY_WORDS": {252        // Must be unlocked and have recovery set up (vault must be v2.12+).253        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };254        try {255          const words = await vault.getRecoveryWords();256          return { ok: true, data: words };257        } catch (e) {258          // pre-v2.12 vault that hasn't migrated259          return { ok: false, error: "recovery_not_setup" };260        }261      }262      case "RECOVER_WITH_WORDS": {263        // User has lost their password but has their 12 recovery words.264        // We: (1) validate the words, (2) re-encrypt vault with new password.265        const { words, newPassword } = msg.payload as {266          words: string[];267          newPassword: string;268        };269        const stored = await vault.loadSlotA();270        if (!stored) return { ok: false, error: "no_vault" };271        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {272          return { ok: false, error: "recovery_not_setup" };273        }274        // Unwrap the root key from the recovery escrow.275        try {276          await vault.unwrapRootKeyForRecovery(277            stored.recovery_wrapped_root_key,278            stored.recovery_nonce ?? "",279            stored.recovery_tag ?? "",280            stored.recovery_salt,281            words282          );283        } catch {284          return { ok: false, error: "invalid_recovery_words" };285        }286        // Re-key: derive fresh salt + key from new password.287        const newSalt = vault.generateSalt();288        const newKey = await vault.deriveKey(newPassword, newSalt);289        // Re-wrap root key under the new password's derived key so the same290        // recovery words continue to work after the password change.291        await vault.rewrapRootKeyForPassword(newKey, newSalt);292        // Re-encrypt vault entries with the new key.293        await vault.changePasswordWithNewKey(newSalt, newKey);294        await setupAutoLock();295        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });296        return { ok: true };297      }298      case "LOCK":299        vault.lock();300        if (isNativePlatform()) await clearInMemoryVault();301        return { ok: true };302      case "IS_UNLOCKED":303        return { ok: true, data: vault.isUnlocked() };304      case "GET_VAULT_STATUS":305        return { ok: true, unlocked: vault.isUnlocked() };306      case "HAS_VAULT":307        return { ok: true, data: await vault.hasVault() };308      case "GET_ENTRIES":309        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };310        return { ok: true, data: vault.getEntries() };311      case "ADD_ENTRY": {312        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };313        const payload = msg.payload;314        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {315          return { ok: false, error: "invalid_payload" };316        }317        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);318        return { ok: true, data: entry };319      }320      case "BATCH_ADD_ENTRIES": {321        const payload = msg.payload as { entries?: unknown } | null | undefined;322        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {323          return { ok: false, error: "invalid_payload" };324        }325        if (!Array.isArray(payload.entries)) {326          return { ok: false, error: "invalid_payload" };327        }328        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);329        return { ok: true, data: added };330      }331      case "RESTORE_ENTRIES": {332        const payload = msg.payload as333          | { entries?: unknown; mode?: unknown; settings?: unknown }334          | null335          | undefined;336        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {337          return { ok: false, error: "invalid_payload" };338        }339        if (!Array.isArray(payload.entries)) {340          return { ok: false, error: "invalid_payload" };341        }342        if (payload.mode !== "replace" && payload.mode !== "merge") {343          return { ok: false, error: "invalid_payload" };344        }345        const summary = await vault.restoreEntries(346          payload.entries as Parameters<typeof vault.restoreEntries>[0],347          payload.mode348        );349        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {350          await vault.updateSettings(payload.settings as vault.VaultSettings);351        }352        return { ok: true, data: summary };353      }354      case "CLEAR_VAULT_ENTRIES": {355        await vault.clearVaultEntries("REPLACE_ALL");356        return { ok: true };357      }358      case "GET_VAULT_HISTORY": {359        const snapshots = await vault.getVaultHistory();360        return { ok: true, data: snapshots };361      }362      case "RESTORE_VAULT_SNAPSHOT": {363        const { snapshotId } = msg.payload as { snapshotId: string };364        const result = await vault.restoreVaultSnapshot(snapshotId);365        if (!result.ok) return { ok: false, error: result.error };366        broadcastToContentScripts({ type: "VAULT_LOCKED" });367        return { ok: true };368      }369      case "COUNT_DUPLICATES": {370        return { ok: true, data: vault.countDuplicates() };371      }372      case "DEDUPLICATE_ENTRIES": {373        const removed = await vault.deduplicateEntries();374        return { ok: true, data: removed };375      }376      case "UPDATE_ENTRY": {377        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;378        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {379          return { ok: false, error: "invalid_payload" };380        }381        const { id, patch } = payload;382        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {383          return { ok: false, error: "invalid_payload" };384        }385        // Single enforcement point for the Canary Entries Pro gate. Only386        // gates the transition into a canary entry — clearing/disabling a387        // canary (`canary: undefined`) is always allowed, so existing388        // canary entries remain manageable.389        const incomingCanary = (patch as { canary?: unknown }).canary;390        if (incomingCanary && typeof incomingCanary === "object") {391          const existing = vault.getEntryById(id);392          if (!existing?.canary) {393            const gate = await requirePro("canary_entry");394            if (!gate.allowed) return { ok: false, error: "pro_required" };395          }396        }397        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);398        return { ok: true };399      }400      case "ADD_ADDITIONAL_URL": {401        const { id, url } = msg.payload as { id: string; url: string };402        const trimmed = typeof url === "string" ? url.trim() : "";403        if (!trimmed) return { ok: false, error: "url_required" };404        const existing = vault.getEntryById(id);405        if (!existing) return { ok: false, error: "entry_not_found" };406        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };407        const merged = [...(existing.additionalUrls ?? []), trimmed];408        await vault.updateEntry(id, { additionalUrls: merged });409        return { ok: true };410      }411      case "DELETE_ENTRY": {412        const { id } = msg.payload as { id: string };413        await vault.deleteEntry(id);414        return { ok: true };415      }416      case "GET_DELETED_ENTRIES":417        return { ok: true, data: vault.getDeletedEntries() };418      case "RESTORE_ENTRY": {419        const { id } = msg.payload as { id: string };420        await vault.restoreEntry(id);421        return { ok: true };422      }423      case "PURGE_ENTRY": {424        const { id } = msg.payload as { id: string };425        await vault.purgeEntry(id);426        return { ok: true };427      }428      case "PURGE_EXPIRED_TRASH": {429        const { retentionMs } = msg.payload as { retentionMs: number };430        const purged = await vault.purgeExpiredTrash(retentionMs);431        return { ok: true, data: purged };432      }433      case "SAVE_NOTE": {434        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };435        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };436        const now = Date.now();437        if (id) {438          const existing = vault.getEntryById(id);439          if (!existing) return { ok: false, error: "not_found" };440          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });441          return { ok: true, data: vault.getEntryById(id) };442        } else {443          const entry = await vault.addEntry({444            type: "note",445            title: title || "Untitled",446            notes: body,447            createdAt: now,448            modifiedAt: now,449          } as any);450          return { ok: true, data: entry };451        }452      }453      case "DELETE_NOTE": {454        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };455        const { id } = msg.payload as { id: string };456        await vault.deleteEntry(id);457        return { ok: true };458      }459      case "GET_NOTES": {460        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };461        const notes = vault.getEntries().filter(462          (e) => e.type === "note" && !e.deletedAt463        );464        return { ok: true, data: notes } as MessageResponse;465      }466      case "SEARCH_VAULT": {467        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };468        // AUD-002: shape-validate the payload before calling string methods.469        // A raw cast lets a malformed message crash the handler with TypeError.470        const { query } = (msg.payload ?? {}) as { query?: unknown };471        if (typeof query !== "string") {472          return { ok: false, error: "invalid_payload" };473        }474        const q = query.toLowerCase();475        const searchResults = vault.getEntries().filter(476          (e) =>477            !e.deletedAt &&478            (e.title.toLowerCase().includes(q) ||479              e.notes?.toLowerCase().includes(q) ||480              e.username?.toLowerCase().includes(q))481        );482        return { ok: true, data: searchResults } as MessageResponse;483      }484      case "AUTOFILL_QUERY": {485        if (!vault.isUnlocked()) {486          return { ok: false, error: "vault_locked" };487        }488        const { domain, includeAll, kind } = msg.payload as {489          domain: string;490          includeAll?: boolean;491          kind?: "login" | "card" | "totp";492        };493        // kind="card": return saved cards as compact summaries for the494        // inline card silver platter. Cards are not domain-scoped — every495        // saved card is a candidate on every checkout page — so domain is496        // ignored when kind === "card".497        if (kind === "card") {498          const cards = vault.getEntries().filter((e) => e.type === "card");499          return {500            ok: true,501            data: cards.map((e) => ({502              id: e.id,503              title: e.cardNickname || e.title,504              cardholderName: e.cardholderName,505              last4: e.last4,506              expMonth: e.expMonth,507              expYear: e.expYear,508              network: e.network,509            })),510          };511        }512        if (kind === "totp") {513          const matches = (514            includeAll515              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")516              : vault.queryDomain(domain)517          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));518          return {519            ok: true,520            data: matches.map((e) => ({521              id: e.id,522              title: e.title,523              username: e.username,524              email: e.email,525              url: e.url,526              hasTotp: true,527            })),528          };529        }530        // The inline selector fills username+password into a form. Passkey-531        // only entries have no password to fill; sign-in for those goes532        // through the WebAuthn path instead. Filter them out everywhere so533        // the user doesn't see four "GitHub" rows that mostly do nothing.534        // Notes and cards never belonged here either.535        const matches = (536          includeAll537            ? vault538                .getEntries()539                .filter((entry) => entry.type !== "note" && entry.type !== "card")540            : vault.queryDomain(domain)541        ).filter((entry) => !isPasskeyOnly(entry));542        return {543          ok: true,544          data: matches.map((e) =>545            includeAll546              ? {547                  id: e.id,548                  title: e.title,549                  // username/email/url shipped so the inline popup's search550                  // affordance can match on them, not just titles. No secrets551                  // cross the boundary — same shape as the domain-matched552                  // response below minus hasTotp (which the search list553                  // doesn't surface).554                  username: e.username,555                  email: e.email,556                  url: e.url,557                  hasPasskey: e.passkey !== undefined,558                }559              : {560                  id: e.id,561                  title: e.title,562                  username: e.username,563                  email: e.email,564                  url: e.url,565                  hasTotp: Boolean(e.totp),566                  hasPasskey: e.passkey !== undefined,567                }568          ),569        };570      }571      case "GET_ENTRY_FOR_FILL": {572        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };573        const { id } = msg.payload as { id: string };574        const entry = vault.getEntryById(id);575        if (!entry) return { ok: false, error: "entry_not_found" };576        // Passkey-only entries (passkey credential, no password) cannot be577        // filled into a form — sign-in goes through the WebAuthn path. A578        // login that ALSO has a passkey is still fillable for its password.579        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };580        // Strip the passkey credential AND the raw base32 TOTP seed from the581        // response. Content scripts never need either: the private key is the582        // authenticator's, and handing over the TOTP seed would let a583        // compromised content script mint valid codes indefinitely (SEV-3-C).584        // Generate the *current* 6-digit code here in the background and send585        // only that, plus the seconds left so the UI can render a countdown.586        const { passkey: _strippedPasskey, totp: seed, ...safeEntry } = entry;587        let totpCode: string | undefined;588        let totpRemaining: number | undefined;589        if (seed) {590          try {591            const generated = generateTOTP(seed);592            totpCode = generated.code;593            totpRemaining = generated.remaining;594          } catch {595            totpCode = undefined;596          }597        }598        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };599      }600      // Trusted full-entry fetch for Peach's own inline-popup surfaces that601      // genuinely need the raw TOTP seed: the edit form (which re-saves the602      // seed and would otherwise wipe it) and nothing else. Unlike603      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside604      // the inline popup, never during passive autofill on an arbitrary page.605      // The passkey credential is still stripped — the edit form never touches it.606      case "GET_ENTRY_FOR_EDIT": {607        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };608        const { id } = msg.payload as { id: string };609        const entry = vault.getEntryById(id);610        if (!entry) return { ok: false, error: "entry_not_found" };611        const { passkey: _passkey, ...safeEntry } = entry;612        return { ok: true, data: safeEntry };613      }614      case "COPY": {615        // AUD-002: shape-validate the payload before passing to the clipboard616        // helper. A raw cast lets a malformed message reach the clipboard API617        // with a non-string and throw.618        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {619          text?: unknown;620          label?: unknown;621          alreadyWritten?: unknown;622        };623        if (typeof text !== "string" || typeof label !== "string") {624          return { ok: false, error: "invalid_payload" };625        }626        await copyToClipboard(text, label, Boolean(alreadyWritten));627        return { ok: true };628      }629      case "CHECK_ALL_BREACHES": {630        const allEntries = vault.getEntries();631        const results: Record<string, number> = {};632        for (const entry of allEntries) {633          if (entry.type === "note") continue;634          if (!entry.password) continue;635          results[entry.id] = await vault.checkBreach(entry.password);636          // Small delay — be a good citizen to the HIBP API637          await new Promise((r) => setTimeout(r, 200));638        }639        // Persist any non-zero counts back to entries640        for (const [id, count] of Object.entries(results)) {641          const entry = vault.getEntryById(id);642          if (entry && (entry.breach ?? 0) !== count) {643            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });644          }645        }646        return { ok: true, data: results };647      }648      case "GET_SETTINGS":649        return { ok: true, data: await vault.ensureSettingsLoaded() };650      case "UPDATE_SETTINGS": {651        const patch = msg.payload;652        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {653          return { ok: false, error: "invalid_payload" };654        }655        await vault.updateSettings(patch as vault.VaultSettings);656        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {657          await setupAutoLock();658          if (vault.isUnlocked()) touchAutoLock();659        }660        return { ok: true };661      }662      case "GET_PENDING_PASSKEY":663        return { ok: true, data: await getPendingPasskeyRequest() };664      case "APPROVE_PASSKEY": {665        const { requestId } = msg.payload as { requestId: number };666        await resolvePendingPasskeyRequest(requestId, true);667        return { ok: true };668      }669      case "DENY_PASSKEY": {670        const { requestId } = msg.payload as { requestId: number };671        await resolvePendingPasskeyRequest(requestId, false);672        return { ok: true };673      }674      case "GET_PASSKEY_PROVIDER_STATE":675        return { ok: true, data: await getPasskeyProviderState() };676      case "SET_PASSKEY_PROVIDER_ENABLED": {677        const { enabled } = msg.payload as { enabled: boolean };678        // Disabling is always free; gating fires only when a free user is679        // trying to turn passkey interception on.680        if (enabled) {681          const gate = await requirePro("passkeys");682          if (!gate.allowed) return { ok: false, error: "pro_required" };683        }684        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };685      }686      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS687      // endpoint. Intentional product behavior — users configure their own688      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private689      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-690      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to691      // users that the entry title leaves the device when the canary fires.692      case "FIRE_CANARY_PING": {693        // Canary alert fires unconditionally for any entry with canary: true.694        // The Pro gate only governs creation/flagging of canary entries; once695        // an entry is flagged, the alert path is a security property and must696        // never be license-gated.697        const { webhookUrl, entryTitle, trigger } = msg.payload as {698          webhookUrl: string;699          entryTitle: string;700          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";701        };702        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {703          return { ok: false, error: "invalid_webhook_url" };704        }705        const body = JSON.stringify({706          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",707          entry: entryTitle,708          trigger,709          timestamp: new Date().toISOString(),710          source: "peach-extension",711        });712        if (trigger === "test") {713          // Permitted outbound fetch: user-configured canary alert endpoint714          // (validated by isAllowedCanaryWebhookUrl above). This is the715          // only non-HIBP outbound call in the extension — see716          // Projects.md §3.7. Test pings are awaited so the UI can show717          // success/failure.718          try {719            const res = await fetch(webhookUrl, {720              method: "POST",721              headers: { "Content-Type": "application/json" },722              body,723            });724            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };725          } catch (err) {726            return { ok: false, error: err instanceof Error ? err.message : "network_error" };727          }728        }729        // Non-test triggers are fire-and-forget730        fetch(webhookUrl, {731          method: "POST",732          headers: { "Content-Type": "application/json" },733          body,734        }).catch(() => {});735        return { ok: true };736      }737      case "ACTIVATE_LICENSE": {738        const { key } = msg.payload as { key: string };739        const licenseInfo = await activateLicense(key);740        return { ok: true, data: licenseInfo };741      }742      case "GET_LICENSE": {743        const licenseInfo = await getLicenseInfo();744        return { ok: true, data: licenseInfo };745      }746      case "GET_LICENSE_KEY": {747        const key = await getLicenseKey();748        return { ok: true, data: key };749      }750      case "DEACTIVATE_LICENSE": {751        await deactivateLicense();752        return { ok: true };753      }754      case "SHOULD_PLAY_CELEBRATION": {755        const should = await shouldPlayCelebration();756        return { ok: true, data: should };757      }758      case "MARK_CELEBRATION_PLAYED": {759        await markCelebrationPlayed();760        return { ok: true };761      }762      case "GET_CODEX_VAULT_DATA": {763        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the764        // popup navigates to the License section without further coordination.765        const gate = await requirePro("codex");766        if (!gate.allowed) return { ok: false, error: "pro_required" };767        return await handleGetCodexVaultData();768      }769      case "ESTIMATE_CODEX_PAGES": {770        const gate = await requirePro("codex");771        if (!gate.allowed) return { ok: false, error: "pro_required" };772        return await handleEstimateCodexPages();773      }774      case "RESTORE_FROM_CODEX": {775        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still776        // be able to restore a vault that was printed by a Pro user.777        // DO NOT add a Pro gate here.778        const payload = msg.payload as CodexRestorePayload;779        return await handleRestoreFromCodex(payload);780      }781      case "OPEN_PRO_GATE": {782        // Content script requests: open popup and navigate to License section.783        const { feature } = (msg.payload ?? {}) as { feature?: string };784        if (chrome.storage.session) {785          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });786        }787        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }788        return { ok: true };789      }790      case "GET_IDENTITIES": {791        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };792        return { ok: true, data: vault.getIdentities() };793      }794      case "TOUCH_AUTO_LOCK": {795        // touchAutoLock() is already called by shouldRefreshAutoLock above;796        // this case just gives the popup a typed message to keep the session alive.797        return { ok: true };798      }799      case "GET_ADVANCED_HEALTH_REPORT": {800        const gate = await requirePro("advanced_health");801        if (!gate.allowed) return { ok: false, error: "pro_required" };802        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };803        const report = await buildAdvancedHealthReport(vault.getEntries());804        return { ok: true, data: report };805      }806      case "IS_DURESS_ENABLED": {807        const enabled = await vault.isDuressEnabled();808        return { ok: true, data: enabled };809      }810      case "SETUP_DURESS": {811        // Single enforcement point for the Duress Vault Pro gate. Free users812        // who somehow reach this handler are rejected here; the popup also813        // pre-checks isPro() to avoid showing the setup form to free users,814        // but server-side is the actual security boundary.815        const gate = await requirePro("duress_vault");816        if (!gate.allowed) return { ok: false, error: "pro_required" };817        // MV3 service workers restart after inactivity, losing the in-memory818        // derived key. Detect this before calling setupDuress so the popup819        // can show a meaningful prompt to re-lock and re-unlock.820        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };821        const { duressPassword } = msg.payload as { duressPassword: string };822        await vault.setupDuress(duressPassword);823        return { ok: true };824      }825      case "DISABLE_DURESS": {826        await vault.disableDuress();827        return { ok: true };828      }829      case "VERIFY_MAIN_PASSWORD": {830        const { password } = msg.payload as { password: string };831        const ok = await vault.verifyMainPassword(password);832        return { ok: true, data: ok };833      }834      case "CHANGE_PASSWORD": {835        const { currentPassword, newPassword } = msg.payload as {836          currentPassword: string;837          newPassword: string;838        };839        const changed = await vault.changePassword(currentPassword, newPassword);840        return changed841          ? { ok: true }842          : { ok: false, error: "incorrect_current_password" };843      }844      case "GET_SITE_PASSWORD_POLICY": {845        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });846        if (!tab?.id) return { ok: true, data: null };847        try {848          const response = await chrome.tabs.sendMessage(tab.id, {849            type: "GET_SITE_PASSWORD_POLICY",850          });851          return (response as MessageResponse) ?? { ok: true, data: null };852        } catch {853          return { ok: true, data: null };854        }855      }856      case "RECORD_MANUAL_SUMMON": {857        const { domain } = msg.payload as { domain: string };858        const settings = vault.getSettings();859        const existing = settings.manualSummonDomains?.[domain];860        const now = Date.now();861        await vault.updateSettings({862          manualSummonDomains: {863            ...settings.manualSummonDomains,864            [domain]: {865              firstSummonedAt: existing?.firstSummonedAt ?? now,866              summonCount: (existing?.summonCount ?? 0) + 1,867              lastSummonedAt: now,868            },869          },870        });871        return { ok: true };872      }873      case "DECLINE_CARD_SAVE": {874        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };875        await vault.declineCardSaveOffer(last4, expMonth, expYear);876        return { ok: true };877      }878      case "IS_CARD_DECLINED": {879        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };880        const declined = await vault.isCardDeclined(last4, expMonth, expYear);881        return { ok: true, data: declined };882      }883      case "INITIATE_FIREFOX_PASSKEY_CREATE": {884        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {885          rpId?: string;886          rpName?: string;887          userName?: string;888          userDisplayName?: string;889        };890        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };891        return await initiateFirefoxPasskeyCreate({892          rpId,893          rpName: rpName ?? rpId,894          userName,895          userDisplayName,896        });897      }898899      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {900        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;901        if (!payload) return { ok: false, error: "missing_payload" };902        return await completeFirefoxPasskeyCreate(payload);903      }904905      case "PASSKEY_OFFER_DECLINE": {906        const { domain } = (msg.payload ?? {}) as { domain?: string };907        if (!domain) return { ok: false, error: "domain_required" };908        await recordPasskeyOfferDecline(domain);909        return { ok: true };910      }911912      case "GET_PASSKEY_OFFER_DECLINED": {913        const { domain } = (msg.payload ?? {}) as { domain?: string };914        if (!domain) return { ok: false, error: "domain_required" };915        return { ok: true, data: await isPasskeyOfferDeclined(domain) };916      }917918      case "PASSKEY_HAS_CREDENTIALS": {919        const payload = msg.payload as {920          rpId?: string;921          allowCredentials?: Array<{ id: string; type?: string }>;922        } | undefined;923        if (!payload?.rpId) return { ok: false, error: "rpid_required" };924        return await handlePasskeyHasCredentials({925          rpId: payload.rpId,926          allowCredentials: payload.allowCredentials ?? [],927        });928      }929930      case "PASSKEY_CREATE": {931        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;932        if (!payload?.rpId || !payload?.userName) {933          return { ok: false, error: "rpid_and_username_required" };934        }935        return await handleFirefoxPasskeyCreate(payload);936      }937938      case "PASSKEY_GET": {939        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;940        if (!payload?.rpId) return { ok: false, error: "rpid_required" };941        return await handleFirefoxPasskeyGet(payload);942      }943944      case "PASSKEY_AUTH_RESPONSE": {945        const { requestId, approved } = (msg.payload ?? {}) as {946          requestId?: string | number;947          approved?: boolean;948        };949        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {950          return { ok: false, error: 'requestId and approved required' };951        }952        await resolvePendingPasskeyRequest(Number(requestId), approved);953        return { ok: true };954      }955956      case "GET_PASSKEY_FOR_DOMAIN": {957        const { domain } = (msg.payload ?? {}) as { domain?: string };958        if (!domain) return { ok: false, error: "domain_required" };959        if (!vault.isUnlocked()) return { ok: true, data: null };960        const match = vault961          .getEntries()962          .find((entry) => entry.passkey?.rpId === domain);963        if (!match || !match.passkey) return { ok: true, data: null };964        // Slim shape — only the fields State 11 needs. Never expose private965        // key material, even though this is locked behind isUnlocked.966        return {967          ok: true,968          data: {969            rpId: match.passkey.rpId,970            userName: match.passkey.userName,971            browser: match.passkey.browser,972          },973        };974      }975976      case "DESTROY_VAULT": {977        // Irreversible by design. Lock zeroes the derived key + in-memory entries;978        // storage.local.clear() wipes every Peach key (slots, settings, license,979        // onboarded flag, history, sync state, declined cards, recall, etc.);980        // session.clear() wipes pending passkey requests + pro-notice queues.981        // Caller (Panic.tsx) handles UI navigation back to onboarding.982        //983        // The Pro license is the one thing that must survive: the user paid for984        // it, and destroying a vault (panic wipe, fresh start) is not a refund.985        // Capture it before the clear and restore it after. peach_pro_celebrated986        // rides along so the Pro celebration doesn't replay on the next unlock.987        const preserved = await chrome.storage.local.get([988          "peach_license",989          "peach_pro_celebrated",990        ]);991        vault.lock();992        await storageClear();993        await vault.clearVaultHistory();994        const toRestore: Record<string, unknown> = {};995        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;996        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;997        if (Object.keys(toRestore).length > 0) {998          await chrome.storage.local.set(toRestore);999        }1000        if (chrome.storage.session) {1001          await chrome.storage.session.clear();1002        }1003        return { ok: true };1004      }10051006      case "SUBMIT_FEEDBACK": {1007        const { category, message, version, browser } = msg.payload as {1008          category: string;1009          message: string;1010          version: string;1011          browser: string;1012        };1013        if (!message.trim()) return { ok: false, error: "message_empty" };1014        if (!FEEDBACK_ENDPOINT) return { ok: true };1015        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1016          return { ok: false, error: "invalid_feedback_endpoint" };1017        }1018        try {1019          const res = await fetch(FEEDBACK_ENDPOINT, {1020            method: "POST",1021            headers: { "Content-Type": "application/json" },1022            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1023          });1024          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1025        } catch (err) {1026          return { ok: false, error: err instanceof Error ? err.message : "network_error" };1027        }1028      }1029      // Android-only: biometric unlock with pre-derived key.1030      case "UNLOCK_WITH_KEY": {1031        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1032        if (!isNativePlatform()) {1033          return { ok: false, error: "desktop_only_uses_password" };1034        }1035        try {1036          const result = await vault.unlockWithKey(masterKeyHex);1037          if (result.ok) {1038            onVaultUnlocked();1039            await publishInMemoryVault(result.entries);1040          }1041          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1042        } catch {1043          return { ok: false, error: "invalid_key" };1044        }1045      }1046      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1047      case "GET_DERIVED_KEY": {1048        if (!isNativePlatform()) {1049          return { ok: false, error: "android_only" };1050        }1051        if (!vault.isUnlocked()) {1052          return { ok: false, error: "vault_locked" };1053        }1054        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1055      }1056      case "GET_IDENTITY_SUGGESTIONS": {1057        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1058        const entries = vault.getEntries();1059        const suggestions = buildIdentitySuggestions(entries);1060        return { ok: true, data: { suggestions } };1061      }1062      case "POPULATE_INLINE_VAULT": {1063        if (!isNativePlatform()) return { ok: false };1064        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1065        const entries = vault.getEntries();1066        await publishInMemoryVault(entries);1067        return { ok: true };1068      }1069      case "ML_INIT":1070        return { ok: true };10711072      case "ML_PREDICT_BATCH": {1073        // AUD-002: shape-validate before forwarding to the ML helper.1074        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1075        if (!Array.isArray(featuresArray)) {1076          return { ok: false, error: "invalid_payload" };1077        }1078        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1079      }10801081      // ── Chirp Sync (v3) ───────────────────────────────────────────────1082      // Returns the public-facing local identity needed by the popup to1083      // drive Phase-1 audio pairing. The private long-term key never1084      // leaves the background.1085      case "CHIRP_GET_LOCAL_IDENTITY": {1086        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1087        const proCheck = await requirePro("sync");1088        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1089        // Identity derives from the stable root key, not the password-derived1090        // key, so pairing survives a master-password change (SEV-2-B).1091        const masterKeyHex = vault.getRootKeyHex();1092        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1093        const masterKey = unhexBytes(masterKeyHex);1094        try {1095          const identity = await buildLocalIdentity(masterKey);1096          return { ok: true, data: identity };1097        } finally {1098          masterKey.fill(0);1099        }1100      }11011102      case "CHIRP_COMPLETE_PAIRING": {1103        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1104        const proCheck = await requirePro("sync");1105        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1106        const paired = (msg.payload as { paired?: unknown })?.paired;1107        if (typeof paired !== "object" || paired === null) {1108          return { ok: false, error: "invalid_payload" };1109        }1110        const candidate = paired as Record<string, unknown>;1111        if (1112          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1113          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1114          typeof candidate.deviceType !== "string" ||1115          typeof candidate.longTermPublicKeyHex !== "string" ||1116          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1117          (1118            candidate.signingPublicKeyHex !== undefined &&1119            (1120              typeof candidate.signingPublicKeyHex !== "string" ||1121              !/^[0-9a-f]{64}$/.test(candidate.signingPublicKeyHex)1122            )1123          ) ||1124          typeof candidate.pairedAt !== "number"1125        ) {1126          return { ok: false, error: "invalid_paired_device" };1127        }1128        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1129        return { ok: true };1130      }11311132      case "CHIRP_LIST_PAIRED_DEVICES": {1133        const devices = await listPairedDevicesV3();1134        return { ok: true, data: { devices } };1135      }11361137      case "CHIRP_UNPAIR_DEVICE": {1138        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1139        if (typeof deviceId !== "string" || !deviceId) {1140          return { ok: false, error: "invalid_payload" };1141        }1142        await removePairedDeviceByIdV3(deviceId);1143        return { ok: true };1144      }11451146      case "CHIRP_RENAME_LOCAL_DEVICE": {1147        const { name } = (msg.payload ?? {}) as { name?: string };1148        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1149        await setDeviceNameV3(name);1150        return { ok: true };1151      }11521153      case "TRIGGER_SYNC": {1154        const payload = (msg.payload ?? {}) as {1155          reason?: "vault_change" | "foreground" | "manual" | "mdns";1156          force?: boolean;1157          deviceId?: string;1158          discoveredIp?: string;1159          discoveredPort?: number;1160        };1161        const reason = payload.reason ?? "foreground";11621163        // mDNS discovery delivers a fresh (ip, port) resolved by the native1164        // side. Update the cached address before the sync runner tries to1165        // connect — avoids a subnet probe on the very next round.1166        if (1167          reason === "mdns" &&1168          typeof payload.deviceId === "string" &&1169          typeof payload.discoveredIp === "string"1170        ) {1171          const { findPairedDeviceById, setLastKnownIp } = await import("./paired-devices");1172          const device = await findPairedDeviceById(payload.deviceId);1173          if (device?.longTermPublicKeyHex) {1174            await setLastKnownIp(device.longTermPublicKeyHex, payload.discoveredIp).catch(() => undefined);1175          }1176        }11771178        const { triggerSyncIfReachable } = await import("./sync-trigger");1179        void triggerSyncIfReachable({ reason, force: payload.force === true });1180        return { ok: true };1181      }11821183      case "GET_SYNC_STATE": {1184        const { getSyncState } = await import("./sync-trigger");1185        return { ok: true, data: getSyncState() };1186      }11871188      default:1189        return { ok: false, error: "unknown_message_type" };1190    }1191  } catch (err) {1192    return {1193      ok: false,1194      error: err instanceof Error ? err.message : "operation_failed",1195    };1196  }1197}11981199// --- Mobile platform helpers ---12001201// Android: populates the in-memory vault used by PeachAutofillService.1202async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1203  const plugin = nativePlugin<{1204    setEntries?: (args: {1205      entries: Array<{1206        id: string;1207        title: string;1208        username: string;1209        email: string;1210        password: string;1211        url: string;1212        totp: string;1213        additionalUrls: string[];1214      }>;1215    }) => Promise<void>;1216  }>("InMemoryVaultPlugin");1217  if (!plugin?.setEntries) return;1218  await plugin.setEntries({1219    entries: entries.map((e) => ({1220      id: e.id,1221      title: e.title ?? "",1222      username: e.username ?? "",1223      email: (e as VaultEntry & { email?: string }).email ?? "",1224      password: e.password ?? "",1225      url: e.url ?? "",1226      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1227      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1228    })),1229  });1230}12311232// Android: clear the autofill in-memory store on lock.1233async function clearInMemoryVault(): Promise<void> {1234  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1235  if (!plugin?.clearEntries) return;1236  await plugin.clearEntries();1237}12381239// Returns username use-counts from the vault, sorted by frequency. Each row1240// also carries the entry's email so the popup can suggest the email/username1241// pair the user has actually used together.1242function buildIdentitySuggestions(1243  entries: VaultEntry[],1244): Array<{ email: string; username: string; count: number }> {1245  const usernameCounts = new Map<string, number>();1246  const usernameEmail = new Map<string, string>();1247  for (const entry of entries) {1248    const username = entry.username ?? "";1249    const email = (entry as VaultEntry & { email?: string }).email ?? "";1250    if (!username && !email) continue;1251    const key = username || email;1252    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1253    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1254  }1255  return Array.from(usernameCounts.entries())1256    .sort((a, b) => b[1] - a[1])1257    .map(([username, count]) => ({1258      email: usernameEmail.get(username) ?? "",1259      username,1260      count,1261    }));1262}12631264/** Notify all content scripts that the vault just became available. */1265function broadcastToContentScripts(message: { type: string }): void {1266  if (!chrome.tabs?.query) return;1267  chrome.tabs.query({}, (tabs) => {1268    for (const tab of tabs) {1269      if (tab.id !== undefined) {1270        chrome.tabs.sendMessage(tab.id, message).catch(() => {1271          // Tab may not have a content script — silently ignore1272        });1273      }1274    }1275  });1276}12771278function shouldRefreshAutoLock(type: MessageType): boolean {1279  return (1280    type !== "HAS_VAULT" &&1281    type !== "IS_UNLOCKED" &&1282    type !== "GET_VAULT_STATUS" &&1283    type !== "LOCK" &&1284    type !== "UPDATE_SETTINGS" &&1285    type !== "GET_PENDING_PASSKEY" &&1286    type !== "GET_PASSKEY_PROVIDER_STATE" &&1287    type !== "DECLINE_CARD_SAVE" &&1288    type !== "IS_CARD_DECLINED" &&1289    type !== "SUBMIT_FEEDBACK"1290  );1291}12921293function isAllowedCanaryWebhookUrl(value: string): boolean {1294  try {1295    const url = new URL(value);1296    if (url.protocol !== "https:") return false;12971298    const hostname = url.hostname.toLowerCase();1299    if (1300      hostname === "localhost" ||1301      hostname.endsWith(".localhost") ||1302      isPrivateIpv4(hostname) ||1303      isPrivateIpv6(hostname)1304    ) {1305      return false;1306    }13071308    return true;1309  } catch {1310    return false;1311  }1312}13131314function isPrivateIpv4(hostname: string): boolean {1315  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1316    return true;1317  }13181319  const octets = hostname.split(".").map((part) => Number(part));1320  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1321    return false;1322  }13231324  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1325}13261327function isPrivateIpv6(hostname: string): boolean {1328  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1329  return (1330    normalized === "::1" ||1331    normalized.startsWith("fc") ||1332    normalized.startsWith("fd") ||1333    normalized.startsWith("fe80:")1334  );1335}