messages.ts

59.9 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 { getPendingSyncAlerts, clearPendingSyncAlerts } from "./sync-alerts";14import { extractDomain } from "../shared/domain";15import { setupAutoLock, touchAutoLock } from "./alarms";16import { runSelfTest } from "./self-test";17import * as vault from "./vault";18import {19  handleEstimateCodexPages,20  handleGetCodexVaultData,21  handleRestoreFromCodex,22} from "./codex-handlers";23import type { CodexRestorePayload } from "../shared/codex-types";24import {25  activateLicense,26  deactivateLicense,27  getLicenseInfo,28  getLicenseKey,29  isProUser,30  markCelebrationPlayed,31  shouldPlayCelebration,32} from "./license";33import {34  completeFirefoxPasskeyCreate,35  getPasskeyProviderState,36  getPendingPasskeyRequest,37  handleFirefoxPasskeyCreate,38  handleFirefoxPasskeyGet,39  handlePasskeyHasCredentials,40  initiateFirefoxPasskeyCreate,41  isPasskeyOfferDeclined,42  onVaultUnlocked,43  recordPasskeyOfferDecline,44  resolvePendingPasskeyRequest,45  setPasskeyProviderEnabled,46} from "./passkey";47import { buildAdvancedHealthReport } from "./health";48import { storageClear } from "../shared/storage";49import { findInvalidWords } from "../shared/recovery-words";50import type {51  Message,52  MessageResponse,53  MessageType,54  ProFeature,55  VaultEntry,56} from "../shared/types";57import { isPasskeyOnly } from "../shared/types";58import { generateTOTP } from "../crypto/totp";59import { isValidRpId } from "../shared/passkey-utils";60import { isNativePlatform, nativePlugin } from "../shared/native";61import { predictBatch as mlPredictBatch } from "./ml";62import type { MLFieldFeatures } from "../shared/ml";63import { buildLocalIdentity, setDeviceName as setDeviceNameV3 } from "./chirp-identity";64import {65  listPairedDevices as listPairedDevicesV3,66  removePairedDeviceById as removePairedDeviceByIdV3,67  upsertPairedDevice as upsertPairedDeviceV3,68} from "./paired-devices";6970// Compile-time E2E flag, folded to a literal by Vite's `define` (false in71// every production build — verified in the bundled output). Mirrors the72// create-path bypass in passkey.ts so the Playwright passkey smoke can enable73// the provider without a real Pro licence; the gate is fully intact for users.74declare const __PEACH_E2E_PASSKEYS__: boolean;75const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true;7677let nativeSyncRunnerBootstrapped = false;7879function unhexBytes(hex: string): Uint8Array {80  if (hex.length % 2 !== 0) throw new Error("invalid hex");81  const out = new Uint8Array(hex.length / 2);82  for (let i = 0; i < out.length; i++) {83    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);84  }85  return out;86}8788/**89 * The single Pro gate. Every gated handler calls this first; the broadcast90 * lets the popup react (navigate to the License section, highlight the91 * relevant feature). Background never touches the popup view directly —92 * the popup owns navigation. See Projects.md "Pro gate rule".93 */94async function requirePro(95  feature: ProFeature,96  trigger: "user" | "background" = "user"97): Promise<{ allowed: boolean }> {98  if (PASSKEY_E2E_PRO_BYPASS && feature === "passkeys") return { allowed: true };99  if (await isProUser()) return { allowed: true };100101  if (trigger === "user") {102    // User deliberately triggered this feature — redirect the popup immediately.103    chrome.runtime104      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })105      .catch(() => {106        // Popup may be closed — the gate signal is best-effort.107      });108  } else {109    // Background trigger (e.g. passive sync initiation) — no popup is open.110    // Queue a notice so the next popup open shows a soft banner instead of111    // silently failing.112    if (chrome.storage.session) {113      chrome.storage.session114        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })115        .catch(() => {});116    }117  }118119  return { allowed: false };120}121122// ---------------------------------------------------------------------------123// Feedback submission target. Empty disables network submission while the UI124// continues to function as a no-op (the handler returns ok:true without125// calling fetch). When set, the URL is validated by126// `isAllowedCanaryWebhookUrl` before any request.127// ---------------------------------------------------------------------------128129const FEEDBACK_ENDPOINT = "";130131const PRIVATE_IPV4_RANGES = [132  { prefix: "10." },133  { prefix: "127." },134  { prefix: "169.254." },135  { prefix: "192.168." },136];137138export function setupMessageHandler(): void {139  chrome.runtime.onMessage.addListener(140    (msg: unknown, sender, sendResponse) => {141      if (!isMessage(msg)) {142        sendResponse({ ok: false, error: "invalid_message" });143        return true;144      }145      handleMessage(msg, sender)146        .then(sendResponse)147        .catch((err) =>148          sendResponse({149            ok: false,150            error: err instanceof Error ? err.message : String(err),151          })152        );153      return true;154    }155  );156157  // Android: the chrome shim queues sendMessage calls until this handler is158  // registered. Without this hookup, every message hangs on Capacitor builds.159  // eslint-disable-next-line @typescript-eslint/no-explicit-any160  const reg = (globalThis as any).__peachRegisterMessageHandler;161  if (typeof reg === "function") {162    reg(async (m: unknown) => {163      if (!isMessage(m)) return { ok: false, error: "invalid_message" };164      try {165        return await handleMessage(m);166      } catch (err) {167        return {168          ok: false,169          error: err instanceof Error ? err.message : String(err),170        };171      }172    });173  }174  if (isNativePlatform()) {175    void bootstrapNativeSyncRunner();176  }177}178179async function bootstrapNativeSyncRunner(): Promise<void> {180  if (nativeSyncRunnerBootstrapped) return;181  nativeSyncRunnerBootstrapped = true;182  try {183    const { setSyncRunner, hydratePersistedSyncState } = await import("./sync-trigger");184    const { productionSyncRunner } = await import("./chirp-sync-runner");185    setSyncRunner(productionSyncRunner);186    await hydratePersistedSyncState();187  } catch (err) {188    nativeSyncRunnerBootstrapped = false;189    console.warn("[Peach] failed to bootstrap native sync runner:", err);190  }191}192193function isMessage(m: unknown): m is Message {194  return typeof m === "object" && m !== null && "type" in m;195}196197/**198 * The browser-attested origin of the page that originated this message. A web199 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),200 * so every page-driven message arrives via the content-script relay and the201 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a202 * value the page cannot forge. This is the ONLY trustworthy origin for passkey203 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.204 */205function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {206  if (sender.origin) return sender.origin;207  if (sender.url) {208    try { return new URL(sender.url).origin; } catch { return undefined; }209  }210  return undefined;211}212213// Resolves once restoreFromSession() has run, so handlers see the correct214// post-restore unlock state. entry.ts registers this BEFORE the message215// handler so the onMessage listener is added synchronously at SW startup216// (MV3 requirement) while unlock-dependent handlers still wait for restore.217let restoreReady: Promise<void> = Promise.resolve();218219/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */220export function setRestoreReady(p: Promise<unknown>): void {221  restoreReady = p.then(() => undefined, () => undefined);222}223224export async function handleMessage(225  msg: Message,226  sender: Partial<chrome.runtime.MessageSender> = {}227): Promise<MessageResponse> {228  try {229    // Wait for session-restore to finish before reading any unlock/vault state.230    // On a cold SW start the popup's first message arrives while restore is231    // still in flight; without this gate IS_UNLOCKED would report locked (a232    // spurious lock screen) and the storage reads could race. The onMessage233    // listener itself is registered synchronously (entry.ts) so this gate, not234    // listener registration, is what absorbs the cold-start window.235    await restoreReady;236    // Validate sender — only allow messages from our extension pages/scripts.237    // `sender.id` is undefined for messages originating from extension UI238    // (popup/options), which is legitimate; reject only when it is defined239    // and does not match our extension id.240    if (241      sender.id !== undefined &&242      sender.id !== chrome.runtime.id243    ) {244      return { ok: false, error: "invalid_sender" };245    }246247    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {248      touchAutoLock();249    }250251    switch (msg.type) {252      case "CREATE_VAULT": {253        const { password } = msg.payload as { password: string };254        // Refuse to create a vault under an empty master password — the derived255        // key would be publicly known and the at-rest AES-GCM protection void256        // (audit HIGH; the CSV-import path previously passed ""). Length/strength257        // policy lives in the onboarding UI; this is the non-negotiable floor.258        if (typeof password !== "string" || password.length === 0) {259          return { ok: false, error: "invalid_payload" };260        }261        await vault.createVault(password);262        await setupAutoLock();263        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });264        onVaultUnlocked();265        return { ok: true };266      }267      case "UNLOCK": {268        const { password } = msg.payload as { password: string };269        const ok = await vault.unlock(password);270        if (ok) {271          // KAT: verify the WebCrypto stack is healthy before the user relies on it.272          // Runs after unlock so latency is hidden behind the vault-load time.273          const kat = await runSelfTest();274          if (!kat.ok) {275            console.error("[Peach] Crypto self-test FAILED:", kat.error);276            await vault.lock();277            return { ok: false, error: "self_test_failed" };278          }279          await setupAutoLock();280          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });281          onVaultUnlocked();282          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());283          return { ok: true };284        }285        // Distinguish corruption from wrong password so the popup can offer286        // a history-restore path instead of falsely accusing the user of287        // mistyping (M7/COR-007).288        const failure = vault.consumeLastUnlockFailureReason();289        if (failure) {290          return {291            ok: false,292            error: "vault_corrupted",293            canRestoreFromHistory: true,294          } as MessageResponse;295        }296        return { ok: false };297      }298      case "VALIDATE_RECOVERY_WORDS": {299        const { words } = msg.payload as { words: string[] };300        const invalid = findInvalidWords(words);301        return { ok: true, data: { valid: invalid.length === 0, invalid } };302      }303      case "GET_RECOVERY_WORDS": {304        // Must be unlocked and have recovery set up (vault must be v2.12+).305        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };306        try {307          const words = await vault.getRecoveryWords();308          return { ok: true, data: words };309        } catch (e) {310          // pre-v2.12 vault that hasn't migrated311          return { ok: false, error: "recovery_not_setup" };312        }313      }314      case "RECOVER_WITH_WORDS": {315        // User has lost their password but has their 12 recovery words.316        // We: (1) validate the words, (2) re-encrypt vault with new password.317        const { words, newPassword } = msg.payload as {318          words: string[];319          newPassword: string;320        };321        const stored = await vault.loadSlotA();322        if (!stored) return { ok: false, error: "no_vault" };323        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {324          return { ok: false, error: "recovery_not_setup" };325        }326        // Unwrap the root key from the recovery escrow.327        try {328          await vault.unwrapRootKeyForRecovery(329            stored.recovery_wrapped_root_key,330            stored.recovery_nonce ?? "",331            stored.recovery_tag ?? "",332            stored.recovery_salt,333            words334          );335        } catch {336          return { ok: false, error: "invalid_recovery_words" };337        }338        // Re-key: derive fresh salt + key from new password.339        const newSalt = vault.generateSalt();340        const newKey = await vault.deriveKey(newPassword, newSalt);341        // Re-wrap root key under the new password's derived key so the same342        // recovery words continue to work after the password change.343        await vault.rewrapRootKeyForPassword(newKey, newSalt);344        // Re-encrypt vault entries with the new key.345        await vault.changePasswordWithNewKey(newSalt, newKey);346        await setupAutoLock();347        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });348        return { ok: true };349      }350      case "LOCK":351        vault.lock();352        if (isNativePlatform()) await clearInMemoryVault();353        return { ok: true };354      case "IS_UNLOCKED":355        return { ok: true, data: vault.isUnlocked() };356      case "GET_VAULT_STATUS":357        return { ok: true, unlocked: vault.isUnlocked() };358      case "HAS_VAULT":359        return { ok: true, data: await vault.hasVault() };360      case "GET_ENTRIES":361        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };362        return { ok: true, data: vault.getEntries() };363      case "ADD_ENTRY": {364        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };365        const payload = msg.payload;366        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {367          return { ok: false, error: "invalid_payload" };368        }369        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);370        return { ok: true, data: entry };371      }372      case "BATCH_ADD_ENTRIES": {373        const payload = msg.payload as { entries?: unknown } | null | undefined;374        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {375          return { ok: false, error: "invalid_payload" };376        }377        if (!Array.isArray(payload.entries)) {378          return { ok: false, error: "invalid_payload" };379        }380        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);381        return { ok: true, data: added };382      }383      case "RESTORE_ENTRIES": {384        const payload = msg.payload as385          | { entries?: unknown; mode?: unknown; settings?: unknown }386          | null387          | undefined;388        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {389          return { ok: false, error: "invalid_payload" };390        }391        if (!Array.isArray(payload.entries)) {392          return { ok: false, error: "invalid_payload" };393        }394        if (payload.mode !== "replace" && payload.mode !== "merge") {395          return { ok: false, error: "invalid_payload" };396        }397        const summary = await vault.restoreEntries(398          payload.entries as Parameters<typeof vault.restoreEntries>[0],399          payload.mode400        );401        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {402          await vault.updateSettings(payload.settings as vault.VaultSettings);403        }404        return { ok: true, data: summary };405      }406      case "CLEAR_VAULT_ENTRIES": {407        await vault.clearVaultEntries("REPLACE_ALL");408        return { ok: true };409      }410      case "GET_VAULT_HISTORY": {411        const snapshots = await vault.getVaultHistory();412        return { ok: true, data: snapshots };413      }414      case "RESTORE_VAULT_SNAPSHOT": {415        const { snapshotId } = msg.payload as { snapshotId: string };416        const result = await vault.restoreVaultSnapshot(snapshotId);417        if (!result.ok) return { ok: false, error: result.error };418        broadcastToContentScripts({ type: "VAULT_LOCKED" });419        return { ok: true };420      }421      case "COUNT_DUPLICATES": {422        return { ok: true, data: vault.countDuplicates() };423      }424      case "DEDUPLICATE_ENTRIES": {425        const removed = await vault.deduplicateEntries();426        return { ok: true, data: removed };427      }428      case "UPDATE_ENTRY": {429        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;430        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {431          return { ok: false, error: "invalid_payload" };432        }433        const { id, patch } = payload;434        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {435          return { ok: false, error: "invalid_payload" };436        }437        // Single enforcement point for the Canary Entries Pro gate. Only438        // gates the transition into a canary entry — clearing/disabling a439        // canary (`canary: undefined`) is always allowed, so existing440        // canary entries remain manageable.441        const incomingCanary = (patch as { canary?: unknown }).canary;442        if (incomingCanary && typeof incomingCanary === "object") {443          const existing = vault.getEntryById(id);444          if (!existing?.canary) {445            const gate = await requirePro("canary_entry");446            if (!gate.allowed) return { ok: false, error: "pro_required" };447          }448        }449        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);450        return { ok: true };451      }452      case "ADD_ADDITIONAL_URL": {453        const { id, url } = msg.payload as { id: string; url: string };454        const trimmed = typeof url === "string" ? url.trim() : "";455        if (!trimmed) return { ok: false, error: "url_required" };456        const existing = vault.getEntryById(id);457        if (!existing) return { ok: false, error: "entry_not_found" };458        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };459        const merged = [...(existing.additionalUrls ?? []), trimmed];460        await vault.updateEntry(id, { additionalUrls: merged });461        return { ok: true };462      }463      case "DELETE_ENTRY": {464        const { id } = msg.payload as { id: string };465        await vault.deleteEntry(id);466        return { ok: true };467      }468      case "GET_DELETED_ENTRIES":469        return { ok: true, data: vault.getDeletedEntries() };470      case "RESTORE_ENTRY": {471        const { id } = msg.payload as { id: string };472        await vault.restoreEntry(id);473        return { ok: true };474      }475      case "PURGE_ENTRY": {476        const { id } = msg.payload as { id: string };477        await vault.purgeEntry(id);478        return { ok: true };479      }480      case "PURGE_EXPIRED_TRASH": {481        const { retentionMs } = msg.payload as { retentionMs: number };482        const purged = await vault.purgeExpiredTrash(retentionMs);483        return { ok: true, data: purged };484      }485      case "SAVE_NOTE": {486        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };487        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };488        const now = Date.now();489        if (id) {490          const existing = vault.getEntryById(id);491          if (!existing) return { ok: false, error: "not_found" };492          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });493          return { ok: true, data: vault.getEntryById(id) };494        } else {495          const entry = await vault.addEntry({496            type: "note",497            title: title || "Untitled",498            notes: body,499            createdAt: now,500            modifiedAt: now,501          } as any);502          return { ok: true, data: entry };503        }504      }505      case "DELETE_NOTE": {506        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };507        const { id } = msg.payload as { id: string };508        await vault.deleteEntry(id);509        return { ok: true };510      }511      case "GET_NOTES": {512        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };513        const notes = vault.getEntries().filter(514          (e) => e.type === "note" && !e.deletedAt515        );516        return { ok: true, data: notes } as MessageResponse;517      }518      case "SEARCH_VAULT": {519        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };520        // AUD-002: shape-validate the payload before calling string methods.521        // A raw cast lets a malformed message crash the handler with TypeError.522        const { query } = (msg.payload ?? {}) as { query?: unknown };523        if (typeof query !== "string") {524          return { ok: false, error: "invalid_payload" };525        }526        const q = query.toLowerCase();527        const searchResults = vault.getEntries().filter(528          (e) =>529            !e.deletedAt &&530            (e.title.toLowerCase().includes(q) ||531              e.notes?.toLowerCase().includes(q) ||532              e.username?.toLowerCase().includes(q))533        );534        return { ok: true, data: searchResults } as MessageResponse;535      }536      case "AUTOFILL_QUERY": {537        if (!vault.isUnlocked()) {538          return { ok: false, error: "vault_locked" };539        }540        let { includeAll } = msg.payload as { includeAll?: boolean };541        const { domain, kind, userGesture } = msg.payload as {542          domain: string;543          kind?: "login" | "card" | "totp";544          userGesture?: boolean;545        };546        // MV-2: the vault-wide inventory (every title/username/email/url)547        // may only leave the background on an explicit user gesture — the548        // user opening the search affordance — never on passive form focus.549        // userGesture is self-declared by our own content script; the value550        // of this gate is that PASSIVE code paths (which never set it)551        // cannot ship the inventory, shrinking what a compromised page that552        // merely triggers focus events can observe.553        if (includeAll && userGesture !== true) {554          includeAll = false;555        }556        // kind="card": return saved cards as compact summaries for the557        // inline card silver platter. Cards are not domain-scoped — every558        // saved card is a candidate on every checkout page — so domain is559        // ignored when kind === "card".560        if (kind === "card") {561          const cards = vault.getEntries().filter((e) => e.type === "card");562          return {563            ok: true,564            data: cards.map((e) => ({565              id: e.id,566              title: e.cardNickname || e.title,567              cardholderName: e.cardholderName,568              last4: e.last4,569              expMonth: e.expMonth,570              expYear: e.expYear,571              network: e.network,572            })),573          };574        }575        if (kind === "totp") {576          const matches = (577            includeAll578              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")579              : vault.queryDomain(domain)580          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));581          return {582            ok: true,583            data: matches.map((e) => ({584              id: e.id,585              title: e.title,586              username: e.username,587              email: e.email,588              url: e.url,589              hasTotp: true,590            })),591          };592        }593        // The inline selector fills username+password into a form. Passkey-594        // only entries have no password to fill; sign-in for those goes595        // through the WebAuthn path instead. Filter them out everywhere so596        // the user doesn't see four "GitHub" rows that mostly do nothing.597        // Notes and cards never belonged here either.598        const matches = (599          includeAll600            ? vault601                .getEntries()602                .filter((entry) => entry.type !== "note" && entry.type !== "card")603            : vault.queryDomain(domain)604        ).filter((entry) => !isPasskeyOnly(entry));605        return {606          ok: true,607          data: matches.map((e) =>608            includeAll609              ? {610                  id: e.id,611                  title: e.title,612                  // username/email/url shipped so the inline popup's search613                  // affordance can match on them, not just titles. No secrets614                  // cross the boundary — same shape as the domain-matched615                  // response below minus hasTotp (which the search list616                  // doesn't surface).617                  username: e.username,618                  email: e.email,619                  url: e.url,620                  hasPasskey: e.passkey !== undefined,621                }622              : {623                  id: e.id,624                  title: e.title,625                  username: e.username,626                  email: e.email,627                  url: e.url,628                  hasTotp: Boolean(e.totp),629                  hasPasskey: e.passkey !== undefined,630                }631          ),632        };633      }634      case "GET_ENTRY_FOR_FILL": {635        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };636        const { id, explicitSummon } = msg.payload as {637          id: string;638          explicitSummon?: boolean;639        };640        const entry = vault.getEntryById(id);641        if (!entry) return { ok: false, error: "entry_not_found" };642        // Passkey-only entries (passkey credential, no password) cannot be643        // filled into a form — sign-in goes through the WebAuthn path. A644        // login that ALSO has a passkey is still fillable for its password.645        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };646647        // MV-1: re-validate the entry against the requesting tab's origin.648        // sender.tab.url is browser-attested — a page cannot forge it. When649        // the request does not come from a tab at all (popup surfaces use650        // GET_ENTRY_FOR_EDIT, not this), refuse.651        if (sender.tab !== undefined || sender.url !== undefined) {652          let senderDomain: string | null = null;653          try {654            const rawUrl = sender.tab?.url ?? sender.url ?? "";655            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;656          } catch {657            senderDomain = null;658          }659          if (!senderDomain) return { ok: false, error: "origin_unverified" };660661          const entryDomains = new Set<string>();662          const primary = extractDomain(entry.url ?? "");663          if (primary) entryDomains.add(primary);664          for (const extra of entry.additionalUrls ?? []) {665            const d = extractDomain(extra);666            if (d) entryDomains.add(d);667          }668669          // explicitSummon=true means the user actively picked this entry670          // from the cross-domain search affordance — an intentional671          // off-domain fill. Passive fill paths must stay domain-bound.672          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {673            // Domain mismatch — refuse silently (no oracle about which ids exist).674            return { ok: false, error: "entry_not_found" };675          }676        }677        // Strip the passkey credential AND the raw base32 TOTP seed from the678        // response. Content scripts never need either: the private key is the679        // authenticator's, and handing over the TOTP seed would let a680        // compromised content script mint valid codes indefinitely (SEV-3-C).681        // Generate the *current* 6-digit code here in the background and send682        // only that, plus the seconds left so the UI can render a countdown.683        // Also drop passwordHistory: filling needs only the *current* password.684        // Handing every past password to a content script during passive685        // autofill on an arbitrary page would widen the blast radius of a686        // compromised page far beyond the one credential being filled.687        const { passkey: _strippedPasskey, totp: seed, passwordHistory: _ph, ...safeEntry } = entry;688        let totpCode: string | undefined;689        let totpRemaining: number | undefined;690        if (seed) {691          try {692            const generated = generateTOTP(seed);693            totpCode = generated.code;694            totpRemaining = generated.remaining;695          } catch {696            totpCode = undefined;697          }698        }699        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };700      }701      // Trusted full-entry fetch for Peach's own inline-popup surfaces that702      // genuinely need the raw TOTP seed: the edit form (which re-saves the703      // seed and would otherwise wipe it) and nothing else. Unlike704      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside705      // the inline popup, never during passive autofill on an arbitrary page.706      // The passkey credential is still stripped — the edit form never touches it.707      case "GET_ENTRY_FOR_EDIT": {708        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };709        const { id } = msg.payload as { id: string };710        const entry = vault.getEntryById(id);711        if (!entry) return { ok: false, error: "entry_not_found" };712        const { passkey: _passkey, ...safeEntry } = entry;713        return { ok: true, data: safeEntry };714      }715      case "COPY": {716        // AUD-002: shape-validate the payload before passing to the clipboard717        // helper. A raw cast lets a malformed message reach the clipboard API718        // with a non-string and throw.719        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {720          text?: unknown;721          label?: unknown;722          alreadyWritten?: unknown;723        };724        if (typeof text !== "string" || typeof label !== "string") {725          return { ok: false, error: "invalid_payload" };726        }727        await copyToClipboard(text, label, Boolean(alreadyWritten));728        return { ok: true };729      }730      case "CHECK_ALL_BREACHES": {731        const allEntries = vault.getEntries();732        const results: Record<string, number> = {};733        for (const entry of allEntries) {734          if (entry.type === "note") continue;735          if (!entry.password) continue;736          results[entry.id] = await vault.checkBreach(entry.password);737          // Small delay — be a good citizen to the HIBP API738          await new Promise((r) => setTimeout(r, 200));739        }740        // Persist any non-zero counts back to entries741        for (const [id, count] of Object.entries(results)) {742          const entry = vault.getEntryById(id);743          if (entry && (entry.breach ?? 0) !== count) {744            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });745          }746        }747        return { ok: true, data: results };748      }749      case "GET_SETTINGS":750        return { ok: true, data: await vault.ensureSettingsLoaded() };751      case "UPDATE_SETTINGS": {752        const patch = msg.payload;753        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {754          return { ok: false, error: "invalid_payload" };755        }756        await vault.updateSettings(patch as vault.VaultSettings);757        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {758          await setupAutoLock();759          if (vault.isUnlocked()) touchAutoLock();760        }761        return { ok: true };762      }763      case "GET_PENDING_PASSKEY":764        return { ok: true, data: await getPendingPasskeyRequest() };765      case "APPROVE_PASSKEY": {766        const { requestId } = msg.payload as { requestId: number };767        await resolvePendingPasskeyRequest(requestId, true);768        return { ok: true };769      }770      case "DENY_PASSKEY": {771        const { requestId } = msg.payload as { requestId: number };772        await resolvePendingPasskeyRequest(requestId, false);773        return { ok: true };774      }775      case "GET_PASSKEY_PROVIDER_STATE":776        return { ok: true, data: await getPasskeyProviderState() };777      case "SET_PASSKEY_PROVIDER_ENABLED": {778        const { enabled } = msg.payload as { enabled: boolean };779        // Disabling is always free; gating fires only when a free user is780        // trying to turn passkey interception on.781        if (enabled) {782          const gate = await requirePro("passkeys");783          if (!gate.allowed) return { ok: false, error: "pro_required" };784        }785        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };786      }787      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS788      // endpoint. Intentional product behavior — users configure their own789      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private790      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-791      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to792      // users that the entry title leaves the device when the canary fires.793      case "FIRE_CANARY_PING": {794        // Canary alert fires unconditionally for any entry with canary: true.795        // The Pro gate only governs creation/flagging of canary entries; once796        // an entry is flagged, the alert path is a security property and must797        // never be license-gated.798        const { webhookUrl, entryTitle, trigger } = msg.payload as {799          webhookUrl: string;800          entryTitle: string;801          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";802        };803        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {804          return { ok: false, error: "invalid_webhook_url" };805        }806        const body = JSON.stringify({807          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",808          entry: entryTitle,809          trigger,810          timestamp: new Date().toISOString(),811          source: "peach-extension",812        });813        if (trigger === "test") {814          // Permitted outbound fetch: user-configured canary alert endpoint815          // (validated by isAllowedCanaryWebhookUrl above). This is the816          // only non-HIBP outbound call in the extension — see817          // Projects.md §3.7. Test pings are awaited so the UI can show818          // success/failure.819          try {820            const res = await fetch(webhookUrl, {821              method: "POST",822              headers: { "Content-Type": "application/json" },823              body,824            });825            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };826          } catch (err) {827            return { ok: false, error: err instanceof Error ? err.message : "network_error" };828          }829        }830        // Non-test triggers are fire-and-forget831        fetch(webhookUrl, {832          method: "POST",833          headers: { "Content-Type": "application/json" },834          body,835        }).catch(() => {});836        return { ok: true };837      }838      case "ACTIVATE_LICENSE": {839        const { key } = msg.payload as { key: string };840        const licenseInfo = await activateLicense(key);841        return { ok: true, data: licenseInfo };842      }843      case "GET_LICENSE": {844        const licenseInfo = await getLicenseInfo();845        return { ok: true, data: licenseInfo };846      }847      case "GET_LICENSE_KEY": {848        const key = await getLicenseKey();849        return { ok: true, data: key };850      }851      case "DEACTIVATE_LICENSE": {852        await deactivateLicense();853        return { ok: true };854      }855      case "SHOULD_PLAY_CELEBRATION": {856        const should = await shouldPlayCelebration();857        return { ok: true, data: should };858      }859      case "MARK_CELEBRATION_PLAYED": {860        await markCelebrationPlayed();861        return { ok: true };862      }863      case "GET_CODEX_VAULT_DATA": {864        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the865        // popup navigates to the License section without further coordination.866        const gate = await requirePro("codex");867        if (!gate.allowed) return { ok: false, error: "pro_required" };868        return await handleGetCodexVaultData();869      }870      case "ESTIMATE_CODEX_PAGES": {871        const gate = await requirePro("codex");872        if (!gate.allowed) return { ok: false, error: "pro_required" };873        return await handleEstimateCodexPages();874      }875      case "RESTORE_FROM_CODEX": {876        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still877        // be able to restore a vault that was printed by a Pro user.878        // DO NOT add a Pro gate here.879        const payload = msg.payload as CodexRestorePayload;880        return await handleRestoreFromCodex(payload);881      }882      case "OPEN_PRO_GATE": {883        // Content script requests: open popup and navigate to License section.884        const { feature } = (msg.payload ?? {}) as { feature?: string };885        if (chrome.storage.session) {886          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });887        }888        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }889        return { ok: true };890      }891      case "OPEN_POPUP": {892        // Content script asks to open the trusted extension popup — used by the893        // inline locked bubble so the master password is entered in the popup,894        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a895        // user gesture + Chrome 127+/Firefox; on failure the user clicks the896        // toolbar icon. The badge already signals Peach needs attention.897        //898        // Set a session flag so the popup knows it was opened for inline unlock899        // and should close itself once the vault is unlocked (returning the user900        // to the inline autofill selector on the page).901        if (chrome.storage.session) {902          await chrome.storage.session.set({ peach_inline_unlock: true });903        }904        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }905        return { ok: true };906      }907      case "GET_IDENTITIES": {908        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };909        return { ok: true, data: vault.getIdentities() };910      }911      case "TOUCH_AUTO_LOCK": {912        // touchAutoLock() is already called by shouldRefreshAutoLock above;913        // this case just gives the popup a typed message to keep the session alive.914        return { ok: true };915      }916      case "GET_ADVANCED_HEALTH_REPORT": {917        const gate = await requirePro("advanced_health");918        if (!gate.allowed) return { ok: false, error: "pro_required" };919        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };920        const report = await buildAdvancedHealthReport(vault.getEntries());921        return { ok: true, data: report };922      }923      case "IS_DURESS_ENABLED": {924        const enabled = await vault.isDuressEnabled();925        return { ok: true, data: enabled };926      }927      case "SETUP_DURESS": {928        // Single enforcement point for the Duress Vault Pro gate. Free users929        // who somehow reach this handler are rejected here; the popup also930        // pre-checks isPro() to avoid showing the setup form to free users,931        // but server-side is the actual security boundary.932        const gate = await requirePro("duress_vault");933        if (!gate.allowed) return { ok: false, error: "pro_required" };934        // MV3 service workers restart after inactivity, losing the in-memory935        // derived key. Detect this before calling setupDuress so the popup936        // can show a meaningful prompt to re-lock and re-unlock.937        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };938        const { duressPassword } = msg.payload as { duressPassword: string };939        await vault.setupDuress(duressPassword);940        return { ok: true };941      }942      case "DISABLE_DURESS": {943        await vault.disableDuress();944        return { ok: true };945      }946      case "VERIFY_MAIN_PASSWORD": {947        const { password } = msg.payload as { password: string };948        const ok = await vault.verifyMainPassword(password);949        return { ok: true, data: ok };950      }951      case "CHANGE_PASSWORD": {952        const { currentPassword, newPassword } = msg.payload as {953          currentPassword: string;954          newPassword: string;955        };956        const changed = await vault.changePassword(currentPassword, newPassword);957        return changed958          ? { ok: true }959          : { ok: false, error: "incorrect_current_password" };960      }961      case "GET_SITE_PASSWORD_POLICY": {962        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });963        if (!tab?.id) return { ok: true, data: null };964        try {965          const response = await chrome.tabs.sendMessage(tab.id, {966            type: "GET_SITE_PASSWORD_POLICY",967          });968          return (response as MessageResponse) ?? { ok: true, data: null };969        } catch {970          return { ok: true, data: null };971        }972      }973      case "RECORD_MANUAL_SUMMON": {974        const { domain } = msg.payload as { domain: string };975        const settings = vault.getSettings();976        const existing = settings.manualSummonDomains?.[domain];977        const now = Date.now();978        await vault.updateSettings({979          manualSummonDomains: {980            ...settings.manualSummonDomains,981            [domain]: {982              firstSummonedAt: existing?.firstSummonedAt ?? now,983              summonCount: (existing?.summonCount ?? 0) + 1,984              lastSummonedAt: now,985            },986          },987        });988        return { ok: true };989      }990      case "DECLINE_CARD_SAVE": {991        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };992        await vault.declineCardSaveOffer(last4, expMonth, expYear);993        return { ok: true };994      }995      case "IS_CARD_DECLINED": {996        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };997        const declined = await vault.isCardDeclined(last4, expMonth, expYear);998        return { ok: true, data: declined };999      }1000      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1001        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1002          rpId?: string;1003          rpName?: string;1004          userName?: string;1005          userDisplayName?: string;1006        };1007        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1008        return await initiateFirefoxPasskeyCreate({1009          rpId,1010          rpName: rpName ?? rpId,1011          userName,1012          userDisplayName,1013        });1014      }10151016      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1017        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1018        if (!payload) return { ok: false, error: "missing_payload" };1019        return await completeFirefoxPasskeyCreate(payload);1020      }10211022      case "PASSKEY_OFFER_DECLINE": {1023        const { domain } = (msg.payload ?? {}) as { domain?: string };1024        if (!domain) return { ok: false, error: "domain_required" };1025        await recordPasskeyOfferDecline(domain);1026        return { ok: true };1027      }10281029      case "GET_PASSKEY_OFFER_DECLINED": {1030        const { domain } = (msg.payload ?? {}) as { domain?: string };1031        if (!domain) return { ok: false, error: "domain_required" };1032        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1033      }10341035      case "PASSKEY_HAS_CREDENTIALS": {1036        const payload = msg.payload as {1037          rpId?: string;1038          allowCredentials?: Array<{ id: string; type?: string }>;1039        } | undefined;1040        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1041        return await handlePasskeyHasCredentials({1042          rpId: payload.rpId,1043          allowCredentials: payload.allowCredentials ?? [],1044        }, attestedSenderOrigin(sender));1045      }10461047      case "PASSKEY_CREATE": {1048        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1049        if (!payload?.rpId || !payload?.userName) {1050          return { ok: false, error: "rpid_and_username_required" };1051        }1052        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1053      }10541055      case "PASSKEY_GET": {1056        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1057        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1058        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1059      }10601061      case "PASSKEY_AUTH_RESPONSE": {1062        const { requestId, approved } = (msg.payload ?? {}) as {1063          requestId?: string | number;1064          approved?: boolean;1065        };1066        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1067          return { ok: false, error: 'requestId and approved required' };1068        }1069        await resolvePendingPasskeyRequest(Number(requestId), approved);1070        return { ok: true };1071      }10721073      case "GET_PASSKEY_FOR_DOMAIN": {1074        const { domain } = (msg.payload ?? {}) as { domain?: string };1075        if (!domain) return { ok: false, error: "domain_required" };1076        // Scope to the caller's own origin: a page may only ask about passkeys1077        // for a domain it actually owns, so an arbitrary page cannot enumerate1078        // which sites the user holds passkeys for or read the username (audit MEDIUM).1079        const origin = attestedSenderOrigin(sender);1080        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1081        if (!vault.isUnlocked()) return { ok: true, data: null };1082        const match = vault1083          .getEntries()1084          .find((entry) => entry.passkey?.rpId === domain);1085        if (!match || !match.passkey) return { ok: true, data: null };1086        // Slim shape — only the fields State 11 needs. Never expose private1087        // key material, even though this is locked behind isUnlocked.1088        return {1089          ok: true,1090          data: {1091            rpId: match.passkey.rpId,1092            userName: match.passkey.userName,1093            browser: match.passkey.browser,1094          },1095        };1096      }10971098      case "DESTROY_VAULT": {1099        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1100        // storage.local.clear() wipes every Peach key (slots, settings, license,1101        // onboarded flag, history, sync state, declined cards, recall, etc.);1102        // session.clear() wipes pending passkey requests + pro-notice queues.1103        // Caller (Panic.tsx) handles UI navigation back to onboarding.1104        //1105        // The Pro license is the one thing that must survive: the user paid for1106        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1107        // Capture it before the clear and restore it after. peach_pro_celebrated1108        // rides along so the Pro celebration doesn't replay on the next unlock.1109        const preserved = await chrome.storage.local.get([1110          "peach_license",1111          "peach_pro_celebrated",1112        ]);1113        vault.lock();1114        await storageClear();1115        await vault.clearVaultHistory();1116        const toRestore: Record<string, unknown> = {};1117        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1118        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1119        if (Object.keys(toRestore).length > 0) {1120          await chrome.storage.local.set(toRestore);1121        }1122        if (chrome.storage.session) {1123          await chrome.storage.session.clear();1124        }1125        return { ok: true };1126      }11271128      case "SUBMIT_FEEDBACK": {1129        const { category, message, version, browser } = msg.payload as {1130          category: string;1131          message: string;1132          version: string;1133          browser: string;1134        };1135        if (!message.trim()) return { ok: false, error: "message_empty" };1136        if (!FEEDBACK_ENDPOINT) return { ok: true };1137        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1138          return { ok: false, error: "invalid_feedback_endpoint" };1139        }1140        try {1141          const res = await fetch(FEEDBACK_ENDPOINT, {1142            method: "POST",1143            headers: { "Content-Type": "application/json" },1144            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1145          });1146          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1147        } catch (err) {1148          return { ok: false, error: err instanceof Error ? err.message : "network_error" };1149        }1150      }1151      // Android-only: biometric unlock with pre-derived key.1152      case "UNLOCK_WITH_KEY": {1153        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1154        if (!isNativePlatform()) {1155          return { ok: false, error: "desktop_only_uses_password" };1156        }1157        try {1158          const result = await vault.unlockWithKey(masterKeyHex);1159          if (result.ok) {1160            onVaultUnlocked();1161            await publishInMemoryVault(result.entries);1162          }1163          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1164        } catch {1165          return { ok: false, error: "invalid_key" };1166        }1167      }1168      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1169      case "GET_DERIVED_KEY": {1170        if (!isNativePlatform()) {1171          return { ok: false, error: "android_only" };1172        }1173        if (!vault.isUnlocked()) {1174          return { ok: false, error: "vault_locked" };1175        }1176        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1177      }1178      case "GET_IDENTITY_SUGGESTIONS": {1179        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1180        const entries = vault.getEntries();1181        const suggestions = buildIdentitySuggestions(entries);1182        return { ok: true, data: { suggestions } };1183      }1184      case "POPULATE_INLINE_VAULT": {1185        if (!isNativePlatform()) return { ok: false };1186        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1187        const entries = vault.getEntries();1188        await publishInMemoryVault(entries);1189        return { ok: true };1190      }1191      case "ML_INIT":1192        return { ok: true };11931194      case "ML_PREDICT_BATCH": {1195        // AUD-002: shape-validate before forwarding to the ML helper.1196        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1197        if (!Array.isArray(featuresArray)) {1198          return { ok: false, error: "invalid_payload" };1199        }1200        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1201      }12021203      // ── Chirp Sync (v3) ───────────────────────────────────────────────1204      // Returns the public-facing local identity needed by the popup to1205      // drive Phase-1 audio pairing. The private long-term key never1206      // leaves the background.1207      case "CHIRP_GET_LOCAL_IDENTITY": {1208        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1209        const proCheck = await requirePro("sync");1210        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1211        // Identity derives from the stable root key, not the password-derived1212        // key, so pairing survives a master-password change (SEV-2-B).1213        const masterKeyHex = vault.getRootKeyHex();1214        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1215        const masterKey = unhexBytes(masterKeyHex);1216        try {1217          const identity = await buildLocalIdentity(masterKey);1218          return { ok: true, data: identity };1219        } finally {1220          masterKey.fill(0);1221        }1222      }12231224      case "CHIRP_COMPLETE_PAIRING": {1225        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1226        const proCheck = await requirePro("sync");1227        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1228        const paired = (msg.payload as { paired?: unknown })?.paired;1229        if (typeof paired !== "object" || paired === null) {1230          return { ok: false, error: "invalid_payload" };1231        }1232        const candidate = paired as Record<string, unknown>;1233        if (1234          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1235          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1236          typeof candidate.deviceType !== "string" ||1237          typeof candidate.longTermPublicKeyHex !== "string" ||1238          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1239          (1240            candidate.signingPublicKeyHex !== undefined &&1241            (1242              typeof candidate.signingPublicKeyHex !== "string" ||1243              !/^[0-9a-f]{64}$/.test(candidate.signingPublicKeyHex)1244            )1245          ) ||1246          typeof candidate.pairedAt !== "number"1247        ) {1248          return { ok: false, error: "invalid_paired_device" };1249        }1250        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1251        return { ok: true };1252      }12531254      case "CHIRP_LIST_PAIRED_DEVICES": {1255        const devices = await listPairedDevicesV3();1256        return { ok: true, data: { devices } };1257      }12581259      case "CHIRP_UNPAIR_DEVICE": {1260        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1261        if (typeof deviceId !== "string" || !deviceId) {1262          return { ok: false, error: "invalid_payload" };1263        }1264        await removePairedDeviceByIdV3(deviceId);1265        return { ok: true };1266      }12671268      case "CHIRP_RENAME_LOCAL_DEVICE": {1269        const { name } = (msg.payload ?? {}) as { name?: string };1270        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1271        await setDeviceNameV3(name);1272        return { ok: true };1273      }12741275      case "TRIGGER_SYNC": {1276        const payload = (msg.payload ?? {}) as {1277          reason?: "vault_change" | "foreground" | "manual" | "mdns";1278          force?: boolean;1279          deviceId?: string;1280          discoveredIp?: string;1281          discoveredPort?: number;1282        };1283        const reason = payload.reason ?? "foreground";12841285        // mDNS discovery delivers a fresh (ip, port) resolved by the native1286        // side. Update the cached address before the sync runner tries to1287        // connect — avoids a subnet probe on the very next round.1288        if (1289          reason === "mdns" &&1290          typeof payload.deviceId === "string" &&1291          typeof payload.discoveredIp === "string"1292        ) {1293          const { findPairedDeviceById, setLastKnownIp } = await import("./paired-devices");1294          const device = await findPairedDeviceById(payload.deviceId);1295          if (device?.longTermPublicKeyHex) {1296            await setLastKnownIp(device.longTermPublicKeyHex, payload.discoveredIp).catch(() => undefined);1297          }1298        }12991300        const { triggerSyncIfReachable } = await import("./sync-trigger");1301        void triggerSyncIfReachable({ reason, force: payload.force === true });1302        return { ok: true };1303      }13041305      case "GET_SYNC_STATE": {1306        const { getSyncState } = await import("./sync-trigger");1307        return { ok: true, data: getSyncState() };1308      }13091310      case "GET_SYNC_ALERTS": {1311        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1312        const alerts = await getPendingSyncAlerts();1313        // The popup reads on open and acknowledges with consume:true after1314        // rendering, so a popup crash between read and render doesn't lose1315        // the alerts.1316        if (consume) await clearPendingSyncAlerts();1317        return { ok: true, data: alerts };1318      }13191320      default:1321        return { ok: false, error: "unknown_message_type" };1322    }1323  } catch (err) {1324    return {1325      ok: false,1326      error: err instanceof Error ? err.message : "operation_failed",1327    };1328  }1329}13301331// --- Mobile platform helpers ---13321333// Android: populates the in-memory vault used by PeachAutofillService.1334async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1335  const plugin = nativePlugin<{1336    setEntries?: (args: {1337      entries: Array<{1338        id: string;1339        title: string;1340        username: string;1341        email: string;1342        password: string;1343        url: string;1344        totp: string;1345        additionalUrls: string[];1346      }>;1347    }) => Promise<void>;1348  }>("InMemoryVaultPlugin");1349  if (!plugin?.setEntries) return;1350  await plugin.setEntries({1351    entries: entries.map((e) => ({1352      id: e.id,1353      title: e.title ?? "",1354      username: e.username ?? "",1355      email: (e as VaultEntry & { email?: string }).email ?? "",1356      password: e.password ?? "",1357      url: e.url ?? "",1358      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1359      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1360    })),1361  });1362}13631364// Android: clear the autofill in-memory store on lock.1365async function clearInMemoryVault(): Promise<void> {1366  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1367  if (!plugin?.clearEntries) return;1368  await plugin.clearEntries();1369}13701371// Returns username use-counts from the vault, sorted by frequency. Each row1372// also carries the entry's email so the popup can suggest the email/username1373// pair the user has actually used together.1374function buildIdentitySuggestions(1375  entries: VaultEntry[],1376): Array<{ email: string; username: string; count: number }> {1377  const usernameCounts = new Map<string, number>();1378  const usernameEmail = new Map<string, string>();1379  for (const entry of entries) {1380    const username = entry.username ?? "";1381    const email = (entry as VaultEntry & { email?: string }).email ?? "";1382    if (!username && !email) continue;1383    const key = username || email;1384    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1385    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1386  }1387  return Array.from(usernameCounts.entries())1388    .sort((a, b) => b[1] - a[1])1389    .map(([username, count]) => ({1390      email: usernameEmail.get(username) ?? "",1391      username,1392      count,1393    }));1394}13951396/** Notify all content scripts that the vault just became available. */1397function broadcastToContentScripts(message: { type: string }): void {1398  if (!chrome.tabs?.query) return;1399  chrome.tabs.query({}, (tabs) => {1400    for (const tab of tabs) {1401      if (tab.id !== undefined) {1402        chrome.tabs.sendMessage(tab.id, message).catch(() => {1403          // Tab may not have a content script — silently ignore1404        });1405      }1406    }1407  });1408}14091410function shouldRefreshAutoLock(type: MessageType): boolean {1411  return (1412    type !== "HAS_VAULT" &&1413    type !== "IS_UNLOCKED" &&1414    type !== "GET_VAULT_STATUS" &&1415    type !== "LOCK" &&1416    type !== "UPDATE_SETTINGS" &&1417    type !== "GET_PENDING_PASSKEY" &&1418    type !== "GET_PASSKEY_PROVIDER_STATE" &&1419    type !== "DECLINE_CARD_SAVE" &&1420    type !== "IS_CARD_DECLINED" &&1421    type !== "SUBMIT_FEEDBACK"1422  );1423}14241425function isAllowedCanaryWebhookUrl(value: string): boolean {1426  try {1427    const url = new URL(value);1428    if (url.protocol !== "https:") return false;14291430    const hostname = url.hostname.toLowerCase();1431    if (1432      hostname === "localhost" ||1433      hostname.endsWith(".localhost") ||1434      isPrivateIpv4(hostname) ||1435      isPrivateIpv6(hostname)1436    ) {1437      return false;1438    }14391440    return true;1441  } catch {1442    return false;1443  }1444}14451446function isPrivateIpv4(hostname: string): boolean {1447  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1448    return true;1449  }14501451  const octets = hostname.split(".").map((part) => Number(part));1452  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1453    return false;1454  }14551456  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1457}14581459function isPrivateIpv6(hostname: string): boolean {1460  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1461  return (1462    normalized === "::1" ||1463    normalized.startsWith("fc") ||1464    normalized.startsWith("fd") ||1465    normalized.startsWith("fe80:")1466  );1467}