messages.ts

60.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  // Defensive: refuse to drive a sync to a key not in the paired-devices212  // list. The WebSocket transport already authenticates the peer via Noise213  // NK + the initiator auth proof (H1), but pinning the key to the paired214  // set here makes "talk to anyone matching this static key" the only path215  // to vault application — there is no orphan-key window between pair and216  // sync (M11/COR-014).217  const paired = await getPairedDevices();218  if (!paired.some(d => d.x25519PublicKey === publicKeyHex)) {219    return { status: 'errored', applied: false, error: 'remote_not_paired' };220  }221  try {222    const identity = await vault.getSyncIdentity();223    const transport = await createWebSocketSyncTransport(224      `ws://${ip}:44100`,225      publicKeyHex,226      identity.privateKeyBytes,227      identity.publicKeyBytes,228    );229    return await runBlobSyncSession('initiator', transport, buildSyncDeps());230  } catch (err) {231    return { status: 'errored', applied: false, error: String(err) };232  }233}234235async function mergeDeviceRegistry(incoming: SyncableDevice[]): Promise<void> {236  const existing = await getPairedDevices();237  const existingKeys = new Set(existing.map(d => d.x25519PublicKey));238  for (const device of incoming) {239    if (!existingKeys.has(device.publicKeyHex)) {240      await addPairedDevice({241        deviceId: device.publicKeyHex,242        displayName: device.deviceName,243        x25519PublicKey: device.publicKeyHex,244        pairedAt: device.pairedAt,245        lastSeenAt: 0,246        lastKnownIp: '',247      }).catch(() => {});248    }249  }250}251252// Background pairing scan — runs after START_PAIRING_SERVER fires on desktop.253// Scans the local subnet for a phone that has accepted the pairing token,254// stores it, runs the initial vault exchange, then notifies the popup.255async function runPairingSubnetScan(token: string): Promise<void> {256  const subnet = await getLocalSubnet();257  if (!subnet) return;258259  const found = await scanForPairingPhone(subnet, token);260  if (!found) return;261262  const { ip, publicKeyHex } = found;263264  try {265    await addPairedDevice({266      deviceId: publicKeyHex,267      displayName: 'Peach',268      x25519PublicKey: publicKeyHex,269      pairedAt: Date.now(),270      lastSeenAt: Date.now(),271      lastKnownIp: ip,272    });273  } catch {274    // Already paired — update IP275    await updatePairedDevice(publicKeyHex, { lastKnownIp: ip, lastSeenAt: Date.now() });276  }277278  // Immediate vault exchange — the free one-time transfer279  await doVaultSync(ip, publicKeyHex);280281  chrome.runtime.sendMessage({282    type: 'PAIRING_COMPLETED',283    payload: { deviceName: 'Peach', publicKeyHex, deviceIp: ip },284  }).catch(() => {});285}286287export function setupMessageHandler(): void {288  chrome.runtime.onMessage.addListener(289    (msg: unknown, sender, sendResponse) => {290      if (!isMessage(msg)) {291        sendResponse({ ok: false, error: "invalid message" });292        return true;293      }294      handleMessage(msg, sender)295        .then(sendResponse)296        .catch((err) =>297          sendResponse({298            ok: false,299            error: err instanceof Error ? err.message : String(err),300          })301        );302      return true;303    }304  );305306  // Android: the chrome shim queues sendMessage calls until this handler is307  // registered. Without this hookup, every message hangs on Capacitor builds.308  // eslint-disable-next-line @typescript-eslint/no-explicit-any309  const reg = (globalThis as any).__peachRegisterMessageHandler;310  if (typeof reg === "function") {311    reg(async (m: unknown) => {312      if (!isMessage(m)) return { ok: false, error: "invalid message" };313      try {314        return await handleMessage(m);315      } catch (err) {316        return {317          ok: false,318          error: err instanceof Error ? err.message : String(err),319        };320      }321    });322  }323324  // Android: subscribe to SyncPlugin events.325  if (isNativePlatform()) {326    const syncPlug = nativePlugin<{327      addListener: (328        event: string,329        handler: (data: Record<string, string>) => void330      ) => void;331    }>("SyncPlugin");332333    // Pairing probe answered — store the paired device (desktop, no IP needed334    // since the desktop never acts as a WS server).335    syncPlug?.addListener?.("peach:pair-probe-answered", (data) => {336      const deviceName = data.deviceName ?? "Peach";337      const publicKeyHex = data.publicKeyHex ?? "";338      void (async () => {339        const { addPairedDevice, setHasPaired: setPaired } = await import("./sync-storage");340        await addPairedDevice({341          deviceId: publicKeyHex || (data.connectionId ?? "unknown"),342          displayName: deviceName,343          x25519PublicKey: publicKeyHex,344          pairedAt: Date.now(),345          lastSeenAt: Date.now(),346        }).catch(() => {});347        await setPaired();348        chrome.runtime.sendMessage({349          type: "PAIRING_COMPLETED",350          payload: { deviceName },351        }).catch(() => {});352      })();353    });354355    // Sync frame received — route to the waiting responder session.356    syncPlug?.addListener?.("peach:sync-frame", (data) => {357      const { connectionId, frame } = data;358      if (connectionId && frame) deliverAndroidSyncFrame(connectionId, frame);359    });360361    // Sync session started (SYNC_HELLO received by SyncPlugin) — dispatch as362    // a background message so SYNC_SESSION_STARTED handler runs the responder.363    syncPlug?.addListener?.("peach:sync-session-started", (data) => {364      const { connectionId } = data;365      if (!connectionId) return;366      void handleMessage({ type: "SYNC_SESSION_STARTED", payload: { connectionId } });367    });368  }369}370371function isMessage(m: unknown): m is Message {372  return typeof m === "object" && m !== null && "type" in m;373}374375export async function handleMessage(376  msg: Message,377  sender: Partial<chrome.runtime.MessageSender> = {}378): Promise<MessageResponse> {379  try {380    // Validate sender — only allow messages from our extension pages/scripts.381    // `sender.id` is undefined for messages originating from extension UI382    // (popup/options), which is legitimate; reject only when it is defined383    // and does not match our extension id.384    if (385      sender.id !== undefined &&386      sender.id !== chrome.runtime.id387    ) {388      return { ok: false, error: "invalid sender" };389    }390391    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {392      touchAutoLock();393    }394395    switch (msg.type) {396      case "CREATE_VAULT": {397        const { password } = msg.payload as { password: string };398        await vault.createVault(password);399        await setupAutoLock();400        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });401        onVaultUnlocked();402        return { ok: true };403      }404      case "UNLOCK": {405        const { password } = msg.payload as { password: string };406        const ok = await vault.unlock(password);407        if (ok) {408          await setupAutoLock();409          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });410          onVaultUnlocked();411          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());412          return { ok: true };413        }414        // Distinguish corruption from wrong password so the popup can offer415        // a history-restore path instead of falsely accusing the user of416        // mistyping (M7/COR-007).417        const failure = vault.consumeLastUnlockFailureReason();418        if (failure) {419          return {420            ok: false,421            error: "vault_corrupted",422            canRestoreFromHistory: true,423          } as MessageResponse;424        }425        return { ok: false };426      }427      case "VALIDATE_RECOVERY_WORDS": {428        const { words } = msg.payload as { words: string[] };429        const invalid = findInvalidWords(words);430        return { ok: true, data: { valid: invalid.length === 0, invalid } };431      }432      case "GET_RECOVERY_WORDS": {433        // Must be unlocked and have recovery set up (vault must be v2.12+).434        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };435        try {436          const words = await vault.getRecoveryWords();437          return { ok: true, data: words };438        } catch (e) {439          // pre-v2.12 vault that hasn't migrated440          return { ok: false, error: "recovery_not_setup" };441        }442      }443      case "RECOVER_WITH_WORDS": {444        // User has lost their password but has their 12 recovery words.445        // We: (1) validate the words, (2) re-encrypt vault with new password.446        const { words, newPassword } = msg.payload as {447          words: string[];448          newPassword: string;449        };450        const stored = await vault.loadSlotA();451        if (!stored) return { ok: false, error: "no vault" };452        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {453          return { ok: false, error: "recovery_not_setup" };454        }455        // Unwrap the root key from the recovery escrow.456        try {457          await vault.unwrapRootKeyForRecovery(458            stored.recovery_wrapped_root_key,459            stored.recovery_nonce ?? "",460            stored.recovery_tag ?? "",461            stored.recovery_salt,462            words463          );464        } catch {465          return { ok: false, error: "invalid_recovery_words" };466        }467        // Re-key: derive fresh salt + key from new password.468        const newSalt = vault.generateSalt();469        const newKey = await vault.deriveKey(newPassword, newSalt);470        // Re-wrap root key under the new password's derived key so the same471        // recovery words continue to work after the password change.472        await vault.rewrapRootKeyForPassword(newKey, newSalt);473        // Re-encrypt vault entries with the new key.474        await vault.changePasswordWithNewKey(newSalt, newKey);475        await setupAutoLock();476        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });477        return { ok: true };478      }479      case "LOCK":480        vault.lock();481        if (isNativePlatform()) await clearInMemoryVault();482        return { ok: true };483      case "IS_UNLOCKED":484        return { ok: true, data: vault.isUnlocked() };485      case "GET_VAULT_STATUS":486        return { ok: true, unlocked: vault.isUnlocked() };487      case "HAS_VAULT":488        return { ok: true, data: await vault.hasVault() };489      case "GET_ENTRIES":490        return { ok: true, data: vault.getEntries() };491      case "ADD_ENTRY": {492        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };493        const entry = await vault.addEntry(msg.payload as any);494        return { ok: true, data: entry };495      }496      case "BATCH_ADD_ENTRIES": {497        const { entries } = msg.payload as { entries: any[] };498        const added = await vault.batchAddEntries(entries);499        return { ok: true, data: added };500      }501      case "RESTORE_ENTRIES": {502        const { entries, mode, settings } = msg.payload as {503          entries: any[];504          mode: "replace" | "merge";505          settings?: vault.VaultSettings;506        };507        const summary = await vault.restoreEntries(entries, mode);508        if (settings && typeof settings === "object") {509          await vault.updateSettings(settings);510        }511        return { ok: true, data: summary };512      }513      case "CLEAR_VAULT_ENTRIES": {514        await vault.clearVaultEntries("REPLACE_ALL");515        return { ok: true };516      }517      case "GET_VAULT_HISTORY": {518        const snapshots = await vault.getVaultHistory();519        return { ok: true, data: snapshots };520      }521      case "RESTORE_VAULT_SNAPSHOT": {522        const { snapshotId } = msg.payload as { snapshotId: string };523        const result = await vault.restoreVaultSnapshot(snapshotId);524        if (!result.ok) return { ok: false, error: result.error };525        broadcastToContentScripts({ type: "VAULT_LOCKED" });526        return { ok: true };527      }528      case "COUNT_DUPLICATES": {529        return { ok: true, data: vault.countDuplicates() };530      }531      case "DEDUPLICATE_ENTRIES": {532        const removed = await vault.deduplicateEntries();533        return { ok: true, data: removed };534      }535      case "UPDATE_ENTRY": {536        const { id, patch } = msg.payload as any;537        await vault.updateEntry(id, patch);538        return { ok: true };539      }540      case "ADD_ADDITIONAL_URL": {541        const { id, url } = msg.payload as { id: string; url: string };542        const trimmed = typeof url === "string" ? url.trim() : "";543        if (!trimmed) return { ok: false, error: "url required" };544        const existing = vault.getEntryById(id);545        if (!existing) return { ok: false, error: "entry not found" };546        if (existing.type !== "login") return { ok: false, error: "login entries only" };547        const merged = [...(existing.additionalUrls ?? []), trimmed];548        await vault.updateEntry(id, { additionalUrls: merged });549        return { ok: true };550      }551      case "DELETE_ENTRY": {552        const { id } = msg.payload as { id: string };553        await vault.deleteEntry(id);554        return { ok: true };555      }556      case "GET_DELETED_ENTRIES":557        return { ok: true, data: vault.getDeletedEntries() };558      case "RESTORE_ENTRY": {559        const { id } = msg.payload as { id: string };560        await vault.restoreEntry(id);561        return { ok: true };562      }563      case "PURGE_ENTRY": {564        const { id } = msg.payload as { id: string };565        await vault.purgeEntry(id);566        return { ok: true };567      }568      case "PURGE_EXPIRED_TRASH": {569        const { retentionMs } = msg.payload as { retentionMs: number };570        const purged = await vault.purgeExpiredTrash(retentionMs);571        return { ok: true, data: purged };572      }573      case "SAVE_NOTE": {574        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };575        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };576        const now = Date.now();577        if (id) {578          const existing = vault.getEntryById(id);579          if (!existing) return { ok: false, error: "not_found" };580          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });581          return { ok: true, data: vault.getEntryById(id) };582        } else {583          const entry = await vault.addEntry({584            type: "note",585            title: title || "Untitled",586            notes: body,587            createdAt: now,588            modifiedAt: now,589          } as any);590          return { ok: true, data: entry };591        }592      }593      case "DELETE_NOTE": {594        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };595        const { id } = msg.payload as { id: string };596        await vault.deleteEntry(id);597        return { ok: true };598      }599      case "GET_NOTES": {600        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };601        const notes = vault.getEntries().filter(602          (e) => e.type === "note" && !e.deletedAt603        );604        return { ok: true, data: notes } as MessageResponse;605      }606      case "SEARCH_VAULT": {607        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };608        const { query } = msg.payload as { query: string };609        const q = query.toLowerCase();610        const searchResults = vault.getEntries().filter(611          (e) =>612            !e.deletedAt &&613            (e.title.toLowerCase().includes(q) ||614              e.notes?.toLowerCase().includes(q) ||615              e.username?.toLowerCase().includes(q))616        );617        return { ok: true, data: searchResults } as MessageResponse;618      }619      case "PAIRING_COMPLETED": {620        const { deviceName, publicKeyHex, deviceIp } = (msg.payload ?? {}) as {621          deviceName?: string;622          publicKeyHex?: string;623          deviceIp?: string;624        };625        if (!publicKeyHex) return { ok: false, error: "publicKeyHex required" };626        const { setHasPaired: setPaired } = await import("./sync-storage");627        await setPaired();628        try {629          await addPairedDevice({630            deviceId: publicKeyHex,631            displayName: deviceName ?? "Unknown",632            x25519PublicKey: publicKeyHex,633            pairedAt: Date.now(),634            lastSeenAt: Date.now(),635            lastKnownIp: deviceIp,636          });637        } catch {638          // Already paired — update IP if provided639          if (deviceIp) {640            await updatePairedDevice(publicKeyHex, { lastKnownIp: deviceIp, lastSeenAt: Date.now() });641          }642        }643        return { ok: true };644      }645      case "AUTOFILL_QUERY": {646        if (!vault.isUnlocked()) {647          return { ok: false, error: "VAULT_LOCKED" };648        }649        const { domain, includeAll, kind } = msg.payload as {650          domain: string;651          includeAll?: boolean;652          kind?: "login" | "card";653        };654        // kind="card": return saved cards as compact summaries for the655        // inline card silver platter. Cards are not domain-scoped — every656        // saved card is a candidate on every checkout page — so domain is657        // ignored when kind === "card".658        if (kind === "card") {659          const cards = vault.getEntries().filter((e) => e.type === "card");660          return {661            ok: true,662            data: cards.map((e) => ({663              id: e.id,664              title: e.cardNickname || e.title,665              cardholderName: e.cardholderName,666              last4: e.last4,667              expMonth: e.expMonth,668              expYear: e.expYear,669              network: e.network,670            })),671          };672        }673        // The inline selector fills username+password into a form. Passkey-674        // only entries have no password to fill; sign-in for those goes675        // through the WebAuthn path instead. Filter them out everywhere so676        // the user doesn't see four "GitHub" rows that mostly do nothing.677        // Notes and cards never belonged here either.678        const matches = (679          includeAll680            ? vault681                .getEntries()682                .filter((entry) => entry.type !== "note" && entry.type !== "card")683            : vault.queryDomain(domain)684        ).filter((entry) => !isPasskeyOnly(entry));685        return {686          ok: true,687          data: matches.map((e) =>688            includeAll689              ? {690                  id: e.id,691                  title: e.title,692                  hasPasskey: e.passkey !== undefined,693                }694              : {695                  id: e.id,696                  title: e.title,697                  username: e.username,698                  email: e.email,699                  url: e.url,700                  hasTotp: Boolean(e.totp),701                  hasPasskey: e.passkey !== undefined,702                }703          ),704        };705      }706      case "GET_ENTRY_FOR_FILL": {707        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };708        const { id } = msg.payload as { id: string };709        const entry = vault.getEntryById(id);710        if (!entry) return { ok: false, error: "entry not found" };711        // Passkey-only entries (passkey credential, no password) cannot be712        // filled into a form — sign-in goes through the WebAuthn path. A713        // login that ALSO has a passkey is still fillable for its password.714        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey not fillable" };715        // Strip the passkey credential from the response — content scripts716        // never need the private key, and there's no reason to expose the717        // public credential metadata over the boundary either.718        const { passkey: _strippedPasskey, ...safeEntry } = entry;719        return { ok: true, data: safeEntry };720      }721      case "COPY": {722        const { text, label, alreadyWritten } = msg.payload as {723          text: string;724          label: string;725          alreadyWritten?: boolean;726        };727        await copyToClipboard(text, label, Boolean(alreadyWritten));728        return { ok: true };729      }730      case "CHECK_ALL_BREACHES": {731        const allEntries = vault.getEntries();732        const results: Record<string, number> = {};733        for (const entry of allEntries) {734          if (entry.type === "note") continue;735          if (!entry.password) continue;736          results[entry.id] = await vault.checkBreach(entry.password);737          // Small delay — be a good citizen to the HIBP API738          await new Promise((r) => setTimeout(r, 200));739        }740        // Persist any non-zero counts back to entries741        for (const [id, count] of Object.entries(results)) {742          const entry = vault.getEntryById(id);743          if (entry && (entry.breach ?? 0) !== count) {744            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });745          }746        }747        return { ok: true, data: results };748      }749      case "GET_SETTINGS":750        return { ok: true, data: await vault.ensureSettingsLoaded() };751      case "UPDATE_SETTINGS": {752        const patch = msg.payload as Record<string, unknown>;753        await vault.updateSettings(patch as any);754        if (typeof patch.autoLockMinutes === "number") {755          await setupAutoLock();756          if (vault.isUnlocked()) touchAutoLock();757        }758        return { ok: true };759      }760      case "GET_PENDING_PASSKEY":761        return { ok: true, data: await getPendingPasskeyRequest() };762      case "APPROVE_PASSKEY": {763        const { requestId } = msg.payload as { requestId: number };764        await resolvePendingPasskeyRequest(requestId, true);765        return { ok: true };766      }767      case "DENY_PASSKEY": {768        const { requestId } = msg.payload as { requestId: number };769        await resolvePendingPasskeyRequest(requestId, false);770        return { ok: true };771      }772      case "GET_PASSKEY_PROVIDER_STATE":773        return { ok: true, data: await getPasskeyProviderState() };774      case "SET_PASSKEY_PROVIDER_ENABLED": {775        const { enabled } = msg.payload as { enabled: boolean };776        // Disabling is always free; gating fires only when a free user is777        // trying to turn passkey interception on.778        if (enabled) {779          const gate = await requirePro("passkeys");780          if (!gate.allowed) return { ok: false, error: "pro_required" };781        }782        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };783      }784      case "FIRE_CANARY_PING": {785        const { webhookUrl, entryTitle, trigger } = msg.payload as {786          webhookUrl: string;787          entryTitle: string;788          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";789        };790        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {791          return { ok: false, error: "invalid webhook url" };792        }793        const body = JSON.stringify({794          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",795          entry: entryTitle,796          trigger,797          timestamp: new Date().toISOString(),798          source: "peach-extension",799        });800        if (trigger === "test") {801          // Permitted outbound fetch: user-configured canary alert endpoint802          // (validated by isAllowedCanaryWebhookUrl above). This is the803          // only non-HIBP outbound call in the extension — see804          // Projects.md §3.7. Test pings are awaited so the UI can show805          // success/failure.806          try {807            const res = await fetch(webhookUrl, {808              method: "POST",809              headers: { "Content-Type": "application/json" },810              body,811            });812            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };813          } catch (err) {814            return { ok: false, error: err instanceof Error ? err.message : "network error" };815          }816        }817        // Non-test triggers are fire-and-forget818        fetch(webhookUrl, {819          method: "POST",820          headers: { "Content-Type": "application/json" },821          body,822        }).catch(() => {});823        return { ok: true };824      }825      case "ACTIVATE_LICENSE": {826        const { key } = msg.payload as { key: string };827        const licenseInfo = await activateLicense(key);828        return { ok: true, data: licenseInfo };829      }830      case "GET_LICENSE": {831        const licenseInfo = await getLicenseInfo();832        return { ok: true, data: licenseInfo };833      }834      case "GET_LICENSE_KEY": {835        const key = await getLicenseKey();836        return { ok: true, data: key };837      }838      case "DEACTIVATE_LICENSE": {839        await deactivateLicense();840        return { ok: true };841      }842      case "SHOULD_PLAY_CELEBRATION": {843        const should = await shouldPlayCelebration();844        return { ok: true, data: should };845      }846      case "MARK_CELEBRATION_PLAYED": {847        await markCelebrationPlayed();848        return { ok: true };849      }850      case "GET_CODEX_VAULT_DATA": {851        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the852        // popup navigates to the License section without further coordination.853        const gate = await requirePro("codex");854        if (!gate.allowed) return { ok: false, error: "pro_required" };855        return await handleGetCodexVaultData();856      }857      case "ESTIMATE_CODEX_PAGES": {858        const gate = await requirePro("codex");859        if (!gate.allowed) return { ok: false, error: "pro_required" };860        return await handleEstimateCodexPages();861      }862      case "RESTORE_FROM_CODEX": {863        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still864        // be able to restore a vault that was printed by a Pro user.865        // DO NOT add a Pro gate here.866        const payload = msg.payload as CodexRestorePayload;867        return await handleRestoreFromCodex(payload);868      }869      case "OPEN_PRO_GATE": {870        // Content script requests: open popup and navigate to License section.871        const { feature } = (msg.payload ?? {}) as { feature?: string };872        if (chrome.storage.session) {873          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });874        }875        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }876        return { ok: true };877      }878      case "GET_IDENTITIES": {879        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };880        return { ok: true, data: vault.getIdentities() };881      }882      case "TOUCH_AUTO_LOCK": {883        // touchAutoLock() is already called by shouldRefreshAutoLock above;884        // this case just gives the popup a typed message to keep the session alive.885        return { ok: true };886      }887      case "GET_ADVANCED_HEALTH_REPORT": {888        const gate = await requirePro("advanced_health");889        if (!gate.allowed) return { ok: false, error: "pro_required" };890        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };891        const report = await buildAdvancedHealthReport(vault.getEntries());892        return { ok: true, data: report };893      }894      case "INITIATE_PASSWORD_CHANGE": {895        const gate = await requirePro("smart_password_change");896        if (!gate.allowed) return { ok: false, error: "pro_required" };897        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };898        const { id } = msg.payload as { id: string };899        const entry = vault.getEntryById(id);900        if (!entry) return { ok: false, error: "entry not found" };901        const url = resolveResetUrl(entry);902        if (!url) return { ok: false, error: "no reset url" };903        try {904          await chrome.tabs.create({ url });905          return { ok: true, data: { url } };906        } catch (err) {907          return {908            ok: false,909            error: err instanceof Error ? err.message : "failed to open tab",910          };911        }912      }913      case "IS_DURESS_ENABLED": {914        const enabled = await vault.isDuressEnabled();915        return { ok: true, data: enabled };916      }917      case "SETUP_DURESS": {918        const { duressPassword } = msg.payload as { duressPassword: string };919        await vault.setupDuress(duressPassword);920        return { ok: true };921      }922      case "DISABLE_DURESS": {923        await vault.disableDuress();924        return { ok: true };925      }926      case "VERIFY_MAIN_PASSWORD": {927        const { password } = msg.payload as { password: string };928        const ok = await vault.verifyMainPassword(password);929        return { ok: true, data: ok };930      }931      case "CHANGE_PASSWORD": {932        const { currentPassword, newPassword } = msg.payload as {933          currentPassword: string;934          newPassword: string;935        };936        const changed = await vault.changePassword(currentPassword, newPassword);937        return changed938          ? { ok: true }939          : { ok: false, error: "incorrect current password" };940      }941      case "GET_SITE_PASSWORD_POLICY": {942        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });943        if (!tab?.id) return { ok: true, data: null };944        try {945          const response = await chrome.tabs.sendMessage(tab.id, {946            type: "GET_SITE_PASSWORD_POLICY",947          });948          return (response as MessageResponse) ?? { ok: true, data: null };949        } catch {950          return { ok: true, data: null };951        }952      }953      case "GET_SYNC_STATE": {954        const pairedDevices = await getPairedDevices();955        const trustedNetworks = await getTrustedNetworks();956        const tailscale = await isOnTailscale();957        const pro = await isProUser();958959        let status: SyncStatus = "offline";960        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {961          if (pairedDevices.length === 0) {962            status = "no_peers";963          } else {964            status = "synced";965          }966        } else {967          status = "not_trusted";968        }969970        const lastSyncRaw = await storageGet("peach_last_sync_at");971        const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN;972        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined;973974        return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } };975      }976      case "GET_PAIRED_DEVICES": {977        const devices = await getPairedDevices();978        return { ok: true, data: { devices } };979      }980      case "GET_SYNC_STATUS": {981        const lastSyncRaw = await storageGet("peach_last_sync_at");982        const lastSyncParsed = lastSyncRaw ? parseInt(lastSyncRaw, 10) : NaN;983        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : null;984        const status: 'up_to_date' | 'never' = lastSyncAt ? 'up_to_date' : 'never';985        return { ok: true, data: { status, lastSyncAt } };986      }987      case "ACCEPT_PAIRING": {988        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.989        return { ok: true };990      }991      case "REMOVE_PAIRED_DEVICE": {992        const { deviceId } = msg.payload as { deviceId: string };993        await removePairedDevice(deviceId);994        return { ok: true };995      }996      case "REMOVE_TRUSTED_NETWORK": {997        const { ssid, bssid, isTailscale } = msg.payload as any;998        const networks = await getTrustedNetworks();999        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 1000          (isTailscale ? n.isTailscale : n.ssid === ssid) && 1001          (!bssid || n.bssid === bssid)1002        );1003        if (network) {1004          await removeTrustedNetwork(network.addedAt);1005        }1006        return { ok: true };1007      }1008      case "MARK_NETWORK_TRUSTED": {1009        const network = await getCurrentNetwork();1010        await addTrustedNetwork({1011          ssid: network.ssid,1012          bssid: network.bssid,1013          isTailscale: network.isTailscale,1014          addedAt: Date.now(),1015        });1016        return { ok: true };1017      }1018      case "GET_INCOMING_PAIRING_REQUEST": {1019        const request = await getIncomingPairingRequest();1020        return { ok: true, data: request };1021      }1022      case "RESPOND_INCOMING_PAIRING": {1023        const { accept } = msg.payload as { accept: boolean };1024        const request = await getIncomingPairingRequest();1025        if (!request) return { ok: false, error: "no_pending_request" };1026        if (Date.now() > request.expiresAt) {1027          await clearIncomingPairingRequest();1028          return { ok: false, error: "expired" };1029        }1030        await clearIncomingPairingRequest();1031        if (accept) {1032          await addPairedDevice({1033            deviceId: request.publicKeyHex,1034            displayName: request.deviceName,1035            x25519PublicKey: request.publicKeyHex,1036            pairedAt: Date.now(),1037            lastSeenAt: Date.now(),1038          });1039        }1040        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };1041      }1042      case "START_PAIRING_SERVER": {1043        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.1044        const token = generateSixDigitToken();1045        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;1046        await setActivePairingToken({ token, expiresAt });1047        // Fire-and-forget subnet scan — finds the phone after it scans the QR1048        // and calls SCAN_PAIRING_QR to register the token with SyncPlugin.1049        if (!isNativePlatform()) {1050          void runPairingSubnetScan(token);1051        }1052        return { ok: true, data: { token, expiresAt } };1053      }1054      case "STOP_PAIRING_SERVER": {1055        try {1056          await setActivePairingToken(null);1057        } catch { /* best-effort */ }1058        return { ok: true };1059      }1060      case "GET_RECENT_PAIRING": {1061        const recent = await consumeRecentPairing();1062        return { ok: true, data: recent };1063      }1064      case "DEBUG_INJECT_INCOMING_PAIRING": {1065        // Manual E2E rehearsal hook. Inserts a synthetic incoming pairing1066        // request into session storage so Phase 7 banner UX can be exercised1067        // without a live native host. No Pro gate — this is a no-op in1068        // production unless explicitly invoked from a Settings debug action.1069        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {1070          deviceName?: string;1071          publicKeyHex?: string;1072        };1073        if (!deviceName || !publicKeyHex) {1074          return { ok: false, error: "missing_payload" };1075        }1076        const now = Date.now();1077        await setIncomingPairingRequest({1078          deviceName,1079          publicKeyHex,1080          receivedAt: now,1081          expiresAt: now + 60_000,1082        });1083        return { ok: true };1084      }1085      case "RESET_SYNC_IDENTITY": {1086        const gate = await requirePro("sync");1087        if (!gate.allowed) return { ok: false, error: "pro_required" };1088        const devices = await getPairedDevices();1089        for (const device of devices) {1090          await removePairedDevice(device.deviceId);1091        }1092        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };1093      }1094      case "RECORD_MANUAL_SUMMON": {1095        const { domain } = msg.payload as { domain: string };1096        const settings = vault.getSettings();1097        const existing = settings.manualSummonDomains?.[domain];1098        const now = Date.now();1099        await vault.updateSettings({1100          manualSummonDomains: {1101            ...settings.manualSummonDomains,1102            [domain]: {1103              firstSummonedAt: existing?.firstSummonedAt ?? now,1104              summonCount: (existing?.summonCount ?? 0) + 1,1105              lastSummonedAt: now,1106            },1107          },1108        });1109        return { ok: true };1110      }1111      case "DECLINE_CARD_SAVE": {1112        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1113        await vault.declineCardSaveOffer(last4, expMonth, expYear);1114        return { ok: true };1115      }1116      case "IS_CARD_DECLINED": {1117        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1118        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1119        return { ok: true, data: declined };1120      }1121      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1122        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1123          rpId?: string;1124          rpName?: string;1125          userName?: string;1126          userDisplayName?: string;1127        };1128        if (!rpId || !userName) return { ok: false, error: "rpId and userName required" };1129        return await initiateFirefoxPasskeyCreate({1130          rpId,1131          rpName: rpName ?? rpId,1132          userName,1133          userDisplayName,1134        });1135      }11361137      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1138        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1139        if (!payload) return { ok: false, error: "missing payload" };1140        return await completeFirefoxPasskeyCreate(payload);1141      }11421143      case "PASSKEY_OFFER_DECLINE": {1144        const { domain } = (msg.payload ?? {}) as { domain?: string };1145        if (!domain) return { ok: false, error: "domain required" };1146        await recordPasskeyOfferDecline(domain);1147        return { ok: true };1148      }11491150      case "GET_PASSKEY_OFFER_DECLINED": {1151        const { domain } = (msg.payload ?? {}) as { domain?: string };1152        if (!domain) return { ok: false, error: "domain required" };1153        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1154      }11551156      case "PASSKEY_HAS_CREDENTIALS": {1157        const payload = msg.payload as {1158          rpId?: string;1159          allowCredentials?: Array<{ id: string; type?: string }>;1160        } | undefined;1161        if (!payload?.rpId) return { ok: false, error: "rpId required" };1162        return await handlePasskeyHasCredentials({1163          rpId: payload.rpId,1164          allowCredentials: payload.allowCredentials ?? [],1165        });1166      }11671168      case "PASSKEY_CREATE": {1169        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1170        if (!payload?.rpId || !payload?.userName) {1171          return { ok: false, error: "rpId and userName required" };1172        }1173        return await handleFirefoxPasskeyCreate(payload);1174      }11751176      case "PASSKEY_GET": {1177        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1178        if (!payload?.rpId) return { ok: false, error: "rpId required" };1179        return await handleFirefoxPasskeyGet(payload);1180      }11811182      case "PASSKEY_AUTH_RESPONSE": {1183        const { requestId, approved } = (msg.payload ?? {}) as {1184          requestId?: string | number;1185          approved?: boolean;1186        };1187        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1188          return { ok: false, error: 'requestId and approved required' };1189        }1190        await resolvePendingPasskeyRequest(Number(requestId), approved);1191        return { ok: true };1192      }11931194      case "GET_PASSKEY_FOR_DOMAIN": {1195        const { domain } = (msg.payload ?? {}) as { domain?: string };1196        if (!domain) return { ok: false, error: "domain required" };1197        if (!vault.isUnlocked()) return { ok: true, data: null };1198        const match = vault1199          .getEntries()1200          .find((entry) => entry.passkey?.rpId === domain);1201        if (!match || !match.passkey) return { ok: true, data: null };1202        // Slim shape — only the fields State 11 needs. Never expose private1203        // key material, even though this is locked behind isUnlocked.1204        return {1205          ok: true,1206          data: {1207            rpId: match.passkey.rpId,1208            userName: match.passkey.userName,1209            browser: match.passkey.browser,1210          },1211        };1212      }12131214      case "DESTROY_VAULT": {1215        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1216        // storage.local.clear() wipes every Peach key (slots, settings, license,1217        // onboarded flag, history, sync state, declined cards, recall, etc.);1218        // session.clear() wipes pending passkey requests + pro-notice queues.1219        // Caller (Panic.tsx) handles UI navigation back to onboarding.1220        vault.lock();1221        await storageClear();1222        await vault.clearVaultHistory();1223        if (chrome.storage.session) {1224          await chrome.storage.session.clear();1225        }1226        return { ok: true };1227      }12281229      case "SUBMIT_FEEDBACK": {1230        const { category, message, version, browser } = msg.payload as {1231          category: string;1232          message: string;1233          version: string;1234          browser: string;1235        };1236        if (!message.trim()) return { ok: false, error: "message is empty" };1237        if (!FEEDBACK_ENDPOINT) return { ok: true };1238        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1239          return { ok: false, error: "invalid feedback endpoint" };1240        }1241        try {1242          const res = await fetch(FEEDBACK_ENDPOINT, {1243            method: "POST",1244            headers: { "Content-Type": "application/json" },1245            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1246          });1247          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1248        } catch (err) {1249          return { ok: false, error: err instanceof Error ? err.message : "network error" };1250        }1251      }1252      case "TRIGGER_SYNC": {1253        const gate = await requirePro("sync");1254        if (!gate.allowed) return { ok: false, error: "pro_required" };1255        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };12561257        if (isNativePlatform()) {1258          // Phone is the server — ensure it's listening for desktop connections.1259          syncBridge()?.ensureServerRunning?.();1260          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };1261        }12621263        // Desktop: iterate all paired devices and sync with each.1264        const paired = await getPairedDevices();1265        if (!paired.length) return { ok: true, data: { syncedCount: 0, reason: "no_paired_devices" } };12661267        const subnet = await getLocalSubnet();1268        const results: Array<{ device: string } & SyncResult> = [];12691270        for (const device of paired) {1271          if (!device.x25519PublicKey) continue;12721273          let result: SyncResult;12741275          // Fast path — use last known IP1276          if (device.lastKnownIp) {1277            result = await doVaultSync(device.lastKnownIp, device.x25519PublicKey);1278          } else {1279            result = { status: 'errored', applied: false, error: 'no_ip' };1280          }12811282          // Discovery path — scan if fast path failed1283          if (result.status === 'errored' && subnet) {1284            const newIp = await discoverDevice(subnet, device.x25519PublicKey);1285            if (newIp) {1286              await updatePairedDevice(device.x25519PublicKey, { lastKnownIp: newIp });1287              result = await doVaultSync(newIp, device.x25519PublicKey);1288            }1289          }12901291          if (result.status === 'completed') {1292            await updatePairedDevice(device.x25519PublicKey, {1293              lastSeenAt: Date.now(),1294              lastSyncAt: Date.now(),1295            });1296          }12971298          results.push({ device: device.displayName, ...result });1299        }13001301        const syncedCount = results.filter(r => r.status === 'completed').length;1302        if (syncedCount > 0) {1303          await chrome.storage.local.set({ peach_last_sync_at: String(Date.now()) });1304        }1305        return { ok: true, data: { syncedCount, results } };1306      }1307      // Android-only: biometric unlock with pre-derived key.1308      case "UNLOCK_WITH_KEY": {1309        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1310        if (!isNativePlatform()) {1311          return { ok: false, error: "desktop_only_uses_password" };1312        }1313        try {1314          const result = await vault.unlockWithKey(masterKeyHex);1315          if (result.ok) {1316            onVaultUnlocked();1317            await publishInMemoryVault(result.entries);1318          }1319          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1320        } catch {1321          return { ok: false, error: "invalid_key" };1322        }1323      }1324      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1325      case "GET_DERIVED_KEY": {1326        if (!isNativePlatform()) {1327          return { ok: false, error: "android_only" };1328        }1329        if (!vault.isUnlocked()) {1330          return { ok: false, error: "vault_locked" };1331        }1332        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1333      }1334      // Android: scanned a QR containing a desktop pairing token.1335      case "SCAN_PAIRING_QR": {1336        if (!isNativePlatform()) {1337          return { ok: false, error: "android_only" };1338        }1339        const { token } = msg.payload as { token: string };1340        syncBridge()?.startPairingSession?.({ token });1341        return { ok: true };1342      }1343      // Android: desktop opened a sync connection to the phone's WS server.1344      // Run the responder side of the vault exchange.1345      case "SYNC_SESSION_STARTED": {1346        if (!isNativePlatform()) return { ok: false };1347        if (!vault.isUnlocked()) {1348          return { ok: false, error: "vault_locked" };1349        }1350        const { connectionId } = (msg.payload ?? {}) as { connectionId?: string };1351        if (!connectionId) return { ok: false, error: "missing_connection_id" };13521353        const transport = createAndroidResponderTransport(connectionId);13541355        // Authenticate the initiator before exchanging any vault data. The1356        // native side has already completed the Noise NK handshake; auth1357        // frames here ride the Noise transport (native encrypts/decrypts).1358        const identity = await vault.getSyncIdentity();1359        try {1360          const noiseSessionStub = {1361            encrypt: (b: Uint8Array) => b,1362            decrypt: (b: Uint8Array) => b,1363            handshakeHash: new Uint8Array(32),1364          };1365          const { initiatorPublicKey } = await performResponderAuth(1366            noiseSessionStub,1367            identity.privateKeyBytes,1368            identity.publicKeyBytes,1369            transport.send,1370            transport.receive,1371          );1372          const initiatorHex = noiseBytesToHex(initiatorPublicKey);1373          const paired = await getPairedDevices();1374          if (!paired.some(d => d.x25519PublicKey === initiatorHex)) {1375            await transport.close();1376            return { ok: false, error: "sync_rejected_unpaired_initiator" };1377          }1378        } catch (err) {1379          await transport.close();1380          return { ok: false, error: `sync_auth_failed: ${String(err)}` };1381        }13821383        const result = await runBlobSyncSession('responder', transport, buildSyncDeps());1384        if (result.applied) {1385          await publishInMemoryVault(vault.getEntries());1386        }1387        return { ok: true, data: result };1388      }1389      // Android: returns the phone's WiFi IP address.1390      case "GET_LOCAL_IP": {1391        if (!isNativePlatform()) {1392          return { ok: false, error: "android_only" };1393        }1394        const { ip } = (await syncBridge()?.getLocalIp?.()) ?? { ip: "" };1395        return { ok: true, data: { ip } };1396      }1397      case "GET_IDENTITY_SUGGESTIONS": {1398        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1399        const entries = vault.getEntries();1400        const suggestions = buildIdentitySuggestions(entries);1401        return { ok: true, data: { suggestions } };1402      }1403      case "POPULATE_INLINE_VAULT": {1404        if (!isNativePlatform()) return { ok: false };1405        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1406        const entries = vault.getEntries();1407        await publishInMemoryVault(entries);1408        return { ok: true };1409      }1410      case "ML_INIT":1411        return { ok: true };14121413      case "ML_PREDICT_BATCH": {1414        const { featuresArray } = msg.payload as { featuresArray: MLFieldFeatures[] };1415        return { ok: true, data: mlPredictBatch(featuresArray) };1416      }14171418      default:1419        return { ok: false, error: "unknown message type" };1420    }1421  } catch (err) {1422    return {1423      ok: false,1424      error: err instanceof Error ? err.message : "operation failed",1425    };1426  }1427}14281429// --- Mobile platform helpers ---14301431// Android: populates the in-memory vault used by PeachAutofillService.1432async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1433  const plugin = nativePlugin<{1434    setEntries?: (args: {1435      entries: Array<{1436        id: string;1437        title: string;1438        username: string;1439        email: string;1440        password: string;1441        url: string;1442        totp: string;1443        additionalUrls: string[];1444      }>;1445    }) => Promise<void>;1446  }>("InMemoryVaultPlugin");1447  if (!plugin?.setEntries) return;1448  await plugin.setEntries({1449    entries: entries.map((e) => ({1450      id: e.id,1451      title: e.title ?? "",1452      username: e.username ?? "",1453      email: (e as VaultEntry & { email?: string }).email ?? "",1454      password: e.password ?? "",1455      url: e.url ?? "",1456      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1457      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1458    })),1459  });1460}14611462// Android: clear the autofill in-memory store on lock.1463async function clearInMemoryVault(): Promise<void> {1464  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1465  if (!plugin?.clearEntries) return;1466  await plugin.clearEntries();1467}14681469interface SyncBridge {1470  ensureServerRunning?: () => void;1471  startPairingSession?: (args: { token: string }) => void;1472  getLocalIp?: () => Promise<{ ip: string }>;1473  sendToConnection?: (args: { connectionId: string; data: string }) => Promise<void>;1474  addListener?: (event: string, handler: (data: Record<string, string>) => void) => void;1475}14761477// Resolve the Capacitor SyncPlugin at call time — module-load resolution1478// races with Capacitor's plugin registration on the Android WebView.1479function syncBridge(): SyncBridge | null {1480  return nativePlugin<SyncBridge>("SyncPlugin");1481}14821483// Build a SyncTransport for the Android responder path — the phone's WS server1484// already has an open connection from the desktop. We send back via1485// SyncPlugin.sendToConnection and receive via the peach:sync-frame queue.1486const androidSyncFrameQueues = new Map<string, Array<(frame: string) => void>>();14871488export function deliverAndroidSyncFrame(connectionId: string, frame: string): void {1489  const queue = androidSyncFrameQueues.get(connectionId);1490  if (queue?.length) queue.shift()!(frame);1491}14921493function createAndroidResponderTransport(connectionId: string) {1494  const pendingReceivers: Array<(frame: string) => void> = [];1495  androidSyncFrameQueues.set(connectionId, pendingReceivers);14961497  return {1498    send: async (data: Uint8Array) => {1499      await syncBridge()?.sendToConnection?.({ connectionId, data: bytesToBase64(data) });1500    },1501    receive: (): Promise<Uint8Array> => new Promise((res) => {1502      pendingReceivers.push((frame) => {1503        res(frame ? base64ToBytes(frame) : new Uint8Array(0));1504      });1505    }),1506    close: async () => {1507      androidSyncFrameQueues.delete(connectionId);1508    },1509  };1510}15111512// Returns username use-counts from the vault, sorted by frequency. Each row1513// also carries the entry's email so the popup can suggest the email/username1514// pair the user has actually used together.1515function buildIdentitySuggestions(1516  entries: VaultEntry[],1517): Array<{ email: string; username: string; count: number }> {1518  const usernameCounts = new Map<string, number>();1519  const usernameEmail = new Map<string, string>();1520  for (const entry of entries) {1521    const username = entry.username ?? "";1522    const email = (entry as VaultEntry & { email?: string }).email ?? "";1523    if (!username && !email) continue;1524    const key = username || email;1525    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1526    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1527  }1528  return Array.from(usernameCounts.entries())1529    .sort((a, b) => b[1] - a[1])1530    .map(([username, count]) => ({1531      email: usernameEmail.get(username) ?? "",1532      username,1533      count,1534    }));1535}15361537/** Notify all content scripts that the vault just became available. */1538function broadcastToContentScripts(message: { type: string }): void {1539  if (!chrome.tabs?.query) return;1540  chrome.tabs.query({}, (tabs) => {1541    for (const tab of tabs) {1542      if (tab.id !== undefined) {1543        chrome.tabs.sendMessage(tab.id, message).catch(() => {1544          // Tab may not have a content script — silently ignore1545        });1546      }1547    }1548  });1549}15501551function shouldRefreshAutoLock(type: MessageType): boolean {1552  return (1553    type !== "HAS_VAULT" &&1554    type !== "IS_UNLOCKED" &&1555    type !== "GET_VAULT_STATUS" &&1556    type !== "LOCK" &&1557    type !== "UPDATE_SETTINGS" &&1558    type !== "GET_PENDING_PASSKEY" &&1559    type !== "GET_PASSKEY_PROVIDER_STATE" &&1560    type !== "DECLINE_CARD_SAVE" &&1561    type !== "IS_CARD_DECLINED" &&1562    type !== "SUBMIT_FEEDBACK"1563  );1564}15651566function isAllowedCanaryWebhookUrl(value: string): boolean {1567  try {1568    const url = new URL(value);1569    if (url.protocol !== "https:") return false;15701571    const hostname = url.hostname.toLowerCase();1572    if (1573      hostname === "localhost" ||1574      hostname.endsWith(".localhost") ||1575      isPrivateIpv4(hostname) ||1576      isPrivateIpv6(hostname)1577    ) {1578      return false;1579    }15801581    return true;1582  } catch {1583    return false;1584  }1585}15861587function isPrivateIpv4(hostname: string): boolean {1588  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1589    return true;1590  }15911592  const octets = hostname.split(".").map((part) => Number(part));1593  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1594    return false;1595  }15961597  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1598}15991600function isPrivateIpv6(hostname: string): boolean {1601  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1602  return (1603    normalized === "::1" ||1604    normalized.startsWith("fc") ||1605    normalized.startsWith("fd") ||1606    normalized.startsWith("fe80:")1607  );1608}