messages.ts

66.6 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard } from "./clipboard";13import { setupAutoLock, touchAutoLock } from "./alarms";14import * as vault from "./vault";15import {16  handleEstimateCodexPages,17  handleGetCodexVaultData,18  handleRestoreFromCodex,19} from "./codex-handlers";20import type { CodexRestorePayload } from "../shared/codex-types";21import {22  activateLicense,23  deactivateLicense,24  getLicenseInfo,25  getLicenseKey,26  isProUser,27  markCelebrationPlayed,28  shouldPlayCelebration,29} from "./license";30import {31  completeFirefoxPasskeyCreate,32  getPasskeyProviderState,33  getPendingPasskeyRequest,34  handleFirefoxPasskeyCreate,35  handleFirefoxPasskeyGet,36  handlePasskeyHasCredentials,37  initiateFirefoxPasskeyCreate,38  isPasskeyOfferDeclined,39  onVaultUnlocked,40  recordPasskeyOfferDecline,41  resolvePendingPasskeyRequest,42  setPasskeyProviderEnabled,43} from "./passkey";44import { buildAdvancedHealthReport, resolveResetUrl } from "./health";45import { storageClear, storageGet } from "../shared/storage";46import { findInvalidWords } from "../shared/recovery-words";47import {48  addPairedDevice,49  addTrustedNetwork,50  clearIncomingPairingRequest,51  getIncomingPairingRequest,52  getPairedDevices,53  getTrustedNetworks,54  removePairedDevice,55  removeTrustedNetwork,56  setIncomingPairingRequest,57  updatePairedDevice,58} from "./sync-storage";59import { getCurrentNetwork, isOnTailscale } from "./sync-network";60import {61  consumeRecentPairing,62  setActivePairingToken,63} from "./pairing-server-state";64import type {65  Message,66  MessageResponse,67  MessageType,68  ProFeature,69  VaultEntry,70} from "../shared/types";71import { isPasskeyOnly } from "../shared/types";72import type { SyncStatus, SyncableDevice } from "../shared/sync-types";73import { isNativePlatform, nativePlugin } from "../shared/native";74import { runBlobSyncSession, type SyncResult } from "./sync-coordinator";75import type { SyncDeps } from "./sync-coordinator";76import { createWebSocketSyncTransport } from "../shared/websocket-sync-transport";77import { performResponderAuth, bytesToHex as noiseBytesToHex } from "../shared/noise-js";78import { getLocalSubnet, discoverDevice, scanForPairingPhone } from "../shared/local-network";79import { predictBatch as mlPredictBatch } from "./ml";80import type { MLFieldFeatures } from "../shared/ml";81import { base64ToBytes, bytesToBase64 } from "../shared/sync-wire";8283/**84 * The single Pro gate. Every gated handler calls this first; the broadcast85 * lets the popup react (navigate to the License section, highlight the86 * relevant feature). Background never touches the popup view directly —87 * the popup owns navigation. See Projects.md "Pro gate rule".88 */89async function requirePro(90  feature: ProFeature,91  trigger: "user" | "background" = "user"92): Promise<{ allowed: boolean }> {93  if (await isProUser()) return { allowed: true };9495  if (trigger === "user") {96    // User deliberately triggered this feature — redirect the popup immediately.97    chrome.runtime98      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })99      .catch(() => {100        // Popup may be closed — the gate signal is best-effort.101      });102  } else {103    // Background trigger (e.g. passive sync initiation) — no popup is open.104    // Queue a notice so the next popup open shows a soft banner instead of105    // silently failing.106    if (chrome.storage.session) {107      chrome.storage.session108        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })109        .catch(() => {});110    }111  }112113  return { allowed: false };114}115116// ---------------------------------------------------------------------------117// 6-digit code pairing.118119const PAIRING_TOKEN_TTL_MS = 5 * 60 * 1000;120121122function generateSixDigitToken(): string {123  // crypto.getRandomValues, not Math.random — the token is the only secret124  // protecting the pairing window from a same-LAN attacker. 6 decimal digits125  // is 1 in 1,000,000; combined with a 5-minute TTL and pairing-mode gating126  // on the responder this is the right tradeoff between UX and security.127  const buf = new Uint32Array(1);128  crypto.getRandomValues(buf);129  const value = buf[0] % 1_000_000;130  return value.toString().padStart(6, "0");131}132133// ---------------------------------------------------------------------------134// Peer discovery glue (Phase 7 popup pairing flow).135136const PRIVATE_IPV4_RANGES = [137  { prefix: "10." },138  { prefix: "127." },139  { prefix: "169.254." },140  { prefix: "192.168." },141];142143// Empty disables network submission while the UI continues to function as a144// no-op (the handler returns ok:true without calling fetch). When set, the145// URL is validated by `isAllowedCanaryWebhookUrl` before any request, so the146// same private-IP/HTTPS rules that gate canary webhooks apply here.147const FEEDBACK_ENDPOINT = "";148149// ---------------------------------------------------------------------------150// Sync helpers151// ---------------------------------------------------------------------------152153/**154 * Short-lived registry of x25519 public keys that just completed a real Noise155 * NK handshake + initiator-auth proof. The PAIRING_COMPLETED handler must156 * find the supplied publicKeyHex here before it will call addPairedDevice —157 * otherwise an attacker could forge the message and pair an arbitrary key158 * (M13/SEC-005).159 *160 * Entries auto-expire after 30s. Each entry is consumed on first successful161 * PAIRING_COMPLETED so a single handshake cannot pair twice.162 */163const PENDING_PAIRS = new Map<string, ReturnType<typeof setTimeout>>();164const PENDING_PAIR_TTL_MS = 30_000;165166export function markPairingHandshakeVerified(publicKeyHex: string): void {167  if (!publicKeyHex) return;168  const existing = PENDING_PAIRS.get(publicKeyHex);169  if (existing) clearTimeout(existing);170  const t = setTimeout(() => PENDING_PAIRS.delete(publicKeyHex), PENDING_PAIR_TTL_MS);171  PENDING_PAIRS.set(publicKeyHex, t);172}173174function consumePendingPair(publicKeyHex: string): boolean {175  const t = PENDING_PAIRS.get(publicKeyHex);176  if (!t) return false;177  clearTimeout(t);178  PENDING_PAIRS.delete(publicKeyHex);179  return true;180}181182export function buildSyncDeps(): SyncDeps {183  return {184    isVaultUnlocked: () => vault.isUnlocked(),185    getVaultBlobForSync: async () => {186      const base = await vault.getVaultBlobForSync();187      if (!base) return null;188      const paired = await getPairedDevices();189      return {190        ...base,191        devices: paired192          .filter(d => d.x25519PublicKey)193          .map(d => ({194            publicKeyHex: d.x25519PublicKey,195            deviceName: d.displayName,196            pairedAt: d.pairedAt,197          })),198      };199    },200    applyIncomingVault: async (blob, ts, license, devices) => {201      const applied = await vault.applyIncomingVault(blob, ts, license);202      if (devices?.length) await mergeDeviceRegistry(devices);203      if (applied) {204        const reloaded = await vault.reloadEntriesAfterSync();205        if (!reloaded) {206          // The remote vault was encrypted under a different key (the remote207          // changed password). Our in-memory entries are now stale and cannot208          // be re-encrypted without overwriting the just-applied blob. Lock209          // to force a re-unlock with the new password (H3/COR-005).210          vault.lock();211          chrome.runtime212            .sendMessage({ type: "VAULT_RELOCK_AFTER_SYNC" })213            .catch(() => {});214        }215      }216      return applied;217    },218  };219}220221async function doVaultSync(ip: string, publicKeyHex: string): Promise<SyncResult> {222  // Defensive: refuse to drive a sync to a key not in the paired-devices223  // list. The WebSocket transport already authenticates the peer via Noise224  // NK + the initiator auth proof (H1), but pinning the key to the paired225  // set here makes "talk to anyone matching this static key" the only path226  // to vault application — there is no orphan-key window between pair and227  // sync (M11/COR-014).228  const paired = await getPairedDevices();229  if (!paired.some(d => d.x25519PublicKey === publicKeyHex)) {230    return { status: 'errored', applied: false, error: 'remote_not_paired' };231  }232  try {233    const identity = await vault.getSyncIdentity();234    const transport = await createWebSocketSyncTransport(235      `ws://${ip}:44100`,236      publicKeyHex,237      identity.privateKeyBytes,238      identity.publicKeyBytes,239    );240    const result = await runBlobSyncSession('initiator', transport, buildSyncDeps());241    // Reaching this point means createWebSocketSyncTransport completed both242    // the Noise NK handshake and the initiator-auth proof — the remote243    // proved possession of the matching static key (M13/SEC-005).244    if (result.status === 'completed') {245      markPairingHandshakeVerified(publicKeyHex);246    }247    return result;248  } catch (err) {249    return { status: 'errored', applied: false, error: String(err) };250  }251}252253async function mergeDeviceRegistry(incoming: SyncableDevice[]): Promise<void> {254  const existing = await getPairedDevices();255  const existingKeys = new Set(existing.map(d => d.x25519PublicKey));256  for (const device of incoming) {257    if (!existingKeys.has(device.publicKeyHex)) {258      await addPairedDevice({259        deviceId: device.publicKeyHex,260        displayName: device.deviceName,261        x25519PublicKey: device.publicKeyHex,262        pairedAt: device.pairedAt,263        lastSeenAt: 0,264        lastKnownIp: '',265      }).catch(() => {});266    }267  }268}269270// Background pairing scan — runs after START_PAIRING_SERVER fires on desktop.271// Scans the local subnet for a phone that has accepted the pairing token,272// stores it, runs the initial vault exchange, then notifies the popup.273async function runPairingSubnetScan(token: string): Promise<void> {274  const subnet = await getLocalSubnet();275  if (!subnet) return;276277  const found = await scanForPairingPhone(subnet, token);278  if (!found) return;279280  const { ip, publicKeyHex } = found;281282  try {283    await addPairedDevice({284      deviceId: publicKeyHex,285      displayName: 'Peach',286      x25519PublicKey: publicKeyHex,287      pairedAt: Date.now(),288      lastSeenAt: Date.now(),289      lastKnownIp: ip,290    });291  } catch {292    // Already paired — update IP293    await updatePairedDevice(publicKeyHex, { lastKnownIp: ip, lastSeenAt: Date.now() });294  }295296  // Immediate vault exchange — the free one-time transfer297  await doVaultSync(ip, publicKeyHex);298299  chrome.runtime.sendMessage({300    type: 'PAIRING_COMPLETED',301    payload: { deviceName: 'Peach', publicKeyHex, deviceIp: ip },302  }).catch(() => {});303}304305export function setupMessageHandler(): void {306  chrome.runtime.onMessage.addListener(307    (msg: unknown, sender, sendResponse) => {308      if (!isMessage(msg)) {309        sendResponse({ ok: false, error: "invalid_message" });310        return true;311      }312      handleMessage(msg, sender)313        .then(sendResponse)314        .catch((err) =>315          sendResponse({316            ok: false,317            error: err instanceof Error ? err.message : String(err),318          })319        );320      return true;321    }322  );323324  // Android: the chrome shim queues sendMessage calls until this handler is325  // registered. Without this hookup, every message hangs on Capacitor builds.326  // eslint-disable-next-line @typescript-eslint/no-explicit-any327  const reg = (globalThis as any).__peachRegisterMessageHandler;328  if (typeof reg === "function") {329    reg(async (m: unknown) => {330      if (!isMessage(m)) return { ok: false, error: "invalid_message" };331      try {332        return await handleMessage(m);333      } catch (err) {334        return {335          ok: false,336          error: err instanceof Error ? err.message : String(err),337        };338      }339    });340  }341342  // Android: subscribe to SyncPlugin events.343  if (isNativePlatform()) {344    const syncPlug = nativePlugin<{345      addListener: (346        event: string,347        handler: (data: Record<string, string>) => void348      ) => void;349    }>("SyncPlugin");350351    // Pairing probe answered — store the paired device (desktop, no IP needed352    // since the desktop never acts as a WS server).353    syncPlug?.addListener?.("peach:pair-probe-answered", (data) => {354      const deviceName = data.deviceName ?? "Peach";355      const publicKeyHex = data.publicKeyHex ?? "";356      // Native handled the pairing handshake — trust this entry into the357      // verified-handshake set (M13/SEC-005). The subsequent PAIRING_COMPLETED358      // message will consume it.359      if (publicKeyHex) markPairingHandshakeVerified(publicKeyHex);360      void (async () => {361        const { addPairedDevice, setHasPaired: setPaired } = await import("./sync-storage");362        await addPairedDevice({363          deviceId: publicKeyHex || (data.connectionId ?? "unknown"),364          displayName: deviceName,365          x25519PublicKey: publicKeyHex,366          pairedAt: Date.now(),367          lastSeenAt: Date.now(),368        }).catch(() => {});369        await setPaired();370        chrome.runtime.sendMessage({371          type: "PAIRING_COMPLETED",372          payload: { deviceName, publicKeyHex },373        }).catch(() => {});374      })();375    });376377    // Sync frame received — route to the waiting responder session.378    syncPlug?.addListener?.("peach:sync-frame", (data) => {379      const { connectionId, frame } = data;380      if (connectionId && frame) deliverAndroidSyncFrame(connectionId, frame);381    });382383    // Sync session started (SYNC_HELLO received by SyncPlugin) — dispatch as384    // a background message so SYNC_SESSION_STARTED handler runs the responder.385    syncPlug?.addListener?.("peach:sync-session-started", (data) => {386      const { connectionId } = data;387      if (!connectionId) return;388      void handleMessage({ type: "SYNC_SESSION_STARTED", payload: { connectionId } });389    });390  }391}392393function isMessage(m: unknown): m is Message {394  return typeof m === "object" && m !== null && "type" in m;395}396397export async function handleMessage(398  msg: Message,399  sender: Partial<chrome.runtime.MessageSender> = {}400): Promise<MessageResponse> {401  try {402    // Validate sender — only allow messages from our extension pages/scripts.403    // `sender.id` is undefined for messages originating from extension UI404    // (popup/options), which is legitimate; reject only when it is defined405    // and does not match our extension id.406    if (407      sender.id !== undefined &&408      sender.id !== chrome.runtime.id409    ) {410      return { ok: false, error: "invalid_sender" };411    }412413    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {414      touchAutoLock();415    }416417    switch (msg.type) {418      case "CREATE_VAULT": {419        const { password } = msg.payload as { password: string };420        await vault.createVault(password);421        await setupAutoLock();422        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });423        onVaultUnlocked();424        return { ok: true };425      }426      case "UNLOCK": {427        const { password } = msg.payload as { password: string };428        const ok = await vault.unlock(password);429        if (ok) {430          await setupAutoLock();431          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });432          onVaultUnlocked();433          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());434          return { ok: true };435        }436        // Distinguish corruption from wrong password so the popup can offer437        // a history-restore path instead of falsely accusing the user of438        // mistyping (M7/COR-007).439        const failure = vault.consumeLastUnlockFailureReason();440        if (failure) {441          return {442            ok: false,443            error: "vault_corrupted",444            canRestoreFromHistory: true,445          } as MessageResponse;446        }447        return { ok: false };448      }449      case "VALIDATE_RECOVERY_WORDS": {450        const { words } = msg.payload as { words: string[] };451        const invalid = findInvalidWords(words);452        return { ok: true, data: { valid: invalid.length === 0, invalid } };453      }454      case "GET_RECOVERY_WORDS": {455        // Must be unlocked and have recovery set up (vault must be v2.12+).456        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };457        try {458          const words = await vault.getRecoveryWords();459          return { ok: true, data: words };460        } catch (e) {461          // pre-v2.12 vault that hasn't migrated462          return { ok: false, error: "recovery_not_setup" };463        }464      }465      case "RECOVER_WITH_WORDS": {466        // User has lost their password but has their 12 recovery words.467        // We: (1) validate the words, (2) re-encrypt vault with new password.468        const { words, newPassword } = msg.payload as {469          words: string[];470          newPassword: string;471        };472        const stored = await vault.loadSlotA();473        if (!stored) return { ok: false, error: "no_vault" };474        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {475          return { ok: false, error: "recovery_not_setup" };476        }477        // Unwrap the root key from the recovery escrow.478        try {479          await vault.unwrapRootKeyForRecovery(480            stored.recovery_wrapped_root_key,481            stored.recovery_nonce ?? "",482            stored.recovery_tag ?? "",483            stored.recovery_salt,484            words485          );486        } catch {487          return { ok: false, error: "invalid_recovery_words" };488        }489        // Re-key: derive fresh salt + key from new password.490        const newSalt = vault.generateSalt();491        const newKey = await vault.deriveKey(newPassword, newSalt);492        // Re-wrap root key under the new password's derived key so the same493        // recovery words continue to work after the password change.494        await vault.rewrapRootKeyForPassword(newKey, newSalt);495        // Re-encrypt vault entries with the new key.496        await vault.changePasswordWithNewKey(newSalt, newKey);497        await setupAutoLock();498        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });499        return { ok: true };500      }501      case "LOCK":502        vault.lock();503        if (isNativePlatform()) await clearInMemoryVault();504        return { ok: true };505      case "IS_UNLOCKED":506        return { ok: true, data: vault.isUnlocked() };507      case "GET_VAULT_STATUS":508        return { ok: true, unlocked: vault.isUnlocked() };509      case "HAS_VAULT":510        return { ok: true, data: await vault.hasVault() };511      case "GET_ENTRIES":512        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };513        return { ok: true, data: vault.getEntries() };514      case "ADD_ENTRY": {515        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };516        const payload = msg.payload;517        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {518          return { ok: false, error: "invalid_payload" };519        }520        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);521        return { ok: true, data: entry };522      }523      case "BATCH_ADD_ENTRIES": {524        const payload = msg.payload as { entries?: unknown } | null | undefined;525        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {526          return { ok: false, error: "invalid_payload" };527        }528        if (!Array.isArray(payload.entries)) {529          return { ok: false, error: "invalid_payload" };530        }531        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);532        return { ok: true, data: added };533      }534      case "RESTORE_ENTRIES": {535        const payload = msg.payload as536          | { entries?: unknown; mode?: unknown; settings?: unknown }537          | null538          | undefined;539        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {540          return { ok: false, error: "invalid_payload" };541        }542        if (!Array.isArray(payload.entries)) {543          return { ok: false, error: "invalid_payload" };544        }545        if (payload.mode !== "replace" && payload.mode !== "merge") {546          return { ok: false, error: "invalid_payload" };547        }548        const summary = await vault.restoreEntries(549          payload.entries as Parameters<typeof vault.restoreEntries>[0],550          payload.mode551        );552        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {553          await vault.updateSettings(payload.settings as vault.VaultSettings);554        }555        return { ok: true, data: summary };556      }557      case "CLEAR_VAULT_ENTRIES": {558        await vault.clearVaultEntries("REPLACE_ALL");559        return { ok: true };560      }561      case "GET_VAULT_HISTORY": {562        const snapshots = await vault.getVaultHistory();563        return { ok: true, data: snapshots };564      }565      case "RESTORE_VAULT_SNAPSHOT": {566        const { snapshotId } = msg.payload as { snapshotId: string };567        const result = await vault.restoreVaultSnapshot(snapshotId);568        if (!result.ok) return { ok: false, error: result.error };569        broadcastToContentScripts({ type: "VAULT_LOCKED" });570        return { ok: true };571      }572      case "COUNT_DUPLICATES": {573        return { ok: true, data: vault.countDuplicates() };574      }575      case "DEDUPLICATE_ENTRIES": {576        const removed = await vault.deduplicateEntries();577        return { ok: true, data: removed };578      }579      case "UPDATE_ENTRY": {580        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;581        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {582          return { ok: false, error: "invalid_payload" };583        }584        const { id, patch } = payload;585        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {586          return { ok: false, error: "invalid_payload" };587        }588        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);589        return { ok: true };590      }591      case "ADD_ADDITIONAL_URL": {592        const { id, url } = msg.payload as { id: string; url: string };593        const trimmed = typeof url === "string" ? url.trim() : "";594        if (!trimmed) return { ok: false, error: "url_required" };595        const existing = vault.getEntryById(id);596        if (!existing) return { ok: false, error: "entry_not_found" };597        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };598        const merged = [...(existing.additionalUrls ?? []), trimmed];599        await vault.updateEntry(id, { additionalUrls: merged });600        return { ok: true };601      }602      case "DELETE_ENTRY": {603        const { id } = msg.payload as { id: string };604        await vault.deleteEntry(id);605        return { ok: true };606      }607      case "GET_DELETED_ENTRIES":608        return { ok: true, data: vault.getDeletedEntries() };609      case "RESTORE_ENTRY": {610        const { id } = msg.payload as { id: string };611        await vault.restoreEntry(id);612        return { ok: true };613      }614      case "PURGE_ENTRY": {615        const { id } = msg.payload as { id: string };616        await vault.purgeEntry(id);617        return { ok: true };618      }619      case "PURGE_EXPIRED_TRASH": {620        const { retentionMs } = msg.payload as { retentionMs: number };621        const purged = await vault.purgeExpiredTrash(retentionMs);622        return { ok: true, data: purged };623      }624      case "SAVE_NOTE": {625        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };626        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };627        const now = Date.now();628        if (id) {629          const existing = vault.getEntryById(id);630          if (!existing) return { ok: false, error: "not_found" };631          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });632          return { ok: true, data: vault.getEntryById(id) };633        } else {634          const entry = await vault.addEntry({635            type: "note",636            title: title || "Untitled",637            notes: body,638            createdAt: now,639            modifiedAt: now,640          } as any);641          return { ok: true, data: entry };642        }643      }644      case "DELETE_NOTE": {645        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };646        const { id } = msg.payload as { id: string };647        await vault.deleteEntry(id);648        return { ok: true };649      }650      case "GET_NOTES": {651        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };652        const notes = vault.getEntries().filter(653          (e) => e.type === "note" && !e.deletedAt654        );655        return { ok: true, data: notes } as MessageResponse;656      }657      case "SEARCH_VAULT": {658        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };659        // AUD-002: shape-validate the payload before calling string methods.660        // A raw cast lets a malformed message crash the handler with TypeError.661        const { query } = (msg.payload ?? {}) as { query?: unknown };662        if (typeof query !== "string") {663          return { ok: false, error: "invalid_payload" };664        }665        const q = query.toLowerCase();666        const searchResults = vault.getEntries().filter(667          (e) =>668            !e.deletedAt &&669            (e.title.toLowerCase().includes(q) ||670              e.notes?.toLowerCase().includes(q) ||671              e.username?.toLowerCase().includes(q))672        );673        return { ok: true, data: searchResults } as MessageResponse;674      }675      case "PAIRING_COMPLETED": {676        const { deviceName, publicKeyHex, deviceIp } = (msg.payload ?? {}) as {677          deviceName?: string;678          publicKeyHex?: string;679          deviceIp?: string;680        };681        if (!publicKeyHex) return { ok: false, error: "publickeyhex_required" };682        // Only accept publicKeyHex values that just completed a real Noise NK683        // handshake (initiator or responder side). Without this gate, anyone684        // who can sendMessage to the background can pair an arbitrary key685        // (M13/SEC-005). Re-confirming an already-paired device is allowed686        // so legitimate update-IP retries still work.687        const alreadyPaired = (await getPairedDevices()).some(688          d => d.x25519PublicKey === publicKeyHex,689        );690        const verified = consumePendingPair(publicKeyHex);691        if (!verified && !alreadyPaired) {692          return { ok: false, error: "pairing_not_verified" };693        }694        const { setHasPaired: setPaired } = await import("./sync-storage");695        await setPaired();696        try {697          await addPairedDevice({698            deviceId: publicKeyHex,699            displayName: deviceName ?? "Unknown",700            x25519PublicKey: publicKeyHex,701            pairedAt: Date.now(),702            lastSeenAt: Date.now(),703            lastKnownIp: deviceIp,704          });705        } catch {706          // Already paired — update IP if provided707          if (deviceIp) {708            await updatePairedDevice(publicKeyHex, { lastKnownIp: deviceIp, lastSeenAt: Date.now() });709          }710        }711        return { ok: true };712      }713      case "AUTOFILL_QUERY": {714        if (!vault.isUnlocked()) {715          return { ok: false, error: "vault_locked" };716        }717        const { domain, includeAll, kind } = msg.payload as {718          domain: string;719          includeAll?: boolean;720          kind?: "login" | "card";721        };722        // kind="card": return saved cards as compact summaries for the723        // inline card silver platter. Cards are not domain-scoped — every724        // saved card is a candidate on every checkout page — so domain is725        // ignored when kind === "card".726        if (kind === "card") {727          const cards = vault.getEntries().filter((e) => e.type === "card");728          return {729            ok: true,730            data: cards.map((e) => ({731              id: e.id,732              title: e.cardNickname || e.title,733              cardholderName: e.cardholderName,734              last4: e.last4,735              expMonth: e.expMonth,736              expYear: e.expYear,737              network: e.network,738            })),739          };740        }741        // The inline selector fills username+password into a form. Passkey-742        // only entries have no password to fill; sign-in for those goes743        // through the WebAuthn path instead. Filter them out everywhere so744        // the user doesn't see four "GitHub" rows that mostly do nothing.745        // Notes and cards never belonged here either.746        const matches = (747          includeAll748            ? vault749                .getEntries()750                .filter((entry) => entry.type !== "note" && entry.type !== "card")751            : vault.queryDomain(domain)752        ).filter((entry) => !isPasskeyOnly(entry));753        return {754          ok: true,755          data: matches.map((e) =>756            includeAll757              ? {758                  id: e.id,759                  title: e.title,760                  hasPasskey: e.passkey !== undefined,761                }762              : {763                  id: e.id,764                  title: e.title,765                  username: e.username,766                  email: e.email,767                  url: e.url,768                  hasTotp: Boolean(e.totp),769                  hasPasskey: e.passkey !== undefined,770                }771          ),772        };773      }774      case "GET_ENTRY_FOR_FILL": {775        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };776        const { id } = msg.payload as { id: string };777        const entry = vault.getEntryById(id);778        if (!entry) return { ok: false, error: "entry_not_found" };779        // Passkey-only entries (passkey credential, no password) cannot be780        // filled into a form — sign-in goes through the WebAuthn path. A781        // login that ALSO has a passkey is still fillable for its password.782        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };783        // Strip the passkey credential from the response — content scripts784        // never need the private key, and there's no reason to expose the785        // public credential metadata over the boundary either.786        const { passkey: _strippedPasskey, ...safeEntry } = entry;787        return { ok: true, data: safeEntry };788      }789      case "COPY": {790        // AUD-002: shape-validate the payload before passing to the clipboard791        // helper. A raw cast lets a malformed message reach the clipboard API792        // with a non-string and throw.793        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {794          text?: unknown;795          label?: unknown;796          alreadyWritten?: unknown;797        };798        if (typeof text !== "string" || typeof label !== "string") {799          return { ok: false, error: "invalid_payload" };800        }801        await copyToClipboard(text, label, Boolean(alreadyWritten));802        return { ok: true };803      }804      case "CHECK_ALL_BREACHES": {805        const allEntries = vault.getEntries();806        const results: Record<string, number> = {};807        for (const entry of allEntries) {808          if (entry.type === "note") continue;809          if (!entry.password) continue;810          results[entry.id] = await vault.checkBreach(entry.password);811          // Small delay — be a good citizen to the HIBP API812          await new Promise((r) => setTimeout(r, 200));813        }814        // Persist any non-zero counts back to entries815        for (const [id, count] of Object.entries(results)) {816          const entry = vault.getEntryById(id);817          if (entry && (entry.breach ?? 0) !== count) {818            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });819          }820        }821        return { ok: true, data: results };822      }823      case "GET_SETTINGS":824        return { ok: true, data: await vault.ensureSettingsLoaded() };825      case "UPDATE_SETTINGS": {826        const patch = msg.payload;827        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {828          return { ok: false, error: "invalid_payload" };829        }830        await vault.updateSettings(patch as vault.VaultSettings);831        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {832          await setupAutoLock();833          if (vault.isUnlocked()) touchAutoLock();834        }835        return { ok: true };836      }837      case "GET_PENDING_PASSKEY":838        return { ok: true, data: await getPendingPasskeyRequest() };839      case "APPROVE_PASSKEY": {840        const { requestId } = msg.payload as { requestId: number };841        await resolvePendingPasskeyRequest(requestId, true);842        return { ok: true };843      }844      case "DENY_PASSKEY": {845        const { requestId } = msg.payload as { requestId: number };846        await resolvePendingPasskeyRequest(requestId, false);847        return { ok: true };848      }849      case "GET_PASSKEY_PROVIDER_STATE":850        return { ok: true, data: await getPasskeyProviderState() };851      case "SET_PASSKEY_PROVIDER_ENABLED": {852        const { enabled } = msg.payload as { enabled: boolean };853        // Disabling is always free; gating fires only when a free user is854        // trying to turn passkey interception on.855        if (enabled) {856          const gate = await requirePro("passkeys");857          if (!gate.allowed) return { ok: false, error: "pro_required" };858        }859        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };860      }861      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS862      // endpoint. Intentional product behavior — users configure their own863      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private864      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-865      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to866      // users that the entry title leaves the device when the canary fires.867      case "FIRE_CANARY_PING": {868        const { webhookUrl, entryTitle, trigger } = msg.payload as {869          webhookUrl: string;870          entryTitle: string;871          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";872        };873        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {874          return { ok: false, error: "invalid_webhook_url" };875        }876        const body = JSON.stringify({877          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",878          entry: entryTitle,879          trigger,880          timestamp: new Date().toISOString(),881          source: "peach-extension",882        });883        if (trigger === "test") {884          // Permitted outbound fetch: user-configured canary alert endpoint885          // (validated by isAllowedCanaryWebhookUrl above). This is the886          // only non-HIBP outbound call in the extension — see887          // Projects.md §3.7. Test pings are awaited so the UI can show888          // success/failure.889          try {890            const res = await fetch(webhookUrl, {891              method: "POST",892              headers: { "Content-Type": "application/json" },893              body,894            });895            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };896          } catch (err) {897            return { ok: false, error: err instanceof Error ? err.message : "network_error" };898          }899        }900        // Non-test triggers are fire-and-forget901        fetch(webhookUrl, {902          method: "POST",903          headers: { "Content-Type": "application/json" },904          body,905        }).catch(() => {});906        return { ok: true };907      }908      case "ACTIVATE_LICENSE": {909        const { key } = msg.payload as { key: string };910        const licenseInfo = await activateLicense(key);911        return { ok: true, data: licenseInfo };912      }913      case "GET_LICENSE": {914        const licenseInfo = await getLicenseInfo();915        return { ok: true, data: licenseInfo };916      }917      case "GET_LICENSE_KEY": {918        const key = await getLicenseKey();919        return { ok: true, data: key };920      }921      case "DEACTIVATE_LICENSE": {922        await deactivateLicense();923        return { ok: true };924      }925      case "SHOULD_PLAY_CELEBRATION": {926        const should = await shouldPlayCelebration();927        return { ok: true, data: should };928      }929      case "MARK_CELEBRATION_PLAYED": {930        await markCelebrationPlayed();931        return { ok: true };932      }933      case "GET_CODEX_VAULT_DATA": {934        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the935        // popup navigates to the License section without further coordination.936        const gate = await requirePro("codex");937        if (!gate.allowed) return { ok: false, error: "pro_required" };938        return await handleGetCodexVaultData();939      }940      case "ESTIMATE_CODEX_PAGES": {941        const gate = await requirePro("codex");942        if (!gate.allowed) return { ok: false, error: "pro_required" };943        return await handleEstimateCodexPages();944      }945      case "RESTORE_FROM_CODEX": {946        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still947        // be able to restore a vault that was printed by a Pro user.948        // DO NOT add a Pro gate here.949        const payload = msg.payload as CodexRestorePayload;950        return await handleRestoreFromCodex(payload);951      }952      case "OPEN_PRO_GATE": {953        // Content script requests: open popup and navigate to License section.954        const { feature } = (msg.payload ?? {}) as { feature?: string };955        if (chrome.storage.session) {956          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });957        }958        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }959        return { ok: true };960      }961      case "GET_IDENTITIES": {962        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };963        return { ok: true, data: vault.getIdentities() };964      }965      case "TOUCH_AUTO_LOCK": {966        // touchAutoLock() is already called by shouldRefreshAutoLock above;967        // this case just gives the popup a typed message to keep the session alive.968        return { ok: true };969      }970      case "GET_ADVANCED_HEALTH_REPORT": {971        const gate = await requirePro("advanced_health");972        if (!gate.allowed) return { ok: false, error: "pro_required" };973        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };974        const report = await buildAdvancedHealthReport(vault.getEntries());975        return { ok: true, data: report };976      }977      case "INITIATE_PASSWORD_CHANGE": {978        const gate = await requirePro("smart_password_change");979        if (!gate.allowed) return { ok: false, error: "pro_required" };980        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };981        const { id } = msg.payload as { id: string };982        const entry = vault.getEntryById(id);983        if (!entry) return { ok: false, error: "entry_not_found" };984        const url = resolveResetUrl(entry);985        if (!url) return { ok: false, error: "no_reset_url" };986        try {987          await chrome.tabs.create({ url });988          return { ok: true, data: { url } };989        } catch (err) {990          return {991            ok: false,992            error: err instanceof Error ? err.message : "failed_to_open_tab",993          };994        }995      }996      case "IS_DURESS_ENABLED": {997        const enabled = await vault.isDuressEnabled();998        return { ok: true, data: enabled };999      }1000      case "SETUP_DURESS": {1001        const { duressPassword } = msg.payload as { duressPassword: string };1002        await vault.setupDuress(duressPassword);1003        return { ok: true };1004      }1005      case "DISABLE_DURESS": {1006        await vault.disableDuress();1007        return { ok: true };1008      }1009      case "VERIFY_MAIN_PASSWORD": {1010        const { password } = msg.payload as { password: string };1011        const ok = await vault.verifyMainPassword(password);1012        return { ok: true, data: ok };1013      }1014      case "CHANGE_PASSWORD": {1015        const { currentPassword, newPassword } = msg.payload as {1016          currentPassword: string;1017          newPassword: string;1018        };1019        const changed = await vault.changePassword(currentPassword, newPassword);1020        return changed1021          ? { ok: true }1022          : { ok: false, error: "incorrect_current_password" };1023      }1024      case "GET_SITE_PASSWORD_POLICY": {1025        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1026        if (!tab?.id) return { ok: true, data: null };1027        try {1028          const response = await chrome.tabs.sendMessage(tab.id, {1029            type: "GET_SITE_PASSWORD_POLICY",1030          });1031          return (response as MessageResponse) ?? { ok: true, data: null };1032        } catch {1033          return { ok: true, data: null };1034        }1035      }1036      case "GET_SYNC_STATE": {1037        const pairedDevices = await getPairedDevices();1038        const trustedNetworks = await getTrustedNetworks();1039        const tailscale = await isOnTailscale();1040        const pro = await isProUser();10411042        let status: SyncStatus = "offline";1043        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {1044          if (pairedDevices.length === 0) {1045            status = "no_peers";1046          } else {1047            status = "synced";1048          }1049        } else {1050          status = "not_trusted";1051        }10521053        const lastSyncRaw = await storageGet("peach_last_sync_at");1054        const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN;1055        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined;10561057        return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } };1058      }1059      case "GET_PAIRED_DEVICES": {1060        const devices = await getPairedDevices();1061        return { ok: true, data: { devices } };1062      }1063      case "GET_SYNC_STATUS": {1064        const lastSyncRaw = await storageGet("peach_last_sync_at");1065        const lastSyncParsed = lastSyncRaw ? parseInt(lastSyncRaw, 10) : NaN;1066        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : null;1067        const status: 'up_to_date' | 'never' = lastSyncAt ? 'up_to_date' : 'never';1068        return { ok: true, data: { status, lastSyncAt } };1069      }1070      case "ACCEPT_PAIRING": {1071        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.1072        return { ok: true };1073      }1074      case "REMOVE_PAIRED_DEVICE": {1075        const { deviceId } = msg.payload as { deviceId: string };1076        await removePairedDevice(deviceId);1077        return { ok: true };1078      }1079      case "REMOVE_TRUSTED_NETWORK": {1080        const payload = msg.payload as1081          | { ssid?: unknown; bssid?: unknown; isTailscale?: unknown }1082          | null1083          | undefined;1084        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {1085          return { ok: false, error: "invalid_payload" };1086        }1087        const { ssid, bssid, isTailscale } = payload as { ssid?: string; bssid?: string; isTailscale?: boolean };1088        const networks = await getTrustedNetworks();1089        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 1090          (isTailscale ? n.isTailscale : n.ssid === ssid) && 1091          (!bssid || n.bssid === bssid)1092        );1093        if (network) {1094          await removeTrustedNetwork(network.addedAt);1095        }1096        return { ok: true };1097      }1098      case "MARK_NETWORK_TRUSTED": {1099        const network = await getCurrentNetwork();1100        await addTrustedNetwork({1101          ssid: network.ssid,1102          bssid: network.bssid,1103          isTailscale: network.isTailscale,1104          addedAt: Date.now(),1105        });1106        return { ok: true };1107      }1108      case "GET_INCOMING_PAIRING_REQUEST": {1109        const request = await getIncomingPairingRequest();1110        return { ok: true, data: request };1111      }1112      case "RESPOND_INCOMING_PAIRING": {1113        const { accept } = msg.payload as { accept: boolean };1114        const request = await getIncomingPairingRequest();1115        if (!request) return { ok: false, error: "no_pending_request" };1116        if (Date.now() > request.expiresAt) {1117          await clearIncomingPairingRequest();1118          return { ok: false, error: "expired" };1119        }1120        await clearIncomingPairingRequest();1121        if (accept) {1122          await addPairedDevice({1123            deviceId: request.publicKeyHex,1124            displayName: request.deviceName,1125            x25519PublicKey: request.publicKeyHex,1126            pairedAt: Date.now(),1127            lastSeenAt: Date.now(),1128          });1129        }1130        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };1131      }1132      case "START_PAIRING_SERVER": {1133        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.1134        const token = generateSixDigitToken();1135        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;1136        await setActivePairingToken({ token, expiresAt });1137        // Fire-and-forget subnet scan — finds the phone after it scans the QR1138        // and calls SCAN_PAIRING_QR to register the token with SyncPlugin.1139        if (!isNativePlatform()) {1140          void runPairingSubnetScan(token);1141        }1142        return { ok: true, data: { token, expiresAt } };1143      }1144      case "STOP_PAIRING_SERVER": {1145        try {1146          await setActivePairingToken(null);1147        } catch { /* best-effort */ }1148        return { ok: true };1149      }1150      case "GET_RECENT_PAIRING": {1151        const recent = await consumeRecentPairing();1152        return { ok: true, data: recent };1153      }1154      case "DEBUG_INJECT_INCOMING_PAIRING": {1155        // M14/SEC-007: blocked in production builds. The handler exists for1156        // Phase 7 banner UX rehearsal without a live native host; shipping1157        // it in production lets any background-message sender inject a1158        // synthetic pairing prompt. Allowed in 'development' and 'test'1159        // modes; vite sets MODE='production' for release builds.1160        if (import.meta.env.MODE === "production") {1161          return { ok: false, error: "not_available" };1162        }1163        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {1164          deviceName?: string;1165          publicKeyHex?: string;1166        };1167        if (!deviceName || !publicKeyHex) {1168          return { ok: false, error: "missing_payload" };1169        }1170        const now = Date.now();1171        await setIncomingPairingRequest({1172          deviceName,1173          publicKeyHex,1174          receivedAt: now,1175          expiresAt: now + 60_000,1176        });1177        return { ok: true };1178      }1179      case "RESET_SYNC_IDENTITY": {1180        const gate = await requirePro("sync");1181        if (!gate.allowed) return { ok: false, error: "pro_required" };1182        const devices = await getPairedDevices();1183        for (const device of devices) {1184          await removePairedDevice(device.deviceId);1185        }1186        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };1187      }1188      case "RECORD_MANUAL_SUMMON": {1189        const { domain } = msg.payload as { domain: string };1190        const settings = vault.getSettings();1191        const existing = settings.manualSummonDomains?.[domain];1192        const now = Date.now();1193        await vault.updateSettings({1194          manualSummonDomains: {1195            ...settings.manualSummonDomains,1196            [domain]: {1197              firstSummonedAt: existing?.firstSummonedAt ?? now,1198              summonCount: (existing?.summonCount ?? 0) + 1,1199              lastSummonedAt: now,1200            },1201          },1202        });1203        return { ok: true };1204      }1205      case "DECLINE_CARD_SAVE": {1206        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1207        await vault.declineCardSaveOffer(last4, expMonth, expYear);1208        return { ok: true };1209      }1210      case "IS_CARD_DECLINED": {1211        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1212        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1213        return { ok: true, data: declined };1214      }1215      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1216        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1217          rpId?: string;1218          rpName?: string;1219          userName?: string;1220          userDisplayName?: string;1221        };1222        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1223        return await initiateFirefoxPasskeyCreate({1224          rpId,1225          rpName: rpName ?? rpId,1226          userName,1227          userDisplayName,1228        });1229      }12301231      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1232        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1233        if (!payload) return { ok: false, error: "missing_payload" };1234        return await completeFirefoxPasskeyCreate(payload);1235      }12361237      case "PASSKEY_OFFER_DECLINE": {1238        const { domain } = (msg.payload ?? {}) as { domain?: string };1239        if (!domain) return { ok: false, error: "domain_required" };1240        await recordPasskeyOfferDecline(domain);1241        return { ok: true };1242      }12431244      case "GET_PASSKEY_OFFER_DECLINED": {1245        const { domain } = (msg.payload ?? {}) as { domain?: string };1246        if (!domain) return { ok: false, error: "domain_required" };1247        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1248      }12491250      case "PASSKEY_HAS_CREDENTIALS": {1251        const payload = msg.payload as {1252          rpId?: string;1253          allowCredentials?: Array<{ id: string; type?: string }>;1254        } | undefined;1255        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1256        return await handlePasskeyHasCredentials({1257          rpId: payload.rpId,1258          allowCredentials: payload.allowCredentials ?? [],1259        });1260      }12611262      case "PASSKEY_CREATE": {1263        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1264        if (!payload?.rpId || !payload?.userName) {1265          return { ok: false, error: "rpid_and_username_required" };1266        }1267        return await handleFirefoxPasskeyCreate(payload);1268      }12691270      case "PASSKEY_GET": {1271        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1272        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1273        return await handleFirefoxPasskeyGet(payload);1274      }12751276      case "PASSKEY_AUTH_RESPONSE": {1277        const { requestId, approved } = (msg.payload ?? {}) as {1278          requestId?: string | number;1279          approved?: boolean;1280        };1281        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1282          return { ok: false, error: 'requestId and approved required' };1283        }1284        await resolvePendingPasskeyRequest(Number(requestId), approved);1285        return { ok: true };1286      }12871288      case "GET_PASSKEY_FOR_DOMAIN": {1289        const { domain } = (msg.payload ?? {}) as { domain?: string };1290        if (!domain) return { ok: false, error: "domain_required" };1291        if (!vault.isUnlocked()) return { ok: true, data: null };1292        const match = vault1293          .getEntries()1294          .find((entry) => entry.passkey?.rpId === domain);1295        if (!match || !match.passkey) return { ok: true, data: null };1296        // Slim shape — only the fields State 11 needs. Never expose private1297        // key material, even though this is locked behind isUnlocked.1298        return {1299          ok: true,1300          data: {1301            rpId: match.passkey.rpId,1302            userName: match.passkey.userName,1303            browser: match.passkey.browser,1304          },1305        };1306      }13071308      case "DESTROY_VAULT": {1309        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1310        // storage.local.clear() wipes every Peach key (slots, settings, license,1311        // onboarded flag, history, sync state, declined cards, recall, etc.);1312        // session.clear() wipes pending passkey requests + pro-notice queues.1313        // Caller (Panic.tsx) handles UI navigation back to onboarding.1314        vault.lock();1315        await storageClear();1316        await vault.clearVaultHistory();1317        if (chrome.storage.session) {1318          await chrome.storage.session.clear();1319        }1320        return { ok: true };1321      }13221323      case "SUBMIT_FEEDBACK": {1324        const { category, message, version, browser } = msg.payload as {1325          category: string;1326          message: string;1327          version: string;1328          browser: string;1329        };1330        if (!message.trim()) return { ok: false, error: "message_empty" };1331        if (!FEEDBACK_ENDPOINT) return { ok: true };1332        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1333          return { ok: false, error: "invalid_feedback_endpoint" };1334        }1335        try {1336          const res = await fetch(FEEDBACK_ENDPOINT, {1337            method: "POST",1338            headers: { "Content-Type": "application/json" },1339            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1340          });1341          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1342        } catch (err) {1343          return { ok: false, error: err instanceof Error ? err.message : "network_error" };1344        }1345      }1346      case "TRIGGER_SYNC": {1347        const gate = await requirePro("sync");1348        if (!gate.allowed) return { ok: false, error: "pro_required" };1349        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };13501351        if (isNativePlatform()) {1352          // Phone is the server — ensure it's listening for desktop connections.1353          syncBridge()?.ensureServerRunning?.();1354          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };1355        }13561357        // Desktop: iterate all paired devices and sync with each.1358        const paired = await getPairedDevices();1359        if (!paired.length) return { ok: true, data: { syncedCount: 0, reason: "no_paired_devices" } };13601361        const subnet = await getLocalSubnet();1362        const results: Array<{ device: string } & SyncResult> = [];13631364        for (const device of paired) {1365          if (!device.x25519PublicKey) continue;13661367          let result: SyncResult;13681369          // Fast path — use last known IP1370          if (device.lastKnownIp) {1371            result = await doVaultSync(device.lastKnownIp, device.x25519PublicKey);1372          } else {1373            result = { status: 'errored', applied: false, error: 'no_ip' };1374          }13751376          // Discovery path — scan if fast path failed1377          if (result.status === 'errored' && subnet) {1378            const newIp = await discoverDevice(subnet, device.x25519PublicKey);1379            if (newIp) {1380              await updatePairedDevice(device.x25519PublicKey, { lastKnownIp: newIp });1381              result = await doVaultSync(newIp, device.x25519PublicKey);1382            }1383          }13841385          if (result.status === 'completed') {1386            await updatePairedDevice(device.x25519PublicKey, {1387              lastSeenAt: Date.now(),1388              lastSyncAt: Date.now(),1389            });1390          }13911392          results.push({ device: device.displayName, ...result });1393        }13941395        const syncedCount = results.filter(r => r.status === 'completed').length;1396        if (syncedCount > 0) {1397          await chrome.storage.local.set({ peach_last_sync_at: String(Date.now()) });1398        }1399        return { ok: true, data: { syncedCount, results } };1400      }1401      // Android-only: biometric unlock with pre-derived key.1402      case "UNLOCK_WITH_KEY": {1403        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1404        if (!isNativePlatform()) {1405          return { ok: false, error: "desktop_only_uses_password" };1406        }1407        try {1408          const result = await vault.unlockWithKey(masterKeyHex);1409          if (result.ok) {1410            onVaultUnlocked();1411            await publishInMemoryVault(result.entries);1412          }1413          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1414        } catch {1415          return { ok: false, error: "invalid_key" };1416        }1417      }1418      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1419      case "GET_DERIVED_KEY": {1420        if (!isNativePlatform()) {1421          return { ok: false, error: "android_only" };1422        }1423        if (!vault.isUnlocked()) {1424          return { ok: false, error: "vault_locked" };1425        }1426        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1427      }1428      // Android: scanned a QR containing a desktop pairing token.1429      case "SCAN_PAIRING_QR": {1430        if (!isNativePlatform()) {1431          return { ok: false, error: "android_only" };1432        }1433        const { token } = msg.payload as { token: string };1434        syncBridge()?.startPairingSession?.({ token });1435        return { ok: true };1436      }1437      // Android: desktop opened a sync connection to the phone's WS server.1438      // Run the responder side of the vault exchange.1439      case "SYNC_SESSION_STARTED": {1440        if (!isNativePlatform()) return { ok: false };1441        if (!vault.isUnlocked()) {1442          return { ok: false, error: "vault_locked" };1443        }1444        const { connectionId } = (msg.payload ?? {}) as { connectionId?: string };1445        if (!connectionId) return { ok: false, error: "missing_connection_id" };14461447        const transport = createAndroidResponderTransport(connectionId);14481449        // Authenticate the initiator before exchanging any vault data. The1450        // native side has already completed the Noise NK handshake; auth1451        // frames here ride the Noise transport (native encrypts/decrypts).1452        const identity = await vault.getSyncIdentity();1453        try {1454          // CAUTION: noiseSessionStub is a structural placeholder — the real1455          // Noise NK handshake runs natively, so JS never holds the session1456          // object. performResponderAuth currently `void`s this argument,1457          // which is why identity-passthrough encrypt/decrypt and a zero1458          // handshake hash are safe. If performResponderAuth is ever updated1459          // to actually use this argument, this auth path will silently break1460          // (no type error). Revisit this stub if that helper changes.1461          const noiseSessionStub = {1462            encrypt: (b: Uint8Array) => b,1463            decrypt: (b: Uint8Array) => b,1464            handshakeHash: new Uint8Array(32),1465          };1466          const { initiatorPublicKey } = await performResponderAuth(1467            noiseSessionStub,1468            identity.privateKeyBytes,1469            identity.publicKeyBytes,1470            transport.send,1471            transport.receive,1472          );1473          const initiatorHex = noiseBytesToHex(initiatorPublicKey);1474          const paired = await getPairedDevices();1475          if (!paired.some(d => d.x25519PublicKey === initiatorHex)) {1476            await transport.close();1477            return { ok: false, error: "sync_rejected_unpaired_initiator" };1478          }1479          // Initiator just proved control of the matching static key; mark it1480          // as a verified handshake so a follow-up PAIRING_COMPLETED message1481          // can be trusted (M13/SEC-005).1482          markPairingHandshakeVerified(initiatorHex);1483        } catch (err) {1484          await transport.close();1485          return { ok: false, error: `sync_auth_failed: ${String(err)}` };1486        }14871488        const result = await runBlobSyncSession('responder', transport, buildSyncDeps());1489        if (result.applied) {1490          await publishInMemoryVault(vault.getEntries());1491        }1492        return { ok: true, data: result };1493      }1494      // Android: returns the phone's WiFi IP address.1495      case "GET_LOCAL_IP": {1496        if (!isNativePlatform()) {1497          return { ok: false, error: "android_only" };1498        }1499        const { ip } = (await syncBridge()?.getLocalIp?.()) ?? { ip: "" };1500        return { ok: true, data: { ip } };1501      }1502      case "GET_IDENTITY_SUGGESTIONS": {1503        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1504        const entries = vault.getEntries();1505        const suggestions = buildIdentitySuggestions(entries);1506        return { ok: true, data: { suggestions } };1507      }1508      case "POPULATE_INLINE_VAULT": {1509        if (!isNativePlatform()) return { ok: false };1510        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1511        const entries = vault.getEntries();1512        await publishInMemoryVault(entries);1513        return { ok: true };1514      }1515      case "ML_INIT":1516        return { ok: true };15171518      case "ML_PREDICT_BATCH": {1519        // AUD-002: shape-validate before forwarding to the ML helper.1520        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1521        if (!Array.isArray(featuresArray)) {1522          return { ok: false, error: "invalid_payload" };1523        }1524        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1525      }15261527      default:1528        return { ok: false, error: "unknown_message_type" };1529    }1530  } catch (err) {1531    return {1532      ok: false,1533      error: err instanceof Error ? err.message : "operation_failed",1534    };1535  }1536}15371538// --- Mobile platform helpers ---15391540// Android: populates the in-memory vault used by PeachAutofillService.1541async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1542  const plugin = nativePlugin<{1543    setEntries?: (args: {1544      entries: Array<{1545        id: string;1546        title: string;1547        username: string;1548        email: string;1549        password: string;1550        url: string;1551        totp: string;1552        additionalUrls: string[];1553      }>;1554    }) => Promise<void>;1555  }>("InMemoryVaultPlugin");1556  if (!plugin?.setEntries) return;1557  await plugin.setEntries({1558    entries: entries.map((e) => ({1559      id: e.id,1560      title: e.title ?? "",1561      username: e.username ?? "",1562      email: (e as VaultEntry & { email?: string }).email ?? "",1563      password: e.password ?? "",1564      url: e.url ?? "",1565      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1566      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1567    })),1568  });1569}15701571// Android: clear the autofill in-memory store on lock.1572async function clearInMemoryVault(): Promise<void> {1573  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1574  if (!plugin?.clearEntries) return;1575  await plugin.clearEntries();1576}15771578interface SyncBridge {1579  ensureServerRunning?: () => void;1580  startPairingSession?: (args: { token: string }) => void;1581  getLocalIp?: () => Promise<{ ip: string }>;1582  sendToConnection?: (args: { connectionId: string; data: string }) => Promise<void>;1583  addListener?: (event: string, handler: (data: Record<string, string>) => void) => void;1584}15851586// Resolve the Capacitor SyncPlugin at call time — module-load resolution1587// races with Capacitor's plugin registration on the Android WebView.1588function syncBridge(): SyncBridge | null {1589  return nativePlugin<SyncBridge>("SyncPlugin");1590}15911592// Build a SyncTransport for the Android responder path — the phone's WS server1593// already has an open connection from the desktop. We send back via1594// SyncPlugin.sendToConnection and receive via the peach:sync-frame queue.1595const androidSyncFrameQueues = new Map<string, Array<(frame: string) => void>>();15961597export function deliverAndroidSyncFrame(connectionId: string, frame: string): void {1598  const queue = androidSyncFrameQueues.get(connectionId);1599  if (queue?.length) queue.shift()!(frame);1600}16011602function createAndroidResponderTransport(connectionId: string) {1603  const pendingReceivers: Array<(frame: string) => void> = [];1604  androidSyncFrameQueues.set(connectionId, pendingReceivers);16051606  return {1607    send: async (data: Uint8Array) => {1608      await syncBridge()?.sendToConnection?.({ connectionId, data: bytesToBase64(data) });1609    },1610    receive: (): Promise<Uint8Array> => new Promise((res) => {1611      pendingReceivers.push((frame) => {1612        res(frame ? base64ToBytes(frame) : new Uint8Array(0));1613      });1614    }),1615    close: async () => {1616      androidSyncFrameQueues.delete(connectionId);1617    },1618  };1619}16201621// Returns username use-counts from the vault, sorted by frequency. Each row1622// also carries the entry's email so the popup can suggest the email/username1623// pair the user has actually used together.1624function buildIdentitySuggestions(1625  entries: VaultEntry[],1626): Array<{ email: string; username: string; count: number }> {1627  const usernameCounts = new Map<string, number>();1628  const usernameEmail = new Map<string, string>();1629  for (const entry of entries) {1630    const username = entry.username ?? "";1631    const email = (entry as VaultEntry & { email?: string }).email ?? "";1632    if (!username && !email) continue;1633    const key = username || email;1634    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1635    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1636  }1637  return Array.from(usernameCounts.entries())1638    .sort((a, b) => b[1] - a[1])1639    .map(([username, count]) => ({1640      email: usernameEmail.get(username) ?? "",1641      username,1642      count,1643    }));1644}16451646/** Notify all content scripts that the vault just became available. */1647function broadcastToContentScripts(message: { type: string }): void {1648  if (!chrome.tabs?.query) return;1649  chrome.tabs.query({}, (tabs) => {1650    for (const tab of tabs) {1651      if (tab.id !== undefined) {1652        chrome.tabs.sendMessage(tab.id, message).catch(() => {1653          // Tab may not have a content script — silently ignore1654        });1655      }1656    }1657  });1658}16591660function shouldRefreshAutoLock(type: MessageType): boolean {1661  return (1662    type !== "HAS_VAULT" &&1663    type !== "IS_UNLOCKED" &&1664    type !== "GET_VAULT_STATUS" &&1665    type !== "LOCK" &&1666    type !== "UPDATE_SETTINGS" &&1667    type !== "GET_PENDING_PASSKEY" &&1668    type !== "GET_PASSKEY_PROVIDER_STATE" &&1669    type !== "DECLINE_CARD_SAVE" &&1670    type !== "IS_CARD_DECLINED" &&1671    type !== "SUBMIT_FEEDBACK"1672  );1673}16741675function isAllowedCanaryWebhookUrl(value: string): boolean {1676  try {1677    const url = new URL(value);1678    if (url.protocol !== "https:") return false;16791680    const hostname = url.hostname.toLowerCase();1681    if (1682      hostname === "localhost" ||1683      hostname.endsWith(".localhost") ||1684      isPrivateIpv4(hostname) ||1685      isPrivateIpv6(hostname)1686    ) {1687      return false;1688    }16891690    return true;1691  } catch {1692    return false;1693  }1694}16951696function isPrivateIpv4(hostname: string): boolean {1697  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1698    return true;1699  }17001701  const octets = hostname.split(".").map((part) => Number(part));1702  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1703    return false;1704  }17051706  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1707}17081709function isPrivateIpv6(hostname: string): boolean {1710  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1711  return (1712    normalized === "::1" ||1713    normalized.startsWith("fc") ||1714    normalized.startsWith("fd") ||1715    normalized.startsWith("fe80:")1716  );1717}