messages.ts

59.1 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// ---------------------------------------------------------------------------170171function buildSyncDeps(): SyncDeps {172  return {173    isVaultUnlocked: () => vault.isUnlocked(),174    getVaultBlobForSync: async () => {175      const base = await vault.getVaultBlobForSync();176      if (!base) return null;177      const paired = await getPairedDevices();178      return {179        ...base,180        devices: paired181          .filter(d => d.x25519PublicKey)182          .map(d => ({183            publicKeyHex: d.x25519PublicKey,184            deviceName: d.displayName,185            pairedAt: d.pairedAt,186          })),187      };188    },189    applyIncomingVault: async (blob, ts, license, devices) => {190      const applied = await vault.applyIncomingVault(blob, ts, license);191      if (devices?.length) await mergeDeviceRegistry(devices);192      if (applied) await vault.reloadEntriesAfterSync();193      return applied;194    },195  };196}197198async function doVaultSync(ip: string, publicKeyHex: string): Promise<SyncResult> {199  try {200    const identity = await vault.getSyncIdentity();201    const transport = await createWebSocketSyncTransport(202      `ws://${ip}:44100`,203      publicKeyHex,204      identity.privateKeyBytes,205      identity.publicKeyBytes,206    );207    return await runBlobSyncSession('initiator', transport, buildSyncDeps());208  } catch (err) {209    return { status: 'errored', applied: false, error: String(err) };210  }211}212213async function mergeDeviceRegistry(incoming: SyncableDevice[]): Promise<void> {214  const existing = await getPairedDevices();215  const existingKeys = new Set(existing.map(d => d.x25519PublicKey));216  for (const device of incoming) {217    if (!existingKeys.has(device.publicKeyHex)) {218      await addPairedDevice({219        deviceId: device.publicKeyHex,220        displayName: device.deviceName,221        x25519PublicKey: device.publicKeyHex,222        pairedAt: device.pairedAt,223        lastSeenAt: 0,224        lastKnownIp: '',225      }).catch(() => {});226    }227  }228}229230// Background pairing scan — runs after START_PAIRING_SERVER fires on desktop.231// Scans the local subnet for a phone that has accepted the pairing token,232// stores it, runs the initial vault exchange, then notifies the popup.233async function runPairingSubnetScan(token: string): Promise<void> {234  const subnet = await getLocalSubnet();235  if (!subnet) return;236237  const found = await scanForPairingPhone(subnet, token);238  if (!found) return;239240  const { ip, publicKeyHex } = found;241242  try {243    await addPairedDevice({244      deviceId: publicKeyHex,245      displayName: 'Peach',246      x25519PublicKey: publicKeyHex,247      pairedAt: Date.now(),248      lastSeenAt: Date.now(),249      lastKnownIp: ip,250    });251  } catch {252    // Already paired — update IP253    await updatePairedDevice(publicKeyHex, { lastKnownIp: ip, lastSeenAt: Date.now() });254  }255256  // Immediate vault exchange — the free one-time transfer257  await doVaultSync(ip, publicKeyHex);258259  chrome.runtime.sendMessage({260    type: 'PAIRING_COMPLETED',261    payload: { deviceName: 'Peach', publicKeyHex, deviceIp: ip },262  }).catch(() => {});263}264265export function setupMessageHandler(): void {266  chrome.runtime.onMessage.addListener(267    (msg: unknown, sender, sendResponse) => {268      if (!isMessage(msg)) {269        sendResponse({ ok: false, error: "invalid message" });270        return true;271      }272      handleMessage(msg, sender)273        .then(sendResponse)274        .catch((err) =>275          sendResponse({276            ok: false,277            error: err instanceof Error ? err.message : String(err),278          })279        );280      return true;281    }282  );283284  // Android: the chrome shim queues sendMessage calls until this handler is285  // registered. Without this hookup, every message hangs on Capacitor builds.286  // eslint-disable-next-line @typescript-eslint/no-explicit-any287  const reg = (globalThis as any).__peachRegisterMessageHandler;288  if (typeof reg === "function") {289    reg(async (m: unknown) => {290      if (!isMessage(m)) return { ok: false, error: "invalid message" };291      try {292        return await handleMessage(m);293      } catch (err) {294        return {295          ok: false,296          error: err instanceof Error ? err.message : String(err),297        };298      }299    });300  }301302  // Android: subscribe to SyncPlugin events.303  if (isNativePlatform()) {304    const syncPlug = nativePlugin<{305      addListener: (306        event: string,307        handler: (data: Record<string, string>) => void308      ) => void;309    }>("SyncPlugin");310311    // Pairing probe answered — store the paired device (desktop, no IP needed312    // since the desktop never acts as a WS server).313    syncPlug?.addListener?.("peach:pair-probe-answered", (data) => {314      const deviceName = data.deviceName ?? "Peach";315      const publicKeyHex = data.publicKeyHex ?? "";316      void (async () => {317        const { addPairedDevice, setHasPaired: setPaired } = await import("./sync-storage");318        await addPairedDevice({319          deviceId: publicKeyHex || (data.connectionId ?? "unknown"),320          displayName: deviceName,321          x25519PublicKey: publicKeyHex,322          pairedAt: Date.now(),323          lastSeenAt: Date.now(),324        }).catch(() => {});325        await setPaired();326        chrome.runtime.sendMessage({327          type: "PAIRING_COMPLETED",328          payload: { deviceName },329        }).catch(() => {});330      })();331    });332333    // Sync frame received — route to the waiting responder session.334    syncPlug?.addListener?.("peach:sync-frame", (data) => {335      const { connectionId, frame } = data;336      if (connectionId && frame) deliverAndroidSyncFrame(connectionId, frame);337    });338339    // Sync session started (SYNC_HELLO received by SyncPlugin) — dispatch as340    // a background message so SYNC_SESSION_STARTED handler runs the responder.341    syncPlug?.addListener?.("peach:sync-session-started", (data) => {342      const { connectionId } = data;343      if (!connectionId) return;344      void handleMessage({ type: "SYNC_SESSION_STARTED", payload: { connectionId } });345    });346  }347}348349function isMessage(m: unknown): m is Message {350  return typeof m === "object" && m !== null && "type" in m;351}352353export async function handleMessage(354  msg: Message,355  sender: Partial<chrome.runtime.MessageSender> = {}356): Promise<MessageResponse> {357  try {358    // Validate sender — only allow messages from our extension pages/scripts.359    // `sender.id` is undefined for messages originating from extension UI360    // (popup/options), which is legitimate; reject only when it is defined361    // and does not match our extension id.362    if (363      sender.id !== undefined &&364      sender.id !== chrome.runtime.id365    ) {366      return { ok: false, error: "invalid sender" };367    }368369    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {370      touchAutoLock();371    }372373    switch (msg.type) {374      case "CREATE_VAULT": {375        const { password } = msg.payload as { password: string };376        await vault.createVault(password);377        await setupAutoLock();378        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });379        onVaultUnlocked();380        return { ok: true };381      }382      case "UNLOCK": {383        const { password } = msg.payload as { password: string };384        const ok = await vault.unlock(password);385        if (ok) {386          await setupAutoLock();387          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });388          onVaultUnlocked();389          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());390        }391        return { ok };392      }393      case "VALIDATE_RECOVERY_WORDS": {394        const { words } = msg.payload as { words: string[] };395        const invalid = findInvalidWords(words);396        return { ok: true, data: { valid: invalid.length === 0, invalid } };397      }398      case "GET_RECOVERY_WORDS": {399        // Must be unlocked and have recovery set up (vault must be v2.12+).400        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };401        try {402          const words = await vault.getRecoveryWords();403          return { ok: true, data: words };404        } catch (e) {405          // pre-v2.12 vault that hasn't migrated406          return { ok: false, error: "recovery_not_setup" };407        }408      }409      case "RECOVER_WITH_WORDS": {410        // User has lost their password but has their 12 recovery words.411        // We: (1) validate the words, (2) re-encrypt vault with new password.412        const { words, newPassword } = msg.payload as {413          words: string[];414          newPassword: string;415        };416        const stored = await vault.loadSlotA();417        if (!stored) return { ok: false, error: "no vault" };418        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {419          return { ok: false, error: "recovery_not_setup" };420        }421        // Unwrap the root key from the recovery escrow.422        try {423          await vault.unwrapRootKeyForRecovery(424            stored.recovery_wrapped_root_key,425            stored.recovery_nonce ?? "",426            stored.recovery_tag ?? "",427            stored.recovery_salt,428            words429          );430        } catch {431          return { ok: false, error: "invalid_recovery_words" };432        }433        // Re-key: derive fresh salt + key from new password.434        const newSalt = vault.generateSalt();435        const newKey = await vault.deriveKey(newPassword, newSalt);436        // Re-wrap root key under the new password's derived key so the same437        // recovery words continue to work after the password change.438        await vault.rewrapRootKeyForPassword(newKey, newSalt);439        // Re-encrypt vault entries with the new key.440        await vault.changePasswordWithNewKey(newSalt, newKey);441        await setupAutoLock();442        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });443        return { ok: true };444      }445      case "LOCK":446        vault.lock();447        if (isNativePlatform()) await clearInMemoryVault();448        return { ok: true };449      case "IS_UNLOCKED":450        return { ok: true, data: vault.isUnlocked() };451      case "GET_VAULT_STATUS":452        return { ok: true, unlocked: vault.isUnlocked() };453      case "HAS_VAULT":454        return { ok: true, data: await vault.hasVault() };455      case "GET_ENTRIES":456        return { ok: true, data: vault.getEntries() };457      case "ADD_ENTRY": {458        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };459        const entry = await vault.addEntry(msg.payload as any);460        return { ok: true, data: entry };461      }462      case "BATCH_ADD_ENTRIES": {463        const { entries } = msg.payload as { entries: any[] };464        const added = await vault.batchAddEntries(entries);465        return { ok: true, data: added };466      }467      case "RESTORE_ENTRIES": {468        const { entries, mode, settings } = msg.payload as {469          entries: any[];470          mode: "replace" | "merge";471          settings?: vault.VaultSettings;472        };473        const summary = await vault.restoreEntries(entries, mode);474        if (settings && typeof settings === "object") {475          await vault.updateSettings(settings);476        }477        return { ok: true, data: summary };478      }479      case "CLEAR_VAULT_ENTRIES": {480        await vault.clearVaultEntries("REPLACE_ALL");481        return { ok: true };482      }483      case "GET_VAULT_HISTORY": {484        const snapshots = await vault.getVaultHistory();485        return { ok: true, data: snapshots };486      }487      case "RESTORE_VAULT_SNAPSHOT": {488        const { snapshotId } = msg.payload as { snapshotId: string };489        const result = await vault.restoreVaultSnapshot(snapshotId);490        if (!result.ok) return { ok: false, error: result.error };491        broadcastToContentScripts({ type: "VAULT_LOCKED" });492        return { ok: true };493      }494      case "COUNT_DUPLICATES": {495        return { ok: true, data: vault.countDuplicates() };496      }497      case "DEDUPLICATE_ENTRIES": {498        const removed = await vault.deduplicateEntries();499        return { ok: true, data: removed };500      }501      case "UPDATE_ENTRY": {502        const { id, patch } = msg.payload as any;503        await vault.updateEntry(id, patch);504        return { ok: true };505      }506      case "ADD_ADDITIONAL_URL": {507        const { id, url } = msg.payload as { id: string; url: string };508        const trimmed = typeof url === "string" ? url.trim() : "";509        if (!trimmed) return { ok: false, error: "url required" };510        const existing = vault.getEntryById(id);511        if (!existing) return { ok: false, error: "entry not found" };512        if (existing.type !== "login") return { ok: false, error: "login entries only" };513        const merged = [...(existing.additionalUrls ?? []), trimmed];514        await vault.updateEntry(id, { additionalUrls: merged });515        return { ok: true };516      }517      case "DELETE_ENTRY": {518        const { id } = msg.payload as { id: string };519        await vault.deleteEntry(id);520        return { ok: true };521      }522      case "GET_DELETED_ENTRIES":523        return { ok: true, data: vault.getDeletedEntries() };524      case "RESTORE_ENTRY": {525        const { id } = msg.payload as { id: string };526        await vault.restoreEntry(id);527        return { ok: true };528      }529      case "PURGE_ENTRY": {530        const { id } = msg.payload as { id: string };531        await vault.purgeEntry(id);532        return { ok: true };533      }534      case "PURGE_EXPIRED_TRASH": {535        const { retentionMs } = msg.payload as { retentionMs: number };536        const purged = await vault.purgeExpiredTrash(retentionMs);537        return { ok: true, data: purged };538      }539      case "SAVE_NOTE": {540        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };541        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };542        const now = Date.now();543        if (id) {544          const existing = vault.getEntryById(id);545          if (!existing) return { ok: false, error: "not_found" };546          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });547          return { ok: true, data: vault.getEntryById(id) };548        } else {549          const entry = await vault.addEntry({550            type: "note",551            title: title || "Untitled",552            notes: body,553            createdAt: now,554            modifiedAt: now,555          } as any);556          return { ok: true, data: entry };557        }558      }559      case "DELETE_NOTE": {560        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };561        const { id } = msg.payload as { id: string };562        await vault.deleteEntry(id);563        return { ok: true };564      }565      case "GET_NOTES": {566        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };567        const notes = vault.getEntries().filter(568          (e) => e.type === "note" && !e.deletedAt569        );570        return { ok: true, data: notes } as MessageResponse;571      }572      case "SEARCH_VAULT": {573        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };574        const { query } = msg.payload as { query: string };575        const q = query.toLowerCase();576        const searchResults = vault.getEntries().filter(577          (e) =>578            !e.deletedAt &&579            (e.title.toLowerCase().includes(q) ||580              e.notes?.toLowerCase().includes(q) ||581              e.username?.toLowerCase().includes(q))582        );583        return { ok: true, data: searchResults } as MessageResponse;584      }585      case "PAIRING_COMPLETED": {586        const { deviceName, publicKeyHex, deviceIp } = (msg.payload ?? {}) as {587          deviceName?: string;588          publicKeyHex?: string;589          deviceIp?: string;590        };591        if (!publicKeyHex) return { ok: false, error: "publicKeyHex required" };592        const { setHasPaired: setPaired } = await import("./sync-storage");593        await setPaired();594        try {595          await addPairedDevice({596            deviceId: publicKeyHex,597            displayName: deviceName ?? "Unknown",598            x25519PublicKey: publicKeyHex,599            pairedAt: Date.now(),600            lastSeenAt: Date.now(),601            lastKnownIp: deviceIp,602          });603        } catch {604          // Already paired — update IP if provided605          if (deviceIp) {606            await updatePairedDevice(publicKeyHex, { lastKnownIp: deviceIp, lastSeenAt: Date.now() });607          }608        }609        return { ok: true };610      }611      case "AUTOFILL_QUERY": {612        if (!vault.isUnlocked()) {613          return { ok: false, error: "VAULT_LOCKED" };614        }615        const { domain, includeAll, kind } = msg.payload as {616          domain: string;617          includeAll?: boolean;618          kind?: "login" | "card";619        };620        // kind="card": return saved cards as compact summaries for the621        // inline card silver platter. Cards are not domain-scoped — every622        // saved card is a candidate on every checkout page — so domain is623        // ignored when kind === "card".624        if (kind === "card") {625          const cards = vault.getEntries().filter((e) => e.type === "card");626          return {627            ok: true,628            data: cards.map((e) => ({629              id: e.id,630              title: e.cardNickname || e.title,631              cardholderName: e.cardholderName,632              last4: e.last4,633              expMonth: e.expMonth,634              expYear: e.expYear,635              network: e.network,636            })),637          };638        }639        // The inline selector fills username+password into a form. Passkey-640        // only entries have no password to fill; sign-in for those goes641        // through the WebAuthn path instead. Filter them out everywhere so642        // the user doesn't see four "GitHub" rows that mostly do nothing.643        // Notes and cards never belonged here either.644        const matches = (645          includeAll646            ? vault647                .getEntries()648                .filter((entry) => entry.type !== "note" && entry.type !== "card")649            : vault.queryDomain(domain)650        ).filter((entry) => !isPasskeyOnly(entry));651        return {652          ok: true,653          data: matches.map((e) =>654            includeAll655              ? {656                  id: e.id,657                  title: e.title,658                  hasPasskey: e.passkey !== undefined,659                }660              : {661                  id: e.id,662                  title: e.title,663                  username: e.username,664                  email: e.email,665                  url: e.url,666                  hasTotp: Boolean(e.totp),667                  hasPasskey: e.passkey !== undefined,668                }669          ),670        };671      }672      case "GET_ENTRY_FOR_FILL": {673        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };674        const { id } = msg.payload as { id: string };675        const entry = vault.getEntryById(id);676        if (!entry) return { ok: false, error: "entry not found" };677        // Passkey-only entries (passkey credential, no password) cannot be678        // filled into a form — sign-in goes through the WebAuthn path. A679        // login that ALSO has a passkey is still fillable for its password.680        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey not fillable" };681        // Strip the passkey credential from the response — content scripts682        // never need the private key, and there's no reason to expose the683        // public credential metadata over the boundary either.684        const { passkey: _strippedPasskey, ...safeEntry } = entry;685        return { ok: true, data: safeEntry };686      }687      case "COPY": {688        const { text, label, alreadyWritten } = msg.payload as {689          text: string;690          label: string;691          alreadyWritten?: boolean;692        };693        await copyToClipboard(text, label, Boolean(alreadyWritten));694        return { ok: true };695      }696      case "CHECK_ALL_BREACHES": {697        const allEntries = vault.getEntries();698        const results: Record<string, number> = {};699        for (const entry of allEntries) {700          if (entry.type === "note") continue;701          if (!entry.password) continue;702          results[entry.id] = await vault.checkBreach(entry.password);703          // Small delay — be a good citizen to the HIBP API704          await new Promise((r) => setTimeout(r, 200));705        }706        // Persist any non-zero counts back to entries707        for (const [id, count] of Object.entries(results)) {708          const entry = vault.getEntryById(id);709          if (entry && (entry.breach ?? 0) !== count) {710            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });711          }712        }713        return { ok: true, data: results };714      }715      case "GET_SETTINGS":716        return { ok: true, data: await vault.ensureSettingsLoaded() };717      case "UPDATE_SETTINGS": {718        const patch = msg.payload as Record<string, unknown>;719        await vault.updateSettings(patch as any);720        if (typeof patch.autoLockMinutes === "number") {721          await setupAutoLock();722          if (vault.isUnlocked()) touchAutoLock();723        }724        return { ok: true };725      }726      case "GET_PENDING_PASSKEY":727        return { ok: true, data: await getPendingPasskeyRequest() };728      case "APPROVE_PASSKEY": {729        const { requestId } = msg.payload as { requestId: number };730        await resolvePendingPasskeyRequest(requestId, true);731        return { ok: true };732      }733      case "DENY_PASSKEY": {734        const { requestId } = msg.payload as { requestId: number };735        await resolvePendingPasskeyRequest(requestId, false);736        return { ok: true };737      }738      case "GET_PASSKEY_PROVIDER_STATE":739        return { ok: true, data: await getPasskeyProviderState() };740      case "SET_PASSKEY_PROVIDER_ENABLED": {741        const { enabled } = msg.payload as { enabled: boolean };742        // Disabling is always free; gating fires only when a free user is743        // trying to turn passkey interception on.744        if (enabled) {745          const gate = await requirePro("passkeys");746          if (!gate.allowed) return { ok: false, error: "pro_required" };747        }748        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };749      }750      case "FIRE_CANARY_PING": {751        const { webhookUrl, entryTitle, trigger } = msg.payload as {752          webhookUrl: string;753          entryTitle: string;754          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";755        };756        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {757          return { ok: false, error: "invalid webhook url" };758        }759        const body = JSON.stringify({760          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",761          entry: entryTitle,762          trigger,763          timestamp: new Date().toISOString(),764          source: "peach-extension",765        });766        if (trigger === "test") {767          // Permitted outbound fetch: user-configured canary alert endpoint768          // (validated by isAllowedCanaryWebhookUrl above). This is the769          // only non-HIBP outbound call in the extension — see770          // Projects.md §3.7. Test pings are awaited so the UI can show771          // success/failure.772          try {773            const res = await fetch(webhookUrl, {774              method: "POST",775              headers: { "Content-Type": "application/json" },776              body,777            });778            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };779          } catch (err) {780            return { ok: false, error: err instanceof Error ? err.message : "network error" };781          }782        }783        // Non-test triggers are fire-and-forget784        fetch(webhookUrl, {785          method: "POST",786          headers: { "Content-Type": "application/json" },787          body,788        }).catch(() => {});789        return { ok: true };790      }791      case "ACTIVATE_LICENSE": {792        const { key } = msg.payload as { key: string };793        const licenseInfo = await activateLicense(key);794        return { ok: true, data: licenseInfo };795      }796      case "GET_LICENSE": {797        const licenseInfo = await getLicenseInfo();798        return { ok: true, data: licenseInfo };799      }800      case "GET_LICENSE_KEY": {801        const key = await getLicenseKey();802        return { ok: true, data: key };803      }804      case "DEACTIVATE_LICENSE": {805        await deactivateLicense();806        return { ok: true };807      }808      case "SHOULD_PLAY_CELEBRATION": {809        const should = await shouldPlayCelebration();810        return { ok: true, data: should };811      }812      case "MARK_CELEBRATION_PLAYED": {813        await markCelebrationPlayed();814        return { ok: true };815      }816      case "GET_CODEX_VAULT_DATA": {817        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the818        // popup navigates to the License section without further coordination.819        const gate = await requirePro("codex");820        if (!gate.allowed) return { ok: false, error: "pro_required" };821        return await handleGetCodexVaultData();822      }823      case "ESTIMATE_CODEX_PAGES": {824        const gate = await requirePro("codex");825        if (!gate.allowed) return { ok: false, error: "pro_required" };826        return await handleEstimateCodexPages();827      }828      case "RESTORE_FROM_CODEX": {829        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still830        // be able to restore a vault that was printed by a Pro user.831        // DO NOT add a Pro gate here.832        const payload = msg.payload as CodexRestorePayload;833        return await handleRestoreFromCodex(payload);834      }835      case "OPEN_PRO_GATE": {836        // Content script requests: open popup and navigate to License section.837        const { feature } = (msg.payload ?? {}) as { feature?: string };838        if (chrome.storage.session) {839          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });840        }841        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }842        return { ok: true };843      }844      case "GET_IDENTITIES": {845        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };846        return { ok: true, data: vault.getIdentities() };847      }848      case "TOUCH_AUTO_LOCK": {849        // touchAutoLock() is already called by shouldRefreshAutoLock above;850        // this case just gives the popup a typed message to keep the session alive.851        return { ok: true };852      }853      case "GET_ADVANCED_HEALTH_REPORT": {854        const gate = await requirePro("advanced_health");855        if (!gate.allowed) return { ok: false, error: "pro_required" };856        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };857        const report = await buildAdvancedHealthReport(vault.getEntries());858        return { ok: true, data: report };859      }860      case "INITIATE_PASSWORD_CHANGE": {861        const gate = await requirePro("smart_password_change");862        if (!gate.allowed) return { ok: false, error: "pro_required" };863        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };864        const { id } = msg.payload as { id: string };865        const entry = vault.getEntryById(id);866        if (!entry) return { ok: false, error: "entry not found" };867        const url = resolveResetUrl(entry);868        if (!url) return { ok: false, error: "no reset url" };869        try {870          await chrome.tabs.create({ url });871          return { ok: true, data: { url } };872        } catch (err) {873          return {874            ok: false,875            error: err instanceof Error ? err.message : "failed to open tab",876          };877        }878      }879      case "IS_DURESS_ENABLED": {880        const enabled = await vault.isDuressEnabled();881        return { ok: true, data: enabled };882      }883      case "SETUP_DURESS": {884        const { duressPassword } = msg.payload as { duressPassword: string };885        await vault.setupDuress(duressPassword);886        return { ok: true };887      }888      case "DISABLE_DURESS": {889        await vault.disableDuress();890        return { ok: true };891      }892      case "VERIFY_MAIN_PASSWORD": {893        const { password } = msg.payload as { password: string };894        const ok = await vault.verifyMainPassword(password);895        return { ok: true, data: ok };896      }897      case "CHANGE_PASSWORD": {898        const { currentPassword, newPassword } = msg.payload as {899          currentPassword: string;900          newPassword: string;901        };902        const changed = await vault.changePassword(currentPassword, newPassword);903        return changed904          ? { ok: true }905          : { ok: false, error: "incorrect current password" };906      }907      case "GET_SITE_PASSWORD_POLICY": {908        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });909        if (!tab?.id) return { ok: true, data: null };910        try {911          const response = await chrome.tabs.sendMessage(tab.id, {912            type: "GET_SITE_PASSWORD_POLICY",913          });914          return (response as MessageResponse) ?? { ok: true, data: null };915        } catch {916          return { ok: true, data: null };917        }918      }919      case "GET_SYNC_STATE": {920        const pairedDevices = await getPairedDevices();921        const trustedNetworks = await getTrustedNetworks();922        const tailscale = await isOnTailscale();923        const pro = await isProUser();924925        let status: SyncStatus = "offline";926        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {927          if (pairedDevices.length === 0) {928            status = "no_peers";929          } else {930            status = "synced";931          }932        } else {933          status = "not_trusted";934        }935936        const lastSyncRaw = await storageGet("peach_last_sync_at");937        const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN;938        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined;939940        return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } };941      }942      case "GET_PAIRED_DEVICES": {943        const devices = await getPairedDevices();944        return { ok: true, data: { devices } };945      }946      case "GET_SYNC_STATUS": {947        const lastSyncRaw = await storageGet("peach_last_sync_at");948        const lastSyncParsed = lastSyncRaw ? parseInt(lastSyncRaw, 10) : NaN;949        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : null;950        const status: 'up_to_date' | 'never' = lastSyncAt ? 'up_to_date' : 'never';951        return { ok: true, data: { status, lastSyncAt } };952      }953      case "ACCEPT_PAIRING": {954        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.955        return { ok: true };956      }957      case "REMOVE_PAIRED_DEVICE": {958        const { deviceId } = msg.payload as { deviceId: string };959        await removePairedDevice(deviceId);960        return { ok: true };961      }962      case "REMOVE_TRUSTED_NETWORK": {963        const { ssid, bssid, isTailscale } = msg.payload as any;964        const networks = await getTrustedNetworks();965        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 966          (isTailscale ? n.isTailscale : n.ssid === ssid) && 967          (!bssid || n.bssid === bssid)968        );969        if (network) {970          await removeTrustedNetwork(network.addedAt);971        }972        return { ok: true };973      }974      case "MARK_NETWORK_TRUSTED": {975        const network = await getCurrentNetwork();976        await addTrustedNetwork({977          ssid: network.ssid,978          bssid: network.bssid,979          isTailscale: network.isTailscale,980          addedAt: Date.now(),981        });982        return { ok: true };983      }984      case "GET_INCOMING_PAIRING_REQUEST": {985        const request = await getIncomingPairingRequest();986        return { ok: true, data: request };987      }988      case "RESPOND_INCOMING_PAIRING": {989        const { accept } = msg.payload as { accept: boolean };990        const request = await getIncomingPairingRequest();991        if (!request) return { ok: false, error: "no_pending_request" };992        if (Date.now() > request.expiresAt) {993          await clearIncomingPairingRequest();994          return { ok: false, error: "expired" };995        }996        await clearIncomingPairingRequest();997        if (accept) {998          await addPairedDevice({999            deviceId: request.publicKeyHex,1000            displayName: request.deviceName,1001            x25519PublicKey: request.publicKeyHex,1002            pairedAt: Date.now(),1003            lastSeenAt: Date.now(),1004          });1005        }1006        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };1007      }1008      case "START_PAIRING_SERVER": {1009        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.1010        const token = generateSixDigitToken();1011        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;1012        await setActivePairingToken({ token, expiresAt });1013        // Fire-and-forget subnet scan — finds the phone after it scans the QR1014        // and calls SCAN_PAIRING_QR to register the token with SyncPlugin.1015        if (!isNativePlatform()) {1016          void runPairingSubnetScan(token);1017        }1018        return { ok: true, data: { token, expiresAt } };1019      }1020      case "STOP_PAIRING_SERVER": {1021        try {1022          await setActivePairingToken(null);1023        } catch { /* best-effort */ }1024        return { ok: true };1025      }1026      case "GET_RECENT_PAIRING": {1027        const recent = await consumeRecentPairing();1028        return { ok: true, data: recent };1029      }1030      case "DEBUG_INJECT_INCOMING_PAIRING": {1031        // Manual E2E rehearsal hook. Inserts a synthetic incoming pairing1032        // request into session storage so Phase 7 banner UX can be exercised1033        // without a live native host. No Pro gate — this is a no-op in1034        // production unless explicitly invoked from a Settings debug action.1035        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {1036          deviceName?: string;1037          publicKeyHex?: string;1038        };1039        if (!deviceName || !publicKeyHex) {1040          return { ok: false, error: "missing_payload" };1041        }1042        const now = Date.now();1043        await setIncomingPairingRequest({1044          deviceName,1045          publicKeyHex,1046          receivedAt: now,1047          expiresAt: now + 60_000,1048        });1049        return { ok: true };1050      }1051      case "RESET_SYNC_IDENTITY": {1052        const gate = await requirePro("sync");1053        if (!gate.allowed) return { ok: false, error: "pro_required" };1054        const devices = await getPairedDevices();1055        for (const device of devices) {1056          await removePairedDevice(device.deviceId);1057        }1058        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };1059      }1060      case "RECORD_MANUAL_SUMMON": {1061        const { domain } = msg.payload as { domain: string };1062        const settings = vault.getSettings();1063        const existing = settings.manualSummonDomains?.[domain];1064        const now = Date.now();1065        await vault.updateSettings({1066          manualSummonDomains: {1067            ...settings.manualSummonDomains,1068            [domain]: {1069              firstSummonedAt: existing?.firstSummonedAt ?? now,1070              summonCount: (existing?.summonCount ?? 0) + 1,1071              lastSummonedAt: now,1072            },1073          },1074        });1075        return { ok: true };1076      }1077      case "DECLINE_CARD_SAVE": {1078        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1079        await vault.declineCardSaveOffer(last4, expMonth, expYear);1080        return { ok: true };1081      }1082      case "IS_CARD_DECLINED": {1083        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1084        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1085        return { ok: true, data: declined };1086      }1087      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1088        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1089          rpId?: string;1090          rpName?: string;1091          userName?: string;1092          userDisplayName?: string;1093        };1094        if (!rpId || !userName) return { ok: false, error: "rpId and userName required" };1095        return await initiateFirefoxPasskeyCreate({1096          rpId,1097          rpName: rpName ?? rpId,1098          userName,1099          userDisplayName,1100        });1101      }11021103      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1104        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1105        if (!payload) return { ok: false, error: "missing payload" };1106        return await completeFirefoxPasskeyCreate(payload);1107      }11081109      case "PASSKEY_OFFER_DECLINE": {1110        const { domain } = (msg.payload ?? {}) as { domain?: string };1111        if (!domain) return { ok: false, error: "domain required" };1112        await recordPasskeyOfferDecline(domain);1113        return { ok: true };1114      }11151116      case "GET_PASSKEY_OFFER_DECLINED": {1117        const { domain } = (msg.payload ?? {}) as { domain?: string };1118        if (!domain) return { ok: false, error: "domain required" };1119        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1120      }11211122      case "PASSKEY_HAS_CREDENTIALS": {1123        const payload = msg.payload as {1124          rpId?: string;1125          allowCredentials?: Array<{ id: string; type?: string }>;1126        } | undefined;1127        if (!payload?.rpId) return { ok: false, error: "rpId required" };1128        return await handlePasskeyHasCredentials({1129          rpId: payload.rpId,1130          allowCredentials: payload.allowCredentials ?? [],1131        });1132      }11331134      case "PASSKEY_CREATE": {1135        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1136        if (!payload?.rpId || !payload?.userName) {1137          return { ok: false, error: "rpId and userName required" };1138        }1139        return await handleFirefoxPasskeyCreate(payload);1140      }11411142      case "PASSKEY_GET": {1143        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1144        if (!payload?.rpId) return { ok: false, error: "rpId required" };1145        return await handleFirefoxPasskeyGet(payload);1146      }11471148      case "PASSKEY_AUTH_RESPONSE": {1149        const { requestId, approved } = (msg.payload ?? {}) as {1150          requestId?: string | number;1151          approved?: boolean;1152        };1153        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1154          return { ok: false, error: 'requestId and approved required' };1155        }1156        await resolvePendingPasskeyRequest(Number(requestId), approved);1157        return { ok: true };1158      }11591160      case "GET_PASSKEY_FOR_DOMAIN": {1161        const { domain } = (msg.payload ?? {}) as { domain?: string };1162        if (!domain) return { ok: false, error: "domain required" };1163        if (!vault.isUnlocked()) return { ok: true, data: null };1164        const match = vault1165          .getEntries()1166          .find((entry) => entry.passkey?.rpId === domain);1167        if (!match || !match.passkey) return { ok: true, data: null };1168        // Slim shape — only the fields State 11 needs. Never expose private1169        // key material, even though this is locked behind isUnlocked.1170        return {1171          ok: true,1172          data: {1173            rpId: match.passkey.rpId,1174            userName: match.passkey.userName,1175            browser: match.passkey.browser,1176          },1177        };1178      }11791180      case "DESTROY_VAULT": {1181        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1182        // storage.local.clear() wipes every Peach key (slots, settings, license,1183        // onboarded flag, history, sync state, declined cards, recall, etc.);1184        // session.clear() wipes pending passkey requests + pro-notice queues.1185        // Caller (Panic.tsx) handles UI navigation back to onboarding.1186        vault.lock();1187        await storageClear();1188        await vault.clearVaultHistory();1189        if (chrome.storage.session) {1190          await chrome.storage.session.clear();1191        }1192        return { ok: true };1193      }11941195      case "SUBMIT_FEEDBACK": {1196        const { category, message, version, browser } = msg.payload as {1197          category: string;1198          message: string;1199          version: string;1200          browser: string;1201        };1202        if (!message.trim()) return { ok: false, error: "message is empty" };1203        if (!FEEDBACK_ENDPOINT) return { ok: true };1204        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1205          return { ok: false, error: "invalid feedback endpoint" };1206        }1207        try {1208          const res = await fetch(FEEDBACK_ENDPOINT, {1209            method: "POST",1210            headers: { "Content-Type": "application/json" },1211            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1212          });1213          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1214        } catch (err) {1215          return { ok: false, error: err instanceof Error ? err.message : "network error" };1216        }1217      }1218      case "TRIGGER_SYNC": {1219        const gate = await requirePro("sync");1220        if (!gate.allowed) return { ok: false, error: "pro_required" };1221        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };12221223        if (isNativePlatform()) {1224          // Phone is the server — ensure it's listening for desktop connections.1225          syncBridge()?.ensureServerRunning?.();1226          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };1227        }12281229        // Desktop: iterate all paired devices and sync with each.1230        const paired = await getPairedDevices();1231        if (!paired.length) return { ok: true, data: { syncedCount: 0, reason: "no_paired_devices" } };12321233        const subnet = await getLocalSubnet();1234        const results: Array<{ device: string } & SyncResult> = [];12351236        for (const device of paired) {1237          if (!device.x25519PublicKey) continue;12381239          let result: SyncResult;12401241          // Fast path — use last known IP1242          if (device.lastKnownIp) {1243            result = await doVaultSync(device.lastKnownIp, device.x25519PublicKey);1244          } else {1245            result = { status: 'errored', applied: false, error: 'no_ip' };1246          }12471248          // Discovery path — scan if fast path failed1249          if (result.status === 'errored' && subnet) {1250            const newIp = await discoverDevice(subnet, device.x25519PublicKey);1251            if (newIp) {1252              await updatePairedDevice(device.x25519PublicKey, { lastKnownIp: newIp });1253              result = await doVaultSync(newIp, device.x25519PublicKey);1254            }1255          }12561257          if (result.status === 'completed') {1258            await updatePairedDevice(device.x25519PublicKey, {1259              lastSeenAt: Date.now(),1260              lastSyncAt: Date.now(),1261            });1262          }12631264          results.push({ device: device.displayName, ...result });1265        }12661267        const syncedCount = results.filter(r => r.status === 'completed').length;1268        if (syncedCount > 0) {1269          await chrome.storage.local.set({ peach_last_sync_at: String(Date.now()) });1270        }1271        return { ok: true, data: { syncedCount, results } };1272      }1273      // Android-only: biometric unlock with pre-derived key.1274      case "UNLOCK_WITH_KEY": {1275        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1276        if (!isNativePlatform()) {1277          return { ok: false, error: "desktop_only_uses_password" };1278        }1279        try {1280          const result = await vault.unlockWithKey(masterKeyHex);1281          if (result.ok) {1282            onVaultUnlocked();1283            await publishInMemoryVault(result.entries);1284          }1285          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1286        } catch {1287          return { ok: false, error: "invalid_key" };1288        }1289      }1290      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1291      case "GET_DERIVED_KEY": {1292        if (!isNativePlatform()) {1293          return { ok: false, error: "android_only" };1294        }1295        if (!vault.isUnlocked()) {1296          return { ok: false, error: "vault_locked" };1297        }1298        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1299      }1300      // Android: scanned a QR containing a desktop pairing token.1301      case "SCAN_PAIRING_QR": {1302        if (!isNativePlatform()) {1303          return { ok: false, error: "android_only" };1304        }1305        const { token } = msg.payload as { token: string };1306        syncBridge()?.startPairingSession?.({ token });1307        return { ok: true };1308      }1309      // Android: desktop opened a sync connection to the phone's WS server.1310      // Run the responder side of the vault exchange.1311      case "SYNC_SESSION_STARTED": {1312        if (!isNativePlatform()) return { ok: false };1313        if (!vault.isUnlocked()) {1314          return { ok: false, error: "vault_locked" };1315        }1316        const { connectionId } = (msg.payload ?? {}) as { connectionId?: string };1317        if (!connectionId) return { ok: false, error: "missing_connection_id" };13181319        const transport = createAndroidResponderTransport(connectionId);13201321        // Authenticate the initiator before exchanging any vault data. The1322        // native side has already completed the Noise NK handshake; auth1323        // frames here ride the Noise transport (native encrypts/decrypts).1324        const identity = await vault.getSyncIdentity();1325        try {1326          const noiseSessionStub = {1327            encrypt: (b: Uint8Array) => b,1328            decrypt: (b: Uint8Array) => b,1329            handshakeHash: new Uint8Array(32),1330          };1331          const { initiatorPublicKey } = await performResponderAuth(1332            noiseSessionStub,1333            identity.privateKeyBytes,1334            identity.publicKeyBytes,1335            transport.send,1336            transport.receive,1337          );1338          const initiatorHex = noiseBytesToHex(initiatorPublicKey);1339          const paired = await getPairedDevices();1340          if (!paired.some(d => d.x25519PublicKey === initiatorHex)) {1341            await transport.close();1342            return { ok: false, error: "sync_rejected_unpaired_initiator" };1343          }1344        } catch (err) {1345          await transport.close();1346          return { ok: false, error: `sync_auth_failed: ${String(err)}` };1347        }13481349        const result = await runBlobSyncSession('responder', transport, buildSyncDeps());1350        if (result.applied) {1351          await publishInMemoryVault(vault.getEntries());1352        }1353        return { ok: true, data: result };1354      }1355      // Android: returns the phone's WiFi IP address.1356      case "GET_LOCAL_IP": {1357        if (!isNativePlatform()) {1358          return { ok: false, error: "android_only" };1359        }1360        const { ip } = (await syncBridge()?.getLocalIp?.()) ?? { ip: "" };1361        return { ok: true, data: { ip } };1362      }1363      case "GET_IDENTITY_SUGGESTIONS": {1364        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1365        const entries = vault.getEntries();1366        const suggestions = buildIdentitySuggestions(entries);1367        return { ok: true, data: { suggestions } };1368      }1369      case "POPULATE_INLINE_VAULT": {1370        if (!isNativePlatform()) return { ok: false };1371        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1372        const entries = vault.getEntries();1373        await publishInMemoryVault(entries);1374        return { ok: true };1375      }1376      case "ML_INIT":1377        return { ok: true };13781379      case "ML_PREDICT_BATCH": {1380        const { featuresArray } = msg.payload as { featuresArray: MLFieldFeatures[] };1381        return { ok: true, data: mlPredictBatch(featuresArray) };1382      }13831384      default:1385        return { ok: false, error: "unknown message type" };1386    }1387  } catch (err) {1388    return {1389      ok: false,1390      error: err instanceof Error ? err.message : "operation failed",1391    };1392  }1393}13941395// --- Mobile platform helpers ---13961397// Android: populates the in-memory vault used by PeachAutofillService.1398async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1399  const plugin = nativePlugin<{1400    setEntries?: (args: {1401      entries: Array<{1402        id: string;1403        title: string;1404        username: string;1405        email: string;1406        password: string;1407        url: string;1408        totp: string;1409        additionalUrls: string[];1410      }>;1411    }) => Promise<void>;1412  }>("InMemoryVaultPlugin");1413  if (!plugin?.setEntries) return;1414  await plugin.setEntries({1415    entries: entries.map((e) => ({1416      id: e.id,1417      title: e.title ?? "",1418      username: e.username ?? "",1419      email: (e as VaultEntry & { email?: string }).email ?? "",1420      password: e.password ?? "",1421      url: e.url ?? "",1422      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1423      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1424    })),1425  });1426}14271428// Android: clear the autofill in-memory store on lock.1429async function clearInMemoryVault(): Promise<void> {1430  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1431  if (!plugin?.clearEntries) return;1432  await plugin.clearEntries();1433}14341435interface SyncBridge {1436  ensureServerRunning?: () => void;1437  startPairingSession?: (args: { token: string }) => void;1438  getLocalIp?: () => Promise<{ ip: string }>;1439  sendToConnection?: (args: { connectionId: string; data: string }) => Promise<void>;1440  addListener?: (event: string, handler: (data: Record<string, string>) => void) => void;1441}14421443// Resolve the Capacitor SyncPlugin at call time — module-load resolution1444// races with Capacitor's plugin registration on the Android WebView.1445function syncBridge(): SyncBridge | null {1446  return nativePlugin<SyncBridge>("SyncPlugin");1447}14481449// Build a SyncTransport for the Android responder path — the phone's WS server1450// already has an open connection from the desktop. We send back via1451// SyncPlugin.sendToConnection and receive via the peach:sync-frame queue.1452const androidSyncFrameQueues = new Map<string, Array<(frame: string) => void>>();14531454export function deliverAndroidSyncFrame(connectionId: string, frame: string): void {1455  const queue = androidSyncFrameQueues.get(connectionId);1456  if (queue?.length) queue.shift()!(frame);1457}14581459function createAndroidResponderTransport(connectionId: string) {1460  const pendingReceivers: Array<(frame: string) => void> = [];1461  androidSyncFrameQueues.set(connectionId, pendingReceivers);14621463  return {1464    send: async (data: Uint8Array) => {1465      await syncBridge()?.sendToConnection?.({ connectionId, data: bytesToBase64(data) });1466    },1467    receive: (): Promise<Uint8Array> => new Promise((res) => {1468      pendingReceivers.push((frame) => {1469        res(frame ? base64ToBytes(frame) : new Uint8Array(0));1470      });1471    }),1472    close: async () => {1473      androidSyncFrameQueues.delete(connectionId);1474    },1475  };1476}14771478// Returns username use-counts from the vault, sorted by frequency. Each row1479// also carries the entry's email so the popup can suggest the email/username1480// pair the user has actually used together.1481function buildIdentitySuggestions(1482  entries: VaultEntry[],1483): Array<{ email: string; username: string; count: number }> {1484  const usernameCounts = new Map<string, number>();1485  const usernameEmail = new Map<string, string>();1486  for (const entry of entries) {1487    const username = entry.username ?? "";1488    const email = (entry as VaultEntry & { email?: string }).email ?? "";1489    if (!username && !email) continue;1490    const key = username || email;1491    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1492    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1493  }1494  return Array.from(usernameCounts.entries())1495    .sort((a, b) => b[1] - a[1])1496    .map(([username, count]) => ({1497      email: usernameEmail.get(username) ?? "",1498      username,1499      count,1500    }));1501}15021503/** Notify all content scripts that the vault just became available. */1504function broadcastToContentScripts(message: { type: string }): void {1505  if (!chrome.tabs?.query) return;1506  chrome.tabs.query({}, (tabs) => {1507    for (const tab of tabs) {1508      if (tab.id !== undefined) {1509        chrome.tabs.sendMessage(tab.id, message).catch(() => {1510          // Tab may not have a content script — silently ignore1511        });1512      }1513    }1514  });1515}15161517function shouldRefreshAutoLock(type: MessageType): boolean {1518  return (1519    type !== "HAS_VAULT" &&1520    type !== "IS_UNLOCKED" &&1521    type !== "GET_VAULT_STATUS" &&1522    type !== "LOCK" &&1523    type !== "UPDATE_SETTINGS" &&1524    type !== "GET_PENDING_PASSKEY" &&1525    type !== "GET_PASSKEY_PROVIDER_STATE" &&1526    type !== "DECLINE_CARD_SAVE" &&1527    type !== "IS_CARD_DECLINED" &&1528    type !== "SUBMIT_FEEDBACK"1529  );1530}15311532function isAllowedCanaryWebhookUrl(value: string): boolean {1533  try {1534    const url = new URL(value);1535    if (url.protocol !== "https:") return false;15361537    const hostname = url.hostname.toLowerCase();1538    if (1539      hostname === "localhost" ||1540      hostname.endsWith(".localhost") ||1541      isPrivateIpv4(hostname) ||1542      isPrivateIpv6(hostname)1543    ) {1544      return false;1545    }15461547    return true;1548  } catch {1549    return false;1550  }1551}15521553function isPrivateIpv4(hostname: string): boolean {1554  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1555    return true;1556  }15571558  const octets = hostname.split(".").map((part) => Number(part));1559  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1560    return false;1561  }15621563  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1564}15651566function isPrivateIpv6(hostname: string): boolean {1567  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1568  return (1569    normalized === "::1" ||1570    normalized.startsWith("fc") ||1571    normalized.startsWith("fd") ||1572    normalized.startsWith("fe80:")1573  );1574}