messages.ts

66.0 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        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };531        return { ok: true, data: vault.getEntries() };532      case "ADD_ENTRY": {533        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };534        const payload = msg.payload;535        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {536          return { ok: false, error: "invalid_payload" };537        }538        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);539        return { ok: true, data: entry };540      }541      case "BATCH_ADD_ENTRIES": {542        const payload = msg.payload as { entries?: unknown } | null | undefined;543        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {544          return { ok: false, error: "invalid_payload" };545        }546        if (!Array.isArray(payload.entries)) {547          return { ok: false, error: "invalid_payload" };548        }549        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);550        return { ok: true, data: added };551      }552      case "RESTORE_ENTRIES": {553        const payload = msg.payload as554          | { entries?: unknown; mode?: unknown; settings?: unknown }555          | null556          | undefined;557        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {558          return { ok: false, error: "invalid_payload" };559        }560        if (!Array.isArray(payload.entries)) {561          return { ok: false, error: "invalid_payload" };562        }563        if (payload.mode !== "replace" && payload.mode !== "merge") {564          return { ok: false, error: "invalid_payload" };565        }566        const summary = await vault.restoreEntries(567          payload.entries as Parameters<typeof vault.restoreEntries>[0],568          payload.mode569        );570        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {571          await vault.updateSettings(payload.settings as vault.VaultSettings);572        }573        return { ok: true, data: summary };574      }575      case "CLEAR_VAULT_ENTRIES": {576        await vault.clearVaultEntries("REPLACE_ALL");577        return { ok: true };578      }579      case "GET_VAULT_HISTORY": {580        const snapshots = await vault.getVaultHistory();581        return { ok: true, data: snapshots };582      }583      case "RESTORE_VAULT_SNAPSHOT": {584        const { snapshotId } = msg.payload as { snapshotId: string };585        const result = await vault.restoreVaultSnapshot(snapshotId);586        if (!result.ok) return { ok: false, error: result.error };587        broadcastToContentScripts({ type: "VAULT_LOCKED" });588        return { ok: true };589      }590      case "COUNT_DUPLICATES": {591        return { ok: true, data: vault.countDuplicates() };592      }593      case "DEDUPLICATE_ENTRIES": {594        const removed = await vault.deduplicateEntries();595        return { ok: true, data: removed };596      }597      case "UPDATE_ENTRY": {598        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;599        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {600          return { ok: false, error: "invalid_payload" };601        }602        const { id, patch } = payload;603        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {604          return { ok: false, error: "invalid_payload" };605        }606        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);607        return { ok: true };608      }609      case "ADD_ADDITIONAL_URL": {610        const { id, url } = msg.payload as { id: string; url: string };611        const trimmed = typeof url === "string" ? url.trim() : "";612        if (!trimmed) return { ok: false, error: "url required" };613        const existing = vault.getEntryById(id);614        if (!existing) return { ok: false, error: "entry not found" };615        if (existing.type !== "login") return { ok: false, error: "login entries only" };616        const merged = [...(existing.additionalUrls ?? []), trimmed];617        await vault.updateEntry(id, { additionalUrls: merged });618        return { ok: true };619      }620      case "DELETE_ENTRY": {621        const { id } = msg.payload as { id: string };622        await vault.deleteEntry(id);623        return { ok: true };624      }625      case "GET_DELETED_ENTRIES":626        return { ok: true, data: vault.getDeletedEntries() };627      case "RESTORE_ENTRY": {628        const { id } = msg.payload as { id: string };629        await vault.restoreEntry(id);630        return { ok: true };631      }632      case "PURGE_ENTRY": {633        const { id } = msg.payload as { id: string };634        await vault.purgeEntry(id);635        return { ok: true };636      }637      case "PURGE_EXPIRED_TRASH": {638        const { retentionMs } = msg.payload as { retentionMs: number };639        const purged = await vault.purgeExpiredTrash(retentionMs);640        return { ok: true, data: purged };641      }642      case "SAVE_NOTE": {643        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };644        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };645        const now = Date.now();646        if (id) {647          const existing = vault.getEntryById(id);648          if (!existing) return { ok: false, error: "not_found" };649          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });650          return { ok: true, data: vault.getEntryById(id) };651        } else {652          const entry = await vault.addEntry({653            type: "note",654            title: title || "Untitled",655            notes: body,656            createdAt: now,657            modifiedAt: now,658          } as any);659          return { ok: true, data: entry };660        }661      }662      case "DELETE_NOTE": {663        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };664        const { id } = msg.payload as { id: string };665        await vault.deleteEntry(id);666        return { ok: true };667      }668      case "GET_NOTES": {669        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };670        const notes = vault.getEntries().filter(671          (e) => e.type === "note" && !e.deletedAt672        );673        return { ok: true, data: notes } as MessageResponse;674      }675      case "SEARCH_VAULT": {676        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };677        const { query } = msg.payload as { query: string };678        const q = query.toLowerCase();679        const searchResults = vault.getEntries().filter(680          (e) =>681            !e.deletedAt &&682            (e.title.toLowerCase().includes(q) ||683              e.notes?.toLowerCase().includes(q) ||684              e.username?.toLowerCase().includes(q))685        );686        return { ok: true, data: searchResults } as MessageResponse;687      }688      case "PAIRING_COMPLETED": {689        const { deviceName, publicKeyHex, deviceIp } = (msg.payload ?? {}) as {690          deviceName?: string;691          publicKeyHex?: string;692          deviceIp?: string;693        };694        if (!publicKeyHex) return { ok: false, error: "publicKeyHex required" };695        // Only accept publicKeyHex values that just completed a real Noise NK696        // handshake (initiator or responder side). Without this gate, anyone697        // who can sendMessage to the background can pair an arbitrary key698        // (M13/SEC-005). Re-confirming an already-paired device is allowed699        // so legitimate update-IP retries still work.700        const alreadyPaired = (await getPairedDevices()).some(701          d => d.x25519PublicKey === publicKeyHex,702        );703        const verified = consumePendingPair(publicKeyHex);704        if (!verified && !alreadyPaired) {705          return { ok: false, error: "pairing_not_verified" };706        }707        const { setHasPaired: setPaired } = await import("./sync-storage");708        await setPaired();709        try {710          await addPairedDevice({711            deviceId: publicKeyHex,712            displayName: deviceName ?? "Unknown",713            x25519PublicKey: publicKeyHex,714            pairedAt: Date.now(),715            lastSeenAt: Date.now(),716            lastKnownIp: deviceIp,717          });718        } catch {719          // Already paired — update IP if provided720          if (deviceIp) {721            await updatePairedDevice(publicKeyHex, { lastKnownIp: deviceIp, lastSeenAt: Date.now() });722          }723        }724        return { ok: true };725      }726      case "AUTOFILL_QUERY": {727        if (!vault.isUnlocked()) {728          return { ok: false, error: "VAULT_LOCKED" };729        }730        const { domain, includeAll, kind } = msg.payload as {731          domain: string;732          includeAll?: boolean;733          kind?: "login" | "card";734        };735        // kind="card": return saved cards as compact summaries for the736        // inline card silver platter. Cards are not domain-scoped — every737        // saved card is a candidate on every checkout page — so domain is738        // ignored when kind === "card".739        if (kind === "card") {740          const cards = vault.getEntries().filter((e) => e.type === "card");741          return {742            ok: true,743            data: cards.map((e) => ({744              id: e.id,745              title: e.cardNickname || e.title,746              cardholderName: e.cardholderName,747              last4: e.last4,748              expMonth: e.expMonth,749              expYear: e.expYear,750              network: e.network,751            })),752          };753        }754        // The inline selector fills username+password into a form. Passkey-755        // only entries have no password to fill; sign-in for those goes756        // through the WebAuthn path instead. Filter them out everywhere so757        // the user doesn't see four "GitHub" rows that mostly do nothing.758        // Notes and cards never belonged here either.759        const matches = (760          includeAll761            ? vault762                .getEntries()763                .filter((entry) => entry.type !== "note" && entry.type !== "card")764            : vault.queryDomain(domain)765        ).filter((entry) => !isPasskeyOnly(entry));766        return {767          ok: true,768          data: matches.map((e) =>769            includeAll770              ? {771                  id: e.id,772                  title: e.title,773                  hasPasskey: e.passkey !== undefined,774                }775              : {776                  id: e.id,777                  title: e.title,778                  username: e.username,779                  email: e.email,780                  url: e.url,781                  hasTotp: Boolean(e.totp),782                  hasPasskey: e.passkey !== undefined,783                }784          ),785        };786      }787      case "GET_ENTRY_FOR_FILL": {788        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };789        const { id } = msg.payload as { id: string };790        const entry = vault.getEntryById(id);791        if (!entry) return { ok: false, error: "entry not found" };792        // Passkey-only entries (passkey credential, no password) cannot be793        // filled into a form — sign-in goes through the WebAuthn path. A794        // login that ALSO has a passkey is still fillable for its password.795        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey not fillable" };796        // Strip the passkey credential from the response — content scripts797        // never need the private key, and there's no reason to expose the798        // public credential metadata over the boundary either.799        const { passkey: _strippedPasskey, ...safeEntry } = entry;800        return { ok: true, data: safeEntry };801      }802      case "COPY": {803        const { text, label, alreadyWritten } = msg.payload as {804          text: string;805          label: string;806          alreadyWritten?: boolean;807        };808        await copyToClipboard(text, label, Boolean(alreadyWritten));809        return { ok: true };810      }811      case "CHECK_ALL_BREACHES": {812        const allEntries = vault.getEntries();813        const results: Record<string, number> = {};814        for (const entry of allEntries) {815          if (entry.type === "note") continue;816          if (!entry.password) continue;817          results[entry.id] = await vault.checkBreach(entry.password);818          // Small delay — be a good citizen to the HIBP API819          await new Promise((r) => setTimeout(r, 200));820        }821        // Persist any non-zero counts back to entries822        for (const [id, count] of Object.entries(results)) {823          const entry = vault.getEntryById(id);824          if (entry && (entry.breach ?? 0) !== count) {825            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });826          }827        }828        return { ok: true, data: results };829      }830      case "GET_SETTINGS":831        return { ok: true, data: await vault.ensureSettingsLoaded() };832      case "UPDATE_SETTINGS": {833        const patch = msg.payload;834        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {835          return { ok: false, error: "invalid_payload" };836        }837        await vault.updateSettings(patch as vault.VaultSettings);838        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {839          await setupAutoLock();840          if (vault.isUnlocked()) touchAutoLock();841        }842        return { ok: true };843      }844      case "GET_PENDING_PASSKEY":845        return { ok: true, data: await getPendingPasskeyRequest() };846      case "APPROVE_PASSKEY": {847        const { requestId } = msg.payload as { requestId: number };848        await resolvePendingPasskeyRequest(requestId, true);849        return { ok: true };850      }851      case "DENY_PASSKEY": {852        const { requestId } = msg.payload as { requestId: number };853        await resolvePendingPasskeyRequest(requestId, false);854        return { ok: true };855      }856      case "GET_PASSKEY_PROVIDER_STATE":857        return { ok: true, data: await getPasskeyProviderState() };858      case "SET_PASSKEY_PROVIDER_ENABLED": {859        const { enabled } = msg.payload as { enabled: boolean };860        // Disabling is always free; gating fires only when a free user is861        // trying to turn passkey interception on.862        if (enabled) {863          const gate = await requirePro("passkeys");864          if (!gate.allowed) return { ok: false, error: "pro_required" };865        }866        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };867      }868      case "FIRE_CANARY_PING": {869        const { webhookUrl, entryTitle, trigger } = msg.payload as {870          webhookUrl: string;871          entryTitle: string;872          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";873        };874        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {875          return { ok: false, error: "invalid webhook url" };876        }877        const body = JSON.stringify({878          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",879          entry: entryTitle,880          trigger,881          timestamp: new Date().toISOString(),882          source: "peach-extension",883        });884        if (trigger === "test") {885          // Permitted outbound fetch: user-configured canary alert endpoint886          // (validated by isAllowedCanaryWebhookUrl above). This is the887          // only non-HIBP outbound call in the extension — see888          // Projects.md §3.7. Test pings are awaited so the UI can show889          // success/failure.890          try {891            const res = await fetch(webhookUrl, {892              method: "POST",893              headers: { "Content-Type": "application/json" },894              body,895            });896            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };897          } catch (err) {898            return { ok: false, error: err instanceof Error ? err.message : "network error" };899          }900        }901        // Non-test triggers are fire-and-forget902        fetch(webhookUrl, {903          method: "POST",904          headers: { "Content-Type": "application/json" },905          body,906        }).catch(() => {});907        return { ok: true };908      }909      case "ACTIVATE_LICENSE": {910        const { key } = msg.payload as { key: string };911        const licenseInfo = await activateLicense(key);912        return { ok: true, data: licenseInfo };913      }914      case "GET_LICENSE": {915        const licenseInfo = await getLicenseInfo();916        return { ok: true, data: licenseInfo };917      }918      case "GET_LICENSE_KEY": {919        const key = await getLicenseKey();920        return { ok: true, data: key };921      }922      case "DEACTIVATE_LICENSE": {923        await deactivateLicense();924        return { ok: true };925      }926      case "SHOULD_PLAY_CELEBRATION": {927        const should = await shouldPlayCelebration();928        return { ok: true, data: should };929      }930      case "MARK_CELEBRATION_PLAYED": {931        await markCelebrationPlayed();932        return { ok: true };933      }934      case "GET_CODEX_VAULT_DATA": {935        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the936        // popup navigates to the License section without further coordination.937        const gate = await requirePro("codex");938        if (!gate.allowed) return { ok: false, error: "pro_required" };939        return await handleGetCodexVaultData();940      }941      case "ESTIMATE_CODEX_PAGES": {942        const gate = await requirePro("codex");943        if (!gate.allowed) return { ok: false, error: "pro_required" };944        return await handleEstimateCodexPages();945      }946      case "RESTORE_FROM_CODEX": {947        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still948        // be able to restore a vault that was printed by a Pro user.949        // DO NOT add a Pro gate here.950        const payload = msg.payload as CodexRestorePayload;951        return await handleRestoreFromCodex(payload);952      }953      case "OPEN_PRO_GATE": {954        // Content script requests: open popup and navigate to License section.955        const { feature } = (msg.payload ?? {}) as { feature?: string };956        if (chrome.storage.session) {957          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });958        }959        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }960        return { ok: true };961      }962      case "GET_IDENTITIES": {963        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };964        return { ok: true, data: vault.getIdentities() };965      }966      case "TOUCH_AUTO_LOCK": {967        // touchAutoLock() is already called by shouldRefreshAutoLock above;968        // this case just gives the popup a typed message to keep the session alive.969        return { ok: true };970      }971      case "GET_ADVANCED_HEALTH_REPORT": {972        const gate = await requirePro("advanced_health");973        if (!gate.allowed) return { ok: false, error: "pro_required" };974        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };975        const report = await buildAdvancedHealthReport(vault.getEntries());976        return { ok: true, data: report };977      }978      case "INITIATE_PASSWORD_CHANGE": {979        const gate = await requirePro("smart_password_change");980        if (!gate.allowed) return { ok: false, error: "pro_required" };981        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };982        const { id } = msg.payload as { id: string };983        const entry = vault.getEntryById(id);984        if (!entry) return { ok: false, error: "entry not found" };985        const url = resolveResetUrl(entry);986        if (!url) return { ok: false, error: "no reset url" };987        try {988          await chrome.tabs.create({ url });989          return { ok: true, data: { url } };990        } catch (err) {991          return {992            ok: false,993            error: err instanceof Error ? err.message : "failed to open tab",994          };995        }996      }997      case "IS_DURESS_ENABLED": {998        const enabled = await vault.isDuressEnabled();999        return { ok: true, data: enabled };1000      }1001      case "SETUP_DURESS": {1002        const { duressPassword } = msg.payload as { duressPassword: string };1003        await vault.setupDuress(duressPassword);1004        return { ok: true };1005      }1006      case "DISABLE_DURESS": {1007        await vault.disableDuress();1008        return { ok: true };1009      }1010      case "VERIFY_MAIN_PASSWORD": {1011        const { password } = msg.payload as { password: string };1012        const ok = await vault.verifyMainPassword(password);1013        return { ok: true, data: ok };1014      }1015      case "CHANGE_PASSWORD": {1016        const { currentPassword, newPassword } = msg.payload as {1017          currentPassword: string;1018          newPassword: string;1019        };1020        const changed = await vault.changePassword(currentPassword, newPassword);1021        return changed1022          ? { ok: true }1023          : { ok: false, error: "incorrect current password" };1024      }1025      case "GET_SITE_PASSWORD_POLICY": {1026        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1027        if (!tab?.id) return { ok: true, data: null };1028        try {1029          const response = await chrome.tabs.sendMessage(tab.id, {1030            type: "GET_SITE_PASSWORD_POLICY",1031          });1032          return (response as MessageResponse) ?? { ok: true, data: null };1033        } catch {1034          return { ok: true, data: null };1035        }1036      }1037      case "GET_SYNC_STATE": {1038        const pairedDevices = await getPairedDevices();1039        const trustedNetworks = await getTrustedNetworks();1040        const tailscale = await isOnTailscale();1041        const pro = await isProUser();10421043        let status: SyncStatus = "offline";1044        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {1045          if (pairedDevices.length === 0) {1046            status = "no_peers";1047          } else {1048            status = "synced";1049          }1050        } else {1051          status = "not_trusted";1052        }10531054        const lastSyncRaw = await storageGet("peach_last_sync_at");1055        const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN;1056        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined;10571058        return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } };1059      }1060      case "GET_PAIRED_DEVICES": {1061        const devices = await getPairedDevices();1062        return { ok: true, data: { devices } };1063      }1064      case "GET_SYNC_STATUS": {1065        const lastSyncRaw = await storageGet("peach_last_sync_at");1066        const lastSyncParsed = lastSyncRaw ? parseInt(lastSyncRaw, 10) : NaN;1067        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : null;1068        const status: 'up_to_date' | 'never' = lastSyncAt ? 'up_to_date' : 'never';1069        return { ok: true, data: { status, lastSyncAt } };1070      }1071      case "ACCEPT_PAIRING": {1072        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.1073        return { ok: true };1074      }1075      case "REMOVE_PAIRED_DEVICE": {1076        const { deviceId } = msg.payload as { deviceId: string };1077        await removePairedDevice(deviceId);1078        return { ok: true };1079      }1080      case "REMOVE_TRUSTED_NETWORK": {1081        const payload = msg.payload as1082          | { ssid?: unknown; bssid?: unknown; isTailscale?: unknown }1083          | null1084          | undefined;1085        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {1086          return { ok: false, error: "invalid_payload" };1087        }1088        const { ssid, bssid, isTailscale } = payload as { ssid?: string; bssid?: string; isTailscale?: boolean };1089        const networks = await getTrustedNetworks();1090        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 1091          (isTailscale ? n.isTailscale : n.ssid === ssid) && 1092          (!bssid || n.bssid === bssid)1093        );1094        if (network) {1095          await removeTrustedNetwork(network.addedAt);1096        }1097        return { ok: true };1098      }1099      case "MARK_NETWORK_TRUSTED": {1100        const network = await getCurrentNetwork();1101        await addTrustedNetwork({1102          ssid: network.ssid,1103          bssid: network.bssid,1104          isTailscale: network.isTailscale,1105          addedAt: Date.now(),1106        });1107        return { ok: true };1108      }1109      case "GET_INCOMING_PAIRING_REQUEST": {1110        const request = await getIncomingPairingRequest();1111        return { ok: true, data: request };1112      }1113      case "RESPOND_INCOMING_PAIRING": {1114        const { accept } = msg.payload as { accept: boolean };1115        const request = await getIncomingPairingRequest();1116        if (!request) return { ok: false, error: "no_pending_request" };1117        if (Date.now() > request.expiresAt) {1118          await clearIncomingPairingRequest();1119          return { ok: false, error: "expired" };1120        }1121        await clearIncomingPairingRequest();1122        if (accept) {1123          await addPairedDevice({1124            deviceId: request.publicKeyHex,1125            displayName: request.deviceName,1126            x25519PublicKey: request.publicKeyHex,1127            pairedAt: Date.now(),1128            lastSeenAt: Date.now(),1129          });1130        }1131        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };1132      }1133      case "START_PAIRING_SERVER": {1134        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.1135        const token = generateSixDigitToken();1136        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;1137        await setActivePairingToken({ token, expiresAt });1138        // Fire-and-forget subnet scan — finds the phone after it scans the QR1139        // and calls SCAN_PAIRING_QR to register the token with SyncPlugin.1140        if (!isNativePlatform()) {1141          void runPairingSubnetScan(token);1142        }1143        return { ok: true, data: { token, expiresAt } };1144      }1145      case "STOP_PAIRING_SERVER": {1146        try {1147          await setActivePairingToken(null);1148        } catch { /* best-effort */ }1149        return { ok: true };1150      }1151      case "GET_RECENT_PAIRING": {1152        const recent = await consumeRecentPairing();1153        return { ok: true, data: recent };1154      }1155      case "DEBUG_INJECT_INCOMING_PAIRING": {1156        // M14/SEC-007: blocked in production builds. The handler exists for1157        // Phase 7 banner UX rehearsal without a live native host; shipping1158        // it in production lets any background-message sender inject a1159        // synthetic pairing prompt. Allowed in 'development' and 'test'1160        // modes; vite sets MODE='production' for release builds.1161        if (import.meta.env.MODE === "production") {1162          return { ok: false, error: "not_available" };1163        }1164        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {1165          deviceName?: string;1166          publicKeyHex?: string;1167        };1168        if (!deviceName || !publicKeyHex) {1169          return { ok: false, error: "missing_payload" };1170        }1171        const now = Date.now();1172        await setIncomingPairingRequest({1173          deviceName,1174          publicKeyHex,1175          receivedAt: now,1176          expiresAt: now + 60_000,1177        });1178        return { ok: true };1179      }1180      case "RESET_SYNC_IDENTITY": {1181        const gate = await requirePro("sync");1182        if (!gate.allowed) return { ok: false, error: "pro_required" };1183        const devices = await getPairedDevices();1184        for (const device of devices) {1185          await removePairedDevice(device.deviceId);1186        }1187        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };1188      }1189      case "RECORD_MANUAL_SUMMON": {1190        const { domain } = msg.payload as { domain: string };1191        const settings = vault.getSettings();1192        const existing = settings.manualSummonDomains?.[domain];1193        const now = Date.now();1194        await vault.updateSettings({1195          manualSummonDomains: {1196            ...settings.manualSummonDomains,1197            [domain]: {1198              firstSummonedAt: existing?.firstSummonedAt ?? now,1199              summonCount: (existing?.summonCount ?? 0) + 1,1200              lastSummonedAt: now,1201            },1202          },1203        });1204        return { ok: true };1205      }1206      case "DECLINE_CARD_SAVE": {1207        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1208        await vault.declineCardSaveOffer(last4, expMonth, expYear);1209        return { ok: true };1210      }1211      case "IS_CARD_DECLINED": {1212        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1213        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1214        return { ok: true, data: declined };1215      }1216      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1217        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1218          rpId?: string;1219          rpName?: string;1220          userName?: string;1221          userDisplayName?: string;1222        };1223        if (!rpId || !userName) return { ok: false, error: "rpId and userName required" };1224        return await initiateFirefoxPasskeyCreate({1225          rpId,1226          rpName: rpName ?? rpId,1227          userName,1228          userDisplayName,1229        });1230      }12311232      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1233        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1234        if (!payload) return { ok: false, error: "missing payload" };1235        return await completeFirefoxPasskeyCreate(payload);1236      }12371238      case "PASSKEY_OFFER_DECLINE": {1239        const { domain } = (msg.payload ?? {}) as { domain?: string };1240        if (!domain) return { ok: false, error: "domain required" };1241        await recordPasskeyOfferDecline(domain);1242        return { ok: true };1243      }12441245      case "GET_PASSKEY_OFFER_DECLINED": {1246        const { domain } = (msg.payload ?? {}) as { domain?: string };1247        if (!domain) return { ok: false, error: "domain required" };1248        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1249      }12501251      case "PASSKEY_HAS_CREDENTIALS": {1252        const payload = msg.payload as {1253          rpId?: string;1254          allowCredentials?: Array<{ id: string; type?: string }>;1255        } | undefined;1256        if (!payload?.rpId) return { ok: false, error: "rpId required" };1257        return await handlePasskeyHasCredentials({1258          rpId: payload.rpId,1259          allowCredentials: payload.allowCredentials ?? [],1260        });1261      }12621263      case "PASSKEY_CREATE": {1264        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1265        if (!payload?.rpId || !payload?.userName) {1266          return { ok: false, error: "rpId and userName required" };1267        }1268        return await handleFirefoxPasskeyCreate(payload);1269      }12701271      case "PASSKEY_GET": {1272        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1273        if (!payload?.rpId) return { ok: false, error: "rpId required" };1274        return await handleFirefoxPasskeyGet(payload);1275      }12761277      case "PASSKEY_AUTH_RESPONSE": {1278        const { requestId, approved } = (msg.payload ?? {}) as {1279          requestId?: string | number;1280          approved?: boolean;1281        };1282        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1283          return { ok: false, error: 'requestId and approved required' };1284        }1285        await resolvePendingPasskeyRequest(Number(requestId), approved);1286        return { ok: true };1287      }12881289      case "GET_PASSKEY_FOR_DOMAIN": {1290        const { domain } = (msg.payload ?? {}) as { domain?: string };1291        if (!domain) return { ok: false, error: "domain required" };1292        if (!vault.isUnlocked()) return { ok: true, data: null };1293        const match = vault1294          .getEntries()1295          .find((entry) => entry.passkey?.rpId === domain);1296        if (!match || !match.passkey) return { ok: true, data: null };1297        // Slim shape — only the fields State 11 needs. Never expose private1298        // key material, even though this is locked behind isUnlocked.1299        return {1300          ok: true,1301          data: {1302            rpId: match.passkey.rpId,1303            userName: match.passkey.userName,1304            browser: match.passkey.browser,1305          },1306        };1307      }13081309      case "DESTROY_VAULT": {1310        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1311        // storage.local.clear() wipes every Peach key (slots, settings, license,1312        // onboarded flag, history, sync state, declined cards, recall, etc.);1313        // session.clear() wipes pending passkey requests + pro-notice queues.1314        // Caller (Panic.tsx) handles UI navigation back to onboarding.1315        vault.lock();1316        await storageClear();1317        await vault.clearVaultHistory();1318        if (chrome.storage.session) {1319          await chrome.storage.session.clear();1320        }1321        return { ok: true };1322      }13231324      case "SUBMIT_FEEDBACK": {1325        const { category, message, version, browser } = msg.payload as {1326          category: string;1327          message: string;1328          version: string;1329          browser: string;1330        };1331        if (!message.trim()) return { ok: false, error: "message is empty" };1332        if (!FEEDBACK_ENDPOINT) return { ok: true };1333        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1334          return { ok: false, error: "invalid feedback endpoint" };1335        }1336        try {1337          const res = await fetch(FEEDBACK_ENDPOINT, {1338            method: "POST",1339            headers: { "Content-Type": "application/json" },1340            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1341          });1342          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1343        } catch (err) {1344          return { ok: false, error: err instanceof Error ? err.message : "network error" };1345        }1346      }1347      case "TRIGGER_SYNC": {1348        const gate = await requirePro("sync");1349        if (!gate.allowed) return { ok: false, error: "pro_required" };1350        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };13511352        if (isNativePlatform()) {1353          // Phone is the server — ensure it's listening for desktop connections.1354          syncBridge()?.ensureServerRunning?.();1355          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };1356        }13571358        // Desktop: iterate all paired devices and sync with each.1359        const paired = await getPairedDevices();1360        if (!paired.length) return { ok: true, data: { syncedCount: 0, reason: "no_paired_devices" } };13611362        const subnet = await getLocalSubnet();1363        const results: Array<{ device: string } & SyncResult> = [];13641365        for (const device of paired) {1366          if (!device.x25519PublicKey) continue;13671368          let result: SyncResult;13691370          // Fast path — use last known IP1371          if (device.lastKnownIp) {1372            result = await doVaultSync(device.lastKnownIp, device.x25519PublicKey);1373          } else {1374            result = { status: 'errored', applied: false, error: 'no_ip' };1375          }13761377          // Discovery path — scan if fast path failed1378          if (result.status === 'errored' && subnet) {1379            const newIp = await discoverDevice(subnet, device.x25519PublicKey);1380            if (newIp) {1381              await updatePairedDevice(device.x25519PublicKey, { lastKnownIp: newIp });1382              result = await doVaultSync(newIp, device.x25519PublicKey);1383            }1384          }13851386          if (result.status === 'completed') {1387            await updatePairedDevice(device.x25519PublicKey, {1388              lastSeenAt: Date.now(),1389              lastSyncAt: Date.now(),1390            });1391          }13921393          results.push({ device: device.displayName, ...result });1394        }13951396        const syncedCount = results.filter(r => r.status === 'completed').length;1397        if (syncedCount > 0) {1398          await chrome.storage.local.set({ peach_last_sync_at: String(Date.now()) });1399        }1400        return { ok: true, data: { syncedCount, results } };1401      }1402      // Android-only: biometric unlock with pre-derived key.1403      case "UNLOCK_WITH_KEY": {1404        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1405        if (!isNativePlatform()) {1406          return { ok: false, error: "desktop_only_uses_password" };1407        }1408        try {1409          const result = await vault.unlockWithKey(masterKeyHex);1410          if (result.ok) {1411            onVaultUnlocked();1412            await publishInMemoryVault(result.entries);1413          }1414          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1415        } catch {1416          return { ok: false, error: "invalid_key" };1417        }1418      }1419      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1420      case "GET_DERIVED_KEY": {1421        if (!isNativePlatform()) {1422          return { ok: false, error: "android_only" };1423        }1424        if (!vault.isUnlocked()) {1425          return { ok: false, error: "vault_locked" };1426        }1427        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1428      }1429      // Android: scanned a QR containing a desktop pairing token.1430      case "SCAN_PAIRING_QR": {1431        if (!isNativePlatform()) {1432          return { ok: false, error: "android_only" };1433        }1434        const { token } = msg.payload as { token: string };1435        syncBridge()?.startPairingSession?.({ token });1436        return { ok: true };1437      }1438      // Android: desktop opened a sync connection to the phone's WS server.1439      // Run the responder side of the vault exchange.1440      case "SYNC_SESSION_STARTED": {1441        if (!isNativePlatform()) return { ok: false };1442        if (!vault.isUnlocked()) {1443          return { ok: false, error: "vault_locked" };1444        }1445        const { connectionId } = (msg.payload ?? {}) as { connectionId?: string };1446        if (!connectionId) return { ok: false, error: "missing_connection_id" };14471448        const transport = createAndroidResponderTransport(connectionId);14491450        // Authenticate the initiator before exchanging any vault data. The1451        // native side has already completed the Noise NK handshake; auth1452        // frames here ride the Noise transport (native encrypts/decrypts).1453        const identity = await vault.getSyncIdentity();1454        try {1455          // CAUTION: noiseSessionStub is a structural placeholder — the real1456          // Noise NK handshake runs natively, so JS never holds the session1457          // object. performResponderAuth currently `void`s this argument,1458          // which is why identity-passthrough encrypt/decrypt and a zero1459          // handshake hash are safe. If performResponderAuth is ever updated1460          // to actually use this argument, this auth path will silently break1461          // (no type error). Revisit this stub if that helper changes.1462          const noiseSessionStub = {1463            encrypt: (b: Uint8Array) => b,1464            decrypt: (b: Uint8Array) => b,1465            handshakeHash: new Uint8Array(32),1466          };1467          const { initiatorPublicKey } = await performResponderAuth(1468            noiseSessionStub,1469            identity.privateKeyBytes,1470            identity.publicKeyBytes,1471            transport.send,1472            transport.receive,1473          );1474          const initiatorHex = noiseBytesToHex(initiatorPublicKey);1475          const paired = await getPairedDevices();1476          if (!paired.some(d => d.x25519PublicKey === initiatorHex)) {1477            await transport.close();1478            return { ok: false, error: "sync_rejected_unpaired_initiator" };1479          }1480          // Initiator just proved control of the matching static key; mark it1481          // as a verified handshake so a follow-up PAIRING_COMPLETED message1482          // can be trusted (M13/SEC-005).1483          markPairingHandshakeVerified(initiatorHex);1484        } catch (err) {1485          await transport.close();1486          return { ok: false, error: `sync_auth_failed: ${String(err)}` };1487        }14881489        const result = await runBlobSyncSession('responder', transport, buildSyncDeps());1490        if (result.applied) {1491          await publishInMemoryVault(vault.getEntries());1492        }1493        return { ok: true, data: result };1494      }1495      // Android: returns the phone's WiFi IP address.1496      case "GET_LOCAL_IP": {1497        if (!isNativePlatform()) {1498          return { ok: false, error: "android_only" };1499        }1500        const { ip } = (await syncBridge()?.getLocalIp?.()) ?? { ip: "" };1501        return { ok: true, data: { ip } };1502      }1503      case "GET_IDENTITY_SUGGESTIONS": {1504        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1505        const entries = vault.getEntries();1506        const suggestions = buildIdentitySuggestions(entries);1507        return { ok: true, data: { suggestions } };1508      }1509      case "POPULATE_INLINE_VAULT": {1510        if (!isNativePlatform()) return { ok: false };1511        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1512        const entries = vault.getEntries();1513        await publishInMemoryVault(entries);1514        return { ok: true };1515      }1516      case "ML_INIT":1517        return { ok: true };15181519      case "ML_PREDICT_BATCH": {1520        const { featuresArray } = msg.payload as { featuresArray: MLFieldFeatures[] };1521        return { ok: true, data: mlPredictBatch(featuresArray) };1522      }15231524      default:1525        return { ok: false, error: "unknown message type" };1526    }1527  } catch (err) {1528    return {1529      ok: false,1530      error: err instanceof Error ? err.message : "operation failed",1531    };1532  }1533}15341535// --- Mobile platform helpers ---15361537// Android: populates the in-memory vault used by PeachAutofillService.1538async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1539  const plugin = nativePlugin<{1540    setEntries?: (args: {1541      entries: Array<{1542        id: string;1543        title: string;1544        username: string;1545        email: string;1546        password: string;1547        url: string;1548        totp: string;1549        additionalUrls: string[];1550      }>;1551    }) => Promise<void>;1552  }>("InMemoryVaultPlugin");1553  if (!plugin?.setEntries) return;1554  await plugin.setEntries({1555    entries: entries.map((e) => ({1556      id: e.id,1557      title: e.title ?? "",1558      username: e.username ?? "",1559      email: (e as VaultEntry & { email?: string }).email ?? "",1560      password: e.password ?? "",1561      url: e.url ?? "",1562      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1563      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1564    })),1565  });1566}15671568// Android: clear the autofill in-memory store on lock.1569async function clearInMemoryVault(): Promise<void> {1570  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1571  if (!plugin?.clearEntries) return;1572  await plugin.clearEntries();1573}15741575interface SyncBridge {1576  ensureServerRunning?: () => void;1577  startPairingSession?: (args: { token: string }) => void;1578  getLocalIp?: () => Promise<{ ip: string }>;1579  sendToConnection?: (args: { connectionId: string; data: string }) => Promise<void>;1580  addListener?: (event: string, handler: (data: Record<string, string>) => void) => void;1581}15821583// Resolve the Capacitor SyncPlugin at call time — module-load resolution1584// races with Capacitor's plugin registration on the Android WebView.1585function syncBridge(): SyncBridge | null {1586  return nativePlugin<SyncBridge>("SyncPlugin");1587}15881589// Build a SyncTransport for the Android responder path — the phone's WS server1590// already has an open connection from the desktop. We send back via1591// SyncPlugin.sendToConnection and receive via the peach:sync-frame queue.1592const androidSyncFrameQueues = new Map<string, Array<(frame: string) => void>>();15931594export function deliverAndroidSyncFrame(connectionId: string, frame: string): void {1595  const queue = androidSyncFrameQueues.get(connectionId);1596  if (queue?.length) queue.shift()!(frame);1597}15981599function createAndroidResponderTransport(connectionId: string) {1600  const pendingReceivers: Array<(frame: string) => void> = [];1601  androidSyncFrameQueues.set(connectionId, pendingReceivers);16021603  return {1604    send: async (data: Uint8Array) => {1605      await syncBridge()?.sendToConnection?.({ connectionId, data: bytesToBase64(data) });1606    },1607    receive: (): Promise<Uint8Array> => new Promise((res) => {1608      pendingReceivers.push((frame) => {1609        res(frame ? base64ToBytes(frame) : new Uint8Array(0));1610      });1611    }),1612    close: async () => {1613      androidSyncFrameQueues.delete(connectionId);1614    },1615  };1616}16171618// Returns username use-counts from the vault, sorted by frequency. Each row1619// also carries the entry's email so the popup can suggest the email/username1620// pair the user has actually used together.1621function buildIdentitySuggestions(1622  entries: VaultEntry[],1623): Array<{ email: string; username: string; count: number }> {1624  const usernameCounts = new Map<string, number>();1625  const usernameEmail = new Map<string, string>();1626  for (const entry of entries) {1627    const username = entry.username ?? "";1628    const email = (entry as VaultEntry & { email?: string }).email ?? "";1629    if (!username && !email) continue;1630    const key = username || email;1631    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1632    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1633  }1634  return Array.from(usernameCounts.entries())1635    .sort((a, b) => b[1] - a[1])1636    .map(([username, count]) => ({1637      email: usernameEmail.get(username) ?? "",1638      username,1639      count,1640    }));1641}16421643/** Notify all content scripts that the vault just became available. */1644function broadcastToContentScripts(message: { type: string }): void {1645  if (!chrome.tabs?.query) return;1646  chrome.tabs.query({}, (tabs) => {1647    for (const tab of tabs) {1648      if (tab.id !== undefined) {1649        chrome.tabs.sendMessage(tab.id, message).catch(() => {1650          // Tab may not have a content script — silently ignore1651        });1652      }1653    }1654  });1655}16561657function shouldRefreshAutoLock(type: MessageType): boolean {1658  return (1659    type !== "HAS_VAULT" &&1660    type !== "IS_UNLOCKED" &&1661    type !== "GET_VAULT_STATUS" &&1662    type !== "LOCK" &&1663    type !== "UPDATE_SETTINGS" &&1664    type !== "GET_PENDING_PASSKEY" &&1665    type !== "GET_PASSKEY_PROVIDER_STATE" &&1666    type !== "DECLINE_CARD_SAVE" &&1667    type !== "IS_CARD_DECLINED" &&1668    type !== "SUBMIT_FEEDBACK"1669  );1670}16711672function isAllowedCanaryWebhookUrl(value: string): boolean {1673  try {1674    const url = new URL(value);1675    if (url.protocol !== "https:") return false;16761677    const hostname = url.hostname.toLowerCase();1678    if (1679      hostname === "localhost" ||1680      hostname.endsWith(".localhost") ||1681      isPrivateIpv4(hostname) ||1682      isPrivateIpv6(hostname)1683    ) {1684      return false;1685    }16861687    return true;1688  } catch {1689    return false;1690  }1691}16921693function isPrivateIpv4(hostname: string): boolean {1694  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1695    return true;1696  }16971698  const octets = hostname.split(".").map((part) => Number(part));1699  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1700    return false;1701  }17021703  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1704}17051706function isPrivateIpv6(hostname: string): boolean {1707  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1708  return (1709    normalized === "::1" ||1710    normalized.startsWith("fc") ||1711    normalized.startsWith("fd") ||1712    normalized.startsWith("fe80:")1713  );1714}