messages.ts

65.7 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 * as vault from "./vault";15import {16  handleEstimateCodexPages,17  handleGetCodexVaultData,18  handleRestoreFromCodex,19} from "./codex-handlers";20import type { CodexRestorePayload } from "../shared/codex-types";21import {22  activateLicense,23  deactivateLicense,24  getLicenseInfo,25  getLicenseKey,26  isProUser,27  markCelebrationPlayed,28  shouldPlayCelebration,29} from "./license";30import {31  cancelFirefoxPasskeyCreate,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";8384/**85 * The single Pro gate. Every gated handler calls this first; the broadcast86 * lets the popup react (navigate to the License section, highlight the87 * relevant feature). Background never touches the popup view directly —88 * the popup owns navigation. See Projects.md "Pro gate rule".89 */90async function requirePro(91  feature: ProFeature,92  trigger: "user" | "background" = "user"93): Promise<{ allowed: boolean }> {94  if (await isProUser()) return { allowed: true };9596  if (trigger === "user") {97    // User deliberately triggered this feature — redirect the popup immediately.98    chrome.runtime99      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })100      .catch(() => {101        // Popup may be closed — the gate signal is best-effort.102      });103  } else {104    // Background trigger (e.g. passive sync initiation) — no popup is open.105    // Queue a notice so the next popup open shows a soft banner instead of106    // silently failing.107    if (chrome.storage.session) {108      chrome.storage.session109        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })110        .catch(() => {});111    }112  }113114  return { allowed: false };115}116117// ---------------------------------------------------------------------------118// Local device name. Peers see this string in PAIR_REQUEST / PAIR_ACCEPT and119// next to the device in their paired-devices list. Default to a platform-aware120// fallback when the user hasn't set one explicitly.121const DEVICE_NAME_KEY = "peach_device_name";122123async function getLocalDeviceName(): Promise<string> {124  try {125    const stored = await chrome.storage.local.get(DEVICE_NAME_KEY);126    const value = (stored as Record<string, string | undefined>)[DEVICE_NAME_KEY];127    if (typeof value === "string" && value.trim()) return value.trim();128  } catch {129    // fall through to default130  }131  return "Peach";132}133134// ---------------------------------------------------------------------------135// 6-digit code pairing.136137const PAIRING_TOKEN_TTL_MS = 5 * 60 * 1000;138139140function generateSixDigitToken(): string {141  // crypto.getRandomValues, not Math.random — the token is the only secret142  // protecting the pairing window from a same-LAN attacker. 6 decimal digits143  // is 1 in 1,000,000; combined with a 5-minute TTL and pairing-mode gating144  // on the responder this is the right tradeoff between UX and security.145  const buf = new Uint32Array(1);146  crypto.getRandomValues(buf);147  const value = buf[0] % 1_000_000;148  return value.toString().padStart(6, "0");149}150151// ---------------------------------------------------------------------------152// Peer discovery glue (Phase 7 popup pairing flow).153154const PRIVATE_IPV4_RANGES = [155  { prefix: "10." },156  { prefix: "127." },157  { prefix: "169.254." },158  { prefix: "192.168." },159];160161// Empty disables network submission while the UI continues to function as a162// no-op (the handler returns ok:true without calling fetch). When set, the163// URL is validated by `isAllowedCanaryWebhookUrl` before any request, so the164// same private-IP/HTTPS rules that gate canary webhooks apply here.165const FEEDBACK_ENDPOINT = "";166167// ---------------------------------------------------------------------------168// Sync helpers169// ---------------------------------------------------------------------------170171/**172 * Short-lived registry of x25519 public keys that just completed a real Noise173 * NK handshake + initiator-auth proof. The PAIRING_COMPLETED handler must174 * find the supplied publicKeyHex here before it will call addPairedDevice —175 * otherwise an attacker could forge the message and pair an arbitrary key176 * (M13/SEC-005).177 *178 * Entries auto-expire after 30s. Each entry is consumed on first successful179 * PAIRING_COMPLETED so a single handshake cannot pair twice.180 */181const PENDING_PAIRS = new Map<string, ReturnType<typeof setTimeout>>();182const PENDING_PAIR_TTL_MS = 30_000;183184export function markPairingHandshakeVerified(publicKeyHex: string): void {185  if (!publicKeyHex) return;186  const existing = PENDING_PAIRS.get(publicKeyHex);187  if (existing) clearTimeout(existing);188  const t = setTimeout(() => PENDING_PAIRS.delete(publicKeyHex), PENDING_PAIR_TTL_MS);189  PENDING_PAIRS.set(publicKeyHex, t);190}191192function consumePendingPair(publicKeyHex: string): boolean {193  const t = PENDING_PAIRS.get(publicKeyHex);194  if (!t) return false;195  clearTimeout(t);196  PENDING_PAIRS.delete(publicKeyHex);197  return true;198}199200export function buildSyncDeps(): SyncDeps {201  return {202    isVaultUnlocked: () => vault.isUnlocked(),203    getVaultBlobForSync: async () => {204      const base = await vault.getVaultBlobForSync();205      if (!base) return null;206      const paired = await getPairedDevices();207      return {208        ...base,209        devices: paired210          .filter(d => d.x25519PublicKey)211          .map(d => ({212            publicKeyHex: d.x25519PublicKey,213            deviceName: d.displayName,214            pairedAt: d.pairedAt,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          await setupAutoLock();449          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });450          onVaultUnlocked();451          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());452          return { ok: true };453        }454        // Distinguish corruption from wrong password so the popup can offer455        // a history-restore path instead of falsely accusing the user of456        // mistyping (M7/COR-007).457        const failure = vault.consumeLastUnlockFailureReason();458        if (failure) {459          return {460            ok: false,461            error: "vault_corrupted",462            canRestoreFromHistory: true,463          } as MessageResponse;464        }465        return { ok: false };466      }467      case "VALIDATE_RECOVERY_WORDS": {468        const { words } = msg.payload as { words: string[] };469        const invalid = findInvalidWords(words);470        return { ok: true, data: { valid: invalid.length === 0, invalid } };471      }472      case "GET_RECOVERY_WORDS": {473        // Must be unlocked and have recovery set up (vault must be v2.12+).474        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };475        try {476          const words = await vault.getRecoveryWords();477          return { ok: true, data: words };478        } catch (e) {479          // pre-v2.12 vault that hasn't migrated480          return { ok: false, error: "recovery_not_setup" };481        }482      }483      case "RECOVER_WITH_WORDS": {484        // User has lost their password but has their 12 recovery words.485        // We: (1) validate the words, (2) re-encrypt vault with new password.486        const { words, newPassword } = msg.payload as {487          words: string[];488          newPassword: string;489        };490        const stored = await vault.loadSlotA();491        if (!stored) return { ok: false, error: "no vault" };492        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {493          return { ok: false, error: "recovery_not_setup" };494        }495        // Unwrap the root key from the recovery escrow.496        try {497          await vault.unwrapRootKeyForRecovery(498            stored.recovery_wrapped_root_key,499            stored.recovery_nonce ?? "",500            stored.recovery_tag ?? "",501            stored.recovery_salt,502            words503          );504        } catch {505          return { ok: false, error: "invalid_recovery_words" };506        }507        // Re-key: derive fresh salt + key from new password.508        const newSalt = vault.generateSalt();509        const newKey = await vault.deriveKey(newPassword, newSalt);510        // Re-wrap root key under the new password's derived key so the same511        // recovery words continue to work after the password change.512        await vault.rewrapRootKeyForPassword(newKey, newSalt);513        // Re-encrypt vault entries with the new key.514        await vault.changePasswordWithNewKey(newSalt, newKey);515        await setupAutoLock();516        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });517        return { ok: true };518      }519      case "LOCK":520        vault.lock();521        if (isNativePlatform()) await clearInMemoryVault();522        return { ok: true };523      case "IS_UNLOCKED":524        return { ok: true, data: vault.isUnlocked() };525      case "GET_VAULT_STATUS":526        return { ok: true, unlocked: vault.isUnlocked() };527      case "HAS_VAULT":528        return { ok: true, data: await vault.hasVault() };529      case "GET_ENTRIES":530        return { ok: true, data: vault.getEntries() };531      case "ADD_ENTRY": {532        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };533        const payload = msg.payload;534        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {535          return { ok: false, error: "invalid_payload" };536        }537        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);538        return { ok: true, data: entry };539      }540      case "BATCH_ADD_ENTRIES": {541        const payload = msg.payload as { entries?: unknown } | null | undefined;542        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {543          return { ok: false, error: "invalid_payload" };544        }545        if (!Array.isArray(payload.entries)) {546          return { ok: false, error: "invalid_payload" };547        }548        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);549        return { ok: true, data: added };550      }551      case "RESTORE_ENTRIES": {552        const payload = msg.payload as553          | { entries?: unknown; mode?: unknown; settings?: unknown }554          | null555          | undefined;556        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {557          return { ok: false, error: "invalid_payload" };558        }559        if (!Array.isArray(payload.entries)) {560          return { ok: false, error: "invalid_payload" };561        }562        if (payload.mode !== "replace" && payload.mode !== "merge") {563          return { ok: false, error: "invalid_payload" };564        }565        const summary = await vault.restoreEntries(566          payload.entries as Parameters<typeof vault.restoreEntries>[0],567          payload.mode568        );569        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {570          await vault.updateSettings(payload.settings as vault.VaultSettings);571        }572        return { ok: true, data: summary };573      }574      case "CLEAR_VAULT_ENTRIES": {575        await vault.clearVaultEntries("REPLACE_ALL");576        return { ok: true };577      }578      case "GET_VAULT_HISTORY": {579        const snapshots = await vault.getVaultHistory();580        return { ok: true, data: snapshots };581      }582      case "RESTORE_VAULT_SNAPSHOT": {583        const { snapshotId } = msg.payload as { snapshotId: string };584        const result = await vault.restoreVaultSnapshot(snapshotId);585        if (!result.ok) return { ok: false, error: result.error };586        broadcastToContentScripts({ type: "VAULT_LOCKED" });587        return { ok: true };588      }589      case "COUNT_DUPLICATES": {590        return { ok: true, data: vault.countDuplicates() };591      }592      case "DEDUPLICATE_ENTRIES": {593        const removed = await vault.deduplicateEntries();594        return { ok: true, data: removed };595      }596      case "UPDATE_ENTRY": {597        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;598        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {599          return { ok: false, error: "invalid_payload" };600        }601        const { id, patch } = payload;602        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {603          return { ok: false, error: "invalid_payload" };604        }605        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);606        return { ok: true };607      }608      case "ADD_ADDITIONAL_URL": {609        const { id, url } = msg.payload as { id: string; url: string };610        const trimmed = typeof url === "string" ? url.trim() : "";611        if (!trimmed) return { ok: false, error: "url required" };612        const existing = vault.getEntryById(id);613        if (!existing) return { ok: false, error: "entry not found" };614        if (existing.type !== "login") return { ok: false, error: "login entries only" };615        const merged = [...(existing.additionalUrls ?? []), trimmed];616        await vault.updateEntry(id, { additionalUrls: merged });617        return { ok: true };618      }619      case "DELETE_ENTRY": {620        const { id } = msg.payload as { id: string };621        await vault.deleteEntry(id);622        return { ok: true };623      }624      case "GET_DELETED_ENTRIES":625        return { ok: true, data: vault.getDeletedEntries() };626      case "RESTORE_ENTRY": {627        const { id } = msg.payload as { id: string };628        await vault.restoreEntry(id);629        return { ok: true };630      }631      case "PURGE_ENTRY": {632        const { id } = msg.payload as { id: string };633        await vault.purgeEntry(id);634        return { ok: true };635      }636      case "PURGE_EXPIRED_TRASH": {637        const { retentionMs } = msg.payload as { retentionMs: number };638        const purged = await vault.purgeExpiredTrash(retentionMs);639        return { ok: true, data: purged };640      }641      case "SAVE_NOTE": {642        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };643        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };644        const now = Date.now();645        if (id) {646          const existing = vault.getEntryById(id);647          if (!existing) return { ok: false, error: "not_found" };648          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });649          return { ok: true, data: vault.getEntryById(id) };650        } else {651          const entry = await vault.addEntry({652            type: "note",653            title: title || "Untitled",654            notes: body,655            createdAt: now,656            modifiedAt: now,657          } as any);658          return { ok: true, data: entry };659        }660      }661      case "DELETE_NOTE": {662        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };663        const { id } = msg.payload as { id: string };664        await vault.deleteEntry(id);665        return { ok: true };666      }667      case "GET_NOTES": {668        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };669        const notes = vault.getEntries().filter(670          (e) => e.type === "note" && !e.deletedAt671        );672        return { ok: true, data: notes } as MessageResponse;673      }674      case "SEARCH_VAULT": {675        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };676        const { query } = msg.payload as { query: string };677        const q = query.toLowerCase();678        const searchResults = vault.getEntries().filter(679          (e) =>680            !e.deletedAt &&681            (e.title.toLowerCase().includes(q) ||682              e.notes?.toLowerCase().includes(q) ||683              e.username?.toLowerCase().includes(q))684        );685        return { ok: true, data: searchResults } as MessageResponse;686      }687      case "PAIRING_COMPLETED": {688        const { deviceName, publicKeyHex, deviceIp } = (msg.payload ?? {}) as {689          deviceName?: string;690          publicKeyHex?: string;691          deviceIp?: string;692        };693        if (!publicKeyHex) return { ok: false, error: "publicKeyHex required" };694        // Only accept publicKeyHex values that just completed a real Noise NK695        // handshake (initiator or responder side). Without this gate, anyone696        // who can sendMessage to the background can pair an arbitrary key697        // (M13/SEC-005). Re-confirming an already-paired device is allowed698        // so legitimate update-IP retries still work.699        const alreadyPaired = (await getPairedDevices()).some(700          d => d.x25519PublicKey === publicKeyHex,701        );702        const verified = consumePendingPair(publicKeyHex);703        if (!verified && !alreadyPaired) {704          return { ok: false, error: "pairing_not_verified" };705        }706        const { setHasPaired: setPaired } = await import("./sync-storage");707        await setPaired();708        try {709          await addPairedDevice({710            deviceId: publicKeyHex,711            displayName: deviceName ?? "Unknown",712            x25519PublicKey: publicKeyHex,713            pairedAt: Date.now(),714            lastSeenAt: Date.now(),715            lastKnownIp: deviceIp,716          });717        } catch {718          // Already paired — update IP if provided719          if (deviceIp) {720            await updatePairedDevice(publicKeyHex, { lastKnownIp: deviceIp, lastSeenAt: Date.now() });721          }722        }723        return { ok: true };724      }725      case "AUTOFILL_QUERY": {726        if (!vault.isUnlocked()) {727          return { ok: false, error: "VAULT_LOCKED" };728        }729        const { domain, includeAll, kind } = msg.payload as {730          domain: string;731          includeAll?: boolean;732          kind?: "login" | "card";733        };734        // kind="card": return saved cards as compact summaries for the735        // inline card silver platter. Cards are not domain-scoped — every736        // saved card is a candidate on every checkout page — so domain is737        // ignored when kind === "card".738        if (kind === "card") {739          const cards = vault.getEntries().filter((e) => e.type === "card");740          return {741            ok: true,742            data: cards.map((e) => ({743              id: e.id,744              title: e.cardNickname || e.title,745              cardholderName: e.cardholderName,746              last4: e.last4,747              expMonth: e.expMonth,748              expYear: e.expYear,749              network: e.network,750            })),751          };752        }753        // The inline selector fills username+password into a form. Passkey-754        // only entries have no password to fill; sign-in for those goes755        // through the WebAuthn path instead. Filter them out everywhere so756        // the user doesn't see four "GitHub" rows that mostly do nothing.757        // Notes and cards never belonged here either.758        const matches = (759          includeAll760            ? vault761                .getEntries()762                .filter((entry) => entry.type !== "note" && entry.type !== "card")763            : vault.queryDomain(domain)764        ).filter((entry) => !isPasskeyOnly(entry));765        return {766          ok: true,767          data: matches.map((e) =>768            includeAll769              ? {770                  id: e.id,771                  title: e.title,772                  hasPasskey: e.passkey !== undefined,773                }774              : {775                  id: e.id,776                  title: e.title,777                  username: e.username,778                  email: e.email,779                  url: e.url,780                  hasTotp: Boolean(e.totp),781                  hasPasskey: e.passkey !== undefined,782                }783          ),784        };785      }786      case "GET_ENTRY_FOR_FILL": {787        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };788        const { id } = msg.payload as { id: string };789        const entry = vault.getEntryById(id);790        if (!entry) return { ok: false, error: "entry not found" };791        // Passkey-only entries (passkey credential, no password) cannot be792        // filled into a form — sign-in goes through the WebAuthn path. A793        // login that ALSO has a passkey is still fillable for its password.794        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey not fillable" };795        // Strip the passkey credential from the response — content scripts796        // never need the private key, and there's no reason to expose the797        // public credential metadata over the boundary either.798        const { passkey: _strippedPasskey, ...safeEntry } = entry;799        return { ok: true, data: safeEntry };800      }801      case "COPY": {802        const { text, label, alreadyWritten } = msg.payload as {803          text: string;804          label: string;805          alreadyWritten?: boolean;806        };807        await copyToClipboard(text, label, Boolean(alreadyWritten));808        return { ok: true };809      }810      case "CHECK_ALL_BREACHES": {811        const allEntries = vault.getEntries();812        const results: Record<string, number> = {};813        for (const entry of allEntries) {814          if (entry.type === "note") continue;815          if (!entry.password) continue;816          results[entry.id] = await vault.checkBreach(entry.password);817          // Small delay — be a good citizen to the HIBP API818          await new Promise((r) => setTimeout(r, 200));819        }820        // Persist any non-zero counts back to entries821        for (const [id, count] of Object.entries(results)) {822          const entry = vault.getEntryById(id);823          if (entry && (entry.breach ?? 0) !== count) {824            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });825          }826        }827        return { ok: true, data: results };828      }829      case "GET_SETTINGS":830        return { ok: true, data: await vault.ensureSettingsLoaded() };831      case "UPDATE_SETTINGS": {832        const patch = msg.payload;833        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {834          return { ok: false, error: "invalid_payload" };835        }836        await vault.updateSettings(patch as vault.VaultSettings);837        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {838          await setupAutoLock();839          if (vault.isUnlocked()) touchAutoLock();840        }841        return { ok: true };842      }843      case "GET_PENDING_PASSKEY":844        return { ok: true, data: await getPendingPasskeyRequest() };845      case "APPROVE_PASSKEY": {846        const { requestId } = msg.payload as { requestId: number };847        await resolvePendingPasskeyRequest(requestId, true);848        return { ok: true };849      }850      case "DENY_PASSKEY": {851        const { requestId } = msg.payload as { requestId: number };852        await resolvePendingPasskeyRequest(requestId, false);853        return { ok: true };854      }855      case "GET_PASSKEY_PROVIDER_STATE":856        return { ok: true, data: await getPasskeyProviderState() };857      case "SET_PASSKEY_PROVIDER_ENABLED": {858        const { enabled } = msg.payload as { enabled: boolean };859        // Disabling is always free; gating fires only when a free user is860        // trying to turn passkey interception on.861        if (enabled) {862          const gate = await requirePro("passkeys");863          if (!gate.allowed) return { ok: false, error: "pro_required" };864        }865        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };866      }867      case "FIRE_CANARY_PING": {868        const { webhookUrl, entryTitle, trigger } = msg.payload as {869          webhookUrl: string;870          entryTitle: string;871          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";872        };873        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {874          return { ok: false, error: "invalid webhook url" };875        }876        const body = JSON.stringify({877          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",878          entry: entryTitle,879          trigger,880          timestamp: new Date().toISOString(),881          source: "peach-extension",882        });883        if (trigger === "test") {884          // Permitted outbound fetch: user-configured canary alert endpoint885          // (validated by isAllowedCanaryWebhookUrl above). This is the886          // only non-HIBP outbound call in the extension — see887          // Projects.md §3.7. Test pings are awaited so the UI can show888          // success/failure.889          try {890            const res = await fetch(webhookUrl, {891              method: "POST",892              headers: { "Content-Type": "application/json" },893              body,894            });895            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };896          } catch (err) {897            return { ok: false, error: err instanceof Error ? err.message : "network error" };898          }899        }900        // Non-test triggers are fire-and-forget901        fetch(webhookUrl, {902          method: "POST",903          headers: { "Content-Type": "application/json" },904          body,905        }).catch(() => {});906        return { ok: true };907      }908      case "ACTIVATE_LICENSE": {909        const { key } = msg.payload as { key: string };910        const licenseInfo = await activateLicense(key);911        return { ok: true, data: licenseInfo };912      }913      case "GET_LICENSE": {914        const licenseInfo = await getLicenseInfo();915        return { ok: true, data: licenseInfo };916      }917      case "GET_LICENSE_KEY": {918        const key = await getLicenseKey();919        return { ok: true, data: key };920      }921      case "DEACTIVATE_LICENSE": {922        await deactivateLicense();923        return { ok: true };924      }925      case "SHOULD_PLAY_CELEBRATION": {926        const should = await shouldPlayCelebration();927        return { ok: true, data: should };928      }929      case "MARK_CELEBRATION_PLAYED": {930        await markCelebrationPlayed();931        return { ok: true };932      }933      case "GET_CODEX_VAULT_DATA": {934        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the935        // popup navigates to the License section without further coordination.936        const gate = await requirePro("codex");937        if (!gate.allowed) return { ok: false, error: "pro_required" };938        return await handleGetCodexVaultData();939      }940      case "ESTIMATE_CODEX_PAGES": {941        const gate = await requirePro("codex");942        if (!gate.allowed) return { ok: false, error: "pro_required" };943        return await handleEstimateCodexPages();944      }945      case "RESTORE_FROM_CODEX": {946        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still947        // be able to restore a vault that was printed by a Pro user.948        // DO NOT add a Pro gate here.949        const payload = msg.payload as CodexRestorePayload;950        return await handleRestoreFromCodex(payload);951      }952      case "OPEN_PRO_GATE": {953        // Content script requests: open popup and navigate to License section.954        const { feature } = (msg.payload ?? {}) as { feature?: string };955        if (chrome.storage.session) {956          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });957        }958        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }959        return { ok: true };960      }961      case "GET_IDENTITIES": {962        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };963        return { ok: true, data: vault.getIdentities() };964      }965      case "TOUCH_AUTO_LOCK": {966        // touchAutoLock() is already called by shouldRefreshAutoLock above;967        // this case just gives the popup a typed message to keep the session alive.968        return { ok: true };969      }970      case "GET_ADVANCED_HEALTH_REPORT": {971        const gate = await requirePro("advanced_health");972        if (!gate.allowed) return { ok: false, error: "pro_required" };973        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };974        const report = await buildAdvancedHealthReport(vault.getEntries());975        return { ok: true, data: report };976      }977      case "INITIATE_PASSWORD_CHANGE": {978        const gate = await requirePro("smart_password_change");979        if (!gate.allowed) return { ok: false, error: "pro_required" };980        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };981        const { id } = msg.payload as { id: string };982        const entry = vault.getEntryById(id);983        if (!entry) return { ok: false, error: "entry not found" };984        const url = resolveResetUrl(entry);985        if (!url) return { ok: false, error: "no reset url" };986        try {987          await chrome.tabs.create({ url });988          return { ok: true, data: { url } };989        } catch (err) {990          return {991            ok: false,992            error: err instanceof Error ? err.message : "failed to open tab",993          };994        }995      }996      case "IS_DURESS_ENABLED": {997        const enabled = await vault.isDuressEnabled();998        return { ok: true, data: enabled };999      }1000      case "SETUP_DURESS": {1001        const { duressPassword } = msg.payload as { duressPassword: string };1002        await vault.setupDuress(duressPassword);1003        return { ok: true };1004      }1005      case "DISABLE_DURESS": {1006        await vault.disableDuress();1007        return { ok: true };1008      }1009      case "VERIFY_MAIN_PASSWORD": {1010        const { password } = msg.payload as { password: string };1011        const ok = await vault.verifyMainPassword(password);1012        return { ok: true, data: ok };1013      }1014      case "CHANGE_PASSWORD": {1015        const { currentPassword, newPassword } = msg.payload as {1016          currentPassword: string;1017          newPassword: string;1018        };1019        const changed = await vault.changePassword(currentPassword, newPassword);1020        return changed1021          ? { ok: true }1022          : { ok: false, error: "incorrect current password" };1023      }1024      case "GET_SITE_PASSWORD_POLICY": {1025        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1026        if (!tab?.id) return { ok: true, data: null };1027        try {1028          const response = await chrome.tabs.sendMessage(tab.id, {1029            type: "GET_SITE_PASSWORD_POLICY",1030          });1031          return (response as MessageResponse) ?? { ok: true, data: null };1032        } catch {1033          return { ok: true, data: null };1034        }1035      }1036      case "GET_SYNC_STATE": {1037        const pairedDevices = await getPairedDevices();1038        const trustedNetworks = await getTrustedNetworks();1039        const tailscale = await isOnTailscale();1040        const pro = await isProUser();10411042        let status: SyncStatus = "offline";1043        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {1044          if (pairedDevices.length === 0) {1045            status = "no_peers";1046          } else {1047            status = "synced";1048          }1049        } else {1050          status = "not_trusted";1051        }10521053        const lastSyncRaw = await storageGet("peach_last_sync_at");1054        const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN;1055        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined;10561057        return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } };1058      }1059      case "GET_PAIRED_DEVICES": {1060        const devices = await getPairedDevices();1061        return { ok: true, data: { devices } };1062      }1063      case "GET_SYNC_STATUS": {1064        const lastSyncRaw = await storageGet("peach_last_sync_at");1065        const lastSyncParsed = lastSyncRaw ? parseInt(lastSyncRaw, 10) : NaN;1066        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : null;1067        const status: 'up_to_date' | 'never' = lastSyncAt ? 'up_to_date' : 'never';1068        return { ok: true, data: { status, lastSyncAt } };1069      }1070      case "ACCEPT_PAIRING": {1071        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.1072        return { ok: true };1073      }1074      case "REMOVE_PAIRED_DEVICE": {1075        const { deviceId } = msg.payload as { deviceId: string };1076        await removePairedDevice(deviceId);1077        return { ok: true };1078      }1079      case "REMOVE_TRUSTED_NETWORK": {1080        const payload = msg.payload as1081          | { ssid?: unknown; bssid?: unknown; isTailscale?: unknown }1082          | null1083          | undefined;1084        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {1085          return { ok: false, error: "invalid_payload" };1086        }1087        const { ssid, bssid, isTailscale } = payload as { ssid?: string; bssid?: string; isTailscale?: boolean };1088        const networks = await getTrustedNetworks();1089        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 1090          (isTailscale ? n.isTailscale : n.ssid === ssid) && 1091          (!bssid || n.bssid === bssid)1092        );1093        if (network) {1094          await removeTrustedNetwork(network.addedAt);1095        }1096        return { ok: true };1097      }1098      case "MARK_NETWORK_TRUSTED": {1099        const network = await getCurrentNetwork();1100        await addTrustedNetwork({1101          ssid: network.ssid,1102          bssid: network.bssid,1103          isTailscale: network.isTailscale,1104          addedAt: Date.now(),1105        });1106        return { ok: true };1107      }1108      case "GET_INCOMING_PAIRING_REQUEST": {1109        const request = await getIncomingPairingRequest();1110        return { ok: true, data: request };1111      }1112      case "RESPOND_INCOMING_PAIRING": {1113        const { accept } = msg.payload as { accept: boolean };1114        const request = await getIncomingPairingRequest();1115        if (!request) return { ok: false, error: "no_pending_request" };1116        if (Date.now() > request.expiresAt) {1117          await clearIncomingPairingRequest();1118          return { ok: false, error: "expired" };1119        }1120        await clearIncomingPairingRequest();1121        if (accept) {1122          await addPairedDevice({1123            deviceId: request.publicKeyHex,1124            displayName: request.deviceName,1125            x25519PublicKey: request.publicKeyHex,1126            pairedAt: Date.now(),1127            lastSeenAt: Date.now(),1128          });1129        }1130        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };1131      }1132      case "START_PAIRING_SERVER": {1133        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.1134        const token = generateSixDigitToken();1135        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;1136        await setActivePairingToken({ token, expiresAt });1137        // Fire-and-forget subnet scan — finds the phone after it scans the QR1138        // and calls SCAN_PAIRING_QR to register the token with SyncPlugin.1139        if (!isNativePlatform()) {1140          void runPairingSubnetScan(token);1141        }1142        return { ok: true, data: { token, expiresAt } };1143      }1144      case "STOP_PAIRING_SERVER": {1145        try {1146          await setActivePairingToken(null);1147        } catch { /* best-effort */ }1148        return { ok: true };1149      }1150      case "GET_RECENT_PAIRING": {1151        const recent = await consumeRecentPairing();1152        return { ok: true, data: recent };1153      }1154      case "DEBUG_INJECT_INCOMING_PAIRING": {1155        // Manual E2E rehearsal hook. Inserts a synthetic incoming pairing1156        // request into session storage so Phase 7 banner UX can be exercised1157        // without a live native host. No Pro gate — this is a no-op in1158        // production unless explicitly invoked from a Settings debug action.1159        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {1160          deviceName?: string;1161          publicKeyHex?: string;1162        };1163        if (!deviceName || !publicKeyHex) {1164          return { ok: false, error: "missing_payload" };1165        }1166        const now = Date.now();1167        await setIncomingPairingRequest({1168          deviceName,1169          publicKeyHex,1170          receivedAt: now,1171          expiresAt: now + 60_000,1172        });1173        return { ok: true };1174      }1175      case "RESET_SYNC_IDENTITY": {1176        const gate = await requirePro("sync");1177        if (!gate.allowed) return { ok: false, error: "pro_required" };1178        const devices = await getPairedDevices();1179        for (const device of devices) {1180          await removePairedDevice(device.deviceId);1181        }1182        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };1183      }1184      case "RECORD_MANUAL_SUMMON": {1185        const { domain } = msg.payload as { domain: string };1186        const settings = vault.getSettings();1187        const existing = settings.manualSummonDomains?.[domain];1188        const now = Date.now();1189        await vault.updateSettings({1190          manualSummonDomains: {1191            ...settings.manualSummonDomains,1192            [domain]: {1193              firstSummonedAt: existing?.firstSummonedAt ?? now,1194              summonCount: (existing?.summonCount ?? 0) + 1,1195              lastSummonedAt: now,1196            },1197          },1198        });1199        return { ok: true };1200      }1201      case "DECLINE_CARD_SAVE": {1202        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1203        await vault.declineCardSaveOffer(last4, expMonth, expYear);1204        return { ok: true };1205      }1206      case "IS_CARD_DECLINED": {1207        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1208        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1209        return { ok: true, data: declined };1210      }1211      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1212        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1213          rpId?: string;1214          rpName?: string;1215          userName?: string;1216          userDisplayName?: string;1217        };1218        if (!rpId || !userName) return { ok: false, error: "rpId and userName required" };1219        return await initiateFirefoxPasskeyCreate({1220          rpId,1221          rpName: rpName ?? rpId,1222          userName,1223          userDisplayName,1224        });1225      }12261227      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1228        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1229        if (!payload) return { ok: false, error: "missing payload" };1230        return await completeFirefoxPasskeyCreate(payload);1231      }12321233      case "PASSKEY_OFFER_DECLINE": {1234        const { domain } = (msg.payload ?? {}) as { domain?: string };1235        if (!domain) return { ok: false, error: "domain required" };1236        await recordPasskeyOfferDecline(domain);1237        return { ok: true };1238      }12391240      case "GET_PASSKEY_OFFER_DECLINED": {1241        const { domain } = (msg.payload ?? {}) as { domain?: string };1242        if (!domain) return { ok: false, error: "domain required" };1243        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1244      }12451246      case "PASSKEY_HAS_CREDENTIALS": {1247        const payload = msg.payload as {1248          rpId?: string;1249          allowCredentials?: Array<{ id: string; type?: string }>;1250        } | undefined;1251        if (!payload?.rpId) return { ok: false, error: "rpId required" };1252        return await handlePasskeyHasCredentials({1253          rpId: payload.rpId,1254          allowCredentials: payload.allowCredentials ?? [],1255        });1256      }12571258      case "PASSKEY_CREATE": {1259        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1260        if (!payload?.rpId || !payload?.userName) {1261          return { ok: false, error: "rpId and userName required" };1262        }1263        return await handleFirefoxPasskeyCreate(payload);1264      }12651266      case "PASSKEY_GET": {1267        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1268        if (!payload?.rpId) return { ok: false, error: "rpId required" };1269        return await handleFirefoxPasskeyGet(payload);1270      }12711272      case "PASSKEY_AUTH_RESPONSE": {1273        const { requestId, approved } = (msg.payload ?? {}) as {1274          requestId?: string | number;1275          approved?: boolean;1276        };1277        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1278          return { ok: false, error: 'requestId and approved required' };1279        }1280        await resolvePendingPasskeyRequest(Number(requestId), approved);1281        return { ok: true };1282      }12831284      case "GET_PASSKEY_FOR_DOMAIN": {1285        const { domain } = (msg.payload ?? {}) as { domain?: string };1286        if (!domain) return { ok: false, error: "domain required" };1287        if (!vault.isUnlocked()) return { ok: true, data: null };1288        const match = vault1289          .getEntries()1290          .find((entry) => entry.passkey?.rpId === domain);1291        if (!match || !match.passkey) return { ok: true, data: null };1292        // Slim shape — only the fields State 11 needs. Never expose private1293        // key material, even though this is locked behind isUnlocked.1294        return {1295          ok: true,1296          data: {1297            rpId: match.passkey.rpId,1298            userName: match.passkey.userName,1299            browser: match.passkey.browser,1300          },1301        };1302      }13031304      case "DESTROY_VAULT": {1305        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1306        // storage.local.clear() wipes every Peach key (slots, settings, license,1307        // onboarded flag, history, sync state, declined cards, recall, etc.);1308        // session.clear() wipes pending passkey requests + pro-notice queues.1309        // Caller (Panic.tsx) handles UI navigation back to onboarding.1310        vault.lock();1311        await storageClear();1312        await vault.clearVaultHistory();1313        if (chrome.storage.session) {1314          await chrome.storage.session.clear();1315        }1316        return { ok: true };1317      }13181319      case "SUBMIT_FEEDBACK": {1320        const { category, message, version, browser } = msg.payload as {1321          category: string;1322          message: string;1323          version: string;1324          browser: string;1325        };1326        if (!message.trim()) return { ok: false, error: "message is empty" };1327        if (!FEEDBACK_ENDPOINT) return { ok: true };1328        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1329          return { ok: false, error: "invalid feedback endpoint" };1330        }1331        try {1332          const res = await fetch(FEEDBACK_ENDPOINT, {1333            method: "POST",1334            headers: { "Content-Type": "application/json" },1335            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1336          });1337          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1338        } catch (err) {1339          return { ok: false, error: err instanceof Error ? err.message : "network error" };1340        }1341      }1342      case "TRIGGER_SYNC": {1343        const gate = await requirePro("sync");1344        if (!gate.allowed) return { ok: false, error: "pro_required" };1345        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };13461347        if (isNativePlatform()) {1348          // Phone is the server — ensure it's listening for desktop connections.1349          syncBridge()?.ensureServerRunning?.();1350          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };1351        }13521353        // Desktop: iterate all paired devices and sync with each.1354        const paired = await getPairedDevices();1355        if (!paired.length) return { ok: true, data: { syncedCount: 0, reason: "no_paired_devices" } };13561357        const subnet = await getLocalSubnet();1358        const results: Array<{ device: string } & SyncResult> = [];13591360        for (const device of paired) {1361          if (!device.x25519PublicKey) continue;13621363          let result: SyncResult;13641365          // Fast path — use last known IP1366          if (device.lastKnownIp) {1367            result = await doVaultSync(device.lastKnownIp, device.x25519PublicKey);1368          } else {1369            result = { status: 'errored', applied: false, error: 'no_ip' };1370          }13711372          // Discovery path — scan if fast path failed1373          if (result.status === 'errored' && subnet) {1374            const newIp = await discoverDevice(subnet, device.x25519PublicKey);1375            if (newIp) {1376              await updatePairedDevice(device.x25519PublicKey, { lastKnownIp: newIp });1377              result = await doVaultSync(newIp, device.x25519PublicKey);1378            }1379          }13801381          if (result.status === 'completed') {1382            await updatePairedDevice(device.x25519PublicKey, {1383              lastSeenAt: Date.now(),1384              lastSyncAt: Date.now(),1385            });1386          }13871388          results.push({ device: device.displayName, ...result });1389        }13901391        const syncedCount = results.filter(r => r.status === 'completed').length;1392        if (syncedCount > 0) {1393          await chrome.storage.local.set({ peach_last_sync_at: String(Date.now()) });1394        }1395        return { ok: true, data: { syncedCount, results } };1396      }1397      // Android-only: biometric unlock with pre-derived key.1398      case "UNLOCK_WITH_KEY": {1399        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1400        if (!isNativePlatform()) {1401          return { ok: false, error: "desktop_only_uses_password" };1402        }1403        try {1404          const result = await vault.unlockWithKey(masterKeyHex);1405          if (result.ok) {1406            onVaultUnlocked();1407            await publishInMemoryVault(result.entries);1408          }1409          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1410        } catch {1411          return { ok: false, error: "invalid_key" };1412        }1413      }1414      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1415      case "GET_DERIVED_KEY": {1416        if (!isNativePlatform()) {1417          return { ok: false, error: "android_only" };1418        }1419        if (!vault.isUnlocked()) {1420          return { ok: false, error: "vault_locked" };1421        }1422        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1423      }1424      // Android: scanned a QR containing a desktop pairing token.1425      case "SCAN_PAIRING_QR": {1426        if (!isNativePlatform()) {1427          return { ok: false, error: "android_only" };1428        }1429        const { token } = msg.payload as { token: string };1430        syncBridge()?.startPairingSession?.({ token });1431        return { ok: true };1432      }1433      // Android: desktop opened a sync connection to the phone's WS server.1434      // Run the responder side of the vault exchange.1435      case "SYNC_SESSION_STARTED": {1436        if (!isNativePlatform()) return { ok: false };1437        if (!vault.isUnlocked()) {1438          return { ok: false, error: "vault_locked" };1439        }1440        const { connectionId } = (msg.payload ?? {}) as { connectionId?: string };1441        if (!connectionId) return { ok: false, error: "missing_connection_id" };14421443        const transport = createAndroidResponderTransport(connectionId);14441445        // Authenticate the initiator before exchanging any vault data. The1446        // native side has already completed the Noise NK handshake; auth1447        // frames here ride the Noise transport (native encrypts/decrypts).1448        const identity = await vault.getSyncIdentity();1449        try {1450          // CAUTION: noiseSessionStub is a structural placeholder — the real1451          // Noise NK handshake runs natively, so JS never holds the session1452          // object. performResponderAuth currently `void`s this argument,1453          // which is why identity-passthrough encrypt/decrypt and a zero1454          // handshake hash are safe. If performResponderAuth is ever updated1455          // to actually use this argument, this auth path will silently break1456          // (no type error). Revisit this stub if that helper changes.1457          const noiseSessionStub = {1458            encrypt: (b: Uint8Array) => b,1459            decrypt: (b: Uint8Array) => b,1460            handshakeHash: new Uint8Array(32),1461          };1462          const { initiatorPublicKey } = await performResponderAuth(1463            noiseSessionStub,1464            identity.privateKeyBytes,1465            identity.publicKeyBytes,1466            transport.send,1467            transport.receive,1468          );1469          const initiatorHex = noiseBytesToHex(initiatorPublicKey);1470          const paired = await getPairedDevices();1471          if (!paired.some(d => d.x25519PublicKey === initiatorHex)) {1472            await transport.close();1473            return { ok: false, error: "sync_rejected_unpaired_initiator" };1474          }1475          // Initiator just proved control of the matching static key; mark it1476          // as a verified handshake so a follow-up PAIRING_COMPLETED message1477          // can be trusted (M13/SEC-005).1478          markPairingHandshakeVerified(initiatorHex);1479        } catch (err) {1480          await transport.close();1481          return { ok: false, error: `sync_auth_failed: ${String(err)}` };1482        }14831484        const result = await runBlobSyncSession('responder', transport, buildSyncDeps());1485        if (result.applied) {1486          await publishInMemoryVault(vault.getEntries());1487        }1488        return { ok: true, data: result };1489      }1490      // Android: returns the phone's WiFi IP address.1491      case "GET_LOCAL_IP": {1492        if (!isNativePlatform()) {1493          return { ok: false, error: "android_only" };1494        }1495        const { ip } = (await syncBridge()?.getLocalIp?.()) ?? { ip: "" };1496        return { ok: true, data: { ip } };1497      }1498      case "GET_IDENTITY_SUGGESTIONS": {1499        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1500        const entries = vault.getEntries();1501        const suggestions = buildIdentitySuggestions(entries);1502        return { ok: true, data: { suggestions } };1503      }1504      case "POPULATE_INLINE_VAULT": {1505        if (!isNativePlatform()) return { ok: false };1506        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1507        const entries = vault.getEntries();1508        await publishInMemoryVault(entries);1509        return { ok: true };1510      }1511      case "ML_INIT":1512        return { ok: true };15131514      case "ML_PREDICT_BATCH": {1515        const { featuresArray } = msg.payload as { featuresArray: MLFieldFeatures[] };1516        return { ok: true, data: mlPredictBatch(featuresArray) };1517      }15181519      default:1520        return { ok: false, error: "unknown message type" };1521    }1522  } catch (err) {1523    return {1524      ok: false,1525      error: err instanceof Error ? err.message : "operation failed",1526    };1527  }1528}15291530// --- Mobile platform helpers ---15311532// Android: populates the in-memory vault used by PeachAutofillService.1533async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1534  const plugin = nativePlugin<{1535    setEntries?: (args: {1536      entries: Array<{1537        id: string;1538        title: string;1539        username: string;1540        email: string;1541        password: string;1542        url: string;1543        totp: string;1544        additionalUrls: string[];1545      }>;1546    }) => Promise<void>;1547  }>("InMemoryVaultPlugin");1548  if (!plugin?.setEntries) return;1549  await plugin.setEntries({1550    entries: entries.map((e) => ({1551      id: e.id,1552      title: e.title ?? "",1553      username: e.username ?? "",1554      email: (e as VaultEntry & { email?: string }).email ?? "",1555      password: e.password ?? "",1556      url: e.url ?? "",1557      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1558      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1559    })),1560  });1561}15621563// Android: clear the autofill in-memory store on lock.1564async function clearInMemoryVault(): Promise<void> {1565  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1566  if (!plugin?.clearEntries) return;1567  await plugin.clearEntries();1568}15691570interface SyncBridge {1571  ensureServerRunning?: () => void;1572  startPairingSession?: (args: { token: string }) => void;1573  getLocalIp?: () => Promise<{ ip: string }>;1574  sendToConnection?: (args: { connectionId: string; data: string }) => Promise<void>;1575  addListener?: (event: string, handler: (data: Record<string, string>) => void) => void;1576}15771578// Resolve the Capacitor SyncPlugin at call time — module-load resolution1579// races with Capacitor's plugin registration on the Android WebView.1580function syncBridge(): SyncBridge | null {1581  return nativePlugin<SyncBridge>("SyncPlugin");1582}15831584// Build a SyncTransport for the Android responder path — the phone's WS server1585// already has an open connection from the desktop. We send back via1586// SyncPlugin.sendToConnection and receive via the peach:sync-frame queue.1587const androidSyncFrameQueues = new Map<string, Array<(frame: string) => void>>();15881589export function deliverAndroidSyncFrame(connectionId: string, frame: string): void {1590  const queue = androidSyncFrameQueues.get(connectionId);1591  if (queue?.length) queue.shift()!(frame);1592}15931594function createAndroidResponderTransport(connectionId: string) {1595  const pendingReceivers: Array<(frame: string) => void> = [];1596  androidSyncFrameQueues.set(connectionId, pendingReceivers);15971598  return {1599    send: async (data: Uint8Array) => {1600      await syncBridge()?.sendToConnection?.({ connectionId, data: bytesToBase64(data) });1601    },1602    receive: (): Promise<Uint8Array> => new Promise((res) => {1603      pendingReceivers.push((frame) => {1604        res(frame ? base64ToBytes(frame) : new Uint8Array(0));1605      });1606    }),1607    close: async () => {1608      androidSyncFrameQueues.delete(connectionId);1609    },1610  };1611}16121613// Returns username use-counts from the vault, sorted by frequency. Each row1614// also carries the entry's email so the popup can suggest the email/username1615// pair the user has actually used together.1616function buildIdentitySuggestions(1617  entries: VaultEntry[],1618): Array<{ email: string; username: string; count: number }> {1619  const usernameCounts = new Map<string, number>();1620  const usernameEmail = new Map<string, string>();1621  for (const entry of entries) {1622    const username = entry.username ?? "";1623    const email = (entry as VaultEntry & { email?: string }).email ?? "";1624    if (!username && !email) continue;1625    const key = username || email;1626    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1627    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1628  }1629  return Array.from(usernameCounts.entries())1630    .sort((a, b) => b[1] - a[1])1631    .map(([username, count]) => ({1632      email: usernameEmail.get(username) ?? "",1633      username,1634      count,1635    }));1636}16371638/** Notify all content scripts that the vault just became available. */1639function broadcastToContentScripts(message: { type: string }): void {1640  if (!chrome.tabs?.query) return;1641  chrome.tabs.query({}, (tabs) => {1642    for (const tab of tabs) {1643      if (tab.id !== undefined) {1644        chrome.tabs.sendMessage(tab.id, message).catch(() => {1645          // Tab may not have a content script — silently ignore1646        });1647      }1648    }1649  });1650}16511652function shouldRefreshAutoLock(type: MessageType): boolean {1653  return (1654    type !== "HAS_VAULT" &&1655    type !== "IS_UNLOCKED" &&1656    type !== "GET_VAULT_STATUS" &&1657    type !== "LOCK" &&1658    type !== "UPDATE_SETTINGS" &&1659    type !== "GET_PENDING_PASSKEY" &&1660    type !== "GET_PASSKEY_PROVIDER_STATE" &&1661    type !== "DECLINE_CARD_SAVE" &&1662    type !== "IS_CARD_DECLINED" &&1663    type !== "SUBMIT_FEEDBACK"1664  );1665}16661667function isAllowedCanaryWebhookUrl(value: string): boolean {1668  try {1669    const url = new URL(value);1670    if (url.protocol !== "https:") return false;16711672    const hostname = url.hostname.toLowerCase();1673    if (1674      hostname === "localhost" ||1675      hostname.endsWith(".localhost") ||1676      isPrivateIpv4(hostname) ||1677      isPrivateIpv6(hostname)1678    ) {1679      return false;1680    }16811682    return true;1683  } catch {1684    return false;1685  }1686}16871688function isPrivateIpv4(hostname: string): boolean {1689  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1690    return true;1691  }16921693  const octets = hostname.split(".").map((part) => Number(part));1694  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1695    return false;1696  }16971698  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1699}17001701function isPrivateIpv6(hostname: string): boolean {1702  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1703  return (1704    normalized === "::1" ||1705    normalized.startsWith("fc") ||1706    normalized.startsWith("fd") ||1707    normalized.startsWith("fe80:")1708  );1709}