messages.ts

60.1 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard } from "./clipboard";13import { setupAutoLock, touchAutoLock } from "./alarms";14import * as vault from "./vault";15import {16  handleEstimateCodexPages,17  handleGetCodexVaultData,18  handleRestoreFromCodex,19} from "./codex-handlers";20import type { CodexRestorePayload } from "../shared/codex-types";21import {22  activateLicense,23  deactivateLicense,24  getLicenseInfo,25  getLicenseKey,26  isProUser,27  markCelebrationPlayed,28  shouldPlayCelebration,29} from "./license";30import {31  cancelFirefoxPasskeyCreate,32  completeFirefoxPasskeyCreate,33  getPasskeyProviderState,34  getPendingPasskeyRequest,35  handleFirefoxPasskeyCreate,36  handleFirefoxPasskeyGet,37  handlePasskeyHasCredentials,38  initiateFirefoxPasskeyCreate,39  isPasskeyOfferDeclined,40  onVaultUnlocked,41  recordPasskeyOfferDecline,42  resolvePendingPasskeyRequest,43  setPasskeyProviderEnabled,44} from "./passkey";45import { buildAdvancedHealthReport, resolveResetUrl } from "./health";46import { storageClear, storageGet } from "../shared/storage";47import { findInvalidWords } from "../shared/recovery-words";48import {49  addPairedDevice,50  addTrustedNetwork,51  clearIncomingPairingRequest,52  getIncomingPairingRequest,53  getPairedDevices,54  getTrustedNetworks,55  removePairedDevice,56  removeTrustedNetwork,57  setIncomingPairingRequest,58  updatePairedDevice,59} from "./sync-storage";60import { getCurrentNetwork, isOnTailscale } from "./sync-network";61import {62  consumeRecentPairing,63  setActivePairingToken,64} from "./pairing-server-state";65import type {66  Message,67  MessageResponse,68  MessageType,69  ProFeature,70  VaultEntry,71} from "../shared/types";72import { isPasskeyOnly } from "../shared/types";73import type { SyncStatus, SyncableDevice } from "../shared/sync-types";74import { isNativePlatform, nativePlugin } from "../shared/native";75import { runBlobSyncSession, type SyncResult } from "./sync-coordinator";76import type { SyncDeps } from "./sync-coordinator";77import { createWebSocketSyncTransport } from "../shared/websocket-sync-transport";78import { performResponderAuth, bytesToHex as noiseBytesToHex } from "../shared/noise-js";79import { getLocalSubnet, discoverDevice, scanForPairingPhone } from "../shared/local-network";80import { predictBatch as mlPredictBatch } from "./ml";81import type { MLFieldFeatures } from "../shared/ml";82import { base64ToBytes, bytesToBase64 } from "../shared/sync-wire";8384/**85 * The single Pro gate. Every gated handler calls this first; the broadcast86 * lets the popup react (navigate to the License section, highlight the87 * relevant feature). Background never touches the popup view directly —88 * the popup owns navigation. See Projects.md "Pro gate rule".89 */90async function requirePro(91  feature: ProFeature,92  trigger: "user" | "background" = "user"93): Promise<{ allowed: boolean }> {94  if (await isProUser()) return { allowed: true };9596  if (trigger === "user") {97    // User deliberately triggered this feature — redirect the popup immediately.98    chrome.runtime99      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })100      .catch(() => {101        // Popup may be closed — the gate signal is best-effort.102      });103  } else {104    // Background trigger (e.g. passive sync initiation) — no popup is open.105    // Queue a notice so the next popup open shows a soft banner instead of106    // silently failing.107    if (chrome.storage.session) {108      chrome.storage.session109        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })110        .catch(() => {});111    }112  }113114  return { allowed: false };115}116117// ---------------------------------------------------------------------------118// Local device name. Peers see this string in PAIR_REQUEST / PAIR_ACCEPT and119// next to the device in their paired-devices list. Default to a platform-aware120// fallback when the user hasn't set one explicitly.121const DEVICE_NAME_KEY = "peach_device_name";122123async function getLocalDeviceName(): Promise<string> {124  try {125    const stored = await chrome.storage.local.get(DEVICE_NAME_KEY);126    const value = (stored as Record<string, string | undefined>)[DEVICE_NAME_KEY];127    if (typeof value === "string" && value.trim()) return value.trim();128  } catch {129    // fall through to default130  }131  return "Peach";132}133134// ---------------------------------------------------------------------------135// 6-digit code pairing.136137const PAIRING_TOKEN_TTL_MS = 5 * 60 * 1000;138139140function generateSixDigitToken(): string {141  // crypto.getRandomValues, not Math.random — the token is the only secret142  // protecting the pairing window from a same-LAN attacker. 6 decimal digits143  // is 1 in 1,000,000; combined with a 5-minute TTL and pairing-mode gating144  // on the responder this is the right tradeoff between UX and security.145  const buf = new Uint32Array(1);146  crypto.getRandomValues(buf);147  const value = buf[0] % 1_000_000;148  return value.toString().padStart(6, "0");149}150151// ---------------------------------------------------------------------------152// Peer discovery glue (Phase 7 popup pairing flow).153154const PRIVATE_IPV4_RANGES = [155  { prefix: "10." },156  { prefix: "127." },157  { prefix: "169.254." },158  { prefix: "192.168." },159];160161// Empty disables network submission while the UI continues to function as a162// no-op (the handler returns ok:true without calling fetch). When set, the163// URL is validated by `isAllowedCanaryWebhookUrl` before any request, so the164// same private-IP/HTTPS rules that gate canary webhooks apply here.165const FEEDBACK_ENDPOINT = "";166167// ---------------------------------------------------------------------------168// Sync helpers169// ---------------------------------------------------------------------------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          return { ok: true };403        }404        // Distinguish corruption from wrong password so the popup can offer405        // a history-restore path instead of falsely accusing the user of406        // mistyping (M7/COR-007).407        const failure = vault.consumeLastUnlockFailureReason();408        if (failure) {409          return {410            ok: false,411            error: "vault_corrupted",412            canRestoreFromHistory: true,413          } as MessageResponse;414        }415        return { ok: false };416      }417      case "VALIDATE_RECOVERY_WORDS": {418        const { words } = msg.payload as { words: string[] };419        const invalid = findInvalidWords(words);420        return { ok: true, data: { valid: invalid.length === 0, invalid } };421      }422      case "GET_RECOVERY_WORDS": {423        // Must be unlocked and have recovery set up (vault must be v2.12+).424        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };425        try {426          const words = await vault.getRecoveryWords();427          return { ok: true, data: words };428        } catch (e) {429          // pre-v2.12 vault that hasn't migrated430          return { ok: false, error: "recovery_not_setup" };431        }432      }433      case "RECOVER_WITH_WORDS": {434        // User has lost their password but has their 12 recovery words.435        // We: (1) validate the words, (2) re-encrypt vault with new password.436        const { words, newPassword } = msg.payload as {437          words: string[];438          newPassword: string;439        };440        const stored = await vault.loadSlotA();441        if (!stored) return { ok: false, error: "no vault" };442        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {443          return { ok: false, error: "recovery_not_setup" };444        }445        // Unwrap the root key from the recovery escrow.446        try {447          await vault.unwrapRootKeyForRecovery(448            stored.recovery_wrapped_root_key,449            stored.recovery_nonce ?? "",450            stored.recovery_tag ?? "",451            stored.recovery_salt,452            words453          );454        } catch {455          return { ok: false, error: "invalid_recovery_words" };456        }457        // Re-key: derive fresh salt + key from new password.458        const newSalt = vault.generateSalt();459        const newKey = await vault.deriveKey(newPassword, newSalt);460        // Re-wrap root key under the new password's derived key so the same461        // recovery words continue to work after the password change.462        await vault.rewrapRootKeyForPassword(newKey, newSalt);463        // Re-encrypt vault entries with the new key.464        await vault.changePasswordWithNewKey(newSalt, newKey);465        await setupAutoLock();466        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });467        return { ok: true };468      }469      case "LOCK":470        vault.lock();471        if (isNativePlatform()) await clearInMemoryVault();472        return { ok: true };473      case "IS_UNLOCKED":474        return { ok: true, data: vault.isUnlocked() };475      case "GET_VAULT_STATUS":476        return { ok: true, unlocked: vault.isUnlocked() };477      case "HAS_VAULT":478        return { ok: true, data: await vault.hasVault() };479      case "GET_ENTRIES":480        return { ok: true, data: vault.getEntries() };481      case "ADD_ENTRY": {482        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };483        const entry = await vault.addEntry(msg.payload as any);484        return { ok: true, data: entry };485      }486      case "BATCH_ADD_ENTRIES": {487        const { entries } = msg.payload as { entries: any[] };488        const added = await vault.batchAddEntries(entries);489        return { ok: true, data: added };490      }491      case "RESTORE_ENTRIES": {492        const { entries, mode, settings } = msg.payload as {493          entries: any[];494          mode: "replace" | "merge";495          settings?: vault.VaultSettings;496        };497        const summary = await vault.restoreEntries(entries, mode);498        if (settings && typeof settings === "object") {499          await vault.updateSettings(settings);500        }501        return { ok: true, data: summary };502      }503      case "CLEAR_VAULT_ENTRIES": {504        await vault.clearVaultEntries("REPLACE_ALL");505        return { ok: true };506      }507      case "GET_VAULT_HISTORY": {508        const snapshots = await vault.getVaultHistory();509        return { ok: true, data: snapshots };510      }511      case "RESTORE_VAULT_SNAPSHOT": {512        const { snapshotId } = msg.payload as { snapshotId: string };513        const result = await vault.restoreVaultSnapshot(snapshotId);514        if (!result.ok) return { ok: false, error: result.error };515        broadcastToContentScripts({ type: "VAULT_LOCKED" });516        return { ok: true };517      }518      case "COUNT_DUPLICATES": {519        return { ok: true, data: vault.countDuplicates() };520      }521      case "DEDUPLICATE_ENTRIES": {522        const removed = await vault.deduplicateEntries();523        return { ok: true, data: removed };524      }525      case "UPDATE_ENTRY": {526        const { id, patch } = msg.payload as any;527        await vault.updateEntry(id, patch);528        return { ok: true };529      }530      case "ADD_ADDITIONAL_URL": {531        const { id, url } = msg.payload as { id: string; url: string };532        const trimmed = typeof url === "string" ? url.trim() : "";533        if (!trimmed) return { ok: false, error: "url required" };534        const existing = vault.getEntryById(id);535        if (!existing) return { ok: false, error: "entry not found" };536        if (existing.type !== "login") return { ok: false, error: "login entries only" };537        const merged = [...(existing.additionalUrls ?? []), trimmed];538        await vault.updateEntry(id, { additionalUrls: merged });539        return { ok: true };540      }541      case "DELETE_ENTRY": {542        const { id } = msg.payload as { id: string };543        await vault.deleteEntry(id);544        return { ok: true };545      }546      case "GET_DELETED_ENTRIES":547        return { ok: true, data: vault.getDeletedEntries() };548      case "RESTORE_ENTRY": {549        const { id } = msg.payload as { id: string };550        await vault.restoreEntry(id);551        return { ok: true };552      }553      case "PURGE_ENTRY": {554        const { id } = msg.payload as { id: string };555        await vault.purgeEntry(id);556        return { ok: true };557      }558      case "PURGE_EXPIRED_TRASH": {559        const { retentionMs } = msg.payload as { retentionMs: number };560        const purged = await vault.purgeExpiredTrash(retentionMs);561        return { ok: true, data: purged };562      }563      case "SAVE_NOTE": {564        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };565        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };566        const now = Date.now();567        if (id) {568          const existing = vault.getEntryById(id);569          if (!existing) return { ok: false, error: "not_found" };570          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });571          return { ok: true, data: vault.getEntryById(id) };572        } else {573          const entry = await vault.addEntry({574            type: "note",575            title: title || "Untitled",576            notes: body,577            createdAt: now,578            modifiedAt: now,579          } as any);580          return { ok: true, data: entry };581        }582      }583      case "DELETE_NOTE": {584        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };585        const { id } = msg.payload as { id: string };586        await vault.deleteEntry(id);587        return { ok: true };588      }589      case "GET_NOTES": {590        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };591        const notes = vault.getEntries().filter(592          (e) => e.type === "note" && !e.deletedAt593        );594        return { ok: true, data: notes } as MessageResponse;595      }596      case "SEARCH_VAULT": {597        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };598        const { query } = msg.payload as { query: string };599        const q = query.toLowerCase();600        const searchResults = vault.getEntries().filter(601          (e) =>602            !e.deletedAt &&603            (e.title.toLowerCase().includes(q) ||604              e.notes?.toLowerCase().includes(q) ||605              e.username?.toLowerCase().includes(q))606        );607        return { ok: true, data: searchResults } as MessageResponse;608      }609      case "PAIRING_COMPLETED": {610        const { deviceName, publicKeyHex, deviceIp } = (msg.payload ?? {}) as {611          deviceName?: string;612          publicKeyHex?: string;613          deviceIp?: string;614        };615        if (!publicKeyHex) return { ok: false, error: "publicKeyHex required" };616        const { setHasPaired: setPaired } = await import("./sync-storage");617        await setPaired();618        try {619          await addPairedDevice({620            deviceId: publicKeyHex,621            displayName: deviceName ?? "Unknown",622            x25519PublicKey: publicKeyHex,623            pairedAt: Date.now(),624            lastSeenAt: Date.now(),625            lastKnownIp: deviceIp,626          });627        } catch {628          // Already paired — update IP if provided629          if (deviceIp) {630            await updatePairedDevice(publicKeyHex, { lastKnownIp: deviceIp, lastSeenAt: Date.now() });631          }632        }633        return { ok: true };634      }635      case "AUTOFILL_QUERY": {636        if (!vault.isUnlocked()) {637          return { ok: false, error: "VAULT_LOCKED" };638        }639        const { domain, includeAll, kind } = msg.payload as {640          domain: string;641          includeAll?: boolean;642          kind?: "login" | "card";643        };644        // kind="card": return saved cards as compact summaries for the645        // inline card silver platter. Cards are not domain-scoped — every646        // saved card is a candidate on every checkout page — so domain is647        // ignored when kind === "card".648        if (kind === "card") {649          const cards = vault.getEntries().filter((e) => e.type === "card");650          return {651            ok: true,652            data: cards.map((e) => ({653              id: e.id,654              title: e.cardNickname || e.title,655              cardholderName: e.cardholderName,656              last4: e.last4,657              expMonth: e.expMonth,658              expYear: e.expYear,659              network: e.network,660            })),661          };662        }663        // The inline selector fills username+password into a form. Passkey-664        // only entries have no password to fill; sign-in for those goes665        // through the WebAuthn path instead. Filter them out everywhere so666        // the user doesn't see four "GitHub" rows that mostly do nothing.667        // Notes and cards never belonged here either.668        const matches = (669          includeAll670            ? vault671                .getEntries()672                .filter((entry) => entry.type !== "note" && entry.type !== "card")673            : vault.queryDomain(domain)674        ).filter((entry) => !isPasskeyOnly(entry));675        return {676          ok: true,677          data: matches.map((e) =>678            includeAll679              ? {680                  id: e.id,681                  title: e.title,682                  hasPasskey: e.passkey !== undefined,683                }684              : {685                  id: e.id,686                  title: e.title,687                  username: e.username,688                  email: e.email,689                  url: e.url,690                  hasTotp: Boolean(e.totp),691                  hasPasskey: e.passkey !== undefined,692                }693          ),694        };695      }696      case "GET_ENTRY_FOR_FILL": {697        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };698        const { id } = msg.payload as { id: string };699        const entry = vault.getEntryById(id);700        if (!entry) return { ok: false, error: "entry not found" };701        // Passkey-only entries (passkey credential, no password) cannot be702        // filled into a form — sign-in goes through the WebAuthn path. A703        // login that ALSO has a passkey is still fillable for its password.704        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey not fillable" };705        // Strip the passkey credential from the response — content scripts706        // never need the private key, and there's no reason to expose the707        // public credential metadata over the boundary either.708        const { passkey: _strippedPasskey, ...safeEntry } = entry;709        return { ok: true, data: safeEntry };710      }711      case "COPY": {712        const { text, label, alreadyWritten } = msg.payload as {713          text: string;714          label: string;715          alreadyWritten?: boolean;716        };717        await copyToClipboard(text, label, Boolean(alreadyWritten));718        return { ok: true };719      }720      case "CHECK_ALL_BREACHES": {721        const allEntries = vault.getEntries();722        const results: Record<string, number> = {};723        for (const entry of allEntries) {724          if (entry.type === "note") continue;725          if (!entry.password) continue;726          results[entry.id] = await vault.checkBreach(entry.password);727          // Small delay — be a good citizen to the HIBP API728          await new Promise((r) => setTimeout(r, 200));729        }730        // Persist any non-zero counts back to entries731        for (const [id, count] of Object.entries(results)) {732          const entry = vault.getEntryById(id);733          if (entry && (entry.breach ?? 0) !== count) {734            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });735          }736        }737        return { ok: true, data: results };738      }739      case "GET_SETTINGS":740        return { ok: true, data: await vault.ensureSettingsLoaded() };741      case "UPDATE_SETTINGS": {742        const patch = msg.payload as Record<string, unknown>;743        await vault.updateSettings(patch as any);744        if (typeof patch.autoLockMinutes === "number") {745          await setupAutoLock();746          if (vault.isUnlocked()) touchAutoLock();747        }748        return { ok: true };749      }750      case "GET_PENDING_PASSKEY":751        return { ok: true, data: await getPendingPasskeyRequest() };752      case "APPROVE_PASSKEY": {753        const { requestId } = msg.payload as { requestId: number };754        await resolvePendingPasskeyRequest(requestId, true);755        return { ok: true };756      }757      case "DENY_PASSKEY": {758        const { requestId } = msg.payload as { requestId: number };759        await resolvePendingPasskeyRequest(requestId, false);760        return { ok: true };761      }762      case "GET_PASSKEY_PROVIDER_STATE":763        return { ok: true, data: await getPasskeyProviderState() };764      case "SET_PASSKEY_PROVIDER_ENABLED": {765        const { enabled } = msg.payload as { enabled: boolean };766        // Disabling is always free; gating fires only when a free user is767        // trying to turn passkey interception on.768        if (enabled) {769          const gate = await requirePro("passkeys");770          if (!gate.allowed) return { ok: false, error: "pro_required" };771        }772        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };773      }774      case "FIRE_CANARY_PING": {775        const { webhookUrl, entryTitle, trigger } = msg.payload as {776          webhookUrl: string;777          entryTitle: string;778          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";779        };780        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {781          return { ok: false, error: "invalid webhook url" };782        }783        const body = JSON.stringify({784          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",785          entry: entryTitle,786          trigger,787          timestamp: new Date().toISOString(),788          source: "peach-extension",789        });790        if (trigger === "test") {791          // Permitted outbound fetch: user-configured canary alert endpoint792          // (validated by isAllowedCanaryWebhookUrl above). This is the793          // only non-HIBP outbound call in the extension — see794          // Projects.md §3.7. Test pings are awaited so the UI can show795          // success/failure.796          try {797            const res = await fetch(webhookUrl, {798              method: "POST",799              headers: { "Content-Type": "application/json" },800              body,801            });802            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };803          } catch (err) {804            return { ok: false, error: err instanceof Error ? err.message : "network error" };805          }806        }807        // Non-test triggers are fire-and-forget808        fetch(webhookUrl, {809          method: "POST",810          headers: { "Content-Type": "application/json" },811          body,812        }).catch(() => {});813        return { ok: true };814      }815      case "ACTIVATE_LICENSE": {816        const { key } = msg.payload as { key: string };817        const licenseInfo = await activateLicense(key);818        return { ok: true, data: licenseInfo };819      }820      case "GET_LICENSE": {821        const licenseInfo = await getLicenseInfo();822        return { ok: true, data: licenseInfo };823      }824      case "GET_LICENSE_KEY": {825        const key = await getLicenseKey();826        return { ok: true, data: key };827      }828      case "DEACTIVATE_LICENSE": {829        await deactivateLicense();830        return { ok: true };831      }832      case "SHOULD_PLAY_CELEBRATION": {833        const should = await shouldPlayCelebration();834        return { ok: true, data: should };835      }836      case "MARK_CELEBRATION_PLAYED": {837        await markCelebrationPlayed();838        return { ok: true };839      }840      case "GET_CODEX_VAULT_DATA": {841        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the842        // popup navigates to the License section without further coordination.843        const gate = await requirePro("codex");844        if (!gate.allowed) return { ok: false, error: "pro_required" };845        return await handleGetCodexVaultData();846      }847      case "ESTIMATE_CODEX_PAGES": {848        const gate = await requirePro("codex");849        if (!gate.allowed) return { ok: false, error: "pro_required" };850        return await handleEstimateCodexPages();851      }852      case "RESTORE_FROM_CODEX": {853        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still854        // be able to restore a vault that was printed by a Pro user.855        // DO NOT add a Pro gate here.856        const payload = msg.payload as CodexRestorePayload;857        return await handleRestoreFromCodex(payload);858      }859      case "OPEN_PRO_GATE": {860        // Content script requests: open popup and navigate to License section.861        const { feature } = (msg.payload ?? {}) as { feature?: string };862        if (chrome.storage.session) {863          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });864        }865        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }866        return { ok: true };867      }868      case "GET_IDENTITIES": {869        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };870        return { ok: true, data: vault.getIdentities() };871      }872      case "TOUCH_AUTO_LOCK": {873        // touchAutoLock() is already called by shouldRefreshAutoLock above;874        // this case just gives the popup a typed message to keep the session alive.875        return { ok: true };876      }877      case "GET_ADVANCED_HEALTH_REPORT": {878        const gate = await requirePro("advanced_health");879        if (!gate.allowed) return { ok: false, error: "pro_required" };880        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };881        const report = await buildAdvancedHealthReport(vault.getEntries());882        return { ok: true, data: report };883      }884      case "INITIATE_PASSWORD_CHANGE": {885        const gate = await requirePro("smart_password_change");886        if (!gate.allowed) return { ok: false, error: "pro_required" };887        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };888        const { id } = msg.payload as { id: string };889        const entry = vault.getEntryById(id);890        if (!entry) return { ok: false, error: "entry not found" };891        const url = resolveResetUrl(entry);892        if (!url) return { ok: false, error: "no reset url" };893        try {894          await chrome.tabs.create({ url });895          return { ok: true, data: { url } };896        } catch (err) {897          return {898            ok: false,899            error: err instanceof Error ? err.message : "failed to open tab",900          };901        }902      }903      case "IS_DURESS_ENABLED": {904        const enabled = await vault.isDuressEnabled();905        return { ok: true, data: enabled };906      }907      case "SETUP_DURESS": {908        const { duressPassword } = msg.payload as { duressPassword: string };909        await vault.setupDuress(duressPassword);910        return { ok: true };911      }912      case "DISABLE_DURESS": {913        await vault.disableDuress();914        return { ok: true };915      }916      case "VERIFY_MAIN_PASSWORD": {917        const { password } = msg.payload as { password: string };918        const ok = await vault.verifyMainPassword(password);919        return { ok: true, data: ok };920      }921      case "CHANGE_PASSWORD": {922        const { currentPassword, newPassword } = msg.payload as {923          currentPassword: string;924          newPassword: string;925        };926        const changed = await vault.changePassword(currentPassword, newPassword);927        return changed928          ? { ok: true }929          : { ok: false, error: "incorrect current password" };930      }931      case "GET_SITE_PASSWORD_POLICY": {932        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });933        if (!tab?.id) return { ok: true, data: null };934        try {935          const response = await chrome.tabs.sendMessage(tab.id, {936            type: "GET_SITE_PASSWORD_POLICY",937          });938          return (response as MessageResponse) ?? { ok: true, data: null };939        } catch {940          return { ok: true, data: null };941        }942      }943      case "GET_SYNC_STATE": {944        const pairedDevices = await getPairedDevices();945        const trustedNetworks = await getTrustedNetworks();946        const tailscale = await isOnTailscale();947        const pro = await isProUser();948949        let status: SyncStatus = "offline";950        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {951          if (pairedDevices.length === 0) {952            status = "no_peers";953          } else {954            status = "synced";955          }956        } else {957          status = "not_trusted";958        }959960        const lastSyncRaw = await storageGet("peach_last_sync_at");961        const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN;962        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined;963964        return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } };965      }966      case "GET_PAIRED_DEVICES": {967        const devices = await getPairedDevices();968        return { ok: true, data: { devices } };969      }970      case "GET_SYNC_STATUS": {971        const lastSyncRaw = await storageGet("peach_last_sync_at");972        const lastSyncParsed = lastSyncRaw ? parseInt(lastSyncRaw, 10) : NaN;973        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : null;974        const status: 'up_to_date' | 'never' = lastSyncAt ? 'up_to_date' : 'never';975        return { ok: true, data: { status, lastSyncAt } };976      }977      case "ACCEPT_PAIRING": {978        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.979        return { ok: true };980      }981      case "REMOVE_PAIRED_DEVICE": {982        const { deviceId } = msg.payload as { deviceId: string };983        await removePairedDevice(deviceId);984        return { ok: true };985      }986      case "REMOVE_TRUSTED_NETWORK": {987        const { ssid, bssid, isTailscale } = msg.payload as any;988        const networks = await getTrustedNetworks();989        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 990          (isTailscale ? n.isTailscale : n.ssid === ssid) && 991          (!bssid || n.bssid === bssid)992        );993        if (network) {994          await removeTrustedNetwork(network.addedAt);995        }996        return { ok: true };997      }998      case "MARK_NETWORK_TRUSTED": {999        const network = await getCurrentNetwork();1000        await addTrustedNetwork({1001          ssid: network.ssid,1002          bssid: network.bssid,1003          isTailscale: network.isTailscale,1004          addedAt: Date.now(),1005        });1006        return { ok: true };1007      }1008      case "GET_INCOMING_PAIRING_REQUEST": {1009        const request = await getIncomingPairingRequest();1010        return { ok: true, data: request };1011      }1012      case "RESPOND_INCOMING_PAIRING": {1013        const { accept } = msg.payload as { accept: boolean };1014        const request = await getIncomingPairingRequest();1015        if (!request) return { ok: false, error: "no_pending_request" };1016        if (Date.now() > request.expiresAt) {1017          await clearIncomingPairingRequest();1018          return { ok: false, error: "expired" };1019        }1020        await clearIncomingPairingRequest();1021        if (accept) {1022          await addPairedDevice({1023            deviceId: request.publicKeyHex,1024            displayName: request.deviceName,1025            x25519PublicKey: request.publicKeyHex,1026            pairedAt: Date.now(),1027            lastSeenAt: Date.now(),1028          });1029        }1030        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };1031      }1032      case "START_PAIRING_SERVER": {1033        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.1034        const token = generateSixDigitToken();1035        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;1036        await setActivePairingToken({ token, expiresAt });1037        // Fire-and-forget subnet scan — finds the phone after it scans the QR1038        // and calls SCAN_PAIRING_QR to register the token with SyncPlugin.1039        if (!isNativePlatform()) {1040          void runPairingSubnetScan(token);1041        }1042        return { ok: true, data: { token, expiresAt } };1043      }1044      case "STOP_PAIRING_SERVER": {1045        try {1046          await setActivePairingToken(null);1047        } catch { /* best-effort */ }1048        return { ok: true };1049      }1050      case "GET_RECENT_PAIRING": {1051        const recent = await consumeRecentPairing();1052        return { ok: true, data: recent };1053      }1054      case "DEBUG_INJECT_INCOMING_PAIRING": {1055        // Manual E2E rehearsal hook. Inserts a synthetic incoming pairing1056        // request into session storage so Phase 7 banner UX can be exercised1057        // without a live native host. No Pro gate — this is a no-op in1058        // production unless explicitly invoked from a Settings debug action.1059        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {1060          deviceName?: string;1061          publicKeyHex?: string;1062        };1063        if (!deviceName || !publicKeyHex) {1064          return { ok: false, error: "missing_payload" };1065        }1066        const now = Date.now();1067        await setIncomingPairingRequest({1068          deviceName,1069          publicKeyHex,1070          receivedAt: now,1071          expiresAt: now + 60_000,1072        });1073        return { ok: true };1074      }1075      case "RESET_SYNC_IDENTITY": {1076        const gate = await requirePro("sync");1077        if (!gate.allowed) return { ok: false, error: "pro_required" };1078        const devices = await getPairedDevices();1079        for (const device of devices) {1080          await removePairedDevice(device.deviceId);1081        }1082        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };1083      }1084      case "RECORD_MANUAL_SUMMON": {1085        const { domain } = msg.payload as { domain: string };1086        const settings = vault.getSettings();1087        const existing = settings.manualSummonDomains?.[domain];1088        const now = Date.now();1089        await vault.updateSettings({1090          manualSummonDomains: {1091            ...settings.manualSummonDomains,1092            [domain]: {1093              firstSummonedAt: existing?.firstSummonedAt ?? now,1094              summonCount: (existing?.summonCount ?? 0) + 1,1095              lastSummonedAt: now,1096            },1097          },1098        });1099        return { ok: true };1100      }1101      case "DECLINE_CARD_SAVE": {1102        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1103        await vault.declineCardSaveOffer(last4, expMonth, expYear);1104        return { ok: true };1105      }1106      case "IS_CARD_DECLINED": {1107        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1108        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1109        return { ok: true, data: declined };1110      }1111      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1112        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1113          rpId?: string;1114          rpName?: string;1115          userName?: string;1116          userDisplayName?: string;1117        };1118        if (!rpId || !userName) return { ok: false, error: "rpId and userName required" };1119        return await initiateFirefoxPasskeyCreate({1120          rpId,1121          rpName: rpName ?? rpId,1122          userName,1123          userDisplayName,1124        });1125      }11261127      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1128        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1129        if (!payload) return { ok: false, error: "missing payload" };1130        return await completeFirefoxPasskeyCreate(payload);1131      }11321133      case "PASSKEY_OFFER_DECLINE": {1134        const { domain } = (msg.payload ?? {}) as { domain?: string };1135        if (!domain) return { ok: false, error: "domain required" };1136        await recordPasskeyOfferDecline(domain);1137        return { ok: true };1138      }11391140      case "GET_PASSKEY_OFFER_DECLINED": {1141        const { domain } = (msg.payload ?? {}) as { domain?: string };1142        if (!domain) return { ok: false, error: "domain required" };1143        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1144      }11451146      case "PASSKEY_HAS_CREDENTIALS": {1147        const payload = msg.payload as {1148          rpId?: string;1149          allowCredentials?: Array<{ id: string; type?: string }>;1150        } | undefined;1151        if (!payload?.rpId) return { ok: false, error: "rpId required" };1152        return await handlePasskeyHasCredentials({1153          rpId: payload.rpId,1154          allowCredentials: payload.allowCredentials ?? [],1155        });1156      }11571158      case "PASSKEY_CREATE": {1159        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1160        if (!payload?.rpId || !payload?.userName) {1161          return { ok: false, error: "rpId and userName required" };1162        }1163        return await handleFirefoxPasskeyCreate(payload);1164      }11651166      case "PASSKEY_GET": {1167        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1168        if (!payload?.rpId) return { ok: false, error: "rpId required" };1169        return await handleFirefoxPasskeyGet(payload);1170      }11711172      case "PASSKEY_AUTH_RESPONSE": {1173        const { requestId, approved } = (msg.payload ?? {}) as {1174          requestId?: string | number;1175          approved?: boolean;1176        };1177        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1178          return { ok: false, error: 'requestId and approved required' };1179        }1180        await resolvePendingPasskeyRequest(Number(requestId), approved);1181        return { ok: true };1182      }11831184      case "GET_PASSKEY_FOR_DOMAIN": {1185        const { domain } = (msg.payload ?? {}) as { domain?: string };1186        if (!domain) return { ok: false, error: "domain required" };1187        if (!vault.isUnlocked()) return { ok: true, data: null };1188        const match = vault1189          .getEntries()1190          .find((entry) => entry.passkey?.rpId === domain);1191        if (!match || !match.passkey) return { ok: true, data: null };1192        // Slim shape — only the fields State 11 needs. Never expose private1193        // key material, even though this is locked behind isUnlocked.1194        return {1195          ok: true,1196          data: {1197            rpId: match.passkey.rpId,1198            userName: match.passkey.userName,1199            browser: match.passkey.browser,1200          },1201        };1202      }12031204      case "DESTROY_VAULT": {1205        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1206        // storage.local.clear() wipes every Peach key (slots, settings, license,1207        // onboarded flag, history, sync state, declined cards, recall, etc.);1208        // session.clear() wipes pending passkey requests + pro-notice queues.1209        // Caller (Panic.tsx) handles UI navigation back to onboarding.1210        vault.lock();1211        await storageClear();1212        await vault.clearVaultHistory();1213        if (chrome.storage.session) {1214          await chrome.storage.session.clear();1215        }1216        return { ok: true };1217      }12181219      case "SUBMIT_FEEDBACK": {1220        const { category, message, version, browser } = msg.payload as {1221          category: string;1222          message: string;1223          version: string;1224          browser: string;1225        };1226        if (!message.trim()) return { ok: false, error: "message is empty" };1227        if (!FEEDBACK_ENDPOINT) return { ok: true };1228        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1229          return { ok: false, error: "invalid feedback endpoint" };1230        }1231        try {1232          const res = await fetch(FEEDBACK_ENDPOINT, {1233            method: "POST",1234            headers: { "Content-Type": "application/json" },1235            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1236          });1237          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1238        } catch (err) {1239          return { ok: false, error: err instanceof Error ? err.message : "network error" };1240        }1241      }1242      case "TRIGGER_SYNC": {1243        const gate = await requirePro("sync");1244        if (!gate.allowed) return { ok: false, error: "pro_required" };1245        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };12461247        if (isNativePlatform()) {1248          // Phone is the server — ensure it's listening for desktop connections.1249          syncBridge()?.ensureServerRunning?.();1250          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };1251        }12521253        // Desktop: iterate all paired devices and sync with each.1254        const paired = await getPairedDevices();1255        if (!paired.length) return { ok: true, data: { syncedCount: 0, reason: "no_paired_devices" } };12561257        const subnet = await getLocalSubnet();1258        const results: Array<{ device: string } & SyncResult> = [];12591260        for (const device of paired) {1261          if (!device.x25519PublicKey) continue;12621263          let result: SyncResult;12641265          // Fast path — use last known IP1266          if (device.lastKnownIp) {1267            result = await doVaultSync(device.lastKnownIp, device.x25519PublicKey);1268          } else {1269            result = { status: 'errored', applied: false, error: 'no_ip' };1270          }12711272          // Discovery path — scan if fast path failed1273          if (result.status === 'errored' && subnet) {1274            const newIp = await discoverDevice(subnet, device.x25519PublicKey);1275            if (newIp) {1276              await updatePairedDevice(device.x25519PublicKey, { lastKnownIp: newIp });1277              result = await doVaultSync(newIp, device.x25519PublicKey);1278            }1279          }12801281          if (result.status === 'completed') {1282            await updatePairedDevice(device.x25519PublicKey, {1283              lastSeenAt: Date.now(),1284              lastSyncAt: Date.now(),1285            });1286          }12871288          results.push({ device: device.displayName, ...result });1289        }12901291        const syncedCount = results.filter(r => r.status === 'completed').length;1292        if (syncedCount > 0) {1293          await chrome.storage.local.set({ peach_last_sync_at: String(Date.now()) });1294        }1295        return { ok: true, data: { syncedCount, results } };1296      }1297      // Android-only: biometric unlock with pre-derived key.1298      case "UNLOCK_WITH_KEY": {1299        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1300        if (!isNativePlatform()) {1301          return { ok: false, error: "desktop_only_uses_password" };1302        }1303        try {1304          const result = await vault.unlockWithKey(masterKeyHex);1305          if (result.ok) {1306            onVaultUnlocked();1307            await publishInMemoryVault(result.entries);1308          }1309          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1310        } catch {1311          return { ok: false, error: "invalid_key" };1312        }1313      }1314      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1315      case "GET_DERIVED_KEY": {1316        if (!isNativePlatform()) {1317          return { ok: false, error: "android_only" };1318        }1319        if (!vault.isUnlocked()) {1320          return { ok: false, error: "vault_locked" };1321        }1322        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1323      }1324      // Android: scanned a QR containing a desktop pairing token.1325      case "SCAN_PAIRING_QR": {1326        if (!isNativePlatform()) {1327          return { ok: false, error: "android_only" };1328        }1329        const { token } = msg.payload as { token: string };1330        syncBridge()?.startPairingSession?.({ token });1331        return { ok: true };1332      }1333      // Android: desktop opened a sync connection to the phone's WS server.1334      // Run the responder side of the vault exchange.1335      case "SYNC_SESSION_STARTED": {1336        if (!isNativePlatform()) return { ok: false };1337        if (!vault.isUnlocked()) {1338          return { ok: false, error: "vault_locked" };1339        }1340        const { connectionId } = (msg.payload ?? {}) as { connectionId?: string };1341        if (!connectionId) return { ok: false, error: "missing_connection_id" };13421343        const transport = createAndroidResponderTransport(connectionId);13441345        // Authenticate the initiator before exchanging any vault data. The1346        // native side has already completed the Noise NK handshake; auth1347        // frames here ride the Noise transport (native encrypts/decrypts).1348        const identity = await vault.getSyncIdentity();1349        try {1350          const noiseSessionStub = {1351            encrypt: (b: Uint8Array) => b,1352            decrypt: (b: Uint8Array) => b,1353            handshakeHash: new Uint8Array(32),1354          };1355          const { initiatorPublicKey } = await performResponderAuth(1356            noiseSessionStub,1357            identity.privateKeyBytes,1358            identity.publicKeyBytes,1359            transport.send,1360            transport.receive,1361          );1362          const initiatorHex = noiseBytesToHex(initiatorPublicKey);1363          const paired = await getPairedDevices();1364          if (!paired.some(d => d.x25519PublicKey === initiatorHex)) {1365            await transport.close();1366            return { ok: false, error: "sync_rejected_unpaired_initiator" };1367          }1368        } catch (err) {1369          await transport.close();1370          return { ok: false, error: `sync_auth_failed: ${String(err)}` };1371        }13721373        const result = await runBlobSyncSession('responder', transport, buildSyncDeps());1374        if (result.applied) {1375          await publishInMemoryVault(vault.getEntries());1376        }1377        return { ok: true, data: result };1378      }1379      // Android: returns the phone's WiFi IP address.1380      case "GET_LOCAL_IP": {1381        if (!isNativePlatform()) {1382          return { ok: false, error: "android_only" };1383        }1384        const { ip } = (await syncBridge()?.getLocalIp?.()) ?? { ip: "" };1385        return { ok: true, data: { ip } };1386      }1387      case "GET_IDENTITY_SUGGESTIONS": {1388        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1389        const entries = vault.getEntries();1390        const suggestions = buildIdentitySuggestions(entries);1391        return { ok: true, data: { suggestions } };1392      }1393      case "POPULATE_INLINE_VAULT": {1394        if (!isNativePlatform()) return { ok: false };1395        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1396        const entries = vault.getEntries();1397        await publishInMemoryVault(entries);1398        return { ok: true };1399      }1400      case "ML_INIT":1401        return { ok: true };14021403      case "ML_PREDICT_BATCH": {1404        const { featuresArray } = msg.payload as { featuresArray: MLFieldFeatures[] };1405        return { ok: true, data: mlPredictBatch(featuresArray) };1406      }14071408      default:1409        return { ok: false, error: "unknown message type" };1410    }1411  } catch (err) {1412    return {1413      ok: false,1414      error: err instanceof Error ? err.message : "operation failed",1415    };1416  }1417}14181419// --- Mobile platform helpers ---14201421// Android: populates the in-memory vault used by PeachAutofillService.1422async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1423  const plugin = nativePlugin<{1424    setEntries?: (args: {1425      entries: Array<{1426        id: string;1427        title: string;1428        username: string;1429        email: string;1430        password: string;1431        url: string;1432        totp: string;1433        additionalUrls: string[];1434      }>;1435    }) => Promise<void>;1436  }>("InMemoryVaultPlugin");1437  if (!plugin?.setEntries) return;1438  await plugin.setEntries({1439    entries: entries.map((e) => ({1440      id: e.id,1441      title: e.title ?? "",1442      username: e.username ?? "",1443      email: (e as VaultEntry & { email?: string }).email ?? "",1444      password: e.password ?? "",1445      url: e.url ?? "",1446      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1447      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1448    })),1449  });1450}14511452// Android: clear the autofill in-memory store on lock.1453async function clearInMemoryVault(): Promise<void> {1454  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1455  if (!plugin?.clearEntries) return;1456  await plugin.clearEntries();1457}14581459interface SyncBridge {1460  ensureServerRunning?: () => void;1461  startPairingSession?: (args: { token: string }) => void;1462  getLocalIp?: () => Promise<{ ip: string }>;1463  sendToConnection?: (args: { connectionId: string; data: string }) => Promise<void>;1464  addListener?: (event: string, handler: (data: Record<string, string>) => void) => void;1465}14661467// Resolve the Capacitor SyncPlugin at call time — module-load resolution1468// races with Capacitor's plugin registration on the Android WebView.1469function syncBridge(): SyncBridge | null {1470  return nativePlugin<SyncBridge>("SyncPlugin");1471}14721473// Build a SyncTransport for the Android responder path — the phone's WS server1474// already has an open connection from the desktop. We send back via1475// SyncPlugin.sendToConnection and receive via the peach:sync-frame queue.1476const androidSyncFrameQueues = new Map<string, Array<(frame: string) => void>>();14771478export function deliverAndroidSyncFrame(connectionId: string, frame: string): void {1479  const queue = androidSyncFrameQueues.get(connectionId);1480  if (queue?.length) queue.shift()!(frame);1481}14821483function createAndroidResponderTransport(connectionId: string) {1484  const pendingReceivers: Array<(frame: string) => void> = [];1485  androidSyncFrameQueues.set(connectionId, pendingReceivers);14861487  return {1488    send: async (data: Uint8Array) => {1489      await syncBridge()?.sendToConnection?.({ connectionId, data: bytesToBase64(data) });1490    },1491    receive: (): Promise<Uint8Array> => new Promise((res) => {1492      pendingReceivers.push((frame) => {1493        res(frame ? base64ToBytes(frame) : new Uint8Array(0));1494      });1495    }),1496    close: async () => {1497      androidSyncFrameQueues.delete(connectionId);1498    },1499  };1500}15011502// Returns username use-counts from the vault, sorted by frequency. Each row1503// also carries the entry's email so the popup can suggest the email/username1504// pair the user has actually used together.1505function buildIdentitySuggestions(1506  entries: VaultEntry[],1507): Array<{ email: string; username: string; count: number }> {1508  const usernameCounts = new Map<string, number>();1509  const usernameEmail = new Map<string, string>();1510  for (const entry of entries) {1511    const username = entry.username ?? "";1512    const email = (entry as VaultEntry & { email?: string }).email ?? "";1513    if (!username && !email) continue;1514    const key = username || email;1515    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1516    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1517  }1518  return Array.from(usernameCounts.entries())1519    .sort((a, b) => b[1] - a[1])1520    .map(([username, count]) => ({1521      email: usernameEmail.get(username) ?? "",1522      username,1523      count,1524    }));1525}15261527/** Notify all content scripts that the vault just became available. */1528function broadcastToContentScripts(message: { type: string }): void {1529  if (!chrome.tabs?.query) return;1530  chrome.tabs.query({}, (tabs) => {1531    for (const tab of tabs) {1532      if (tab.id !== undefined) {1533        chrome.tabs.sendMessage(tab.id, message).catch(() => {1534          // Tab may not have a content script — silently ignore1535        });1536      }1537    }1538  });1539}15401541function shouldRefreshAutoLock(type: MessageType): boolean {1542  return (1543    type !== "HAS_VAULT" &&1544    type !== "IS_UNLOCKED" &&1545    type !== "GET_VAULT_STATUS" &&1546    type !== "LOCK" &&1547    type !== "UPDATE_SETTINGS" &&1548    type !== "GET_PENDING_PASSKEY" &&1549    type !== "GET_PASSKEY_PROVIDER_STATE" &&1550    type !== "DECLINE_CARD_SAVE" &&1551    type !== "IS_CARD_DECLINED" &&1552    type !== "SUBMIT_FEEDBACK"1553  );1554}15551556function isAllowedCanaryWebhookUrl(value: string): boolean {1557  try {1558    const url = new URL(value);1559    if (url.protocol !== "https:") return false;15601561    const hostname = url.hostname.toLowerCase();1562    if (1563      hostname === "localhost" ||1564      hostname.endsWith(".localhost") ||1565      isPrivateIpv4(hostname) ||1566      isPrivateIpv6(hostname)1567    ) {1568      return false;1569    }15701571    return true;1572  } catch {1573    return false;1574  }1575}15761577function isPrivateIpv4(hostname: string): boolean {1578  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1579    return true;1580  }15811582  const octets = hostname.split(".").map((part) => Number(part));1583  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1584    return false;1585  }15861587  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1588}15891590function isPrivateIpv6(hostname: string): boolean {1591  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1592  return (1593    normalized === "::1" ||1594    normalized.startsWith("fc") ||1595    normalized.startsWith("fd") ||1596    normalized.startsWith("fe80:")1597  );1598}