messages.ts

55.0 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard } 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 "OPEN_POPUP": {815        // Content script asks to open the trusted extension popup — used by the816        // inline locked bubble so the master password is entered in the popup,817        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a818        // user gesture + Chrome 127+/Firefox; on failure the user clicks the819        // toolbar icon. The badge already signals Peach needs attention.820        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }821        return { ok: true };822      }823      case "GET_IDENTITIES": {824        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };825        return { ok: true, data: vault.getIdentities() };826      }827      case "TOUCH_AUTO_LOCK": {828        // touchAutoLock() is already called by shouldRefreshAutoLock above;829        // this case just gives the popup a typed message to keep the session alive.830        return { ok: true };831      }832      case "GET_ADVANCED_HEALTH_REPORT": {833        const gate = await requirePro("advanced_health");834        if (!gate.allowed) return { ok: false, error: "pro_required" };835        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };836        const report = await buildAdvancedHealthReport(vault.getEntries());837        return { ok: true, data: report };838      }839      case "IS_DURESS_ENABLED": {840        const enabled = await vault.isDuressEnabled();841        return { ok: true, data: enabled };842      }843      case "SETUP_DURESS": {844        // Single enforcement point for the Duress Vault Pro gate. Free users845        // who somehow reach this handler are rejected here; the popup also846        // pre-checks isPro() to avoid showing the setup form to free users,847        // but server-side is the actual security boundary.848        const gate = await requirePro("duress_vault");849        if (!gate.allowed) return { ok: false, error: "pro_required" };850        // MV3 service workers restart after inactivity, losing the in-memory851        // derived key. Detect this before calling setupDuress so the popup852        // can show a meaningful prompt to re-lock and re-unlock.853        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };854        const { duressPassword } = msg.payload as { duressPassword: string };855        await vault.setupDuress(duressPassword);856        return { ok: true };857      }858      case "DISABLE_DURESS": {859        await vault.disableDuress();860        return { ok: true };861      }862      case "VERIFY_MAIN_PASSWORD": {863        const { password } = msg.payload as { password: string };864        const ok = await vault.verifyMainPassword(password);865        return { ok: true, data: ok };866      }867      case "CHANGE_PASSWORD": {868        const { currentPassword, newPassword } = msg.payload as {869          currentPassword: string;870          newPassword: string;871        };872        const changed = await vault.changePassword(currentPassword, newPassword);873        return changed874          ? { ok: true }875          : { ok: false, error: "incorrect_current_password" };876      }877      case "GET_SITE_PASSWORD_POLICY": {878        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });879        if (!tab?.id) return { ok: true, data: null };880        try {881          const response = await chrome.tabs.sendMessage(tab.id, {882            type: "GET_SITE_PASSWORD_POLICY",883          });884          return (response as MessageResponse) ?? { ok: true, data: null };885        } catch {886          return { ok: true, data: null };887        }888      }889      case "RECORD_MANUAL_SUMMON": {890        const { domain } = msg.payload as { domain: string };891        const settings = vault.getSettings();892        const existing = settings.manualSummonDomains?.[domain];893        const now = Date.now();894        await vault.updateSettings({895          manualSummonDomains: {896            ...settings.manualSummonDomains,897            [domain]: {898              firstSummonedAt: existing?.firstSummonedAt ?? now,899              summonCount: (existing?.summonCount ?? 0) + 1,900              lastSummonedAt: now,901            },902          },903        });904        return { ok: true };905      }906      case "DECLINE_CARD_SAVE": {907        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };908        await vault.declineCardSaveOffer(last4, expMonth, expYear);909        return { ok: true };910      }911      case "IS_CARD_DECLINED": {912        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };913        const declined = await vault.isCardDeclined(last4, expMonth, expYear);914        return { ok: true, data: declined };915      }916      case "INITIATE_FIREFOX_PASSKEY_CREATE": {917        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {918          rpId?: string;919          rpName?: string;920          userName?: string;921          userDisplayName?: string;922        };923        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };924        return await initiateFirefoxPasskeyCreate({925          rpId,926          rpName: rpName ?? rpId,927          userName,928          userDisplayName,929        });930      }931932      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {933        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;934        if (!payload) return { ok: false, error: "missing_payload" };935        return await completeFirefoxPasskeyCreate(payload);936      }937938      case "PASSKEY_OFFER_DECLINE": {939        const { domain } = (msg.payload ?? {}) as { domain?: string };940        if (!domain) return { ok: false, error: "domain_required" };941        await recordPasskeyOfferDecline(domain);942        return { ok: true };943      }944945      case "GET_PASSKEY_OFFER_DECLINED": {946        const { domain } = (msg.payload ?? {}) as { domain?: string };947        if (!domain) return { ok: false, error: "domain_required" };948        return { ok: true, data: await isPasskeyOfferDeclined(domain) };949      }950951      case "PASSKEY_HAS_CREDENTIALS": {952        const payload = msg.payload as {953          rpId?: string;954          allowCredentials?: Array<{ id: string; type?: string }>;955        } | undefined;956        if (!payload?.rpId) return { ok: false, error: "rpid_required" };957        return await handlePasskeyHasCredentials({958          rpId: payload.rpId,959          allowCredentials: payload.allowCredentials ?? [],960        }, attestedSenderOrigin(sender));961      }962963      case "PASSKEY_CREATE": {964        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;965        if (!payload?.rpId || !payload?.userName) {966          return { ok: false, error: "rpid_and_username_required" };967        }968        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));969      }970971      case "PASSKEY_GET": {972        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;973        if (!payload?.rpId) return { ok: false, error: "rpid_required" };974        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));975      }976977      case "PASSKEY_AUTH_RESPONSE": {978        const { requestId, approved } = (msg.payload ?? {}) as {979          requestId?: string | number;980          approved?: boolean;981        };982        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {983          return { ok: false, error: 'requestId and approved required' };984        }985        await resolvePendingPasskeyRequest(Number(requestId), approved);986        return { ok: true };987      }988989      case "GET_PASSKEY_FOR_DOMAIN": {990        const { domain } = (msg.payload ?? {}) as { domain?: string };991        if (!domain) return { ok: false, error: "domain_required" };992        // Scope to the caller's own origin: a page may only ask about passkeys993        // for a domain it actually owns, so an arbitrary page cannot enumerate994        // which sites the user holds passkeys for or read the username (audit MEDIUM).995        const origin = attestedSenderOrigin(sender);996        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };997        if (!vault.isUnlocked()) return { ok: true, data: null };998        const match = vault999          .getEntries()1000          .find((entry) => entry.passkey?.rpId === domain);1001        if (!match || !match.passkey) return { ok: true, data: null };1002        // Slim shape — only the fields State 11 needs. Never expose private1003        // key material, even though this is locked behind isUnlocked.1004        return {1005          ok: true,1006          data: {1007            rpId: match.passkey.rpId,1008            userName: match.passkey.userName,1009            browser: match.passkey.browser,1010          },1011        };1012      }10131014      case "DESTROY_VAULT": {1015        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1016        // storage.local.clear() wipes every Peach key (slots, settings, license,1017        // onboarded flag, history, sync state, declined cards, recall, etc.);1018        // session.clear() wipes pending passkey requests + pro-notice queues.1019        // Caller (Panic.tsx) handles UI navigation back to onboarding.1020        //1021        // The Pro license is the one thing that must survive: the user paid for1022        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1023        // Capture it before the clear and restore it after. peach_pro_celebrated1024        // rides along so the Pro celebration doesn't replay on the next unlock.1025        const preserved = await chrome.storage.local.get([1026          "peach_license",1027          "peach_pro_celebrated",1028        ]);1029        vault.lock();1030        await storageClear();1031        await vault.clearVaultHistory();1032        const toRestore: Record<string, unknown> = {};1033        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1034        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1035        if (Object.keys(toRestore).length > 0) {1036          await chrome.storage.local.set(toRestore);1037        }1038        if (chrome.storage.session) {1039          await chrome.storage.session.clear();1040        }1041        return { ok: true };1042      }10431044      case "SUBMIT_FEEDBACK": {1045        const { category, message, version, browser } = msg.payload as {1046          category: string;1047          message: string;1048          version: string;1049          browser: string;1050        };1051        if (!message.trim()) return { ok: false, error: "message_empty" };1052        if (!FEEDBACK_ENDPOINT) return { ok: true };1053        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1054          return { ok: false, error: "invalid_feedback_endpoint" };1055        }1056        try {1057          const res = await fetch(FEEDBACK_ENDPOINT, {1058            method: "POST",1059            headers: { "Content-Type": "application/json" },1060            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1061          });1062          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1063        } catch (err) {1064          return { ok: false, error: err instanceof Error ? err.message : "network_error" };1065        }1066      }1067      // Android-only: biometric unlock with pre-derived key.1068      case "UNLOCK_WITH_KEY": {1069        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1070        if (!isNativePlatform()) {1071          return { ok: false, error: "desktop_only_uses_password" };1072        }1073        try {1074          const result = await vault.unlockWithKey(masterKeyHex);1075          if (result.ok) {1076            onVaultUnlocked();1077            await publishInMemoryVault(result.entries);1078          }1079          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1080        } catch {1081          return { ok: false, error: "invalid_key" };1082        }1083      }1084      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1085      case "GET_DERIVED_KEY": {1086        if (!isNativePlatform()) {1087          return { ok: false, error: "android_only" };1088        }1089        if (!vault.isUnlocked()) {1090          return { ok: false, error: "vault_locked" };1091        }1092        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1093      }1094      case "GET_IDENTITY_SUGGESTIONS": {1095        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1096        const entries = vault.getEntries();1097        const suggestions = buildIdentitySuggestions(entries);1098        return { ok: true, data: { suggestions } };1099      }1100      case "POPULATE_INLINE_VAULT": {1101        if (!isNativePlatform()) return { ok: false };1102        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1103        const entries = vault.getEntries();1104        await publishInMemoryVault(entries);1105        return { ok: true };1106      }1107      case "ML_INIT":1108        return { ok: true };11091110      case "ML_PREDICT_BATCH": {1111        // AUD-002: shape-validate before forwarding to the ML helper.1112        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1113        if (!Array.isArray(featuresArray)) {1114          return { ok: false, error: "invalid_payload" };1115        }1116        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1117      }11181119      // ── Chirp Sync (v3) ───────────────────────────────────────────────1120      // Returns the public-facing local identity needed by the popup to1121      // drive Phase-1 audio pairing. The private long-term key never1122      // leaves the background.1123      case "CHIRP_GET_LOCAL_IDENTITY": {1124        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1125        const proCheck = await requirePro("sync");1126        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1127        // Identity derives from the stable root key, not the password-derived1128        // key, so pairing survives a master-password change (SEV-2-B).1129        const masterKeyHex = vault.getRootKeyHex();1130        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1131        const masterKey = unhexBytes(masterKeyHex);1132        try {1133          const identity = await buildLocalIdentity(masterKey);1134          return { ok: true, data: identity };1135        } finally {1136          masterKey.fill(0);1137        }1138      }11391140      case "CHIRP_COMPLETE_PAIRING": {1141        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1142        const proCheck = await requirePro("sync");1143        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1144        const paired = (msg.payload as { paired?: unknown })?.paired;1145        if (typeof paired !== "object" || paired === null) {1146          return { ok: false, error: "invalid_payload" };1147        }1148        const candidate = paired as Record<string, unknown>;1149        if (1150          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1151          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1152          typeof candidate.deviceType !== "string" ||1153          typeof candidate.longTermPublicKeyHex !== "string" ||1154          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1155          (1156            candidate.signingPublicKeyHex !== undefined &&1157            (1158              typeof candidate.signingPublicKeyHex !== "string" ||1159              !/^[0-9a-f]{64}$/.test(candidate.signingPublicKeyHex)1160            )1161          ) ||1162          typeof candidate.pairedAt !== "number"1163        ) {1164          return { ok: false, error: "invalid_paired_device" };1165        }1166        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1167        return { ok: true };1168      }11691170      case "CHIRP_LIST_PAIRED_DEVICES": {1171        const devices = await listPairedDevicesV3();1172        return { ok: true, data: { devices } };1173      }11741175      case "CHIRP_UNPAIR_DEVICE": {1176        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1177        if (typeof deviceId !== "string" || !deviceId) {1178          return { ok: false, error: "invalid_payload" };1179        }1180        await removePairedDeviceByIdV3(deviceId);1181        return { ok: true };1182      }11831184      case "CHIRP_RENAME_LOCAL_DEVICE": {1185        const { name } = (msg.payload ?? {}) as { name?: string };1186        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1187        await setDeviceNameV3(name);1188        return { ok: true };1189      }11901191      case "TRIGGER_SYNC": {1192        const payload = (msg.payload ?? {}) as {1193          reason?: "vault_change" | "foreground" | "manual" | "mdns";1194          force?: boolean;1195          deviceId?: string;1196          discoveredIp?: string;1197          discoveredPort?: number;1198        };1199        const reason = payload.reason ?? "foreground";12001201        // mDNS discovery delivers a fresh (ip, port) resolved by the native1202        // side. Update the cached address before the sync runner tries to1203        // connect — avoids a subnet probe on the very next round.1204        if (1205          reason === "mdns" &&1206          typeof payload.deviceId === "string" &&1207          typeof payload.discoveredIp === "string"1208        ) {1209          const { findPairedDeviceById, setLastKnownIp } = await import("./paired-devices");1210          const device = await findPairedDeviceById(payload.deviceId);1211          if (device?.longTermPublicKeyHex) {1212            await setLastKnownIp(device.longTermPublicKeyHex, payload.discoveredIp).catch(() => undefined);1213          }1214        }12151216        const { triggerSyncIfReachable } = await import("./sync-trigger");1217        void triggerSyncIfReachable({ reason, force: payload.force === true });1218        return { ok: true };1219      }12201221      case "GET_SYNC_STATE": {1222        const { getSyncState } = await import("./sync-trigger");1223        return { ok: true, data: getSyncState() };1224      }12251226      default:1227        return { ok: false, error: "unknown_message_type" };1228    }1229  } catch (err) {1230    return {1231      ok: false,1232      error: err instanceof Error ? err.message : "operation_failed",1233    };1234  }1235}12361237// --- Mobile platform helpers ---12381239// Android: populates the in-memory vault used by PeachAutofillService.1240async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1241  const plugin = nativePlugin<{1242    setEntries?: (args: {1243      entries: Array<{1244        id: string;1245        title: string;1246        username: string;1247        email: string;1248        password: string;1249        url: string;1250        totp: string;1251        additionalUrls: string[];1252      }>;1253    }) => Promise<void>;1254  }>("InMemoryVaultPlugin");1255  if (!plugin?.setEntries) return;1256  await plugin.setEntries({1257    entries: entries.map((e) => ({1258      id: e.id,1259      title: e.title ?? "",1260      username: e.username ?? "",1261      email: (e as VaultEntry & { email?: string }).email ?? "",1262      password: e.password ?? "",1263      url: e.url ?? "",1264      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1265      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1266    })),1267  });1268}12691270// Android: clear the autofill in-memory store on lock.1271async function clearInMemoryVault(): Promise<void> {1272  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1273  if (!plugin?.clearEntries) return;1274  await plugin.clearEntries();1275}12761277// Returns username use-counts from the vault, sorted by frequency. Each row1278// also carries the entry's email so the popup can suggest the email/username1279// pair the user has actually used together.1280function buildIdentitySuggestions(1281  entries: VaultEntry[],1282): Array<{ email: string; username: string; count: number }> {1283  const usernameCounts = new Map<string, number>();1284  const usernameEmail = new Map<string, string>();1285  for (const entry of entries) {1286    const username = entry.username ?? "";1287    const email = (entry as VaultEntry & { email?: string }).email ?? "";1288    if (!username && !email) continue;1289    const key = username || email;1290    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1291    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1292  }1293  return Array.from(usernameCounts.entries())1294    .sort((a, b) => b[1] - a[1])1295    .map(([username, count]) => ({1296      email: usernameEmail.get(username) ?? "",1297      username,1298      count,1299    }));1300}13011302/** Notify all content scripts that the vault just became available. */1303function broadcastToContentScripts(message: { type: string }): void {1304  if (!chrome.tabs?.query) return;1305  chrome.tabs.query({}, (tabs) => {1306    for (const tab of tabs) {1307      if (tab.id !== undefined) {1308        chrome.tabs.sendMessage(tab.id, message).catch(() => {1309          // Tab may not have a content script — silently ignore1310        });1311      }1312    }1313  });1314}13151316function shouldRefreshAutoLock(type: MessageType): boolean {1317  return (1318    type !== "HAS_VAULT" &&1319    type !== "IS_UNLOCKED" &&1320    type !== "GET_VAULT_STATUS" &&1321    type !== "LOCK" &&1322    type !== "UPDATE_SETTINGS" &&1323    type !== "GET_PENDING_PASSKEY" &&1324    type !== "GET_PASSKEY_PROVIDER_STATE" &&1325    type !== "DECLINE_CARD_SAVE" &&1326    type !== "IS_CARD_DECLINED" &&1327    type !== "SUBMIT_FEEDBACK"1328  );1329}13301331function isAllowedCanaryWebhookUrl(value: string): boolean {1332  try {1333    const url = new URL(value);1334    if (url.protocol !== "https:") return false;13351336    const hostname = url.hostname.toLowerCase();1337    if (1338      hostname === "localhost" ||1339      hostname.endsWith(".localhost") ||1340      isPrivateIpv4(hostname) ||1341      isPrivateIpv6(hostname)1342    ) {1343      return false;1344    }13451346    return true;1347  } catch {1348    return false;1349  }1350}13511352function isPrivateIpv4(hostname: string): boolean {1353  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1354    return true;1355  }13561357  const octets = hostname.split(".").map((part) => Number(part));1358  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1359    return false;1360  }13611362  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1363}13641365function isPrivateIpv6(hostname: string): boolean {1366  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1367  return (1368    normalized === "::1" ||1369    normalized.startsWith("fc") ||1370    normalized.startsWith("fd") ||1371    normalized.startsWith("fe80:")1372  );1373}