messages.ts

67.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 { runSelfTest } from "./self-test";15import * as vault from "./vault";16import {17  handleEstimateCodexPages,18  handleGetCodexVaultData,19  handleRestoreFromCodex,20} from "./codex-handlers";21import type { CodexRestorePayload } from "../shared/codex-types";22import {23  activateLicense,24  deactivateLicense,25  getLicenseInfo,26  getLicenseKey,27  isProUser,28  markCelebrationPlayed,29  shouldPlayCelebration,30} from "./license";31import {32  completeFirefoxPasskeyCreate,33  getPasskeyProviderState,34  getPendingPasskeyRequest,35  handleFirefoxPasskeyCreate,36  handleFirefoxPasskeyGet,37  handlePasskeyHasCredentials,38  initiateFirefoxPasskeyCreate,39  isPasskeyOfferDeclined,40  onVaultUnlocked,41  recordPasskeyOfferDecline,42  resolvePendingPasskeyRequest,43  setPasskeyProviderEnabled,44} from "./passkey";45import { buildAdvancedHealthReport, resolveResetUrl } from "./health";46import { storageClear, storageGet } from "../shared/storage";47import { findInvalidWords } from "../shared/recovery-words";48import {49  addPairedDevice,50  addTrustedNetwork,51  clearIncomingPairingRequest,52  getIncomingPairingRequest,53  getPairedDevices,54  getTrustedNetworks,55  removePairedDevice,56  removeTrustedNetwork,57  setIncomingPairingRequest,58  updatePairedDevice,59} from "./sync-storage";60import { getCurrentNetwork, isOnTailscale } from "./sync-network";61import {62  consumeRecentPairing,63  setActivePairingToken,64} from "./pairing-server-state";65import type {66  Message,67  MessageResponse,68  MessageType,69  ProFeature,70  VaultEntry,71} from "../shared/types";72import { isPasskeyOnly } from "../shared/types";73import type { SyncStatus, SyncableDevice } from "../shared/sync-types";74import { isNativePlatform, nativePlugin } from "../shared/native";75import { runBlobSyncSession, type SyncResult } from "./sync-coordinator";76import type { SyncDeps } from "./sync-coordinator";77import { createWebSocketSyncTransport } from "../shared/websocket-sync-transport";78import { performResponderAuth, bytesToHex as noiseBytesToHex } from "../shared/noise-js";79import { getLocalSubnet, discoverDevice, scanForPairingPhone } from "../shared/local-network";80import { predictBatch as mlPredictBatch } from "./ml";81import type { MLFieldFeatures } from "../shared/ml";82import { base64ToBytes, bytesToBase64 } from "../shared/sync-wire";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// 6-digit code pairing.119120const PAIRING_TOKEN_TTL_MS = 5 * 60 * 1000;121122123function generateSixDigitToken(): string {124  // crypto.getRandomValues, not Math.random — the token is the only secret125  // protecting the pairing window from a same-LAN attacker. 6 decimal digits126  // is 1 in 1,000,000; combined with a 5-minute TTL and pairing-mode gating127  // on the responder this is the right tradeoff between UX and security.128  const buf = new Uint32Array(1);129  crypto.getRandomValues(buf);130  const value = buf[0] % 1_000_000;131  return value.toString().padStart(6, "0");132}133134// ---------------------------------------------------------------------------135// Peer discovery glue (Phase 7 popup pairing flow).136137const PRIVATE_IPV4_RANGES = [138  { prefix: "10." },139  { prefix: "127." },140  { prefix: "169.254." },141  { prefix: "192.168." },142];143144// Empty disables network submission while the UI continues to function as a145// no-op (the handler returns ok:true without calling fetch). When set, the146// URL is validated by `isAllowedCanaryWebhookUrl` before any request, so the147// same private-IP/HTTPS rules that gate canary webhooks apply here.148const FEEDBACK_ENDPOINT = "";149150// ---------------------------------------------------------------------------151// Sync helpers152// ---------------------------------------------------------------------------153154/**155 * Short-lived registry of x25519 public keys that just completed a real Noise156 * NK handshake + initiator-auth proof. The PAIRING_COMPLETED handler must157 * find the supplied publicKeyHex here before it will call addPairedDevice —158 * otherwise an attacker could forge the message and pair an arbitrary key159 * (M13/SEC-005).160 *161 * Entries auto-expire after 30s. Each entry is consumed on first successful162 * PAIRING_COMPLETED so a single handshake cannot pair twice.163 */164const PENDING_PAIRS = new Map<string, ReturnType<typeof setTimeout>>();165const PENDING_PAIR_TTL_MS = 30_000;166167export function markPairingHandshakeVerified(publicKeyHex: string): void {168  if (!publicKeyHex) return;169  const existing = PENDING_PAIRS.get(publicKeyHex);170  if (existing) clearTimeout(existing);171  const t = setTimeout(() => PENDING_PAIRS.delete(publicKeyHex), PENDING_PAIR_TTL_MS);172  PENDING_PAIRS.set(publicKeyHex, t);173}174175function consumePendingPair(publicKeyHex: string): boolean {176  const t = PENDING_PAIRS.get(publicKeyHex);177  if (!t) return false;178  clearTimeout(t);179  PENDING_PAIRS.delete(publicKeyHex);180  return true;181}182183export function buildSyncDeps(): SyncDeps {184  return {185    isVaultUnlocked: () => vault.isUnlocked(),186    getVaultBlobForSync: async () => {187      const base = await vault.getVaultBlobForSync();188      if (!base) return null;189      const paired = await getPairedDevices();190      return {191        ...base,192        devices: paired193          .filter(d => d.x25519PublicKey)194          .map(d => ({195            publicKeyHex: d.x25519PublicKey,196            deviceName: d.displayName,197            pairedAt: d.pairedAt,198          })),199      };200    },201    applyIncomingVault: async (blob, ts, license, devices) => {202      const applied = await vault.applyIncomingVault(blob, ts, license);203      if (devices?.length) await mergeDeviceRegistry(devices);204      if (applied) {205        const reloaded = await vault.reloadEntriesAfterSync();206        if (!reloaded) {207          // The remote vault was encrypted under a different key (the remote208          // changed password). Our in-memory entries are now stale and cannot209          // be re-encrypted without overwriting the just-applied blob. Lock210          // to force a re-unlock with the new password (H3/COR-005).211          vault.lock();212          chrome.runtime213            .sendMessage({ type: "VAULT_RELOCK_AFTER_SYNC" })214            .catch(() => {});215        }216      }217      return applied;218    },219  };220}221222async function doVaultSync(ip: string, publicKeyHex: string): Promise<SyncResult> {223  // Defensive: refuse to drive a sync to a key not in the paired-devices224  // list. The WebSocket transport already authenticates the peer via Noise225  // NK + the initiator auth proof (H1), but pinning the key to the paired226  // set here makes "talk to anyone matching this static key" the only path227  // to vault application — there is no orphan-key window between pair and228  // sync (M11/COR-014).229  const paired = await getPairedDevices();230  if (!paired.some(d => d.x25519PublicKey === publicKeyHex)) {231    return { status: 'errored', applied: false, error: 'remote_not_paired' };232  }233  try {234    const identity = await vault.getSyncIdentity();235    const transport = await createWebSocketSyncTransport(236      `ws://${ip}:44100`,237      publicKeyHex,238      identity.privateKeyBytes,239      identity.publicKeyBytes,240    );241    const result = await runBlobSyncSession('initiator', transport, buildSyncDeps());242    // Reaching this point means createWebSocketSyncTransport completed both243    // the Noise NK handshake and the initiator-auth proof — the remote244    // proved possession of the matching static key (M13/SEC-005).245    if (result.status === 'completed') {246      markPairingHandshakeVerified(publicKeyHex);247    }248    return result;249  } catch (err) {250    return { status: 'errored', applied: false, error: String(err) };251  }252}253254async function mergeDeviceRegistry(incoming: SyncableDevice[]): Promise<void> {255  const existing = await getPairedDevices();256  const existingKeys = new Set(existing.map(d => d.x25519PublicKey));257  for (const device of incoming) {258    if (!existingKeys.has(device.publicKeyHex)) {259      await addPairedDevice({260        deviceId: device.publicKeyHex,261        displayName: device.deviceName,262        x25519PublicKey: device.publicKeyHex,263        pairedAt: device.pairedAt,264        lastSeenAt: 0,265        lastKnownIp: '',266      }).catch(() => {});267    }268  }269}270271// Background pairing scan — runs after START_PAIRING_SERVER fires on desktop.272// Scans the local subnet for a phone that has accepted the pairing token,273// stores it, runs the initial vault exchange, then notifies the popup.274async function runPairingSubnetScan(token: string): Promise<void> {275  const subnet = await getLocalSubnet();276  if (!subnet) return;277278  const found = await scanForPairingPhone(subnet, token);279  if (!found) return;280281  const { ip, publicKeyHex } = found;282283  try {284    await addPairedDevice({285      deviceId: publicKeyHex,286      displayName: 'Peach',287      x25519PublicKey: publicKeyHex,288      pairedAt: Date.now(),289      lastSeenAt: Date.now(),290      lastKnownIp: ip,291    });292  } catch {293    // Already paired — update IP294    await updatePairedDevice(publicKeyHex, { lastKnownIp: ip, lastSeenAt: Date.now() });295  }296297  // Immediate vault exchange — the free one-time transfer298  await doVaultSync(ip, publicKeyHex);299300  chrome.runtime.sendMessage({301    type: 'PAIRING_COMPLETED',302    payload: { deviceName: 'Peach', publicKeyHex, deviceIp: ip },303  }).catch(() => {});304}305306export function setupMessageHandler(): void {307  chrome.runtime.onMessage.addListener(308    (msg: unknown, sender, sendResponse) => {309      if (!isMessage(msg)) {310        sendResponse({ ok: false, error: "invalid_message" });311        return true;312      }313      handleMessage(msg, sender)314        .then(sendResponse)315        .catch((err) =>316          sendResponse({317            ok: false,318            error: err instanceof Error ? err.message : String(err),319          })320        );321      return true;322    }323  );324325  // Android: the chrome shim queues sendMessage calls until this handler is326  // registered. Without this hookup, every message hangs on Capacitor builds.327  // eslint-disable-next-line @typescript-eslint/no-explicit-any328  const reg = (globalThis as any).__peachRegisterMessageHandler;329  if (typeof reg === "function") {330    reg(async (m: unknown) => {331      if (!isMessage(m)) return { ok: false, error: "invalid_message" };332      try {333        return await handleMessage(m);334      } catch (err) {335        return {336          ok: false,337          error: err instanceof Error ? err.message : String(err),338        };339      }340    });341  }342343  // Android: subscribe to SyncPlugin events.344  if (isNativePlatform()) {345    const syncPlug = nativePlugin<{346      addListener: (347        event: string,348        handler: (data: Record<string, string>) => void349      ) => void;350    }>("SyncPlugin");351352    // Pairing probe answered — store the paired device (desktop, no IP needed353    // since the desktop never acts as a WS server).354    syncPlug?.addListener?.("peach:pair-probe-answered", (data) => {355      const deviceName = data.deviceName ?? "Peach";356      const publicKeyHex = data.publicKeyHex ?? "";357      // Native handled the pairing handshake — trust this entry into the358      // verified-handshake set (M13/SEC-005). The subsequent PAIRING_COMPLETED359      // message will consume it.360      if (publicKeyHex) markPairingHandshakeVerified(publicKeyHex);361      void (async () => {362        const { addPairedDevice, setHasPaired: setPaired } = await import("./sync-storage");363        await addPairedDevice({364          deviceId: publicKeyHex || (data.connectionId ?? "unknown"),365          displayName: deviceName,366          x25519PublicKey: publicKeyHex,367          pairedAt: Date.now(),368          lastSeenAt: Date.now(),369        }).catch(() => {});370        await setPaired();371        chrome.runtime.sendMessage({372          type: "PAIRING_COMPLETED",373          payload: { deviceName, publicKeyHex },374        }).catch(() => {});375      })();376    });377378    // Sync frame received — route to the waiting responder session.379    syncPlug?.addListener?.("peach:sync-frame", (data) => {380      const { connectionId, frame } = data;381      if (connectionId && frame) deliverAndroidSyncFrame(connectionId, frame);382    });383384    // Sync session started (SYNC_HELLO received by SyncPlugin) — dispatch as385    // a background message so SYNC_SESSION_STARTED handler runs the responder.386    syncPlug?.addListener?.("peach:sync-session-started", (data) => {387      const { connectionId } = data;388      if (!connectionId) return;389      void handleMessage({ type: "SYNC_SESSION_STARTED", payload: { connectionId } });390    });391  }392}393394function isMessage(m: unknown): m is Message {395  return typeof m === "object" && m !== null && "type" in m;396}397398export async function handleMessage(399  msg: Message,400  sender: Partial<chrome.runtime.MessageSender> = {}401): Promise<MessageResponse> {402  try {403    // Validate sender — only allow messages from our extension pages/scripts.404    // `sender.id` is undefined for messages originating from extension UI405    // (popup/options), which is legitimate; reject only when it is defined406    // and does not match our extension id.407    if (408      sender.id !== undefined &&409      sender.id !== chrome.runtime.id410    ) {411      return { ok: false, error: "invalid_sender" };412    }413414    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {415      touchAutoLock();416    }417418    switch (msg.type) {419      case "CREATE_VAULT": {420        const { password } = msg.payload as { password: string };421        await vault.createVault(password);422        await setupAutoLock();423        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });424        onVaultUnlocked();425        return { ok: true };426      }427      case "UNLOCK": {428        const { password } = msg.payload as { password: string };429        const ok = await vault.unlock(password);430        if (ok) {431          // KAT: verify the WebCrypto stack is healthy before the user relies on it.432          // Runs after unlock so latency is hidden behind the vault-load time.433          const kat = await runSelfTest();434          if (!kat.ok) {435            console.error("[Peach] Crypto self-test FAILED:", kat.error);436            await vault.lock();437            return { ok: false, error: "self_test_failed" };438          }439          await setupAutoLock();440          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });441          onVaultUnlocked();442          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());443          return { ok: true };444        }445        // Distinguish corruption from wrong password so the popup can offer446        // a history-restore path instead of falsely accusing the user of447        // mistyping (M7/COR-007).448        const failure = vault.consumeLastUnlockFailureReason();449        if (failure) {450          return {451            ok: false,452            error: "vault_corrupted",453            canRestoreFromHistory: true,454          } as MessageResponse;455        }456        return { ok: false };457      }458      case "VALIDATE_RECOVERY_WORDS": {459        const { words } = msg.payload as { words: string[] };460        const invalid = findInvalidWords(words);461        return { ok: true, data: { valid: invalid.length === 0, invalid } };462      }463      case "GET_RECOVERY_WORDS": {464        // Must be unlocked and have recovery set up (vault must be v2.12+).465        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };466        try {467          const words = await vault.getRecoveryWords();468          return { ok: true, data: words };469        } catch (e) {470          // pre-v2.12 vault that hasn't migrated471          return { ok: false, error: "recovery_not_setup" };472        }473      }474      case "RECOVER_WITH_WORDS": {475        // User has lost their password but has their 12 recovery words.476        // We: (1) validate the words, (2) re-encrypt vault with new password.477        const { words, newPassword } = msg.payload as {478          words: string[];479          newPassword: string;480        };481        const stored = await vault.loadSlotA();482        if (!stored) return { ok: false, error: "no_vault" };483        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {484          return { ok: false, error: "recovery_not_setup" };485        }486        // Unwrap the root key from the recovery escrow.487        try {488          await vault.unwrapRootKeyForRecovery(489            stored.recovery_wrapped_root_key,490            stored.recovery_nonce ?? "",491            stored.recovery_tag ?? "",492            stored.recovery_salt,493            words494          );495        } catch {496          return { ok: false, error: "invalid_recovery_words" };497        }498        // Re-key: derive fresh salt + key from new password.499        const newSalt = vault.generateSalt();500        const newKey = await vault.deriveKey(newPassword, newSalt);501        // Re-wrap root key under the new password's derived key so the same502        // recovery words continue to work after the password change.503        await vault.rewrapRootKeyForPassword(newKey, newSalt);504        // Re-encrypt vault entries with the new key.505        await vault.changePasswordWithNewKey(newSalt, newKey);506        await setupAutoLock();507        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });508        return { ok: true };509      }510      case "LOCK":511        vault.lock();512        if (isNativePlatform()) await clearInMemoryVault();513        return { ok: true };514      case "IS_UNLOCKED":515        return { ok: true, data: vault.isUnlocked() };516      case "GET_VAULT_STATUS":517        return { ok: true, unlocked: vault.isUnlocked() };518      case "HAS_VAULT":519        return { ok: true, data: await vault.hasVault() };520      case "GET_ENTRIES":521        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };522        return { ok: true, data: vault.getEntries() };523      case "ADD_ENTRY": {524        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };525        const payload = msg.payload;526        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {527          return { ok: false, error: "invalid_payload" };528        }529        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);530        return { ok: true, data: entry };531      }532      case "BATCH_ADD_ENTRIES": {533        const payload = msg.payload as { entries?: unknown } | null | undefined;534        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {535          return { ok: false, error: "invalid_payload" };536        }537        if (!Array.isArray(payload.entries)) {538          return { ok: false, error: "invalid_payload" };539        }540        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);541        return { ok: true, data: added };542      }543      case "RESTORE_ENTRIES": {544        const payload = msg.payload as545          | { entries?: unknown; mode?: unknown; settings?: unknown }546          | null547          | undefined;548        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {549          return { ok: false, error: "invalid_payload" };550        }551        if (!Array.isArray(payload.entries)) {552          return { ok: false, error: "invalid_payload" };553        }554        if (payload.mode !== "replace" && payload.mode !== "merge") {555          return { ok: false, error: "invalid_payload" };556        }557        const summary = await vault.restoreEntries(558          payload.entries as Parameters<typeof vault.restoreEntries>[0],559          payload.mode560        );561        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {562          await vault.updateSettings(payload.settings as vault.VaultSettings);563        }564        return { ok: true, data: summary };565      }566      case "CLEAR_VAULT_ENTRIES": {567        await vault.clearVaultEntries("REPLACE_ALL");568        return { ok: true };569      }570      case "GET_VAULT_HISTORY": {571        const snapshots = await vault.getVaultHistory();572        return { ok: true, data: snapshots };573      }574      case "RESTORE_VAULT_SNAPSHOT": {575        const { snapshotId } = msg.payload as { snapshotId: string };576        const result = await vault.restoreVaultSnapshot(snapshotId);577        if (!result.ok) return { ok: false, error: result.error };578        broadcastToContentScripts({ type: "VAULT_LOCKED" });579        return { ok: true };580      }581      case "COUNT_DUPLICATES": {582        return { ok: true, data: vault.countDuplicates() };583      }584      case "DEDUPLICATE_ENTRIES": {585        const removed = await vault.deduplicateEntries();586        return { ok: true, data: removed };587      }588      case "UPDATE_ENTRY": {589        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;590        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {591          return { ok: false, error: "invalid_payload" };592        }593        const { id, patch } = payload;594        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {595          return { ok: false, error: "invalid_payload" };596        }597        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);598        return { ok: true };599      }600      case "ADD_ADDITIONAL_URL": {601        const { id, url } = msg.payload as { id: string; url: string };602        const trimmed = typeof url === "string" ? url.trim() : "";603        if (!trimmed) return { ok: false, error: "url_required" };604        const existing = vault.getEntryById(id);605        if (!existing) return { ok: false, error: "entry_not_found" };606        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };607        const merged = [...(existing.additionalUrls ?? []), trimmed];608        await vault.updateEntry(id, { additionalUrls: merged });609        return { ok: true };610      }611      case "DELETE_ENTRY": {612        const { id } = msg.payload as { id: string };613        await vault.deleteEntry(id);614        return { ok: true };615      }616      case "GET_DELETED_ENTRIES":617        return { ok: true, data: vault.getDeletedEntries() };618      case "RESTORE_ENTRY": {619        const { id } = msg.payload as { id: string };620        await vault.restoreEntry(id);621        return { ok: true };622      }623      case "PURGE_ENTRY": {624        const { id } = msg.payload as { id: string };625        await vault.purgeEntry(id);626        return { ok: true };627      }628      case "PURGE_EXPIRED_TRASH": {629        const { retentionMs } = msg.payload as { retentionMs: number };630        const purged = await vault.purgeExpiredTrash(retentionMs);631        return { ok: true, data: purged };632      }633      case "SAVE_NOTE": {634        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };635        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };636        const now = Date.now();637        if (id) {638          const existing = vault.getEntryById(id);639          if (!existing) return { ok: false, error: "not_found" };640          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });641          return { ok: true, data: vault.getEntryById(id) };642        } else {643          const entry = await vault.addEntry({644            type: "note",645            title: title || "Untitled",646            notes: body,647            createdAt: now,648            modifiedAt: now,649          } as any);650          return { ok: true, data: entry };651        }652      }653      case "DELETE_NOTE": {654        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };655        const { id } = msg.payload as { id: string };656        await vault.deleteEntry(id);657        return { ok: true };658      }659      case "GET_NOTES": {660        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };661        const notes = vault.getEntries().filter(662          (e) => e.type === "note" && !e.deletedAt663        );664        return { ok: true, data: notes } as MessageResponse;665      }666      case "SEARCH_VAULT": {667        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };668        // AUD-002: shape-validate the payload before calling string methods.669        // A raw cast lets a malformed message crash the handler with TypeError.670        const { query } = (msg.payload ?? {}) as { query?: unknown };671        if (typeof query !== "string") {672          return { ok: false, error: "invalid_payload" };673        }674        const q = query.toLowerCase();675        const searchResults = vault.getEntries().filter(676          (e) =>677            !e.deletedAt &&678            (e.title.toLowerCase().includes(q) ||679              e.notes?.toLowerCase().includes(q) ||680              e.username?.toLowerCase().includes(q))681        );682        return { ok: true, data: searchResults } as MessageResponse;683      }684      case "PAIRING_COMPLETED": {685        const { deviceName, publicKeyHex, deviceIp } = (msg.payload ?? {}) as {686          deviceName?: string;687          publicKeyHex?: string;688          deviceIp?: string;689        };690        if (!publicKeyHex) return { ok: false, error: "publickeyhex_required" };691        // Only accept publicKeyHex values that just completed a real Noise NK692        // handshake (initiator or responder side). Without this gate, anyone693        // who can sendMessage to the background can pair an arbitrary key694        // (M13/SEC-005). Re-confirming an already-paired device is allowed695        // so legitimate update-IP retries still work.696        const alreadyPaired = (await getPairedDevices()).some(697          d => d.x25519PublicKey === publicKeyHex,698        );699        const verified = consumePendingPair(publicKeyHex);700        if (!verified && !alreadyPaired) {701          return { ok: false, error: "pairing_not_verified" };702        }703        const { setHasPaired: setPaired } = await import("./sync-storage");704        await setPaired();705        try {706          await addPairedDevice({707            deviceId: publicKeyHex,708            displayName: deviceName ?? "Unknown",709            x25519PublicKey: publicKeyHex,710            pairedAt: Date.now(),711            lastSeenAt: Date.now(),712            lastKnownIp: deviceIp,713          });714        } catch {715          // Already paired — update IP if provided716          if (deviceIp) {717            await updatePairedDevice(publicKeyHex, { lastKnownIp: deviceIp, lastSeenAt: Date.now() });718          }719        }720        return { ok: true };721      }722      case "AUTOFILL_QUERY": {723        if (!vault.isUnlocked()) {724          return { ok: false, error: "vault_locked" };725        }726        const { domain, includeAll, kind } = msg.payload as {727          domain: string;728          includeAll?: boolean;729          kind?: "login" | "card";730        };731        // kind="card": return saved cards as compact summaries for the732        // inline card silver platter. Cards are not domain-scoped — every733        // saved card is a candidate on every checkout page — so domain is734        // ignored when kind === "card".735        if (kind === "card") {736          const cards = vault.getEntries().filter((e) => e.type === "card");737          return {738            ok: true,739            data: cards.map((e) => ({740              id: e.id,741              title: e.cardNickname || e.title,742              cardholderName: e.cardholderName,743              last4: e.last4,744              expMonth: e.expMonth,745              expYear: e.expYear,746              network: e.network,747            })),748          };749        }750        // The inline selector fills username+password into a form. Passkey-751        // only entries have no password to fill; sign-in for those goes752        // through the WebAuthn path instead. Filter them out everywhere so753        // the user doesn't see four "GitHub" rows that mostly do nothing.754        // Notes and cards never belonged here either.755        const matches = (756          includeAll757            ? vault758                .getEntries()759                .filter((entry) => entry.type !== "note" && entry.type !== "card")760            : vault.queryDomain(domain)761        ).filter((entry) => !isPasskeyOnly(entry));762        return {763          ok: true,764          data: matches.map((e) =>765            includeAll766              ? {767                  id: e.id,768                  title: e.title,769                  hasPasskey: e.passkey !== undefined,770                }771              : {772                  id: e.id,773                  title: e.title,774                  username: e.username,775                  email: e.email,776                  url: e.url,777                  hasTotp: Boolean(e.totp),778                  hasPasskey: e.passkey !== undefined,779                }780          ),781        };782      }783      case "GET_ENTRY_FOR_FILL": {784        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };785        const { id } = msg.payload as { id: string };786        const entry = vault.getEntryById(id);787        if (!entry) return { ok: false, error: "entry_not_found" };788        // Passkey-only entries (passkey credential, no password) cannot be789        // filled into a form — sign-in goes through the WebAuthn path. A790        // login that ALSO has a passkey is still fillable for its password.791        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };792        // Strip the passkey credential from the response — content scripts793        // never need the private key, and there's no reason to expose the794        // public credential metadata over the boundary either.795        const { passkey: _strippedPasskey, ...safeEntry } = entry;796        return { ok: true, data: safeEntry };797      }798      case "COPY": {799        // AUD-002: shape-validate the payload before passing to the clipboard800        // helper. A raw cast lets a malformed message reach the clipboard API801        // with a non-string and throw.802        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {803          text?: unknown;804          label?: unknown;805          alreadyWritten?: unknown;806        };807        if (typeof text !== "string" || typeof label !== "string") {808          return { ok: false, error: "invalid_payload" };809        }810        await copyToClipboard(text, label, Boolean(alreadyWritten));811        return { ok: true };812      }813      case "CHECK_ALL_BREACHES": {814        const allEntries = vault.getEntries();815        const results: Record<string, number> = {};816        for (const entry of allEntries) {817          if (entry.type === "note") continue;818          if (!entry.password) continue;819          results[entry.id] = await vault.checkBreach(entry.password);820          // Small delay — be a good citizen to the HIBP API821          await new Promise((r) => setTimeout(r, 200));822        }823        // Persist any non-zero counts back to entries824        for (const [id, count] of Object.entries(results)) {825          const entry = vault.getEntryById(id);826          if (entry && (entry.breach ?? 0) !== count) {827            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });828          }829        }830        return { ok: true, data: results };831      }832      case "GET_SETTINGS":833        return { ok: true, data: await vault.ensureSettingsLoaded() };834      case "UPDATE_SETTINGS": {835        const patch = msg.payload;836        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {837          return { ok: false, error: "invalid_payload" };838        }839        await vault.updateSettings(patch as vault.VaultSettings);840        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {841          await setupAutoLock();842          if (vault.isUnlocked()) touchAutoLock();843        }844        return { ok: true };845      }846      case "GET_PENDING_PASSKEY":847        return { ok: true, data: await getPendingPasskeyRequest() };848      case "APPROVE_PASSKEY": {849        const { requestId } = msg.payload as { requestId: number };850        await resolvePendingPasskeyRequest(requestId, true);851        return { ok: true };852      }853      case "DENY_PASSKEY": {854        const { requestId } = msg.payload as { requestId: number };855        await resolvePendingPasskeyRequest(requestId, false);856        return { ok: true };857      }858      case "GET_PASSKEY_PROVIDER_STATE":859        return { ok: true, data: await getPasskeyProviderState() };860      case "SET_PASSKEY_PROVIDER_ENABLED": {861        const { enabled } = msg.payload as { enabled: boolean };862        // Disabling is always free; gating fires only when a free user is863        // trying to turn passkey interception on.864        if (enabled) {865          const gate = await requirePro("passkeys");866          if (!gate.allowed) return { ok: false, error: "pro_required" };867        }868        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };869      }870      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS871      // endpoint. Intentional product behavior — users configure their own872      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private873      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-874      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to875      // users that the entry title leaves the device when the canary fires.876      case "FIRE_CANARY_PING": {877        const { webhookUrl, entryTitle, trigger } = msg.payload as {878          webhookUrl: string;879          entryTitle: string;880          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";881        };882        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {883          return { ok: false, error: "invalid_webhook_url" };884        }885        const body = JSON.stringify({886          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",887          entry: entryTitle,888          trigger,889          timestamp: new Date().toISOString(),890          source: "peach-extension",891        });892        if (trigger === "test") {893          // Permitted outbound fetch: user-configured canary alert endpoint894          // (validated by isAllowedCanaryWebhookUrl above). This is the895          // only non-HIBP outbound call in the extension — see896          // Projects.md §3.7. Test pings are awaited so the UI can show897          // success/failure.898          try {899            const res = await fetch(webhookUrl, {900              method: "POST",901              headers: { "Content-Type": "application/json" },902              body,903            });904            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };905          } catch (err) {906            return { ok: false, error: err instanceof Error ? err.message : "network_error" };907          }908        }909        // Non-test triggers are fire-and-forget910        fetch(webhookUrl, {911          method: "POST",912          headers: { "Content-Type": "application/json" },913          body,914        }).catch(() => {});915        return { ok: true };916      }917      case "ACTIVATE_LICENSE": {918        const { key } = msg.payload as { key: string };919        const licenseInfo = await activateLicense(key);920        return { ok: true, data: licenseInfo };921      }922      case "GET_LICENSE": {923        const licenseInfo = await getLicenseInfo();924        return { ok: true, data: licenseInfo };925      }926      case "GET_LICENSE_KEY": {927        const key = await getLicenseKey();928        return { ok: true, data: key };929      }930      case "DEACTIVATE_LICENSE": {931        await deactivateLicense();932        return { ok: true };933      }934      case "SHOULD_PLAY_CELEBRATION": {935        const should = await shouldPlayCelebration();936        return { ok: true, data: should };937      }938      case "MARK_CELEBRATION_PLAYED": {939        await markCelebrationPlayed();940        return { ok: true };941      }942      case "GET_CODEX_VAULT_DATA": {943        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the944        // popup navigates to the License section without further coordination.945        const gate = await requirePro("codex");946        if (!gate.allowed) return { ok: false, error: "pro_required" };947        return await handleGetCodexVaultData();948      }949      case "ESTIMATE_CODEX_PAGES": {950        const gate = await requirePro("codex");951        if (!gate.allowed) return { ok: false, error: "pro_required" };952        return await handleEstimateCodexPages();953      }954      case "RESTORE_FROM_CODEX": {955        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still956        // be able to restore a vault that was printed by a Pro user.957        // DO NOT add a Pro gate here.958        const payload = msg.payload as CodexRestorePayload;959        return await handleRestoreFromCodex(payload);960      }961      case "OPEN_PRO_GATE": {962        // Content script requests: open popup and navigate to License section.963        const { feature } = (msg.payload ?? {}) as { feature?: string };964        if (chrome.storage.session) {965          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });966        }967        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }968        return { ok: true };969      }970      case "GET_IDENTITIES": {971        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };972        return { ok: true, data: vault.getIdentities() };973      }974      case "TOUCH_AUTO_LOCK": {975        // touchAutoLock() is already called by shouldRefreshAutoLock above;976        // this case just gives the popup a typed message to keep the session alive.977        return { ok: true };978      }979      case "GET_ADVANCED_HEALTH_REPORT": {980        const gate = await requirePro("advanced_health");981        if (!gate.allowed) return { ok: false, error: "pro_required" };982        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };983        const report = await buildAdvancedHealthReport(vault.getEntries());984        return { ok: true, data: report };985      }986      case "INITIATE_PASSWORD_CHANGE": {987        const gate = await requirePro("smart_password_change");988        if (!gate.allowed) return { ok: false, error: "pro_required" };989        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };990        const { id } = msg.payload as { id: string };991        const entry = vault.getEntryById(id);992        if (!entry) return { ok: false, error: "entry_not_found" };993        const url = resolveResetUrl(entry);994        if (!url) return { ok: false, error: "no_reset_url" };995        try {996          await chrome.tabs.create({ url });997          return { ok: true, data: { url } };998        } catch (err) {999          return {1000            ok: false,1001            error: err instanceof Error ? err.message : "failed_to_open_tab",1002          };1003        }1004      }1005      case "IS_DURESS_ENABLED": {1006        const enabled = await vault.isDuressEnabled();1007        return { ok: true, data: enabled };1008      }1009      case "SETUP_DURESS": {1010        const { duressPassword } = msg.payload as { duressPassword: string };1011        await vault.setupDuress(duressPassword);1012        return { ok: true };1013      }1014      case "DISABLE_DURESS": {1015        await vault.disableDuress();1016        return { ok: true };1017      }1018      case "VERIFY_MAIN_PASSWORD": {1019        const { password } = msg.payload as { password: string };1020        const ok = await vault.verifyMainPassword(password);1021        return { ok: true, data: ok };1022      }1023      case "CHANGE_PASSWORD": {1024        const { currentPassword, newPassword } = msg.payload as {1025          currentPassword: string;1026          newPassword: string;1027        };1028        const changed = await vault.changePassword(currentPassword, newPassword);1029        return changed1030          ? { ok: true }1031          : { ok: false, error: "incorrect_current_password" };1032      }1033      case "GET_SITE_PASSWORD_POLICY": {1034        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1035        if (!tab?.id) return { ok: true, data: null };1036        try {1037          const response = await chrome.tabs.sendMessage(tab.id, {1038            type: "GET_SITE_PASSWORD_POLICY",1039          });1040          return (response as MessageResponse) ?? { ok: true, data: null };1041        } catch {1042          return { ok: true, data: null };1043        }1044      }1045      case "GET_SYNC_STATE": {1046        const pairedDevices = await getPairedDevices();1047        const trustedNetworks = await getTrustedNetworks();1048        const tailscale = await isOnTailscale();1049        const pro = await isProUser();10501051        let status: SyncStatus = "offline";1052        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {1053          if (pairedDevices.length === 0) {1054            status = "no_peers";1055          } else {1056            status = "synced";1057          }1058        } else {1059          status = "not_trusted";1060        }10611062        const lastSyncRaw = await storageGet("peach_last_sync_at");1063        const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN;1064        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined;10651066        return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } };1067      }1068      case "GET_PAIRED_DEVICES": {1069        const devices = await getPairedDevices();1070        return { ok: true, data: { devices } };1071      }1072      case "GET_SYNC_STATUS": {1073        const lastSyncRaw = await storageGet("peach_last_sync_at");1074        const lastSyncParsed = lastSyncRaw ? parseInt(lastSyncRaw, 10) : NaN;1075        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : null;1076        const status: 'up_to_date' | 'never' = lastSyncAt ? 'up_to_date' : 'never';1077        return { ok: true, data: { status, lastSyncAt } };1078      }1079      case "ACCEPT_PAIRING": {1080        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.1081        return { ok: true };1082      }1083      case "REMOVE_PAIRED_DEVICE": {1084        const { deviceId } = msg.payload as { deviceId: string };1085        await removePairedDevice(deviceId);1086        return { ok: true };1087      }1088      case "REMOVE_TRUSTED_NETWORK": {1089        const payload = msg.payload as1090          | { ssid?: unknown; bssid?: unknown; isTailscale?: unknown }1091          | null1092          | undefined;1093        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {1094          return { ok: false, error: "invalid_payload" };1095        }1096        const { ssid, bssid, isTailscale } = payload as { ssid?: string; bssid?: string; isTailscale?: boolean };1097        const networks = await getTrustedNetworks();1098        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 1099          (isTailscale ? n.isTailscale : n.ssid === ssid) && 1100          (!bssid || n.bssid === bssid)1101        );1102        if (network) {1103          await removeTrustedNetwork(network.addedAt);1104        }1105        return { ok: true };1106      }1107      case "MARK_NETWORK_TRUSTED": {1108        const network = await getCurrentNetwork();1109        await addTrustedNetwork({1110          ssid: network.ssid,1111          bssid: network.bssid,1112          isTailscale: network.isTailscale,1113          addedAt: Date.now(),1114        });1115        return { ok: true };1116      }1117      case "GET_INCOMING_PAIRING_REQUEST": {1118        const request = await getIncomingPairingRequest();1119        return { ok: true, data: request };1120      }1121      case "RESPOND_INCOMING_PAIRING": {1122        const { accept } = msg.payload as { accept: boolean };1123        const request = await getIncomingPairingRequest();1124        if (!request) return { ok: false, error: "no_pending_request" };1125        if (Date.now() > request.expiresAt) {1126          await clearIncomingPairingRequest();1127          return { ok: false, error: "expired" };1128        }1129        await clearIncomingPairingRequest();1130        if (accept) {1131          await addPairedDevice({1132            deviceId: request.publicKeyHex,1133            displayName: request.deviceName,1134            x25519PublicKey: request.publicKeyHex,1135            pairedAt: Date.now(),1136            lastSeenAt: Date.now(),1137          });1138        }1139        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };1140      }1141      case "START_PAIRING_SERVER": {1142        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.1143        const token = generateSixDigitToken();1144        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;1145        await setActivePairingToken({ token, expiresAt });1146        // Fire-and-forget subnet scan — finds the phone after it scans the QR1147        // and calls SCAN_PAIRING_QR to register the token with SyncPlugin.1148        if (!isNativePlatform()) {1149          void runPairingSubnetScan(token);1150        }1151        return { ok: true, data: { token, expiresAt } };1152      }1153      case "STOP_PAIRING_SERVER": {1154        try {1155          await setActivePairingToken(null);1156        } catch { /* best-effort */ }1157        return { ok: true };1158      }1159      case "GET_RECENT_PAIRING": {1160        const recent = await consumeRecentPairing();1161        return { ok: true, data: recent };1162      }1163      case "DEBUG_INJECT_INCOMING_PAIRING": {1164        // M14/SEC-007: blocked in production builds. The handler exists for1165        // Phase 7 banner UX rehearsal without a live native host; shipping1166        // it in production lets any background-message sender inject a1167        // synthetic pairing prompt. Allowed in 'development' and 'test'1168        // modes; vite sets MODE='production' for release builds.1169        if (import.meta.env.MODE === "production") {1170          return { ok: false, error: "not_available" };1171        }1172        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {1173          deviceName?: string;1174          publicKeyHex?: string;1175        };1176        if (!deviceName || !publicKeyHex) {1177          return { ok: false, error: "missing_payload" };1178        }1179        const now = Date.now();1180        await setIncomingPairingRequest({1181          deviceName,1182          publicKeyHex,1183          receivedAt: now,1184          expiresAt: now + 60_000,1185        });1186        return { ok: true };1187      }1188      case "RESET_SYNC_IDENTITY": {1189        const gate = await requirePro("sync");1190        if (!gate.allowed) return { ok: false, error: "pro_required" };1191        const devices = await getPairedDevices();1192        for (const device of devices) {1193          await removePairedDevice(device.deviceId);1194        }1195        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };1196      }1197      case "RECORD_MANUAL_SUMMON": {1198        const { domain } = msg.payload as { domain: string };1199        const settings = vault.getSettings();1200        const existing = settings.manualSummonDomains?.[domain];1201        const now = Date.now();1202        await vault.updateSettings({1203          manualSummonDomains: {1204            ...settings.manualSummonDomains,1205            [domain]: {1206              firstSummonedAt: existing?.firstSummonedAt ?? now,1207              summonCount: (existing?.summonCount ?? 0) + 1,1208              lastSummonedAt: now,1209            },1210          },1211        });1212        return { ok: true };1213      }1214      case "DECLINE_CARD_SAVE": {1215        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1216        await vault.declineCardSaveOffer(last4, expMonth, expYear);1217        return { ok: true };1218      }1219      case "IS_CARD_DECLINED": {1220        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1221        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1222        return { ok: true, data: declined };1223      }1224      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1225        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1226          rpId?: string;1227          rpName?: string;1228          userName?: string;1229          userDisplayName?: string;1230        };1231        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1232        return await initiateFirefoxPasskeyCreate({1233          rpId,1234          rpName: rpName ?? rpId,1235          userName,1236          userDisplayName,1237        });1238      }12391240      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1241        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1242        if (!payload) return { ok: false, error: "missing_payload" };1243        return await completeFirefoxPasskeyCreate(payload);1244      }12451246      case "PASSKEY_OFFER_DECLINE": {1247        const { domain } = (msg.payload ?? {}) as { domain?: string };1248        if (!domain) return { ok: false, error: "domain_required" };1249        await recordPasskeyOfferDecline(domain);1250        return { ok: true };1251      }12521253      case "GET_PASSKEY_OFFER_DECLINED": {1254        const { domain } = (msg.payload ?? {}) as { domain?: string };1255        if (!domain) return { ok: false, error: "domain_required" };1256        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1257      }12581259      case "PASSKEY_HAS_CREDENTIALS": {1260        const payload = msg.payload as {1261          rpId?: string;1262          allowCredentials?: Array<{ id: string; type?: string }>;1263        } | undefined;1264        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1265        return await handlePasskeyHasCredentials({1266          rpId: payload.rpId,1267          allowCredentials: payload.allowCredentials ?? [],1268        });1269      }12701271      case "PASSKEY_CREATE": {1272        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1273        if (!payload?.rpId || !payload?.userName) {1274          return { ok: false, error: "rpid_and_username_required" };1275        }1276        return await handleFirefoxPasskeyCreate(payload);1277      }12781279      case "PASSKEY_GET": {1280        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1281        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1282        return await handleFirefoxPasskeyGet(payload);1283      }12841285      case "PASSKEY_AUTH_RESPONSE": {1286        const { requestId, approved } = (msg.payload ?? {}) as {1287          requestId?: string | number;1288          approved?: boolean;1289        };1290        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1291          return { ok: false, error: 'requestId and approved required' };1292        }1293        await resolvePendingPasskeyRequest(Number(requestId), approved);1294        return { ok: true };1295      }12961297      case "GET_PASSKEY_FOR_DOMAIN": {1298        const { domain } = (msg.payload ?? {}) as { domain?: string };1299        if (!domain) return { ok: false, error: "domain_required" };1300        if (!vault.isUnlocked()) return { ok: true, data: null };1301        const match = vault1302          .getEntries()1303          .find((entry) => entry.passkey?.rpId === domain);1304        if (!match || !match.passkey) return { ok: true, data: null };1305        // Slim shape — only the fields State 11 needs. Never expose private1306        // key material, even though this is locked behind isUnlocked.1307        return {1308          ok: true,1309          data: {1310            rpId: match.passkey.rpId,1311            userName: match.passkey.userName,1312            browser: match.passkey.browser,1313          },1314        };1315      }13161317      case "DESTROY_VAULT": {1318        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1319        // storage.local.clear() wipes every Peach key (slots, settings, license,1320        // onboarded flag, history, sync state, declined cards, recall, etc.);1321        // session.clear() wipes pending passkey requests + pro-notice queues.1322        // Caller (Panic.tsx) handles UI navigation back to onboarding.1323        vault.lock();1324        await storageClear();1325        await vault.clearVaultHistory();1326        if (chrome.storage.session) {1327          await chrome.storage.session.clear();1328        }1329        return { ok: true };1330      }13311332      case "SUBMIT_FEEDBACK": {1333        const { category, message, version, browser } = msg.payload as {1334          category: string;1335          message: string;1336          version: string;1337          browser: string;1338        };1339        if (!message.trim()) return { ok: false, error: "message_empty" };1340        if (!FEEDBACK_ENDPOINT) return { ok: true };1341        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1342          return { ok: false, error: "invalid_feedback_endpoint" };1343        }1344        try {1345          const res = await fetch(FEEDBACK_ENDPOINT, {1346            method: "POST",1347            headers: { "Content-Type": "application/json" },1348            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1349          });1350          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1351        } catch (err) {1352          return { ok: false, error: err instanceof Error ? err.message : "network_error" };1353        }1354      }1355      case "TRIGGER_SYNC": {1356        const gate = await requirePro("sync");1357        if (!gate.allowed) return { ok: false, error: "pro_required" };1358        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };13591360        if (isNativePlatform()) {1361          // Phone is the server — ensure it's listening for desktop connections.1362          syncBridge()?.ensureServerRunning?.();1363          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };1364        }13651366        // Desktop: iterate all paired devices and sync with each.1367        const paired = await getPairedDevices();1368        if (!paired.length) return { ok: true, data: { syncedCount: 0, reason: "no_paired_devices" } };13691370        const subnet = await getLocalSubnet();1371        const results: Array<{ device: string } & SyncResult> = [];13721373        for (const device of paired) {1374          if (!device.x25519PublicKey) continue;13751376          let result: SyncResult;13771378          // Fast path — use last known IP1379          if (device.lastKnownIp) {1380            result = await doVaultSync(device.lastKnownIp, device.x25519PublicKey);1381          } else {1382            result = { status: 'errored', applied: false, error: 'no_ip' };1383          }13841385          // Discovery path — scan if fast path failed1386          if (result.status === 'errored' && subnet) {1387            const newIp = await discoverDevice(subnet, device.x25519PublicKey);1388            if (newIp) {1389              await updatePairedDevice(device.x25519PublicKey, { lastKnownIp: newIp });1390              result = await doVaultSync(newIp, device.x25519PublicKey);1391            }1392          }13931394          if (result.status === 'completed') {1395            await updatePairedDevice(device.x25519PublicKey, {1396              lastSeenAt: Date.now(),1397              lastSyncAt: Date.now(),1398            });1399          }14001401          results.push({ device: device.displayName, ...result });1402        }14031404        const syncedCount = results.filter(r => r.status === 'completed').length;1405        if (syncedCount > 0) {1406          await chrome.storage.local.set({ peach_last_sync_at: String(Date.now()) });1407        }1408        return { ok: true, data: { syncedCount, results } };1409      }1410      // Android-only: biometric unlock with pre-derived key.1411      case "UNLOCK_WITH_KEY": {1412        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1413        if (!isNativePlatform()) {1414          return { ok: false, error: "desktop_only_uses_password" };1415        }1416        try {1417          const result = await vault.unlockWithKey(masterKeyHex);1418          if (result.ok) {1419            onVaultUnlocked();1420            await publishInMemoryVault(result.entries);1421          }1422          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1423        } catch {1424          return { ok: false, error: "invalid_key" };1425        }1426      }1427      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1428      case "GET_DERIVED_KEY": {1429        if (!isNativePlatform()) {1430          return { ok: false, error: "android_only" };1431        }1432        if (!vault.isUnlocked()) {1433          return { ok: false, error: "vault_locked" };1434        }1435        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1436      }1437      // Android: scanned a QR containing a desktop pairing token.1438      case "SCAN_PAIRING_QR": {1439        if (!isNativePlatform()) {1440          return { ok: false, error: "android_only" };1441        }1442        const { token } = msg.payload as { token: string };1443        syncBridge()?.startPairingSession?.({ token });1444        return { ok: true };1445      }1446      // Android: desktop opened a sync connection to the phone's WS server.1447      // Run the responder side of the vault exchange.1448      case "SYNC_SESSION_STARTED": {1449        if (!isNativePlatform()) return { ok: false };1450        if (!vault.isUnlocked()) {1451          return { ok: false, error: "vault_locked" };1452        }1453        const { connectionId } = (msg.payload ?? {}) as { connectionId?: string };1454        if (!connectionId) return { ok: false, error: "missing_connection_id" };14551456        const transport = createAndroidResponderTransport(connectionId);14571458        // Authenticate the initiator before exchanging any vault data. The1459        // native side has already completed the Noise NK handshake; auth1460        // frames here ride the Noise transport (native encrypts/decrypts).1461        const identity = await vault.getSyncIdentity();1462        try {1463          // CAUTION: noiseSessionStub is a structural placeholder — the real1464          // Noise NK handshake runs natively, so JS never holds the session1465          // object. performResponderAuth currently `void`s this argument,1466          // which is why identity-passthrough encrypt/decrypt and a zero1467          // handshake hash are safe. If performResponderAuth is ever updated1468          // to actually use this argument, this auth path will silently break1469          // (no type error). Revisit this stub if that helper changes.1470          const noiseSessionStub = {1471            encrypt: (b: Uint8Array) => b,1472            decrypt: (b: Uint8Array) => b,1473            handshakeHash: new Uint8Array(32),1474          };1475          const { initiatorPublicKey } = await performResponderAuth(1476            noiseSessionStub,1477            identity.privateKeyBytes,1478            identity.publicKeyBytes,1479            transport.send,1480            transport.receive,1481          );1482          const initiatorHex = noiseBytesToHex(initiatorPublicKey);1483          const paired = await getPairedDevices();1484          if (!paired.some(d => d.x25519PublicKey === initiatorHex)) {1485            await transport.close();1486            return { ok: false, error: "sync_rejected_unpaired_initiator" };1487          }1488          // Initiator just proved control of the matching static key; mark it1489          // as a verified handshake so a follow-up PAIRING_COMPLETED message1490          // can be trusted (M13/SEC-005).1491          markPairingHandshakeVerified(initiatorHex);1492        } catch (err) {1493          await transport.close();1494          return { ok: false, error: `sync_auth_failed: ${String(err)}` };1495        }14961497        const result = await runBlobSyncSession('responder', transport, buildSyncDeps());1498        if (result.applied) {1499          await publishInMemoryVault(vault.getEntries());1500        }1501        return { ok: true, data: result };1502      }1503      // Android: returns the phone's WiFi IP address.1504      case "GET_LOCAL_IP": {1505        if (!isNativePlatform()) {1506          return { ok: false, error: "android_only" };1507        }1508        const { ip } = (await syncBridge()?.getLocalIp?.()) ?? { ip: "" };1509        return { ok: true, data: { ip } };1510      }1511      case "GET_IDENTITY_SUGGESTIONS": {1512        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1513        const entries = vault.getEntries();1514        const suggestions = buildIdentitySuggestions(entries);1515        return { ok: true, data: { suggestions } };1516      }1517      case "POPULATE_INLINE_VAULT": {1518        if (!isNativePlatform()) return { ok: false };1519        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1520        const entries = vault.getEntries();1521        await publishInMemoryVault(entries);1522        return { ok: true };1523      }1524      case "ML_INIT":1525        return { ok: true };15261527      case "ML_PREDICT_BATCH": {1528        // AUD-002: shape-validate before forwarding to the ML helper.1529        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1530        if (!Array.isArray(featuresArray)) {1531          return { ok: false, error: "invalid_payload" };1532        }1533        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1534      }15351536      default:1537        return { ok: false, error: "unknown_message_type" };1538    }1539  } catch (err) {1540    return {1541      ok: false,1542      error: err instanceof Error ? err.message : "operation_failed",1543    };1544  }1545}15461547// --- Mobile platform helpers ---15481549// Android: populates the in-memory vault used by PeachAutofillService.1550async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1551  const plugin = nativePlugin<{1552    setEntries?: (args: {1553      entries: Array<{1554        id: string;1555        title: string;1556        username: string;1557        email: string;1558        password: string;1559        url: string;1560        totp: string;1561        additionalUrls: string[];1562      }>;1563    }) => Promise<void>;1564  }>("InMemoryVaultPlugin");1565  if (!plugin?.setEntries) return;1566  await plugin.setEntries({1567    entries: entries.map((e) => ({1568      id: e.id,1569      title: e.title ?? "",1570      username: e.username ?? "",1571      email: (e as VaultEntry & { email?: string }).email ?? "",1572      password: e.password ?? "",1573      url: e.url ?? "",1574      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1575      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1576    })),1577  });1578}15791580// Android: clear the autofill in-memory store on lock.1581async function clearInMemoryVault(): Promise<void> {1582  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1583  if (!plugin?.clearEntries) return;1584  await plugin.clearEntries();1585}15861587interface SyncBridge {1588  ensureServerRunning?: () => void;1589  startPairingSession?: (args: { token: string }) => void;1590  getLocalIp?: () => Promise<{ ip: string }>;1591  sendToConnection?: (args: { connectionId: string; data: string }) => Promise<void>;1592  addListener?: (event: string, handler: (data: Record<string, string>) => void) => void;1593}15941595// Resolve the Capacitor SyncPlugin at call time — module-load resolution1596// races with Capacitor's plugin registration on the Android WebView.1597function syncBridge(): SyncBridge | null {1598  return nativePlugin<SyncBridge>("SyncPlugin");1599}16001601// Build a SyncTransport for the Android responder path — the phone's WS server1602// already has an open connection from the desktop. We send back via1603// SyncPlugin.sendToConnection and receive via the peach:sync-frame queue.1604const androidSyncFrameQueues = new Map<string, Array<(frame: string) => void>>();16051606export function deliverAndroidSyncFrame(connectionId: string, frame: string): void {1607  const queue = androidSyncFrameQueues.get(connectionId);1608  if (queue?.length) queue.shift()!(frame);1609}16101611function createAndroidResponderTransport(connectionId: string) {1612  const pendingReceivers: Array<(frame: string) => void> = [];1613  androidSyncFrameQueues.set(connectionId, pendingReceivers);16141615  return {1616    send: async (data: Uint8Array) => {1617      await syncBridge()?.sendToConnection?.({ connectionId, data: bytesToBase64(data) });1618    },1619    receive: (): Promise<Uint8Array> => new Promise((res) => {1620      pendingReceivers.push((frame) => {1621        res(frame ? base64ToBytes(frame) : new Uint8Array(0));1622      });1623    }),1624    close: async () => {1625      androidSyncFrameQueues.delete(connectionId);1626    },1627  };1628}16291630// Returns username use-counts from the vault, sorted by frequency. Each row1631// also carries the entry's email so the popup can suggest the email/username1632// pair the user has actually used together.1633function buildIdentitySuggestions(1634  entries: VaultEntry[],1635): Array<{ email: string; username: string; count: number }> {1636  const usernameCounts = new Map<string, number>();1637  const usernameEmail = new Map<string, string>();1638  for (const entry of entries) {1639    const username = entry.username ?? "";1640    const email = (entry as VaultEntry & { email?: string }).email ?? "";1641    if (!username && !email) continue;1642    const key = username || email;1643    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1644    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1645  }1646  return Array.from(usernameCounts.entries())1647    .sort((a, b) => b[1] - a[1])1648    .map(([username, count]) => ({1649      email: usernameEmail.get(username) ?? "",1650      username,1651      count,1652    }));1653}16541655/** Notify all content scripts that the vault just became available. */1656function broadcastToContentScripts(message: { type: string }): void {1657  if (!chrome.tabs?.query) return;1658  chrome.tabs.query({}, (tabs) => {1659    for (const tab of tabs) {1660      if (tab.id !== undefined) {1661        chrome.tabs.sendMessage(tab.id, message).catch(() => {1662          // Tab may not have a content script — silently ignore1663        });1664      }1665    }1666  });1667}16681669function shouldRefreshAutoLock(type: MessageType): boolean {1670  return (1671    type !== "HAS_VAULT" &&1672    type !== "IS_UNLOCKED" &&1673    type !== "GET_VAULT_STATUS" &&1674    type !== "LOCK" &&1675    type !== "UPDATE_SETTINGS" &&1676    type !== "GET_PENDING_PASSKEY" &&1677    type !== "GET_PASSKEY_PROVIDER_STATE" &&1678    type !== "DECLINE_CARD_SAVE" &&1679    type !== "IS_CARD_DECLINED" &&1680    type !== "SUBMIT_FEEDBACK"1681  );1682}16831684function isAllowedCanaryWebhookUrl(value: string): boolean {1685  try {1686    const url = new URL(value);1687    if (url.protocol !== "https:") return false;16881689    const hostname = url.hostname.toLowerCase();1690    if (1691      hostname === "localhost" ||1692      hostname.endsWith(".localhost") ||1693      isPrivateIpv4(hostname) ||1694      isPrivateIpv6(hostname)1695    ) {1696      return false;1697    }16981699    return true;1700  } catch {1701    return false;1702  }1703}17041705function isPrivateIpv4(hostname: string): boolean {1706  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1707    return true;1708  }17091710  const octets = hostname.split(".").map((part) => Number(part));1711  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1712    return false;1713  }17141715  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1716}17171718function isPrivateIpv6(hostname: string): boolean {1719  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1720  return (1721    normalized === "::1" ||1722    normalized.startsWith("fc") ||1723    normalized.startsWith("fd") ||1724    normalized.startsWith("fe80:")1725  );1726}