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: paired.flatMap(d =>193          d.x25519PublicKey194            ? [{195                publicKeyHex: d.x25519PublicKey,196                deviceName: d.displayName ?? "",197                pairedAt: d.pairedAt,198              }]199            : [],200        ),201      };202    },203    applyIncomingVault: async (blob, ts, license, devices) => {204      const applied = await vault.applyIncomingVault(blob, ts, license);205      if (devices?.length) await mergeDeviceRegistry(devices);206      if (applied) {207        const reloaded = await vault.reloadEntriesAfterSync();208        if (!reloaded) {209          // The remote vault was encrypted under a different key (the remote210          // changed password). Our in-memory entries are now stale and cannot211          // be re-encrypted without overwriting the just-applied blob. Lock212          // to force a re-unlock with the new password (H3/COR-005).213          vault.lock();214          chrome.runtime215            .sendMessage({ type: "VAULT_RELOCK_AFTER_SYNC" })216            .catch(() => {});217        }218      }219      return applied;220    },221  };222}223224async function doVaultSync(ip: string, publicKeyHex: string): Promise<SyncResult> {225  // Defensive: refuse to drive a sync to a key not in the paired-devices226  // list. The WebSocket transport already authenticates the peer via Noise227  // NK + the initiator auth proof (H1), but pinning the key to the paired228  // set here makes "talk to anyone matching this static key" the only path229  // to vault application — there is no orphan-key window between pair and230  // sync (M11/COR-014).231  const paired = await getPairedDevices();232  if (!paired.some(d => d.x25519PublicKey === publicKeyHex)) {233    return { status: 'errored', applied: false, error: 'remote_not_paired' };234  }235  try {236    const identity = await vault.getSyncIdentity();237    const transport = await createWebSocketSyncTransport(238      `ws://${ip}:44100`,239      publicKeyHex,240      identity.privateKeyBytes,241      identity.publicKeyBytes,242    );243    const result = await runBlobSyncSession('initiator', transport, buildSyncDeps());244    // Reaching this point means createWebSocketSyncTransport completed both245    // the Noise NK handshake and the initiator-auth proof — the remote246    // proved possession of the matching static key (M13/SEC-005).247    if (result.status === 'completed') {248      markPairingHandshakeVerified(publicKeyHex);249    }250    return result;251  } catch (err) {252    return { status: 'errored', applied: false, error: String(err) };253  }254}255256async function mergeDeviceRegistry(incoming: SyncableDevice[]): Promise<void> {257  const existing = await getPairedDevices();258  const existingKeys = new Set(existing.map(d => d.x25519PublicKey));259  for (const device of incoming) {260    if (!existingKeys.has(device.publicKeyHex)) {261      await addPairedDevice({262        deviceId: device.publicKeyHex,263        displayName: device.deviceName,264        x25519PublicKey: device.publicKeyHex,265        pairedAt: device.pairedAt,266        lastSeenAt: 0,267        lastKnownIp: '',268      }).catch(() => {});269    }270  }271}272273// Background pairing scan — runs after START_PAIRING_SERVER fires on desktop.274// Scans the local subnet for a phone that has accepted the pairing token,275// stores it, runs the initial vault exchange, then notifies the popup.276async function runPairingSubnetScan(token: string): Promise<void> {277  const subnet = await getLocalSubnet();278  if (!subnet) return;279280  const found = await scanForPairingPhone(subnet, token);281  if (!found) return;282283  const { ip, publicKeyHex } = found;284285  try {286    await addPairedDevice({287      deviceId: publicKeyHex,288      displayName: 'Peach',289      x25519PublicKey: publicKeyHex,290      pairedAt: Date.now(),291      lastSeenAt: Date.now(),292      lastKnownIp: ip,293    });294  } catch {295    // Already paired — update IP296    await updatePairedDevice(publicKeyHex, { lastKnownIp: ip, lastSeenAt: Date.now() });297  }298299  // Immediate vault exchange — the free one-time transfer300  await doVaultSync(ip, publicKeyHex);301302  chrome.runtime.sendMessage({303    type: 'PAIRING_COMPLETED',304    payload: { deviceName: 'Peach', publicKeyHex, deviceIp: ip },305  }).catch(() => {});306}307308export function setupMessageHandler(): void {309  chrome.runtime.onMessage.addListener(310    (msg: unknown, sender, sendResponse) => {311      if (!isMessage(msg)) {312        sendResponse({ ok: false, error: "invalid_message" });313        return true;314      }315      handleMessage(msg, sender)316        .then(sendResponse)317        .catch((err) =>318          sendResponse({319            ok: false,320            error: err instanceof Error ? err.message : String(err),321          })322        );323      return true;324    }325  );326327  // Android: the chrome shim queues sendMessage calls until this handler is328  // registered. Without this hookup, every message hangs on Capacitor builds.329  // eslint-disable-next-line @typescript-eslint/no-explicit-any330  const reg = (globalThis as any).__peachRegisterMessageHandler;331  if (typeof reg === "function") {332    reg(async (m: unknown) => {333      if (!isMessage(m)) return { ok: false, error: "invalid_message" };334      try {335        return await handleMessage(m);336      } catch (err) {337        return {338          ok: false,339          error: err instanceof Error ? err.message : String(err),340        };341      }342    });343  }344345  // Android: subscribe to SyncPlugin events.346  if (isNativePlatform()) {347    const syncPlug = nativePlugin<{348      addListener: (349        event: string,350        handler: (data: Record<string, string>) => void351      ) => void;352    }>("SyncPlugin");353354    // Pairing probe answered — store the paired device (desktop, no IP needed355    // since the desktop never acts as a WS server).356    syncPlug?.addListener?.("peach:pair-probe-answered", (data) => {357      const deviceName = data.deviceName ?? "Peach";358      const publicKeyHex = data.publicKeyHex ?? "";359      // Native handled the pairing handshake — trust this entry into the360      // verified-handshake set (M13/SEC-005). The subsequent PAIRING_COMPLETED361      // message will consume it.362      if (publicKeyHex) markPairingHandshakeVerified(publicKeyHex);363      void (async () => {364        const { addPairedDevice, setHasPaired: setPaired } = await import("./sync-storage");365        await addPairedDevice({366          deviceId: publicKeyHex || (data.connectionId ?? "unknown"),367          displayName: deviceName,368          x25519PublicKey: publicKeyHex,369          pairedAt: Date.now(),370          lastSeenAt: Date.now(),371        }).catch(() => {});372        await setPaired();373        chrome.runtime.sendMessage({374          type: "PAIRING_COMPLETED",375          payload: { deviceName, publicKeyHex },376        }).catch(() => {});377      })();378    });379380    // Sync frame received — route to the waiting responder session.381    syncPlug?.addListener?.("peach:sync-frame", (data) => {382      const { connectionId, frame } = data;383      if (connectionId && frame) deliverAndroidSyncFrame(connectionId, frame);384    });385386    // Sync session started (SYNC_HELLO received by SyncPlugin) — dispatch as387    // a background message so SYNC_SESSION_STARTED handler runs the responder.388    syncPlug?.addListener?.("peach:sync-session-started", (data) => {389      const { connectionId } = data;390      if (!connectionId) return;391      void handleMessage({ type: "SYNC_SESSION_STARTED", payload: { connectionId } });392    });393  }394}395396function isMessage(m: unknown): m is Message {397  return typeof m === "object" && m !== null && "type" in m;398}399400export async function handleMessage(401  msg: Message,402  sender: Partial<chrome.runtime.MessageSender> = {}403): Promise<MessageResponse> {404  try {405    // Validate sender — only allow messages from our extension pages/scripts.406    // `sender.id` is undefined for messages originating from extension UI407    // (popup/options), which is legitimate; reject only when it is defined408    // and does not match our extension id.409    if (410      sender.id !== undefined &&411      sender.id !== chrome.runtime.id412    ) {413      return { ok: false, error: "invalid_sender" };414    }415416    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {417      touchAutoLock();418    }419420    switch (msg.type) {421      case "CREATE_VAULT": {422        const { password } = msg.payload as { password: string };423        await vault.createVault(password);424        await setupAutoLock();425        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });426        onVaultUnlocked();427        return { ok: true };428      }429      case "UNLOCK": {430        const { password } = msg.payload as { password: string };431        const ok = await vault.unlock(password);432        if (ok) {433          // KAT: verify the WebCrypto stack is healthy before the user relies on it.434          // Runs after unlock so latency is hidden behind the vault-load time.435          const kat = await runSelfTest();436          if (!kat.ok) {437            console.error("[Peach] Crypto self-test FAILED:", kat.error);438            await vault.lock();439            return { ok: false, error: "self_test_failed" };440          }441          await setupAutoLock();442          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });443          onVaultUnlocked();444          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());445          return { ok: true };446        }447        // Distinguish corruption from wrong password so the popup can offer448        // a history-restore path instead of falsely accusing the user of449        // mistyping (M7/COR-007).450        const failure = vault.consumeLastUnlockFailureReason();451        if (failure) {452          return {453            ok: false,454            error: "vault_corrupted",455            canRestoreFromHistory: true,456          } as MessageResponse;457        }458        return { ok: false };459      }460      case "VALIDATE_RECOVERY_WORDS": {461        const { words } = msg.payload as { words: string[] };462        const invalid = findInvalidWords(words);463        return { ok: true, data: { valid: invalid.length === 0, invalid } };464      }465      case "GET_RECOVERY_WORDS": {466        // Must be unlocked and have recovery set up (vault must be v2.12+).467        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };468        try {469          const words = await vault.getRecoveryWords();470          return { ok: true, data: words };471        } catch (e) {472          // pre-v2.12 vault that hasn't migrated473          return { ok: false, error: "recovery_not_setup" };474        }475      }476      case "RECOVER_WITH_WORDS": {477        // User has lost their password but has their 12 recovery words.478        // We: (1) validate the words, (2) re-encrypt vault with new password.479        const { words, newPassword } = msg.payload as {480          words: string[];481          newPassword: string;482        };483        const stored = await vault.loadSlotA();484        if (!stored) return { ok: false, error: "no_vault" };485        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {486          return { ok: false, error: "recovery_not_setup" };487        }488        // Unwrap the root key from the recovery escrow.489        try {490          await vault.unwrapRootKeyForRecovery(491            stored.recovery_wrapped_root_key,492            stored.recovery_nonce ?? "",493            stored.recovery_tag ?? "",494            stored.recovery_salt,495            words496          );497        } catch {498          return { ok: false, error: "invalid_recovery_words" };499        }500        // Re-key: derive fresh salt + key from new password.501        const newSalt = vault.generateSalt();502        const newKey = await vault.deriveKey(newPassword, newSalt);503        // Re-wrap root key under the new password's derived key so the same504        // recovery words continue to work after the password change.505        await vault.rewrapRootKeyForPassword(newKey, newSalt);506        // Re-encrypt vault entries with the new key.507        await vault.changePasswordWithNewKey(newSalt, newKey);508        await setupAutoLock();509        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });510        return { ok: true };511      }512      case "LOCK":513        vault.lock();514        if (isNativePlatform()) await clearInMemoryVault();515        return { ok: true };516      case "IS_UNLOCKED":517        return { ok: true, data: vault.isUnlocked() };518      case "GET_VAULT_STATUS":519        return { ok: true, unlocked: vault.isUnlocked() };520      case "HAS_VAULT":521        return { ok: true, data: await vault.hasVault() };522      case "GET_ENTRIES":523        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };524        return { ok: true, data: vault.getEntries() };525      case "ADD_ENTRY": {526        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };527        const payload = msg.payload;528        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {529          return { ok: false, error: "invalid_payload" };530        }531        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);532        return { ok: true, data: entry };533      }534      case "BATCH_ADD_ENTRIES": {535        const payload = msg.payload as { entries?: unknown } | null | undefined;536        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {537          return { ok: false, error: "invalid_payload" };538        }539        if (!Array.isArray(payload.entries)) {540          return { ok: false, error: "invalid_payload" };541        }542        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);543        return { ok: true, data: added };544      }545      case "RESTORE_ENTRIES": {546        const payload = msg.payload as547          | { entries?: unknown; mode?: unknown; settings?: unknown }548          | null549          | undefined;550        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {551          return { ok: false, error: "invalid_payload" };552        }553        if (!Array.isArray(payload.entries)) {554          return { ok: false, error: "invalid_payload" };555        }556        if (payload.mode !== "replace" && payload.mode !== "merge") {557          return { ok: false, error: "invalid_payload" };558        }559        const summary = await vault.restoreEntries(560          payload.entries as Parameters<typeof vault.restoreEntries>[0],561          payload.mode562        );563        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {564          await vault.updateSettings(payload.settings as vault.VaultSettings);565        }566        return { ok: true, data: summary };567      }568      case "CLEAR_VAULT_ENTRIES": {569        await vault.clearVaultEntries("REPLACE_ALL");570        return { ok: true };571      }572      case "GET_VAULT_HISTORY": {573        const snapshots = await vault.getVaultHistory();574        return { ok: true, data: snapshots };575      }576      case "RESTORE_VAULT_SNAPSHOT": {577        const { snapshotId } = msg.payload as { snapshotId: string };578        const result = await vault.restoreVaultSnapshot(snapshotId);579        if (!result.ok) return { ok: false, error: result.error };580        broadcastToContentScripts({ type: "VAULT_LOCKED" });581        return { ok: true };582      }583      case "COUNT_DUPLICATES": {584        return { ok: true, data: vault.countDuplicates() };585      }586      case "DEDUPLICATE_ENTRIES": {587        const removed = await vault.deduplicateEntries();588        return { ok: true, data: removed };589      }590      case "UPDATE_ENTRY": {591        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;592        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {593          return { ok: false, error: "invalid_payload" };594        }595        const { id, patch } = payload;596        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {597          return { ok: false, error: "invalid_payload" };598        }599        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);600        return { ok: true };601      }602      case "ADD_ADDITIONAL_URL": {603        const { id, url } = msg.payload as { id: string; url: string };604        const trimmed = typeof url === "string" ? url.trim() : "";605        if (!trimmed) return { ok: false, error: "url_required" };606        const existing = vault.getEntryById(id);607        if (!existing) return { ok: false, error: "entry_not_found" };608        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };609        const merged = [...(existing.additionalUrls ?? []), trimmed];610        await vault.updateEntry(id, { additionalUrls: merged });611        return { ok: true };612      }613      case "DELETE_ENTRY": {614        const { id } = msg.payload as { id: string };615        await vault.deleteEntry(id);616        return { ok: true };617      }618      case "GET_DELETED_ENTRIES":619        return { ok: true, data: vault.getDeletedEntries() };620      case "RESTORE_ENTRY": {621        const { id } = msg.payload as { id: string };622        await vault.restoreEntry(id);623        return { ok: true };624      }625      case "PURGE_ENTRY": {626        const { id } = msg.payload as { id: string };627        await vault.purgeEntry(id);628        return { ok: true };629      }630      case "PURGE_EXPIRED_TRASH": {631        const { retentionMs } = msg.payload as { retentionMs: number };632        const purged = await vault.purgeExpiredTrash(retentionMs);633        return { ok: true, data: purged };634      }635      case "SAVE_NOTE": {636        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };637        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };638        const now = Date.now();639        if (id) {640          const existing = vault.getEntryById(id);641          if (!existing) return { ok: false, error: "not_found" };642          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });643          return { ok: true, data: vault.getEntryById(id) };644        } else {645          const entry = await vault.addEntry({646            type: "note",647            title: title || "Untitled",648            notes: body,649            createdAt: now,650            modifiedAt: now,651          } as any);652          return { ok: true, data: entry };653        }654      }655      case "DELETE_NOTE": {656        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };657        const { id } = msg.payload as { id: string };658        await vault.deleteEntry(id);659        return { ok: true };660      }661      case "GET_NOTES": {662        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };663        const notes = vault.getEntries().filter(664          (e) => e.type === "note" && !e.deletedAt665        );666        return { ok: true, data: notes } as MessageResponse;667      }668      case "SEARCH_VAULT": {669        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };670        // AUD-002: shape-validate the payload before calling string methods.671        // A raw cast lets a malformed message crash the handler with TypeError.672        const { query } = (msg.payload ?? {}) as { query?: unknown };673        if (typeof query !== "string") {674          return { ok: false, error: "invalid_payload" };675        }676        const q = query.toLowerCase();677        const searchResults = vault.getEntries().filter(678          (e) =>679            !e.deletedAt &&680            (e.title.toLowerCase().includes(q) ||681              e.notes?.toLowerCase().includes(q) ||682              e.username?.toLowerCase().includes(q))683        );684        return { ok: true, data: searchResults } as MessageResponse;685      }686      case "PAIRING_COMPLETED": {687        const { deviceName, publicKeyHex, deviceIp } = (msg.payload ?? {}) as {688          deviceName?: string;689          publicKeyHex?: string;690          deviceIp?: string;691        };692        if (!publicKeyHex) return { ok: false, error: "publickeyhex_required" };693        // Only accept publicKeyHex values that just completed a real Noise NK694        // handshake (initiator or responder side). Without this gate, anyone695        // who can sendMessage to the background can pair an arbitrary key696        // (M13/SEC-005). Re-confirming an already-paired device is allowed697        // so legitimate update-IP retries still work.698        const alreadyPaired = (await getPairedDevices()).some(699          d => d.x25519PublicKey === publicKeyHex,700        );701        const verified = consumePendingPair(publicKeyHex);702        if (!verified && !alreadyPaired) {703          return { ok: false, error: "pairing_not_verified" };704        }705        const { setHasPaired: setPaired } = await import("./sync-storage");706        await setPaired();707        try {708          await addPairedDevice({709            deviceId: publicKeyHex,710            displayName: deviceName ?? "Unknown",711            x25519PublicKey: publicKeyHex,712            pairedAt: Date.now(),713            lastSeenAt: Date.now(),714            lastKnownIp: deviceIp,715          });716        } catch {717          // Already paired — update IP if provided718          if (deviceIp) {719            await updatePairedDevice(publicKeyHex, { lastKnownIp: deviceIp, lastSeenAt: Date.now() });720          }721        }722        return { ok: true };723      }724      case "AUTOFILL_QUERY": {725        if (!vault.isUnlocked()) {726          return { ok: false, error: "vault_locked" };727        }728        const { domain, includeAll, kind } = msg.payload as {729          domain: string;730          includeAll?: boolean;731          kind?: "login" | "card";732        };733        // kind="card": return saved cards as compact summaries for the734        // inline card silver platter. Cards are not domain-scoped — every735        // saved card is a candidate on every checkout page — so domain is736        // ignored when kind === "card".737        if (kind === "card") {738          const cards = vault.getEntries().filter((e) => e.type === "card");739          return {740            ok: true,741            data: cards.map((e) => ({742              id: e.id,743              title: e.cardNickname || e.title,744              cardholderName: e.cardholderName,745              last4: e.last4,746              expMonth: e.expMonth,747              expYear: e.expYear,748              network: e.network,749            })),750          };751        }752        // The inline selector fills username+password into a form. Passkey-753        // only entries have no password to fill; sign-in for those goes754        // through the WebAuthn path instead. Filter them out everywhere so755        // the user doesn't see four "GitHub" rows that mostly do nothing.756        // Notes and cards never belonged here either.757        const matches = (758          includeAll759            ? vault760                .getEntries()761                .filter((entry) => entry.type !== "note" && entry.type !== "card")762            : vault.queryDomain(domain)763        ).filter((entry) => !isPasskeyOnly(entry));764        return {765          ok: true,766          data: matches.map((e) =>767            includeAll768              ? {769                  id: e.id,770                  title: e.title,771                  hasPasskey: e.passkey !== undefined,772                }773              : {774                  id: e.id,775                  title: e.title,776                  username: e.username,777                  email: e.email,778                  url: e.url,779                  hasTotp: Boolean(e.totp),780                  hasPasskey: e.passkey !== undefined,781                }782          ),783        };784      }785      case "GET_ENTRY_FOR_FILL": {786        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };787        const { id } = msg.payload as { id: string };788        const entry = vault.getEntryById(id);789        if (!entry) return { ok: false, error: "entry_not_found" };790        // Passkey-only entries (passkey credential, no password) cannot be791        // filled into a form — sign-in goes through the WebAuthn path. A792        // login that ALSO has a passkey is still fillable for its password.793        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };794        // Strip the passkey credential from the response — content scripts795        // never need the private key, and there's no reason to expose the796        // public credential metadata over the boundary either.797        const { passkey: _strippedPasskey, ...safeEntry } = entry;798        return { ok: true, data: safeEntry };799      }800      case "COPY": {801        // AUD-002: shape-validate the payload before passing to the clipboard802        // helper. A raw cast lets a malformed message reach the clipboard API803        // with a non-string and throw.804        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {805          text?: unknown;806          label?: unknown;807          alreadyWritten?: unknown;808        };809        if (typeof text !== "string" || typeof label !== "string") {810          return { ok: false, error: "invalid_payload" };811        }812        await copyToClipboard(text, label, Boolean(alreadyWritten));813        return { ok: true };814      }815      case "CHECK_ALL_BREACHES": {816        const allEntries = vault.getEntries();817        const results: Record<string, number> = {};818        for (const entry of allEntries) {819          if (entry.type === "note") continue;820          if (!entry.password) continue;821          results[entry.id] = await vault.checkBreach(entry.password);822          // Small delay — be a good citizen to the HIBP API823          await new Promise((r) => setTimeout(r, 200));824        }825        // Persist any non-zero counts back to entries826        for (const [id, count] of Object.entries(results)) {827          const entry = vault.getEntryById(id);828          if (entry && (entry.breach ?? 0) !== count) {829            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });830          }831        }832        return { ok: true, data: results };833      }834      case "GET_SETTINGS":835        return { ok: true, data: await vault.ensureSettingsLoaded() };836      case "UPDATE_SETTINGS": {837        const patch = msg.payload;838        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {839          return { ok: false, error: "invalid_payload" };840        }841        await vault.updateSettings(patch as vault.VaultSettings);842        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {843          await setupAutoLock();844          if (vault.isUnlocked()) touchAutoLock();845        }846        return { ok: true };847      }848      case "GET_PENDING_PASSKEY":849        return { ok: true, data: await getPendingPasskeyRequest() };850      case "APPROVE_PASSKEY": {851        const { requestId } = msg.payload as { requestId: number };852        await resolvePendingPasskeyRequest(requestId, true);853        return { ok: true };854      }855      case "DENY_PASSKEY": {856        const { requestId } = msg.payload as { requestId: number };857        await resolvePendingPasskeyRequest(requestId, false);858        return { ok: true };859      }860      case "GET_PASSKEY_PROVIDER_STATE":861        return { ok: true, data: await getPasskeyProviderState() };862      case "SET_PASSKEY_PROVIDER_ENABLED": {863        const { enabled } = msg.payload as { enabled: boolean };864        // Disabling is always free; gating fires only when a free user is865        // trying to turn passkey interception on.866        if (enabled) {867          const gate = await requirePro("passkeys");868          if (!gate.allowed) return { ok: false, error: "pro_required" };869        }870        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };871      }872      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS873      // endpoint. Intentional product behavior — users configure their own874      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private875      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-876      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to877      // users that the entry title leaves the device when the canary fires.878      case "FIRE_CANARY_PING": {879        const { webhookUrl, entryTitle, trigger } = msg.payload as {880          webhookUrl: string;881          entryTitle: string;882          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";883        };884        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {885          return { ok: false, error: "invalid_webhook_url" };886        }887        const body = JSON.stringify({888          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",889          entry: entryTitle,890          trigger,891          timestamp: new Date().toISOString(),892          source: "peach-extension",893        });894        if (trigger === "test") {895          // Permitted outbound fetch: user-configured canary alert endpoint896          // (validated by isAllowedCanaryWebhookUrl above). This is the897          // only non-HIBP outbound call in the extension — see898          // Projects.md §3.7. Test pings are awaited so the UI can show899          // success/failure.900          try {901            const res = await fetch(webhookUrl, {902              method: "POST",903              headers: { "Content-Type": "application/json" },904              body,905            });906            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };907          } catch (err) {908            return { ok: false, error: err instanceof Error ? err.message : "network_error" };909          }910        }911        // Non-test triggers are fire-and-forget912        fetch(webhookUrl, {913          method: "POST",914          headers: { "Content-Type": "application/json" },915          body,916        }).catch(() => {});917        return { ok: true };918      }919      case "ACTIVATE_LICENSE": {920        const { key } = msg.payload as { key: string };921        const licenseInfo = await activateLicense(key);922        return { ok: true, data: licenseInfo };923      }924      case "GET_LICENSE": {925        const licenseInfo = await getLicenseInfo();926        return { ok: true, data: licenseInfo };927      }928      case "GET_LICENSE_KEY": {929        const key = await getLicenseKey();930        return { ok: true, data: key };931      }932      case "DEACTIVATE_LICENSE": {933        await deactivateLicense();934        return { ok: true };935      }936      case "SHOULD_PLAY_CELEBRATION": {937        const should = await shouldPlayCelebration();938        return { ok: true, data: should };939      }940      case "MARK_CELEBRATION_PLAYED": {941        await markCelebrationPlayed();942        return { ok: true };943      }944      case "GET_CODEX_VAULT_DATA": {945        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the946        // popup navigates to the License section without further coordination.947        const gate = await requirePro("codex");948        if (!gate.allowed) return { ok: false, error: "pro_required" };949        return await handleGetCodexVaultData();950      }951      case "ESTIMATE_CODEX_PAGES": {952        const gate = await requirePro("codex");953        if (!gate.allowed) return { ok: false, error: "pro_required" };954        return await handleEstimateCodexPages();955      }956      case "RESTORE_FROM_CODEX": {957        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still958        // be able to restore a vault that was printed by a Pro user.959        // DO NOT add a Pro gate here.960        const payload = msg.payload as CodexRestorePayload;961        return await handleRestoreFromCodex(payload);962      }963      case "OPEN_PRO_GATE": {964        // Content script requests: open popup and navigate to License section.965        const { feature } = (msg.payload ?? {}) as { feature?: string };966        if (chrome.storage.session) {967          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });968        }969        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }970        return { ok: true };971      }972      case "GET_IDENTITIES": {973        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };974        return { ok: true, data: vault.getIdentities() };975      }976      case "TOUCH_AUTO_LOCK": {977        // touchAutoLock() is already called by shouldRefreshAutoLock above;978        // this case just gives the popup a typed message to keep the session alive.979        return { ok: true };980      }981      case "GET_ADVANCED_HEALTH_REPORT": {982        const gate = await requirePro("advanced_health");983        if (!gate.allowed) return { ok: false, error: "pro_required" };984        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };985        const report = await buildAdvancedHealthReport(vault.getEntries());986        return { ok: true, data: report };987      }988      case "INITIATE_PASSWORD_CHANGE": {989        const gate = await requirePro("smart_password_change");990        if (!gate.allowed) return { ok: false, error: "pro_required" };991        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };992        const { id } = msg.payload as { id: string };993        const entry = vault.getEntryById(id);994        if (!entry) return { ok: false, error: "entry_not_found" };995        const url = resolveResetUrl(entry);996        if (!url) return { ok: false, error: "no_reset_url" };997        try {998          await chrome.tabs.create({ url });999          return { ok: true, data: { url } };1000        } catch (err) {1001          return {1002            ok: false,1003            error: err instanceof Error ? err.message : "failed_to_open_tab",1004          };1005        }1006      }1007      case "IS_DURESS_ENABLED": {1008        const enabled = await vault.isDuressEnabled();1009        return { ok: true, data: enabled };1010      }1011      case "SETUP_DURESS": {1012        const { duressPassword } = msg.payload as { duressPassword: string };1013        await vault.setupDuress(duressPassword);1014        return { ok: true };1015      }1016      case "DISABLE_DURESS": {1017        await vault.disableDuress();1018        return { ok: true };1019      }1020      case "VERIFY_MAIN_PASSWORD": {1021        const { password } = msg.payload as { password: string };1022        const ok = await vault.verifyMainPassword(password);1023        return { ok: true, data: ok };1024      }1025      case "CHANGE_PASSWORD": {1026        const { currentPassword, newPassword } = msg.payload as {1027          currentPassword: string;1028          newPassword: string;1029        };1030        const changed = await vault.changePassword(currentPassword, newPassword);1031        return changed1032          ? { ok: true }1033          : { ok: false, error: "incorrect_current_password" };1034      }1035      case "GET_SITE_PASSWORD_POLICY": {1036        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1037        if (!tab?.id) return { ok: true, data: null };1038        try {1039          const response = await chrome.tabs.sendMessage(tab.id, {1040            type: "GET_SITE_PASSWORD_POLICY",1041          });1042          return (response as MessageResponse) ?? { ok: true, data: null };1043        } catch {1044          return { ok: true, data: null };1045        }1046      }1047      case "GET_SYNC_STATE": {1048        const pairedDevices = await getPairedDevices();1049        const trustedNetworks = await getTrustedNetworks();1050        const tailscale = await isOnTailscale();1051        const pro = await isProUser();10521053        let status: SyncStatus = "offline";1054        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {1055          if (pairedDevices.length === 0) {1056            status = "no_peers";1057          } else {1058            status = "synced";1059          }1060        } else {1061          status = "not_trusted";1062        }10631064        const lastSyncRaw = await storageGet("peach_last_sync_at");1065        const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN;1066        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined;10671068        return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } };1069      }1070      case "GET_PAIRED_DEVICES": {1071        const devices = await getPairedDevices();1072        return { ok: true, data: { devices } };1073      }1074      case "GET_SYNC_STATUS": {1075        const lastSyncRaw = await storageGet("peach_last_sync_at");1076        const lastSyncParsed = lastSyncRaw ? parseInt(lastSyncRaw, 10) : NaN;1077        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : null;1078        const status: 'up_to_date' | 'never' = lastSyncAt ? 'up_to_date' : 'never';1079        return { ok: true, data: { status, lastSyncAt } };1080      }1081      case "ACCEPT_PAIRING": {1082        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.1083        return { ok: true };1084      }1085      case "REMOVE_PAIRED_DEVICE": {1086        const { deviceId } = msg.payload as { deviceId: string };1087        await removePairedDevice(deviceId);1088        return { ok: true };1089      }1090      case "REMOVE_TRUSTED_NETWORK": {1091        const payload = msg.payload as1092          | { ssid?: unknown; bssid?: unknown; isTailscale?: unknown }1093          | null1094          | undefined;1095        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {1096          return { ok: false, error: "invalid_payload" };1097        }1098        const { ssid, bssid, isTailscale } = payload as { ssid?: string; bssid?: string; isTailscale?: boolean };1099        const networks = await getTrustedNetworks();1100        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 1101          (isTailscale ? n.isTailscale : n.ssid === ssid) && 1102          (!bssid || n.bssid === bssid)1103        );1104        if (network) {1105          await removeTrustedNetwork(network.addedAt);1106        }1107        return { ok: true };1108      }1109      case "MARK_NETWORK_TRUSTED": {1110        const network = await getCurrentNetwork();1111        await addTrustedNetwork({1112          ssid: network.ssid,1113          bssid: network.bssid,1114          isTailscale: network.isTailscale,1115          addedAt: Date.now(),1116        });1117        return { ok: true };1118      }1119      case "GET_INCOMING_PAIRING_REQUEST": {1120        const request = await getIncomingPairingRequest();1121        return { ok: true, data: request };1122      }1123      case "RESPOND_INCOMING_PAIRING": {1124        const { accept } = msg.payload as { accept: boolean };1125        const request = await getIncomingPairingRequest();1126        if (!request) return { ok: false, error: "no_pending_request" };1127        if (Date.now() > request.expiresAt) {1128          await clearIncomingPairingRequest();1129          return { ok: false, error: "expired" };1130        }1131        await clearIncomingPairingRequest();1132        if (accept) {1133          await addPairedDevice({1134            deviceId: request.publicKeyHex,1135            displayName: request.deviceName,1136            x25519PublicKey: request.publicKeyHex,1137            pairedAt: Date.now(),1138            lastSeenAt: Date.now(),1139          });1140        }1141        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };1142      }1143      case "START_PAIRING_SERVER": {1144        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.1145        const token = generateSixDigitToken();1146        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;1147        await setActivePairingToken({ token, expiresAt });1148        // Fire-and-forget subnet scan — finds the phone after it scans the QR1149        // and calls SCAN_PAIRING_QR to register the token with SyncPlugin.1150        if (!isNativePlatform()) {1151          void runPairingSubnetScan(token);1152        }1153        return { ok: true, data: { token, expiresAt } };1154      }1155      case "STOP_PAIRING_SERVER": {1156        try {1157          await setActivePairingToken(null);1158        } catch { /* best-effort */ }1159        return { ok: true };1160      }1161      case "GET_RECENT_PAIRING": {1162        const recent = await consumeRecentPairing();1163        return { ok: true, data: recent };1164      }1165      case "DEBUG_INJECT_INCOMING_PAIRING": {1166        // M14/SEC-007: blocked in production builds. The handler exists for1167        // Phase 7 banner UX rehearsal without a live native host; shipping1168        // it in production lets any background-message sender inject a1169        // synthetic pairing prompt. Allowed in 'development' and 'test'1170        // modes; vite sets MODE='production' for release builds.1171        if (import.meta.env.MODE === "production") {1172          return { ok: false, error: "not_available" };1173        }1174        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {1175          deviceName?: string;1176          publicKeyHex?: string;1177        };1178        if (!deviceName || !publicKeyHex) {1179          return { ok: false, error: "missing_payload" };1180        }1181        const now = Date.now();1182        await setIncomingPairingRequest({1183          deviceName,1184          publicKeyHex,1185          receivedAt: now,1186          expiresAt: now + 60_000,1187        });1188        return { ok: true };1189      }1190      case "RESET_SYNC_IDENTITY": {1191        const gate = await requirePro("sync");1192        if (!gate.allowed) return { ok: false, error: "pro_required" };1193        const devices = await getPairedDevices();1194        for (const device of devices) {1195          await removePairedDevice(device.deviceId);1196        }1197        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };1198      }1199      case "RECORD_MANUAL_SUMMON": {1200        const { domain } = msg.payload as { domain: string };1201        const settings = vault.getSettings();1202        const existing = settings.manualSummonDomains?.[domain];1203        const now = Date.now();1204        await vault.updateSettings({1205          manualSummonDomains: {1206            ...settings.manualSummonDomains,1207            [domain]: {1208              firstSummonedAt: existing?.firstSummonedAt ?? now,1209              summonCount: (existing?.summonCount ?? 0) + 1,1210              lastSummonedAt: now,1211            },1212          },1213        });1214        return { ok: true };1215      }1216      case "DECLINE_CARD_SAVE": {1217        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1218        await vault.declineCardSaveOffer(last4, expMonth, expYear);1219        return { ok: true };1220      }1221      case "IS_CARD_DECLINED": {1222        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1223        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1224        return { ok: true, data: declined };1225      }1226      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1227        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1228          rpId?: string;1229          rpName?: string;1230          userName?: string;1231          userDisplayName?: string;1232        };1233        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1234        return await initiateFirefoxPasskeyCreate({1235          rpId,1236          rpName: rpName ?? rpId,1237          userName,1238          userDisplayName,1239        });1240      }12411242      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1243        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1244        if (!payload) return { ok: false, error: "missing_payload" };1245        return await completeFirefoxPasskeyCreate(payload);1246      }12471248      case "PASSKEY_OFFER_DECLINE": {1249        const { domain } = (msg.payload ?? {}) as { domain?: string };1250        if (!domain) return { ok: false, error: "domain_required" };1251        await recordPasskeyOfferDecline(domain);1252        return { ok: true };1253      }12541255      case "GET_PASSKEY_OFFER_DECLINED": {1256        const { domain } = (msg.payload ?? {}) as { domain?: string };1257        if (!domain) return { ok: false, error: "domain_required" };1258        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1259      }12601261      case "PASSKEY_HAS_CREDENTIALS": {1262        const payload = msg.payload as {1263          rpId?: string;1264          allowCredentials?: Array<{ id: string; type?: string }>;1265        } | undefined;1266        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1267        return await handlePasskeyHasCredentials({1268          rpId: payload.rpId,1269          allowCredentials: payload.allowCredentials ?? [],1270        });1271      }12721273      case "PASSKEY_CREATE": {1274        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1275        if (!payload?.rpId || !payload?.userName) {1276          return { ok: false, error: "rpid_and_username_required" };1277        }1278        return await handleFirefoxPasskeyCreate(payload);1279      }12801281      case "PASSKEY_GET": {1282        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1283        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1284        return await handleFirefoxPasskeyGet(payload);1285      }12861287      case "PASSKEY_AUTH_RESPONSE": {1288        const { requestId, approved } = (msg.payload ?? {}) as {1289          requestId?: string | number;1290          approved?: boolean;1291        };1292        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1293          return { ok: false, error: 'requestId and approved required' };1294        }1295        await resolvePendingPasskeyRequest(Number(requestId), approved);1296        return { ok: true };1297      }12981299      case "GET_PASSKEY_FOR_DOMAIN": {1300        const { domain } = (msg.payload ?? {}) as { domain?: string };1301        if (!domain) return { ok: false, error: "domain_required" };1302        if (!vault.isUnlocked()) return { ok: true, data: null };1303        const match = vault1304          .getEntries()1305          .find((entry) => entry.passkey?.rpId === domain);1306        if (!match || !match.passkey) return { ok: true, data: null };1307        // Slim shape — only the fields State 11 needs. Never expose private1308        // key material, even though this is locked behind isUnlocked.1309        return {1310          ok: true,1311          data: {1312            rpId: match.passkey.rpId,1313            userName: match.passkey.userName,1314            browser: match.passkey.browser,1315          },1316        };1317      }13181319      case "DESTROY_VAULT": {1320        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1321        // storage.local.clear() wipes every Peach key (slots, settings, license,1322        // onboarded flag, history, sync state, declined cards, recall, etc.);1323        // session.clear() wipes pending passkey requests + pro-notice queues.1324        // Caller (Panic.tsx) handles UI navigation back to onboarding.1325        vault.lock();1326        await storageClear();1327        await vault.clearVaultHistory();1328        if (chrome.storage.session) {1329          await chrome.storage.session.clear();1330        }1331        return { ok: true };1332      }13331334      case "SUBMIT_FEEDBACK": {1335        const { category, message, version, browser } = msg.payload as {1336          category: string;1337          message: string;1338          version: string;1339          browser: string;1340        };1341        if (!message.trim()) return { ok: false, error: "message_empty" };1342        if (!FEEDBACK_ENDPOINT) return { ok: true };1343        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1344          return { ok: false, error: "invalid_feedback_endpoint" };1345        }1346        try {1347          const res = await fetch(FEEDBACK_ENDPOINT, {1348            method: "POST",1349            headers: { "Content-Type": "application/json" },1350            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1351          });1352          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1353        } catch (err) {1354          return { ok: false, error: err instanceof Error ? err.message : "network_error" };1355        }1356      }1357      case "TRIGGER_SYNC": {1358        const gate = await requirePro("sync");1359        if (!gate.allowed) return { ok: false, error: "pro_required" };1360        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };13611362        if (isNativePlatform()) {1363          // Phone is the server — ensure it's listening for desktop connections.1364          syncBridge()?.ensureServerRunning?.();1365          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };1366        }13671368        // Desktop: iterate all paired devices and sync with each.1369        const paired = await getPairedDevices();1370        if (!paired.length) return { ok: true, data: { syncedCount: 0, reason: "no_paired_devices" } };13711372        const subnet = await getLocalSubnet();1373        const results: Array<{ device: string } & SyncResult> = [];13741375        for (const device of paired) {1376          const pubkey = device.x25519PublicKey;1377          if (!pubkey) continue;13781379          let result: SyncResult;13801381          // Fast path — use last known IP1382          if (device.lastKnownIp) {1383            result = await doVaultSync(device.lastKnownIp, pubkey);1384          } else {1385            result = { status: 'errored', applied: false, error: 'no_ip' };1386          }13871388          // Discovery path — scan if fast path failed1389          if (result.status === 'errored' && subnet) {1390            const newIp = await discoverDevice(subnet, pubkey);1391            if (newIp) {1392              await updatePairedDevice(pubkey, { lastKnownIp: newIp });1393              result = await doVaultSync(newIp, pubkey);1394            }1395          }13961397          if (result.status === 'completed') {1398            await updatePairedDevice(pubkey, {1399              lastSeenAt: Date.now(),1400              lastSyncAt: Date.now(),1401            });1402          }14031404          results.push({ device: device.displayName ?? "", ...result });1405        }14061407        const syncedCount = results.filter(r => r.status === 'completed').length;1408        if (syncedCount > 0) {1409          await chrome.storage.local.set({ peach_last_sync_at: String(Date.now()) });1410        }1411        return { ok: true, data: { syncedCount, results } };1412      }1413      // Android-only: biometric unlock with pre-derived key.1414      case "UNLOCK_WITH_KEY": {1415        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1416        if (!isNativePlatform()) {1417          return { ok: false, error: "desktop_only_uses_password" };1418        }1419        try {1420          const result = await vault.unlockWithKey(masterKeyHex);1421          if (result.ok) {1422            onVaultUnlocked();1423            await publishInMemoryVault(result.entries);1424          }1425          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1426        } catch {1427          return { ok: false, error: "invalid_key" };1428        }1429      }1430      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1431      case "GET_DERIVED_KEY": {1432        if (!isNativePlatform()) {1433          return { ok: false, error: "android_only" };1434        }1435        if (!vault.isUnlocked()) {1436          return { ok: false, error: "vault_locked" };1437        }1438        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1439      }1440      // Android: scanned a QR containing a desktop pairing token.1441      case "SCAN_PAIRING_QR": {1442        if (!isNativePlatform()) {1443          return { ok: false, error: "android_only" };1444        }1445        const { token } = msg.payload as { token: string };1446        syncBridge()?.startPairingSession?.({ token });1447        return { ok: true };1448      }1449      // Android: desktop opened a sync connection to the phone's WS server.1450      // Run the responder side of the vault exchange.1451      case "SYNC_SESSION_STARTED": {1452        if (!isNativePlatform()) return { ok: false };1453        if (!vault.isUnlocked()) {1454          return { ok: false, error: "vault_locked" };1455        }1456        const { connectionId } = (msg.payload ?? {}) as { connectionId?: string };1457        if (!connectionId) return { ok: false, error: "missing_connection_id" };14581459        const transport = createAndroidResponderTransport(connectionId);14601461        // Authenticate the initiator before exchanging any vault data. The1462        // native side has already completed the Noise NK handshake; auth1463        // frames here ride the Noise transport (native encrypts/decrypts).1464        const identity = await vault.getSyncIdentity();1465        try {1466          // CAUTION: noiseSessionStub is a structural placeholder — the real1467          // Noise NK handshake runs natively, so JS never holds the session1468          // object. performResponderAuth currently `void`s this argument,1469          // which is why identity-passthrough encrypt/decrypt and a zero1470          // handshake hash are safe. If performResponderAuth is ever updated1471          // to actually use this argument, this auth path will silently break1472          // (no type error). Revisit this stub if that helper changes.1473          const noiseSessionStub = {1474            encrypt: (b: Uint8Array) => b,1475            decrypt: (b: Uint8Array) => b,1476            handshakeHash: new Uint8Array(32),1477          };1478          const { initiatorPublicKey } = await performResponderAuth(1479            noiseSessionStub,1480            identity.privateKeyBytes,1481            identity.publicKeyBytes,1482            transport.send,1483            transport.receive,1484          );1485          const initiatorHex = noiseBytesToHex(initiatorPublicKey);1486          const paired = await getPairedDevices();1487          if (!paired.some(d => d.x25519PublicKey === initiatorHex)) {1488            await transport.close();1489            return { ok: false, error: "sync_rejected_unpaired_initiator" };1490          }1491          // Initiator just proved control of the matching static key; mark it1492          // as a verified handshake so a follow-up PAIRING_COMPLETED message1493          // can be trusted (M13/SEC-005).1494          markPairingHandshakeVerified(initiatorHex);1495        } catch (err) {1496          await transport.close();1497          return { ok: false, error: `sync_auth_failed: ${String(err)}` };1498        }14991500        const result = await runBlobSyncSession('responder', transport, buildSyncDeps());1501        if (result.applied) {1502          await publishInMemoryVault(vault.getEntries());1503        }1504        return { ok: true, data: result };1505      }1506      // Android: returns the phone's WiFi IP address.1507      case "GET_LOCAL_IP": {1508        if (!isNativePlatform()) {1509          return { ok: false, error: "android_only" };1510        }1511        const { ip } = (await syncBridge()?.getLocalIp?.()) ?? { ip: "" };1512        return { ok: true, data: { ip } };1513      }1514      case "GET_IDENTITY_SUGGESTIONS": {1515        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1516        const entries = vault.getEntries();1517        const suggestions = buildIdentitySuggestions(entries);1518        return { ok: true, data: { suggestions } };1519      }1520      case "POPULATE_INLINE_VAULT": {1521        if (!isNativePlatform()) return { ok: false };1522        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1523        const entries = vault.getEntries();1524        await publishInMemoryVault(entries);1525        return { ok: true };1526      }1527      case "ML_INIT":1528        return { ok: true };15291530      case "ML_PREDICT_BATCH": {1531        // AUD-002: shape-validate before forwarding to the ML helper.1532        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1533        if (!Array.isArray(featuresArray)) {1534          return { ok: false, error: "invalid_payload" };1535        }1536        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1537      }15381539      default:1540        return { ok: false, error: "unknown_message_type" };1541    }1542  } catch (err) {1543    return {1544      ok: false,1545      error: err instanceof Error ? err.message : "operation_failed",1546    };1547  }1548}15491550// --- Mobile platform helpers ---15511552// Android: populates the in-memory vault used by PeachAutofillService.1553async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1554  const plugin = nativePlugin<{1555    setEntries?: (args: {1556      entries: Array<{1557        id: string;1558        title: string;1559        username: string;1560        email: string;1561        password: string;1562        url: string;1563        totp: string;1564        additionalUrls: string[];1565      }>;1566    }) => Promise<void>;1567  }>("InMemoryVaultPlugin");1568  if (!plugin?.setEntries) return;1569  await plugin.setEntries({1570    entries: entries.map((e) => ({1571      id: e.id,1572      title: e.title ?? "",1573      username: e.username ?? "",1574      email: (e as VaultEntry & { email?: string }).email ?? "",1575      password: e.password ?? "",1576      url: e.url ?? "",1577      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1578      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1579    })),1580  });1581}15821583// Android: clear the autofill in-memory store on lock.1584async function clearInMemoryVault(): Promise<void> {1585  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1586  if (!plugin?.clearEntries) return;1587  await plugin.clearEntries();1588}15891590interface SyncBridge {1591  ensureServerRunning?: () => void;1592  startPairingSession?: (args: { token: string }) => void;1593  getLocalIp?: () => Promise<{ ip: string }>;1594  sendToConnection?: (args: { connectionId: string; data: string }) => Promise<void>;1595  addListener?: (event: string, handler: (data: Record<string, string>) => void) => void;1596}15971598// Resolve the Capacitor SyncPlugin at call time — module-load resolution1599// races with Capacitor's plugin registration on the Android WebView.1600function syncBridge(): SyncBridge | null {1601  return nativePlugin<SyncBridge>("SyncPlugin");1602}16031604// Build a SyncTransport for the Android responder path — the phone's WS server1605// already has an open connection from the desktop. We send back via1606// SyncPlugin.sendToConnection and receive via the peach:sync-frame queue.1607const androidSyncFrameQueues = new Map<string, Array<(frame: string) => void>>();16081609export function deliverAndroidSyncFrame(connectionId: string, frame: string): void {1610  const queue = androidSyncFrameQueues.get(connectionId);1611  if (queue?.length) queue.shift()!(frame);1612}16131614function createAndroidResponderTransport(connectionId: string) {1615  const pendingReceivers: Array<(frame: string) => void> = [];1616  androidSyncFrameQueues.set(connectionId, pendingReceivers);16171618  return {1619    send: async (data: Uint8Array) => {1620      await syncBridge()?.sendToConnection?.({ connectionId, data: bytesToBase64(data) });1621    },1622    receive: (): Promise<Uint8Array> => new Promise((res) => {1623      pendingReceivers.push((frame) => {1624        res(frame ? base64ToBytes(frame) : new Uint8Array(0));1625      });1626    }),1627    close: async () => {1628      androidSyncFrameQueues.delete(connectionId);1629    },1630  };1631}16321633// Returns username use-counts from the vault, sorted by frequency. Each row1634// also carries the entry's email so the popup can suggest the email/username1635// pair the user has actually used together.1636function buildIdentitySuggestions(1637  entries: VaultEntry[],1638): Array<{ email: string; username: string; count: number }> {1639  const usernameCounts = new Map<string, number>();1640  const usernameEmail = new Map<string, string>();1641  for (const entry of entries) {1642    const username = entry.username ?? "";1643    const email = (entry as VaultEntry & { email?: string }).email ?? "";1644    if (!username && !email) continue;1645    const key = username || email;1646    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1647    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1648  }1649  return Array.from(usernameCounts.entries())1650    .sort((a, b) => b[1] - a[1])1651    .map(([username, count]) => ({1652      email: usernameEmail.get(username) ?? "",1653      username,1654      count,1655    }));1656}16571658/** Notify all content scripts that the vault just became available. */1659function broadcastToContentScripts(message: { type: string }): void {1660  if (!chrome.tabs?.query) return;1661  chrome.tabs.query({}, (tabs) => {1662    for (const tab of tabs) {1663      if (tab.id !== undefined) {1664        chrome.tabs.sendMessage(tab.id, message).catch(() => {1665          // Tab may not have a content script — silently ignore1666        });1667      }1668    }1669  });1670}16711672function shouldRefreshAutoLock(type: MessageType): boolean {1673  return (1674    type !== "HAS_VAULT" &&1675    type !== "IS_UNLOCKED" &&1676    type !== "GET_VAULT_STATUS" &&1677    type !== "LOCK" &&1678    type !== "UPDATE_SETTINGS" &&1679    type !== "GET_PENDING_PASSKEY" &&1680    type !== "GET_PASSKEY_PROVIDER_STATE" &&1681    type !== "DECLINE_CARD_SAVE" &&1682    type !== "IS_CARD_DECLINED" &&1683    type !== "SUBMIT_FEEDBACK"1684  );1685}16861687function isAllowedCanaryWebhookUrl(value: string): boolean {1688  try {1689    const url = new URL(value);1690    if (url.protocol !== "https:") return false;16911692    const hostname = url.hostname.toLowerCase();1693    if (1694      hostname === "localhost" ||1695      hostname.endsWith(".localhost") ||1696      isPrivateIpv4(hostname) ||1697      isPrivateIpv6(hostname)1698    ) {1699      return false;1700    }17011702    return true;1703  } catch {1704    return false;1705  }1706}17071708function isPrivateIpv4(hostname: string): boolean {1709  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1710    return true;1711  }17121713  const octets = hostname.split(".").map((part) => Number(part));1714  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1715    return false;1716  }17171718  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1719}17201721function isPrivateIpv6(hostname: string): boolean {1722  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1723  return (1724    normalized === "::1" ||1725    normalized.startsWith("fc") ||1726    normalized.startsWith("fd") ||1727    normalized.startsWith("fe80:")1728  );1729}