messages.ts

56.4 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}202203// Resolves once restoreFromSession() has run, so handlers see the correct204// post-restore unlock state. entry.ts registers this BEFORE the message205// handler so the onMessage listener is added synchronously at SW startup206// (MV3 requirement) while unlock-dependent handlers still wait for restore.207let restoreReady: Promise<void> = Promise.resolve();208209/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */210export function setRestoreReady(p: Promise<unknown>): void {211  restoreReady = p.then(() => undefined, () => undefined);212}213214export async function handleMessage(215  msg: Message,216  sender: Partial<chrome.runtime.MessageSender> = {}217): Promise<MessageResponse> {218  try {219    // Wait for session-restore to finish before reading any unlock/vault state.220    // On a cold SW start the popup's first message arrives while restore is221    // still in flight; without this gate IS_UNLOCKED would report locked (a222    // spurious lock screen) and the storage reads could race. The onMessage223    // listener itself is registered synchronously (entry.ts) so this gate, not224    // listener registration, is what absorbs the cold-start window.225    await restoreReady;226    // Validate sender — only allow messages from our extension pages/scripts.227    // `sender.id` is undefined for messages originating from extension UI228    // (popup/options), which is legitimate; reject only when it is defined229    // and does not match our extension id.230    if (231      sender.id !== undefined &&232      sender.id !== chrome.runtime.id233    ) {234      return { ok: false, error: "invalid_sender" };235    }236237    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {238      touchAutoLock();239    }240241    switch (msg.type) {242      case "CREATE_VAULT": {243        const { password } = msg.payload as { password: string };244        // Refuse to create a vault under an empty master password — the derived245        // key would be publicly known and the at-rest AES-GCM protection void246        // (audit HIGH; the CSV-import path previously passed ""). Length/strength247        // policy lives in the onboarding UI; this is the non-negotiable floor.248        if (typeof password !== "string" || password.length === 0) {249          return { ok: false, error: "invalid_payload" };250        }251        await vault.createVault(password);252        await setupAutoLock();253        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });254        onVaultUnlocked();255        return { ok: true };256      }257      case "UNLOCK": {258        const { password } = msg.payload as { password: string };259        const ok = await vault.unlock(password);260        if (ok) {261          // KAT: verify the WebCrypto stack is healthy before the user relies on it.262          // Runs after unlock so latency is hidden behind the vault-load time.263          const kat = await runSelfTest();264          if (!kat.ok) {265            console.error("[Peach] Crypto self-test FAILED:", kat.error);266            await vault.lock();267            return { ok: false, error: "self_test_failed" };268          }269          await setupAutoLock();270          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });271          onVaultUnlocked();272          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());273          return { ok: true };274        }275        // Distinguish corruption from wrong password so the popup can offer276        // a history-restore path instead of falsely accusing the user of277        // mistyping (M7/COR-007).278        const failure = vault.consumeLastUnlockFailureReason();279        if (failure) {280          return {281            ok: false,282            error: "vault_corrupted",283            canRestoreFromHistory: true,284          } as MessageResponse;285        }286        return { ok: false };287      }288      case "VALIDATE_RECOVERY_WORDS": {289        const { words } = msg.payload as { words: string[] };290        const invalid = findInvalidWords(words);291        return { ok: true, data: { valid: invalid.length === 0, invalid } };292      }293      case "GET_RECOVERY_WORDS": {294        // Must be unlocked and have recovery set up (vault must be v2.12+).295        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };296        try {297          const words = await vault.getRecoveryWords();298          return { ok: true, data: words };299        } catch (e) {300          // pre-v2.12 vault that hasn't migrated301          return { ok: false, error: "recovery_not_setup" };302        }303      }304      case "RECOVER_WITH_WORDS": {305        // User has lost their password but has their 12 recovery words.306        // We: (1) validate the words, (2) re-encrypt vault with new password.307        const { words, newPassword } = msg.payload as {308          words: string[];309          newPassword: string;310        };311        const stored = await vault.loadSlotA();312        if (!stored) return { ok: false, error: "no_vault" };313        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {314          return { ok: false, error: "recovery_not_setup" };315        }316        // Unwrap the root key from the recovery escrow.317        try {318          await vault.unwrapRootKeyForRecovery(319            stored.recovery_wrapped_root_key,320            stored.recovery_nonce ?? "",321            stored.recovery_tag ?? "",322            stored.recovery_salt,323            words324          );325        } catch {326          return { ok: false, error: "invalid_recovery_words" };327        }328        // Re-key: derive fresh salt + key from new password.329        const newSalt = vault.generateSalt();330        const newKey = await vault.deriveKey(newPassword, newSalt);331        // Re-wrap root key under the new password's derived key so the same332        // recovery words continue to work after the password change.333        await vault.rewrapRootKeyForPassword(newKey, newSalt);334        // Re-encrypt vault entries with the new key.335        await vault.changePasswordWithNewKey(newSalt, newKey);336        await setupAutoLock();337        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });338        return { ok: true };339      }340      case "LOCK":341        vault.lock();342        if (isNativePlatform()) await clearInMemoryVault();343        return { ok: true };344      case "IS_UNLOCKED":345        return { ok: true, data: vault.isUnlocked() };346      case "GET_VAULT_STATUS":347        return { ok: true, unlocked: vault.isUnlocked() };348      case "HAS_VAULT":349        return { ok: true, data: await vault.hasVault() };350      case "GET_ENTRIES":351        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };352        return { ok: true, data: vault.getEntries() };353      case "ADD_ENTRY": {354        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };355        const payload = msg.payload;356        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {357          return { ok: false, error: "invalid_payload" };358        }359        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);360        return { ok: true, data: entry };361      }362      case "BATCH_ADD_ENTRIES": {363        const payload = msg.payload as { entries?: unknown } | null | undefined;364        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {365          return { ok: false, error: "invalid_payload" };366        }367        if (!Array.isArray(payload.entries)) {368          return { ok: false, error: "invalid_payload" };369        }370        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);371        return { ok: true, data: added };372      }373      case "RESTORE_ENTRIES": {374        const payload = msg.payload as375          | { entries?: unknown; mode?: unknown; settings?: unknown }376          | null377          | undefined;378        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {379          return { ok: false, error: "invalid_payload" };380        }381        if (!Array.isArray(payload.entries)) {382          return { ok: false, error: "invalid_payload" };383        }384        if (payload.mode !== "replace" && payload.mode !== "merge") {385          return { ok: false, error: "invalid_payload" };386        }387        const summary = await vault.restoreEntries(388          payload.entries as Parameters<typeof vault.restoreEntries>[0],389          payload.mode390        );391        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {392          await vault.updateSettings(payload.settings as vault.VaultSettings);393        }394        return { ok: true, data: summary };395      }396      case "CLEAR_VAULT_ENTRIES": {397        await vault.clearVaultEntries("REPLACE_ALL");398        return { ok: true };399      }400      case "GET_VAULT_HISTORY": {401        const snapshots = await vault.getVaultHistory();402        return { ok: true, data: snapshots };403      }404      case "RESTORE_VAULT_SNAPSHOT": {405        const { snapshotId } = msg.payload as { snapshotId: string };406        const result = await vault.restoreVaultSnapshot(snapshotId);407        if (!result.ok) return { ok: false, error: result.error };408        broadcastToContentScripts({ type: "VAULT_LOCKED" });409        return { ok: true };410      }411      case "COUNT_DUPLICATES": {412        return { ok: true, data: vault.countDuplicates() };413      }414      case "DEDUPLICATE_ENTRIES": {415        const removed = await vault.deduplicateEntries();416        return { ok: true, data: removed };417      }418      case "UPDATE_ENTRY": {419        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;420        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {421          return { ok: false, error: "invalid_payload" };422        }423        const { id, patch } = payload;424        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {425          return { ok: false, error: "invalid_payload" };426        }427        // Single enforcement point for the Canary Entries Pro gate. Only428        // gates the transition into a canary entry — clearing/disabling a429        // canary (`canary: undefined`) is always allowed, so existing430        // canary entries remain manageable.431        const incomingCanary = (patch as { canary?: unknown }).canary;432        if (incomingCanary && typeof incomingCanary === "object") {433          const existing = vault.getEntryById(id);434          if (!existing?.canary) {435            const gate = await requirePro("canary_entry");436            if (!gate.allowed) return { ok: false, error: "pro_required" };437          }438        }439        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);440        return { ok: true };441      }442      case "ADD_ADDITIONAL_URL": {443        const { id, url } = msg.payload as { id: string; url: string };444        const trimmed = typeof url === "string" ? url.trim() : "";445        if (!trimmed) return { ok: false, error: "url_required" };446        const existing = vault.getEntryById(id);447        if (!existing) return { ok: false, error: "entry_not_found" };448        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };449        const merged = [...(existing.additionalUrls ?? []), trimmed];450        await vault.updateEntry(id, { additionalUrls: merged });451        return { ok: true };452      }453      case "DELETE_ENTRY": {454        const { id } = msg.payload as { id: string };455        await vault.deleteEntry(id);456        return { ok: true };457      }458      case "GET_DELETED_ENTRIES":459        return { ok: true, data: vault.getDeletedEntries() };460      case "RESTORE_ENTRY": {461        const { id } = msg.payload as { id: string };462        await vault.restoreEntry(id);463        return { ok: true };464      }465      case "PURGE_ENTRY": {466        const { id } = msg.payload as { id: string };467        await vault.purgeEntry(id);468        return { ok: true };469      }470      case "PURGE_EXPIRED_TRASH": {471        const { retentionMs } = msg.payload as { retentionMs: number };472        const purged = await vault.purgeExpiredTrash(retentionMs);473        return { ok: true, data: purged };474      }475      case "SAVE_NOTE": {476        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };477        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };478        const now = Date.now();479        if (id) {480          const existing = vault.getEntryById(id);481          if (!existing) return { ok: false, error: "not_found" };482          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });483          return { ok: true, data: vault.getEntryById(id) };484        } else {485          const entry = await vault.addEntry({486            type: "note",487            title: title || "Untitled",488            notes: body,489            createdAt: now,490            modifiedAt: now,491          } as any);492          return { ok: true, data: entry };493        }494      }495      case "DELETE_NOTE": {496        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };497        const { id } = msg.payload as { id: string };498        await vault.deleteEntry(id);499        return { ok: true };500      }501      case "GET_NOTES": {502        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };503        const notes = vault.getEntries().filter(504          (e) => e.type === "note" && !e.deletedAt505        );506        return { ok: true, data: notes } as MessageResponse;507      }508      case "SEARCH_VAULT": {509        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };510        // AUD-002: shape-validate the payload before calling string methods.511        // A raw cast lets a malformed message crash the handler with TypeError.512        const { query } = (msg.payload ?? {}) as { query?: unknown };513        if (typeof query !== "string") {514          return { ok: false, error: "invalid_payload" };515        }516        const q = query.toLowerCase();517        const searchResults = vault.getEntries().filter(518          (e) =>519            !e.deletedAt &&520            (e.title.toLowerCase().includes(q) ||521              e.notes?.toLowerCase().includes(q) ||522              e.username?.toLowerCase().includes(q))523        );524        return { ok: true, data: searchResults } as MessageResponse;525      }526      case "AUTOFILL_QUERY": {527        if (!vault.isUnlocked()) {528          return { ok: false, error: "vault_locked" };529        }530        const { domain, includeAll, kind } = msg.payload as {531          domain: string;532          includeAll?: boolean;533          kind?: "login" | "card" | "totp";534        };535        // kind="card": return saved cards as compact summaries for the536        // inline card silver platter. Cards are not domain-scoped — every537        // saved card is a candidate on every checkout page — so domain is538        // ignored when kind === "card".539        if (kind === "card") {540          const cards = vault.getEntries().filter((e) => e.type === "card");541          return {542            ok: true,543            data: cards.map((e) => ({544              id: e.id,545              title: e.cardNickname || e.title,546              cardholderName: e.cardholderName,547              last4: e.last4,548              expMonth: e.expMonth,549              expYear: e.expYear,550              network: e.network,551            })),552          };553        }554        if (kind === "totp") {555          const matches = (556            includeAll557              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")558              : vault.queryDomain(domain)559          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));560          return {561            ok: true,562            data: matches.map((e) => ({563              id: e.id,564              title: e.title,565              username: e.username,566              email: e.email,567              url: e.url,568              hasTotp: true,569            })),570          };571        }572        // The inline selector fills username+password into a form. Passkey-573        // only entries have no password to fill; sign-in for those goes574        // through the WebAuthn path instead. Filter them out everywhere so575        // the user doesn't see four "GitHub" rows that mostly do nothing.576        // Notes and cards never belonged here either.577        const matches = (578          includeAll579            ? vault580                .getEntries()581                .filter((entry) => entry.type !== "note" && entry.type !== "card")582            : vault.queryDomain(domain)583        ).filter((entry) => !isPasskeyOnly(entry));584        return {585          ok: true,586          data: matches.map((e) =>587            includeAll588              ? {589                  id: e.id,590                  title: e.title,591                  // username/email/url shipped so the inline popup's search592                  // affordance can match on them, not just titles. No secrets593                  // cross the boundary — same shape as the domain-matched594                  // response below minus hasTotp (which the search list595                  // doesn't surface).596                  username: e.username,597                  email: e.email,598                  url: e.url,599                  hasPasskey: e.passkey !== undefined,600                }601              : {602                  id: e.id,603                  title: e.title,604                  username: e.username,605                  email: e.email,606                  url: e.url,607                  hasTotp: Boolean(e.totp),608                  hasPasskey: e.passkey !== undefined,609                }610          ),611        };612      }613      case "GET_ENTRY_FOR_FILL": {614        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };615        const { id } = msg.payload as { id: string };616        const entry = vault.getEntryById(id);617        if (!entry) return { ok: false, error: "entry_not_found" };618        // Passkey-only entries (passkey credential, no password) cannot be619        // filled into a form — sign-in goes through the WebAuthn path. A620        // login that ALSO has a passkey is still fillable for its password.621        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };622        // Strip the passkey credential AND the raw base32 TOTP seed from the623        // response. Content scripts never need either: the private key is the624        // authenticator's, and handing over the TOTP seed would let a625        // compromised content script mint valid codes indefinitely (SEV-3-C).626        // Generate the *current* 6-digit code here in the background and send627        // only that, plus the seconds left so the UI can render a countdown.628        const { passkey: _strippedPasskey, totp: seed, ...safeEntry } = entry;629        let totpCode: string | undefined;630        let totpRemaining: number | undefined;631        if (seed) {632          try {633            const generated = generateTOTP(seed);634            totpCode = generated.code;635            totpRemaining = generated.remaining;636          } catch {637            totpCode = undefined;638          }639        }640        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };641      }642      // Trusted full-entry fetch for Peach's own inline-popup surfaces that643      // genuinely need the raw TOTP seed: the edit form (which re-saves the644      // seed and would otherwise wipe it) and nothing else. Unlike645      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside646      // the inline popup, never during passive autofill on an arbitrary page.647      // The passkey credential is still stripped — the edit form never touches it.648      case "GET_ENTRY_FOR_EDIT": {649        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };650        const { id } = msg.payload as { id: string };651        const entry = vault.getEntryById(id);652        if (!entry) return { ok: false, error: "entry_not_found" };653        const { passkey: _passkey, ...safeEntry } = entry;654        return { ok: true, data: safeEntry };655      }656      case "COPY": {657        // AUD-002: shape-validate the payload before passing to the clipboard658        // helper. A raw cast lets a malformed message reach the clipboard API659        // with a non-string and throw.660        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {661          text?: unknown;662          label?: unknown;663          alreadyWritten?: unknown;664        };665        if (typeof text !== "string" || typeof label !== "string") {666          return { ok: false, error: "invalid_payload" };667        }668        await copyToClipboard(text, label, Boolean(alreadyWritten));669        return { ok: true };670      }671      case "CHECK_ALL_BREACHES": {672        const allEntries = vault.getEntries();673        const results: Record<string, number> = {};674        for (const entry of allEntries) {675          if (entry.type === "note") continue;676          if (!entry.password) continue;677          results[entry.id] = await vault.checkBreach(entry.password);678          // Small delay — be a good citizen to the HIBP API679          await new Promise((r) => setTimeout(r, 200));680        }681        // Persist any non-zero counts back to entries682        for (const [id, count] of Object.entries(results)) {683          const entry = vault.getEntryById(id);684          if (entry && (entry.breach ?? 0) !== count) {685            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });686          }687        }688        return { ok: true, data: results };689      }690      case "GET_SETTINGS":691        return { ok: true, data: await vault.ensureSettingsLoaded() };692      case "UPDATE_SETTINGS": {693        const patch = msg.payload;694        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {695          return { ok: false, error: "invalid_payload" };696        }697        await vault.updateSettings(patch as vault.VaultSettings);698        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {699          await setupAutoLock();700          if (vault.isUnlocked()) touchAutoLock();701        }702        return { ok: true };703      }704      case "GET_PENDING_PASSKEY":705        return { ok: true, data: await getPendingPasskeyRequest() };706      case "APPROVE_PASSKEY": {707        const { requestId } = msg.payload as { requestId: number };708        await resolvePendingPasskeyRequest(requestId, true);709        return { ok: true };710      }711      case "DENY_PASSKEY": {712        const { requestId } = msg.payload as { requestId: number };713        await resolvePendingPasskeyRequest(requestId, false);714        return { ok: true };715      }716      case "GET_PASSKEY_PROVIDER_STATE":717        return { ok: true, data: await getPasskeyProviderState() };718      case "SET_PASSKEY_PROVIDER_ENABLED": {719        const { enabled } = msg.payload as { enabled: boolean };720        // Disabling is always free; gating fires only when a free user is721        // trying to turn passkey interception on.722        if (enabled) {723          const gate = await requirePro("passkeys");724          if (!gate.allowed) return { ok: false, error: "pro_required" };725        }726        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };727      }728      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS729      // endpoint. Intentional product behavior — users configure their own730      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private731      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-732      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to733      // users that the entry title leaves the device when the canary fires.734      case "FIRE_CANARY_PING": {735        // Canary alert fires unconditionally for any entry with canary: true.736        // The Pro gate only governs creation/flagging of canary entries; once737        // an entry is flagged, the alert path is a security property and must738        // never be license-gated.739        const { webhookUrl, entryTitle, trigger } = msg.payload as {740          webhookUrl: string;741          entryTitle: string;742          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";743        };744        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {745          return { ok: false, error: "invalid_webhook_url" };746        }747        const body = JSON.stringify({748          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",749          entry: entryTitle,750          trigger,751          timestamp: new Date().toISOString(),752          source: "peach-extension",753        });754        if (trigger === "test") {755          // Permitted outbound fetch: user-configured canary alert endpoint756          // (validated by isAllowedCanaryWebhookUrl above). This is the757          // only non-HIBP outbound call in the extension — see758          // Projects.md §3.7. Test pings are awaited so the UI can show759          // success/failure.760          try {761            const res = await fetch(webhookUrl, {762              method: "POST",763              headers: { "Content-Type": "application/json" },764              body,765            });766            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };767          } catch (err) {768            return { ok: false, error: err instanceof Error ? err.message : "network_error" };769          }770        }771        // Non-test triggers are fire-and-forget772        fetch(webhookUrl, {773          method: "POST",774          headers: { "Content-Type": "application/json" },775          body,776        }).catch(() => {});777        return { ok: true };778      }779      case "ACTIVATE_LICENSE": {780        const { key } = msg.payload as { key: string };781        const licenseInfo = await activateLicense(key);782        return { ok: true, data: licenseInfo };783      }784      case "GET_LICENSE": {785        const licenseInfo = await getLicenseInfo();786        return { ok: true, data: licenseInfo };787      }788      case "GET_LICENSE_KEY": {789        const key = await getLicenseKey();790        return { ok: true, data: key };791      }792      case "DEACTIVATE_LICENSE": {793        await deactivateLicense();794        return { ok: true };795      }796      case "SHOULD_PLAY_CELEBRATION": {797        const should = await shouldPlayCelebration();798        return { ok: true, data: should };799      }800      case "MARK_CELEBRATION_PLAYED": {801        await markCelebrationPlayed();802        return { ok: true };803      }804      case "GET_CODEX_VAULT_DATA": {805        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the806        // popup navigates to the License section without further coordination.807        const gate = await requirePro("codex");808        if (!gate.allowed) return { ok: false, error: "pro_required" };809        return await handleGetCodexVaultData();810      }811      case "ESTIMATE_CODEX_PAGES": {812        const gate = await requirePro("codex");813        if (!gate.allowed) return { ok: false, error: "pro_required" };814        return await handleEstimateCodexPages();815      }816      case "RESTORE_FROM_CODEX": {817        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still818        // be able to restore a vault that was printed by a Pro user.819        // DO NOT add a Pro gate here.820        const payload = msg.payload as CodexRestorePayload;821        return await handleRestoreFromCodex(payload);822      }823      case "OPEN_PRO_GATE": {824        // Content script requests: open popup and navigate to License section.825        const { feature } = (msg.payload ?? {}) as { feature?: string };826        if (chrome.storage.session) {827          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });828        }829        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }830        return { ok: true };831      }832      case "OPEN_POPUP": {833        // Content script asks to open the trusted extension popup — used by the834        // inline locked bubble so the master password is entered in the popup,835        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a836        // user gesture + Chrome 127+/Firefox; on failure the user clicks the837        // toolbar icon. The badge already signals Peach needs attention.838        //839        // Set a session flag so the popup knows it was opened for inline unlock840        // and should close itself once the vault is unlocked (returning the user841        // to the inline autofill selector on the page).842        if (chrome.storage.session) {843          await chrome.storage.session.set({ peach_inline_unlock: true });844        }845        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }846        return { ok: true };847      }848      case "GET_IDENTITIES": {849        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };850        return { ok: true, data: vault.getIdentities() };851      }852      case "TOUCH_AUTO_LOCK": {853        // touchAutoLock() is already called by shouldRefreshAutoLock above;854        // this case just gives the popup a typed message to keep the session alive.855        return { ok: true };856      }857      case "GET_ADVANCED_HEALTH_REPORT": {858        const gate = await requirePro("advanced_health");859        if (!gate.allowed) return { ok: false, error: "pro_required" };860        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };861        const report = await buildAdvancedHealthReport(vault.getEntries());862        return { ok: true, data: report };863      }864      case "IS_DURESS_ENABLED": {865        const enabled = await vault.isDuressEnabled();866        return { ok: true, data: enabled };867      }868      case "SETUP_DURESS": {869        // Single enforcement point for the Duress Vault Pro gate. Free users870        // who somehow reach this handler are rejected here; the popup also871        // pre-checks isPro() to avoid showing the setup form to free users,872        // but server-side is the actual security boundary.873        const gate = await requirePro("duress_vault");874        if (!gate.allowed) return { ok: false, error: "pro_required" };875        // MV3 service workers restart after inactivity, losing the in-memory876        // derived key. Detect this before calling setupDuress so the popup877        // can show a meaningful prompt to re-lock and re-unlock.878        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };879        const { duressPassword } = msg.payload as { duressPassword: string };880        await vault.setupDuress(duressPassword);881        return { ok: true };882      }883      case "DISABLE_DURESS": {884        await vault.disableDuress();885        return { ok: true };886      }887      case "VERIFY_MAIN_PASSWORD": {888        const { password } = msg.payload as { password: string };889        const ok = await vault.verifyMainPassword(password);890        return { ok: true, data: ok };891      }892      case "CHANGE_PASSWORD": {893        const { currentPassword, newPassword } = msg.payload as {894          currentPassword: string;895          newPassword: string;896        };897        const changed = await vault.changePassword(currentPassword, newPassword);898        return changed899          ? { ok: true }900          : { ok: false, error: "incorrect_current_password" };901      }902      case "GET_SITE_PASSWORD_POLICY": {903        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });904        if (!tab?.id) return { ok: true, data: null };905        try {906          const response = await chrome.tabs.sendMessage(tab.id, {907            type: "GET_SITE_PASSWORD_POLICY",908          });909          return (response as MessageResponse) ?? { ok: true, data: null };910        } catch {911          return { ok: true, data: null };912        }913      }914      case "RECORD_MANUAL_SUMMON": {915        const { domain } = msg.payload as { domain: string };916        const settings = vault.getSettings();917        const existing = settings.manualSummonDomains?.[domain];918        const now = Date.now();919        await vault.updateSettings({920          manualSummonDomains: {921            ...settings.manualSummonDomains,922            [domain]: {923              firstSummonedAt: existing?.firstSummonedAt ?? now,924              summonCount: (existing?.summonCount ?? 0) + 1,925              lastSummonedAt: now,926            },927          },928        });929        return { ok: true };930      }931      case "DECLINE_CARD_SAVE": {932        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };933        await vault.declineCardSaveOffer(last4, expMonth, expYear);934        return { ok: true };935      }936      case "IS_CARD_DECLINED": {937        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };938        const declined = await vault.isCardDeclined(last4, expMonth, expYear);939        return { ok: true, data: declined };940      }941      case "INITIATE_FIREFOX_PASSKEY_CREATE": {942        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {943          rpId?: string;944          rpName?: string;945          userName?: string;946          userDisplayName?: string;947        };948        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };949        return await initiateFirefoxPasskeyCreate({950          rpId,951          rpName: rpName ?? rpId,952          userName,953          userDisplayName,954        });955      }956957      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {958        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;959        if (!payload) return { ok: false, error: "missing_payload" };960        return await completeFirefoxPasskeyCreate(payload);961      }962963      case "PASSKEY_OFFER_DECLINE": {964        const { domain } = (msg.payload ?? {}) as { domain?: string };965        if (!domain) return { ok: false, error: "domain_required" };966        await recordPasskeyOfferDecline(domain);967        return { ok: true };968      }969970      case "GET_PASSKEY_OFFER_DECLINED": {971        const { domain } = (msg.payload ?? {}) as { domain?: string };972        if (!domain) return { ok: false, error: "domain_required" };973        return { ok: true, data: await isPasskeyOfferDeclined(domain) };974      }975976      case "PASSKEY_HAS_CREDENTIALS": {977        const payload = msg.payload as {978          rpId?: string;979          allowCredentials?: Array<{ id: string; type?: string }>;980        } | undefined;981        if (!payload?.rpId) return { ok: false, error: "rpid_required" };982        return await handlePasskeyHasCredentials({983          rpId: payload.rpId,984          allowCredentials: payload.allowCredentials ?? [],985        }, attestedSenderOrigin(sender));986      }987988      case "PASSKEY_CREATE": {989        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;990        if (!payload?.rpId || !payload?.userName) {991          return { ok: false, error: "rpid_and_username_required" };992        }993        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));994      }995996      case "PASSKEY_GET": {997        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;998        if (!payload?.rpId) return { ok: false, error: "rpid_required" };999        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1000      }10011002      case "PASSKEY_AUTH_RESPONSE": {1003        const { requestId, approved } = (msg.payload ?? {}) as {1004          requestId?: string | number;1005          approved?: boolean;1006        };1007        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1008          return { ok: false, error: 'requestId and approved required' };1009        }1010        await resolvePendingPasskeyRequest(Number(requestId), approved);1011        return { ok: true };1012      }10131014      case "GET_PASSKEY_FOR_DOMAIN": {1015        const { domain } = (msg.payload ?? {}) as { domain?: string };1016        if (!domain) return { ok: false, error: "domain_required" };1017        // Scope to the caller's own origin: a page may only ask about passkeys1018        // for a domain it actually owns, so an arbitrary page cannot enumerate1019        // which sites the user holds passkeys for or read the username (audit MEDIUM).1020        const origin = attestedSenderOrigin(sender);1021        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1022        if (!vault.isUnlocked()) return { ok: true, data: null };1023        const match = vault1024          .getEntries()1025          .find((entry) => entry.passkey?.rpId === domain);1026        if (!match || !match.passkey) return { ok: true, data: null };1027        // Slim shape — only the fields State 11 needs. Never expose private1028        // key material, even though this is locked behind isUnlocked.1029        return {1030          ok: true,1031          data: {1032            rpId: match.passkey.rpId,1033            userName: match.passkey.userName,1034            browser: match.passkey.browser,1035          },1036        };1037      }10381039      case "DESTROY_VAULT": {1040        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1041        // storage.local.clear() wipes every Peach key (slots, settings, license,1042        // onboarded flag, history, sync state, declined cards, recall, etc.);1043        // session.clear() wipes pending passkey requests + pro-notice queues.1044        // Caller (Panic.tsx) handles UI navigation back to onboarding.1045        //1046        // The Pro license is the one thing that must survive: the user paid for1047        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1048        // Capture it before the clear and restore it after. peach_pro_celebrated1049        // rides along so the Pro celebration doesn't replay on the next unlock.1050        const preserved = await chrome.storage.local.get([1051          "peach_license",1052          "peach_pro_celebrated",1053        ]);1054        vault.lock();1055        await storageClear();1056        await vault.clearVaultHistory();1057        const toRestore: Record<string, unknown> = {};1058        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1059        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1060        if (Object.keys(toRestore).length > 0) {1061          await chrome.storage.local.set(toRestore);1062        }1063        if (chrome.storage.session) {1064          await chrome.storage.session.clear();1065        }1066        return { ok: true };1067      }10681069      case "SUBMIT_FEEDBACK": {1070        const { category, message, version, browser } = msg.payload as {1071          category: string;1072          message: string;1073          version: string;1074          browser: string;1075        };1076        if (!message.trim()) return { ok: false, error: "message_empty" };1077        if (!FEEDBACK_ENDPOINT) return { ok: true };1078        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1079          return { ok: false, error: "invalid_feedback_endpoint" };1080        }1081        try {1082          const res = await fetch(FEEDBACK_ENDPOINT, {1083            method: "POST",1084            headers: { "Content-Type": "application/json" },1085            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1086          });1087          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1088        } catch (err) {1089          return { ok: false, error: err instanceof Error ? err.message : "network_error" };1090        }1091      }1092      // Android-only: biometric unlock with pre-derived key.1093      case "UNLOCK_WITH_KEY": {1094        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1095        if (!isNativePlatform()) {1096          return { ok: false, error: "desktop_only_uses_password" };1097        }1098        try {1099          const result = await vault.unlockWithKey(masterKeyHex);1100          if (result.ok) {1101            onVaultUnlocked();1102            await publishInMemoryVault(result.entries);1103          }1104          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1105        } catch {1106          return { ok: false, error: "invalid_key" };1107        }1108      }1109      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1110      case "GET_DERIVED_KEY": {1111        if (!isNativePlatform()) {1112          return { ok: false, error: "android_only" };1113        }1114        if (!vault.isUnlocked()) {1115          return { ok: false, error: "vault_locked" };1116        }1117        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1118      }1119      case "GET_IDENTITY_SUGGESTIONS": {1120        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1121        const entries = vault.getEntries();1122        const suggestions = buildIdentitySuggestions(entries);1123        return { ok: true, data: { suggestions } };1124      }1125      case "POPULATE_INLINE_VAULT": {1126        if (!isNativePlatform()) return { ok: false };1127        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1128        const entries = vault.getEntries();1129        await publishInMemoryVault(entries);1130        return { ok: true };1131      }1132      case "ML_INIT":1133        return { ok: true };11341135      case "ML_PREDICT_BATCH": {1136        // AUD-002: shape-validate before forwarding to the ML helper.1137        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1138        if (!Array.isArray(featuresArray)) {1139          return { ok: false, error: "invalid_payload" };1140        }1141        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1142      }11431144      // ── Chirp Sync (v3) ───────────────────────────────────────────────1145      // Returns the public-facing local identity needed by the popup to1146      // drive Phase-1 audio pairing. The private long-term key never1147      // leaves the background.1148      case "CHIRP_GET_LOCAL_IDENTITY": {1149        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1150        const proCheck = await requirePro("sync");1151        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1152        // Identity derives from the stable root key, not the password-derived1153        // key, so pairing survives a master-password change (SEV-2-B).1154        const masterKeyHex = vault.getRootKeyHex();1155        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1156        const masterKey = unhexBytes(masterKeyHex);1157        try {1158          const identity = await buildLocalIdentity(masterKey);1159          return { ok: true, data: identity };1160        } finally {1161          masterKey.fill(0);1162        }1163      }11641165      case "CHIRP_COMPLETE_PAIRING": {1166        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1167        const proCheck = await requirePro("sync");1168        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1169        const paired = (msg.payload as { paired?: unknown })?.paired;1170        if (typeof paired !== "object" || paired === null) {1171          return { ok: false, error: "invalid_payload" };1172        }1173        const candidate = paired as Record<string, unknown>;1174        if (1175          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1176          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1177          typeof candidate.deviceType !== "string" ||1178          typeof candidate.longTermPublicKeyHex !== "string" ||1179          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1180          (1181            candidate.signingPublicKeyHex !== undefined &&1182            (1183              typeof candidate.signingPublicKeyHex !== "string" ||1184              !/^[0-9a-f]{64}$/.test(candidate.signingPublicKeyHex)1185            )1186          ) ||1187          typeof candidate.pairedAt !== "number"1188        ) {1189          return { ok: false, error: "invalid_paired_device" };1190        }1191        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1192        return { ok: true };1193      }11941195      case "CHIRP_LIST_PAIRED_DEVICES": {1196        const devices = await listPairedDevicesV3();1197        return { ok: true, data: { devices } };1198      }11991200      case "CHIRP_UNPAIR_DEVICE": {1201        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1202        if (typeof deviceId !== "string" || !deviceId) {1203          return { ok: false, error: "invalid_payload" };1204        }1205        await removePairedDeviceByIdV3(deviceId);1206        return { ok: true };1207      }12081209      case "CHIRP_RENAME_LOCAL_DEVICE": {1210        const { name } = (msg.payload ?? {}) as { name?: string };1211        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1212        await setDeviceNameV3(name);1213        return { ok: true };1214      }12151216      case "TRIGGER_SYNC": {1217        const payload = (msg.payload ?? {}) as {1218          reason?: "vault_change" | "foreground" | "manual" | "mdns";1219          force?: boolean;1220          deviceId?: string;1221          discoveredIp?: string;1222          discoveredPort?: number;1223        };1224        const reason = payload.reason ?? "foreground";12251226        // mDNS discovery delivers a fresh (ip, port) resolved by the native1227        // side. Update the cached address before the sync runner tries to1228        // connect — avoids a subnet probe on the very next round.1229        if (1230          reason === "mdns" &&1231          typeof payload.deviceId === "string" &&1232          typeof payload.discoveredIp === "string"1233        ) {1234          const { findPairedDeviceById, setLastKnownIp } = await import("./paired-devices");1235          const device = await findPairedDeviceById(payload.deviceId);1236          if (device?.longTermPublicKeyHex) {1237            await setLastKnownIp(device.longTermPublicKeyHex, payload.discoveredIp).catch(() => undefined);1238          }1239        }12401241        const { triggerSyncIfReachable } = await import("./sync-trigger");1242        void triggerSyncIfReachable({ reason, force: payload.force === true });1243        return { ok: true };1244      }12451246      case "GET_SYNC_STATE": {1247        const { getSyncState } = await import("./sync-trigger");1248        return { ok: true, data: getSyncState() };1249      }12501251      default:1252        return { ok: false, error: "unknown_message_type" };1253    }1254  } catch (err) {1255    return {1256      ok: false,1257      error: err instanceof Error ? err.message : "operation_failed",1258    };1259  }1260}12611262// --- Mobile platform helpers ---12631264// Android: populates the in-memory vault used by PeachAutofillService.1265async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1266  const plugin = nativePlugin<{1267    setEntries?: (args: {1268      entries: Array<{1269        id: string;1270        title: string;1271        username: string;1272        email: string;1273        password: string;1274        url: string;1275        totp: string;1276        additionalUrls: string[];1277      }>;1278    }) => Promise<void>;1279  }>("InMemoryVaultPlugin");1280  if (!plugin?.setEntries) return;1281  await plugin.setEntries({1282    entries: entries.map((e) => ({1283      id: e.id,1284      title: e.title ?? "",1285      username: e.username ?? "",1286      email: (e as VaultEntry & { email?: string }).email ?? "",1287      password: e.password ?? "",1288      url: e.url ?? "",1289      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1290      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1291    })),1292  });1293}12941295// Android: clear the autofill in-memory store on lock.1296async function clearInMemoryVault(): Promise<void> {1297  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1298  if (!plugin?.clearEntries) return;1299  await plugin.clearEntries();1300}13011302// Returns username use-counts from the vault, sorted by frequency. Each row1303// also carries the entry's email so the popup can suggest the email/username1304// pair the user has actually used together.1305function buildIdentitySuggestions(1306  entries: VaultEntry[],1307): Array<{ email: string; username: string; count: number }> {1308  const usernameCounts = new Map<string, number>();1309  const usernameEmail = new Map<string, string>();1310  for (const entry of entries) {1311    const username = entry.username ?? "";1312    const email = (entry as VaultEntry & { email?: string }).email ?? "";1313    if (!username && !email) continue;1314    const key = username || email;1315    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1316    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1317  }1318  return Array.from(usernameCounts.entries())1319    .sort((a, b) => b[1] - a[1])1320    .map(([username, count]) => ({1321      email: usernameEmail.get(username) ?? "",1322      username,1323      count,1324    }));1325}13261327/** Notify all content scripts that the vault just became available. */1328function broadcastToContentScripts(message: { type: string }): void {1329  if (!chrome.tabs?.query) return;1330  chrome.tabs.query({}, (tabs) => {1331    for (const tab of tabs) {1332      if (tab.id !== undefined) {1333        chrome.tabs.sendMessage(tab.id, message).catch(() => {1334          // Tab may not have a content script — silently ignore1335        });1336      }1337    }1338  });1339}13401341function shouldRefreshAutoLock(type: MessageType): boolean {1342  return (1343    type !== "HAS_VAULT" &&1344    type !== "IS_UNLOCKED" &&1345    type !== "GET_VAULT_STATUS" &&1346    type !== "LOCK" &&1347    type !== "UPDATE_SETTINGS" &&1348    type !== "GET_PENDING_PASSKEY" &&1349    type !== "GET_PASSKEY_PROVIDER_STATE" &&1350    type !== "DECLINE_CARD_SAVE" &&1351    type !== "IS_CARD_DECLINED" &&1352    type !== "SUBMIT_FEEDBACK"1353  );1354}13551356function isAllowedCanaryWebhookUrl(value: string): boolean {1357  try {1358    const url = new URL(value);1359    if (url.protocol !== "https:") return false;13601361    const hostname = url.hostname.toLowerCase();1362    if (1363      hostname === "localhost" ||1364      hostname.endsWith(".localhost") ||1365      isPrivateIpv4(hostname) ||1366      isPrivateIpv6(hostname)1367    ) {1368      return false;1369    }13701371    return true;1372  } catch {1373    return false;1374  }1375}13761377function isPrivateIpv4(hostname: string): boolean {1378  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1379    return true;1380  }13811382  const octets = hostname.split(".").map((part) => Number(part));1383  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1384    return false;1385  }13861387  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1388}13891390function isPrivateIpv6(hostname: string): boolean {1391  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1392  return (1393    normalized === "::1" ||1394    normalized.startsWith("fc") ||1395    normalized.startsWith("fd") ||1396    normalized.startsWith("fe80:")1397  );1398}