messages.ts

63.2 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard } from "./clipboard";13import { setupAutoLock, touchAutoLock } from "./alarms";14import * as vault from "./vault";15import {16  handleEstimateCodexPages,17  handleGetCodexVaultData,18  handleRestoreFromCodex,19} from "./codex-handlers";20import type { CodexRestorePayload } from "../shared/codex-types";21import {22  activateLicense,23  deactivateLicense,24  getLicenseInfo,25  getLicenseKey,26  isProUser,27  markCelebrationPlayed,28  shouldPlayCelebration,29} from "./license";30import {31  cancelFirefoxPasskeyCreate,32  completeFirefoxPasskeyCreate,33  getPasskeyProviderState,34  getPendingPasskeyRequest,35  handleFirefoxPasskeyCreate,36  handleFirefoxPasskeyGet,37  handlePasskeyHasCredentials,38  initiateFirefoxPasskeyCreate,39  isPasskeyOfferDeclined,40  onVaultUnlocked,41  recordPasskeyOfferDecline,42  resolvePendingPasskeyRequest,43  setPasskeyProviderEnabled,44} from "./passkey";45import { buildAdvancedHealthReport, resolveResetUrl } from "./health";46import { storageClear, storageGet } from "../shared/storage";47import { findInvalidWords } from "../shared/recovery-words";48import {49  addPairedDevice,50  addTrustedNetwork,51  clearIncomingPairingRequest,52  getIncomingPairingRequest,53  getPairedDevices,54  getTrustedNetworks,55  removePairedDevice,56  removeTrustedNetwork,57  setIncomingPairingRequest,58  updatePairedDevice,59} from "./sync-storage";60import { getCurrentNetwork, isOnTailscale } from "./sync-network";61import {62  consumeRecentPairing,63  setActivePairingToken,64} from "./pairing-server-state";65import type {66  Message,67  MessageResponse,68  MessageType,69  ProFeature,70  VaultEntry,71} from "../shared/types";72import { isPasskeyOnly } from "../shared/types";73import type { SyncStatus, SyncableDevice } from "../shared/sync-types";74import { isNativePlatform, nativePlugin } from "../shared/native";75import { runBlobSyncSession, type SyncResult } from "./sync-coordinator";76import type { SyncDeps } from "./sync-coordinator";77import { createWebSocketSyncTransport } from "../shared/websocket-sync-transport";78import { performResponderAuth, bytesToHex as noiseBytesToHex } from "../shared/noise-js";79import { getLocalSubnet, discoverDevice, scanForPairingPhone } from "../shared/local-network";80import { predictBatch as mlPredictBatch } from "./ml";81import type { MLFieldFeatures } from "../shared/ml";82import { base64ToBytes, bytesToBase64 } from "../shared/sync-wire";8384/**85 * The single Pro gate. Every gated handler calls this first; the broadcast86 * lets the popup react (navigate to the License section, highlight the87 * relevant feature). Background never touches the popup view directly —88 * the popup owns navigation. See Projects.md "Pro gate rule".89 */90async function requirePro(91  feature: ProFeature,92  trigger: "user" | "background" = "user"93): Promise<{ allowed: boolean }> {94  if (await isProUser()) return { allowed: true };9596  if (trigger === "user") {97    // User deliberately triggered this feature — redirect the popup immediately.98    chrome.runtime99      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })100      .catch(() => {101        // Popup may be closed — the gate signal is best-effort.102      });103  } else {104    // Background trigger (e.g. passive sync initiation) — no popup is open.105    // Queue a notice so the next popup open shows a soft banner instead of106    // silently failing.107    if (chrome.storage.session) {108      chrome.storage.session109        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })110        .catch(() => {});111    }112  }113114  return { allowed: false };115}116117// ---------------------------------------------------------------------------118// Local device name. Peers see this string in PAIR_REQUEST / PAIR_ACCEPT and119// next to the device in their paired-devices list. Default to a platform-aware120// fallback when the user hasn't set one explicitly.121const DEVICE_NAME_KEY = "peach_device_name";122123async function getLocalDeviceName(): Promise<string> {124  try {125    const stored = await chrome.storage.local.get(DEVICE_NAME_KEY);126    const value = (stored as Record<string, string | undefined>)[DEVICE_NAME_KEY];127    if (typeof value === "string" && value.trim()) return value.trim();128  } catch {129    // fall through to default130  }131  return "Peach";132}133134// ---------------------------------------------------------------------------135// 6-digit code pairing.136137const PAIRING_TOKEN_TTL_MS = 5 * 60 * 1000;138139140function generateSixDigitToken(): string {141  // crypto.getRandomValues, not Math.random — the token is the only secret142  // protecting the pairing window from a same-LAN attacker. 6 decimal digits143  // is 1 in 1,000,000; combined with a 5-minute TTL and pairing-mode gating144  // on the responder this is the right tradeoff between UX and security.145  const buf = new Uint32Array(1);146  crypto.getRandomValues(buf);147  const value = buf[0] % 1_000_000;148  return value.toString().padStart(6, "0");149}150151// ---------------------------------------------------------------------------152// Peer discovery glue (Phase 7 popup pairing flow).153154const PRIVATE_IPV4_RANGES = [155  { prefix: "10." },156  { prefix: "127." },157  { prefix: "169.254." },158  { prefix: "192.168." },159];160161// Empty disables network submission while the UI continues to function as a162// no-op (the handler returns ok:true without calling fetch). When set, the163// URL is validated by `isAllowedCanaryWebhookUrl` before any request, so the164// same private-IP/HTTPS rules that gate canary webhooks apply here.165const FEEDBACK_ENDPOINT = "";166167// ---------------------------------------------------------------------------168// Sync helpers169// ---------------------------------------------------------------------------170171/**172 * Short-lived registry of x25519 public keys that just completed a real Noise173 * NK handshake + initiator-auth proof. The PAIRING_COMPLETED handler must174 * find the supplied publicKeyHex here before it will call addPairedDevice —175 * otherwise an attacker could forge the message and pair an arbitrary key176 * (M13/SEC-005).177 *178 * Entries auto-expire after 30s. Each entry is consumed on first successful179 * PAIRING_COMPLETED so a single handshake cannot pair twice.180 */181const PENDING_PAIRS = new Map<string, ReturnType<typeof setTimeout>>();182const PENDING_PAIR_TTL_MS = 30_000;183184export function markPairingHandshakeVerified(publicKeyHex: string): void {185  if (!publicKeyHex) return;186  const existing = PENDING_PAIRS.get(publicKeyHex);187  if (existing) clearTimeout(existing);188  const t = setTimeout(() => PENDING_PAIRS.delete(publicKeyHex), PENDING_PAIR_TTL_MS);189  PENDING_PAIRS.set(publicKeyHex, t);190}191192function consumePendingPair(publicKeyHex: string): boolean {193  const t = PENDING_PAIRS.get(publicKeyHex);194  if (!t) return false;195  clearTimeout(t);196  PENDING_PAIRS.delete(publicKeyHex);197  return true;198}199200export function buildSyncDeps(): SyncDeps {201  return {202    isVaultUnlocked: () => vault.isUnlocked(),203    getVaultBlobForSync: async () => {204      const base = await vault.getVaultBlobForSync();205      if (!base) return null;206      const paired = await getPairedDevices();207      return {208        ...base,209        devices: paired210          .filter(d => d.x25519PublicKey)211          .map(d => ({212            publicKeyHex: d.x25519PublicKey,213            deviceName: d.displayName,214            pairedAt: d.pairedAt,215          })),216      };217    },218    applyIncomingVault: async (blob, ts, license, devices) => {219      const applied = await vault.applyIncomingVault(blob, ts, license);220      if (devices?.length) await mergeDeviceRegistry(devices);221      if (applied) {222        const reloaded = await vault.reloadEntriesAfterSync();223        if (!reloaded) {224          // The remote vault was encrypted under a different key (the remote225          // changed password). Our in-memory entries are now stale and cannot226          // be re-encrypted without overwriting the just-applied blob. Lock227          // to force a re-unlock with the new password (H3/COR-005).228          vault.lock();229          chrome.runtime230            .sendMessage({ type: "VAULT_RELOCK_AFTER_SYNC" })231            .catch(() => {});232        }233      }234      return applied;235    },236  };237}238239async function doVaultSync(ip: string, publicKeyHex: string): Promise<SyncResult> {240  // Defensive: refuse to drive a sync to a key not in the paired-devices241  // list. The WebSocket transport already authenticates the peer via Noise242  // NK + the initiator auth proof (H1), but pinning the key to the paired243  // set here makes "talk to anyone matching this static key" the only path244  // to vault application — there is no orphan-key window between pair and245  // sync (M11/COR-014).246  const paired = await getPairedDevices();247  if (!paired.some(d => d.x25519PublicKey === publicKeyHex)) {248    return { status: 'errored', applied: false, error: 'remote_not_paired' };249  }250  try {251    const identity = await vault.getSyncIdentity();252    const transport = await createWebSocketSyncTransport(253      `ws://${ip}:44100`,254      publicKeyHex,255      identity.privateKeyBytes,256      identity.publicKeyBytes,257    );258    const result = await runBlobSyncSession('initiator', transport, buildSyncDeps());259    // Reaching this point means createWebSocketSyncTransport completed both260    // the Noise NK handshake and the initiator-auth proof — the remote261    // proved possession of the matching static key (M13/SEC-005).262    if (result.status === 'completed') {263      markPairingHandshakeVerified(publicKeyHex);264    }265    return result;266  } catch (err) {267    return { status: 'errored', applied: false, error: String(err) };268  }269}270271async function mergeDeviceRegistry(incoming: SyncableDevice[]): Promise<void> {272  const existing = await getPairedDevices();273  const existingKeys = new Set(existing.map(d => d.x25519PublicKey));274  for (const device of incoming) {275    if (!existingKeys.has(device.publicKeyHex)) {276      await addPairedDevice({277        deviceId: device.publicKeyHex,278        displayName: device.deviceName,279        x25519PublicKey: device.publicKeyHex,280        pairedAt: device.pairedAt,281        lastSeenAt: 0,282        lastKnownIp: '',283      }).catch(() => {});284    }285  }286}287288// Background pairing scan — runs after START_PAIRING_SERVER fires on desktop.289// Scans the local subnet for a phone that has accepted the pairing token,290// stores it, runs the initial vault exchange, then notifies the popup.291async function runPairingSubnetScan(token: string): Promise<void> {292  const subnet = await getLocalSubnet();293  if (!subnet) return;294295  const found = await scanForPairingPhone(subnet, token);296  if (!found) return;297298  const { ip, publicKeyHex } = found;299300  try {301    await addPairedDevice({302      deviceId: publicKeyHex,303      displayName: 'Peach',304      x25519PublicKey: publicKeyHex,305      pairedAt: Date.now(),306      lastSeenAt: Date.now(),307      lastKnownIp: ip,308    });309  } catch {310    // Already paired — update IP311    await updatePairedDevice(publicKeyHex, { lastKnownIp: ip, lastSeenAt: Date.now() });312  }313314  // Immediate vault exchange — the free one-time transfer315  await doVaultSync(ip, publicKeyHex);316317  chrome.runtime.sendMessage({318    type: 'PAIRING_COMPLETED',319    payload: { deviceName: 'Peach', publicKeyHex, deviceIp: ip },320  }).catch(() => {});321}322323export function setupMessageHandler(): void {324  chrome.runtime.onMessage.addListener(325    (msg: unknown, sender, sendResponse) => {326      if (!isMessage(msg)) {327        sendResponse({ ok: false, error: "invalid message" });328        return true;329      }330      handleMessage(msg, sender)331        .then(sendResponse)332        .catch((err) =>333          sendResponse({334            ok: false,335            error: err instanceof Error ? err.message : String(err),336          })337        );338      return true;339    }340  );341342  // Android: the chrome shim queues sendMessage calls until this handler is343  // registered. Without this hookup, every message hangs on Capacitor builds.344  // eslint-disable-next-line @typescript-eslint/no-explicit-any345  const reg = (globalThis as any).__peachRegisterMessageHandler;346  if (typeof reg === "function") {347    reg(async (m: unknown) => {348      if (!isMessage(m)) return { ok: false, error: "invalid message" };349      try {350        return await handleMessage(m);351      } catch (err) {352        return {353          ok: false,354          error: err instanceof Error ? err.message : String(err),355        };356      }357    });358  }359360  // Android: subscribe to SyncPlugin events.361  if (isNativePlatform()) {362    const syncPlug = nativePlugin<{363      addListener: (364        event: string,365        handler: (data: Record<string, string>) => void366      ) => void;367    }>("SyncPlugin");368369    // Pairing probe answered — store the paired device (desktop, no IP needed370    // since the desktop never acts as a WS server).371    syncPlug?.addListener?.("peach:pair-probe-answered", (data) => {372      const deviceName = data.deviceName ?? "Peach";373      const publicKeyHex = data.publicKeyHex ?? "";374      // Native handled the pairing handshake — trust this entry into the375      // verified-handshake set (M13/SEC-005). The subsequent PAIRING_COMPLETED376      // message will consume it.377      if (publicKeyHex) markPairingHandshakeVerified(publicKeyHex);378      void (async () => {379        const { addPairedDevice, setHasPaired: setPaired } = await import("./sync-storage");380        await addPairedDevice({381          deviceId: publicKeyHex || (data.connectionId ?? "unknown"),382          displayName: deviceName,383          x25519PublicKey: publicKeyHex,384          pairedAt: Date.now(),385          lastSeenAt: Date.now(),386        }).catch(() => {});387        await setPaired();388        chrome.runtime.sendMessage({389          type: "PAIRING_COMPLETED",390          payload: { deviceName, publicKeyHex },391        }).catch(() => {});392      })();393    });394395    // Sync frame received — route to the waiting responder session.396    syncPlug?.addListener?.("peach:sync-frame", (data) => {397      const { connectionId, frame } = data;398      if (connectionId && frame) deliverAndroidSyncFrame(connectionId, frame);399    });400401    // Sync session started (SYNC_HELLO received by SyncPlugin) — dispatch as402    // a background message so SYNC_SESSION_STARTED handler runs the responder.403    syncPlug?.addListener?.("peach:sync-session-started", (data) => {404      const { connectionId } = data;405      if (!connectionId) return;406      void handleMessage({ type: "SYNC_SESSION_STARTED", payload: { connectionId } });407    });408  }409}410411function isMessage(m: unknown): m is Message {412  return typeof m === "object" && m !== null && "type" in m;413}414415export async function handleMessage(416  msg: Message,417  sender: Partial<chrome.runtime.MessageSender> = {}418): Promise<MessageResponse> {419  try {420    // Validate sender — only allow messages from our extension pages/scripts.421    // `sender.id` is undefined for messages originating from extension UI422    // (popup/options), which is legitimate; reject only when it is defined423    // and does not match our extension id.424    if (425      sender.id !== undefined &&426      sender.id !== chrome.runtime.id427    ) {428      return { ok: false, error: "invalid sender" };429    }430431    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {432      touchAutoLock();433    }434435    switch (msg.type) {436      case "CREATE_VAULT": {437        const { password } = msg.payload as { password: string };438        await vault.createVault(password);439        await setupAutoLock();440        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });441        onVaultUnlocked();442        return { ok: true };443      }444      case "UNLOCK": {445        const { password } = msg.payload as { password: string };446        const ok = await vault.unlock(password);447        if (ok) {448          await setupAutoLock();449          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });450          onVaultUnlocked();451          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());452          return { ok: true };453        }454        // Distinguish corruption from wrong password so the popup can offer455        // a history-restore path instead of falsely accusing the user of456        // mistyping (M7/COR-007).457        const failure = vault.consumeLastUnlockFailureReason();458        if (failure) {459          return {460            ok: false,461            error: "vault_corrupted",462            canRestoreFromHistory: true,463          } as MessageResponse;464        }465        return { ok: false };466      }467      case "VALIDATE_RECOVERY_WORDS": {468        const { words } = msg.payload as { words: string[] };469        const invalid = findInvalidWords(words);470        return { ok: true, data: { valid: invalid.length === 0, invalid } };471      }472      case "GET_RECOVERY_WORDS": {473        // Must be unlocked and have recovery set up (vault must be v2.12+).474        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };475        try {476          const words = await vault.getRecoveryWords();477          return { ok: true, data: words };478        } catch (e) {479          // pre-v2.12 vault that hasn't migrated480          return { ok: false, error: "recovery_not_setup" };481        }482      }483      case "RECOVER_WITH_WORDS": {484        // User has lost their password but has their 12 recovery words.485        // We: (1) validate the words, (2) re-encrypt vault with new password.486        const { words, newPassword } = msg.payload as {487          words: string[];488          newPassword: string;489        };490        const stored = await vault.loadSlotA();491        if (!stored) return { ok: false, error: "no vault" };492        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {493          return { ok: false, error: "recovery_not_setup" };494        }495        // Unwrap the root key from the recovery escrow.496        try {497          await vault.unwrapRootKeyForRecovery(498            stored.recovery_wrapped_root_key,499            stored.recovery_nonce ?? "",500            stored.recovery_tag ?? "",501            stored.recovery_salt,502            words503          );504        } catch {505          return { ok: false, error: "invalid_recovery_words" };506        }507        // Re-key: derive fresh salt + key from new password.508        const newSalt = vault.generateSalt();509        const newKey = await vault.deriveKey(newPassword, newSalt);510        // Re-wrap root key under the new password's derived key so the same511        // recovery words continue to work after the password change.512        await vault.rewrapRootKeyForPassword(newKey, newSalt);513        // Re-encrypt vault entries with the new key.514        await vault.changePasswordWithNewKey(newSalt, newKey);515        await setupAutoLock();516        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });517        return { ok: true };518      }519      case "LOCK":520        vault.lock();521        if (isNativePlatform()) await clearInMemoryVault();522        return { ok: true };523      case "IS_UNLOCKED":524        return { ok: true, data: vault.isUnlocked() };525      case "GET_VAULT_STATUS":526        return { ok: true, unlocked: vault.isUnlocked() };527      case "HAS_VAULT":528        return { ok: true, data: await vault.hasVault() };529      case "GET_ENTRIES":530        return { ok: true, data: vault.getEntries() };531      case "ADD_ENTRY": {532        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };533        const entry = await vault.addEntry(msg.payload as any);534        return { ok: true, data: entry };535      }536      case "BATCH_ADD_ENTRIES": {537        const { entries } = msg.payload as { entries: any[] };538        const added = await vault.batchAddEntries(entries);539        return { ok: true, data: added };540      }541      case "RESTORE_ENTRIES": {542        const { entries, mode, settings } = msg.payload as {543          entries: any[];544          mode: "replace" | "merge";545          settings?: vault.VaultSettings;546        };547        const summary = await vault.restoreEntries(entries, mode);548        if (settings && typeof settings === "object") {549          await vault.updateSettings(settings);550        }551        return { ok: true, data: summary };552      }553      case "CLEAR_VAULT_ENTRIES": {554        await vault.clearVaultEntries("REPLACE_ALL");555        return { ok: true };556      }557      case "GET_VAULT_HISTORY": {558        const snapshots = await vault.getVaultHistory();559        return { ok: true, data: snapshots };560      }561      case "RESTORE_VAULT_SNAPSHOT": {562        const { snapshotId } = msg.payload as { snapshotId: string };563        const result = await vault.restoreVaultSnapshot(snapshotId);564        if (!result.ok) return { ok: false, error: result.error };565        broadcastToContentScripts({ type: "VAULT_LOCKED" });566        return { ok: true };567      }568      case "COUNT_DUPLICATES": {569        return { ok: true, data: vault.countDuplicates() };570      }571      case "DEDUPLICATE_ENTRIES": {572        const removed = await vault.deduplicateEntries();573        return { ok: true, data: removed };574      }575      case "UPDATE_ENTRY": {576        const { id, patch } = msg.payload as any;577        await vault.updateEntry(id, patch);578        return { ok: true };579      }580      case "ADD_ADDITIONAL_URL": {581        const { id, url } = msg.payload as { id: string; url: string };582        const trimmed = typeof url === "string" ? url.trim() : "";583        if (!trimmed) return { ok: false, error: "url required" };584        const existing = vault.getEntryById(id);585        if (!existing) return { ok: false, error: "entry not found" };586        if (existing.type !== "login") return { ok: false, error: "login entries only" };587        const merged = [...(existing.additionalUrls ?? []), trimmed];588        await vault.updateEntry(id, { additionalUrls: merged });589        return { ok: true };590      }591      case "DELETE_ENTRY": {592        const { id } = msg.payload as { id: string };593        await vault.deleteEntry(id);594        return { ok: true };595      }596      case "GET_DELETED_ENTRIES":597        return { ok: true, data: vault.getDeletedEntries() };598      case "RESTORE_ENTRY": {599        const { id } = msg.payload as { id: string };600        await vault.restoreEntry(id);601        return { ok: true };602      }603      case "PURGE_ENTRY": {604        const { id } = msg.payload as { id: string };605        await vault.purgeEntry(id);606        return { ok: true };607      }608      case "PURGE_EXPIRED_TRASH": {609        const { retentionMs } = msg.payload as { retentionMs: number };610        const purged = await vault.purgeExpiredTrash(retentionMs);611        return { ok: true, data: purged };612      }613      case "SAVE_NOTE": {614        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };615        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };616        const now = Date.now();617        if (id) {618          const existing = vault.getEntryById(id);619          if (!existing) return { ok: false, error: "not_found" };620          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });621          return { ok: true, data: vault.getEntryById(id) };622        } else {623          const entry = await vault.addEntry({624            type: "note",625            title: title || "Untitled",626            notes: body,627            createdAt: now,628            modifiedAt: now,629          } as any);630          return { ok: true, data: entry };631        }632      }633      case "DELETE_NOTE": {634        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };635        const { id } = msg.payload as { id: string };636        await vault.deleteEntry(id);637        return { ok: true };638      }639      case "GET_NOTES": {640        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };641        const notes = vault.getEntries().filter(642          (e) => e.type === "note" && !e.deletedAt643        );644        return { ok: true, data: notes } as MessageResponse;645      }646      case "SEARCH_VAULT": {647        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };648        const { query } = msg.payload as { query: string };649        const q = query.toLowerCase();650        const searchResults = vault.getEntries().filter(651          (e) =>652            !e.deletedAt &&653            (e.title.toLowerCase().includes(q) ||654              e.notes?.toLowerCase().includes(q) ||655              e.username?.toLowerCase().includes(q))656        );657        return { ok: true, data: searchResults } as MessageResponse;658      }659      case "PAIRING_COMPLETED": {660        const { deviceName, publicKeyHex, deviceIp } = (msg.payload ?? {}) as {661          deviceName?: string;662          publicKeyHex?: string;663          deviceIp?: string;664        };665        if (!publicKeyHex) return { ok: false, error: "publicKeyHex required" };666        // Only accept publicKeyHex values that just completed a real Noise NK667        // handshake (initiator or responder side). Without this gate, anyone668        // who can sendMessage to the background can pair an arbitrary key669        // (M13/SEC-005). Re-confirming an already-paired device is allowed670        // so legitimate update-IP retries still work.671        const alreadyPaired = (await getPairedDevices()).some(672          d => d.x25519PublicKey === publicKeyHex,673        );674        const verified = consumePendingPair(publicKeyHex);675        if (!verified && !alreadyPaired) {676          return { ok: false, error: "pairing_not_verified" };677        }678        const { setHasPaired: setPaired } = await import("./sync-storage");679        await setPaired();680        try {681          await addPairedDevice({682            deviceId: publicKeyHex,683            displayName: deviceName ?? "Unknown",684            x25519PublicKey: publicKeyHex,685            pairedAt: Date.now(),686            lastSeenAt: Date.now(),687            lastKnownIp: deviceIp,688          });689        } catch {690          // Already paired — update IP if provided691          if (deviceIp) {692            await updatePairedDevice(publicKeyHex, { lastKnownIp: deviceIp, lastSeenAt: Date.now() });693          }694        }695        return { ok: true };696      }697      case "AUTOFILL_QUERY": {698        if (!vault.isUnlocked()) {699          return { ok: false, error: "VAULT_LOCKED" };700        }701        const { domain, includeAll, kind } = msg.payload as {702          domain: string;703          includeAll?: boolean;704          kind?: "login" | "card";705        };706        // kind="card": return saved cards as compact summaries for the707        // inline card silver platter. Cards are not domain-scoped — every708        // saved card is a candidate on every checkout page — so domain is709        // ignored when kind === "card".710        if (kind === "card") {711          const cards = vault.getEntries().filter((e) => e.type === "card");712          return {713            ok: true,714            data: cards.map((e) => ({715              id: e.id,716              title: e.cardNickname || e.title,717              cardholderName: e.cardholderName,718              last4: e.last4,719              expMonth: e.expMonth,720              expYear: e.expYear,721              network: e.network,722            })),723          };724        }725        // The inline selector fills username+password into a form. Passkey-726        // only entries have no password to fill; sign-in for those goes727        // through the WebAuthn path instead. Filter them out everywhere so728        // the user doesn't see four "GitHub" rows that mostly do nothing.729        // Notes and cards never belonged here either.730        const matches = (731          includeAll732            ? vault733                .getEntries()734                .filter((entry) => entry.type !== "note" && entry.type !== "card")735            : vault.queryDomain(domain)736        ).filter((entry) => !isPasskeyOnly(entry));737        return {738          ok: true,739          data: matches.map((e) =>740            includeAll741              ? {742                  id: e.id,743                  title: e.title,744                  hasPasskey: e.passkey !== undefined,745                }746              : {747                  id: e.id,748                  title: e.title,749                  username: e.username,750                  email: e.email,751                  url: e.url,752                  hasTotp: Boolean(e.totp),753                  hasPasskey: e.passkey !== undefined,754                }755          ),756        };757      }758      case "GET_ENTRY_FOR_FILL": {759        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };760        const { id } = msg.payload as { id: string };761        const entry = vault.getEntryById(id);762        if (!entry) return { ok: false, error: "entry not found" };763        // Passkey-only entries (passkey credential, no password) cannot be764        // filled into a form — sign-in goes through the WebAuthn path. A765        // login that ALSO has a passkey is still fillable for its password.766        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey not fillable" };767        // Strip the passkey credential from the response — content scripts768        // never need the private key, and there's no reason to expose the769        // public credential metadata over the boundary either.770        const { passkey: _strippedPasskey, ...safeEntry } = entry;771        return { ok: true, data: safeEntry };772      }773      case "COPY": {774        const { text, label, alreadyWritten } = msg.payload as {775          text: string;776          label: string;777          alreadyWritten?: boolean;778        };779        await copyToClipboard(text, label, Boolean(alreadyWritten));780        return { ok: true };781      }782      case "CHECK_ALL_BREACHES": {783        const allEntries = vault.getEntries();784        const results: Record<string, number> = {};785        for (const entry of allEntries) {786          if (entry.type === "note") continue;787          if (!entry.password) continue;788          results[entry.id] = await vault.checkBreach(entry.password);789          // Small delay — be a good citizen to the HIBP API790          await new Promise((r) => setTimeout(r, 200));791        }792        // Persist any non-zero counts back to entries793        for (const [id, count] of Object.entries(results)) {794          const entry = vault.getEntryById(id);795          if (entry && (entry.breach ?? 0) !== count) {796            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });797          }798        }799        return { ok: true, data: results };800      }801      case "GET_SETTINGS":802        return { ok: true, data: await vault.ensureSettingsLoaded() };803      case "UPDATE_SETTINGS": {804        const patch = msg.payload as Record<string, unknown>;805        await vault.updateSettings(patch as any);806        if (typeof patch.autoLockMinutes === "number") {807          await setupAutoLock();808          if (vault.isUnlocked()) touchAutoLock();809        }810        return { ok: true };811      }812      case "GET_PENDING_PASSKEY":813        return { ok: true, data: await getPendingPasskeyRequest() };814      case "APPROVE_PASSKEY": {815        const { requestId } = msg.payload as { requestId: number };816        await resolvePendingPasskeyRequest(requestId, true);817        return { ok: true };818      }819      case "DENY_PASSKEY": {820        const { requestId } = msg.payload as { requestId: number };821        await resolvePendingPasskeyRequest(requestId, false);822        return { ok: true };823      }824      case "GET_PASSKEY_PROVIDER_STATE":825        return { ok: true, data: await getPasskeyProviderState() };826      case "SET_PASSKEY_PROVIDER_ENABLED": {827        const { enabled } = msg.payload as { enabled: boolean };828        // Disabling is always free; gating fires only when a free user is829        // trying to turn passkey interception on.830        if (enabled) {831          const gate = await requirePro("passkeys");832          if (!gate.allowed) return { ok: false, error: "pro_required" };833        }834        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };835      }836      case "FIRE_CANARY_PING": {837        const { webhookUrl, entryTitle, trigger } = msg.payload as {838          webhookUrl: string;839          entryTitle: string;840          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";841        };842        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {843          return { ok: false, error: "invalid webhook url" };844        }845        const body = JSON.stringify({846          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",847          entry: entryTitle,848          trigger,849          timestamp: new Date().toISOString(),850          source: "peach-extension",851        });852        if (trigger === "test") {853          // Permitted outbound fetch: user-configured canary alert endpoint854          // (validated by isAllowedCanaryWebhookUrl above). This is the855          // only non-HIBP outbound call in the extension — see856          // Projects.md §3.7. Test pings are awaited so the UI can show857          // success/failure.858          try {859            const res = await fetch(webhookUrl, {860              method: "POST",861              headers: { "Content-Type": "application/json" },862              body,863            });864            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };865          } catch (err) {866            return { ok: false, error: err instanceof Error ? err.message : "network error" };867          }868        }869        // Non-test triggers are fire-and-forget870        fetch(webhookUrl, {871          method: "POST",872          headers: { "Content-Type": "application/json" },873          body,874        }).catch(() => {});875        return { ok: true };876      }877      case "ACTIVATE_LICENSE": {878        const { key } = msg.payload as { key: string };879        const licenseInfo = await activateLicense(key);880        return { ok: true, data: licenseInfo };881      }882      case "GET_LICENSE": {883        const licenseInfo = await getLicenseInfo();884        return { ok: true, data: licenseInfo };885      }886      case "GET_LICENSE_KEY": {887        const key = await getLicenseKey();888        return { ok: true, data: key };889      }890      case "DEACTIVATE_LICENSE": {891        await deactivateLicense();892        return { ok: true };893      }894      case "SHOULD_PLAY_CELEBRATION": {895        const should = await shouldPlayCelebration();896        return { ok: true, data: should };897      }898      case "MARK_CELEBRATION_PLAYED": {899        await markCelebrationPlayed();900        return { ok: true };901      }902      case "GET_CODEX_VAULT_DATA": {903        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the904        // popup navigates to the License section without further coordination.905        const gate = await requirePro("codex");906        if (!gate.allowed) return { ok: false, error: "pro_required" };907        return await handleGetCodexVaultData();908      }909      case "ESTIMATE_CODEX_PAGES": {910        const gate = await requirePro("codex");911        if (!gate.allowed) return { ok: false, error: "pro_required" };912        return await handleEstimateCodexPages();913      }914      case "RESTORE_FROM_CODEX": {915        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still916        // be able to restore a vault that was printed by a Pro user.917        // DO NOT add a Pro gate here.918        const payload = msg.payload as CodexRestorePayload;919        return await handleRestoreFromCodex(payload);920      }921      case "OPEN_PRO_GATE": {922        // Content script requests: open popup and navigate to License section.923        const { feature } = (msg.payload ?? {}) as { feature?: string };924        if (chrome.storage.session) {925          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });926        }927        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }928        return { ok: true };929      }930      case "GET_IDENTITIES": {931        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };932        return { ok: true, data: vault.getIdentities() };933      }934      case "TOUCH_AUTO_LOCK": {935        // touchAutoLock() is already called by shouldRefreshAutoLock above;936        // this case just gives the popup a typed message to keep the session alive.937        return { ok: true };938      }939      case "GET_ADVANCED_HEALTH_REPORT": {940        const gate = await requirePro("advanced_health");941        if (!gate.allowed) return { ok: false, error: "pro_required" };942        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };943        const report = await buildAdvancedHealthReport(vault.getEntries());944        return { ok: true, data: report };945      }946      case "INITIATE_PASSWORD_CHANGE": {947        const gate = await requirePro("smart_password_change");948        if (!gate.allowed) return { ok: false, error: "pro_required" };949        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };950        const { id } = msg.payload as { id: string };951        const entry = vault.getEntryById(id);952        if (!entry) return { ok: false, error: "entry not found" };953        const url = resolveResetUrl(entry);954        if (!url) return { ok: false, error: "no reset url" };955        try {956          await chrome.tabs.create({ url });957          return { ok: true, data: { url } };958        } catch (err) {959          return {960            ok: false,961            error: err instanceof Error ? err.message : "failed to open tab",962          };963        }964      }965      case "IS_DURESS_ENABLED": {966        const enabled = await vault.isDuressEnabled();967        return { ok: true, data: enabled };968      }969      case "SETUP_DURESS": {970        const { duressPassword } = msg.payload as { duressPassword: string };971        await vault.setupDuress(duressPassword);972        return { ok: true };973      }974      case "DISABLE_DURESS": {975        await vault.disableDuress();976        return { ok: true };977      }978      case "VERIFY_MAIN_PASSWORD": {979        const { password } = msg.payload as { password: string };980        const ok = await vault.verifyMainPassword(password);981        return { ok: true, data: ok };982      }983      case "CHANGE_PASSWORD": {984        const { currentPassword, newPassword } = msg.payload as {985          currentPassword: string;986          newPassword: string;987        };988        const changed = await vault.changePassword(currentPassword, newPassword);989        return changed990          ? { ok: true }991          : { ok: false, error: "incorrect current password" };992      }993      case "GET_SITE_PASSWORD_POLICY": {994        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });995        if (!tab?.id) return { ok: true, data: null };996        try {997          const response = await chrome.tabs.sendMessage(tab.id, {998            type: "GET_SITE_PASSWORD_POLICY",999          });1000          return (response as MessageResponse) ?? { ok: true, data: null };1001        } catch {1002          return { ok: true, data: null };1003        }1004      }1005      case "GET_SYNC_STATE": {1006        const pairedDevices = await getPairedDevices();1007        const trustedNetworks = await getTrustedNetworks();1008        const tailscale = await isOnTailscale();1009        const pro = await isProUser();10101011        let status: SyncStatus = "offline";1012        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {1013          if (pairedDevices.length === 0) {1014            status = "no_peers";1015          } else {1016            status = "synced";1017          }1018        } else {1019          status = "not_trusted";1020        }10211022        const lastSyncRaw = await storageGet("peach_last_sync_at");1023        const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN;1024        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined;10251026        return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } };1027      }1028      case "GET_PAIRED_DEVICES": {1029        const devices = await getPairedDevices();1030        return { ok: true, data: { devices } };1031      }1032      case "GET_SYNC_STATUS": {1033        const lastSyncRaw = await storageGet("peach_last_sync_at");1034        const lastSyncParsed = lastSyncRaw ? parseInt(lastSyncRaw, 10) : NaN;1035        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : null;1036        const status: 'up_to_date' | 'never' = lastSyncAt ? 'up_to_date' : 'never';1037        return { ok: true, data: { status, lastSyncAt } };1038      }1039      case "ACCEPT_PAIRING": {1040        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.1041        return { ok: true };1042      }1043      case "REMOVE_PAIRED_DEVICE": {1044        const { deviceId } = msg.payload as { deviceId: string };1045        await removePairedDevice(deviceId);1046        return { ok: true };1047      }1048      case "REMOVE_TRUSTED_NETWORK": {1049        const { ssid, bssid, isTailscale } = msg.payload as any;1050        const networks = await getTrustedNetworks();1051        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 1052          (isTailscale ? n.isTailscale : n.ssid === ssid) && 1053          (!bssid || n.bssid === bssid)1054        );1055        if (network) {1056          await removeTrustedNetwork(network.addedAt);1057        }1058        return { ok: true };1059      }1060      case "MARK_NETWORK_TRUSTED": {1061        const network = await getCurrentNetwork();1062        await addTrustedNetwork({1063          ssid: network.ssid,1064          bssid: network.bssid,1065          isTailscale: network.isTailscale,1066          addedAt: Date.now(),1067        });1068        return { ok: true };1069      }1070      case "GET_INCOMING_PAIRING_REQUEST": {1071        const request = await getIncomingPairingRequest();1072        return { ok: true, data: request };1073      }1074      case "RESPOND_INCOMING_PAIRING": {1075        const { accept } = msg.payload as { accept: boolean };1076        const request = await getIncomingPairingRequest();1077        if (!request) return { ok: false, error: "no_pending_request" };1078        if (Date.now() > request.expiresAt) {1079          await clearIncomingPairingRequest();1080          return { ok: false, error: "expired" };1081        }1082        await clearIncomingPairingRequest();1083        if (accept) {1084          await addPairedDevice({1085            deviceId: request.publicKeyHex,1086            displayName: request.deviceName,1087            x25519PublicKey: request.publicKeyHex,1088            pairedAt: Date.now(),1089            lastSeenAt: Date.now(),1090          });1091        }1092        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };1093      }1094      case "START_PAIRING_SERVER": {1095        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.1096        const token = generateSixDigitToken();1097        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;1098        await setActivePairingToken({ token, expiresAt });1099        // Fire-and-forget subnet scan — finds the phone after it scans the QR1100        // and calls SCAN_PAIRING_QR to register the token with SyncPlugin.1101        if (!isNativePlatform()) {1102          void runPairingSubnetScan(token);1103        }1104        return { ok: true, data: { token, expiresAt } };1105      }1106      case "STOP_PAIRING_SERVER": {1107        try {1108          await setActivePairingToken(null);1109        } catch { /* best-effort */ }1110        return { ok: true };1111      }1112      case "GET_RECENT_PAIRING": {1113        const recent = await consumeRecentPairing();1114        return { ok: true, data: recent };1115      }1116      case "DEBUG_INJECT_INCOMING_PAIRING": {1117        // Manual E2E rehearsal hook. Inserts a synthetic incoming pairing1118        // request into session storage so Phase 7 banner UX can be exercised1119        // without a live native host. No Pro gate — this is a no-op in1120        // production unless explicitly invoked from a Settings debug action.1121        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {1122          deviceName?: string;1123          publicKeyHex?: string;1124        };1125        if (!deviceName || !publicKeyHex) {1126          return { ok: false, error: "missing_payload" };1127        }1128        const now = Date.now();1129        await setIncomingPairingRequest({1130          deviceName,1131          publicKeyHex,1132          receivedAt: now,1133          expiresAt: now + 60_000,1134        });1135        return { ok: true };1136      }1137      case "RESET_SYNC_IDENTITY": {1138        const gate = await requirePro("sync");1139        if (!gate.allowed) return { ok: false, error: "pro_required" };1140        const devices = await getPairedDevices();1141        for (const device of devices) {1142          await removePairedDevice(device.deviceId);1143        }1144        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };1145      }1146      case "RECORD_MANUAL_SUMMON": {1147        const { domain } = msg.payload as { domain: string };1148        const settings = vault.getSettings();1149        const existing = settings.manualSummonDomains?.[domain];1150        const now = Date.now();1151        await vault.updateSettings({1152          manualSummonDomains: {1153            ...settings.manualSummonDomains,1154            [domain]: {1155              firstSummonedAt: existing?.firstSummonedAt ?? now,1156              summonCount: (existing?.summonCount ?? 0) + 1,1157              lastSummonedAt: now,1158            },1159          },1160        });1161        return { ok: true };1162      }1163      case "DECLINE_CARD_SAVE": {1164        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1165        await vault.declineCardSaveOffer(last4, expMonth, expYear);1166        return { ok: true };1167      }1168      case "IS_CARD_DECLINED": {1169        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1170        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1171        return { ok: true, data: declined };1172      }1173      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1174        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1175          rpId?: string;1176          rpName?: string;1177          userName?: string;1178          userDisplayName?: string;1179        };1180        if (!rpId || !userName) return { ok: false, error: "rpId and userName required" };1181        return await initiateFirefoxPasskeyCreate({1182          rpId,1183          rpName: rpName ?? rpId,1184          userName,1185          userDisplayName,1186        });1187      }11881189      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1190        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1191        if (!payload) return { ok: false, error: "missing payload" };1192        return await completeFirefoxPasskeyCreate(payload);1193      }11941195      case "PASSKEY_OFFER_DECLINE": {1196        const { domain } = (msg.payload ?? {}) as { domain?: string };1197        if (!domain) return { ok: false, error: "domain required" };1198        await recordPasskeyOfferDecline(domain);1199        return { ok: true };1200      }12011202      case "GET_PASSKEY_OFFER_DECLINED": {1203        const { domain } = (msg.payload ?? {}) as { domain?: string };1204        if (!domain) return { ok: false, error: "domain required" };1205        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1206      }12071208      case "PASSKEY_HAS_CREDENTIALS": {1209        const payload = msg.payload as {1210          rpId?: string;1211          allowCredentials?: Array<{ id: string; type?: string }>;1212        } | undefined;1213        if (!payload?.rpId) return { ok: false, error: "rpId required" };1214        return await handlePasskeyHasCredentials({1215          rpId: payload.rpId,1216          allowCredentials: payload.allowCredentials ?? [],1217        });1218      }12191220      case "PASSKEY_CREATE": {1221        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1222        if (!payload?.rpId || !payload?.userName) {1223          return { ok: false, error: "rpId and userName required" };1224        }1225        return await handleFirefoxPasskeyCreate(payload);1226      }12271228      case "PASSKEY_GET": {1229        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1230        if (!payload?.rpId) return { ok: false, error: "rpId required" };1231        return await handleFirefoxPasskeyGet(payload);1232      }12331234      case "PASSKEY_AUTH_RESPONSE": {1235        const { requestId, approved } = (msg.payload ?? {}) as {1236          requestId?: string | number;1237          approved?: boolean;1238        };1239        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1240          return { ok: false, error: 'requestId and approved required' };1241        }1242        await resolvePendingPasskeyRequest(Number(requestId), approved);1243        return { ok: true };1244      }12451246      case "GET_PASSKEY_FOR_DOMAIN": {1247        const { domain } = (msg.payload ?? {}) as { domain?: string };1248        if (!domain) return { ok: false, error: "domain required" };1249        if (!vault.isUnlocked()) return { ok: true, data: null };1250        const match = vault1251          .getEntries()1252          .find((entry) => entry.passkey?.rpId === domain);1253        if (!match || !match.passkey) return { ok: true, data: null };1254        // Slim shape — only the fields State 11 needs. Never expose private1255        // key material, even though this is locked behind isUnlocked.1256        return {1257          ok: true,1258          data: {1259            rpId: match.passkey.rpId,1260            userName: match.passkey.userName,1261            browser: match.passkey.browser,1262          },1263        };1264      }12651266      case "DESTROY_VAULT": {1267        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1268        // storage.local.clear() wipes every Peach key (slots, settings, license,1269        // onboarded flag, history, sync state, declined cards, recall, etc.);1270        // session.clear() wipes pending passkey requests + pro-notice queues.1271        // Caller (Panic.tsx) handles UI navigation back to onboarding.1272        vault.lock();1273        await storageClear();1274        await vault.clearVaultHistory();1275        if (chrome.storage.session) {1276          await chrome.storage.session.clear();1277        }1278        return { ok: true };1279      }12801281      case "SUBMIT_FEEDBACK": {1282        const { category, message, version, browser } = msg.payload as {1283          category: string;1284          message: string;1285          version: string;1286          browser: string;1287        };1288        if (!message.trim()) return { ok: false, error: "message is empty" };1289        if (!FEEDBACK_ENDPOINT) return { ok: true };1290        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1291          return { ok: false, error: "invalid feedback endpoint" };1292        }1293        try {1294          const res = await fetch(FEEDBACK_ENDPOINT, {1295            method: "POST",1296            headers: { "Content-Type": "application/json" },1297            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1298          });1299          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1300        } catch (err) {1301          return { ok: false, error: err instanceof Error ? err.message : "network error" };1302        }1303      }1304      case "TRIGGER_SYNC": {1305        const gate = await requirePro("sync");1306        if (!gate.allowed) return { ok: false, error: "pro_required" };1307        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };13081309        if (isNativePlatform()) {1310          // Phone is the server — ensure it's listening for desktop connections.1311          syncBridge()?.ensureServerRunning?.();1312          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };1313        }13141315        // Desktop: iterate all paired devices and sync with each.1316        const paired = await getPairedDevices();1317        if (!paired.length) return { ok: true, data: { syncedCount: 0, reason: "no_paired_devices" } };13181319        const subnet = await getLocalSubnet();1320        const results: Array<{ device: string } & SyncResult> = [];13211322        for (const device of paired) {1323          if (!device.x25519PublicKey) continue;13241325          let result: SyncResult;13261327          // Fast path — use last known IP1328          if (device.lastKnownIp) {1329            result = await doVaultSync(device.lastKnownIp, device.x25519PublicKey);1330          } else {1331            result = { status: 'errored', applied: false, error: 'no_ip' };1332          }13331334          // Discovery path — scan if fast path failed1335          if (result.status === 'errored' && subnet) {1336            const newIp = await discoverDevice(subnet, device.x25519PublicKey);1337            if (newIp) {1338              await updatePairedDevice(device.x25519PublicKey, { lastKnownIp: newIp });1339              result = await doVaultSync(newIp, device.x25519PublicKey);1340            }1341          }13421343          if (result.status === 'completed') {1344            await updatePairedDevice(device.x25519PublicKey, {1345              lastSeenAt: Date.now(),1346              lastSyncAt: Date.now(),1347            });1348          }13491350          results.push({ device: device.displayName, ...result });1351        }13521353        const syncedCount = results.filter(r => r.status === 'completed').length;1354        if (syncedCount > 0) {1355          await chrome.storage.local.set({ peach_last_sync_at: String(Date.now()) });1356        }1357        return { ok: true, data: { syncedCount, results } };1358      }1359      // Android-only: biometric unlock with pre-derived key.1360      case "UNLOCK_WITH_KEY": {1361        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1362        if (!isNativePlatform()) {1363          return { ok: false, error: "desktop_only_uses_password" };1364        }1365        try {1366          const result = await vault.unlockWithKey(masterKeyHex);1367          if (result.ok) {1368            onVaultUnlocked();1369            await publishInMemoryVault(result.entries);1370          }1371          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1372        } catch {1373          return { ok: false, error: "invalid_key" };1374        }1375      }1376      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1377      case "GET_DERIVED_KEY": {1378        if (!isNativePlatform()) {1379          return { ok: false, error: "android_only" };1380        }1381        if (!vault.isUnlocked()) {1382          return { ok: false, error: "vault_locked" };1383        }1384        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1385      }1386      // Android: scanned a QR containing a desktop pairing token.1387      case "SCAN_PAIRING_QR": {1388        if (!isNativePlatform()) {1389          return { ok: false, error: "android_only" };1390        }1391        const { token } = msg.payload as { token: string };1392        syncBridge()?.startPairingSession?.({ token });1393        return { ok: true };1394      }1395      // Android: desktop opened a sync connection to the phone's WS server.1396      // Run the responder side of the vault exchange.1397      case "SYNC_SESSION_STARTED": {1398        if (!isNativePlatform()) return { ok: false };1399        if (!vault.isUnlocked()) {1400          return { ok: false, error: "vault_locked" };1401        }1402        const { connectionId } = (msg.payload ?? {}) as { connectionId?: string };1403        if (!connectionId) return { ok: false, error: "missing_connection_id" };14041405        const transport = createAndroidResponderTransport(connectionId);14061407        // Authenticate the initiator before exchanging any vault data. The1408        // native side has already completed the Noise NK handshake; auth1409        // frames here ride the Noise transport (native encrypts/decrypts).1410        const identity = await vault.getSyncIdentity();1411        try {1412          const noiseSessionStub = {1413            encrypt: (b: Uint8Array) => b,1414            decrypt: (b: Uint8Array) => b,1415            handshakeHash: new Uint8Array(32),1416          };1417          const { initiatorPublicKey } = await performResponderAuth(1418            noiseSessionStub,1419            identity.privateKeyBytes,1420            identity.publicKeyBytes,1421            transport.send,1422            transport.receive,1423          );1424          const initiatorHex = noiseBytesToHex(initiatorPublicKey);1425          const paired = await getPairedDevices();1426          if (!paired.some(d => d.x25519PublicKey === initiatorHex)) {1427            await transport.close();1428            return { ok: false, error: "sync_rejected_unpaired_initiator" };1429          }1430          // Initiator just proved control of the matching static key; mark it1431          // as a verified handshake so a follow-up PAIRING_COMPLETED message1432          // can be trusted (M13/SEC-005).1433          markPairingHandshakeVerified(initiatorHex);1434        } catch (err) {1435          await transport.close();1436          return { ok: false, error: `sync_auth_failed: ${String(err)}` };1437        }14381439        const result = await runBlobSyncSession('responder', transport, buildSyncDeps());1440        if (result.applied) {1441          await publishInMemoryVault(vault.getEntries());1442        }1443        return { ok: true, data: result };1444      }1445      // Android: returns the phone's WiFi IP address.1446      case "GET_LOCAL_IP": {1447        if (!isNativePlatform()) {1448          return { ok: false, error: "android_only" };1449        }1450        const { ip } = (await syncBridge()?.getLocalIp?.()) ?? { ip: "" };1451        return { ok: true, data: { ip } };1452      }1453      case "GET_IDENTITY_SUGGESTIONS": {1454        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1455        const entries = vault.getEntries();1456        const suggestions = buildIdentitySuggestions(entries);1457        return { ok: true, data: { suggestions } };1458      }1459      case "POPULATE_INLINE_VAULT": {1460        if (!isNativePlatform()) return { ok: false };1461        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1462        const entries = vault.getEntries();1463        await publishInMemoryVault(entries);1464        return { ok: true };1465      }1466      case "ML_INIT":1467        return { ok: true };14681469      case "ML_PREDICT_BATCH": {1470        const { featuresArray } = msg.payload as { featuresArray: MLFieldFeatures[] };1471        return { ok: true, data: mlPredictBatch(featuresArray) };1472      }14731474      default:1475        return { ok: false, error: "unknown message type" };1476    }1477  } catch (err) {1478    return {1479      ok: false,1480      error: err instanceof Error ? err.message : "operation failed",1481    };1482  }1483}14841485// --- Mobile platform helpers ---14861487// Android: populates the in-memory vault used by PeachAutofillService.1488async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1489  const plugin = nativePlugin<{1490    setEntries?: (args: {1491      entries: Array<{1492        id: string;1493        title: string;1494        username: string;1495        email: string;1496        password: string;1497        url: string;1498        totp: string;1499        additionalUrls: string[];1500      }>;1501    }) => Promise<void>;1502  }>("InMemoryVaultPlugin");1503  if (!plugin?.setEntries) return;1504  await plugin.setEntries({1505    entries: entries.map((e) => ({1506      id: e.id,1507      title: e.title ?? "",1508      username: e.username ?? "",1509      email: (e as VaultEntry & { email?: string }).email ?? "",1510      password: e.password ?? "",1511      url: e.url ?? "",1512      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1513      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1514    })),1515  });1516}15171518// Android: clear the autofill in-memory store on lock.1519async function clearInMemoryVault(): Promise<void> {1520  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1521  if (!plugin?.clearEntries) return;1522  await plugin.clearEntries();1523}15241525interface SyncBridge {1526  ensureServerRunning?: () => void;1527  startPairingSession?: (args: { token: string }) => void;1528  getLocalIp?: () => Promise<{ ip: string }>;1529  sendToConnection?: (args: { connectionId: string; data: string }) => Promise<void>;1530  addListener?: (event: string, handler: (data: Record<string, string>) => void) => void;1531}15321533// Resolve the Capacitor SyncPlugin at call time — module-load resolution1534// races with Capacitor's plugin registration on the Android WebView.1535function syncBridge(): SyncBridge | null {1536  return nativePlugin<SyncBridge>("SyncPlugin");1537}15381539// Build a SyncTransport for the Android responder path — the phone's WS server1540// already has an open connection from the desktop. We send back via1541// SyncPlugin.sendToConnection and receive via the peach:sync-frame queue.1542const androidSyncFrameQueues = new Map<string, Array<(frame: string) => void>>();15431544export function deliverAndroidSyncFrame(connectionId: string, frame: string): void {1545  const queue = androidSyncFrameQueues.get(connectionId);1546  if (queue?.length) queue.shift()!(frame);1547}15481549function createAndroidResponderTransport(connectionId: string) {1550  const pendingReceivers: Array<(frame: string) => void> = [];1551  androidSyncFrameQueues.set(connectionId, pendingReceivers);15521553  return {1554    send: async (data: Uint8Array) => {1555      await syncBridge()?.sendToConnection?.({ connectionId, data: bytesToBase64(data) });1556    },1557    receive: (): Promise<Uint8Array> => new Promise((res) => {1558      pendingReceivers.push((frame) => {1559        res(frame ? base64ToBytes(frame) : new Uint8Array(0));1560      });1561    }),1562    close: async () => {1563      androidSyncFrameQueues.delete(connectionId);1564    },1565  };1566}15671568// Returns username use-counts from the vault, sorted by frequency. Each row1569// also carries the entry's email so the popup can suggest the email/username1570// pair the user has actually used together.1571function buildIdentitySuggestions(1572  entries: VaultEntry[],1573): Array<{ email: string; username: string; count: number }> {1574  const usernameCounts = new Map<string, number>();1575  const usernameEmail = new Map<string, string>();1576  for (const entry of entries) {1577    const username = entry.username ?? "";1578    const email = (entry as VaultEntry & { email?: string }).email ?? "";1579    if (!username && !email) continue;1580    const key = username || email;1581    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1582    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1583  }1584  return Array.from(usernameCounts.entries())1585    .sort((a, b) => b[1] - a[1])1586    .map(([username, count]) => ({1587      email: usernameEmail.get(username) ?? "",1588      username,1589      count,1590    }));1591}15921593/** Notify all content scripts that the vault just became available. */1594function broadcastToContentScripts(message: { type: string }): void {1595  if (!chrome.tabs?.query) return;1596  chrome.tabs.query({}, (tabs) => {1597    for (const tab of tabs) {1598      if (tab.id !== undefined) {1599        chrome.tabs.sendMessage(tab.id, message).catch(() => {1600          // Tab may not have a content script — silently ignore1601        });1602      }1603    }1604  });1605}16061607function shouldRefreshAutoLock(type: MessageType): boolean {1608  return (1609    type !== "HAS_VAULT" &&1610    type !== "IS_UNLOCKED" &&1611    type !== "GET_VAULT_STATUS" &&1612    type !== "LOCK" &&1613    type !== "UPDATE_SETTINGS" &&1614    type !== "GET_PENDING_PASSKEY" &&1615    type !== "GET_PASSKEY_PROVIDER_STATE" &&1616    type !== "DECLINE_CARD_SAVE" &&1617    type !== "IS_CARD_DECLINED" &&1618    type !== "SUBMIT_FEEDBACK"1619  );1620}16211622function isAllowedCanaryWebhookUrl(value: string): boolean {1623  try {1624    const url = new URL(value);1625    if (url.protocol !== "https:") return false;16261627    const hostname = url.hostname.toLowerCase();1628    if (1629      hostname === "localhost" ||1630      hostname.endsWith(".localhost") ||1631      isPrivateIpv4(hostname) ||1632      isPrivateIpv6(hostname)1633    ) {1634      return false;1635    }16361637    return true;1638  } catch {1639    return false;1640  }1641}16421643function isPrivateIpv4(hostname: string): boolean {1644  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1645    return true;1646  }16471648  const octets = hostname.split(".").map((part) => Number(part));1649  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1650    return false;1651  }16521653  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1654}16551656function isPrivateIpv6(hostname: string): boolean {1657  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1658  return (1659    normalized === "::1" ||1660    normalized.startsWith("fc") ||1661    normalized.startsWith("fd") ||1662    normalized.startsWith("fe80:")1663  );1664}