messages.ts

54.5 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard } 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 { isValidRpId } from "../shared/passkey-utils";58import { isNativePlatform, nativePlugin } from "../shared/native";59import { predictBatch as mlPredictBatch } from "./ml";60import type { MLFieldFeatures } from "../shared/ml";61import { buildLocalIdentity, setDeviceName as setDeviceNameV3 } from "./chirp-identity";62import {63  listPairedDevices as listPairedDevicesV3,64  removePairedDeviceById as removePairedDeviceByIdV3,65  upsertPairedDevice as upsertPairedDeviceV3,66} from "./paired-devices";6768let nativeSyncRunnerBootstrapped = false;6970function unhexBytes(hex: string): Uint8Array {71  if (hex.length % 2 !== 0) throw new Error("invalid hex");72  const out = new Uint8Array(hex.length / 2);73  for (let i = 0; i < out.length; i++) {74    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);75  }76  return out;77}7879/**80 * The single Pro gate. Every gated handler calls this first; the broadcast81 * lets the popup react (navigate to the License section, highlight the82 * relevant feature). Background never touches the popup view directly —83 * the popup owns navigation. See Projects.md "Pro gate rule".84 */85async function requirePro(86  feature: ProFeature,87  trigger: "user" | "background" = "user"88): Promise<{ allowed: boolean }> {89  if (await isProUser()) return { allowed: true };9091  if (trigger === "user") {92    // User deliberately triggered this feature — redirect the popup immediately.93    chrome.runtime94      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })95      .catch(() => {96        // Popup may be closed — the gate signal is best-effort.97      });98  } else {99    // Background trigger (e.g. passive sync initiation) — no popup is open.100    // Queue a notice so the next popup open shows a soft banner instead of101    // silently failing.102    if (chrome.storage.session) {103      chrome.storage.session104        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })105        .catch(() => {});106    }107  }108109  return { allowed: false };110}111112// ---------------------------------------------------------------------------113// Feedback submission target. Empty disables network submission while the UI114// continues to function as a no-op (the handler returns ok:true without115// calling fetch). When set, the URL is validated by116// `isAllowedCanaryWebhookUrl` before any request.117// ---------------------------------------------------------------------------118119const FEEDBACK_ENDPOINT = "";120121const PRIVATE_IPV4_RANGES = [122  { prefix: "10." },123  { prefix: "127." },124  { prefix: "169.254." },125  { prefix: "192.168." },126];127128export function setupMessageHandler(): void {129  chrome.runtime.onMessage.addListener(130    (msg: unknown, sender, sendResponse) => {131      if (!isMessage(msg)) {132        sendResponse({ ok: false, error: "invalid_message" });133        return true;134      }135      handleMessage(msg, sender)136        .then(sendResponse)137        .catch((err) =>138          sendResponse({139            ok: false,140            error: err instanceof Error ? err.message : String(err),141          })142        );143      return true;144    }145  );146147  // Android: the chrome shim queues sendMessage calls until this handler is148  // registered. Without this hookup, every message hangs on Capacitor builds.149  // eslint-disable-next-line @typescript-eslint/no-explicit-any150  const reg = (globalThis as any).__peachRegisterMessageHandler;151  if (typeof reg === "function") {152    reg(async (m: unknown) => {153      if (!isMessage(m)) return { ok: false, error: "invalid_message" };154      try {155        return await handleMessage(m);156      } catch (err) {157        return {158          ok: false,159          error: err instanceof Error ? err.message : String(err),160        };161      }162    });163  }164  if (isNativePlatform()) {165    void bootstrapNativeSyncRunner();166  }167}168169async function bootstrapNativeSyncRunner(): Promise<void> {170  if (nativeSyncRunnerBootstrapped) return;171  nativeSyncRunnerBootstrapped = true;172  try {173    const { setSyncRunner, hydratePersistedSyncState } = await import("./sync-trigger");174    const { productionSyncRunner } = await import("./chirp-sync-runner");175    setSyncRunner(productionSyncRunner);176    await hydratePersistedSyncState();177  } catch (err) {178    nativeSyncRunnerBootstrapped = false;179    console.warn("[Peach] failed to bootstrap native sync runner:", err);180  }181}182183function isMessage(m: unknown): m is Message {184  return typeof m === "object" && m !== null && "type" in m;185}186187/**188 * The browser-attested origin of the page that originated this message. A web189 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),190 * so every page-driven message arrives via the content-script relay and the191 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a192 * value the page cannot forge. This is the ONLY trustworthy origin for passkey193 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.194 */195function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {196  if (sender.origin) return sender.origin;197  if (sender.url) {198    try { return new URL(sender.url).origin; } catch { return undefined; }199  }200  return undefined;201}202203export async function handleMessage(204  msg: Message,205  sender: Partial<chrome.runtime.MessageSender> = {}206): Promise<MessageResponse> {207  try {208    // Validate sender — only allow messages from our extension pages/scripts.209    // `sender.id` is undefined for messages originating from extension UI210    // (popup/options), which is legitimate; reject only when it is defined211    // and does not match our extension id.212    if (213      sender.id !== undefined &&214      sender.id !== chrome.runtime.id215    ) {216      return { ok: false, error: "invalid_sender" };217    }218219    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {220      touchAutoLock();221    }222223    switch (msg.type) {224      case "CREATE_VAULT": {225        const { password } = msg.payload as { password: string };226        // Refuse to create a vault under an empty master password — the derived227        // key would be publicly known and the at-rest AES-GCM protection void228        // (audit HIGH; the CSV-import path previously passed ""). Length/strength229        // policy lives in the onboarding UI; this is the non-negotiable floor.230        if (typeof password !== "string" || password.length === 0) {231          return { ok: false, error: "invalid_payload" };232        }233        await vault.createVault(password);234        await setupAutoLock();235        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });236        onVaultUnlocked();237        return { ok: true };238      }239      case "UNLOCK": {240        const { password } = msg.payload as { password: string };241        const ok = await vault.unlock(password);242        if (ok) {243          // KAT: verify the WebCrypto stack is healthy before the user relies on it.244          // Runs after unlock so latency is hidden behind the vault-load time.245          const kat = await runSelfTest();246          if (!kat.ok) {247            console.error("[Peach] Crypto self-test FAILED:", kat.error);248            await vault.lock();249            return { ok: false, error: "self_test_failed" };250          }251          await setupAutoLock();252          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });253          onVaultUnlocked();254          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());255          return { ok: true };256        }257        // Distinguish corruption from wrong password so the popup can offer258        // a history-restore path instead of falsely accusing the user of259        // mistyping (M7/COR-007).260        const failure = vault.consumeLastUnlockFailureReason();261        if (failure) {262          return {263            ok: false,264            error: "vault_corrupted",265            canRestoreFromHistory: true,266          } as MessageResponse;267        }268        return { ok: false };269      }270      case "VALIDATE_RECOVERY_WORDS": {271        const { words } = msg.payload as { words: string[] };272        const invalid = findInvalidWords(words);273        return { ok: true, data: { valid: invalid.length === 0, invalid } };274      }275      case "GET_RECOVERY_WORDS": {276        // Must be unlocked and have recovery set up (vault must be v2.12+).277        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };278        try {279          const words = await vault.getRecoveryWords();280          return { ok: true, data: words };281        } catch (e) {282          // pre-v2.12 vault that hasn't migrated283          return { ok: false, error: "recovery_not_setup" };284        }285      }286      case "RECOVER_WITH_WORDS": {287        // User has lost their password but has their 12 recovery words.288        // We: (1) validate the words, (2) re-encrypt vault with new password.289        const { words, newPassword } = msg.payload as {290          words: string[];291          newPassword: string;292        };293        const stored = await vault.loadSlotA();294        if (!stored) return { ok: false, error: "no_vault" };295        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {296          return { ok: false, error: "recovery_not_setup" };297        }298        // Unwrap the root key from the recovery escrow.299        try {300          await vault.unwrapRootKeyForRecovery(301            stored.recovery_wrapped_root_key,302            stored.recovery_nonce ?? "",303            stored.recovery_tag ?? "",304            stored.recovery_salt,305            words306          );307        } catch {308          return { ok: false, error: "invalid_recovery_words" };309        }310        // Re-key: derive fresh salt + key from new password.311        const newSalt = vault.generateSalt();312        const newKey = await vault.deriveKey(newPassword, newSalt);313        // Re-wrap root key under the new password's derived key so the same314        // recovery words continue to work after the password change.315        await vault.rewrapRootKeyForPassword(newKey, newSalt);316        // Re-encrypt vault entries with the new key.317        await vault.changePasswordWithNewKey(newSalt, newKey);318        await setupAutoLock();319        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });320        return { ok: true };321      }322      case "LOCK":323        vault.lock();324        if (isNativePlatform()) await clearInMemoryVault();325        return { ok: true };326      case "IS_UNLOCKED":327        return { ok: true, data: vault.isUnlocked() };328      case "GET_VAULT_STATUS":329        return { ok: true, unlocked: vault.isUnlocked() };330      case "HAS_VAULT":331        return { ok: true, data: await vault.hasVault() };332      case "GET_ENTRIES":333        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };334        return { ok: true, data: vault.getEntries() };335      case "ADD_ENTRY": {336        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };337        const payload = msg.payload;338        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {339          return { ok: false, error: "invalid_payload" };340        }341        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);342        return { ok: true, data: entry };343      }344      case "BATCH_ADD_ENTRIES": {345        const payload = msg.payload as { entries?: unknown } | null | undefined;346        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {347          return { ok: false, error: "invalid_payload" };348        }349        if (!Array.isArray(payload.entries)) {350          return { ok: false, error: "invalid_payload" };351        }352        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);353        return { ok: true, data: added };354      }355      case "RESTORE_ENTRIES": {356        const payload = msg.payload as357          | { entries?: unknown; mode?: unknown; settings?: unknown }358          | null359          | undefined;360        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {361          return { ok: false, error: "invalid_payload" };362        }363        if (!Array.isArray(payload.entries)) {364          return { ok: false, error: "invalid_payload" };365        }366        if (payload.mode !== "replace" && payload.mode !== "merge") {367          return { ok: false, error: "invalid_payload" };368        }369        const summary = await vault.restoreEntries(370          payload.entries as Parameters<typeof vault.restoreEntries>[0],371          payload.mode372        );373        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {374          await vault.updateSettings(payload.settings as vault.VaultSettings);375        }376        return { ok: true, data: summary };377      }378      case "CLEAR_VAULT_ENTRIES": {379        await vault.clearVaultEntries("REPLACE_ALL");380        return { ok: true };381      }382      case "GET_VAULT_HISTORY": {383        const snapshots = await vault.getVaultHistory();384        return { ok: true, data: snapshots };385      }386      case "RESTORE_VAULT_SNAPSHOT": {387        const { snapshotId } = msg.payload as { snapshotId: string };388        const result = await vault.restoreVaultSnapshot(snapshotId);389        if (!result.ok) return { ok: false, error: result.error };390        broadcastToContentScripts({ type: "VAULT_LOCKED" });391        return { ok: true };392      }393      case "COUNT_DUPLICATES": {394        return { ok: true, data: vault.countDuplicates() };395      }396      case "DEDUPLICATE_ENTRIES": {397        const removed = await vault.deduplicateEntries();398        return { ok: true, data: removed };399      }400      case "UPDATE_ENTRY": {401        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;402        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {403          return { ok: false, error: "invalid_payload" };404        }405        const { id, patch } = payload;406        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {407          return { ok: false, error: "invalid_payload" };408        }409        // Single enforcement point for the Canary Entries Pro gate. Only410        // gates the transition into a canary entry — clearing/disabling a411        // canary (`canary: undefined`) is always allowed, so existing412        // canary entries remain manageable.413        const incomingCanary = (patch as { canary?: unknown }).canary;414        if (incomingCanary && typeof incomingCanary === "object") {415          const existing = vault.getEntryById(id);416          if (!existing?.canary) {417            const gate = await requirePro("canary_entry");418            if (!gate.allowed) return { ok: false, error: "pro_required" };419          }420        }421        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);422        return { ok: true };423      }424      case "ADD_ADDITIONAL_URL": {425        const { id, url } = msg.payload as { id: string; url: string };426        const trimmed = typeof url === "string" ? url.trim() : "";427        if (!trimmed) return { ok: false, error: "url_required" };428        const existing = vault.getEntryById(id);429        if (!existing) return { ok: false, error: "entry_not_found" };430        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };431        const merged = [...(existing.additionalUrls ?? []), trimmed];432        await vault.updateEntry(id, { additionalUrls: merged });433        return { ok: true };434      }435      case "DELETE_ENTRY": {436        const { id } = msg.payload as { id: string };437        await vault.deleteEntry(id);438        return { ok: true };439      }440      case "GET_DELETED_ENTRIES":441        return { ok: true, data: vault.getDeletedEntries() };442      case "RESTORE_ENTRY": {443        const { id } = msg.payload as { id: string };444        await vault.restoreEntry(id);445        return { ok: true };446      }447      case "PURGE_ENTRY": {448        const { id } = msg.payload as { id: string };449        await vault.purgeEntry(id);450        return { ok: true };451      }452      case "PURGE_EXPIRED_TRASH": {453        const { retentionMs } = msg.payload as { retentionMs: number };454        const purged = await vault.purgeExpiredTrash(retentionMs);455        return { ok: true, data: purged };456      }457      case "SAVE_NOTE": {458        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };459        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };460        const now = Date.now();461        if (id) {462          const existing = vault.getEntryById(id);463          if (!existing) return { ok: false, error: "not_found" };464          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });465          return { ok: true, data: vault.getEntryById(id) };466        } else {467          const entry = await vault.addEntry({468            type: "note",469            title: title || "Untitled",470            notes: body,471            createdAt: now,472            modifiedAt: now,473          } as any);474          return { ok: true, data: entry };475        }476      }477      case "DELETE_NOTE": {478        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };479        const { id } = msg.payload as { id: string };480        await vault.deleteEntry(id);481        return { ok: true };482      }483      case "GET_NOTES": {484        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };485        const notes = vault.getEntries().filter(486          (e) => e.type === "note" && !e.deletedAt487        );488        return { ok: true, data: notes } as MessageResponse;489      }490      case "SEARCH_VAULT": {491        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };492        // AUD-002: shape-validate the payload before calling string methods.493        // A raw cast lets a malformed message crash the handler with TypeError.494        const { query } = (msg.payload ?? {}) as { query?: unknown };495        if (typeof query !== "string") {496          return { ok: false, error: "invalid_payload" };497        }498        const q = query.toLowerCase();499        const searchResults = vault.getEntries().filter(500          (e) =>501            !e.deletedAt &&502            (e.title.toLowerCase().includes(q) ||503              e.notes?.toLowerCase().includes(q) ||504              e.username?.toLowerCase().includes(q))505        );506        return { ok: true, data: searchResults } as MessageResponse;507      }508      case "AUTOFILL_QUERY": {509        if (!vault.isUnlocked()) {510          return { ok: false, error: "vault_locked" };511        }512        const { domain, includeAll, kind } = msg.payload as {513          domain: string;514          includeAll?: boolean;515          kind?: "login" | "card" | "totp";516        };517        // kind="card": return saved cards as compact summaries for the518        // inline card silver platter. Cards are not domain-scoped — every519        // saved card is a candidate on every checkout page — so domain is520        // ignored when kind === "card".521        if (kind === "card") {522          const cards = vault.getEntries().filter((e) => e.type === "card");523          return {524            ok: true,525            data: cards.map((e) => ({526              id: e.id,527              title: e.cardNickname || e.title,528              cardholderName: e.cardholderName,529              last4: e.last4,530              expMonth: e.expMonth,531              expYear: e.expYear,532              network: e.network,533            })),534          };535        }536        if (kind === "totp") {537          const matches = (538            includeAll539              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")540              : vault.queryDomain(domain)541          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));542          return {543            ok: true,544            data: matches.map((e) => ({545              id: e.id,546              title: e.title,547              username: e.username,548              email: e.email,549              url: e.url,550              hasTotp: true,551            })),552          };553        }554        // The inline selector fills username+password into a form. Passkey-555        // only entries have no password to fill; sign-in for those goes556        // through the WebAuthn path instead. Filter them out everywhere so557        // the user doesn't see four "GitHub" rows that mostly do nothing.558        // Notes and cards never belonged here either.559        const matches = (560          includeAll561            ? vault562                .getEntries()563                .filter((entry) => entry.type !== "note" && entry.type !== "card")564            : vault.queryDomain(domain)565        ).filter((entry) => !isPasskeyOnly(entry));566        return {567          ok: true,568          data: matches.map((e) =>569            includeAll570              ? {571                  id: e.id,572                  title: e.title,573                  // username/email/url shipped so the inline popup's search574                  // affordance can match on them, not just titles. No secrets575                  // cross the boundary — same shape as the domain-matched576                  // response below minus hasTotp (which the search list577                  // doesn't surface).578                  username: e.username,579                  email: e.email,580                  url: e.url,581                  hasPasskey: e.passkey !== undefined,582                }583              : {584                  id: e.id,585                  title: e.title,586                  username: e.username,587                  email: e.email,588                  url: e.url,589                  hasTotp: Boolean(e.totp),590                  hasPasskey: e.passkey !== undefined,591                }592          ),593        };594      }595      case "GET_ENTRY_FOR_FILL": {596        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };597        const { id } = msg.payload as { id: string };598        const entry = vault.getEntryById(id);599        if (!entry) return { ok: false, error: "entry_not_found" };600        // Passkey-only entries (passkey credential, no password) cannot be601        // filled into a form — sign-in goes through the WebAuthn path. A602        // login that ALSO has a passkey is still fillable for its password.603        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };604        // Strip the passkey credential AND the raw base32 TOTP seed from the605        // response. Content scripts never need either: the private key is the606        // authenticator's, and handing over the TOTP seed would let a607        // compromised content script mint valid codes indefinitely (SEV-3-C).608        // Generate the *current* 6-digit code here in the background and send609        // only that, plus the seconds left so the UI can render a countdown.610        const { passkey: _strippedPasskey, totp: seed, ...safeEntry } = entry;611        let totpCode: string | undefined;612        let totpRemaining: number | undefined;613        if (seed) {614          try {615            const generated = generateTOTP(seed);616            totpCode = generated.code;617            totpRemaining = generated.remaining;618          } catch {619            totpCode = undefined;620          }621        }622        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };623      }624      // Trusted full-entry fetch for Peach's own inline-popup surfaces that625      // genuinely need the raw TOTP seed: the edit form (which re-saves the626      // seed and would otherwise wipe it) and nothing else. Unlike627      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside628      // the inline popup, never during passive autofill on an arbitrary page.629      // The passkey credential is still stripped — the edit form never touches it.630      case "GET_ENTRY_FOR_EDIT": {631        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };632        const { id } = msg.payload as { id: string };633        const entry = vault.getEntryById(id);634        if (!entry) return { ok: false, error: "entry_not_found" };635        const { passkey: _passkey, ...safeEntry } = entry;636        return { ok: true, data: safeEntry };637      }638      case "COPY": {639        // AUD-002: shape-validate the payload before passing to the clipboard640        // helper. A raw cast lets a malformed message reach the clipboard API641        // with a non-string and throw.642        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {643          text?: unknown;644          label?: unknown;645          alreadyWritten?: unknown;646        };647        if (typeof text !== "string" || typeof label !== "string") {648          return { ok: false, error: "invalid_payload" };649        }650        await copyToClipboard(text, label, Boolean(alreadyWritten));651        return { ok: true };652      }653      case "CHECK_ALL_BREACHES": {654        const allEntries = vault.getEntries();655        const results: Record<string, number> = {};656        for (const entry of allEntries) {657          if (entry.type === "note") continue;658          if (!entry.password) continue;659          results[entry.id] = await vault.checkBreach(entry.password);660          // Small delay — be a good citizen to the HIBP API661          await new Promise((r) => setTimeout(r, 200));662        }663        // Persist any non-zero counts back to entries664        for (const [id, count] of Object.entries(results)) {665          const entry = vault.getEntryById(id);666          if (entry && (entry.breach ?? 0) !== count) {667            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });668          }669        }670        return { ok: true, data: results };671      }672      case "GET_SETTINGS":673        return { ok: true, data: await vault.ensureSettingsLoaded() };674      case "UPDATE_SETTINGS": {675        const patch = msg.payload;676        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {677          return { ok: false, error: "invalid_payload" };678        }679        await vault.updateSettings(patch as vault.VaultSettings);680        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {681          await setupAutoLock();682          if (vault.isUnlocked()) touchAutoLock();683        }684        return { ok: true };685      }686      case "GET_PENDING_PASSKEY":687        return { ok: true, data: await getPendingPasskeyRequest() };688      case "APPROVE_PASSKEY": {689        const { requestId } = msg.payload as { requestId: number };690        await resolvePendingPasskeyRequest(requestId, true);691        return { ok: true };692      }693      case "DENY_PASSKEY": {694        const { requestId } = msg.payload as { requestId: number };695        await resolvePendingPasskeyRequest(requestId, false);696        return { ok: true };697      }698      case "GET_PASSKEY_PROVIDER_STATE":699        return { ok: true, data: await getPasskeyProviderState() };700      case "SET_PASSKEY_PROVIDER_ENABLED": {701        const { enabled } = msg.payload as { enabled: boolean };702        // Disabling is always free; gating fires only when a free user is703        // trying to turn passkey interception on.704        if (enabled) {705          const gate = await requirePro("passkeys");706          if (!gate.allowed) return { ok: false, error: "pro_required" };707        }708        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };709      }710      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS711      // endpoint. Intentional product behavior — users configure their own712      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private713      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-714      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to715      // users that the entry title leaves the device when the canary fires.716      case "FIRE_CANARY_PING": {717        // Canary alert fires unconditionally for any entry with canary: true.718        // The Pro gate only governs creation/flagging of canary entries; once719        // an entry is flagged, the alert path is a security property and must720        // never be license-gated.721        const { webhookUrl, entryTitle, trigger } = msg.payload as {722          webhookUrl: string;723          entryTitle: string;724          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";725        };726        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {727          return { ok: false, error: "invalid_webhook_url" };728        }729        const body = JSON.stringify({730          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",731          entry: entryTitle,732          trigger,733          timestamp: new Date().toISOString(),734          source: "peach-extension",735        });736        if (trigger === "test") {737          // Permitted outbound fetch: user-configured canary alert endpoint738          // (validated by isAllowedCanaryWebhookUrl above). This is the739          // only non-HIBP outbound call in the extension — see740          // Projects.md §3.7. Test pings are awaited so the UI can show741          // success/failure.742          try {743            const res = await fetch(webhookUrl, {744              method: "POST",745              headers: { "Content-Type": "application/json" },746              body,747            });748            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };749          } catch (err) {750            return { ok: false, error: err instanceof Error ? err.message : "network_error" };751          }752        }753        // Non-test triggers are fire-and-forget754        fetch(webhookUrl, {755          method: "POST",756          headers: { "Content-Type": "application/json" },757          body,758        }).catch(() => {});759        return { ok: true };760      }761      case "ACTIVATE_LICENSE": {762        const { key } = msg.payload as { key: string };763        const licenseInfo = await activateLicense(key);764        return { ok: true, data: licenseInfo };765      }766      case "GET_LICENSE": {767        const licenseInfo = await getLicenseInfo();768        return { ok: true, data: licenseInfo };769      }770      case "GET_LICENSE_KEY": {771        const key = await getLicenseKey();772        return { ok: true, data: key };773      }774      case "DEACTIVATE_LICENSE": {775        await deactivateLicense();776        return { ok: true };777      }778      case "SHOULD_PLAY_CELEBRATION": {779        const should = await shouldPlayCelebration();780        return { ok: true, data: should };781      }782      case "MARK_CELEBRATION_PLAYED": {783        await markCelebrationPlayed();784        return { ok: true };785      }786      case "GET_CODEX_VAULT_DATA": {787        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the788        // popup navigates to the License section without further coordination.789        const gate = await requirePro("codex");790        if (!gate.allowed) return { ok: false, error: "pro_required" };791        return await handleGetCodexVaultData();792      }793      case "ESTIMATE_CODEX_PAGES": {794        const gate = await requirePro("codex");795        if (!gate.allowed) return { ok: false, error: "pro_required" };796        return await handleEstimateCodexPages();797      }798      case "RESTORE_FROM_CODEX": {799        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still800        // be able to restore a vault that was printed by a Pro user.801        // DO NOT add a Pro gate here.802        const payload = msg.payload as CodexRestorePayload;803        return await handleRestoreFromCodex(payload);804      }805      case "OPEN_PRO_GATE": {806        // Content script requests: open popup and navigate to License section.807        const { feature } = (msg.payload ?? {}) as { feature?: string };808        if (chrome.storage.session) {809          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });810        }811        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }812        return { ok: true };813      }814      case "GET_IDENTITIES": {815        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };816        return { ok: true, data: vault.getIdentities() };817      }818      case "TOUCH_AUTO_LOCK": {819        // touchAutoLock() is already called by shouldRefreshAutoLock above;820        // this case just gives the popup a typed message to keep the session alive.821        return { ok: true };822      }823      case "GET_ADVANCED_HEALTH_REPORT": {824        const gate = await requirePro("advanced_health");825        if (!gate.allowed) return { ok: false, error: "pro_required" };826        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };827        const report = await buildAdvancedHealthReport(vault.getEntries());828        return { ok: true, data: report };829      }830      case "IS_DURESS_ENABLED": {831        const enabled = await vault.isDuressEnabled();832        return { ok: true, data: enabled };833      }834      case "SETUP_DURESS": {835        // Single enforcement point for the Duress Vault Pro gate. Free users836        // who somehow reach this handler are rejected here; the popup also837        // pre-checks isPro() to avoid showing the setup form to free users,838        // but server-side is the actual security boundary.839        const gate = await requirePro("duress_vault");840        if (!gate.allowed) return { ok: false, error: "pro_required" };841        // MV3 service workers restart after inactivity, losing the in-memory842        // derived key. Detect this before calling setupDuress so the popup843        // can show a meaningful prompt to re-lock and re-unlock.844        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };845        const { duressPassword } = msg.payload as { duressPassword: string };846        await vault.setupDuress(duressPassword);847        return { ok: true };848      }849      case "DISABLE_DURESS": {850        await vault.disableDuress();851        return { ok: true };852      }853      case "VERIFY_MAIN_PASSWORD": {854        const { password } = msg.payload as { password: string };855        const ok = await vault.verifyMainPassword(password);856        return { ok: true, data: ok };857      }858      case "CHANGE_PASSWORD": {859        const { currentPassword, newPassword } = msg.payload as {860          currentPassword: string;861          newPassword: string;862        };863        const changed = await vault.changePassword(currentPassword, newPassword);864        return changed865          ? { ok: true }866          : { ok: false, error: "incorrect_current_password" };867      }868      case "GET_SITE_PASSWORD_POLICY": {869        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });870        if (!tab?.id) return { ok: true, data: null };871        try {872          const response = await chrome.tabs.sendMessage(tab.id, {873            type: "GET_SITE_PASSWORD_POLICY",874          });875          return (response as MessageResponse) ?? { ok: true, data: null };876        } catch {877          return { ok: true, data: null };878        }879      }880      case "RECORD_MANUAL_SUMMON": {881        const { domain } = msg.payload as { domain: string };882        const settings = vault.getSettings();883        const existing = settings.manualSummonDomains?.[domain];884        const now = Date.now();885        await vault.updateSettings({886          manualSummonDomains: {887            ...settings.manualSummonDomains,888            [domain]: {889              firstSummonedAt: existing?.firstSummonedAt ?? now,890              summonCount: (existing?.summonCount ?? 0) + 1,891              lastSummonedAt: now,892            },893          },894        });895        return { ok: true };896      }897      case "DECLINE_CARD_SAVE": {898        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };899        await vault.declineCardSaveOffer(last4, expMonth, expYear);900        return { ok: true };901      }902      case "IS_CARD_DECLINED": {903        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };904        const declined = await vault.isCardDeclined(last4, expMonth, expYear);905        return { ok: true, data: declined };906      }907      case "INITIATE_FIREFOX_PASSKEY_CREATE": {908        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {909          rpId?: string;910          rpName?: string;911          userName?: string;912          userDisplayName?: string;913        };914        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };915        return await initiateFirefoxPasskeyCreate({916          rpId,917          rpName: rpName ?? rpId,918          userName,919          userDisplayName,920        });921      }922923      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {924        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;925        if (!payload) return { ok: false, error: "missing_payload" };926        return await completeFirefoxPasskeyCreate(payload);927      }928929      case "PASSKEY_OFFER_DECLINE": {930        const { domain } = (msg.payload ?? {}) as { domain?: string };931        if (!domain) return { ok: false, error: "domain_required" };932        await recordPasskeyOfferDecline(domain);933        return { ok: true };934      }935936      case "GET_PASSKEY_OFFER_DECLINED": {937        const { domain } = (msg.payload ?? {}) as { domain?: string };938        if (!domain) return { ok: false, error: "domain_required" };939        return { ok: true, data: await isPasskeyOfferDeclined(domain) };940      }941942      case "PASSKEY_HAS_CREDENTIALS": {943        const payload = msg.payload as {944          rpId?: string;945          allowCredentials?: Array<{ id: string; type?: string }>;946        } | undefined;947        if (!payload?.rpId) return { ok: false, error: "rpid_required" };948        return await handlePasskeyHasCredentials({949          rpId: payload.rpId,950          allowCredentials: payload.allowCredentials ?? [],951        }, attestedSenderOrigin(sender));952      }953954      case "PASSKEY_CREATE": {955        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;956        if (!payload?.rpId || !payload?.userName) {957          return { ok: false, error: "rpid_and_username_required" };958        }959        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));960      }961962      case "PASSKEY_GET": {963        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;964        if (!payload?.rpId) return { ok: false, error: "rpid_required" };965        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));966      }967968      case "PASSKEY_AUTH_RESPONSE": {969        const { requestId, approved } = (msg.payload ?? {}) as {970          requestId?: string | number;971          approved?: boolean;972        };973        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {974          return { ok: false, error: 'requestId and approved required' };975        }976        await resolvePendingPasskeyRequest(Number(requestId), approved);977        return { ok: true };978      }979980      case "GET_PASSKEY_FOR_DOMAIN": {981        const { domain } = (msg.payload ?? {}) as { domain?: string };982        if (!domain) return { ok: false, error: "domain_required" };983        // Scope to the caller's own origin: a page may only ask about passkeys984        // for a domain it actually owns, so an arbitrary page cannot enumerate985        // which sites the user holds passkeys for or read the username (audit MEDIUM).986        const origin = attestedSenderOrigin(sender);987        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };988        if (!vault.isUnlocked()) return { ok: true, data: null };989        const match = vault990          .getEntries()991          .find((entry) => entry.passkey?.rpId === domain);992        if (!match || !match.passkey) return { ok: true, data: null };993        // Slim shape — only the fields State 11 needs. Never expose private994        // key material, even though this is locked behind isUnlocked.995        return {996          ok: true,997          data: {998            rpId: match.passkey.rpId,999            userName: match.passkey.userName,1000            browser: match.passkey.browser,1001          },1002        };1003      }10041005      case "DESTROY_VAULT": {1006        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1007        // storage.local.clear() wipes every Peach key (slots, settings, license,1008        // onboarded flag, history, sync state, declined cards, recall, etc.);1009        // session.clear() wipes pending passkey requests + pro-notice queues.1010        // Caller (Panic.tsx) handles UI navigation back to onboarding.1011        //1012        // The Pro license is the one thing that must survive: the user paid for1013        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1014        // Capture it before the clear and restore it after. peach_pro_celebrated1015        // rides along so the Pro celebration doesn't replay on the next unlock.1016        const preserved = await chrome.storage.local.get([1017          "peach_license",1018          "peach_pro_celebrated",1019        ]);1020        vault.lock();1021        await storageClear();1022        await vault.clearVaultHistory();1023        const toRestore: Record<string, unknown> = {};1024        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1025        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1026        if (Object.keys(toRestore).length > 0) {1027          await chrome.storage.local.set(toRestore);1028        }1029        if (chrome.storage.session) {1030          await chrome.storage.session.clear();1031        }1032        return { ok: true };1033      }10341035      case "SUBMIT_FEEDBACK": {1036        const { category, message, version, browser } = msg.payload as {1037          category: string;1038          message: string;1039          version: string;1040          browser: string;1041        };1042        if (!message.trim()) return { ok: false, error: "message_empty" };1043        if (!FEEDBACK_ENDPOINT) return { ok: true };1044        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1045          return { ok: false, error: "invalid_feedback_endpoint" };1046        }1047        try {1048          const res = await fetch(FEEDBACK_ENDPOINT, {1049            method: "POST",1050            headers: { "Content-Type": "application/json" },1051            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1052          });1053          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1054        } catch (err) {1055          return { ok: false, error: err instanceof Error ? err.message : "network_error" };1056        }1057      }1058      // Android-only: biometric unlock with pre-derived key.1059      case "UNLOCK_WITH_KEY": {1060        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1061        if (!isNativePlatform()) {1062          return { ok: false, error: "desktop_only_uses_password" };1063        }1064        try {1065          const result = await vault.unlockWithKey(masterKeyHex);1066          if (result.ok) {1067            onVaultUnlocked();1068            await publishInMemoryVault(result.entries);1069          }1070          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1071        } catch {1072          return { ok: false, error: "invalid_key" };1073        }1074      }1075      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1076      case "GET_DERIVED_KEY": {1077        if (!isNativePlatform()) {1078          return { ok: false, error: "android_only" };1079        }1080        if (!vault.isUnlocked()) {1081          return { ok: false, error: "vault_locked" };1082        }1083        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1084      }1085      case "GET_IDENTITY_SUGGESTIONS": {1086        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1087        const entries = vault.getEntries();1088        const suggestions = buildIdentitySuggestions(entries);1089        return { ok: true, data: { suggestions } };1090      }1091      case "POPULATE_INLINE_VAULT": {1092        if (!isNativePlatform()) return { ok: false };1093        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1094        const entries = vault.getEntries();1095        await publishInMemoryVault(entries);1096        return { ok: true };1097      }1098      case "ML_INIT":1099        return { ok: true };11001101      case "ML_PREDICT_BATCH": {1102        // AUD-002: shape-validate before forwarding to the ML helper.1103        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1104        if (!Array.isArray(featuresArray)) {1105          return { ok: false, error: "invalid_payload" };1106        }1107        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1108      }11091110      // ── Chirp Sync (v3) ───────────────────────────────────────────────1111      // Returns the public-facing local identity needed by the popup to1112      // drive Phase-1 audio pairing. The private long-term key never1113      // leaves the background.1114      case "CHIRP_GET_LOCAL_IDENTITY": {1115        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1116        const proCheck = await requirePro("sync");1117        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1118        // Identity derives from the stable root key, not the password-derived1119        // key, so pairing survives a master-password change (SEV-2-B).1120        const masterKeyHex = vault.getRootKeyHex();1121        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1122        const masterKey = unhexBytes(masterKeyHex);1123        try {1124          const identity = await buildLocalIdentity(masterKey);1125          return { ok: true, data: identity };1126        } finally {1127          masterKey.fill(0);1128        }1129      }11301131      case "CHIRP_COMPLETE_PAIRING": {1132        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1133        const proCheck = await requirePro("sync");1134        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1135        const paired = (msg.payload as { paired?: unknown })?.paired;1136        if (typeof paired !== "object" || paired === null) {1137          return { ok: false, error: "invalid_payload" };1138        }1139        const candidate = paired as Record<string, unknown>;1140        if (1141          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1142          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1143          typeof candidate.deviceType !== "string" ||1144          typeof candidate.longTermPublicKeyHex !== "string" ||1145          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1146          (1147            candidate.signingPublicKeyHex !== undefined &&1148            (1149              typeof candidate.signingPublicKeyHex !== "string" ||1150              !/^[0-9a-f]{64}$/.test(candidate.signingPublicKeyHex)1151            )1152          ) ||1153          typeof candidate.pairedAt !== "number"1154        ) {1155          return { ok: false, error: "invalid_paired_device" };1156        }1157        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1158        return { ok: true };1159      }11601161      case "CHIRP_LIST_PAIRED_DEVICES": {1162        const devices = await listPairedDevicesV3();1163        return { ok: true, data: { devices } };1164      }11651166      case "CHIRP_UNPAIR_DEVICE": {1167        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1168        if (typeof deviceId !== "string" || !deviceId) {1169          return { ok: false, error: "invalid_payload" };1170        }1171        await removePairedDeviceByIdV3(deviceId);1172        return { ok: true };1173      }11741175      case "CHIRP_RENAME_LOCAL_DEVICE": {1176        const { name } = (msg.payload ?? {}) as { name?: string };1177        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1178        await setDeviceNameV3(name);1179        return { ok: true };1180      }11811182      case "TRIGGER_SYNC": {1183        const payload = (msg.payload ?? {}) as {1184          reason?: "vault_change" | "foreground" | "manual" | "mdns";1185          force?: boolean;1186          deviceId?: string;1187          discoveredIp?: string;1188          discoveredPort?: number;1189        };1190        const reason = payload.reason ?? "foreground";11911192        // mDNS discovery delivers a fresh (ip, port) resolved by the native1193        // side. Update the cached address before the sync runner tries to1194        // connect — avoids a subnet probe on the very next round.1195        if (1196          reason === "mdns" &&1197          typeof payload.deviceId === "string" &&1198          typeof payload.discoveredIp === "string"1199        ) {1200          const { findPairedDeviceById, setLastKnownIp } = await import("./paired-devices");1201          const device = await findPairedDeviceById(payload.deviceId);1202          if (device?.longTermPublicKeyHex) {1203            await setLastKnownIp(device.longTermPublicKeyHex, payload.discoveredIp).catch(() => undefined);1204          }1205        }12061207        const { triggerSyncIfReachable } = await import("./sync-trigger");1208        void triggerSyncIfReachable({ reason, force: payload.force === true });1209        return { ok: true };1210      }12111212      case "GET_SYNC_STATE": {1213        const { getSyncState } = await import("./sync-trigger");1214        return { ok: true, data: getSyncState() };1215      }12161217      default:1218        return { ok: false, error: "unknown_message_type" };1219    }1220  } catch (err) {1221    return {1222      ok: false,1223      error: err instanceof Error ? err.message : "operation_failed",1224    };1225  }1226}12271228// --- Mobile platform helpers ---12291230// Android: populates the in-memory vault used by PeachAutofillService.1231async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1232  const plugin = nativePlugin<{1233    setEntries?: (args: {1234      entries: Array<{1235        id: string;1236        title: string;1237        username: string;1238        email: string;1239        password: string;1240        url: string;1241        totp: string;1242        additionalUrls: string[];1243      }>;1244    }) => Promise<void>;1245  }>("InMemoryVaultPlugin");1246  if (!plugin?.setEntries) return;1247  await plugin.setEntries({1248    entries: entries.map((e) => ({1249      id: e.id,1250      title: e.title ?? "",1251      username: e.username ?? "",1252      email: (e as VaultEntry & { email?: string }).email ?? "",1253      password: e.password ?? "",1254      url: e.url ?? "",1255      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1256      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1257    })),1258  });1259}12601261// Android: clear the autofill in-memory store on lock.1262async function clearInMemoryVault(): Promise<void> {1263  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1264  if (!plugin?.clearEntries) return;1265  await plugin.clearEntries();1266}12671268// Returns username use-counts from the vault, sorted by frequency. Each row1269// also carries the entry's email so the popup can suggest the email/username1270// pair the user has actually used together.1271function buildIdentitySuggestions(1272  entries: VaultEntry[],1273): Array<{ email: string; username: string; count: number }> {1274  const usernameCounts = new Map<string, number>();1275  const usernameEmail = new Map<string, string>();1276  for (const entry of entries) {1277    const username = entry.username ?? "";1278    const email = (entry as VaultEntry & { email?: string }).email ?? "";1279    if (!username && !email) continue;1280    const key = username || email;1281    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1282    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1283  }1284  return Array.from(usernameCounts.entries())1285    .sort((a, b) => b[1] - a[1])1286    .map(([username, count]) => ({1287      email: usernameEmail.get(username) ?? "",1288      username,1289      count,1290    }));1291}12921293/** Notify all content scripts that the vault just became available. */1294function broadcastToContentScripts(message: { type: string }): void {1295  if (!chrome.tabs?.query) return;1296  chrome.tabs.query({}, (tabs) => {1297    for (const tab of tabs) {1298      if (tab.id !== undefined) {1299        chrome.tabs.sendMessage(tab.id, message).catch(() => {1300          // Tab may not have a content script — silently ignore1301        });1302      }1303    }1304  });1305}13061307function shouldRefreshAutoLock(type: MessageType): boolean {1308  return (1309    type !== "HAS_VAULT" &&1310    type !== "IS_UNLOCKED" &&1311    type !== "GET_VAULT_STATUS" &&1312    type !== "LOCK" &&1313    type !== "UPDATE_SETTINGS" &&1314    type !== "GET_PENDING_PASSKEY" &&1315    type !== "GET_PASSKEY_PROVIDER_STATE" &&1316    type !== "DECLINE_CARD_SAVE" &&1317    type !== "IS_CARD_DECLINED" &&1318    type !== "SUBMIT_FEEDBACK"1319  );1320}13211322function isAllowedCanaryWebhookUrl(value: string): boolean {1323  try {1324    const url = new URL(value);1325    if (url.protocol !== "https:") return false;13261327    const hostname = url.hostname.toLowerCase();1328    if (1329      hostname === "localhost" ||1330      hostname.endsWith(".localhost") ||1331      isPrivateIpv4(hostname) ||1332      isPrivateIpv6(hostname)1333    ) {1334      return false;1335    }13361337    return true;1338  } catch {1339    return false;1340  }1341}13421343function isPrivateIpv4(hostname: string): boolean {1344  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1345    return true;1346  }13471348  const octets = hostname.split(".").map((part) => Number(part));1349  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1350    return false;1351  }13521353  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1354}13551356function isPrivateIpv6(hostname: string): boolean {1357  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1358  return (1359    normalized === "::1" ||1360    normalized.startsWith("fc") ||1361    normalized.startsWith("fd") ||1362    normalized.startsWith("fe80:")1363  );1364}