messages.ts

70.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 { setupAutoLock, touchAutoLock } from "./alarms";14import { runSelfTest } from "./self-test";15import * as vault from "./vault";16import {17  handleEstimateCodexPages,18  handleGetCodexVaultData,19  handleRestoreFromCodex,20} from "./codex-handlers";21import type { CodexRestorePayload } from "../shared/codex-types";22import {23  activateLicense,24  deactivateLicense,25  getLicenseInfo,26  getLicenseKey,27  isProUser,28  markCelebrationPlayed,29  shouldPlayCelebration,30} from "./license";31import {32  completeFirefoxPasskeyCreate,33  getPasskeyProviderState,34  getPendingPasskeyRequest,35  handleFirefoxPasskeyCreate,36  handleFirefoxPasskeyGet,37  handlePasskeyHasCredentials,38  initiateFirefoxPasskeyCreate,39  isPasskeyOfferDeclined,40  onVaultUnlocked,41  recordPasskeyOfferDecline,42  resolvePendingPasskeyRequest,43  setPasskeyProviderEnabled,44} from "./passkey";45import { buildAdvancedHealthReport, resolveResetUrl } from "./health";46import { storageClear, storageGet } from "../shared/storage";47import { findInvalidWords } from "../shared/recovery-words";48import {49  addPairedDevice,50  addTrustedNetwork,51  clearIncomingPairingRequest,52  getIncomingPairingRequest,53  getPairedDevices,54  getTrustedNetworks,55  removePairedDevice,56  removeTrustedNetwork,57  setIncomingPairingRequest,58  updatePairedDevice,59} from "./sync-storage";60import { getCurrentNetwork, isOnTailscale } from "./sync-network";61import {62  consumeRecentPairing,63  setActivePairingToken,64} from "./pairing-server-state";65import type {66  Message,67  MessageResponse,68  MessageType,69  ProFeature,70  VaultEntry,71} from "../shared/types";72import { isPasskeyOnly } from "../shared/types";73import type { SyncStatus, SyncableDevice } from "../shared/sync-types";74import { isNativePlatform, nativePlugin } from "../shared/native";75import { runBlobSyncSession, type SyncResult } from "./sync-coordinator";76import type { SyncDeps } from "./sync-coordinator";77import { createWebSocketSyncTransport } from "../shared/websocket-sync-transport";78import { performResponderAuth, bytesToHex as noiseBytesToHex } from "../shared/noise-js";79import { getLocalSubnet, discoverDevice, scanForPairingPhone } from "../shared/local-network";80import { predictBatch as mlPredictBatch } from "./ml";81import type { MLFieldFeatures } from "../shared/ml";82import { base64ToBytes, bytesToBase64 } from "../shared/sync-wire";83import { buildLocalIdentity, setDeviceName as setDeviceNameV3 } from "./chirp-identity";84import {85  listPairedDevices as listPairedDevicesV3,86  removePairedDeviceById as removePairedDeviceByIdV3,87  upsertPairedDevice as upsertPairedDeviceV3,88} from "./paired-devices";8990function unhexBytes(hex: string): Uint8Array {91  if (hex.length % 2 !== 0) throw new Error("invalid hex");92  const out = new Uint8Array(hex.length / 2);93  for (let i = 0; i < out.length; i++) {94    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);95  }96  return out;97}9899/**100 * The single Pro gate. Every gated handler calls this first; the broadcast101 * lets the popup react (navigate to the License section, highlight the102 * relevant feature). Background never touches the popup view directly —103 * the popup owns navigation. See Projects.md "Pro gate rule".104 */105async function requirePro(106  feature: ProFeature,107  trigger: "user" | "background" = "user"108): Promise<{ allowed: boolean }> {109  if (await isProUser()) return { allowed: true };110111  if (trigger === "user") {112    // User deliberately triggered this feature — redirect the popup immediately.113    chrome.runtime114      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })115      .catch(() => {116        // Popup may be closed — the gate signal is best-effort.117      });118  } else {119    // Background trigger (e.g. passive sync initiation) — no popup is open.120    // Queue a notice so the next popup open shows a soft banner instead of121    // silently failing.122    if (chrome.storage.session) {123      chrome.storage.session124        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })125        .catch(() => {});126    }127  }128129  return { allowed: false };130}131132// ---------------------------------------------------------------------------133// 6-digit code pairing.134135const PAIRING_TOKEN_TTL_MS = 5 * 60 * 1000;136137138function generateSixDigitToken(): string {139  // crypto.getRandomValues, not Math.random — the token is the only secret140  // protecting the pairing window from a same-LAN attacker. 6 decimal digits141  // is 1 in 1,000,000; combined with a 5-minute TTL and pairing-mode gating142  // on the responder this is the right tradeoff between UX and security.143  const buf = new Uint32Array(1);144  crypto.getRandomValues(buf);145  const value = buf[0] % 1_000_000;146  return value.toString().padStart(6, "0");147}148149// ---------------------------------------------------------------------------150// Peer discovery glue (Phase 7 popup pairing flow).151152const PRIVATE_IPV4_RANGES = [153  { prefix: "10." },154  { prefix: "127." },155  { prefix: "169.254." },156  { prefix: "192.168." },157];158159// Empty disables network submission while the UI continues to function as a160// no-op (the handler returns ok:true without calling fetch). When set, the161// URL is validated by `isAllowedCanaryWebhookUrl` before any request, so the162// same private-IP/HTTPS rules that gate canary webhooks apply here.163const FEEDBACK_ENDPOINT = "";164165// ---------------------------------------------------------------------------166// Sync helpers167// ---------------------------------------------------------------------------168169/**170 * Short-lived registry of x25519 public keys that just completed a real Noise171 * NK handshake + initiator-auth proof. The PAIRING_COMPLETED handler must172 * find the supplied publicKeyHex here before it will call addPairedDevice —173 * otherwise an attacker could forge the message and pair an arbitrary key174 * (M13/SEC-005).175 *176 * Entries auto-expire after 30s. Each entry is consumed on first successful177 * PAIRING_COMPLETED so a single handshake cannot pair twice.178 */179const PENDING_PAIRS = new Map<string, ReturnType<typeof setTimeout>>();180const PENDING_PAIR_TTL_MS = 30_000;181182export function markPairingHandshakeVerified(publicKeyHex: string): void {183  if (!publicKeyHex) return;184  const existing = PENDING_PAIRS.get(publicKeyHex);185  if (existing) clearTimeout(existing);186  const t = setTimeout(() => PENDING_PAIRS.delete(publicKeyHex), PENDING_PAIR_TTL_MS);187  PENDING_PAIRS.set(publicKeyHex, t);188}189190function consumePendingPair(publicKeyHex: string): boolean {191  const t = PENDING_PAIRS.get(publicKeyHex);192  if (!t) return false;193  clearTimeout(t);194  PENDING_PAIRS.delete(publicKeyHex);195  return true;196}197198export function buildSyncDeps(): SyncDeps {199  return {200    isVaultUnlocked: () => vault.isUnlocked(),201    getVaultBlobForSync: async () => {202      const base = await vault.getVaultBlobForSync();203      if (!base) return null;204      const paired = await getPairedDevices();205      return {206        ...base,207        devices: paired.flatMap(d =>208          d.x25519PublicKey209            ? [{210                publicKeyHex: d.x25519PublicKey,211                deviceName: d.displayName ?? "",212                pairedAt: d.pairedAt,213              }]214            : [],215        ),216      };217    },218    applyIncomingVault: async (blob, ts, license, devices) => {219      const applied = await vault.applyIncomingVault(blob, ts, license);220      if (devices?.length) await mergeDeviceRegistry(devices);221      if (applied) {222        const reloaded = await vault.reloadEntriesAfterSync();223        if (!reloaded) {224          // The remote vault was encrypted under a different key (the remote225          // changed password). Our in-memory entries are now stale and cannot226          // be re-encrypted without overwriting the just-applied blob. Lock227          // to force a re-unlock with the new password (H3/COR-005).228          vault.lock();229          chrome.runtime230            .sendMessage({ type: "VAULT_RELOCK_AFTER_SYNC" })231            .catch(() => {});232        }233      }234      return applied;235    },236  };237}238239async function doVaultSync(ip: string, publicKeyHex: string): Promise<SyncResult> {240  // Defensive: refuse to drive a sync to a key not in the paired-devices241  // list. The WebSocket transport already authenticates the peer via Noise242  // NK + the initiator auth proof (H1), but pinning the key to the paired243  // set here makes "talk to anyone matching this static key" the only path244  // to vault application — there is no orphan-key window between pair and245  // sync (M11/COR-014).246  const paired = await getPairedDevices();247  if (!paired.some(d => d.x25519PublicKey === publicKeyHex)) {248    return { status: 'errored', applied: false, error: 'remote_not_paired' };249  }250  try {251    const identity = await vault.getSyncIdentity();252    const transport = await createWebSocketSyncTransport(253      `ws://${ip}:44100`,254      publicKeyHex,255      identity.privateKeyBytes,256      identity.publicKeyBytes,257    );258    const result = await runBlobSyncSession('initiator', transport, buildSyncDeps());259    // Reaching this point means createWebSocketSyncTransport completed both260    // the Noise NK handshake and the initiator-auth proof — the remote261    // proved possession of the matching static key (M13/SEC-005).262    if (result.status === 'completed') {263      markPairingHandshakeVerified(publicKeyHex);264    }265    return result;266  } catch (err) {267    return { status: 'errored', applied: false, error: String(err) };268  }269}270271async function mergeDeviceRegistry(incoming: SyncableDevice[]): Promise<void> {272  const existing = await getPairedDevices();273  const existingKeys = new Set(existing.map(d => d.x25519PublicKey));274  for (const device of incoming) {275    if (!existingKeys.has(device.publicKeyHex)) {276      await addPairedDevice({277        deviceId: device.publicKeyHex,278        displayName: device.deviceName,279        x25519PublicKey: device.publicKeyHex,280        pairedAt: device.pairedAt,281        lastSeenAt: 0,282        lastKnownIp: '',283      }).catch(() => {});284    }285  }286}287288// Background pairing scan — runs after START_PAIRING_SERVER fires on desktop.289// Scans the local subnet for a phone that has accepted the pairing token,290// stores it, runs the initial vault exchange, then notifies the popup.291async function runPairingSubnetScan(token: string): Promise<void> {292  const subnet = await getLocalSubnet();293  if (!subnet) return;294295  const found = await scanForPairingPhone(subnet, token);296  if (!found) return;297298  const { ip, publicKeyHex } = found;299300  try {301    await addPairedDevice({302      deviceId: publicKeyHex,303      displayName: 'Peach',304      x25519PublicKey: publicKeyHex,305      pairedAt: Date.now(),306      lastSeenAt: Date.now(),307      lastKnownIp: ip,308    });309  } catch {310    // Already paired — update IP311    await updatePairedDevice(publicKeyHex, { lastKnownIp: ip, lastSeenAt: Date.now() });312  }313314  // Immediate vault exchange — the free one-time transfer315  await doVaultSync(ip, publicKeyHex);316317  chrome.runtime.sendMessage({318    type: 'PAIRING_COMPLETED',319    payload: { deviceName: 'Peach', publicKeyHex, deviceIp: ip },320  }).catch(() => {});321}322323export function setupMessageHandler(): void {324  chrome.runtime.onMessage.addListener(325    (msg: unknown, sender, sendResponse) => {326      if (!isMessage(msg)) {327        sendResponse({ ok: false, error: "invalid_message" });328        return true;329      }330      handleMessage(msg, sender)331        .then(sendResponse)332        .catch((err) =>333          sendResponse({334            ok: false,335            error: err instanceof Error ? err.message : String(err),336          })337        );338      return true;339    }340  );341342  // Android: the chrome shim queues sendMessage calls until this handler is343  // registered. Without this hookup, every message hangs on Capacitor builds.344  // eslint-disable-next-line @typescript-eslint/no-explicit-any345  const reg = (globalThis as any).__peachRegisterMessageHandler;346  if (typeof reg === "function") {347    reg(async (m: unknown) => {348      if (!isMessage(m)) return { ok: false, error: "invalid_message" };349      try {350        return await handleMessage(m);351      } catch (err) {352        return {353          ok: false,354          error: err instanceof Error ? err.message : String(err),355        };356      }357    });358  }359360  // Android: subscribe to SyncPlugin events.361  if (isNativePlatform()) {362    const syncPlug = nativePlugin<{363      addListener: (364        event: string,365        handler: (data: Record<string, string>) => void366      ) => void;367    }>("SyncPlugin");368369    // Pairing probe answered — store the paired device (desktop, no IP needed370    // since the desktop never acts as a WS server).371    syncPlug?.addListener?.("peach:pair-probe-answered", (data) => {372      const deviceName = data.deviceName ?? "Peach";373      const publicKeyHex = data.publicKeyHex ?? "";374      // Native handled the pairing handshake — trust this entry into the375      // verified-handshake set (M13/SEC-005). The subsequent PAIRING_COMPLETED376      // message will consume it.377      if (publicKeyHex) markPairingHandshakeVerified(publicKeyHex);378      void (async () => {379        const { addPairedDevice, setHasPaired: setPaired } = await import("./sync-storage");380        await addPairedDevice({381          deviceId: publicKeyHex || (data.connectionId ?? "unknown"),382          displayName: deviceName,383          x25519PublicKey: publicKeyHex,384          pairedAt: Date.now(),385          lastSeenAt: Date.now(),386        }).catch(() => {});387        await setPaired();388        chrome.runtime.sendMessage({389          type: "PAIRING_COMPLETED",390          payload: { deviceName, publicKeyHex },391        }).catch(() => {});392      })();393    });394395    // Sync frame received — route to the waiting responder session.396    syncPlug?.addListener?.("peach:sync-frame", (data) => {397      const { connectionId, frame } = data;398      if (connectionId && frame) deliverAndroidSyncFrame(connectionId, frame);399    });400401    // Sync session started (SYNC_HELLO received by SyncPlugin) — dispatch as402    // a background message so SYNC_SESSION_STARTED handler runs the responder.403    syncPlug?.addListener?.("peach:sync-session-started", (data) => {404      const { connectionId } = data;405      if (!connectionId) return;406      void handleMessage({ type: "SYNC_SESSION_STARTED", payload: { connectionId } });407    });408  }409}410411function isMessage(m: unknown): m is Message {412  return typeof m === "object" && m !== null && "type" in m;413}414415export async function handleMessage(416  msg: Message,417  sender: Partial<chrome.runtime.MessageSender> = {}418): Promise<MessageResponse> {419  try {420    // Validate sender — only allow messages from our extension pages/scripts.421    // `sender.id` is undefined for messages originating from extension UI422    // (popup/options), which is legitimate; reject only when it is defined423    // and does not match our extension id.424    if (425      sender.id !== undefined &&426      sender.id !== chrome.runtime.id427    ) {428      return { ok: false, error: "invalid_sender" };429    }430431    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {432      touchAutoLock();433    }434435    switch (msg.type) {436      case "CREATE_VAULT": {437        const { password } = msg.payload as { password: string };438        await vault.createVault(password);439        await setupAutoLock();440        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });441        onVaultUnlocked();442        return { ok: true };443      }444      case "UNLOCK": {445        const { password } = msg.payload as { password: string };446        const ok = await vault.unlock(password);447        if (ok) {448          // KAT: verify the WebCrypto stack is healthy before the user relies on it.449          // Runs after unlock so latency is hidden behind the vault-load time.450          const kat = await runSelfTest();451          if (!kat.ok) {452            console.error("[Peach] Crypto self-test FAILED:", kat.error);453            await vault.lock();454            return { ok: false, error: "self_test_failed" };455          }456          await setupAutoLock();457          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });458          onVaultUnlocked();459          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());460          return { ok: true };461        }462        // Distinguish corruption from wrong password so the popup can offer463        // a history-restore path instead of falsely accusing the user of464        // mistyping (M7/COR-007).465        const failure = vault.consumeLastUnlockFailureReason();466        if (failure) {467          return {468            ok: false,469            error: "vault_corrupted",470            canRestoreFromHistory: true,471          } as MessageResponse;472        }473        return { ok: false };474      }475      case "VALIDATE_RECOVERY_WORDS": {476        const { words } = msg.payload as { words: string[] };477        const invalid = findInvalidWords(words);478        return { ok: true, data: { valid: invalid.length === 0, invalid } };479      }480      case "GET_RECOVERY_WORDS": {481        // Must be unlocked and have recovery set up (vault must be v2.12+).482        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };483        try {484          const words = await vault.getRecoveryWords();485          return { ok: true, data: words };486        } catch (e) {487          // pre-v2.12 vault that hasn't migrated488          return { ok: false, error: "recovery_not_setup" };489        }490      }491      case "RECOVER_WITH_WORDS": {492        // User has lost their password but has their 12 recovery words.493        // We: (1) validate the words, (2) re-encrypt vault with new password.494        const { words, newPassword } = msg.payload as {495          words: string[];496          newPassword: string;497        };498        const stored = await vault.loadSlotA();499        if (!stored) return { ok: false, error: "no_vault" };500        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {501          return { ok: false, error: "recovery_not_setup" };502        }503        // Unwrap the root key from the recovery escrow.504        try {505          await vault.unwrapRootKeyForRecovery(506            stored.recovery_wrapped_root_key,507            stored.recovery_nonce ?? "",508            stored.recovery_tag ?? "",509            stored.recovery_salt,510            words511          );512        } catch {513          return { ok: false, error: "invalid_recovery_words" };514        }515        // Re-key: derive fresh salt + key from new password.516        const newSalt = vault.generateSalt();517        const newKey = await vault.deriveKey(newPassword, newSalt);518        // Re-wrap root key under the new password's derived key so the same519        // recovery words continue to work after the password change.520        await vault.rewrapRootKeyForPassword(newKey, newSalt);521        // Re-encrypt vault entries with the new key.522        await vault.changePasswordWithNewKey(newSalt, newKey);523        await setupAutoLock();524        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });525        return { ok: true };526      }527      case "LOCK":528        vault.lock();529        if (isNativePlatform()) await clearInMemoryVault();530        return { ok: true };531      case "IS_UNLOCKED":532        return { ok: true, data: vault.isUnlocked() };533      case "GET_VAULT_STATUS":534        return { ok: true, unlocked: vault.isUnlocked() };535      case "HAS_VAULT":536        return { ok: true, data: await vault.hasVault() };537      case "GET_ENTRIES":538        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };539        return { ok: true, data: vault.getEntries() };540      case "ADD_ENTRY": {541        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };542        const payload = msg.payload;543        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {544          return { ok: false, error: "invalid_payload" };545        }546        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);547        return { ok: true, data: entry };548      }549      case "BATCH_ADD_ENTRIES": {550        const payload = msg.payload as { entries?: unknown } | null | undefined;551        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {552          return { ok: false, error: "invalid_payload" };553        }554        if (!Array.isArray(payload.entries)) {555          return { ok: false, error: "invalid_payload" };556        }557        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);558        return { ok: true, data: added };559      }560      case "RESTORE_ENTRIES": {561        const payload = msg.payload as562          | { entries?: unknown; mode?: unknown; settings?: unknown }563          | null564          | undefined;565        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {566          return { ok: false, error: "invalid_payload" };567        }568        if (!Array.isArray(payload.entries)) {569          return { ok: false, error: "invalid_payload" };570        }571        if (payload.mode !== "replace" && payload.mode !== "merge") {572          return { ok: false, error: "invalid_payload" };573        }574        const summary = await vault.restoreEntries(575          payload.entries as Parameters<typeof vault.restoreEntries>[0],576          payload.mode577        );578        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {579          await vault.updateSettings(payload.settings as vault.VaultSettings);580        }581        return { ok: true, data: summary };582      }583      case "CLEAR_VAULT_ENTRIES": {584        await vault.clearVaultEntries("REPLACE_ALL");585        return { ok: true };586      }587      case "GET_VAULT_HISTORY": {588        const snapshots = await vault.getVaultHistory();589        return { ok: true, data: snapshots };590      }591      case "RESTORE_VAULT_SNAPSHOT": {592        const { snapshotId } = msg.payload as { snapshotId: string };593        const result = await vault.restoreVaultSnapshot(snapshotId);594        if (!result.ok) return { ok: false, error: result.error };595        broadcastToContentScripts({ type: "VAULT_LOCKED" });596        return { ok: true };597      }598      case "COUNT_DUPLICATES": {599        return { ok: true, data: vault.countDuplicates() };600      }601      case "DEDUPLICATE_ENTRIES": {602        const removed = await vault.deduplicateEntries();603        return { ok: true, data: removed };604      }605      case "UPDATE_ENTRY": {606        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;607        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {608          return { ok: false, error: "invalid_payload" };609        }610        const { id, patch } = payload;611        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {612          return { ok: false, error: "invalid_payload" };613        }614        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);615        return { ok: true };616      }617      case "ADD_ADDITIONAL_URL": {618        const { id, url } = msg.payload as { id: string; url: string };619        const trimmed = typeof url === "string" ? url.trim() : "";620        if (!trimmed) return { ok: false, error: "url_required" };621        const existing = vault.getEntryById(id);622        if (!existing) return { ok: false, error: "entry_not_found" };623        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };624        const merged = [...(existing.additionalUrls ?? []), trimmed];625        await vault.updateEntry(id, { additionalUrls: merged });626        return { ok: true };627      }628      case "DELETE_ENTRY": {629        const { id } = msg.payload as { id: string };630        await vault.deleteEntry(id);631        return { ok: true };632      }633      case "GET_DELETED_ENTRIES":634        return { ok: true, data: vault.getDeletedEntries() };635      case "RESTORE_ENTRY": {636        const { id } = msg.payload as { id: string };637        await vault.restoreEntry(id);638        return { ok: true };639      }640      case "PURGE_ENTRY": {641        const { id } = msg.payload as { id: string };642        await vault.purgeEntry(id);643        return { ok: true };644      }645      case "PURGE_EXPIRED_TRASH": {646        const { retentionMs } = msg.payload as { retentionMs: number };647        const purged = await vault.purgeExpiredTrash(retentionMs);648        return { ok: true, data: purged };649      }650      case "SAVE_NOTE": {651        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };652        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };653        const now = Date.now();654        if (id) {655          const existing = vault.getEntryById(id);656          if (!existing) return { ok: false, error: "not_found" };657          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });658          return { ok: true, data: vault.getEntryById(id) };659        } else {660          const entry = await vault.addEntry({661            type: "note",662            title: title || "Untitled",663            notes: body,664            createdAt: now,665            modifiedAt: now,666          } as any);667          return { ok: true, data: entry };668        }669      }670      case "DELETE_NOTE": {671        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };672        const { id } = msg.payload as { id: string };673        await vault.deleteEntry(id);674        return { ok: true };675      }676      case "GET_NOTES": {677        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };678        const notes = vault.getEntries().filter(679          (e) => e.type === "note" && !e.deletedAt680        );681        return { ok: true, data: notes } as MessageResponse;682      }683      case "SEARCH_VAULT": {684        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };685        // AUD-002: shape-validate the payload before calling string methods.686        // A raw cast lets a malformed message crash the handler with TypeError.687        const { query } = (msg.payload ?? {}) as { query?: unknown };688        if (typeof query !== "string") {689          return { ok: false, error: "invalid_payload" };690        }691        const q = query.toLowerCase();692        const searchResults = vault.getEntries().filter(693          (e) =>694            !e.deletedAt &&695            (e.title.toLowerCase().includes(q) ||696              e.notes?.toLowerCase().includes(q) ||697              e.username?.toLowerCase().includes(q))698        );699        return { ok: true, data: searchResults } as MessageResponse;700      }701      case "PAIRING_COMPLETED": {702        const { deviceName, publicKeyHex, deviceIp } = (msg.payload ?? {}) as {703          deviceName?: string;704          publicKeyHex?: string;705          deviceIp?: string;706        };707        if (!publicKeyHex) return { ok: false, error: "publickeyhex_required" };708        // Only accept publicKeyHex values that just completed a real Noise NK709        // handshake (initiator or responder side). Without this gate, anyone710        // who can sendMessage to the background can pair an arbitrary key711        // (M13/SEC-005). Re-confirming an already-paired device is allowed712        // so legitimate update-IP retries still work.713        const alreadyPaired = (await getPairedDevices()).some(714          d => d.x25519PublicKey === publicKeyHex,715        );716        const verified = consumePendingPair(publicKeyHex);717        if (!verified && !alreadyPaired) {718          return { ok: false, error: "pairing_not_verified" };719        }720        const { setHasPaired: setPaired } = await import("./sync-storage");721        await setPaired();722        try {723          await addPairedDevice({724            deviceId: publicKeyHex,725            displayName: deviceName ?? "Unknown",726            x25519PublicKey: publicKeyHex,727            pairedAt: Date.now(),728            lastSeenAt: Date.now(),729            lastKnownIp: deviceIp,730          });731        } catch {732          // Already paired — update IP if provided733          if (deviceIp) {734            await updatePairedDevice(publicKeyHex, { lastKnownIp: deviceIp, lastSeenAt: Date.now() });735          }736        }737        return { ok: true };738      }739      case "AUTOFILL_QUERY": {740        if (!vault.isUnlocked()) {741          return { ok: false, error: "vault_locked" };742        }743        const { domain, includeAll, kind } = msg.payload as {744          domain: string;745          includeAll?: boolean;746          kind?: "login" | "card";747        };748        // kind="card": return saved cards as compact summaries for the749        // inline card silver platter. Cards are not domain-scoped — every750        // saved card is a candidate on every checkout page — so domain is751        // ignored when kind === "card".752        if (kind === "card") {753          const cards = vault.getEntries().filter((e) => e.type === "card");754          return {755            ok: true,756            data: cards.map((e) => ({757              id: e.id,758              title: e.cardNickname || e.title,759              cardholderName: e.cardholderName,760              last4: e.last4,761              expMonth: e.expMonth,762              expYear: e.expYear,763              network: e.network,764            })),765          };766        }767        // The inline selector fills username+password into a form. Passkey-768        // only entries have no password to fill; sign-in for those goes769        // through the WebAuthn path instead. Filter them out everywhere so770        // the user doesn't see four "GitHub" rows that mostly do nothing.771        // Notes and cards never belonged here either.772        const matches = (773          includeAll774            ? vault775                .getEntries()776                .filter((entry) => entry.type !== "note" && entry.type !== "card")777            : vault.queryDomain(domain)778        ).filter((entry) => !isPasskeyOnly(entry));779        return {780          ok: true,781          data: matches.map((e) =>782            includeAll783              ? {784                  id: e.id,785                  title: e.title,786                  hasPasskey: e.passkey !== undefined,787                }788              : {789                  id: e.id,790                  title: e.title,791                  username: e.username,792                  email: e.email,793                  url: e.url,794                  hasTotp: Boolean(e.totp),795                  hasPasskey: e.passkey !== undefined,796                }797          ),798        };799      }800      case "GET_ENTRY_FOR_FILL": {801        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };802        const { id } = msg.payload as { id: string };803        const entry = vault.getEntryById(id);804        if (!entry) return { ok: false, error: "entry_not_found" };805        // Passkey-only entries (passkey credential, no password) cannot be806        // filled into a form — sign-in goes through the WebAuthn path. A807        // login that ALSO has a passkey is still fillable for its password.808        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };809        // Strip the passkey credential from the response — content scripts810        // never need the private key, and there's no reason to expose the811        // public credential metadata over the boundary either.812        const { passkey: _strippedPasskey, ...safeEntry } = entry;813        return { ok: true, data: safeEntry };814      }815      case "COPY": {816        // AUD-002: shape-validate the payload before passing to the clipboard817        // helper. A raw cast lets a malformed message reach the clipboard API818        // with a non-string and throw.819        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {820          text?: unknown;821          label?: unknown;822          alreadyWritten?: unknown;823        };824        if (typeof text !== "string" || typeof label !== "string") {825          return { ok: false, error: "invalid_payload" };826        }827        await copyToClipboard(text, label, Boolean(alreadyWritten));828        return { ok: true };829      }830      case "CHECK_ALL_BREACHES": {831        const allEntries = vault.getEntries();832        const results: Record<string, number> = {};833        for (const entry of allEntries) {834          if (entry.type === "note") continue;835          if (!entry.password) continue;836          results[entry.id] = await vault.checkBreach(entry.password);837          // Small delay — be a good citizen to the HIBP API838          await new Promise((r) => setTimeout(r, 200));839        }840        // Persist any non-zero counts back to entries841        for (const [id, count] of Object.entries(results)) {842          const entry = vault.getEntryById(id);843          if (entry && (entry.breach ?? 0) !== count) {844            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });845          }846        }847        return { ok: true, data: results };848      }849      case "GET_SETTINGS":850        return { ok: true, data: await vault.ensureSettingsLoaded() };851      case "UPDATE_SETTINGS": {852        const patch = msg.payload;853        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {854          return { ok: false, error: "invalid_payload" };855        }856        await vault.updateSettings(patch as vault.VaultSettings);857        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {858          await setupAutoLock();859          if (vault.isUnlocked()) touchAutoLock();860        }861        return { ok: true };862      }863      case "GET_PENDING_PASSKEY":864        return { ok: true, data: await getPendingPasskeyRequest() };865      case "APPROVE_PASSKEY": {866        const { requestId } = msg.payload as { requestId: number };867        await resolvePendingPasskeyRequest(requestId, true);868        return { ok: true };869      }870      case "DENY_PASSKEY": {871        const { requestId } = msg.payload as { requestId: number };872        await resolvePendingPasskeyRequest(requestId, false);873        return { ok: true };874      }875      case "GET_PASSKEY_PROVIDER_STATE":876        return { ok: true, data: await getPasskeyProviderState() };877      case "SET_PASSKEY_PROVIDER_ENABLED": {878        const { enabled } = msg.payload as { enabled: boolean };879        // Disabling is always free; gating fires only when a free user is880        // trying to turn passkey interception on.881        if (enabled) {882          const gate = await requirePro("passkeys");883          if (!gate.allowed) return { ok: false, error: "pro_required" };884        }885        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };886      }887      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS888      // endpoint. Intentional product behavior — users configure their own889      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private890      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-891      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to892      // users that the entry title leaves the device when the canary fires.893      case "FIRE_CANARY_PING": {894        const { webhookUrl, entryTitle, trigger } = msg.payload as {895          webhookUrl: string;896          entryTitle: string;897          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";898        };899        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {900          return { ok: false, error: "invalid_webhook_url" };901        }902        const body = JSON.stringify({903          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",904          entry: entryTitle,905          trigger,906          timestamp: new Date().toISOString(),907          source: "peach-extension",908        });909        if (trigger === "test") {910          // Permitted outbound fetch: user-configured canary alert endpoint911          // (validated by isAllowedCanaryWebhookUrl above). This is the912          // only non-HIBP outbound call in the extension — see913          // Projects.md §3.7. Test pings are awaited so the UI can show914          // success/failure.915          try {916            const res = await fetch(webhookUrl, {917              method: "POST",918              headers: { "Content-Type": "application/json" },919              body,920            });921            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };922          } catch (err) {923            return { ok: false, error: err instanceof Error ? err.message : "network_error" };924          }925        }926        // Non-test triggers are fire-and-forget927        fetch(webhookUrl, {928          method: "POST",929          headers: { "Content-Type": "application/json" },930          body,931        }).catch(() => {});932        return { ok: true };933      }934      case "ACTIVATE_LICENSE": {935        const { key } = msg.payload as { key: string };936        const licenseInfo = await activateLicense(key);937        return { ok: true, data: licenseInfo };938      }939      case "GET_LICENSE": {940        const licenseInfo = await getLicenseInfo();941        return { ok: true, data: licenseInfo };942      }943      case "GET_LICENSE_KEY": {944        const key = await getLicenseKey();945        return { ok: true, data: key };946      }947      case "DEACTIVATE_LICENSE": {948        await deactivateLicense();949        return { ok: true };950      }951      case "SHOULD_PLAY_CELEBRATION": {952        const should = await shouldPlayCelebration();953        return { ok: true, data: should };954      }955      case "MARK_CELEBRATION_PLAYED": {956        await markCelebrationPlayed();957        return { ok: true };958      }959      case "GET_CODEX_VAULT_DATA": {960        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the961        // popup navigates to the License section without further coordination.962        const gate = await requirePro("codex");963        if (!gate.allowed) return { ok: false, error: "pro_required" };964        return await handleGetCodexVaultData();965      }966      case "ESTIMATE_CODEX_PAGES": {967        const gate = await requirePro("codex");968        if (!gate.allowed) return { ok: false, error: "pro_required" };969        return await handleEstimateCodexPages();970      }971      case "RESTORE_FROM_CODEX": {972        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still973        // be able to restore a vault that was printed by a Pro user.974        // DO NOT add a Pro gate here.975        const payload = msg.payload as CodexRestorePayload;976        return await handleRestoreFromCodex(payload);977      }978      case "OPEN_PRO_GATE": {979        // Content script requests: open popup and navigate to License section.980        const { feature } = (msg.payload ?? {}) as { feature?: string };981        if (chrome.storage.session) {982          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });983        }984        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }985        return { ok: true };986      }987      case "GET_IDENTITIES": {988        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };989        return { ok: true, data: vault.getIdentities() };990      }991      case "TOUCH_AUTO_LOCK": {992        // touchAutoLock() is already called by shouldRefreshAutoLock above;993        // this case just gives the popup a typed message to keep the session alive.994        return { ok: true };995      }996      case "GET_ADVANCED_HEALTH_REPORT": {997        const gate = await requirePro("advanced_health");998        if (!gate.allowed) return { ok: false, error: "pro_required" };999        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1000        const report = await buildAdvancedHealthReport(vault.getEntries());1001        return { ok: true, data: report };1002      }1003      case "INITIATE_PASSWORD_CHANGE": {1004        const gate = await requirePro("smart_password_change");1005        if (!gate.allowed) return { ok: false, error: "pro_required" };1006        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1007        const { id } = msg.payload as { id: string };1008        const entry = vault.getEntryById(id);1009        if (!entry) return { ok: false, error: "entry_not_found" };1010        const url = resolveResetUrl(entry);1011        if (!url) return { ok: false, error: "no_reset_url" };1012        try {1013          await chrome.tabs.create({ url });1014          return { ok: true, data: { url } };1015        } catch (err) {1016          return {1017            ok: false,1018            error: err instanceof Error ? err.message : "failed_to_open_tab",1019          };1020        }1021      }1022      case "IS_DURESS_ENABLED": {1023        const enabled = await vault.isDuressEnabled();1024        return { ok: true, data: enabled };1025      }1026      case "SETUP_DURESS": {1027        const { duressPassword } = msg.payload as { duressPassword: string };1028        await vault.setupDuress(duressPassword);1029        return { ok: true };1030      }1031      case "DISABLE_DURESS": {1032        await vault.disableDuress();1033        return { ok: true };1034      }1035      case "VERIFY_MAIN_PASSWORD": {1036        const { password } = msg.payload as { password: string };1037        const ok = await vault.verifyMainPassword(password);1038        return { ok: true, data: ok };1039      }1040      case "CHANGE_PASSWORD": {1041        const { currentPassword, newPassword } = msg.payload as {1042          currentPassword: string;1043          newPassword: string;1044        };1045        const changed = await vault.changePassword(currentPassword, newPassword);1046        return changed1047          ? { ok: true }1048          : { ok: false, error: "incorrect_current_password" };1049      }1050      case "GET_SITE_PASSWORD_POLICY": {1051        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1052        if (!tab?.id) return { ok: true, data: null };1053        try {1054          const response = await chrome.tabs.sendMessage(tab.id, {1055            type: "GET_SITE_PASSWORD_POLICY",1056          });1057          return (response as MessageResponse) ?? { ok: true, data: null };1058        } catch {1059          return { ok: true, data: null };1060        }1061      }1062      case "GET_SYNC_STATE": {1063        const pairedDevices = await getPairedDevices();1064        const trustedNetworks = await getTrustedNetworks();1065        const tailscale = await isOnTailscale();1066        const pro = await isProUser();10671068        let status: SyncStatus = "offline";1069        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {1070          if (pairedDevices.length === 0) {1071            status = "no_peers";1072          } else {1073            status = "synced";1074          }1075        } else {1076          status = "not_trusted";1077        }10781079        const lastSyncRaw = await storageGet("peach_last_sync_at");1080        const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN;1081        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined;10821083        return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } };1084      }1085      case "GET_PAIRED_DEVICES": {1086        const devices = await getPairedDevices();1087        return { ok: true, data: { devices } };1088      }1089      case "GET_SYNC_STATUS": {1090        const lastSyncRaw = await storageGet("peach_last_sync_at");1091        const lastSyncParsed = lastSyncRaw ? parseInt(lastSyncRaw, 10) : NaN;1092        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : null;1093        const status: 'up_to_date' | 'never' = lastSyncAt ? 'up_to_date' : 'never';1094        return { ok: true, data: { status, lastSyncAt } };1095      }1096      case "ACCEPT_PAIRING": {1097        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.1098        return { ok: true };1099      }1100      case "REMOVE_PAIRED_DEVICE": {1101        const { deviceId } = msg.payload as { deviceId: string };1102        await removePairedDevice(deviceId);1103        return { ok: true };1104      }1105      case "REMOVE_TRUSTED_NETWORK": {1106        const payload = msg.payload as1107          | { ssid?: unknown; bssid?: unknown; isTailscale?: unknown }1108          | null1109          | undefined;1110        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {1111          return { ok: false, error: "invalid_payload" };1112        }1113        const { ssid, bssid, isTailscale } = payload as { ssid?: string; bssid?: string; isTailscale?: boolean };1114        const networks = await getTrustedNetworks();1115        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 1116          (isTailscale ? n.isTailscale : n.ssid === ssid) && 1117          (!bssid || n.bssid === bssid)1118        );1119        if (network) {1120          await removeTrustedNetwork(network.addedAt);1121        }1122        return { ok: true };1123      }1124      case "MARK_NETWORK_TRUSTED": {1125        const network = await getCurrentNetwork();1126        await addTrustedNetwork({1127          ssid: network.ssid,1128          bssid: network.bssid,1129          isTailscale: network.isTailscale,1130          addedAt: Date.now(),1131        });1132        return { ok: true };1133      }1134      case "GET_INCOMING_PAIRING_REQUEST": {1135        const request = await getIncomingPairingRequest();1136        return { ok: true, data: request };1137      }1138      case "RESPOND_INCOMING_PAIRING": {1139        const { accept } = msg.payload as { accept: boolean };1140        const request = await getIncomingPairingRequest();1141        if (!request) return { ok: false, error: "no_pending_request" };1142        if (Date.now() > request.expiresAt) {1143          await clearIncomingPairingRequest();1144          return { ok: false, error: "expired" };1145        }1146        await clearIncomingPairingRequest();1147        if (accept) {1148          await addPairedDevice({1149            deviceId: request.publicKeyHex,1150            displayName: request.deviceName,1151            x25519PublicKey: request.publicKeyHex,1152            pairedAt: Date.now(),1153            lastSeenAt: Date.now(),1154          });1155        }1156        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };1157      }1158      case "START_PAIRING_SERVER": {1159        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.1160        const token = generateSixDigitToken();1161        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;1162        await setActivePairingToken({ token, expiresAt });1163        // Fire-and-forget subnet scan — finds the phone after it scans the QR1164        // and calls SCAN_PAIRING_QR to register the token with SyncPlugin.1165        if (!isNativePlatform()) {1166          void runPairingSubnetScan(token);1167        }1168        return { ok: true, data: { token, expiresAt } };1169      }1170      case "STOP_PAIRING_SERVER": {1171        try {1172          await setActivePairingToken(null);1173        } catch { /* best-effort */ }1174        return { ok: true };1175      }1176      case "GET_RECENT_PAIRING": {1177        const recent = await consumeRecentPairing();1178        return { ok: true, data: recent };1179      }1180      case "DEBUG_INJECT_INCOMING_PAIRING": {1181        // M14/SEC-007: blocked in production builds. The handler exists for1182        // Phase 7 banner UX rehearsal without a live native host; shipping1183        // it in production lets any background-message sender inject a1184        // synthetic pairing prompt. Allowed in 'development' and 'test'1185        // modes; vite sets MODE='production' for release builds.1186        if (import.meta.env.MODE === "production") {1187          return { ok: false, error: "not_available" };1188        }1189        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {1190          deviceName?: string;1191          publicKeyHex?: string;1192        };1193        if (!deviceName || !publicKeyHex) {1194          return { ok: false, error: "missing_payload" };1195        }1196        const now = Date.now();1197        await setIncomingPairingRequest({1198          deviceName,1199          publicKeyHex,1200          receivedAt: now,1201          expiresAt: now + 60_000,1202        });1203        return { ok: true };1204      }1205      case "RESET_SYNC_IDENTITY": {1206        const gate = await requirePro("sync");1207        if (!gate.allowed) return { ok: false, error: "pro_required" };1208        const devices = await getPairedDevices();1209        for (const device of devices) {1210          await removePairedDevice(device.deviceId);1211        }1212        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };1213      }1214      case "RECORD_MANUAL_SUMMON": {1215        const { domain } = msg.payload as { domain: string };1216        const settings = vault.getSettings();1217        const existing = settings.manualSummonDomains?.[domain];1218        const now = Date.now();1219        await vault.updateSettings({1220          manualSummonDomains: {1221            ...settings.manualSummonDomains,1222            [domain]: {1223              firstSummonedAt: existing?.firstSummonedAt ?? now,1224              summonCount: (existing?.summonCount ?? 0) + 1,1225              lastSummonedAt: now,1226            },1227          },1228        });1229        return { ok: true };1230      }1231      case "DECLINE_CARD_SAVE": {1232        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1233        await vault.declineCardSaveOffer(last4, expMonth, expYear);1234        return { ok: true };1235      }1236      case "IS_CARD_DECLINED": {1237        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1238        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1239        return { ok: true, data: declined };1240      }1241      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1242        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1243          rpId?: string;1244          rpName?: string;1245          userName?: string;1246          userDisplayName?: string;1247        };1248        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1249        return await initiateFirefoxPasskeyCreate({1250          rpId,1251          rpName: rpName ?? rpId,1252          userName,1253          userDisplayName,1254        });1255      }12561257      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1258        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1259        if (!payload) return { ok: false, error: "missing_payload" };1260        return await completeFirefoxPasskeyCreate(payload);1261      }12621263      case "PASSKEY_OFFER_DECLINE": {1264        const { domain } = (msg.payload ?? {}) as { domain?: string };1265        if (!domain) return { ok: false, error: "domain_required" };1266        await recordPasskeyOfferDecline(domain);1267        return { ok: true };1268      }12691270      case "GET_PASSKEY_OFFER_DECLINED": {1271        const { domain } = (msg.payload ?? {}) as { domain?: string };1272        if (!domain) return { ok: false, error: "domain_required" };1273        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1274      }12751276      case "PASSKEY_HAS_CREDENTIALS": {1277        const payload = msg.payload as {1278          rpId?: string;1279          allowCredentials?: Array<{ id: string; type?: string }>;1280        } | undefined;1281        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1282        return await handlePasskeyHasCredentials({1283          rpId: payload.rpId,1284          allowCredentials: payload.allowCredentials ?? [],1285        });1286      }12871288      case "PASSKEY_CREATE": {1289        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1290        if (!payload?.rpId || !payload?.userName) {1291          return { ok: false, error: "rpid_and_username_required" };1292        }1293        return await handleFirefoxPasskeyCreate(payload);1294      }12951296      case "PASSKEY_GET": {1297        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1298        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1299        return await handleFirefoxPasskeyGet(payload);1300      }13011302      case "PASSKEY_AUTH_RESPONSE": {1303        const { requestId, approved } = (msg.payload ?? {}) as {1304          requestId?: string | number;1305          approved?: boolean;1306        };1307        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1308          return { ok: false, error: 'requestId and approved required' };1309        }1310        await resolvePendingPasskeyRequest(Number(requestId), approved);1311        return { ok: true };1312      }13131314      case "GET_PASSKEY_FOR_DOMAIN": {1315        const { domain } = (msg.payload ?? {}) as { domain?: string };1316        if (!domain) return { ok: false, error: "domain_required" };1317        if (!vault.isUnlocked()) return { ok: true, data: null };1318        const match = vault1319          .getEntries()1320          .find((entry) => entry.passkey?.rpId === domain);1321        if (!match || !match.passkey) return { ok: true, data: null };1322        // Slim shape — only the fields State 11 needs. Never expose private1323        // key material, even though this is locked behind isUnlocked.1324        return {1325          ok: true,1326          data: {1327            rpId: match.passkey.rpId,1328            userName: match.passkey.userName,1329            browser: match.passkey.browser,1330          },1331        };1332      }13331334      case "DESTROY_VAULT": {1335        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1336        // storage.local.clear() wipes every Peach key (slots, settings, license,1337        // onboarded flag, history, sync state, declined cards, recall, etc.);1338        // session.clear() wipes pending passkey requests + pro-notice queues.1339        // Caller (Panic.tsx) handles UI navigation back to onboarding.1340        vault.lock();1341        await storageClear();1342        await vault.clearVaultHistory();1343        if (chrome.storage.session) {1344          await chrome.storage.session.clear();1345        }1346        return { ok: true };1347      }13481349      case "SUBMIT_FEEDBACK": {1350        const { category, message, version, browser } = msg.payload as {1351          category: string;1352          message: string;1353          version: string;1354          browser: string;1355        };1356        if (!message.trim()) return { ok: false, error: "message_empty" };1357        if (!FEEDBACK_ENDPOINT) return { ok: true };1358        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1359          return { ok: false, error: "invalid_feedback_endpoint" };1360        }1361        try {1362          const res = await fetch(FEEDBACK_ENDPOINT, {1363            method: "POST",1364            headers: { "Content-Type": "application/json" },1365            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1366          });1367          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1368        } catch (err) {1369          return { ok: false, error: err instanceof Error ? err.message : "network_error" };1370        }1371      }1372      case "TRIGGER_SYNC": {1373        const gate = await requirePro("sync");1374        if (!gate.allowed) return { ok: false, error: "pro_required" };1375        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };13761377        if (isNativePlatform()) {1378          // Phone is the server — ensure it's listening for desktop connections.1379          syncBridge()?.ensureServerRunning?.();1380          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };1381        }13821383        // Desktop: iterate all paired devices and sync with each.1384        const paired = await getPairedDevices();1385        if (!paired.length) return { ok: true, data: { syncedCount: 0, reason: "no_paired_devices" } };13861387        const subnet = await getLocalSubnet();1388        const results: Array<{ device: string } & SyncResult> = [];13891390        for (const device of paired) {1391          const pubkey = device.x25519PublicKey;1392          if (!pubkey) continue;13931394          let result: SyncResult;13951396          // Fast path — use last known IP1397          if (device.lastKnownIp) {1398            result = await doVaultSync(device.lastKnownIp, pubkey);1399          } else {1400            result = { status: 'errored', applied: false, error: 'no_ip' };1401          }14021403          // Discovery path — scan if fast path failed1404          if (result.status === 'errored' && subnet) {1405            const newIp = await discoverDevice(subnet, pubkey);1406            if (newIp) {1407              await updatePairedDevice(pubkey, { lastKnownIp: newIp });1408              result = await doVaultSync(newIp, pubkey);1409            }1410          }14111412          if (result.status === 'completed') {1413            await updatePairedDevice(pubkey, {1414              lastSeenAt: Date.now(),1415              lastSyncAt: Date.now(),1416            });1417          }14181419          results.push({ device: device.displayName ?? "", ...result });1420        }14211422        const syncedCount = results.filter(r => r.status === 'completed').length;1423        if (syncedCount > 0) {1424          await chrome.storage.local.set({ peach_last_sync_at: String(Date.now()) });1425        }1426        return { ok: true, data: { syncedCount, results } };1427      }1428      // Android-only: biometric unlock with pre-derived key.1429      case "UNLOCK_WITH_KEY": {1430        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1431        if (!isNativePlatform()) {1432          return { ok: false, error: "desktop_only_uses_password" };1433        }1434        try {1435          const result = await vault.unlockWithKey(masterKeyHex);1436          if (result.ok) {1437            onVaultUnlocked();1438            await publishInMemoryVault(result.entries);1439          }1440          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1441        } catch {1442          return { ok: false, error: "invalid_key" };1443        }1444      }1445      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1446      case "GET_DERIVED_KEY": {1447        if (!isNativePlatform()) {1448          return { ok: false, error: "android_only" };1449        }1450        if (!vault.isUnlocked()) {1451          return { ok: false, error: "vault_locked" };1452        }1453        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1454      }1455      // Android: scanned a QR containing a desktop pairing token.1456      case "SCAN_PAIRING_QR": {1457        if (!isNativePlatform()) {1458          return { ok: false, error: "android_only" };1459        }1460        const { token } = msg.payload as { token: string };1461        syncBridge()?.startPairingSession?.({ token });1462        return { ok: true };1463      }1464      // Android: desktop opened a sync connection to the phone's WS server.1465      // Run the responder side of the vault exchange.1466      case "SYNC_SESSION_STARTED": {1467        if (!isNativePlatform()) return { ok: false };1468        if (!vault.isUnlocked()) {1469          return { ok: false, error: "vault_locked" };1470        }1471        const { connectionId } = (msg.payload ?? {}) as { connectionId?: string };1472        if (!connectionId) return { ok: false, error: "missing_connection_id" };14731474        const transport = createAndroidResponderTransport(connectionId);14751476        // Authenticate the initiator before exchanging any vault data. The1477        // native side has already completed the Noise NK handshake; auth1478        // frames here ride the Noise transport (native encrypts/decrypts).1479        const identity = await vault.getSyncIdentity();1480        try {1481          // CAUTION: noiseSessionStub is a structural placeholder — the real1482          // Noise NK handshake runs natively, so JS never holds the session1483          // object. performResponderAuth currently `void`s this argument,1484          // which is why identity-passthrough encrypt/decrypt and a zero1485          // handshake hash are safe. If performResponderAuth is ever updated1486          // to actually use this argument, this auth path will silently break1487          // (no type error). Revisit this stub if that helper changes.1488          const noiseSessionStub = {1489            encrypt: (b: Uint8Array) => b,1490            decrypt: (b: Uint8Array) => b,1491            handshakeHash: new Uint8Array(32),1492          };1493          const { initiatorPublicKey } = await performResponderAuth(1494            noiseSessionStub,1495            identity.privateKeyBytes,1496            identity.publicKeyBytes,1497            transport.send,1498            transport.receive,1499          );1500          const initiatorHex = noiseBytesToHex(initiatorPublicKey);1501          const paired = await getPairedDevices();1502          if (!paired.some(d => d.x25519PublicKey === initiatorHex)) {1503            await transport.close();1504            return { ok: false, error: "sync_rejected_unpaired_initiator" };1505          }1506          // Initiator just proved control of the matching static key; mark it1507          // as a verified handshake so a follow-up PAIRING_COMPLETED message1508          // can be trusted (M13/SEC-005).1509          markPairingHandshakeVerified(initiatorHex);1510        } catch (err) {1511          await transport.close();1512          return { ok: false, error: `sync_auth_failed: ${String(err)}` };1513        }15141515        const result = await runBlobSyncSession('responder', transport, buildSyncDeps());1516        if (result.applied) {1517          await publishInMemoryVault(vault.getEntries());1518        }1519        return { ok: true, data: result };1520      }1521      // Android: returns the phone's WiFi IP address.1522      case "GET_LOCAL_IP": {1523        if (!isNativePlatform()) {1524          return { ok: false, error: "android_only" };1525        }1526        const { ip } = (await syncBridge()?.getLocalIp?.()) ?? { ip: "" };1527        return { ok: true, data: { ip } };1528      }1529      case "GET_IDENTITY_SUGGESTIONS": {1530        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1531        const entries = vault.getEntries();1532        const suggestions = buildIdentitySuggestions(entries);1533        return { ok: true, data: { suggestions } };1534      }1535      case "POPULATE_INLINE_VAULT": {1536        if (!isNativePlatform()) return { ok: false };1537        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1538        const entries = vault.getEntries();1539        await publishInMemoryVault(entries);1540        return { ok: true };1541      }1542      case "ML_INIT":1543        return { ok: true };15441545      case "ML_PREDICT_BATCH": {1546        // AUD-002: shape-validate before forwarding to the ML helper.1547        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1548        if (!Array.isArray(featuresArray)) {1549          return { ok: false, error: "invalid_payload" };1550        }1551        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1552      }15531554      // ── Chirp Sync (v3) ───────────────────────────────────────────────1555      // Returns the public-facing local identity needed by the popup to1556      // drive Phase-1 audio pairing. The private long-term key never1557      // leaves the background.1558      case "CHIRP_GET_LOCAL_IDENTITY": {1559        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1560        const proCheck = await requirePro("sync");1561        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1562        const masterKeyHex = vault.getDerivedKeyHex();1563        const masterKey = unhexBytes(masterKeyHex);1564        try {1565          const identity = await buildLocalIdentity(masterKey);1566          return { ok: true, data: identity };1567        } finally {1568          masterKey.fill(0);1569        }1570      }15711572      case "CHIRP_COMPLETE_PAIRING": {1573        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1574        const proCheck = await requirePro("sync");1575        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1576        const paired = (msg.payload as { paired?: unknown })?.paired;1577        if (typeof paired !== "object" || paired === null) {1578          return { ok: false, error: "invalid_payload" };1579        }1580        const candidate = paired as Record<string, unknown>;1581        if (1582          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1583          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1584          typeof candidate.deviceType !== "string" ||1585          typeof candidate.longTermPublicKeyHex !== "string" ||1586          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1587          typeof candidate.pairedAt !== "number"1588        ) {1589          return { ok: false, error: "invalid_paired_device" };1590        }1591        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1592        return { ok: true };1593      }15941595      case "CHIRP_LIST_PAIRED_DEVICES": {1596        const devices = await listPairedDevicesV3();1597        return { ok: true, data: { devices } };1598      }15991600      case "CHIRP_UNPAIR_DEVICE": {1601        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1602        if (typeof deviceId !== "string" || !deviceId) {1603          return { ok: false, error: "invalid_payload" };1604        }1605        await removePairedDeviceByIdV3(deviceId);1606        return { ok: true };1607      }16081609      case "CHIRP_RENAME_LOCAL_DEVICE": {1610        const { name } = (msg.payload ?? {}) as { name?: string };1611        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1612        await setDeviceNameV3(name);1613        return { ok: true };1614      }16151616      default:1617        return { ok: false, error: "unknown_message_type" };1618    }1619  } catch (err) {1620    return {1621      ok: false,1622      error: err instanceof Error ? err.message : "operation_failed",1623    };1624  }1625}16261627// --- Mobile platform helpers ---16281629// Android: populates the in-memory vault used by PeachAutofillService.1630async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1631  const plugin = nativePlugin<{1632    setEntries?: (args: {1633      entries: Array<{1634        id: string;1635        title: string;1636        username: string;1637        email: string;1638        password: string;1639        url: string;1640        totp: string;1641        additionalUrls: string[];1642      }>;1643    }) => Promise<void>;1644  }>("InMemoryVaultPlugin");1645  if (!plugin?.setEntries) return;1646  await plugin.setEntries({1647    entries: entries.map((e) => ({1648      id: e.id,1649      title: e.title ?? "",1650      username: e.username ?? "",1651      email: (e as VaultEntry & { email?: string }).email ?? "",1652      password: e.password ?? "",1653      url: e.url ?? "",1654      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1655      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1656    })),1657  });1658}16591660// Android: clear the autofill in-memory store on lock.1661async function clearInMemoryVault(): Promise<void> {1662  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1663  if (!plugin?.clearEntries) return;1664  await plugin.clearEntries();1665}16661667interface SyncBridge {1668  ensureServerRunning?: () => void;1669  startPairingSession?: (args: { token: string }) => void;1670  getLocalIp?: () => Promise<{ ip: string }>;1671  sendToConnection?: (args: { connectionId: string; data: string }) => Promise<void>;1672  addListener?: (event: string, handler: (data: Record<string, string>) => void) => void;1673}16741675// Resolve the Capacitor SyncPlugin at call time — module-load resolution1676// races with Capacitor's plugin registration on the Android WebView.1677function syncBridge(): SyncBridge | null {1678  return nativePlugin<SyncBridge>("SyncPlugin");1679}16801681// Build a SyncTransport for the Android responder path — the phone's WS server1682// already has an open connection from the desktop. We send back via1683// SyncPlugin.sendToConnection and receive via the peach:sync-frame queue.1684const androidSyncFrameQueues = new Map<string, Array<(frame: string) => void>>();16851686export function deliverAndroidSyncFrame(connectionId: string, frame: string): void {1687  const queue = androidSyncFrameQueues.get(connectionId);1688  if (queue?.length) queue.shift()!(frame);1689}16901691function createAndroidResponderTransport(connectionId: string) {1692  const pendingReceivers: Array<(frame: string) => void> = [];1693  androidSyncFrameQueues.set(connectionId, pendingReceivers);16941695  return {1696    send: async (data: Uint8Array) => {1697      await syncBridge()?.sendToConnection?.({ connectionId, data: bytesToBase64(data) });1698    },1699    receive: (): Promise<Uint8Array> => new Promise((res) => {1700      pendingReceivers.push((frame) => {1701        res(frame ? base64ToBytes(frame) : new Uint8Array(0));1702      });1703    }),1704    close: async () => {1705      androidSyncFrameQueues.delete(connectionId);1706    },1707  };1708}17091710// Returns username use-counts from the vault, sorted by frequency. Each row1711// also carries the entry's email so the popup can suggest the email/username1712// pair the user has actually used together.1713function buildIdentitySuggestions(1714  entries: VaultEntry[],1715): Array<{ email: string; username: string; count: number }> {1716  const usernameCounts = new Map<string, number>();1717  const usernameEmail = new Map<string, string>();1718  for (const entry of entries) {1719    const username = entry.username ?? "";1720    const email = (entry as VaultEntry & { email?: string }).email ?? "";1721    if (!username && !email) continue;1722    const key = username || email;1723    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1724    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1725  }1726  return Array.from(usernameCounts.entries())1727    .sort((a, b) => b[1] - a[1])1728    .map(([username, count]) => ({1729      email: usernameEmail.get(username) ?? "",1730      username,1731      count,1732    }));1733}17341735/** Notify all content scripts that the vault just became available. */1736function broadcastToContentScripts(message: { type: string }): void {1737  if (!chrome.tabs?.query) return;1738  chrome.tabs.query({}, (tabs) => {1739    for (const tab of tabs) {1740      if (tab.id !== undefined) {1741        chrome.tabs.sendMessage(tab.id, message).catch(() => {1742          // Tab may not have a content script — silently ignore1743        });1744      }1745    }1746  });1747}17481749function shouldRefreshAutoLock(type: MessageType): boolean {1750  return (1751    type !== "HAS_VAULT" &&1752    type !== "IS_UNLOCKED" &&1753    type !== "GET_VAULT_STATUS" &&1754    type !== "LOCK" &&1755    type !== "UPDATE_SETTINGS" &&1756    type !== "GET_PENDING_PASSKEY" &&1757    type !== "GET_PASSKEY_PROVIDER_STATE" &&1758    type !== "DECLINE_CARD_SAVE" &&1759    type !== "IS_CARD_DECLINED" &&1760    type !== "SUBMIT_FEEDBACK"1761  );1762}17631764function isAllowedCanaryWebhookUrl(value: string): boolean {1765  try {1766    const url = new URL(value);1767    if (url.protocol !== "https:") return false;17681769    const hostname = url.hostname.toLowerCase();1770    if (1771      hostname === "localhost" ||1772      hostname.endsWith(".localhost") ||1773      isPrivateIpv4(hostname) ||1774      isPrivateIpv6(hostname)1775    ) {1776      return false;1777    }17781779    return true;1780  } catch {1781    return false;1782  }1783}17841785function isPrivateIpv4(hostname: string): boolean {1786  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1787    return true;1788  }17891790  const octets = hostname.split(".").map((part) => Number(part));1791  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1792    return false;1793  }17941795  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1796}17971798function isPrivateIpv6(hostname: string): boolean {1799  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1800  return (1801    normalized === "::1" ||1802    normalized.startsWith("fc") ||1803    normalized.startsWith("fd") ||1804    normalized.startsWith("fe80:")1805  );1806}