messages.ts

59.6 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard } from "./clipboard";13import { setupAutoLock, touchAutoLock } from "./alarms";14import * as vault from "./vault";15import {16  handleEstimateCodexPages,17  handleGetCodexVaultData,18  handleRestoreFromCodex,19} from "./codex-handlers";20import type { CodexRestorePayload } from "../shared/codex-types";21import {22  activateLicense,23  deactivateLicense,24  getLicenseInfo,25  getLicenseKey,26  isProUser,27  markCelebrationPlayed,28  shouldPlayCelebration,29} from "./license";30import {31  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// ---------------------------------------------------------------------------170171export function 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) {193        const reloaded = await vault.reloadEntriesAfterSync();194        if (!reloaded) {195          // The remote vault was encrypted under a different key (the remote196          // changed password). Our in-memory entries are now stale and cannot197          // be re-encrypted without overwriting the just-applied blob. Lock198          // to force a re-unlock with the new password (H3/COR-005).199          vault.lock();200          chrome.runtime201            .sendMessage({ type: "VAULT_RELOCK_AFTER_SYNC" })202            .catch(() => {});203        }204      }205      return applied;206    },207  };208}209210async function doVaultSync(ip: string, publicKeyHex: string): Promise<SyncResult> {211  try {212    const identity = await vault.getSyncIdentity();213    const transport = await createWebSocketSyncTransport(214      `ws://${ip}:44100`,215      publicKeyHex,216      identity.privateKeyBytes,217      identity.publicKeyBytes,218    );219    return await runBlobSyncSession('initiator', transport, buildSyncDeps());220  } catch (err) {221    return { status: 'errored', applied: false, error: String(err) };222  }223}224225async function mergeDeviceRegistry(incoming: SyncableDevice[]): Promise<void> {226  const existing = await getPairedDevices();227  const existingKeys = new Set(existing.map(d => d.x25519PublicKey));228  for (const device of incoming) {229    if (!existingKeys.has(device.publicKeyHex)) {230      await addPairedDevice({231        deviceId: device.publicKeyHex,232        displayName: device.deviceName,233        x25519PublicKey: device.publicKeyHex,234        pairedAt: device.pairedAt,235        lastSeenAt: 0,236        lastKnownIp: '',237      }).catch(() => {});238    }239  }240}241242// Background pairing scan — runs after START_PAIRING_SERVER fires on desktop.243// Scans the local subnet for a phone that has accepted the pairing token,244// stores it, runs the initial vault exchange, then notifies the popup.245async function runPairingSubnetScan(token: string): Promise<void> {246  const subnet = await getLocalSubnet();247  if (!subnet) return;248249  const found = await scanForPairingPhone(subnet, token);250  if (!found) return;251252  const { ip, publicKeyHex } = found;253254  try {255    await addPairedDevice({256      deviceId: publicKeyHex,257      displayName: 'Peach',258      x25519PublicKey: publicKeyHex,259      pairedAt: Date.now(),260      lastSeenAt: Date.now(),261      lastKnownIp: ip,262    });263  } catch {264    // Already paired — update IP265    await updatePairedDevice(publicKeyHex, { lastKnownIp: ip, lastSeenAt: Date.now() });266  }267268  // Immediate vault exchange — the free one-time transfer269  await doVaultSync(ip, publicKeyHex);270271  chrome.runtime.sendMessage({272    type: 'PAIRING_COMPLETED',273    payload: { deviceName: 'Peach', publicKeyHex, deviceIp: ip },274  }).catch(() => {});275}276277export function setupMessageHandler(): void {278  chrome.runtime.onMessage.addListener(279    (msg: unknown, sender, sendResponse) => {280      if (!isMessage(msg)) {281        sendResponse({ ok: false, error: "invalid message" });282        return true;283      }284      handleMessage(msg, sender)285        .then(sendResponse)286        .catch((err) =>287          sendResponse({288            ok: false,289            error: err instanceof Error ? err.message : String(err),290          })291        );292      return true;293    }294  );295296  // Android: the chrome shim queues sendMessage calls until this handler is297  // registered. Without this hookup, every message hangs on Capacitor builds.298  // eslint-disable-next-line @typescript-eslint/no-explicit-any299  const reg = (globalThis as any).__peachRegisterMessageHandler;300  if (typeof reg === "function") {301    reg(async (m: unknown) => {302      if (!isMessage(m)) return { ok: false, error: "invalid message" };303      try {304        return await handleMessage(m);305      } catch (err) {306        return {307          ok: false,308          error: err instanceof Error ? err.message : String(err),309        };310      }311    });312  }313314  // Android: subscribe to SyncPlugin events.315  if (isNativePlatform()) {316    const syncPlug = nativePlugin<{317      addListener: (318        event: string,319        handler: (data: Record<string, string>) => void320      ) => void;321    }>("SyncPlugin");322323    // Pairing probe answered — store the paired device (desktop, no IP needed324    // since the desktop never acts as a WS server).325    syncPlug?.addListener?.("peach:pair-probe-answered", (data) => {326      const deviceName = data.deviceName ?? "Peach";327      const publicKeyHex = data.publicKeyHex ?? "";328      void (async () => {329        const { addPairedDevice, setHasPaired: setPaired } = await import("./sync-storage");330        await addPairedDevice({331          deviceId: publicKeyHex || (data.connectionId ?? "unknown"),332          displayName: deviceName,333          x25519PublicKey: publicKeyHex,334          pairedAt: Date.now(),335          lastSeenAt: Date.now(),336        }).catch(() => {});337        await setPaired();338        chrome.runtime.sendMessage({339          type: "PAIRING_COMPLETED",340          payload: { deviceName },341        }).catch(() => {});342      })();343    });344345    // Sync frame received — route to the waiting responder session.346    syncPlug?.addListener?.("peach:sync-frame", (data) => {347      const { connectionId, frame } = data;348      if (connectionId && frame) deliverAndroidSyncFrame(connectionId, frame);349    });350351    // Sync session started (SYNC_HELLO received by SyncPlugin) — dispatch as352    // a background message so SYNC_SESSION_STARTED handler runs the responder.353    syncPlug?.addListener?.("peach:sync-session-started", (data) => {354      const { connectionId } = data;355      if (!connectionId) return;356      void handleMessage({ type: "SYNC_SESSION_STARTED", payload: { connectionId } });357    });358  }359}360361function isMessage(m: unknown): m is Message {362  return typeof m === "object" && m !== null && "type" in m;363}364365export async function handleMessage(366  msg: Message,367  sender: Partial<chrome.runtime.MessageSender> = {}368): Promise<MessageResponse> {369  try {370    // Validate sender — only allow messages from our extension pages/scripts.371    // `sender.id` is undefined for messages originating from extension UI372    // (popup/options), which is legitimate; reject only when it is defined373    // and does not match our extension id.374    if (375      sender.id !== undefined &&376      sender.id !== chrome.runtime.id377    ) {378      return { ok: false, error: "invalid sender" };379    }380381    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {382      touchAutoLock();383    }384385    switch (msg.type) {386      case "CREATE_VAULT": {387        const { password } = msg.payload as { password: string };388        await vault.createVault(password);389        await setupAutoLock();390        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });391        onVaultUnlocked();392        return { ok: true };393      }394      case "UNLOCK": {395        const { password } = msg.payload as { password: string };396        const ok = await vault.unlock(password);397        if (ok) {398          await setupAutoLock();399          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });400          onVaultUnlocked();401          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());402        }403        return { ok };404      }405      case "VALIDATE_RECOVERY_WORDS": {406        const { words } = msg.payload as { words: string[] };407        const invalid = findInvalidWords(words);408        return { ok: true, data: { valid: invalid.length === 0, invalid } };409      }410      case "GET_RECOVERY_WORDS": {411        // Must be unlocked and have recovery set up (vault must be v2.12+).412        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };413        try {414          const words = await vault.getRecoveryWords();415          return { ok: true, data: words };416        } catch (e) {417          // pre-v2.12 vault that hasn't migrated418          return { ok: false, error: "recovery_not_setup" };419        }420      }421      case "RECOVER_WITH_WORDS": {422        // User has lost their password but has their 12 recovery words.423        // We: (1) validate the words, (2) re-encrypt vault with new password.424        const { words, newPassword } = msg.payload as {425          words: string[];426          newPassword: string;427        };428        const stored = await vault.loadSlotA();429        if (!stored) return { ok: false, error: "no vault" };430        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {431          return { ok: false, error: "recovery_not_setup" };432        }433        // Unwrap the root key from the recovery escrow.434        try {435          await vault.unwrapRootKeyForRecovery(436            stored.recovery_wrapped_root_key,437            stored.recovery_nonce ?? "",438            stored.recovery_tag ?? "",439            stored.recovery_salt,440            words441          );442        } catch {443          return { ok: false, error: "invalid_recovery_words" };444        }445        // Re-key: derive fresh salt + key from new password.446        const newSalt = vault.generateSalt();447        const newKey = await vault.deriveKey(newPassword, newSalt);448        // Re-wrap root key under the new password's derived key so the same449        // recovery words continue to work after the password change.450        await vault.rewrapRootKeyForPassword(newKey, newSalt);451        // Re-encrypt vault entries with the new key.452        await vault.changePasswordWithNewKey(newSalt, newKey);453        await setupAutoLock();454        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });455        return { ok: true };456      }457      case "LOCK":458        vault.lock();459        if (isNativePlatform()) await clearInMemoryVault();460        return { ok: true };461      case "IS_UNLOCKED":462        return { ok: true, data: vault.isUnlocked() };463      case "GET_VAULT_STATUS":464        return { ok: true, unlocked: vault.isUnlocked() };465      case "HAS_VAULT":466        return { ok: true, data: await vault.hasVault() };467      case "GET_ENTRIES":468        return { ok: true, data: vault.getEntries() };469      case "ADD_ENTRY": {470        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };471        const entry = await vault.addEntry(msg.payload as any);472        return { ok: true, data: entry };473      }474      case "BATCH_ADD_ENTRIES": {475        const { entries } = msg.payload as { entries: any[] };476        const added = await vault.batchAddEntries(entries);477        return { ok: true, data: added };478      }479      case "RESTORE_ENTRIES": {480        const { entries, mode, settings } = msg.payload as {481          entries: any[];482          mode: "replace" | "merge";483          settings?: vault.VaultSettings;484        };485        const summary = await vault.restoreEntries(entries, mode);486        if (settings && typeof settings === "object") {487          await vault.updateSettings(settings);488        }489        return { ok: true, data: summary };490      }491      case "CLEAR_VAULT_ENTRIES": {492        await vault.clearVaultEntries("REPLACE_ALL");493        return { ok: true };494      }495      case "GET_VAULT_HISTORY": {496        const snapshots = await vault.getVaultHistory();497        return { ok: true, data: snapshots };498      }499      case "RESTORE_VAULT_SNAPSHOT": {500        const { snapshotId } = msg.payload as { snapshotId: string };501        const result = await vault.restoreVaultSnapshot(snapshotId);502        if (!result.ok) return { ok: false, error: result.error };503        broadcastToContentScripts({ type: "VAULT_LOCKED" });504        return { ok: true };505      }506      case "COUNT_DUPLICATES": {507        return { ok: true, data: vault.countDuplicates() };508      }509      case "DEDUPLICATE_ENTRIES": {510        const removed = await vault.deduplicateEntries();511        return { ok: true, data: removed };512      }513      case "UPDATE_ENTRY": {514        const { id, patch } = msg.payload as any;515        await vault.updateEntry(id, patch);516        return { ok: true };517      }518      case "ADD_ADDITIONAL_URL": {519        const { id, url } = msg.payload as { id: string; url: string };520        const trimmed = typeof url === "string" ? url.trim() : "";521        if (!trimmed) return { ok: false, error: "url required" };522        const existing = vault.getEntryById(id);523        if (!existing) return { ok: false, error: "entry not found" };524        if (existing.type !== "login") return { ok: false, error: "login entries only" };525        const merged = [...(existing.additionalUrls ?? []), trimmed];526        await vault.updateEntry(id, { additionalUrls: merged });527        return { ok: true };528      }529      case "DELETE_ENTRY": {530        const { id } = msg.payload as { id: string };531        await vault.deleteEntry(id);532        return { ok: true };533      }534      case "GET_DELETED_ENTRIES":535        return { ok: true, data: vault.getDeletedEntries() };536      case "RESTORE_ENTRY": {537        const { id } = msg.payload as { id: string };538        await vault.restoreEntry(id);539        return { ok: true };540      }541      case "PURGE_ENTRY": {542        const { id } = msg.payload as { id: string };543        await vault.purgeEntry(id);544        return { ok: true };545      }546      case "PURGE_EXPIRED_TRASH": {547        const { retentionMs } = msg.payload as { retentionMs: number };548        const purged = await vault.purgeExpiredTrash(retentionMs);549        return { ok: true, data: purged };550      }551      case "SAVE_NOTE": {552        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };553        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };554        const now = Date.now();555        if (id) {556          const existing = vault.getEntryById(id);557          if (!existing) return { ok: false, error: "not_found" };558          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });559          return { ok: true, data: vault.getEntryById(id) };560        } else {561          const entry = await vault.addEntry({562            type: "note",563            title: title || "Untitled",564            notes: body,565            createdAt: now,566            modifiedAt: now,567          } as any);568          return { ok: true, data: entry };569        }570      }571      case "DELETE_NOTE": {572        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };573        const { id } = msg.payload as { id: string };574        await vault.deleteEntry(id);575        return { ok: true };576      }577      case "GET_NOTES": {578        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };579        const notes = vault.getEntries().filter(580          (e) => e.type === "note" && !e.deletedAt581        );582        return { ok: true, data: notes } as MessageResponse;583      }584      case "SEARCH_VAULT": {585        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };586        const { query } = msg.payload as { query: string };587        const q = query.toLowerCase();588        const searchResults = vault.getEntries().filter(589          (e) =>590            !e.deletedAt &&591            (e.title.toLowerCase().includes(q) ||592              e.notes?.toLowerCase().includes(q) ||593              e.username?.toLowerCase().includes(q))594        );595        return { ok: true, data: searchResults } as MessageResponse;596      }597      case "PAIRING_COMPLETED": {598        const { deviceName, publicKeyHex, deviceIp } = (msg.payload ?? {}) as {599          deviceName?: string;600          publicKeyHex?: string;601          deviceIp?: string;602        };603        if (!publicKeyHex) return { ok: false, error: "publicKeyHex required" };604        const { setHasPaired: setPaired } = await import("./sync-storage");605        await setPaired();606        try {607          await addPairedDevice({608            deviceId: publicKeyHex,609            displayName: deviceName ?? "Unknown",610            x25519PublicKey: publicKeyHex,611            pairedAt: Date.now(),612            lastSeenAt: Date.now(),613            lastKnownIp: deviceIp,614          });615        } catch {616          // Already paired — update IP if provided617          if (deviceIp) {618            await updatePairedDevice(publicKeyHex, { lastKnownIp: deviceIp, lastSeenAt: Date.now() });619          }620        }621        return { ok: true };622      }623      case "AUTOFILL_QUERY": {624        if (!vault.isUnlocked()) {625          return { ok: false, error: "VAULT_LOCKED" };626        }627        const { domain, includeAll, kind } = msg.payload as {628          domain: string;629          includeAll?: boolean;630          kind?: "login" | "card";631        };632        // kind="card": return saved cards as compact summaries for the633        // inline card silver platter. Cards are not domain-scoped — every634        // saved card is a candidate on every checkout page — so domain is635        // ignored when kind === "card".636        if (kind === "card") {637          const cards = vault.getEntries().filter((e) => e.type === "card");638          return {639            ok: true,640            data: cards.map((e) => ({641              id: e.id,642              title: e.cardNickname || e.title,643              cardholderName: e.cardholderName,644              last4: e.last4,645              expMonth: e.expMonth,646              expYear: e.expYear,647              network: e.network,648            })),649          };650        }651        // The inline selector fills username+password into a form. Passkey-652        // only entries have no password to fill; sign-in for those goes653        // through the WebAuthn path instead. Filter them out everywhere so654        // the user doesn't see four "GitHub" rows that mostly do nothing.655        // Notes and cards never belonged here either.656        const matches = (657          includeAll658            ? vault659                .getEntries()660                .filter((entry) => entry.type !== "note" && entry.type !== "card")661            : vault.queryDomain(domain)662        ).filter((entry) => !isPasskeyOnly(entry));663        return {664          ok: true,665          data: matches.map((e) =>666            includeAll667              ? {668                  id: e.id,669                  title: e.title,670                  hasPasskey: e.passkey !== undefined,671                }672              : {673                  id: e.id,674                  title: e.title,675                  username: e.username,676                  email: e.email,677                  url: e.url,678                  hasTotp: Boolean(e.totp),679                  hasPasskey: e.passkey !== undefined,680                }681          ),682        };683      }684      case "GET_ENTRY_FOR_FILL": {685        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };686        const { id } = msg.payload as { id: string };687        const entry = vault.getEntryById(id);688        if (!entry) return { ok: false, error: "entry not found" };689        // Passkey-only entries (passkey credential, no password) cannot be690        // filled into a form — sign-in goes through the WebAuthn path. A691        // login that ALSO has a passkey is still fillable for its password.692        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey not fillable" };693        // Strip the passkey credential from the response — content scripts694        // never need the private key, and there's no reason to expose the695        // public credential metadata over the boundary either.696        const { passkey: _strippedPasskey, ...safeEntry } = entry;697        return { ok: true, data: safeEntry };698      }699      case "COPY": {700        const { text, label, alreadyWritten } = msg.payload as {701          text: string;702          label: string;703          alreadyWritten?: boolean;704        };705        await copyToClipboard(text, label, Boolean(alreadyWritten));706        return { ok: true };707      }708      case "CHECK_ALL_BREACHES": {709        const allEntries = vault.getEntries();710        const results: Record<string, number> = {};711        for (const entry of allEntries) {712          if (entry.type === "note") continue;713          if (!entry.password) continue;714          results[entry.id] = await vault.checkBreach(entry.password);715          // Small delay — be a good citizen to the HIBP API716          await new Promise((r) => setTimeout(r, 200));717        }718        // Persist any non-zero counts back to entries719        for (const [id, count] of Object.entries(results)) {720          const entry = vault.getEntryById(id);721          if (entry && (entry.breach ?? 0) !== count) {722            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });723          }724        }725        return { ok: true, data: results };726      }727      case "GET_SETTINGS":728        return { ok: true, data: await vault.ensureSettingsLoaded() };729      case "UPDATE_SETTINGS": {730        const patch = msg.payload as Record<string, unknown>;731        await vault.updateSettings(patch as any);732        if (typeof patch.autoLockMinutes === "number") {733          await setupAutoLock();734          if (vault.isUnlocked()) touchAutoLock();735        }736        return { ok: true };737      }738      case "GET_PENDING_PASSKEY":739        return { ok: true, data: await getPendingPasskeyRequest() };740      case "APPROVE_PASSKEY": {741        const { requestId } = msg.payload as { requestId: number };742        await resolvePendingPasskeyRequest(requestId, true);743        return { ok: true };744      }745      case "DENY_PASSKEY": {746        const { requestId } = msg.payload as { requestId: number };747        await resolvePendingPasskeyRequest(requestId, false);748        return { ok: true };749      }750      case "GET_PASSKEY_PROVIDER_STATE":751        return { ok: true, data: await getPasskeyProviderState() };752      case "SET_PASSKEY_PROVIDER_ENABLED": {753        const { enabled } = msg.payload as { enabled: boolean };754        // Disabling is always free; gating fires only when a free user is755        // trying to turn passkey interception on.756        if (enabled) {757          const gate = await requirePro("passkeys");758          if (!gate.allowed) return { ok: false, error: "pro_required" };759        }760        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };761      }762      case "FIRE_CANARY_PING": {763        const { webhookUrl, entryTitle, trigger } = msg.payload as {764          webhookUrl: string;765          entryTitle: string;766          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";767        };768        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {769          return { ok: false, error: "invalid webhook url" };770        }771        const body = JSON.stringify({772          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",773          entry: entryTitle,774          trigger,775          timestamp: new Date().toISOString(),776          source: "peach-extension",777        });778        if (trigger === "test") {779          // Permitted outbound fetch: user-configured canary alert endpoint780          // (validated by isAllowedCanaryWebhookUrl above). This is the781          // only non-HIBP outbound call in the extension — see782          // Projects.md §3.7. Test pings are awaited so the UI can show783          // success/failure.784          try {785            const res = await fetch(webhookUrl, {786              method: "POST",787              headers: { "Content-Type": "application/json" },788              body,789            });790            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };791          } catch (err) {792            return { ok: false, error: err instanceof Error ? err.message : "network error" };793          }794        }795        // Non-test triggers are fire-and-forget796        fetch(webhookUrl, {797          method: "POST",798          headers: { "Content-Type": "application/json" },799          body,800        }).catch(() => {});801        return { ok: true };802      }803      case "ACTIVATE_LICENSE": {804        const { key } = msg.payload as { key: string };805        const licenseInfo = await activateLicense(key);806        return { ok: true, data: licenseInfo };807      }808      case "GET_LICENSE": {809        const licenseInfo = await getLicenseInfo();810        return { ok: true, data: licenseInfo };811      }812      case "GET_LICENSE_KEY": {813        const key = await getLicenseKey();814        return { ok: true, data: key };815      }816      case "DEACTIVATE_LICENSE": {817        await deactivateLicense();818        return { ok: true };819      }820      case "SHOULD_PLAY_CELEBRATION": {821        const should = await shouldPlayCelebration();822        return { ok: true, data: should };823      }824      case "MARK_CELEBRATION_PLAYED": {825        await markCelebrationPlayed();826        return { ok: true };827      }828      case "GET_CODEX_VAULT_DATA": {829        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the830        // popup navigates to the License section without further coordination.831        const gate = await requirePro("codex");832        if (!gate.allowed) return { ok: false, error: "pro_required" };833        return await handleGetCodexVaultData();834      }835      case "ESTIMATE_CODEX_PAGES": {836        const gate = await requirePro("codex");837        if (!gate.allowed) return { ok: false, error: "pro_required" };838        return await handleEstimateCodexPages();839      }840      case "RESTORE_FROM_CODEX": {841        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still842        // be able to restore a vault that was printed by a Pro user.843        // DO NOT add a Pro gate here.844        const payload = msg.payload as CodexRestorePayload;845        return await handleRestoreFromCodex(payload);846      }847      case "OPEN_PRO_GATE": {848        // Content script requests: open popup and navigate to License section.849        const { feature } = (msg.payload ?? {}) as { feature?: string };850        if (chrome.storage.session) {851          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });852        }853        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }854        return { ok: true };855      }856      case "GET_IDENTITIES": {857        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };858        return { ok: true, data: vault.getIdentities() };859      }860      case "TOUCH_AUTO_LOCK": {861        // touchAutoLock() is already called by shouldRefreshAutoLock above;862        // this case just gives the popup a typed message to keep the session alive.863        return { ok: true };864      }865      case "GET_ADVANCED_HEALTH_REPORT": {866        const gate = await requirePro("advanced_health");867        if (!gate.allowed) return { ok: false, error: "pro_required" };868        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };869        const report = await buildAdvancedHealthReport(vault.getEntries());870        return { ok: true, data: report };871      }872      case "INITIATE_PASSWORD_CHANGE": {873        const gate = await requirePro("smart_password_change");874        if (!gate.allowed) return { ok: false, error: "pro_required" };875        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };876        const { id } = msg.payload as { id: string };877        const entry = vault.getEntryById(id);878        if (!entry) return { ok: false, error: "entry not found" };879        const url = resolveResetUrl(entry);880        if (!url) return { ok: false, error: "no reset url" };881        try {882          await chrome.tabs.create({ url });883          return { ok: true, data: { url } };884        } catch (err) {885          return {886            ok: false,887            error: err instanceof Error ? err.message : "failed to open tab",888          };889        }890      }891      case "IS_DURESS_ENABLED": {892        const enabled = await vault.isDuressEnabled();893        return { ok: true, data: enabled };894      }895      case "SETUP_DURESS": {896        const { duressPassword } = msg.payload as { duressPassword: string };897        await vault.setupDuress(duressPassword);898        return { ok: true };899      }900      case "DISABLE_DURESS": {901        await vault.disableDuress();902        return { ok: true };903      }904      case "VERIFY_MAIN_PASSWORD": {905        const { password } = msg.payload as { password: string };906        const ok = await vault.verifyMainPassword(password);907        return { ok: true, data: ok };908      }909      case "CHANGE_PASSWORD": {910        const { currentPassword, newPassword } = msg.payload as {911          currentPassword: string;912          newPassword: string;913        };914        const changed = await vault.changePassword(currentPassword, newPassword);915        return changed916          ? { ok: true }917          : { ok: false, error: "incorrect current password" };918      }919      case "GET_SITE_PASSWORD_POLICY": {920        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });921        if (!tab?.id) return { ok: true, data: null };922        try {923          const response = await chrome.tabs.sendMessage(tab.id, {924            type: "GET_SITE_PASSWORD_POLICY",925          });926          return (response as MessageResponse) ?? { ok: true, data: null };927        } catch {928          return { ok: true, data: null };929        }930      }931      case "GET_SYNC_STATE": {932        const pairedDevices = await getPairedDevices();933        const trustedNetworks = await getTrustedNetworks();934        const tailscale = await isOnTailscale();935        const pro = await isProUser();936937        let status: SyncStatus = "offline";938        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {939          if (pairedDevices.length === 0) {940            status = "no_peers";941          } else {942            status = "synced";943          }944        } else {945          status = "not_trusted";946        }947948        const lastSyncRaw = await storageGet("peach_last_sync_at");949        const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN;950        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined;951952        return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } };953      }954      case "GET_PAIRED_DEVICES": {955        const devices = await getPairedDevices();956        return { ok: true, data: { devices } };957      }958      case "GET_SYNC_STATUS": {959        const lastSyncRaw = await storageGet("peach_last_sync_at");960        const lastSyncParsed = lastSyncRaw ? parseInt(lastSyncRaw, 10) : NaN;961        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : null;962        const status: 'up_to_date' | 'never' = lastSyncAt ? 'up_to_date' : 'never';963        return { ok: true, data: { status, lastSyncAt } };964      }965      case "ACCEPT_PAIRING": {966        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.967        return { ok: true };968      }969      case "REMOVE_PAIRED_DEVICE": {970        const { deviceId } = msg.payload as { deviceId: string };971        await removePairedDevice(deviceId);972        return { ok: true };973      }974      case "REMOVE_TRUSTED_NETWORK": {975        const { ssid, bssid, isTailscale } = msg.payload as any;976        const networks = await getTrustedNetworks();977        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 978          (isTailscale ? n.isTailscale : n.ssid === ssid) && 979          (!bssid || n.bssid === bssid)980        );981        if (network) {982          await removeTrustedNetwork(network.addedAt);983        }984        return { ok: true };985      }986      case "MARK_NETWORK_TRUSTED": {987        const network = await getCurrentNetwork();988        await addTrustedNetwork({989          ssid: network.ssid,990          bssid: network.bssid,991          isTailscale: network.isTailscale,992          addedAt: Date.now(),993        });994        return { ok: true };995      }996      case "GET_INCOMING_PAIRING_REQUEST": {997        const request = await getIncomingPairingRequest();998        return { ok: true, data: request };999      }1000      case "RESPOND_INCOMING_PAIRING": {1001        const { accept } = msg.payload as { accept: boolean };1002        const request = await getIncomingPairingRequest();1003        if (!request) return { ok: false, error: "no_pending_request" };1004        if (Date.now() > request.expiresAt) {1005          await clearIncomingPairingRequest();1006          return { ok: false, error: "expired" };1007        }1008        await clearIncomingPairingRequest();1009        if (accept) {1010          await addPairedDevice({1011            deviceId: request.publicKeyHex,1012            displayName: request.deviceName,1013            x25519PublicKey: request.publicKeyHex,1014            pairedAt: Date.now(),1015            lastSeenAt: Date.now(),1016          });1017        }1018        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };1019      }1020      case "START_PAIRING_SERVER": {1021        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.1022        const token = generateSixDigitToken();1023        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;1024        await setActivePairingToken({ token, expiresAt });1025        // Fire-and-forget subnet scan — finds the phone after it scans the QR1026        // and calls SCAN_PAIRING_QR to register the token with SyncPlugin.1027        if (!isNativePlatform()) {1028          void runPairingSubnetScan(token);1029        }1030        return { ok: true, data: { token, expiresAt } };1031      }1032      case "STOP_PAIRING_SERVER": {1033        try {1034          await setActivePairingToken(null);1035        } catch { /* best-effort */ }1036        return { ok: true };1037      }1038      case "GET_RECENT_PAIRING": {1039        const recent = await consumeRecentPairing();1040        return { ok: true, data: recent };1041      }1042      case "DEBUG_INJECT_INCOMING_PAIRING": {1043        // Manual E2E rehearsal hook. Inserts a synthetic incoming pairing1044        // request into session storage so Phase 7 banner UX can be exercised1045        // without a live native host. No Pro gate — this is a no-op in1046        // production unless explicitly invoked from a Settings debug action.1047        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {1048          deviceName?: string;1049          publicKeyHex?: string;1050        };1051        if (!deviceName || !publicKeyHex) {1052          return { ok: false, error: "missing_payload" };1053        }1054        const now = Date.now();1055        await setIncomingPairingRequest({1056          deviceName,1057          publicKeyHex,1058          receivedAt: now,1059          expiresAt: now + 60_000,1060        });1061        return { ok: true };1062      }1063      case "RESET_SYNC_IDENTITY": {1064        const gate = await requirePro("sync");1065        if (!gate.allowed) return { ok: false, error: "pro_required" };1066        const devices = await getPairedDevices();1067        for (const device of devices) {1068          await removePairedDevice(device.deviceId);1069        }1070        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };1071      }1072      case "RECORD_MANUAL_SUMMON": {1073        const { domain } = msg.payload as { domain: string };1074        const settings = vault.getSettings();1075        const existing = settings.manualSummonDomains?.[domain];1076        const now = Date.now();1077        await vault.updateSettings({1078          manualSummonDomains: {1079            ...settings.manualSummonDomains,1080            [domain]: {1081              firstSummonedAt: existing?.firstSummonedAt ?? now,1082              summonCount: (existing?.summonCount ?? 0) + 1,1083              lastSummonedAt: now,1084            },1085          },1086        });1087        return { ok: true };1088      }1089      case "DECLINE_CARD_SAVE": {1090        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1091        await vault.declineCardSaveOffer(last4, expMonth, expYear);1092        return { ok: true };1093      }1094      case "IS_CARD_DECLINED": {1095        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1096        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1097        return { ok: true, data: declined };1098      }1099      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1100        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1101          rpId?: string;1102          rpName?: string;1103          userName?: string;1104          userDisplayName?: string;1105        };1106        if (!rpId || !userName) return { ok: false, error: "rpId and userName required" };1107        return await initiateFirefoxPasskeyCreate({1108          rpId,1109          rpName: rpName ?? rpId,1110          userName,1111          userDisplayName,1112        });1113      }11141115      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1116        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1117        if (!payload) return { ok: false, error: "missing payload" };1118        return await completeFirefoxPasskeyCreate(payload);1119      }11201121      case "PASSKEY_OFFER_DECLINE": {1122        const { domain } = (msg.payload ?? {}) as { domain?: string };1123        if (!domain) return { ok: false, error: "domain required" };1124        await recordPasskeyOfferDecline(domain);1125        return { ok: true };1126      }11271128      case "GET_PASSKEY_OFFER_DECLINED": {1129        const { domain } = (msg.payload ?? {}) as { domain?: string };1130        if (!domain) return { ok: false, error: "domain required" };1131        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1132      }11331134      case "PASSKEY_HAS_CREDENTIALS": {1135        const payload = msg.payload as {1136          rpId?: string;1137          allowCredentials?: Array<{ id: string; type?: string }>;1138        } | undefined;1139        if (!payload?.rpId) return { ok: false, error: "rpId required" };1140        return await handlePasskeyHasCredentials({1141          rpId: payload.rpId,1142          allowCredentials: payload.allowCredentials ?? [],1143        });1144      }11451146      case "PASSKEY_CREATE": {1147        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1148        if (!payload?.rpId || !payload?.userName) {1149          return { ok: false, error: "rpId and userName required" };1150        }1151        return await handleFirefoxPasskeyCreate(payload);1152      }11531154      case "PASSKEY_GET": {1155        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1156        if (!payload?.rpId) return { ok: false, error: "rpId required" };1157        return await handleFirefoxPasskeyGet(payload);1158      }11591160      case "PASSKEY_AUTH_RESPONSE": {1161        const { requestId, approved } = (msg.payload ?? {}) as {1162          requestId?: string | number;1163          approved?: boolean;1164        };1165        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1166          return { ok: false, error: 'requestId and approved required' };1167        }1168        await resolvePendingPasskeyRequest(Number(requestId), approved);1169        return { ok: true };1170      }11711172      case "GET_PASSKEY_FOR_DOMAIN": {1173        const { domain } = (msg.payload ?? {}) as { domain?: string };1174        if (!domain) return { ok: false, error: "domain required" };1175        if (!vault.isUnlocked()) return { ok: true, data: null };1176        const match = vault1177          .getEntries()1178          .find((entry) => entry.passkey?.rpId === domain);1179        if (!match || !match.passkey) return { ok: true, data: null };1180        // Slim shape — only the fields State 11 needs. Never expose private1181        // key material, even though this is locked behind isUnlocked.1182        return {1183          ok: true,1184          data: {1185            rpId: match.passkey.rpId,1186            userName: match.passkey.userName,1187            browser: match.passkey.browser,1188          },1189        };1190      }11911192      case "DESTROY_VAULT": {1193        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1194        // storage.local.clear() wipes every Peach key (slots, settings, license,1195        // onboarded flag, history, sync state, declined cards, recall, etc.);1196        // session.clear() wipes pending passkey requests + pro-notice queues.1197        // Caller (Panic.tsx) handles UI navigation back to onboarding.1198        vault.lock();1199        await storageClear();1200        await vault.clearVaultHistory();1201        if (chrome.storage.session) {1202          await chrome.storage.session.clear();1203        }1204        return { ok: true };1205      }12061207      case "SUBMIT_FEEDBACK": {1208        const { category, message, version, browser } = msg.payload as {1209          category: string;1210          message: string;1211          version: string;1212          browser: string;1213        };1214        if (!message.trim()) return { ok: false, error: "message is empty" };1215        if (!FEEDBACK_ENDPOINT) return { ok: true };1216        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1217          return { ok: false, error: "invalid feedback endpoint" };1218        }1219        try {1220          const res = await fetch(FEEDBACK_ENDPOINT, {1221            method: "POST",1222            headers: { "Content-Type": "application/json" },1223            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1224          });1225          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1226        } catch (err) {1227          return { ok: false, error: err instanceof Error ? err.message : "network error" };1228        }1229      }1230      case "TRIGGER_SYNC": {1231        const gate = await requirePro("sync");1232        if (!gate.allowed) return { ok: false, error: "pro_required" };1233        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };12341235        if (isNativePlatform()) {1236          // Phone is the server — ensure it's listening for desktop connections.1237          syncBridge()?.ensureServerRunning?.();1238          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };1239        }12401241        // Desktop: iterate all paired devices and sync with each.1242        const paired = await getPairedDevices();1243        if (!paired.length) return { ok: true, data: { syncedCount: 0, reason: "no_paired_devices" } };12441245        const subnet = await getLocalSubnet();1246        const results: Array<{ device: string } & SyncResult> = [];12471248        for (const device of paired) {1249          if (!device.x25519PublicKey) continue;12501251          let result: SyncResult;12521253          // Fast path — use last known IP1254          if (device.lastKnownIp) {1255            result = await doVaultSync(device.lastKnownIp, device.x25519PublicKey);1256          } else {1257            result = { status: 'errored', applied: false, error: 'no_ip' };1258          }12591260          // Discovery path — scan if fast path failed1261          if (result.status === 'errored' && subnet) {1262            const newIp = await discoverDevice(subnet, device.x25519PublicKey);1263            if (newIp) {1264              await updatePairedDevice(device.x25519PublicKey, { lastKnownIp: newIp });1265              result = await doVaultSync(newIp, device.x25519PublicKey);1266            }1267          }12681269          if (result.status === 'completed') {1270            await updatePairedDevice(device.x25519PublicKey, {1271              lastSeenAt: Date.now(),1272              lastSyncAt: Date.now(),1273            });1274          }12751276          results.push({ device: device.displayName, ...result });1277        }12781279        const syncedCount = results.filter(r => r.status === 'completed').length;1280        if (syncedCount > 0) {1281          await chrome.storage.local.set({ peach_last_sync_at: String(Date.now()) });1282        }1283        return { ok: true, data: { syncedCount, results } };1284      }1285      // Android-only: biometric unlock with pre-derived key.1286      case "UNLOCK_WITH_KEY": {1287        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1288        if (!isNativePlatform()) {1289          return { ok: false, error: "desktop_only_uses_password" };1290        }1291        try {1292          const result = await vault.unlockWithKey(masterKeyHex);1293          if (result.ok) {1294            onVaultUnlocked();1295            await publishInMemoryVault(result.entries);1296          }1297          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1298        } catch {1299          return { ok: false, error: "invalid_key" };1300        }1301      }1302      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1303      case "GET_DERIVED_KEY": {1304        if (!isNativePlatform()) {1305          return { ok: false, error: "android_only" };1306        }1307        if (!vault.isUnlocked()) {1308          return { ok: false, error: "vault_locked" };1309        }1310        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1311      }1312      // Android: scanned a QR containing a desktop pairing token.1313      case "SCAN_PAIRING_QR": {1314        if (!isNativePlatform()) {1315          return { ok: false, error: "android_only" };1316        }1317        const { token } = msg.payload as { token: string };1318        syncBridge()?.startPairingSession?.({ token });1319        return { ok: true };1320      }1321      // Android: desktop opened a sync connection to the phone's WS server.1322      // Run the responder side of the vault exchange.1323      case "SYNC_SESSION_STARTED": {1324        if (!isNativePlatform()) return { ok: false };1325        if (!vault.isUnlocked()) {1326          return { ok: false, error: "vault_locked" };1327        }1328        const { connectionId } = (msg.payload ?? {}) as { connectionId?: string };1329        if (!connectionId) return { ok: false, error: "missing_connection_id" };13301331        const transport = createAndroidResponderTransport(connectionId);13321333        // Authenticate the initiator before exchanging any vault data. The1334        // native side has already completed the Noise NK handshake; auth1335        // frames here ride the Noise transport (native encrypts/decrypts).1336        const identity = await vault.getSyncIdentity();1337        try {1338          const noiseSessionStub = {1339            encrypt: (b: Uint8Array) => b,1340            decrypt: (b: Uint8Array) => b,1341            handshakeHash: new Uint8Array(32),1342          };1343          const { initiatorPublicKey } = await performResponderAuth(1344            noiseSessionStub,1345            identity.privateKeyBytes,1346            identity.publicKeyBytes,1347            transport.send,1348            transport.receive,1349          );1350          const initiatorHex = noiseBytesToHex(initiatorPublicKey);1351          const paired = await getPairedDevices();1352          if (!paired.some(d => d.x25519PublicKey === initiatorHex)) {1353            await transport.close();1354            return { ok: false, error: "sync_rejected_unpaired_initiator" };1355          }1356        } catch (err) {1357          await transport.close();1358          return { ok: false, error: `sync_auth_failed: ${String(err)}` };1359        }13601361        const result = await runBlobSyncSession('responder', transport, buildSyncDeps());1362        if (result.applied) {1363          await publishInMemoryVault(vault.getEntries());1364        }1365        return { ok: true, data: result };1366      }1367      // Android: returns the phone's WiFi IP address.1368      case "GET_LOCAL_IP": {1369        if (!isNativePlatform()) {1370          return { ok: false, error: "android_only" };1371        }1372        const { ip } = (await syncBridge()?.getLocalIp?.()) ?? { ip: "" };1373        return { ok: true, data: { ip } };1374      }1375      case "GET_IDENTITY_SUGGESTIONS": {1376        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1377        const entries = vault.getEntries();1378        const suggestions = buildIdentitySuggestions(entries);1379        return { ok: true, data: { suggestions } };1380      }1381      case "POPULATE_INLINE_VAULT": {1382        if (!isNativePlatform()) return { ok: false };1383        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1384        const entries = vault.getEntries();1385        await publishInMemoryVault(entries);1386        return { ok: true };1387      }1388      case "ML_INIT":1389        return { ok: true };13901391      case "ML_PREDICT_BATCH": {1392        const { featuresArray } = msg.payload as { featuresArray: MLFieldFeatures[] };1393        return { ok: true, data: mlPredictBatch(featuresArray) };1394      }13951396      default:1397        return { ok: false, error: "unknown message type" };1398    }1399  } catch (err) {1400    return {1401      ok: false,1402      error: err instanceof Error ? err.message : "operation failed",1403    };1404  }1405}14061407// --- Mobile platform helpers ---14081409// Android: populates the in-memory vault used by PeachAutofillService.1410async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1411  const plugin = nativePlugin<{1412    setEntries?: (args: {1413      entries: Array<{1414        id: string;1415        title: string;1416        username: string;1417        email: string;1418        password: string;1419        url: string;1420        totp: string;1421        additionalUrls: string[];1422      }>;1423    }) => Promise<void>;1424  }>("InMemoryVaultPlugin");1425  if (!plugin?.setEntries) return;1426  await plugin.setEntries({1427    entries: entries.map((e) => ({1428      id: e.id,1429      title: e.title ?? "",1430      username: e.username ?? "",1431      email: (e as VaultEntry & { email?: string }).email ?? "",1432      password: e.password ?? "",1433      url: e.url ?? "",1434      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1435      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1436    })),1437  });1438}14391440// Android: clear the autofill in-memory store on lock.1441async function clearInMemoryVault(): Promise<void> {1442  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1443  if (!plugin?.clearEntries) return;1444  await plugin.clearEntries();1445}14461447interface SyncBridge {1448  ensureServerRunning?: () => void;1449  startPairingSession?: (args: { token: string }) => void;1450  getLocalIp?: () => Promise<{ ip: string }>;1451  sendToConnection?: (args: { connectionId: string; data: string }) => Promise<void>;1452  addListener?: (event: string, handler: (data: Record<string, string>) => void) => void;1453}14541455// Resolve the Capacitor SyncPlugin at call time — module-load resolution1456// races with Capacitor's plugin registration on the Android WebView.1457function syncBridge(): SyncBridge | null {1458  return nativePlugin<SyncBridge>("SyncPlugin");1459}14601461// Build a SyncTransport for the Android responder path — the phone's WS server1462// already has an open connection from the desktop. We send back via1463// SyncPlugin.sendToConnection and receive via the peach:sync-frame queue.1464const androidSyncFrameQueues = new Map<string, Array<(frame: string) => void>>();14651466export function deliverAndroidSyncFrame(connectionId: string, frame: string): void {1467  const queue = androidSyncFrameQueues.get(connectionId);1468  if (queue?.length) queue.shift()!(frame);1469}14701471function createAndroidResponderTransport(connectionId: string) {1472  const pendingReceivers: Array<(frame: string) => void> = [];1473  androidSyncFrameQueues.set(connectionId, pendingReceivers);14741475  return {1476    send: async (data: Uint8Array) => {1477      await syncBridge()?.sendToConnection?.({ connectionId, data: bytesToBase64(data) });1478    },1479    receive: (): Promise<Uint8Array> => new Promise((res) => {1480      pendingReceivers.push((frame) => {1481        res(frame ? base64ToBytes(frame) : new Uint8Array(0));1482      });1483    }),1484    close: async () => {1485      androidSyncFrameQueues.delete(connectionId);1486    },1487  };1488}14891490// Returns username use-counts from the vault, sorted by frequency. Each row1491// also carries the entry's email so the popup can suggest the email/username1492// pair the user has actually used together.1493function buildIdentitySuggestions(1494  entries: VaultEntry[],1495): Array<{ email: string; username: string; count: number }> {1496  const usernameCounts = new Map<string, number>();1497  const usernameEmail = new Map<string, string>();1498  for (const entry of entries) {1499    const username = entry.username ?? "";1500    const email = (entry as VaultEntry & { email?: string }).email ?? "";1501    if (!username && !email) continue;1502    const key = username || email;1503    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1504    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1505  }1506  return Array.from(usernameCounts.entries())1507    .sort((a, b) => b[1] - a[1])1508    .map(([username, count]) => ({1509      email: usernameEmail.get(username) ?? "",1510      username,1511      count,1512    }));1513}15141515/** Notify all content scripts that the vault just became available. */1516function broadcastToContentScripts(message: { type: string }): void {1517  if (!chrome.tabs?.query) return;1518  chrome.tabs.query({}, (tabs) => {1519    for (const tab of tabs) {1520      if (tab.id !== undefined) {1521        chrome.tabs.sendMessage(tab.id, message).catch(() => {1522          // Tab may not have a content script — silently ignore1523        });1524      }1525    }1526  });1527}15281529function shouldRefreshAutoLock(type: MessageType): boolean {1530  return (1531    type !== "HAS_VAULT" &&1532    type !== "IS_UNLOCKED" &&1533    type !== "GET_VAULT_STATUS" &&1534    type !== "LOCK" &&1535    type !== "UPDATE_SETTINGS" &&1536    type !== "GET_PENDING_PASSKEY" &&1537    type !== "GET_PASSKEY_PROVIDER_STATE" &&1538    type !== "DECLINE_CARD_SAVE" &&1539    type !== "IS_CARD_DECLINED" &&1540    type !== "SUBMIT_FEEDBACK"1541  );1542}15431544function isAllowedCanaryWebhookUrl(value: string): boolean {1545  try {1546    const url = new URL(value);1547    if (url.protocol !== "https:") return false;15481549    const hostname = url.hostname.toLowerCase();1550    if (1551      hostname === "localhost" ||1552      hostname.endsWith(".localhost") ||1553      isPrivateIpv4(hostname) ||1554      isPrivateIpv6(hostname)1555    ) {1556      return false;1557    }15581559    return true;1560  } catch {1561    return false;1562  }1563}15641565function isPrivateIpv4(hostname: string): boolean {1566  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1567    return true;1568  }15691570  const octets = hostname.split(".").map((part) => Number(part));1571  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1572    return false;1573  }15741575  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1576}15771578function isPrivateIpv6(hostname: string): boolean {1579  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1580  return (1581    normalized === "::1" ||1582    normalized.startsWith("fc") ||1583    normalized.startsWith("fd") ||1584    normalized.startsWith("fe80:")1585  );1586}