messages.ts

61.4 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard } from "./clipboard";13import { getPendingSyncAlerts, clearPendingSyncAlerts } from "./sync-alerts";14import { extractDomain } from "../shared/domain";15import {16  getPendingVouchedDevice,17  listPendingVouchedDevices,18  removePendingVouchedDevice,19} from "./pending-vouched-devices";20import { setupAutoLock, touchAutoLock } from "./alarms";21import { runSelfTest } from "./self-test";22import * as vault from "./vault";23import {24  handleEstimateCodexPages,25  handleGetCodexVaultData,26  handleRestoreFromCodex,27} from "./codex-handlers";28import type { CodexRestorePayload } from "../shared/codex-types";29import {30  activateLicense,31  deactivateLicense,32  getLicenseInfo,33  getLicenseKey,34  isProUser,35  markCelebrationPlayed,36  shouldPlayCelebration,37} from "./license";38import {39  completeFirefoxPasskeyCreate,40  getPasskeyProviderState,41  getPendingPasskeyRequest,42  handleFirefoxPasskeyCreate,43  handleFirefoxPasskeyGet,44  handlePasskeyHasCredentials,45  initiateFirefoxPasskeyCreate,46  isPasskeyOfferDeclined,47  onVaultUnlocked,48  recordPasskeyOfferDecline,49  resolvePendingPasskeyRequest,50  setPasskeyProviderEnabled,51} from "./passkey";52import { buildAdvancedHealthReport } from "./health";53import { storageClear } from "../shared/storage";54import { findInvalidWords } from "../shared/recovery-words";55import type {56  Message,57  MessageResponse,58  MessageType,59  ProFeature,60  VaultEntry,61} from "../shared/types";62import { isPasskeyOnly } from "../shared/types";63import { generateTOTP } from "../crypto/totp";64import { isValidRpId } from "../shared/passkey-utils";65import { isNativePlatform, nativePlugin } from "../shared/native";66import { predictBatch as mlPredictBatch } from "./ml";67import type { MLFieldFeatures } from "../shared/ml";68import { buildLocalIdentity, setDeviceName as setDeviceNameV3 } from "./chirp-identity";69import {70  listPairedDevices as listPairedDevicesV3,71  removePairedDeviceById as removePairedDeviceByIdV3,72  upsertPairedDevice as upsertPairedDeviceV3,73} from "./paired-devices";7475// Compile-time E2E flag, folded to a literal by Vite's `define` (false in76// every production build — verified in the bundled output). Mirrors the77// create-path bypass in passkey.ts so the Playwright passkey smoke can enable78// the provider without a real Pro licence; the gate is fully intact for users.79declare const __PEACH_E2E_PASSKEYS__: boolean;80const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true;8182let nativeSyncRunnerBootstrapped = false;8384function unhexBytes(hex: string): Uint8Array {85  if (hex.length % 2 !== 0) throw new Error("invalid hex");86  const out = new Uint8Array(hex.length / 2);87  for (let i = 0; i < out.length; i++) {88    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);89  }90  return out;91}9293/**94 * The single Pro gate. Every gated handler calls this first; the broadcast95 * lets the popup react (navigate to the License section, highlight the96 * relevant feature). Background never touches the popup view directly —97 * the popup owns navigation. See Projects.md "Pro gate rule".98 */99async function requirePro(100  feature: ProFeature,101  trigger: "user" | "background" = "user"102): Promise<{ allowed: boolean }> {103  if (PASSKEY_E2E_PRO_BYPASS && feature === "passkeys") return { allowed: true };104  if (await isProUser()) return { allowed: true };105106  if (trigger === "user") {107    // User deliberately triggered this feature — redirect the popup immediately.108    chrome.runtime109      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })110      .catch(() => {111        // Popup may be closed — the gate signal is best-effort.112      });113  } else {114    // Background trigger (e.g. passive sync initiation) — no popup is open.115    // Queue a notice so the next popup open shows a soft banner instead of116    // silently failing.117    if (chrome.storage.session) {118      chrome.storage.session119        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })120        .catch(() => {});121    }122  }123124  return { allowed: false };125}126127// ---------------------------------------------------------------------------128// Feedback submission target. Empty disables network submission while the UI129// continues to function as a no-op (the handler returns ok:true without130// calling fetch). When set, the URL is validated by131// `isAllowedCanaryWebhookUrl` before any request.132// ---------------------------------------------------------------------------133134const FEEDBACK_ENDPOINT = "";135136const PRIVATE_IPV4_RANGES = [137  { prefix: "10." },138  { prefix: "127." },139  { prefix: "169.254." },140  { prefix: "192.168." },141];142143export function setupMessageHandler(): void {144  chrome.runtime.onMessage.addListener(145    (msg: unknown, sender, sendResponse) => {146      if (!isMessage(msg)) {147        sendResponse({ ok: false, error: "invalid_message" });148        return true;149      }150      handleMessage(msg, sender)151        .then(sendResponse)152        .catch((err) =>153          sendResponse({154            ok: false,155            error: err instanceof Error ? err.message : String(err),156          })157        );158      return true;159    }160  );161162  // Android: the chrome shim queues sendMessage calls until this handler is163  // registered. Without this hookup, every message hangs on Capacitor builds.164  // eslint-disable-next-line @typescript-eslint/no-explicit-any165  const reg = (globalThis as any).__peachRegisterMessageHandler;166  if (typeof reg === "function") {167    reg(async (m: unknown) => {168      if (!isMessage(m)) return { ok: false, error: "invalid_message" };169      try {170        return await handleMessage(m);171      } catch (err) {172        return {173          ok: false,174          error: err instanceof Error ? err.message : String(err),175        };176      }177    });178  }179  if (isNativePlatform()) {180    void bootstrapNativeSyncRunner();181  }182}183184async function bootstrapNativeSyncRunner(): Promise<void> {185  if (nativeSyncRunnerBootstrapped) return;186  nativeSyncRunnerBootstrapped = true;187  try {188    const { setSyncRunner, hydratePersistedSyncState } = await import("./sync-trigger");189    const { productionSyncRunner } = await import("./chirp-sync-runner");190    setSyncRunner(productionSyncRunner);191    await hydratePersistedSyncState();192  } catch (err) {193    nativeSyncRunnerBootstrapped = false;194    console.warn("[Peach] failed to bootstrap native sync runner:", err);195  }196}197198function isMessage(m: unknown): m is Message {199  return typeof m === "object" && m !== null && "type" in m;200}201202/**203 * The browser-attested origin of the page that originated this message. A web204 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),205 * so every page-driven message arrives via the content-script relay and the206 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a207 * value the page cannot forge. This is the ONLY trustworthy origin for passkey208 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.209 */210function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {211  if (sender.origin) return sender.origin;212  if (sender.url) {213    try { return new URL(sender.url).origin; } catch { return undefined; }214  }215  return undefined;216}217218// Resolves once restoreFromSession() has run, so handlers see the correct219// post-restore unlock state. entry.ts registers this BEFORE the message220// handler so the onMessage listener is added synchronously at SW startup221// (MV3 requirement) while unlock-dependent handlers still wait for restore.222let restoreReady: Promise<void> = Promise.resolve();223224/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */225export function setRestoreReady(p: Promise<unknown>): void {226  restoreReady = p.then(() => undefined, () => undefined);227}228229export async function handleMessage(230  msg: Message,231  sender: Partial<chrome.runtime.MessageSender> = {}232): Promise<MessageResponse> {233  try {234    // Wait for session-restore to finish before reading any unlock/vault state.235    // On a cold SW start the popup's first message arrives while restore is236    // still in flight; without this gate IS_UNLOCKED would report locked (a237    // spurious lock screen) and the storage reads could race. The onMessage238    // listener itself is registered synchronously (entry.ts) so this gate, not239    // listener registration, is what absorbs the cold-start window.240    await restoreReady;241    // Validate sender — only allow messages from our extension pages/scripts.242    // `sender.id` is undefined for messages originating from extension UI243    // (popup/options), which is legitimate; reject only when it is defined244    // and does not match our extension id.245    if (246      sender.id !== undefined &&247      sender.id !== chrome.runtime.id248    ) {249      return { ok: false, error: "invalid_sender" };250    }251252    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {253      touchAutoLock();254    }255256    switch (msg.type) {257      case "CREATE_VAULT": {258        const { password } = msg.payload as { password: string };259        // Refuse to create a vault under an empty master password — the derived260        // key would be publicly known and the at-rest AES-GCM protection void261        // (audit HIGH; the CSV-import path previously passed ""). Length/strength262        // policy lives in the onboarding UI; this is the non-negotiable floor.263        if (typeof password !== "string" || password.length === 0) {264          return { ok: false, error: "invalid_payload" };265        }266        await vault.createVault(password);267        await setupAutoLock();268        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });269        onVaultUnlocked();270        return { ok: true };271      }272      case "UNLOCK": {273        const { password } = msg.payload as { password: string };274        const ok = await vault.unlock(password);275        if (ok) {276          // KAT: verify the WebCrypto stack is healthy before the user relies on it.277          // Runs after unlock so latency is hidden behind the vault-load time.278          const kat = await runSelfTest();279          if (!kat.ok) {280            console.error("[Peach] Crypto self-test FAILED:", kat.error);281            await vault.lock();282            return { ok: false, error: "self_test_failed" };283          }284          await setupAutoLock();285          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });286          onVaultUnlocked();287          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());288          return { ok: true };289        }290        // Distinguish corruption from wrong password so the popup can offer291        // a history-restore path instead of falsely accusing the user of292        // mistyping (M7/COR-007).293        const failure = vault.consumeLastUnlockFailureReason();294        if (failure) {295          return {296            ok: false,297            error: "vault_corrupted",298            canRestoreFromHistory: true,299          } as MessageResponse;300        }301        return { ok: false };302      }303      case "VALIDATE_RECOVERY_WORDS": {304        const { words } = msg.payload as { words: string[] };305        const invalid = findInvalidWords(words);306        return { ok: true, data: { valid: invalid.length === 0, invalid } };307      }308      case "GET_RECOVERY_WORDS": {309        // Must be unlocked and have recovery set up (vault must be v2.12+).310        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };311        try {312          const words = await vault.getRecoveryWords();313          return { ok: true, data: words };314        } catch (e) {315          // pre-v2.12 vault that hasn't migrated316          return { ok: false, error: "recovery_not_setup" };317        }318      }319      case "RECOVER_WITH_WORDS": {320        // User has lost their password but has their 12 recovery words.321        // We: (1) validate the words, (2) re-encrypt vault with new password.322        const { words, newPassword } = msg.payload as {323          words: string[];324          newPassword: string;325        };326        const stored = await vault.loadSlotA();327        if (!stored) return { ok: false, error: "no_vault" };328        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {329          return { ok: false, error: "recovery_not_setup" };330        }331        // Unwrap the root key from the recovery escrow.332        try {333          await vault.unwrapRootKeyForRecovery(334            stored.recovery_wrapped_root_key,335            stored.recovery_nonce ?? "",336            stored.recovery_tag ?? "",337            stored.recovery_salt,338            words339          );340        } catch {341          return { ok: false, error: "invalid_recovery_words" };342        }343        // Re-key: derive fresh salt + key from new password.344        const newSalt = vault.generateSalt();345        const newKey = await vault.deriveKey(newPassword, newSalt);346        // Re-wrap root key under the new password's derived key so the same347        // recovery words continue to work after the password change.348        await vault.rewrapRootKeyForPassword(newKey, newSalt);349        // Re-encrypt vault entries with the new key.350        await vault.changePasswordWithNewKey(newSalt, newKey);351        await setupAutoLock();352        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });353        return { ok: true };354      }355      case "LOCK":356        vault.lock();357        if (isNativePlatform()) await clearInMemoryVault();358        return { ok: true };359      case "IS_UNLOCKED":360        return { ok: true, data: vault.isUnlocked() };361      case "GET_VAULT_STATUS":362        return { ok: true, unlocked: vault.isUnlocked() };363      case "HAS_VAULT":364        return { ok: true, data: await vault.hasVault() };365      case "GET_ENTRIES":366        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };367        return { ok: true, data: vault.getEntries() };368      case "ADD_ENTRY": {369        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };370        const payload = msg.payload;371        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {372          return { ok: false, error: "invalid_payload" };373        }374        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);375        return { ok: true, data: entry };376      }377      case "BATCH_ADD_ENTRIES": {378        const payload = msg.payload as { entries?: unknown } | null | undefined;379        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {380          return { ok: false, error: "invalid_payload" };381        }382        if (!Array.isArray(payload.entries)) {383          return { ok: false, error: "invalid_payload" };384        }385        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);386        return { ok: true, data: added };387      }388      case "RESTORE_ENTRIES": {389        const payload = msg.payload as390          | { entries?: unknown; mode?: unknown; settings?: unknown }391          | null392          | undefined;393        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {394          return { ok: false, error: "invalid_payload" };395        }396        if (!Array.isArray(payload.entries)) {397          return { ok: false, error: "invalid_payload" };398        }399        if (payload.mode !== "replace" && payload.mode !== "merge") {400          return { ok: false, error: "invalid_payload" };401        }402        const summary = await vault.restoreEntries(403          payload.entries as Parameters<typeof vault.restoreEntries>[0],404          payload.mode405        );406        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {407          await vault.updateSettings(payload.settings as vault.VaultSettings);408        }409        return { ok: true, data: summary };410      }411      case "CLEAR_VAULT_ENTRIES": {412        await vault.clearVaultEntries("REPLACE_ALL");413        return { ok: true };414      }415      case "GET_VAULT_HISTORY": {416        const snapshots = await vault.getVaultHistory();417        return { ok: true, data: snapshots };418      }419      case "RESTORE_VAULT_SNAPSHOT": {420        const { snapshotId } = msg.payload as { snapshotId: string };421        const result = await vault.restoreVaultSnapshot(snapshotId);422        if (!result.ok) return { ok: false, error: result.error };423        broadcastToContentScripts({ type: "VAULT_LOCKED" });424        return { ok: true };425      }426      case "COUNT_DUPLICATES": {427        return { ok: true, data: vault.countDuplicates() };428      }429      case "DEDUPLICATE_ENTRIES": {430        const removed = await vault.deduplicateEntries();431        return { ok: true, data: removed };432      }433      case "UPDATE_ENTRY": {434        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;435        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {436          return { ok: false, error: "invalid_payload" };437        }438        const { id, patch } = payload;439        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {440          return { ok: false, error: "invalid_payload" };441        }442        // Single enforcement point for the Canary Entries Pro gate. Only443        // gates the transition into a canary entry — clearing/disabling a444        // canary (`canary: undefined`) is always allowed, so existing445        // canary entries remain manageable.446        const incomingCanary = (patch as { canary?: unknown }).canary;447        if (incomingCanary && typeof incomingCanary === "object") {448          const existing = vault.getEntryById(id);449          if (!existing?.canary) {450            const gate = await requirePro("canary_entry");451            if (!gate.allowed) return { ok: false, error: "pro_required" };452          }453        }454        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);455        return { ok: true };456      }457      case "ADD_ADDITIONAL_URL": {458        const { id, url } = msg.payload as { id: string; url: string };459        const trimmed = typeof url === "string" ? url.trim() : "";460        if (!trimmed) return { ok: false, error: "url_required" };461        const existing = vault.getEntryById(id);462        if (!existing) return { ok: false, error: "entry_not_found" };463        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };464        const merged = [...(existing.additionalUrls ?? []), trimmed];465        await vault.updateEntry(id, { additionalUrls: merged });466        return { ok: true };467      }468      case "DELETE_ENTRY": {469        const { id } = msg.payload as { id: string };470        await vault.deleteEntry(id);471        return { ok: true };472      }473      case "GET_DELETED_ENTRIES":474        return { ok: true, data: vault.getDeletedEntries() };475      case "RESTORE_ENTRY": {476        const { id } = msg.payload as { id: string };477        await vault.restoreEntry(id);478        return { ok: true };479      }480      case "PURGE_ENTRY": {481        const { id } = msg.payload as { id: string };482        await vault.purgeEntry(id);483        return { ok: true };484      }485      case "PURGE_EXPIRED_TRASH": {486        const { retentionMs } = msg.payload as { retentionMs: number };487        const purged = await vault.purgeExpiredTrash(retentionMs);488        return { ok: true, data: purged };489      }490      case "SAVE_NOTE": {491        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };492        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };493        const now = Date.now();494        if (id) {495          const existing = vault.getEntryById(id);496          if (!existing) return { ok: false, error: "not_found" };497          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });498          return { ok: true, data: vault.getEntryById(id) };499        } else {500          const entry = await vault.addEntry({501            type: "note",502            title: title || "Untitled",503            notes: body,504            createdAt: now,505            modifiedAt: now,506          } as any);507          return { ok: true, data: entry };508        }509      }510      case "DELETE_NOTE": {511        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };512        const { id } = msg.payload as { id: string };513        await vault.deleteEntry(id);514        return { ok: true };515      }516      case "GET_NOTES": {517        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };518        const notes = vault.getEntries().filter(519          (e) => e.type === "note" && !e.deletedAt520        );521        return { ok: true, data: notes } as MessageResponse;522      }523      case "SEARCH_VAULT": {524        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };525        // AUD-002: shape-validate the payload before calling string methods.526        // A raw cast lets a malformed message crash the handler with TypeError.527        const { query } = (msg.payload ?? {}) as { query?: unknown };528        if (typeof query !== "string") {529          return { ok: false, error: "invalid_payload" };530        }531        const q = query.toLowerCase();532        const searchResults = vault.getEntries().filter(533          (e) =>534            !e.deletedAt &&535            (e.title.toLowerCase().includes(q) ||536              e.notes?.toLowerCase().includes(q) ||537              e.username?.toLowerCase().includes(q))538        );539        return { ok: true, data: searchResults } as MessageResponse;540      }541      case "AUTOFILL_QUERY": {542        if (!vault.isUnlocked()) {543          return { ok: false, error: "vault_locked" };544        }545        let { includeAll } = msg.payload as { includeAll?: boolean };546        const { domain, kind, userGesture } = msg.payload as {547          domain: string;548          kind?: "login" | "card" | "totp";549          userGesture?: boolean;550        };551        // MV-2: the vault-wide inventory (every title/username/email/url)552        // may only leave the background on an explicit user gesture — the553        // user opening the search affordance — never on passive form focus.554        // userGesture is self-declared by our own content script; the value555        // of this gate is that PASSIVE code paths (which never set it)556        // cannot ship the inventory, shrinking what a compromised page that557        // merely triggers focus events can observe.558        if (includeAll && userGesture !== true) {559          includeAll = false;560        }561        // kind="card": return saved cards as compact summaries for the562        // inline card silver platter. Cards are not domain-scoped — every563        // saved card is a candidate on every checkout page — so domain is564        // ignored when kind === "card".565        if (kind === "card") {566          const cards = vault.getEntries().filter((e) => e.type === "card");567          return {568            ok: true,569            data: cards.map((e) => ({570              id: e.id,571              title: e.cardNickname || e.title,572              cardholderName: e.cardholderName,573              last4: e.last4,574              expMonth: e.expMonth,575              expYear: e.expYear,576              network: e.network,577            })),578          };579        }580        if (kind === "totp") {581          const matches = (582            includeAll583              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")584              : vault.queryDomain(domain)585          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));586          return {587            ok: true,588            data: matches.map((e) => ({589              id: e.id,590              title: e.title,591              username: e.username,592              email: e.email,593              url: e.url,594              hasTotp: true,595            })),596          };597        }598        // The inline selector fills username+password into a form. Passkey-599        // only entries have no password to fill; sign-in for those goes600        // through the WebAuthn path instead. Filter them out everywhere so601        // the user doesn't see four "GitHub" rows that mostly do nothing.602        // Notes and cards never belonged here either.603        const matches = (604          includeAll605            ? vault606                .getEntries()607                .filter((entry) => entry.type !== "note" && entry.type !== "card")608            : vault.queryDomain(domain)609        ).filter((entry) => !isPasskeyOnly(entry));610        return {611          ok: true,612          data: matches.map((e) =>613            includeAll614              ? {615                  id: e.id,616                  title: e.title,617                  // username/email/url shipped so the inline popup's search618                  // affordance can match on them, not just titles. No secrets619                  // cross the boundary — same shape as the domain-matched620                  // response below minus hasTotp (which the search list621                  // doesn't surface).622                  username: e.username,623                  email: e.email,624                  url: e.url,625                  hasPasskey: e.passkey !== undefined,626                }627              : {628                  id: e.id,629                  title: e.title,630                  username: e.username,631                  email: e.email,632                  url: e.url,633                  hasTotp: Boolean(e.totp),634                  hasPasskey: e.passkey !== undefined,635                }636          ),637        };638      }639      case "GET_ENTRY_FOR_FILL": {640        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };641        const { id, explicitSummon } = msg.payload as {642          id: string;643          explicitSummon?: boolean;644        };645        const entry = vault.getEntryById(id);646        if (!entry) return { ok: false, error: "entry_not_found" };647        // Passkey-only entries (passkey credential, no password) cannot be648        // filled into a form — sign-in goes through the WebAuthn path. A649        // login that ALSO has a passkey is still fillable for its password.650        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };651652        // MV-1: re-validate the entry against the requesting tab's origin.653        // sender.tab.url is browser-attested — a page cannot forge it. When654        // the request does not come from a tab at all (popup surfaces use655        // GET_ENTRY_FOR_EDIT, not this), refuse.656        if (sender.tab !== undefined || sender.url !== undefined) {657          let senderDomain: string | null = null;658          try {659            const rawUrl = sender.tab?.url ?? sender.url ?? "";660            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;661          } catch {662            senderDomain = null;663          }664          if (!senderDomain) return { ok: false, error: "origin_unverified" };665666          const entryDomains = new Set<string>();667          const primary = extractDomain(entry.url ?? "");668          if (primary) entryDomains.add(primary);669          for (const extra of entry.additionalUrls ?? []) {670            const d = extractDomain(extra);671            if (d) entryDomains.add(d);672          }673674          // explicitSummon=true means the user actively picked this entry675          // from the cross-domain search affordance — an intentional676          // off-domain fill. Passive fill paths must stay domain-bound.677          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {678            // Domain mismatch — refuse silently (no oracle about which ids exist).679            return { ok: false, error: "entry_not_found" };680          }681        }682        // Strip the passkey credential AND the raw base32 TOTP seed from the683        // response. Content scripts never need either: the private key is the684        // authenticator's, and handing over the TOTP seed would let a685        // compromised content script mint valid codes indefinitely (SEV-3-C).686        // Generate the *current* 6-digit code here in the background and send687        // only that, plus the seconds left so the UI can render a countdown.688        // Also drop passwordHistory: filling needs only the *current* password.689        // Handing every past password to a content script during passive690        // autofill on an arbitrary page would widen the blast radius of a691        // compromised page far beyond the one credential being filled.692        const { passkey: _strippedPasskey, totp: seed, passwordHistory: _ph, ...safeEntry } = entry;693        let totpCode: string | undefined;694        let totpRemaining: number | undefined;695        if (seed) {696          try {697            const generated = generateTOTP(seed);698            totpCode = generated.code;699            totpRemaining = generated.remaining;700          } catch {701            totpCode = undefined;702          }703        }704        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };705      }706      // Trusted full-entry fetch for Peach's own inline-popup surfaces that707      // genuinely need the raw TOTP seed: the edit form (which re-saves the708      // seed and would otherwise wipe it) and nothing else. Unlike709      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside710      // the inline popup, never during passive autofill on an arbitrary page.711      // The passkey credential is still stripped — the edit form never touches it.712      case "GET_ENTRY_FOR_EDIT": {713        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };714        const { id } = msg.payload as { id: string };715        const entry = vault.getEntryById(id);716        if (!entry) return { ok: false, error: "entry_not_found" };717        const { passkey: _passkey, ...safeEntry } = entry;718        return { ok: true, data: safeEntry };719      }720      case "COPY": {721        // AUD-002: shape-validate the payload before passing to the clipboard722        // helper. A raw cast lets a malformed message reach the clipboard API723        // with a non-string and throw.724        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {725          text?: unknown;726          label?: unknown;727          alreadyWritten?: unknown;728        };729        if (typeof text !== "string" || typeof label !== "string") {730          return { ok: false, error: "invalid_payload" };731        }732        await copyToClipboard(text, label, Boolean(alreadyWritten));733        return { ok: true };734      }735      case "CHECK_ALL_BREACHES": {736        const allEntries = vault.getEntries();737        const results: Record<string, number> = {};738        for (const entry of allEntries) {739          if (entry.type === "note") continue;740          if (!entry.password) continue;741          results[entry.id] = await vault.checkBreach(entry.password);742          // Small delay — be a good citizen to the HIBP API743          await new Promise((r) => setTimeout(r, 200));744        }745        // Persist any non-zero counts back to entries746        for (const [id, count] of Object.entries(results)) {747          const entry = vault.getEntryById(id);748          if (entry && (entry.breach ?? 0) !== count) {749            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });750          }751        }752        return { ok: true, data: results };753      }754      case "GET_SETTINGS":755        return { ok: true, data: await vault.ensureSettingsLoaded() };756      case "UPDATE_SETTINGS": {757        const patch = msg.payload;758        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {759          return { ok: false, error: "invalid_payload" };760        }761        await vault.updateSettings(patch as vault.VaultSettings);762        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {763          await setupAutoLock();764          if (vault.isUnlocked()) touchAutoLock();765        }766        return { ok: true };767      }768      case "GET_PENDING_PASSKEY":769        return { ok: true, data: await getPendingPasskeyRequest() };770      case "APPROVE_PASSKEY": {771        const { requestId } = msg.payload as { requestId: number };772        await resolvePendingPasskeyRequest(requestId, true);773        return { ok: true };774      }775      case "DENY_PASSKEY": {776        const { requestId } = msg.payload as { requestId: number };777        await resolvePendingPasskeyRequest(requestId, false);778        return { ok: true };779      }780      case "GET_PASSKEY_PROVIDER_STATE":781        return { ok: true, data: await getPasskeyProviderState() };782      case "SET_PASSKEY_PROVIDER_ENABLED": {783        const { enabled } = msg.payload as { enabled: boolean };784        // Disabling is always free; gating fires only when a free user is785        // trying to turn passkey interception on.786        if (enabled) {787          const gate = await requirePro("passkeys");788          if (!gate.allowed) return { ok: false, error: "pro_required" };789        }790        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };791      }792      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS793      // endpoint. Intentional product behavior — users configure their own794      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private795      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-796      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to797      // users that the entry title leaves the device when the canary fires.798      case "FIRE_CANARY_PING": {799        // Canary alert fires unconditionally for any entry with canary: true.800        // The Pro gate only governs creation/flagging of canary entries; once801        // an entry is flagged, the alert path is a security property and must802        // never be license-gated.803        const { webhookUrl, entryTitle, trigger } = msg.payload as {804          webhookUrl: string;805          entryTitle: string;806          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";807        };808        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {809          return { ok: false, error: "invalid_webhook_url" };810        }811        const body = JSON.stringify({812          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",813          entry: entryTitle,814          trigger,815          timestamp: new Date().toISOString(),816          source: "peach-extension",817        });818        if (trigger === "test") {819          // Permitted outbound fetch: user-configured canary alert endpoint820          // (validated by isAllowedCanaryWebhookUrl above). This is the821          // only non-HIBP outbound call in the extension — see822          // Projects.md §3.7. Test pings are awaited so the UI can show823          // success/failure.824          try {825            const res = await fetch(webhookUrl, {826              method: "POST",827              headers: { "Content-Type": "application/json" },828              body,829            });830            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };831          } catch (err) {832            return { ok: false, error: err instanceof Error ? err.message : "network_error" };833          }834        }835        // Non-test triggers are fire-and-forget836        fetch(webhookUrl, {837          method: "POST",838          headers: { "Content-Type": "application/json" },839          body,840        }).catch(() => {});841        return { ok: true };842      }843      case "ACTIVATE_LICENSE": {844        const { key } = msg.payload as { key: string };845        const licenseInfo = await activateLicense(key);846        return { ok: true, data: licenseInfo };847      }848      case "GET_LICENSE": {849        const licenseInfo = await getLicenseInfo();850        return { ok: true, data: licenseInfo };851      }852      case "GET_LICENSE_KEY": {853        const key = await getLicenseKey();854        return { ok: true, data: key };855      }856      case "DEACTIVATE_LICENSE": {857        await deactivateLicense();858        return { ok: true };859      }860      case "SHOULD_PLAY_CELEBRATION": {861        const should = await shouldPlayCelebration();862        return { ok: true, data: should };863      }864      case "MARK_CELEBRATION_PLAYED": {865        await markCelebrationPlayed();866        return { ok: true };867      }868      case "GET_CODEX_VAULT_DATA": {869        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the870        // popup navigates to the License section without further coordination.871        const gate = await requirePro("codex");872        if (!gate.allowed) return { ok: false, error: "pro_required" };873        return await handleGetCodexVaultData();874      }875      case "ESTIMATE_CODEX_PAGES": {876        const gate = await requirePro("codex");877        if (!gate.allowed) return { ok: false, error: "pro_required" };878        return await handleEstimateCodexPages();879      }880      case "RESTORE_FROM_CODEX": {881        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still882        // be able to restore a vault that was printed by a Pro user.883        // DO NOT add a Pro gate here.884        const payload = msg.payload as CodexRestorePayload;885        return await handleRestoreFromCodex(payload);886      }887      case "OPEN_PRO_GATE": {888        // Content script requests: open popup and navigate to License section.889        const { feature } = (msg.payload ?? {}) as { feature?: string };890        if (chrome.storage.session) {891          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });892        }893        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }894        return { ok: true };895      }896      case "OPEN_POPUP": {897        // Content script asks to open the trusted extension popup — used by the898        // inline locked bubble so the master password is entered in the popup,899        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a900        // user gesture + Chrome 127+/Firefox; on failure the user clicks the901        // toolbar icon. The badge already signals Peach needs attention.902        //903        // Set a session flag so the popup knows it was opened for inline unlock904        // and should close itself once the vault is unlocked (returning the user905        // to the inline autofill selector on the page).906        if (chrome.storage.session) {907          await chrome.storage.session.set({ peach_inline_unlock: true });908        }909        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }910        return { ok: true };911      }912      case "GET_IDENTITIES": {913        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };914        return { ok: true, data: vault.getIdentities() };915      }916      case "TOUCH_AUTO_LOCK": {917        // touchAutoLock() is already called by shouldRefreshAutoLock above;918        // this case just gives the popup a typed message to keep the session alive.919        return { ok: true };920      }921      case "GET_ADVANCED_HEALTH_REPORT": {922        const gate = await requirePro("advanced_health");923        if (!gate.allowed) return { ok: false, error: "pro_required" };924        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };925        const report = await buildAdvancedHealthReport(vault.getEntries());926        return { ok: true, data: report };927      }928      case "IS_DURESS_ENABLED": {929        const enabled = await vault.isDuressEnabled();930        return { ok: true, data: enabled };931      }932      case "SETUP_DURESS": {933        // Single enforcement point for the Duress Vault Pro gate. Free users934        // who somehow reach this handler are rejected here; the popup also935        // pre-checks isPro() to avoid showing the setup form to free users,936        // but server-side is the actual security boundary.937        const gate = await requirePro("duress_vault");938        if (!gate.allowed) return { ok: false, error: "pro_required" };939        // MV3 service workers restart after inactivity, losing the in-memory940        // derived key. Detect this before calling setupDuress so the popup941        // can show a meaningful prompt to re-lock and re-unlock.942        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };943        const { duressPassword } = msg.payload as { duressPassword: string };944        await vault.setupDuress(duressPassword);945        return { ok: true };946      }947      case "DISABLE_DURESS": {948        await vault.disableDuress();949        return { ok: true };950      }951      case "VERIFY_MAIN_PASSWORD": {952        const { password } = msg.payload as { password: string };953        const ok = await vault.verifyMainPassword(password);954        return { ok: true, data: ok };955      }956      case "CHANGE_PASSWORD": {957        const { currentPassword, newPassword } = msg.payload as {958          currentPassword: string;959          newPassword: string;960        };961        const changed = await vault.changePassword(currentPassword, newPassword);962        return changed963          ? { ok: true }964          : { ok: false, error: "incorrect_current_password" };965      }966      case "GET_SITE_PASSWORD_POLICY": {967        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });968        if (!tab?.id) return { ok: true, data: null };969        try {970          const response = await chrome.tabs.sendMessage(tab.id, {971            type: "GET_SITE_PASSWORD_POLICY",972          });973          return (response as MessageResponse) ?? { ok: true, data: null };974        } catch {975          return { ok: true, data: null };976        }977      }978      case "RECORD_MANUAL_SUMMON": {979        const { domain } = msg.payload as { domain: string };980        const settings = vault.getSettings();981        const existing = settings.manualSummonDomains?.[domain];982        const now = Date.now();983        await vault.updateSettings({984          manualSummonDomains: {985            ...settings.manualSummonDomains,986            [domain]: {987              firstSummonedAt: existing?.firstSummonedAt ?? now,988              summonCount: (existing?.summonCount ?? 0) + 1,989              lastSummonedAt: now,990            },991          },992        });993        return { ok: true };994      }995      case "DECLINE_CARD_SAVE": {996        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };997        await vault.declineCardSaveOffer(last4, expMonth, expYear);998        return { ok: true };999      }1000      case "IS_CARD_DECLINED": {1001        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1002        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1003        return { ok: true, data: declined };1004      }1005      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1006        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1007          rpId?: string;1008          rpName?: string;1009          userName?: string;1010          userDisplayName?: string;1011        };1012        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1013        return await initiateFirefoxPasskeyCreate({1014          rpId,1015          rpName: rpName ?? rpId,1016          userName,1017          userDisplayName,1018        });1019      }10201021      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1022        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1023        if (!payload) return { ok: false, error: "missing_payload" };1024        return await completeFirefoxPasskeyCreate(payload);1025      }10261027      case "PASSKEY_OFFER_DECLINE": {1028        const { domain } = (msg.payload ?? {}) as { domain?: string };1029        if (!domain) return { ok: false, error: "domain_required" };1030        await recordPasskeyOfferDecline(domain);1031        return { ok: true };1032      }10331034      case "GET_PASSKEY_OFFER_DECLINED": {1035        const { domain } = (msg.payload ?? {}) as { domain?: string };1036        if (!domain) return { ok: false, error: "domain_required" };1037        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1038      }10391040      case "PASSKEY_HAS_CREDENTIALS": {1041        const payload = msg.payload as {1042          rpId?: string;1043          allowCredentials?: Array<{ id: string; type?: string }>;1044        } | undefined;1045        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1046        return await handlePasskeyHasCredentials({1047          rpId: payload.rpId,1048          allowCredentials: payload.allowCredentials ?? [],1049        }, attestedSenderOrigin(sender));1050      }10511052      case "PASSKEY_CREATE": {1053        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1054        if (!payload?.rpId || !payload?.userName) {1055          return { ok: false, error: "rpid_and_username_required" };1056        }1057        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1058      }10591060      case "PASSKEY_GET": {1061        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1062        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1063        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1064      }10651066      case "PASSKEY_AUTH_RESPONSE": {1067        const { requestId, approved } = (msg.payload ?? {}) as {1068          requestId?: string | number;1069          approved?: boolean;1070        };1071        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1072          return { ok: false, error: 'requestId and approved required' };1073        }1074        await resolvePendingPasskeyRequest(Number(requestId), approved);1075        return { ok: true };1076      }10771078      case "GET_PASSKEY_FOR_DOMAIN": {1079        const { domain } = (msg.payload ?? {}) as { domain?: string };1080        if (!domain) return { ok: false, error: "domain_required" };1081        // Scope to the caller's own origin: a page may only ask about passkeys1082        // for a domain it actually owns, so an arbitrary page cannot enumerate1083        // which sites the user holds passkeys for or read the username (audit MEDIUM).1084        const origin = attestedSenderOrigin(sender);1085        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1086        if (!vault.isUnlocked()) return { ok: true, data: null };1087        const match = vault1088          .getEntries()1089          .find((entry) => entry.passkey?.rpId === domain);1090        if (!match || !match.passkey) return { ok: true, data: null };1091        // Slim shape — only the fields State 11 needs. Never expose private1092        // key material, even though this is locked behind isUnlocked.1093        return {1094          ok: true,1095          data: {1096            rpId: match.passkey.rpId,1097            userName: match.passkey.userName,1098            browser: match.passkey.browser,1099          },1100        };1101      }11021103      case "DESTROY_VAULT": {1104        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1105        // storage.local.clear() wipes every Peach key (slots, settings, license,1106        // onboarded flag, history, sync state, declined cards, recall, etc.);1107        // session.clear() wipes pending passkey requests + pro-notice queues.1108        // Caller (Panic.tsx) handles UI navigation back to onboarding.1109        //1110        // The Pro license is the one thing that must survive: the user paid for1111        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1112        // Capture it before the clear and restore it after. peach_pro_celebrated1113        // rides along so the Pro celebration doesn't replay on the next unlock.1114        const preserved = await chrome.storage.local.get([1115          "peach_license",1116          "peach_pro_celebrated",1117        ]);1118        vault.lock();1119        await storageClear();1120        await vault.clearVaultHistory();1121        const toRestore: Record<string, unknown> = {};1122        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1123        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1124        if (Object.keys(toRestore).length > 0) {1125          await chrome.storage.local.set(toRestore);1126        }1127        if (chrome.storage.session) {1128          await chrome.storage.session.clear();1129        }1130        return { ok: true };1131      }11321133      case "SUBMIT_FEEDBACK": {1134        const { category, message, version, browser } = msg.payload as {1135          category: string;1136          message: string;1137          version: string;1138          browser: string;1139        };1140        if (!message.trim()) return { ok: false, error: "message_empty" };1141        if (!FEEDBACK_ENDPOINT) return { ok: true };1142        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1143          return { ok: false, error: "invalid_feedback_endpoint" };1144        }1145        try {1146          const res = await fetch(FEEDBACK_ENDPOINT, {1147            method: "POST",1148            headers: { "Content-Type": "application/json" },1149            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1150          });1151          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1152        } catch (err) {1153          return { ok: false, error: err instanceof Error ? err.message : "network_error" };1154        }1155      }1156      // Android-only: biometric unlock with pre-derived key.1157      case "UNLOCK_WITH_KEY": {1158        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1159        if (!isNativePlatform()) {1160          return { ok: false, error: "desktop_only_uses_password" };1161        }1162        try {1163          const result = await vault.unlockWithKey(masterKeyHex);1164          if (result.ok) {1165            onVaultUnlocked();1166            await publishInMemoryVault(result.entries);1167          }1168          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1169        } catch {1170          return { ok: false, error: "invalid_key" };1171        }1172      }1173      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1174      case "GET_DERIVED_KEY": {1175        if (!isNativePlatform()) {1176          return { ok: false, error: "android_only" };1177        }1178        if (!vault.isUnlocked()) {1179          return { ok: false, error: "vault_locked" };1180        }1181        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1182      }1183      case "GET_IDENTITY_SUGGESTIONS": {1184        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1185        const entries = vault.getEntries();1186        const suggestions = buildIdentitySuggestions(entries);1187        return { ok: true, data: { suggestions } };1188      }1189      case "POPULATE_INLINE_VAULT": {1190        if (!isNativePlatform()) return { ok: false };1191        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1192        const entries = vault.getEntries();1193        await publishInMemoryVault(entries);1194        return { ok: true };1195      }1196      case "ML_INIT":1197        return { ok: true };11981199      case "ML_PREDICT_BATCH": {1200        // AUD-002: shape-validate before forwarding to the ML helper.1201        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1202        if (!Array.isArray(featuresArray)) {1203          return { ok: false, error: "invalid_payload" };1204        }1205        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1206      }12071208      // ── Chirp Sync (v3) ───────────────────────────────────────────────1209      // Returns the public-facing local identity needed by the popup to1210      // drive Phase-1 audio pairing. The private long-term key never1211      // leaves the background.1212      case "CHIRP_GET_LOCAL_IDENTITY": {1213        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1214        const proCheck = await requirePro("sync");1215        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1216        // Identity derives from the stable root key, not the password-derived1217        // key, so pairing survives a master-password change (SEV-2-B).1218        const masterKeyHex = vault.getRootKeyHex();1219        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1220        const masterKey = unhexBytes(masterKeyHex);1221        try {1222          const identity = await buildLocalIdentity(masterKey);1223          return { ok: true, data: identity };1224        } finally {1225          masterKey.fill(0);1226        }1227      }12281229      case "CHIRP_COMPLETE_PAIRING": {1230        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1231        const proCheck = await requirePro("sync");1232        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1233        const paired = (msg.payload as { paired?: unknown })?.paired;1234        if (typeof paired !== "object" || paired === null) {1235          return { ok: false, error: "invalid_payload" };1236        }1237        const candidate = paired as Record<string, unknown>;1238        if (1239          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1240          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1241          typeof candidate.deviceType !== "string" ||1242          typeof candidate.longTermPublicKeyHex !== "string" ||1243          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1244          (1245            candidate.signingPublicKeyHex !== undefined &&1246            (1247              typeof candidate.signingPublicKeyHex !== "string" ||1248              !/^[0-9a-f]{64}$/.test(candidate.signingPublicKeyHex)1249            )1250          ) ||1251          typeof candidate.pairedAt !== "number"1252        ) {1253          return { ok: false, error: "invalid_paired_device" };1254        }1255        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1256        return { ok: true };1257      }12581259      case "CHIRP_LIST_PAIRED_DEVICES": {1260        const devices = await listPairedDevicesV3();1261        return { ok: true, data: { devices } };1262      }12631264      case "CHIRP_UNPAIR_DEVICE": {1265        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1266        if (typeof deviceId !== "string" || !deviceId) {1267          return { ok: false, error: "invalid_payload" };1268        }1269        await removePairedDeviceByIdV3(deviceId);1270        return { ok: true };1271      }12721273      case "CHIRP_RENAME_LOCAL_DEVICE": {1274        const { name } = (msg.payload ?? {}) as { name?: string };1275        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1276        await setDeviceNameV3(name);1277        return { ok: true };1278      }12791280      case "TRIGGER_SYNC": {1281        const payload = (msg.payload ?? {}) as {1282          reason?: "vault_change" | "foreground" | "manual" | "mdns";1283          force?: boolean;1284          deviceId?: string;1285          discoveredIp?: string;1286          discoveredPort?: number;1287        };1288        const reason = payload.reason ?? "foreground";12891290        // mDNS discovery delivers a fresh (ip, port) resolved by the native1291        // side. Update the cached address before the sync runner tries to1292        // connect — avoids a subnet probe on the very next round.1293        if (1294          reason === "mdns" &&1295          typeof payload.deviceId === "string" &&1296          typeof payload.discoveredIp === "string"1297        ) {1298          const { findPairedDeviceById, setLastKnownIp } = await import("./paired-devices");1299          const device = await findPairedDeviceById(payload.deviceId);1300          if (device?.longTermPublicKeyHex) {1301            await setLastKnownIp(device.longTermPublicKeyHex, payload.discoveredIp).catch(() => undefined);1302          }1303        }13041305        const { triggerSyncIfReachable } = await import("./sync-trigger");1306        void triggerSyncIfReachable({ reason, force: payload.force === true });1307        return { ok: true };1308      }13091310      case "GET_SYNC_STATE": {1311        const { getSyncState } = await import("./sync-trigger");1312        return { ok: true, data: getSyncState() };1313      }13141315      case "GET_SYNC_ALERTS": {1316        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1317        const alerts = await getPendingSyncAlerts();1318        // The popup reads on open and acknowledges with consume:true after1319        // rendering, so a popup crash between read and render doesn't lose1320        // the alerts.1321        if (consume) await clearPendingSyncAlerts();1322        return { ok: true, data: alerts };1323      }13241325      case "GET_PENDING_VOUCHED_DEVICES": {1326        return { ok: true, data: await listPendingVouchedDevices() };1327      }1328      case "CONFIRM_VOUCHED_DEVICE": {1329        const { deviceId } = msg.payload as { deviceId: string };1330        const pending = await getPendingVouchedDevice(deviceId);1331        if (!pending) return { ok: false, error: "not_pending" };1332        await upsertPairedDeviceV3({1333          deviceId: pending.deviceId,1334          deviceName: pending.deviceName,1335          deviceType:1336            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1337          longTermPublicKeyHex: pending.longTermPublicKeyHex,1338          signingPublicKeyHex: pending.signingPublicKeyHex,1339          wsPort: pending.wsPort,1340          pairedAt: pending.pairedAt,1341          trustSource: "vouched",1342        });1343        await removePendingVouchedDevice(deviceId);1344        return { ok: true };1345      }1346      case "REJECT_VOUCHED_DEVICE": {1347        const { deviceId } = msg.payload as { deviceId: string };1348        await removePendingVouchedDevice(deviceId);1349        return { ok: true };1350      }1351      case "ROTATE_SYNC_IDENTITY": {1352        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1353        const result = await vault.rotateSyncIdentity();1354        return result.ok ? { ok: true } : { ok: false, error: result.error };1355      }13561357      default:1358        return { ok: false, error: "unknown_message_type" };1359    }1360  } catch (err) {1361    return {1362      ok: false,1363      error: err instanceof Error ? err.message : "operation_failed",1364    };1365  }1366}13671368// --- Mobile platform helpers ---13691370// Android: populates the in-memory vault used by PeachAutofillService.1371async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1372  const plugin = nativePlugin<{1373    setEntries?: (args: {1374      entries: Array<{1375        id: string;1376        title: string;1377        username: string;1378        email: string;1379        password: string;1380        url: string;1381        totp: string;1382        additionalUrls: string[];1383      }>;1384    }) => Promise<void>;1385  }>("InMemoryVaultPlugin");1386  if (!plugin?.setEntries) return;1387  await plugin.setEntries({1388    entries: entries.map((e) => ({1389      id: e.id,1390      title: e.title ?? "",1391      username: e.username ?? "",1392      email: (e as VaultEntry & { email?: string }).email ?? "",1393      password: e.password ?? "",1394      url: e.url ?? "",1395      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1396      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1397    })),1398  });1399}14001401// Android: clear the autofill in-memory store on lock.1402async function clearInMemoryVault(): Promise<void> {1403  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1404  if (!plugin?.clearEntries) return;1405  await plugin.clearEntries();1406}14071408// Returns username use-counts from the vault, sorted by frequency. Each row1409// also carries the entry's email so the popup can suggest the email/username1410// pair the user has actually used together.1411function buildIdentitySuggestions(1412  entries: VaultEntry[],1413): Array<{ email: string; username: string; count: number }> {1414  const usernameCounts = new Map<string, number>();1415  const usernameEmail = new Map<string, string>();1416  for (const entry of entries) {1417    const username = entry.username ?? "";1418    const email = (entry as VaultEntry & { email?: string }).email ?? "";1419    if (!username && !email) continue;1420    const key = username || email;1421    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1422    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1423  }1424  return Array.from(usernameCounts.entries())1425    .sort((a, b) => b[1] - a[1])1426    .map(([username, count]) => ({1427      email: usernameEmail.get(username) ?? "",1428      username,1429      count,1430    }));1431}14321433/** Notify all content scripts that the vault just became available. */1434function broadcastToContentScripts(message: { type: string }): void {1435  if (!chrome.tabs?.query) return;1436  chrome.tabs.query({}, (tabs) => {1437    for (const tab of tabs) {1438      if (tab.id !== undefined) {1439        chrome.tabs.sendMessage(tab.id, message).catch(() => {1440          // Tab may not have a content script — silently ignore1441        });1442      }1443    }1444  });1445}14461447function shouldRefreshAutoLock(type: MessageType): boolean {1448  return (1449    type !== "HAS_VAULT" &&1450    type !== "IS_UNLOCKED" &&1451    type !== "GET_VAULT_STATUS" &&1452    type !== "LOCK" &&1453    type !== "UPDATE_SETTINGS" &&1454    type !== "GET_PENDING_PASSKEY" &&1455    type !== "GET_PASSKEY_PROVIDER_STATE" &&1456    type !== "DECLINE_CARD_SAVE" &&1457    type !== "IS_CARD_DECLINED" &&1458    type !== "SUBMIT_FEEDBACK"1459  );1460}14611462function isAllowedCanaryWebhookUrl(value: string): boolean {1463  try {1464    const url = new URL(value);1465    if (url.protocol !== "https:") return false;14661467    const hostname = url.hostname.toLowerCase();1468    if (1469      hostname === "localhost" ||1470      hostname.endsWith(".localhost") ||1471      isPrivateIpv4(hostname) ||1472      isPrivateIpv6(hostname)1473    ) {1474      return false;1475    }14761477    return true;1478  } catch {1479    return false;1480  }1481}14821483function isPrivateIpv4(hostname: string): boolean {1484  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1485    return true;1486  }14871488  const octets = hostname.split(".").map((part) => Number(part));1489  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1490    return false;1491  }14921493  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1494}14951496function isPrivateIpv6(hostname: string): boolean {1497  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1498  return (1499    normalized === "::1" ||1500    normalized.startsWith("fc") ||1501    normalized.startsWith("fd") ||1502    normalized.startsWith("fe80:")1503  );1504}