messages.ts

59.2 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        const { domain, includeAll, kind } = msg.payload as {541          domain: string;542          includeAll?: boolean;543          kind?: "login" | "card" | "totp";544        };545        // kind="card": return saved cards as compact summaries for the546        // inline card silver platter. Cards are not domain-scoped — every547        // saved card is a candidate on every checkout page — so domain is548        // ignored when kind === "card".549        if (kind === "card") {550          const cards = vault.getEntries().filter((e) => e.type === "card");551          return {552            ok: true,553            data: cards.map((e) => ({554              id: e.id,555              title: e.cardNickname || e.title,556              cardholderName: e.cardholderName,557              last4: e.last4,558              expMonth: e.expMonth,559              expYear: e.expYear,560              network: e.network,561            })),562          };563        }564        if (kind === "totp") {565          const matches = (566            includeAll567              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")568              : vault.queryDomain(domain)569          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));570          return {571            ok: true,572            data: matches.map((e) => ({573              id: e.id,574              title: e.title,575              username: e.username,576              email: e.email,577              url: e.url,578              hasTotp: true,579            })),580          };581        }582        // The inline selector fills username+password into a form. Passkey-583        // only entries have no password to fill; sign-in for those goes584        // through the WebAuthn path instead. Filter them out everywhere so585        // the user doesn't see four "GitHub" rows that mostly do nothing.586        // Notes and cards never belonged here either.587        const matches = (588          includeAll589            ? vault590                .getEntries()591                .filter((entry) => entry.type !== "note" && entry.type !== "card")592            : vault.queryDomain(domain)593        ).filter((entry) => !isPasskeyOnly(entry));594        return {595          ok: true,596          data: matches.map((e) =>597            includeAll598              ? {599                  id: e.id,600                  title: e.title,601                  // username/email/url shipped so the inline popup's search602                  // affordance can match on them, not just titles. No secrets603                  // cross the boundary — same shape as the domain-matched604                  // response below minus hasTotp (which the search list605                  // doesn't surface).606                  username: e.username,607                  email: e.email,608                  url: e.url,609                  hasPasskey: e.passkey !== undefined,610                }611              : {612                  id: e.id,613                  title: e.title,614                  username: e.username,615                  email: e.email,616                  url: e.url,617                  hasTotp: Boolean(e.totp),618                  hasPasskey: e.passkey !== undefined,619                }620          ),621        };622      }623      case "GET_ENTRY_FOR_FILL": {624        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };625        const { id, explicitSummon } = msg.payload as {626          id: string;627          explicitSummon?: boolean;628        };629        const entry = vault.getEntryById(id);630        if (!entry) return { ok: false, error: "entry_not_found" };631        // Passkey-only entries (passkey credential, no password) cannot be632        // filled into a form — sign-in goes through the WebAuthn path. A633        // login that ALSO has a passkey is still fillable for its password.634        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };635636        // MV-1: re-validate the entry against the requesting tab's origin.637        // sender.tab.url is browser-attested — a page cannot forge it. When638        // the request does not come from a tab at all (popup surfaces use639        // GET_ENTRY_FOR_EDIT, not this), refuse.640        if (sender.tab !== undefined || sender.url !== undefined) {641          let senderDomain: string | null = null;642          try {643            const rawUrl = sender.tab?.url ?? sender.url ?? "";644            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;645          } catch {646            senderDomain = null;647          }648          if (!senderDomain) return { ok: false, error: "origin_unverified" };649650          const entryDomains = new Set<string>();651          const primary = extractDomain(entry.url ?? "");652          if (primary) entryDomains.add(primary);653          for (const extra of entry.additionalUrls ?? []) {654            const d = extractDomain(extra);655            if (d) entryDomains.add(d);656          }657658          // explicitSummon=true means the user actively picked this entry659          // from the cross-domain search affordance — an intentional660          // off-domain fill. Passive fill paths must stay domain-bound.661          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {662            // Domain mismatch — refuse silently (no oracle about which ids exist).663            return { ok: false, error: "entry_not_found" };664          }665        }666        // Strip the passkey credential AND the raw base32 TOTP seed from the667        // response. Content scripts never need either: the private key is the668        // authenticator's, and handing over the TOTP seed would let a669        // compromised content script mint valid codes indefinitely (SEV-3-C).670        // Generate the *current* 6-digit code here in the background and send671        // only that, plus the seconds left so the UI can render a countdown.672        // Also drop passwordHistory: filling needs only the *current* password.673        // Handing every past password to a content script during passive674        // autofill on an arbitrary page would widen the blast radius of a675        // compromised page far beyond the one credential being filled.676        const { passkey: _strippedPasskey, totp: seed, passwordHistory: _ph, ...safeEntry } = entry;677        let totpCode: string | undefined;678        let totpRemaining: number | undefined;679        if (seed) {680          try {681            const generated = generateTOTP(seed);682            totpCode = generated.code;683            totpRemaining = generated.remaining;684          } catch {685            totpCode = undefined;686          }687        }688        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };689      }690      // Trusted full-entry fetch for Peach's own inline-popup surfaces that691      // genuinely need the raw TOTP seed: the edit form (which re-saves the692      // seed and would otherwise wipe it) and nothing else. Unlike693      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside694      // the inline popup, never during passive autofill on an arbitrary page.695      // The passkey credential is still stripped — the edit form never touches it.696      case "GET_ENTRY_FOR_EDIT": {697        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };698        const { id } = msg.payload as { id: string };699        const entry = vault.getEntryById(id);700        if (!entry) return { ok: false, error: "entry_not_found" };701        const { passkey: _passkey, ...safeEntry } = entry;702        return { ok: true, data: safeEntry };703      }704      case "COPY": {705        // AUD-002: shape-validate the payload before passing to the clipboard706        // helper. A raw cast lets a malformed message reach the clipboard API707        // with a non-string and throw.708        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {709          text?: unknown;710          label?: unknown;711          alreadyWritten?: unknown;712        };713        if (typeof text !== "string" || typeof label !== "string") {714          return { ok: false, error: "invalid_payload" };715        }716        await copyToClipboard(text, label, Boolean(alreadyWritten));717        return { ok: true };718      }719      case "CHECK_ALL_BREACHES": {720        const allEntries = vault.getEntries();721        const results: Record<string, number> = {};722        for (const entry of allEntries) {723          if (entry.type === "note") continue;724          if (!entry.password) continue;725          results[entry.id] = await vault.checkBreach(entry.password);726          // Small delay — be a good citizen to the HIBP API727          await new Promise((r) => setTimeout(r, 200));728        }729        // Persist any non-zero counts back to entries730        for (const [id, count] of Object.entries(results)) {731          const entry = vault.getEntryById(id);732          if (entry && (entry.breach ?? 0) !== count) {733            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });734          }735        }736        return { ok: true, data: results };737      }738      case "GET_SETTINGS":739        return { ok: true, data: await vault.ensureSettingsLoaded() };740      case "UPDATE_SETTINGS": {741        const patch = msg.payload;742        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {743          return { ok: false, error: "invalid_payload" };744        }745        await vault.updateSettings(patch as vault.VaultSettings);746        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {747          await setupAutoLock();748          if (vault.isUnlocked()) touchAutoLock();749        }750        return { ok: true };751      }752      case "GET_PENDING_PASSKEY":753        return { ok: true, data: await getPendingPasskeyRequest() };754      case "APPROVE_PASSKEY": {755        const { requestId } = msg.payload as { requestId: number };756        await resolvePendingPasskeyRequest(requestId, true);757        return { ok: true };758      }759      case "DENY_PASSKEY": {760        const { requestId } = msg.payload as { requestId: number };761        await resolvePendingPasskeyRequest(requestId, false);762        return { ok: true };763      }764      case "GET_PASSKEY_PROVIDER_STATE":765        return { ok: true, data: await getPasskeyProviderState() };766      case "SET_PASSKEY_PROVIDER_ENABLED": {767        const { enabled } = msg.payload as { enabled: boolean };768        // Disabling is always free; gating fires only when a free user is769        // trying to turn passkey interception on.770        if (enabled) {771          const gate = await requirePro("passkeys");772          if (!gate.allowed) return { ok: false, error: "pro_required" };773        }774        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };775      }776      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS777      // endpoint. Intentional product behavior — users configure their own778      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private779      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-780      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to781      // users that the entry title leaves the device when the canary fires.782      case "FIRE_CANARY_PING": {783        // Canary alert fires unconditionally for any entry with canary: true.784        // The Pro gate only governs creation/flagging of canary entries; once785        // an entry is flagged, the alert path is a security property and must786        // never be license-gated.787        const { webhookUrl, entryTitle, trigger } = msg.payload as {788          webhookUrl: string;789          entryTitle: string;790          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";791        };792        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {793          return { ok: false, error: "invalid_webhook_url" };794        }795        const body = JSON.stringify({796          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",797          entry: entryTitle,798          trigger,799          timestamp: new Date().toISOString(),800          source: "peach-extension",801        });802        if (trigger === "test") {803          // Permitted outbound fetch: user-configured canary alert endpoint804          // (validated by isAllowedCanaryWebhookUrl above). This is the805          // only non-HIBP outbound call in the extension — see806          // Projects.md §3.7. Test pings are awaited so the UI can show807          // success/failure.808          try {809            const res = await fetch(webhookUrl, {810              method: "POST",811              headers: { "Content-Type": "application/json" },812              body,813            });814            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };815          } catch (err) {816            return { ok: false, error: err instanceof Error ? err.message : "network_error" };817          }818        }819        // Non-test triggers are fire-and-forget820        fetch(webhookUrl, {821          method: "POST",822          headers: { "Content-Type": "application/json" },823          body,824        }).catch(() => {});825        return { ok: true };826      }827      case "ACTIVATE_LICENSE": {828        const { key } = msg.payload as { key: string };829        const licenseInfo = await activateLicense(key);830        return { ok: true, data: licenseInfo };831      }832      case "GET_LICENSE": {833        const licenseInfo = await getLicenseInfo();834        return { ok: true, data: licenseInfo };835      }836      case "GET_LICENSE_KEY": {837        const key = await getLicenseKey();838        return { ok: true, data: key };839      }840      case "DEACTIVATE_LICENSE": {841        await deactivateLicense();842        return { ok: true };843      }844      case "SHOULD_PLAY_CELEBRATION": {845        const should = await shouldPlayCelebration();846        return { ok: true, data: should };847      }848      case "MARK_CELEBRATION_PLAYED": {849        await markCelebrationPlayed();850        return { ok: true };851      }852      case "GET_CODEX_VAULT_DATA": {853        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the854        // popup navigates to the License section without further coordination.855        const gate = await requirePro("codex");856        if (!gate.allowed) return { ok: false, error: "pro_required" };857        return await handleGetCodexVaultData();858      }859      case "ESTIMATE_CODEX_PAGES": {860        const gate = await requirePro("codex");861        if (!gate.allowed) return { ok: false, error: "pro_required" };862        return await handleEstimateCodexPages();863      }864      case "RESTORE_FROM_CODEX": {865        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still866        // be able to restore a vault that was printed by a Pro user.867        // DO NOT add a Pro gate here.868        const payload = msg.payload as CodexRestorePayload;869        return await handleRestoreFromCodex(payload);870      }871      case "OPEN_PRO_GATE": {872        // Content script requests: open popup and navigate to License section.873        const { feature } = (msg.payload ?? {}) as { feature?: string };874        if (chrome.storage.session) {875          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });876        }877        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }878        return { ok: true };879      }880      case "OPEN_POPUP": {881        // Content script asks to open the trusted extension popup — used by the882        // inline locked bubble so the master password is entered in the popup,883        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a884        // user gesture + Chrome 127+/Firefox; on failure the user clicks the885        // toolbar icon. The badge already signals Peach needs attention.886        //887        // Set a session flag so the popup knows it was opened for inline unlock888        // and should close itself once the vault is unlocked (returning the user889        // to the inline autofill selector on the page).890        if (chrome.storage.session) {891          await chrome.storage.session.set({ peach_inline_unlock: true });892        }893        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }894        return { ok: true };895      }896      case "GET_IDENTITIES": {897        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };898        return { ok: true, data: vault.getIdentities() };899      }900      case "TOUCH_AUTO_LOCK": {901        // touchAutoLock() is already called by shouldRefreshAutoLock above;902        // this case just gives the popup a typed message to keep the session alive.903        return { ok: true };904      }905      case "GET_ADVANCED_HEALTH_REPORT": {906        const gate = await requirePro("advanced_health");907        if (!gate.allowed) return { ok: false, error: "pro_required" };908        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };909        const report = await buildAdvancedHealthReport(vault.getEntries());910        return { ok: true, data: report };911      }912      case "IS_DURESS_ENABLED": {913        const enabled = await vault.isDuressEnabled();914        return { ok: true, data: enabled };915      }916      case "SETUP_DURESS": {917        // Single enforcement point for the Duress Vault Pro gate. Free users918        // who somehow reach this handler are rejected here; the popup also919        // pre-checks isPro() to avoid showing the setup form to free users,920        // but server-side is the actual security boundary.921        const gate = await requirePro("duress_vault");922        if (!gate.allowed) return { ok: false, error: "pro_required" };923        // MV3 service workers restart after inactivity, losing the in-memory924        // derived key. Detect this before calling setupDuress so the popup925        // can show a meaningful prompt to re-lock and re-unlock.926        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };927        const { duressPassword } = msg.payload as { duressPassword: string };928        await vault.setupDuress(duressPassword);929        return { ok: true };930      }931      case "DISABLE_DURESS": {932        await vault.disableDuress();933        return { ok: true };934      }935      case "VERIFY_MAIN_PASSWORD": {936        const { password } = msg.payload as { password: string };937        const ok = await vault.verifyMainPassword(password);938        return { ok: true, data: ok };939      }940      case "CHANGE_PASSWORD": {941        const { currentPassword, newPassword } = msg.payload as {942          currentPassword: string;943          newPassword: string;944        };945        const changed = await vault.changePassword(currentPassword, newPassword);946        return changed947          ? { ok: true }948          : { ok: false, error: "incorrect_current_password" };949      }950      case "GET_SITE_PASSWORD_POLICY": {951        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });952        if (!tab?.id) return { ok: true, data: null };953        try {954          const response = await chrome.tabs.sendMessage(tab.id, {955            type: "GET_SITE_PASSWORD_POLICY",956          });957          return (response as MessageResponse) ?? { ok: true, data: null };958        } catch {959          return { ok: true, data: null };960        }961      }962      case "RECORD_MANUAL_SUMMON": {963        const { domain } = msg.payload as { domain: string };964        const settings = vault.getSettings();965        const existing = settings.manualSummonDomains?.[domain];966        const now = Date.now();967        await vault.updateSettings({968          manualSummonDomains: {969            ...settings.manualSummonDomains,970            [domain]: {971              firstSummonedAt: existing?.firstSummonedAt ?? now,972              summonCount: (existing?.summonCount ?? 0) + 1,973              lastSummonedAt: now,974            },975          },976        });977        return { ok: true };978      }979      case "DECLINE_CARD_SAVE": {980        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };981        await vault.declineCardSaveOffer(last4, expMonth, expYear);982        return { ok: true };983      }984      case "IS_CARD_DECLINED": {985        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };986        const declined = await vault.isCardDeclined(last4, expMonth, expYear);987        return { ok: true, data: declined };988      }989      case "INITIATE_FIREFOX_PASSKEY_CREATE": {990        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {991          rpId?: string;992          rpName?: string;993          userName?: string;994          userDisplayName?: string;995        };996        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };997        return await initiateFirefoxPasskeyCreate({998          rpId,999          rpName: rpName ?? rpId,1000          userName,1001          userDisplayName,1002        });1003      }10041005      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1006        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1007        if (!payload) return { ok: false, error: "missing_payload" };1008        return await completeFirefoxPasskeyCreate(payload);1009      }10101011      case "PASSKEY_OFFER_DECLINE": {1012        const { domain } = (msg.payload ?? {}) as { domain?: string };1013        if (!domain) return { ok: false, error: "domain_required" };1014        await recordPasskeyOfferDecline(domain);1015        return { ok: true };1016      }10171018      case "GET_PASSKEY_OFFER_DECLINED": {1019        const { domain } = (msg.payload ?? {}) as { domain?: string };1020        if (!domain) return { ok: false, error: "domain_required" };1021        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1022      }10231024      case "PASSKEY_HAS_CREDENTIALS": {1025        const payload = msg.payload as {1026          rpId?: string;1027          allowCredentials?: Array<{ id: string; type?: string }>;1028        } | undefined;1029        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1030        return await handlePasskeyHasCredentials({1031          rpId: payload.rpId,1032          allowCredentials: payload.allowCredentials ?? [],1033        }, attestedSenderOrigin(sender));1034      }10351036      case "PASSKEY_CREATE": {1037        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1038        if (!payload?.rpId || !payload?.userName) {1039          return { ok: false, error: "rpid_and_username_required" };1040        }1041        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1042      }10431044      case "PASSKEY_GET": {1045        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1046        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1047        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1048      }10491050      case "PASSKEY_AUTH_RESPONSE": {1051        const { requestId, approved } = (msg.payload ?? {}) as {1052          requestId?: string | number;1053          approved?: boolean;1054        };1055        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1056          return { ok: false, error: 'requestId and approved required' };1057        }1058        await resolvePendingPasskeyRequest(Number(requestId), approved);1059        return { ok: true };1060      }10611062      case "GET_PASSKEY_FOR_DOMAIN": {1063        const { domain } = (msg.payload ?? {}) as { domain?: string };1064        if (!domain) return { ok: false, error: "domain_required" };1065        // Scope to the caller's own origin: a page may only ask about passkeys1066        // for a domain it actually owns, so an arbitrary page cannot enumerate1067        // which sites the user holds passkeys for or read the username (audit MEDIUM).1068        const origin = attestedSenderOrigin(sender);1069        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1070        if (!vault.isUnlocked()) return { ok: true, data: null };1071        const match = vault1072          .getEntries()1073          .find((entry) => entry.passkey?.rpId === domain);1074        if (!match || !match.passkey) return { ok: true, data: null };1075        // Slim shape — only the fields State 11 needs. Never expose private1076        // key material, even though this is locked behind isUnlocked.1077        return {1078          ok: true,1079          data: {1080            rpId: match.passkey.rpId,1081            userName: match.passkey.userName,1082            browser: match.passkey.browser,1083          },1084        };1085      }10861087      case "DESTROY_VAULT": {1088        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1089        // storage.local.clear() wipes every Peach key (slots, settings, license,1090        // onboarded flag, history, sync state, declined cards, recall, etc.);1091        // session.clear() wipes pending passkey requests + pro-notice queues.1092        // Caller (Panic.tsx) handles UI navigation back to onboarding.1093        //1094        // The Pro license is the one thing that must survive: the user paid for1095        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1096        // Capture it before the clear and restore it after. peach_pro_celebrated1097        // rides along so the Pro celebration doesn't replay on the next unlock.1098        const preserved = await chrome.storage.local.get([1099          "peach_license",1100          "peach_pro_celebrated",1101        ]);1102        vault.lock();1103        await storageClear();1104        await vault.clearVaultHistory();1105        const toRestore: Record<string, unknown> = {};1106        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1107        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1108        if (Object.keys(toRestore).length > 0) {1109          await chrome.storage.local.set(toRestore);1110        }1111        if (chrome.storage.session) {1112          await chrome.storage.session.clear();1113        }1114        return { ok: true };1115      }11161117      case "SUBMIT_FEEDBACK": {1118        const { category, message, version, browser } = msg.payload as {1119          category: string;1120          message: string;1121          version: string;1122          browser: string;1123        };1124        if (!message.trim()) return { ok: false, error: "message_empty" };1125        if (!FEEDBACK_ENDPOINT) return { ok: true };1126        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1127          return { ok: false, error: "invalid_feedback_endpoint" };1128        }1129        try {1130          const res = await fetch(FEEDBACK_ENDPOINT, {1131            method: "POST",1132            headers: { "Content-Type": "application/json" },1133            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1134          });1135          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1136        } catch (err) {1137          return { ok: false, error: err instanceof Error ? err.message : "network_error" };1138        }1139      }1140      // Android-only: biometric unlock with pre-derived key.1141      case "UNLOCK_WITH_KEY": {1142        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1143        if (!isNativePlatform()) {1144          return { ok: false, error: "desktop_only_uses_password" };1145        }1146        try {1147          const result = await vault.unlockWithKey(masterKeyHex);1148          if (result.ok) {1149            onVaultUnlocked();1150            await publishInMemoryVault(result.entries);1151          }1152          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1153        } catch {1154          return { ok: false, error: "invalid_key" };1155        }1156      }1157      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1158      case "GET_DERIVED_KEY": {1159        if (!isNativePlatform()) {1160          return { ok: false, error: "android_only" };1161        }1162        if (!vault.isUnlocked()) {1163          return { ok: false, error: "vault_locked" };1164        }1165        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1166      }1167      case "GET_IDENTITY_SUGGESTIONS": {1168        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1169        const entries = vault.getEntries();1170        const suggestions = buildIdentitySuggestions(entries);1171        return { ok: true, data: { suggestions } };1172      }1173      case "POPULATE_INLINE_VAULT": {1174        if (!isNativePlatform()) return { ok: false };1175        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1176        const entries = vault.getEntries();1177        await publishInMemoryVault(entries);1178        return { ok: true };1179      }1180      case "ML_INIT":1181        return { ok: true };11821183      case "ML_PREDICT_BATCH": {1184        // AUD-002: shape-validate before forwarding to the ML helper.1185        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1186        if (!Array.isArray(featuresArray)) {1187          return { ok: false, error: "invalid_payload" };1188        }1189        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1190      }11911192      // ── Chirp Sync (v3) ───────────────────────────────────────────────1193      // Returns the public-facing local identity needed by the popup to1194      // drive Phase-1 audio pairing. The private long-term key never1195      // leaves the background.1196      case "CHIRP_GET_LOCAL_IDENTITY": {1197        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1198        const proCheck = await requirePro("sync");1199        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1200        // Identity derives from the stable root key, not the password-derived1201        // key, so pairing survives a master-password change (SEV-2-B).1202        const masterKeyHex = vault.getRootKeyHex();1203        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1204        const masterKey = unhexBytes(masterKeyHex);1205        try {1206          const identity = await buildLocalIdentity(masterKey);1207          return { ok: true, data: identity };1208        } finally {1209          masterKey.fill(0);1210        }1211      }12121213      case "CHIRP_COMPLETE_PAIRING": {1214        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1215        const proCheck = await requirePro("sync");1216        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1217        const paired = (msg.payload as { paired?: unknown })?.paired;1218        if (typeof paired !== "object" || paired === null) {1219          return { ok: false, error: "invalid_payload" };1220        }1221        const candidate = paired as Record<string, unknown>;1222        if (1223          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1224          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1225          typeof candidate.deviceType !== "string" ||1226          typeof candidate.longTermPublicKeyHex !== "string" ||1227          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1228          (1229            candidate.signingPublicKeyHex !== undefined &&1230            (1231              typeof candidate.signingPublicKeyHex !== "string" ||1232              !/^[0-9a-f]{64}$/.test(candidate.signingPublicKeyHex)1233            )1234          ) ||1235          typeof candidate.pairedAt !== "number"1236        ) {1237          return { ok: false, error: "invalid_paired_device" };1238        }1239        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1240        return { ok: true };1241      }12421243      case "CHIRP_LIST_PAIRED_DEVICES": {1244        const devices = await listPairedDevicesV3();1245        return { ok: true, data: { devices } };1246      }12471248      case "CHIRP_UNPAIR_DEVICE": {1249        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1250        if (typeof deviceId !== "string" || !deviceId) {1251          return { ok: false, error: "invalid_payload" };1252        }1253        await removePairedDeviceByIdV3(deviceId);1254        return { ok: true };1255      }12561257      case "CHIRP_RENAME_LOCAL_DEVICE": {1258        const { name } = (msg.payload ?? {}) as { name?: string };1259        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1260        await setDeviceNameV3(name);1261        return { ok: true };1262      }12631264      case "TRIGGER_SYNC": {1265        const payload = (msg.payload ?? {}) as {1266          reason?: "vault_change" | "foreground" | "manual" | "mdns";1267          force?: boolean;1268          deviceId?: string;1269          discoveredIp?: string;1270          discoveredPort?: number;1271        };1272        const reason = payload.reason ?? "foreground";12731274        // mDNS discovery delivers a fresh (ip, port) resolved by the native1275        // side. Update the cached address before the sync runner tries to1276        // connect — avoids a subnet probe on the very next round.1277        if (1278          reason === "mdns" &&1279          typeof payload.deviceId === "string" &&1280          typeof payload.discoveredIp === "string"1281        ) {1282          const { findPairedDeviceById, setLastKnownIp } = await import("./paired-devices");1283          const device = await findPairedDeviceById(payload.deviceId);1284          if (device?.longTermPublicKeyHex) {1285            await setLastKnownIp(device.longTermPublicKeyHex, payload.discoveredIp).catch(() => undefined);1286          }1287        }12881289        const { triggerSyncIfReachable } = await import("./sync-trigger");1290        void triggerSyncIfReachable({ reason, force: payload.force === true });1291        return { ok: true };1292      }12931294      case "GET_SYNC_STATE": {1295        const { getSyncState } = await import("./sync-trigger");1296        return { ok: true, data: getSyncState() };1297      }12981299      case "GET_SYNC_ALERTS": {1300        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1301        const alerts = await getPendingSyncAlerts();1302        // The popup reads on open and acknowledges with consume:true after1303        // rendering, so a popup crash between read and render doesn't lose1304        // the alerts.1305        if (consume) await clearPendingSyncAlerts();1306        return { ok: true, data: alerts };1307      }13081309      default:1310        return { ok: false, error: "unknown_message_type" };1311    }1312  } catch (err) {1313    return {1314      ok: false,1315      error: err instanceof Error ? err.message : "operation_failed",1316    };1317  }1318}13191320// --- Mobile platform helpers ---13211322// Android: populates the in-memory vault used by PeachAutofillService.1323async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1324  const plugin = nativePlugin<{1325    setEntries?: (args: {1326      entries: Array<{1327        id: string;1328        title: string;1329        username: string;1330        email: string;1331        password: string;1332        url: string;1333        totp: string;1334        additionalUrls: string[];1335      }>;1336    }) => Promise<void>;1337  }>("InMemoryVaultPlugin");1338  if (!plugin?.setEntries) return;1339  await plugin.setEntries({1340    entries: entries.map((e) => ({1341      id: e.id,1342      title: e.title ?? "",1343      username: e.username ?? "",1344      email: (e as VaultEntry & { email?: string }).email ?? "",1345      password: e.password ?? "",1346      url: e.url ?? "",1347      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1348      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1349    })),1350  });1351}13521353// Android: clear the autofill in-memory store on lock.1354async function clearInMemoryVault(): Promise<void> {1355  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1356  if (!plugin?.clearEntries) return;1357  await plugin.clearEntries();1358}13591360// Returns username use-counts from the vault, sorted by frequency. Each row1361// also carries the entry's email so the popup can suggest the email/username1362// pair the user has actually used together.1363function buildIdentitySuggestions(1364  entries: VaultEntry[],1365): Array<{ email: string; username: string; count: number }> {1366  const usernameCounts = new Map<string, number>();1367  const usernameEmail = new Map<string, string>();1368  for (const entry of entries) {1369    const username = entry.username ?? "";1370    const email = (entry as VaultEntry & { email?: string }).email ?? "";1371    if (!username && !email) continue;1372    const key = username || email;1373    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1374    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1375  }1376  return Array.from(usernameCounts.entries())1377    .sort((a, b) => b[1] - a[1])1378    .map(([username, count]) => ({1379      email: usernameEmail.get(username) ?? "",1380      username,1381      count,1382    }));1383}13841385/** Notify all content scripts that the vault just became available. */1386function broadcastToContentScripts(message: { type: string }): void {1387  if (!chrome.tabs?.query) return;1388  chrome.tabs.query({}, (tabs) => {1389    for (const tab of tabs) {1390      if (tab.id !== undefined) {1391        chrome.tabs.sendMessage(tab.id, message).catch(() => {1392          // Tab may not have a content script — silently ignore1393        });1394      }1395    }1396  });1397}13981399function shouldRefreshAutoLock(type: MessageType): boolean {1400  return (1401    type !== "HAS_VAULT" &&1402    type !== "IS_UNLOCKED" &&1403    type !== "GET_VAULT_STATUS" &&1404    type !== "LOCK" &&1405    type !== "UPDATE_SETTINGS" &&1406    type !== "GET_PENDING_PASSKEY" &&1407    type !== "GET_PASSKEY_PROVIDER_STATE" &&1408    type !== "DECLINE_CARD_SAVE" &&1409    type !== "IS_CARD_DECLINED" &&1410    type !== "SUBMIT_FEEDBACK"1411  );1412}14131414function isAllowedCanaryWebhookUrl(value: string): boolean {1415  try {1416    const url = new URL(value);1417    if (url.protocol !== "https:") return false;14181419    const hostname = url.hostname.toLowerCase();1420    if (1421      hostname === "localhost" ||1422      hostname.endsWith(".localhost") ||1423      isPrivateIpv4(hostname) ||1424      isPrivateIpv6(hostname)1425    ) {1426      return false;1427    }14281429    return true;1430  } catch {1431    return false;1432  }1433}14341435function isPrivateIpv4(hostname: string): boolean {1436  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1437    return true;1438  }14391440  const octets = hostname.split(".").map((part) => Number(part));1441  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1442    return false;1443  }14441445  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1446}14471448function isPrivateIpv6(hostname: string): boolean {1449  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1450  return (1451    normalized === "::1" ||1452    normalized.startsWith("fc") ||1453    normalized.startsWith("fd") ||1454    normalized.startsWith("fe80:")1455  );1456}