messages.ts

65.9 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard } from "./clipboard";13import { 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        // M14/SEC-007: blocked in production builds. The handler exists for1156        // Phase 7 banner UX rehearsal without a live native host; shipping1157        // it in production lets any background-message sender inject a1158        // synthetic pairing prompt. Allowed in 'development' and 'test'1159        // modes; vite sets MODE='production' for release builds.1160        if (import.meta.env.MODE === "production") {1161          return { ok: false, error: "not_available" };1162        }1163        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {1164          deviceName?: string;1165          publicKeyHex?: string;1166        };1167        if (!deviceName || !publicKeyHex) {1168          return { ok: false, error: "missing_payload" };1169        }1170        const now = Date.now();1171        await setIncomingPairingRequest({1172          deviceName,1173          publicKeyHex,1174          receivedAt: now,1175          expiresAt: now + 60_000,1176        });1177        return { ok: true };1178      }1179      case "RESET_SYNC_IDENTITY": {1180        const gate = await requirePro("sync");1181        if (!gate.allowed) return { ok: false, error: "pro_required" };1182        const devices = await getPairedDevices();1183        for (const device of devices) {1184          await removePairedDevice(device.deviceId);1185        }1186        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };1187      }1188      case "RECORD_MANUAL_SUMMON": {1189        const { domain } = msg.payload as { domain: string };1190        const settings = vault.getSettings();1191        const existing = settings.manualSummonDomains?.[domain];1192        const now = Date.now();1193        await vault.updateSettings({1194          manualSummonDomains: {1195            ...settings.manualSummonDomains,1196            [domain]: {1197              firstSummonedAt: existing?.firstSummonedAt ?? now,1198              summonCount: (existing?.summonCount ?? 0) + 1,1199              lastSummonedAt: now,1200            },1201          },1202        });1203        return { ok: true };1204      }1205      case "DECLINE_CARD_SAVE": {1206        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1207        await vault.declineCardSaveOffer(last4, expMonth, expYear);1208        return { ok: true };1209      }1210      case "IS_CARD_DECLINED": {1211        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1212        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1213        return { ok: true, data: declined };1214      }1215      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1216        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1217          rpId?: string;1218          rpName?: string;1219          userName?: string;1220          userDisplayName?: string;1221        };1222        if (!rpId || !userName) return { ok: false, error: "rpId and userName required" };1223        return await initiateFirefoxPasskeyCreate({1224          rpId,1225          rpName: rpName ?? rpId,1226          userName,1227          userDisplayName,1228        });1229      }12301231      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1232        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1233        if (!payload) return { ok: false, error: "missing payload" };1234        return await completeFirefoxPasskeyCreate(payload);1235      }12361237      case "PASSKEY_OFFER_DECLINE": {1238        const { domain } = (msg.payload ?? {}) as { domain?: string };1239        if (!domain) return { ok: false, error: "domain required" };1240        await recordPasskeyOfferDecline(domain);1241        return { ok: true };1242      }12431244      case "GET_PASSKEY_OFFER_DECLINED": {1245        const { domain } = (msg.payload ?? {}) as { domain?: string };1246        if (!domain) return { ok: false, error: "domain required" };1247        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1248      }12491250      case "PASSKEY_HAS_CREDENTIALS": {1251        const payload = msg.payload as {1252          rpId?: string;1253          allowCredentials?: Array<{ id: string; type?: string }>;1254        } | undefined;1255        if (!payload?.rpId) return { ok: false, error: "rpId required" };1256        return await handlePasskeyHasCredentials({1257          rpId: payload.rpId,1258          allowCredentials: payload.allowCredentials ?? [],1259        });1260      }12611262      case "PASSKEY_CREATE": {1263        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1264        if (!payload?.rpId || !payload?.userName) {1265          return { ok: false, error: "rpId and userName required" };1266        }1267        return await handleFirefoxPasskeyCreate(payload);1268      }12691270      case "PASSKEY_GET": {1271        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1272        if (!payload?.rpId) return { ok: false, error: "rpId required" };1273        return await handleFirefoxPasskeyGet(payload);1274      }12751276      case "PASSKEY_AUTH_RESPONSE": {1277        const { requestId, approved } = (msg.payload ?? {}) as {1278          requestId?: string | number;1279          approved?: boolean;1280        };1281        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1282          return { ok: false, error: 'requestId and approved required' };1283        }1284        await resolvePendingPasskeyRequest(Number(requestId), approved);1285        return { ok: true };1286      }12871288      case "GET_PASSKEY_FOR_DOMAIN": {1289        const { domain } = (msg.payload ?? {}) as { domain?: string };1290        if (!domain) return { ok: false, error: "domain required" };1291        if (!vault.isUnlocked()) return { ok: true, data: null };1292        const match = vault1293          .getEntries()1294          .find((entry) => entry.passkey?.rpId === domain);1295        if (!match || !match.passkey) return { ok: true, data: null };1296        // Slim shape — only the fields State 11 needs. Never expose private1297        // key material, even though this is locked behind isUnlocked.1298        return {1299          ok: true,1300          data: {1301            rpId: match.passkey.rpId,1302            userName: match.passkey.userName,1303            browser: match.passkey.browser,1304          },1305        };1306      }13071308      case "DESTROY_VAULT": {1309        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1310        // storage.local.clear() wipes every Peach key (slots, settings, license,1311        // onboarded flag, history, sync state, declined cards, recall, etc.);1312        // session.clear() wipes pending passkey requests + pro-notice queues.1313        // Caller (Panic.tsx) handles UI navigation back to onboarding.1314        vault.lock();1315        await storageClear();1316        await vault.clearVaultHistory();1317        if (chrome.storage.session) {1318          await chrome.storage.session.clear();1319        }1320        return { ok: true };1321      }13221323      case "SUBMIT_FEEDBACK": {1324        const { category, message, version, browser } = msg.payload as {1325          category: string;1326          message: string;1327          version: string;1328          browser: string;1329        };1330        if (!message.trim()) return { ok: false, error: "message is empty" };1331        if (!FEEDBACK_ENDPOINT) return { ok: true };1332        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1333          return { ok: false, error: "invalid feedback endpoint" };1334        }1335        try {1336          const res = await fetch(FEEDBACK_ENDPOINT, {1337            method: "POST",1338            headers: { "Content-Type": "application/json" },1339            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1340          });1341          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1342        } catch (err) {1343          return { ok: false, error: err instanceof Error ? err.message : "network error" };1344        }1345      }1346      case "TRIGGER_SYNC": {1347        const gate = await requirePro("sync");1348        if (!gate.allowed) return { ok: false, error: "pro_required" };1349        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };13501351        if (isNativePlatform()) {1352          // Phone is the server — ensure it's listening for desktop connections.1353          syncBridge()?.ensureServerRunning?.();1354          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };1355        }13561357        // Desktop: iterate all paired devices and sync with each.1358        const paired = await getPairedDevices();1359        if (!paired.length) return { ok: true, data: { syncedCount: 0, reason: "no_paired_devices" } };13601361        const subnet = await getLocalSubnet();1362        const results: Array<{ device: string } & SyncResult> = [];13631364        for (const device of paired) {1365          if (!device.x25519PublicKey) continue;13661367          let result: SyncResult;13681369          // Fast path — use last known IP1370          if (device.lastKnownIp) {1371            result = await doVaultSync(device.lastKnownIp, device.x25519PublicKey);1372          } else {1373            result = { status: 'errored', applied: false, error: 'no_ip' };1374          }13751376          // Discovery path — scan if fast path failed1377          if (result.status === 'errored' && subnet) {1378            const newIp = await discoverDevice(subnet, device.x25519PublicKey);1379            if (newIp) {1380              await updatePairedDevice(device.x25519PublicKey, { lastKnownIp: newIp });1381              result = await doVaultSync(newIp, device.x25519PublicKey);1382            }1383          }13841385          if (result.status === 'completed') {1386            await updatePairedDevice(device.x25519PublicKey, {1387              lastSeenAt: Date.now(),1388              lastSyncAt: Date.now(),1389            });1390          }13911392          results.push({ device: device.displayName, ...result });1393        }13941395        const syncedCount = results.filter(r => r.status === 'completed').length;1396        if (syncedCount > 0) {1397          await chrome.storage.local.set({ peach_last_sync_at: String(Date.now()) });1398        }1399        return { ok: true, data: { syncedCount, results } };1400      }1401      // Android-only: biometric unlock with pre-derived key.1402      case "UNLOCK_WITH_KEY": {1403        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1404        if (!isNativePlatform()) {1405          return { ok: false, error: "desktop_only_uses_password" };1406        }1407        try {1408          const result = await vault.unlockWithKey(masterKeyHex);1409          if (result.ok) {1410            onVaultUnlocked();1411            await publishInMemoryVault(result.entries);1412          }1413          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1414        } catch {1415          return { ok: false, error: "invalid_key" };1416        }1417      }1418      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1419      case "GET_DERIVED_KEY": {1420        if (!isNativePlatform()) {1421          return { ok: false, error: "android_only" };1422        }1423        if (!vault.isUnlocked()) {1424          return { ok: false, error: "vault_locked" };1425        }1426        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1427      }1428      // Android: scanned a QR containing a desktop pairing token.1429      case "SCAN_PAIRING_QR": {1430        if (!isNativePlatform()) {1431          return { ok: false, error: "android_only" };1432        }1433        const { token } = msg.payload as { token: string };1434        syncBridge()?.startPairingSession?.({ token });1435        return { ok: true };1436      }1437      // Android: desktop opened a sync connection to the phone's WS server.1438      // Run the responder side of the vault exchange.1439      case "SYNC_SESSION_STARTED": {1440        if (!isNativePlatform()) return { ok: false };1441        if (!vault.isUnlocked()) {1442          return { ok: false, error: "vault_locked" };1443        }1444        const { connectionId } = (msg.payload ?? {}) as { connectionId?: string };1445        if (!connectionId) return { ok: false, error: "missing_connection_id" };14461447        const transport = createAndroidResponderTransport(connectionId);14481449        // Authenticate the initiator before exchanging any vault data. The1450        // native side has already completed the Noise NK handshake; auth1451        // frames here ride the Noise transport (native encrypts/decrypts).1452        const identity = await vault.getSyncIdentity();1453        try {1454          // CAUTION: noiseSessionStub is a structural placeholder — the real1455          // Noise NK handshake runs natively, so JS never holds the session1456          // object. performResponderAuth currently `void`s this argument,1457          // which is why identity-passthrough encrypt/decrypt and a zero1458          // handshake hash are safe. If performResponderAuth is ever updated1459          // to actually use this argument, this auth path will silently break1460          // (no type error). Revisit this stub if that helper changes.1461          const noiseSessionStub = {1462            encrypt: (b: Uint8Array) => b,1463            decrypt: (b: Uint8Array) => b,1464            handshakeHash: new Uint8Array(32),1465          };1466          const { initiatorPublicKey } = await performResponderAuth(1467            noiseSessionStub,1468            identity.privateKeyBytes,1469            identity.publicKeyBytes,1470            transport.send,1471            transport.receive,1472          );1473          const initiatorHex = noiseBytesToHex(initiatorPublicKey);1474          const paired = await getPairedDevices();1475          if (!paired.some(d => d.x25519PublicKey === initiatorHex)) {1476            await transport.close();1477            return { ok: false, error: "sync_rejected_unpaired_initiator" };1478          }1479          // Initiator just proved control of the matching static key; mark it1480          // as a verified handshake so a follow-up PAIRING_COMPLETED message1481          // can be trusted (M13/SEC-005).1482          markPairingHandshakeVerified(initiatorHex);1483        } catch (err) {1484          await transport.close();1485          return { ok: false, error: `sync_auth_failed: ${String(err)}` };1486        }14871488        const result = await runBlobSyncSession('responder', transport, buildSyncDeps());1489        if (result.applied) {1490          await publishInMemoryVault(vault.getEntries());1491        }1492        return { ok: true, data: result };1493      }1494      // Android: returns the phone's WiFi IP address.1495      case "GET_LOCAL_IP": {1496        if (!isNativePlatform()) {1497          return { ok: false, error: "android_only" };1498        }1499        const { ip } = (await syncBridge()?.getLocalIp?.()) ?? { ip: "" };1500        return { ok: true, data: { ip } };1501      }1502      case "GET_IDENTITY_SUGGESTIONS": {1503        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1504        const entries = vault.getEntries();1505        const suggestions = buildIdentitySuggestions(entries);1506        return { ok: true, data: { suggestions } };1507      }1508      case "POPULATE_INLINE_VAULT": {1509        if (!isNativePlatform()) return { ok: false };1510        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1511        const entries = vault.getEntries();1512        await publishInMemoryVault(entries);1513        return { ok: true };1514      }1515      case "ML_INIT":1516        return { ok: true };15171518      case "ML_PREDICT_BATCH": {1519        const { featuresArray } = msg.payload as { featuresArray: MLFieldFeatures[] };1520        return { ok: true, data: mlPredictBatch(featuresArray) };1521      }15221523      default:1524        return { ok: false, error: "unknown message type" };1525    }1526  } catch (err) {1527    return {1528      ok: false,1529      error: err instanceof Error ? err.message : "operation failed",1530    };1531  }1532}15331534// --- Mobile platform helpers ---15351536// Android: populates the in-memory vault used by PeachAutofillService.1537async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1538  const plugin = nativePlugin<{1539    setEntries?: (args: {1540      entries: Array<{1541        id: string;1542        title: string;1543        username: string;1544        email: string;1545        password: string;1546        url: string;1547        totp: string;1548        additionalUrls: string[];1549      }>;1550    }) => Promise<void>;1551  }>("InMemoryVaultPlugin");1552  if (!plugin?.setEntries) return;1553  await plugin.setEntries({1554    entries: entries.map((e) => ({1555      id: e.id,1556      title: e.title ?? "",1557      username: e.username ?? "",1558      email: (e as VaultEntry & { email?: string }).email ?? "",1559      password: e.password ?? "",1560      url: e.url ?? "",1561      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1562      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1563    })),1564  });1565}15661567// Android: clear the autofill in-memory store on lock.1568async function clearInMemoryVault(): Promise<void> {1569  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1570  if (!plugin?.clearEntries) return;1571  await plugin.clearEntries();1572}15731574interface SyncBridge {1575  ensureServerRunning?: () => void;1576  startPairingSession?: (args: { token: string }) => void;1577  getLocalIp?: () => Promise<{ ip: string }>;1578  sendToConnection?: (args: { connectionId: string; data: string }) => Promise<void>;1579  addListener?: (event: string, handler: (data: Record<string, string>) => void) => void;1580}15811582// Resolve the Capacitor SyncPlugin at call time — module-load resolution1583// races with Capacitor's plugin registration on the Android WebView.1584function syncBridge(): SyncBridge | null {1585  return nativePlugin<SyncBridge>("SyncPlugin");1586}15871588// Build a SyncTransport for the Android responder path — the phone's WS server1589// already has an open connection from the desktop. We send back via1590// SyncPlugin.sendToConnection and receive via the peach:sync-frame queue.1591const androidSyncFrameQueues = new Map<string, Array<(frame: string) => void>>();15921593export function deliverAndroidSyncFrame(connectionId: string, frame: string): void {1594  const queue = androidSyncFrameQueues.get(connectionId);1595  if (queue?.length) queue.shift()!(frame);1596}15971598function createAndroidResponderTransport(connectionId: string) {1599  const pendingReceivers: Array<(frame: string) => void> = [];1600  androidSyncFrameQueues.set(connectionId, pendingReceivers);16011602  return {1603    send: async (data: Uint8Array) => {1604      await syncBridge()?.sendToConnection?.({ connectionId, data: bytesToBase64(data) });1605    },1606    receive: (): Promise<Uint8Array> => new Promise((res) => {1607      pendingReceivers.push((frame) => {1608        res(frame ? base64ToBytes(frame) : new Uint8Array(0));1609      });1610    }),1611    close: async () => {1612      androidSyncFrameQueues.delete(connectionId);1613    },1614  };1615}16161617// Returns username use-counts from the vault, sorted by frequency. Each row1618// also carries the entry's email so the popup can suggest the email/username1619// pair the user has actually used together.1620function buildIdentitySuggestions(1621  entries: VaultEntry[],1622): Array<{ email: string; username: string; count: number }> {1623  const usernameCounts = new Map<string, number>();1624  const usernameEmail = new Map<string, string>();1625  for (const entry of entries) {1626    const username = entry.username ?? "";1627    const email = (entry as VaultEntry & { email?: string }).email ?? "";1628    if (!username && !email) continue;1629    const key = username || email;1630    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1631    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1632  }1633  return Array.from(usernameCounts.entries())1634    .sort((a, b) => b[1] - a[1])1635    .map(([username, count]) => ({1636      email: usernameEmail.get(username) ?? "",1637      username,1638      count,1639    }));1640}16411642/** Notify all content scripts that the vault just became available. */1643function broadcastToContentScripts(message: { type: string }): void {1644  if (!chrome.tabs?.query) return;1645  chrome.tabs.query({}, (tabs) => {1646    for (const tab of tabs) {1647      if (tab.id !== undefined) {1648        chrome.tabs.sendMessage(tab.id, message).catch(() => {1649          // Tab may not have a content script — silently ignore1650        });1651      }1652    }1653  });1654}16551656function shouldRefreshAutoLock(type: MessageType): boolean {1657  return (1658    type !== "HAS_VAULT" &&1659    type !== "IS_UNLOCKED" &&1660    type !== "GET_VAULT_STATUS" &&1661    type !== "LOCK" &&1662    type !== "UPDATE_SETTINGS" &&1663    type !== "GET_PENDING_PASSKEY" &&1664    type !== "GET_PASSKEY_PROVIDER_STATE" &&1665    type !== "DECLINE_CARD_SAVE" &&1666    type !== "IS_CARD_DECLINED" &&1667    type !== "SUBMIT_FEEDBACK"1668  );1669}16701671function isAllowedCanaryWebhookUrl(value: string): boolean {1672  try {1673    const url = new URL(value);1674    if (url.protocol !== "https:") return false;16751676    const hostname = url.hostname.toLowerCase();1677    if (1678      hostname === "localhost" ||1679      hostname.endsWith(".localhost") ||1680      isPrivateIpv4(hostname) ||1681      isPrivateIpv6(hostname)1682    ) {1683      return false;1684    }16851686    return true;1687  } catch {1688    return false;1689  }1690}16911692function isPrivateIpv4(hostname: string): boolean {1693  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1694    return true;1695  }16961697  const octets = hostname.split(".").map((part) => Number(part));1698  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1699    return false;1700  }17011702  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1703}17041705function isPrivateIpv6(hostname: string): boolean {1706  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1707  return (1708    normalized === "::1" ||1709    normalized.startsWith("fc") ||1710    normalized.startsWith("fd") ||1711    normalized.startsWith("fe80:")1712  );1713}