messages.ts

65.7 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        const { query } = msg.payload as { query: string };660        const q = query.toLowerCase();661        const searchResults = vault.getEntries().filter(662          (e) =>663            !e.deletedAt &&664            (e.title.toLowerCase().includes(q) ||665              e.notes?.toLowerCase().includes(q) ||666              e.username?.toLowerCase().includes(q))667        );668        return { ok: true, data: searchResults } as MessageResponse;669      }670      case "PAIRING_COMPLETED": {671        const { deviceName, publicKeyHex, deviceIp } = (msg.payload ?? {}) as {672          deviceName?: string;673          publicKeyHex?: string;674          deviceIp?: string;675        };676        if (!publicKeyHex) return { ok: false, error: "publickeyhex_required" };677        // Only accept publicKeyHex values that just completed a real Noise NK678        // handshake (initiator or responder side). Without this gate, anyone679        // who can sendMessage to the background can pair an arbitrary key680        // (M13/SEC-005). Re-confirming an already-paired device is allowed681        // so legitimate update-IP retries still work.682        const alreadyPaired = (await getPairedDevices()).some(683          d => d.x25519PublicKey === publicKeyHex,684        );685        const verified = consumePendingPair(publicKeyHex);686        if (!verified && !alreadyPaired) {687          return { ok: false, error: "pairing_not_verified" };688        }689        const { setHasPaired: setPaired } = await import("./sync-storage");690        await setPaired();691        try {692          await addPairedDevice({693            deviceId: publicKeyHex,694            displayName: deviceName ?? "Unknown",695            x25519PublicKey: publicKeyHex,696            pairedAt: Date.now(),697            lastSeenAt: Date.now(),698            lastKnownIp: deviceIp,699          });700        } catch {701          // Already paired — update IP if provided702          if (deviceIp) {703            await updatePairedDevice(publicKeyHex, { lastKnownIp: deviceIp, lastSeenAt: Date.now() });704          }705        }706        return { ok: true };707      }708      case "AUTOFILL_QUERY": {709        if (!vault.isUnlocked()) {710          return { ok: false, error: "vault_locked" };711        }712        const { domain, includeAll, kind } = msg.payload as {713          domain: string;714          includeAll?: boolean;715          kind?: "login" | "card";716        };717        // kind="card": return saved cards as compact summaries for the718        // inline card silver platter. Cards are not domain-scoped — every719        // saved card is a candidate on every checkout page — so domain is720        // ignored when kind === "card".721        if (kind === "card") {722          const cards = vault.getEntries().filter((e) => e.type === "card");723          return {724            ok: true,725            data: cards.map((e) => ({726              id: e.id,727              title: e.cardNickname || e.title,728              cardholderName: e.cardholderName,729              last4: e.last4,730              expMonth: e.expMonth,731              expYear: e.expYear,732              network: e.network,733            })),734          };735        }736        // The inline selector fills username+password into a form. Passkey-737        // only entries have no password to fill; sign-in for those goes738        // through the WebAuthn path instead. Filter them out everywhere so739        // the user doesn't see four "GitHub" rows that mostly do nothing.740        // Notes and cards never belonged here either.741        const matches = (742          includeAll743            ? vault744                .getEntries()745                .filter((entry) => entry.type !== "note" && entry.type !== "card")746            : vault.queryDomain(domain)747        ).filter((entry) => !isPasskeyOnly(entry));748        return {749          ok: true,750          data: matches.map((e) =>751            includeAll752              ? {753                  id: e.id,754                  title: e.title,755                  hasPasskey: e.passkey !== undefined,756                }757              : {758                  id: e.id,759                  title: e.title,760                  username: e.username,761                  email: e.email,762                  url: e.url,763                  hasTotp: Boolean(e.totp),764                  hasPasskey: e.passkey !== undefined,765                }766          ),767        };768      }769      case "GET_ENTRY_FOR_FILL": {770        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };771        const { id } = msg.payload as { id: string };772        const entry = vault.getEntryById(id);773        if (!entry) return { ok: false, error: "entry_not_found" };774        // Passkey-only entries (passkey credential, no password) cannot be775        // filled into a form — sign-in goes through the WebAuthn path. A776        // login that ALSO has a passkey is still fillable for its password.777        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };778        // Strip the passkey credential from the response — content scripts779        // never need the private key, and there's no reason to expose the780        // public credential metadata over the boundary either.781        const { passkey: _strippedPasskey, ...safeEntry } = entry;782        return { ok: true, data: safeEntry };783      }784      case "COPY": {785        const { text, label, alreadyWritten } = msg.payload as {786          text: string;787          label: string;788          alreadyWritten?: boolean;789        };790        await copyToClipboard(text, label, Boolean(alreadyWritten));791        return { ok: true };792      }793      case "CHECK_ALL_BREACHES": {794        const allEntries = vault.getEntries();795        const results: Record<string, number> = {};796        for (const entry of allEntries) {797          if (entry.type === "note") continue;798          if (!entry.password) continue;799          results[entry.id] = await vault.checkBreach(entry.password);800          // Small delay — be a good citizen to the HIBP API801          await new Promise((r) => setTimeout(r, 200));802        }803        // Persist any non-zero counts back to entries804        for (const [id, count] of Object.entries(results)) {805          const entry = vault.getEntryById(id);806          if (entry && (entry.breach ?? 0) !== count) {807            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });808          }809        }810        return { ok: true, data: results };811      }812      case "GET_SETTINGS":813        return { ok: true, data: await vault.ensureSettingsLoaded() };814      case "UPDATE_SETTINGS": {815        const patch = msg.payload;816        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {817          return { ok: false, error: "invalid_payload" };818        }819        await vault.updateSettings(patch as vault.VaultSettings);820        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {821          await setupAutoLock();822          if (vault.isUnlocked()) touchAutoLock();823        }824        return { ok: true };825      }826      case "GET_PENDING_PASSKEY":827        return { ok: true, data: await getPendingPasskeyRequest() };828      case "APPROVE_PASSKEY": {829        const { requestId } = msg.payload as { requestId: number };830        await resolvePendingPasskeyRequest(requestId, true);831        return { ok: true };832      }833      case "DENY_PASSKEY": {834        const { requestId } = msg.payload as { requestId: number };835        await resolvePendingPasskeyRequest(requestId, false);836        return { ok: true };837      }838      case "GET_PASSKEY_PROVIDER_STATE":839        return { ok: true, data: await getPasskeyProviderState() };840      case "SET_PASSKEY_PROVIDER_ENABLED": {841        const { enabled } = msg.payload as { enabled: boolean };842        // Disabling is always free; gating fires only when a free user is843        // trying to turn passkey interception on.844        if (enabled) {845          const gate = await requirePro("passkeys");846          if (!gate.allowed) return { ok: false, error: "pro_required" };847        }848        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };849      }850      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS851      // endpoint. Intentional product behavior — users configure their own852      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private853      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-854      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to855      // users that the entry title leaves the device when the canary fires.856      case "FIRE_CANARY_PING": {857        const { webhookUrl, entryTitle, trigger } = msg.payload as {858          webhookUrl: string;859          entryTitle: string;860          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";861        };862        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {863          return { ok: false, error: "invalid_webhook_url" };864        }865        const body = JSON.stringify({866          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",867          entry: entryTitle,868          trigger,869          timestamp: new Date().toISOString(),870          source: "peach-extension",871        });872        if (trigger === "test") {873          // Permitted outbound fetch: user-configured canary alert endpoint874          // (validated by isAllowedCanaryWebhookUrl above). This is the875          // only non-HIBP outbound call in the extension — see876          // Projects.md §3.7. Test pings are awaited so the UI can show877          // success/failure.878          try {879            const res = await fetch(webhookUrl, {880              method: "POST",881              headers: { "Content-Type": "application/json" },882              body,883            });884            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };885          } catch (err) {886            return { ok: false, error: err instanceof Error ? err.message : "network_error" };887          }888        }889        // Non-test triggers are fire-and-forget890        fetch(webhookUrl, {891          method: "POST",892          headers: { "Content-Type": "application/json" },893          body,894        }).catch(() => {});895        return { ok: true };896      }897      case "ACTIVATE_LICENSE": {898        const { key } = msg.payload as { key: string };899        const licenseInfo = await activateLicense(key);900        return { ok: true, data: licenseInfo };901      }902      case "GET_LICENSE": {903        const licenseInfo = await getLicenseInfo();904        return { ok: true, data: licenseInfo };905      }906      case "GET_LICENSE_KEY": {907        const key = await getLicenseKey();908        return { ok: true, data: key };909      }910      case "DEACTIVATE_LICENSE": {911        await deactivateLicense();912        return { ok: true };913      }914      case "SHOULD_PLAY_CELEBRATION": {915        const should = await shouldPlayCelebration();916        return { ok: true, data: should };917      }918      case "MARK_CELEBRATION_PLAYED": {919        await markCelebrationPlayed();920        return { ok: true };921      }922      case "GET_CODEX_VAULT_DATA": {923        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the924        // popup navigates to the License section without further coordination.925        const gate = await requirePro("codex");926        if (!gate.allowed) return { ok: false, error: "pro_required" };927        return await handleGetCodexVaultData();928      }929      case "ESTIMATE_CODEX_PAGES": {930        const gate = await requirePro("codex");931        if (!gate.allowed) return { ok: false, error: "pro_required" };932        return await handleEstimateCodexPages();933      }934      case "RESTORE_FROM_CODEX": {935        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still936        // be able to restore a vault that was printed by a Pro user.937        // DO NOT add a Pro gate here.938        const payload = msg.payload as CodexRestorePayload;939        return await handleRestoreFromCodex(payload);940      }941      case "OPEN_PRO_GATE": {942        // Content script requests: open popup and navigate to License section.943        const { feature } = (msg.payload ?? {}) as { feature?: string };944        if (chrome.storage.session) {945          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });946        }947        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }948        return { ok: true };949      }950      case "GET_IDENTITIES": {951        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };952        return { ok: true, data: vault.getIdentities() };953      }954      case "TOUCH_AUTO_LOCK": {955        // touchAutoLock() is already called by shouldRefreshAutoLock above;956        // this case just gives the popup a typed message to keep the session alive.957        return { ok: true };958      }959      case "GET_ADVANCED_HEALTH_REPORT": {960        const gate = await requirePro("advanced_health");961        if (!gate.allowed) return { ok: false, error: "pro_required" };962        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };963        const report = await buildAdvancedHealthReport(vault.getEntries());964        return { ok: true, data: report };965      }966      case "INITIATE_PASSWORD_CHANGE": {967        const gate = await requirePro("smart_password_change");968        if (!gate.allowed) return { ok: false, error: "pro_required" };969        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };970        const { id } = msg.payload as { id: string };971        const entry = vault.getEntryById(id);972        if (!entry) return { ok: false, error: "entry_not_found" };973        const url = resolveResetUrl(entry);974        if (!url) return { ok: false, error: "no_reset_url" };975        try {976          await chrome.tabs.create({ url });977          return { ok: true, data: { url } };978        } catch (err) {979          return {980            ok: false,981            error: err instanceof Error ? err.message : "failed_to_open_tab",982          };983        }984      }985      case "IS_DURESS_ENABLED": {986        const enabled = await vault.isDuressEnabled();987        return { ok: true, data: enabled };988      }989      case "SETUP_DURESS": {990        const { duressPassword } = msg.payload as { duressPassword: string };991        await vault.setupDuress(duressPassword);992        return { ok: true };993      }994      case "DISABLE_DURESS": {995        await vault.disableDuress();996        return { ok: true };997      }998      case "VERIFY_MAIN_PASSWORD": {999        const { password } = msg.payload as { password: string };1000        const ok = await vault.verifyMainPassword(password);1001        return { ok: true, data: ok };1002      }1003      case "CHANGE_PASSWORD": {1004        const { currentPassword, newPassword } = msg.payload as {1005          currentPassword: string;1006          newPassword: string;1007        };1008        const changed = await vault.changePassword(currentPassword, newPassword);1009        return changed1010          ? { ok: true }1011          : { ok: false, error: "incorrect_current_password" };1012      }1013      case "GET_SITE_PASSWORD_POLICY": {1014        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1015        if (!tab?.id) return { ok: true, data: null };1016        try {1017          const response = await chrome.tabs.sendMessage(tab.id, {1018            type: "GET_SITE_PASSWORD_POLICY",1019          });1020          return (response as MessageResponse) ?? { ok: true, data: null };1021        } catch {1022          return { ok: true, data: null };1023        }1024      }1025      case "GET_SYNC_STATE": {1026        const pairedDevices = await getPairedDevices();1027        const trustedNetworks = await getTrustedNetworks();1028        const tailscale = await isOnTailscale();1029        const pro = await isProUser();10301031        let status: SyncStatus = "offline";1032        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {1033          if (pairedDevices.length === 0) {1034            status = "no_peers";1035          } else {1036            status = "synced";1037          }1038        } else {1039          status = "not_trusted";1040        }10411042        const lastSyncRaw = await storageGet("peach_last_sync_at");1043        const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN;1044        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined;10451046        return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } };1047      }1048      case "GET_PAIRED_DEVICES": {1049        const devices = await getPairedDevices();1050        return { ok: true, data: { devices } };1051      }1052      case "GET_SYNC_STATUS": {1053        const lastSyncRaw = await storageGet("peach_last_sync_at");1054        const lastSyncParsed = lastSyncRaw ? parseInt(lastSyncRaw, 10) : NaN;1055        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : null;1056        const status: 'up_to_date' | 'never' = lastSyncAt ? 'up_to_date' : 'never';1057        return { ok: true, data: { status, lastSyncAt } };1058      }1059      case "ACCEPT_PAIRING": {1060        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.1061        return { ok: true };1062      }1063      case "REMOVE_PAIRED_DEVICE": {1064        const { deviceId } = msg.payload as { deviceId: string };1065        await removePairedDevice(deviceId);1066        return { ok: true };1067      }1068      case "REMOVE_TRUSTED_NETWORK": {1069        const payload = msg.payload as1070          | { ssid?: unknown; bssid?: unknown; isTailscale?: unknown }1071          | null1072          | undefined;1073        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {1074          return { ok: false, error: "invalid_payload" };1075        }1076        const { ssid, bssid, isTailscale } = payload as { ssid?: string; bssid?: string; isTailscale?: boolean };1077        const networks = await getTrustedNetworks();1078        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 1079          (isTailscale ? n.isTailscale : n.ssid === ssid) && 1080          (!bssid || n.bssid === bssid)1081        );1082        if (network) {1083          await removeTrustedNetwork(network.addedAt);1084        }1085        return { ok: true };1086      }1087      case "MARK_NETWORK_TRUSTED": {1088        const network = await getCurrentNetwork();1089        await addTrustedNetwork({1090          ssid: network.ssid,1091          bssid: network.bssid,1092          isTailscale: network.isTailscale,1093          addedAt: Date.now(),1094        });1095        return { ok: true };1096      }1097      case "GET_INCOMING_PAIRING_REQUEST": {1098        const request = await getIncomingPairingRequest();1099        return { ok: true, data: request };1100      }1101      case "RESPOND_INCOMING_PAIRING": {1102        const { accept } = msg.payload as { accept: boolean };1103        const request = await getIncomingPairingRequest();1104        if (!request) return { ok: false, error: "no_pending_request" };1105        if (Date.now() > request.expiresAt) {1106          await clearIncomingPairingRequest();1107          return { ok: false, error: "expired" };1108        }1109        await clearIncomingPairingRequest();1110        if (accept) {1111          await addPairedDevice({1112            deviceId: request.publicKeyHex,1113            displayName: request.deviceName,1114            x25519PublicKey: request.publicKeyHex,1115            pairedAt: Date.now(),1116            lastSeenAt: Date.now(),1117          });1118        }1119        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };1120      }1121      case "START_PAIRING_SERVER": {1122        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.1123        const token = generateSixDigitToken();1124        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;1125        await setActivePairingToken({ token, expiresAt });1126        // Fire-and-forget subnet scan — finds the phone after it scans the QR1127        // and calls SCAN_PAIRING_QR to register the token with SyncPlugin.1128        if (!isNativePlatform()) {1129          void runPairingSubnetScan(token);1130        }1131        return { ok: true, data: { token, expiresAt } };1132      }1133      case "STOP_PAIRING_SERVER": {1134        try {1135          await setActivePairingToken(null);1136        } catch { /* best-effort */ }1137        return { ok: true };1138      }1139      case "GET_RECENT_PAIRING": {1140        const recent = await consumeRecentPairing();1141        return { ok: true, data: recent };1142      }1143      case "DEBUG_INJECT_INCOMING_PAIRING": {1144        // M14/SEC-007: blocked in production builds. The handler exists for1145        // Phase 7 banner UX rehearsal without a live native host; shipping1146        // it in production lets any background-message sender inject a1147        // synthetic pairing prompt. Allowed in 'development' and 'test'1148        // modes; vite sets MODE='production' for release builds.1149        if (import.meta.env.MODE === "production") {1150          return { ok: false, error: "not_available" };1151        }1152        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {1153          deviceName?: string;1154          publicKeyHex?: string;1155        };1156        if (!deviceName || !publicKeyHex) {1157          return { ok: false, error: "missing_payload" };1158        }1159        const now = Date.now();1160        await setIncomingPairingRequest({1161          deviceName,1162          publicKeyHex,1163          receivedAt: now,1164          expiresAt: now + 60_000,1165        });1166        return { ok: true };1167      }1168      case "RESET_SYNC_IDENTITY": {1169        const gate = await requirePro("sync");1170        if (!gate.allowed) return { ok: false, error: "pro_required" };1171        const devices = await getPairedDevices();1172        for (const device of devices) {1173          await removePairedDevice(device.deviceId);1174        }1175        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };1176      }1177      case "RECORD_MANUAL_SUMMON": {1178        const { domain } = msg.payload as { domain: string };1179        const settings = vault.getSettings();1180        const existing = settings.manualSummonDomains?.[domain];1181        const now = Date.now();1182        await vault.updateSettings({1183          manualSummonDomains: {1184            ...settings.manualSummonDomains,1185            [domain]: {1186              firstSummonedAt: existing?.firstSummonedAt ?? now,1187              summonCount: (existing?.summonCount ?? 0) + 1,1188              lastSummonedAt: now,1189            },1190          },1191        });1192        return { ok: true };1193      }1194      case "DECLINE_CARD_SAVE": {1195        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1196        await vault.declineCardSaveOffer(last4, expMonth, expYear);1197        return { ok: true };1198      }1199      case "IS_CARD_DECLINED": {1200        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1201        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1202        return { ok: true, data: declined };1203      }1204      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1205        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1206          rpId?: string;1207          rpName?: string;1208          userName?: string;1209          userDisplayName?: string;1210        };1211        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1212        return await initiateFirefoxPasskeyCreate({1213          rpId,1214          rpName: rpName ?? rpId,1215          userName,1216          userDisplayName,1217        });1218      }12191220      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1221        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1222        if (!payload) return { ok: false, error: "missing_payload" };1223        return await completeFirefoxPasskeyCreate(payload);1224      }12251226      case "PASSKEY_OFFER_DECLINE": {1227        const { domain } = (msg.payload ?? {}) as { domain?: string };1228        if (!domain) return { ok: false, error: "domain_required" };1229        await recordPasskeyOfferDecline(domain);1230        return { ok: true };1231      }12321233      case "GET_PASSKEY_OFFER_DECLINED": {1234        const { domain } = (msg.payload ?? {}) as { domain?: string };1235        if (!domain) return { ok: false, error: "domain_required" };1236        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1237      }12381239      case "PASSKEY_HAS_CREDENTIALS": {1240        const payload = msg.payload as {1241          rpId?: string;1242          allowCredentials?: Array<{ id: string; type?: string }>;1243        } | undefined;1244        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1245        return await handlePasskeyHasCredentials({1246          rpId: payload.rpId,1247          allowCredentials: payload.allowCredentials ?? [],1248        });1249      }12501251      case "PASSKEY_CREATE": {1252        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1253        if (!payload?.rpId || !payload?.userName) {1254          return { ok: false, error: "rpid_and_username_required" };1255        }1256        return await handleFirefoxPasskeyCreate(payload);1257      }12581259      case "PASSKEY_GET": {1260        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1261        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1262        return await handleFirefoxPasskeyGet(payload);1263      }12641265      case "PASSKEY_AUTH_RESPONSE": {1266        const { requestId, approved } = (msg.payload ?? {}) as {1267          requestId?: string | number;1268          approved?: boolean;1269        };1270        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1271          return { ok: false, error: 'requestId and approved required' };1272        }1273        await resolvePendingPasskeyRequest(Number(requestId), approved);1274        return { ok: true };1275      }12761277      case "GET_PASSKEY_FOR_DOMAIN": {1278        const { domain } = (msg.payload ?? {}) as { domain?: string };1279        if (!domain) return { ok: false, error: "domain_required" };1280        if (!vault.isUnlocked()) return { ok: true, data: null };1281        const match = vault1282          .getEntries()1283          .find((entry) => entry.passkey?.rpId === domain);1284        if (!match || !match.passkey) return { ok: true, data: null };1285        // Slim shape — only the fields State 11 needs. Never expose private1286        // key material, even though this is locked behind isUnlocked.1287        return {1288          ok: true,1289          data: {1290            rpId: match.passkey.rpId,1291            userName: match.passkey.userName,1292            browser: match.passkey.browser,1293          },1294        };1295      }12961297      case "DESTROY_VAULT": {1298        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1299        // storage.local.clear() wipes every Peach key (slots, settings, license,1300        // onboarded flag, history, sync state, declined cards, recall, etc.);1301        // session.clear() wipes pending passkey requests + pro-notice queues.1302        // Caller (Panic.tsx) handles UI navigation back to onboarding.1303        vault.lock();1304        await storageClear();1305        await vault.clearVaultHistory();1306        if (chrome.storage.session) {1307          await chrome.storage.session.clear();1308        }1309        return { ok: true };1310      }13111312      case "SUBMIT_FEEDBACK": {1313        const { category, message, version, browser } = msg.payload as {1314          category: string;1315          message: string;1316          version: string;1317          browser: string;1318        };1319        if (!message.trim()) return { ok: false, error: "message_empty" };1320        if (!FEEDBACK_ENDPOINT) return { ok: true };1321        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1322          return { ok: false, error: "invalid_feedback_endpoint" };1323        }1324        try {1325          const res = await fetch(FEEDBACK_ENDPOINT, {1326            method: "POST",1327            headers: { "Content-Type": "application/json" },1328            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1329          });1330          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1331        } catch (err) {1332          return { ok: false, error: err instanceof Error ? err.message : "network_error" };1333        }1334      }1335      case "TRIGGER_SYNC": {1336        const gate = await requirePro("sync");1337        if (!gate.allowed) return { ok: false, error: "pro_required" };1338        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };13391340        if (isNativePlatform()) {1341          // Phone is the server — ensure it's listening for desktop connections.1342          syncBridge()?.ensureServerRunning?.();1343          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };1344        }13451346        // Desktop: iterate all paired devices and sync with each.1347        const paired = await getPairedDevices();1348        if (!paired.length) return { ok: true, data: { syncedCount: 0, reason: "no_paired_devices" } };13491350        const subnet = await getLocalSubnet();1351        const results: Array<{ device: string } & SyncResult> = [];13521353        for (const device of paired) {1354          if (!device.x25519PublicKey) continue;13551356          let result: SyncResult;13571358          // Fast path — use last known IP1359          if (device.lastKnownIp) {1360            result = await doVaultSync(device.lastKnownIp, device.x25519PublicKey);1361          } else {1362            result = { status: 'errored', applied: false, error: 'no_ip' };1363          }13641365          // Discovery path — scan if fast path failed1366          if (result.status === 'errored' && subnet) {1367            const newIp = await discoverDevice(subnet, device.x25519PublicKey);1368            if (newIp) {1369              await updatePairedDevice(device.x25519PublicKey, { lastKnownIp: newIp });1370              result = await doVaultSync(newIp, device.x25519PublicKey);1371            }1372          }13731374          if (result.status === 'completed') {1375            await updatePairedDevice(device.x25519PublicKey, {1376              lastSeenAt: Date.now(),1377              lastSyncAt: Date.now(),1378            });1379          }13801381          results.push({ device: device.displayName, ...result });1382        }13831384        const syncedCount = results.filter(r => r.status === 'completed').length;1385        if (syncedCount > 0) {1386          await chrome.storage.local.set({ peach_last_sync_at: String(Date.now()) });1387        }1388        return { ok: true, data: { syncedCount, results } };1389      }1390      // Android-only: biometric unlock with pre-derived key.1391      case "UNLOCK_WITH_KEY": {1392        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1393        if (!isNativePlatform()) {1394          return { ok: false, error: "desktop_only_uses_password" };1395        }1396        try {1397          const result = await vault.unlockWithKey(masterKeyHex);1398          if (result.ok) {1399            onVaultUnlocked();1400            await publishInMemoryVault(result.entries);1401          }1402          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1403        } catch {1404          return { ok: false, error: "invalid_key" };1405        }1406      }1407      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1408      case "GET_DERIVED_KEY": {1409        if (!isNativePlatform()) {1410          return { ok: false, error: "android_only" };1411        }1412        if (!vault.isUnlocked()) {1413          return { ok: false, error: "vault_locked" };1414        }1415        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1416      }1417      // Android: scanned a QR containing a desktop pairing token.1418      case "SCAN_PAIRING_QR": {1419        if (!isNativePlatform()) {1420          return { ok: false, error: "android_only" };1421        }1422        const { token } = msg.payload as { token: string };1423        syncBridge()?.startPairingSession?.({ token });1424        return { ok: true };1425      }1426      // Android: desktop opened a sync connection to the phone's WS server.1427      // Run the responder side of the vault exchange.1428      case "SYNC_SESSION_STARTED": {1429        if (!isNativePlatform()) return { ok: false };1430        if (!vault.isUnlocked()) {1431          return { ok: false, error: "vault_locked" };1432        }1433        const { connectionId } = (msg.payload ?? {}) as { connectionId?: string };1434        if (!connectionId) return { ok: false, error: "missing_connection_id" };14351436        const transport = createAndroidResponderTransport(connectionId);14371438        // Authenticate the initiator before exchanging any vault data. The1439        // native side has already completed the Noise NK handshake; auth1440        // frames here ride the Noise transport (native encrypts/decrypts).1441        const identity = await vault.getSyncIdentity();1442        try {1443          // CAUTION: noiseSessionStub is a structural placeholder — the real1444          // Noise NK handshake runs natively, so JS never holds the session1445          // object. performResponderAuth currently `void`s this argument,1446          // which is why identity-passthrough encrypt/decrypt and a zero1447          // handshake hash are safe. If performResponderAuth is ever updated1448          // to actually use this argument, this auth path will silently break1449          // (no type error). Revisit this stub if that helper changes.1450          const noiseSessionStub = {1451            encrypt: (b: Uint8Array) => b,1452            decrypt: (b: Uint8Array) => b,1453            handshakeHash: new Uint8Array(32),1454          };1455          const { initiatorPublicKey } = await performResponderAuth(1456            noiseSessionStub,1457            identity.privateKeyBytes,1458            identity.publicKeyBytes,1459            transport.send,1460            transport.receive,1461          );1462          const initiatorHex = noiseBytesToHex(initiatorPublicKey);1463          const paired = await getPairedDevices();1464          if (!paired.some(d => d.x25519PublicKey === initiatorHex)) {1465            await transport.close();1466            return { ok: false, error: "sync_rejected_unpaired_initiator" };1467          }1468          // Initiator just proved control of the matching static key; mark it1469          // as a verified handshake so a follow-up PAIRING_COMPLETED message1470          // can be trusted (M13/SEC-005).1471          markPairingHandshakeVerified(initiatorHex);1472        } catch (err) {1473          await transport.close();1474          return { ok: false, error: `sync_auth_failed: ${String(err)}` };1475        }14761477        const result = await runBlobSyncSession('responder', transport, buildSyncDeps());1478        if (result.applied) {1479          await publishInMemoryVault(vault.getEntries());1480        }1481        return { ok: true, data: result };1482      }1483      // Android: returns the phone's WiFi IP address.1484      case "GET_LOCAL_IP": {1485        if (!isNativePlatform()) {1486          return { ok: false, error: "android_only" };1487        }1488        const { ip } = (await syncBridge()?.getLocalIp?.()) ?? { ip: "" };1489        return { ok: true, data: { ip } };1490      }1491      case "GET_IDENTITY_SUGGESTIONS": {1492        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1493        const entries = vault.getEntries();1494        const suggestions = buildIdentitySuggestions(entries);1495        return { ok: true, data: { suggestions } };1496      }1497      case "POPULATE_INLINE_VAULT": {1498        if (!isNativePlatform()) return { ok: false };1499        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1500        const entries = vault.getEntries();1501        await publishInMemoryVault(entries);1502        return { ok: true };1503      }1504      case "ML_INIT":1505        return { ok: true };15061507      case "ML_PREDICT_BATCH": {1508        const { featuresArray } = msg.payload as { featuresArray: MLFieldFeatures[] };1509        return { ok: true, data: mlPredictBatch(featuresArray) };1510      }15111512      default:1513        return { ok: false, error: "unknown_message_type" };1514    }1515  } catch (err) {1516    return {1517      ok: false,1518      error: err instanceof Error ? err.message : "operation_failed",1519    };1520  }1521}15221523// --- Mobile platform helpers ---15241525// Android: populates the in-memory vault used by PeachAutofillService.1526async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1527  const plugin = nativePlugin<{1528    setEntries?: (args: {1529      entries: Array<{1530        id: string;1531        title: string;1532        username: string;1533        email: string;1534        password: string;1535        url: string;1536        totp: string;1537        additionalUrls: string[];1538      }>;1539    }) => Promise<void>;1540  }>("InMemoryVaultPlugin");1541  if (!plugin?.setEntries) return;1542  await plugin.setEntries({1543    entries: entries.map((e) => ({1544      id: e.id,1545      title: e.title ?? "",1546      username: e.username ?? "",1547      email: (e as VaultEntry & { email?: string }).email ?? "",1548      password: e.password ?? "",1549      url: e.url ?? "",1550      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1551      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1552    })),1553  });1554}15551556// Android: clear the autofill in-memory store on lock.1557async function clearInMemoryVault(): Promise<void> {1558  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1559  if (!plugin?.clearEntries) return;1560  await plugin.clearEntries();1561}15621563interface SyncBridge {1564  ensureServerRunning?: () => void;1565  startPairingSession?: (args: { token: string }) => void;1566  getLocalIp?: () => Promise<{ ip: string }>;1567  sendToConnection?: (args: { connectionId: string; data: string }) => Promise<void>;1568  addListener?: (event: string, handler: (data: Record<string, string>) => void) => void;1569}15701571// Resolve the Capacitor SyncPlugin at call time — module-load resolution1572// races with Capacitor's plugin registration on the Android WebView.1573function syncBridge(): SyncBridge | null {1574  return nativePlugin<SyncBridge>("SyncPlugin");1575}15761577// Build a SyncTransport for the Android responder path — the phone's WS server1578// already has an open connection from the desktop. We send back via1579// SyncPlugin.sendToConnection and receive via the peach:sync-frame queue.1580const androidSyncFrameQueues = new Map<string, Array<(frame: string) => void>>();15811582export function deliverAndroidSyncFrame(connectionId: string, frame: string): void {1583  const queue = androidSyncFrameQueues.get(connectionId);1584  if (queue?.length) queue.shift()!(frame);1585}15861587function createAndroidResponderTransport(connectionId: string) {1588  const pendingReceivers: Array<(frame: string) => void> = [];1589  androidSyncFrameQueues.set(connectionId, pendingReceivers);15901591  return {1592    send: async (data: Uint8Array) => {1593      await syncBridge()?.sendToConnection?.({ connectionId, data: bytesToBase64(data) });1594    },1595    receive: (): Promise<Uint8Array> => new Promise((res) => {1596      pendingReceivers.push((frame) => {1597        res(frame ? base64ToBytes(frame) : new Uint8Array(0));1598      });1599    }),1600    close: async () => {1601      androidSyncFrameQueues.delete(connectionId);1602    },1603  };1604}16051606// Returns username use-counts from the vault, sorted by frequency. Each row1607// also carries the entry's email so the popup can suggest the email/username1608// pair the user has actually used together.1609function buildIdentitySuggestions(1610  entries: VaultEntry[],1611): Array<{ email: string; username: string; count: number }> {1612  const usernameCounts = new Map<string, number>();1613  const usernameEmail = new Map<string, string>();1614  for (const entry of entries) {1615    const username = entry.username ?? "";1616    const email = (entry as VaultEntry & { email?: string }).email ?? "";1617    if (!username && !email) continue;1618    const key = username || email;1619    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1620    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1621  }1622  return Array.from(usernameCounts.entries())1623    .sort((a, b) => b[1] - a[1])1624    .map(([username, count]) => ({1625      email: usernameEmail.get(username) ?? "",1626      username,1627      count,1628    }));1629}16301631/** Notify all content scripts that the vault just became available. */1632function broadcastToContentScripts(message: { type: string }): void {1633  if (!chrome.tabs?.query) return;1634  chrome.tabs.query({}, (tabs) => {1635    for (const tab of tabs) {1636      if (tab.id !== undefined) {1637        chrome.tabs.sendMessage(tab.id, message).catch(() => {1638          // Tab may not have a content script — silently ignore1639        });1640      }1641    }1642  });1643}16441645function shouldRefreshAutoLock(type: MessageType): boolean {1646  return (1647    type !== "HAS_VAULT" &&1648    type !== "IS_UNLOCKED" &&1649    type !== "GET_VAULT_STATUS" &&1650    type !== "LOCK" &&1651    type !== "UPDATE_SETTINGS" &&1652    type !== "GET_PENDING_PASSKEY" &&1653    type !== "GET_PASSKEY_PROVIDER_STATE" &&1654    type !== "DECLINE_CARD_SAVE" &&1655    type !== "IS_CARD_DECLINED" &&1656    type !== "SUBMIT_FEEDBACK"1657  );1658}16591660function isAllowedCanaryWebhookUrl(value: string): boolean {1661  try {1662    const url = new URL(value);1663    if (url.protocol !== "https:") return false;16641665    const hostname = url.hostname.toLowerCase();1666    if (1667      hostname === "localhost" ||1668      hostname.endsWith(".localhost") ||1669      isPrivateIpv4(hostname) ||1670      isPrivateIpv6(hostname)1671    ) {1672      return false;1673    }16741675    return true;1676  } catch {1677    return false;1678  }1679}16801681function isPrivateIpv4(hostname: string): boolean {1682  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1683    return true;1684  }16851686  const octets = hostname.split(".").map((part) => Number(part));1687  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1688    return false;1689  }16901691  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1692}16931694function isPrivateIpv6(hostname: string): boolean {1695  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1696  return (1697    normalized === "::1" ||1698    normalized.startsWith("fc") ||1699    normalized.startsWith("fd") ||1700    normalized.startsWith("fe80:")1701  );1702}