messages.ts

57.7 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 { getLocalSubnet, discoverDevice, scanForPairingPhone } from "../shared/local-network";79import { predictBatch as mlPredictBatch } from "./ml";80import type { MLFieldFeatures } from "../shared/ml";81import { base64ToBytes, bytesToBase64 } from "../shared/sync-wire";8283/**84 * The single Pro gate. Every gated handler calls this first; the broadcast85 * lets the popup react (navigate to the License section, highlight the86 * relevant feature). Background never touches the popup view directly —87 * the popup owns navigation. See Projects.md "Pro gate rule".88 */89async function requirePro(90  feature: ProFeature,91  trigger: "user" | "background" = "user"92): Promise<{ allowed: boolean }> {93  if (await isProUser()) return { allowed: true };9495  if (trigger === "user") {96    // User deliberately triggered this feature — redirect the popup immediately.97    chrome.runtime98      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })99      .catch(() => {100        // Popup may be closed — the gate signal is best-effort.101      });102  } else {103    // Background trigger (e.g. passive sync initiation) — no popup is open.104    // Queue a notice so the next popup open shows a soft banner instead of105    // silently failing.106    if (chrome.storage.session) {107      chrome.storage.session108        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })109        .catch(() => {});110    }111  }112113  return { allowed: false };114}115116// ---------------------------------------------------------------------------117// Local device name. Peers see this string in PAIR_REQUEST / PAIR_ACCEPT and118// next to the device in their paired-devices list. Default to a platform-aware119// fallback when the user hasn't set one explicitly.120const DEVICE_NAME_KEY = "peach_device_name";121122async function getLocalDeviceName(): Promise<string> {123  try {124    const stored = await chrome.storage.local.get(DEVICE_NAME_KEY);125    const value = (stored as Record<string, string | undefined>)[DEVICE_NAME_KEY];126    if (typeof value === "string" && value.trim()) return value.trim();127  } catch {128    // fall through to default129  }130  return "Peach";131}132133// ---------------------------------------------------------------------------134// 6-digit code pairing.135136const PAIRING_TOKEN_TTL_MS = 5 * 60 * 1000;137138139function generateSixDigitToken(): string {140  // crypto.getRandomValues, not Math.random — the token is the only secret141  // protecting the pairing window from a same-LAN attacker. 6 decimal digits142  // is 1 in 1,000,000; combined with a 5-minute TTL and pairing-mode gating143  // on the responder this is the right tradeoff between UX and security.144  const buf = new Uint32Array(1);145  crypto.getRandomValues(buf);146  const value = buf[0] % 1_000_000;147  return value.toString().padStart(6, "0");148}149150// ---------------------------------------------------------------------------151// Peer discovery glue (Phase 7 popup pairing flow).152153const PRIVATE_IPV4_RANGES = [154  { prefix: "10." },155  { prefix: "127." },156  { prefix: "169.254." },157  { prefix: "192.168." },158];159160// Empty disables network submission while the UI continues to function as a161// no-op (the handler returns ok:true without calling fetch). When set, the162// URL is validated by `isAllowedCanaryWebhookUrl` before any request, so the163// same private-IP/HTTPS rules that gate canary webhooks apply here.164const FEEDBACK_ENDPOINT = "";165166// ---------------------------------------------------------------------------167// Sync helpers168// ---------------------------------------------------------------------------169170function buildSyncDeps(): SyncDeps {171  return {172    isVaultUnlocked: () => vault.isUnlocked(),173    getVaultBlobForSync: async () => {174      const base = await vault.getVaultBlobForSync();175      if (!base) return null;176      const paired = await getPairedDevices();177      return {178        ...base,179        devices: paired180          .filter(d => d.x25519PublicKey)181          .map(d => ({182            publicKeyHex: d.x25519PublicKey,183            deviceName: d.displayName,184            pairedAt: d.pairedAt,185          })),186      };187    },188    applyIncomingVault: async (blob, ts, license, devices) => {189      const applied = await vault.applyIncomingVault(blob, ts, license);190      if (devices?.length) await mergeDeviceRegistry(devices);191      if (applied) await vault.reloadEntriesAfterSync();192      return applied;193    },194  };195}196197async function doVaultSync(ip: string, publicKeyHex: string): Promise<SyncResult> {198  try {199    const transport = await createWebSocketSyncTransport(`ws://${ip}:44100`, publicKeyHex);200    return await runBlobSyncSession('initiator', transport, buildSyncDeps());201  } catch (err) {202    return { status: 'errored', applied: false, error: String(err) };203  }204}205206async function mergeDeviceRegistry(incoming: SyncableDevice[]): Promise<void> {207  const existing = await getPairedDevices();208  const existingKeys = new Set(existing.map(d => d.x25519PublicKey));209  for (const device of incoming) {210    if (!existingKeys.has(device.publicKeyHex)) {211      await addPairedDevice({212        deviceId: device.publicKeyHex,213        displayName: device.deviceName,214        x25519PublicKey: device.publicKeyHex,215        pairedAt: device.pairedAt,216        lastSeenAt: 0,217        lastKnownIp: '',218      }).catch(() => {});219    }220  }221}222223// Background pairing scan — runs after START_PAIRING_SERVER fires on desktop.224// Scans the local subnet for a phone that has accepted the pairing token,225// stores it, runs the initial vault exchange, then notifies the popup.226async function runPairingSubnetScan(token: string): Promise<void> {227  const subnet = await getLocalSubnet();228  if (!subnet) return;229230  const found = await scanForPairingPhone(subnet, token);231  if (!found) return;232233  const { ip, publicKeyHex } = found;234235  try {236    await addPairedDevice({237      deviceId: publicKeyHex,238      displayName: 'Peach',239      x25519PublicKey: publicKeyHex,240      pairedAt: Date.now(),241      lastSeenAt: Date.now(),242      lastKnownIp: ip,243    });244  } catch {245    // Already paired — update IP246    await updatePairedDevice(publicKeyHex, { lastKnownIp: ip, lastSeenAt: Date.now() });247  }248249  // Immediate vault exchange — the free one-time transfer250  await doVaultSync(ip, publicKeyHex);251252  chrome.runtime.sendMessage({253    type: 'PAIRING_COMPLETED',254    payload: { deviceName: 'Peach', publicKeyHex, deviceIp: ip },255  }).catch(() => {});256}257258export function setupMessageHandler(): void {259  chrome.runtime.onMessage.addListener(260    (msg: unknown, sender, sendResponse) => {261      if (!isMessage(msg)) {262        sendResponse({ ok: false, error: "invalid message" });263        return true;264      }265      handleMessage(msg, sender)266        .then(sendResponse)267        .catch((err) =>268          sendResponse({269            ok: false,270            error: err instanceof Error ? err.message : String(err),271          })272        );273      return true;274    }275  );276277  // Android: the chrome shim queues sendMessage calls until this handler is278  // registered. Without this hookup, every message hangs on Capacitor builds.279  // eslint-disable-next-line @typescript-eslint/no-explicit-any280  const reg = (globalThis as any).__peachRegisterMessageHandler;281  if (typeof reg === "function") {282    reg(async (m: unknown) => {283      if (!isMessage(m)) return { ok: false, error: "invalid message" };284      try {285        return await handleMessage(m);286      } catch (err) {287        return {288          ok: false,289          error: err instanceof Error ? err.message : String(err),290        };291      }292    });293  }294295  // Android: subscribe to SyncPlugin events.296  if (isNativePlatform()) {297    const syncPlug = nativePlugin<{298      addListener: (299        event: string,300        handler: (data: Record<string, string>) => void301      ) => void;302    }>("SyncPlugin");303304    // Pairing probe answered — store the paired device (desktop, no IP needed305    // since the desktop never acts as a WS server).306    syncPlug?.addListener?.("peach:pair-probe-answered", (data) => {307      const deviceName = data.deviceName ?? "Peach";308      const publicKeyHex = data.publicKeyHex ?? "";309      void (async () => {310        const { addPairedDevice, setHasPaired: setPaired } = await import("./sync-storage");311        await addPairedDevice({312          deviceId: publicKeyHex || (data.connectionId ?? "unknown"),313          displayName: deviceName,314          x25519PublicKey: publicKeyHex,315          pairedAt: Date.now(),316          lastSeenAt: Date.now(),317        }).catch(() => {});318        await setPaired();319        chrome.runtime.sendMessage({320          type: "PAIRING_COMPLETED",321          payload: { deviceName },322        }).catch(() => {});323      })();324    });325326    // Sync frame received — route to the waiting responder session.327    syncPlug?.addListener?.("peach:sync-frame", (data) => {328      const { connectionId, frame } = data;329      if (connectionId && frame) deliverAndroidSyncFrame(connectionId, frame);330    });331332    // Sync session started (SYNC_HELLO received by SyncPlugin) — dispatch as333    // a background message so SYNC_SESSION_STARTED handler runs the responder.334    syncPlug?.addListener?.("peach:sync-session-started", (data) => {335      const { connectionId } = data;336      if (!connectionId) return;337      void handleMessage({ type: "SYNC_SESSION_STARTED", payload: { connectionId } });338    });339  }340}341342function isMessage(m: unknown): m is Message {343  return typeof m === "object" && m !== null && "type" in m;344}345346export async function handleMessage(347  msg: Message,348  sender: Partial<chrome.runtime.MessageSender> = {}349): Promise<MessageResponse> {350  try {351    // Validate sender — only allow messages from our extension pages/scripts.352    // `sender.id` is undefined for messages originating from extension UI353    // (popup/options), which is legitimate; reject only when it is defined354    // and does not match our extension id.355    if (356      sender.id !== undefined &&357      sender.id !== chrome.runtime.id358    ) {359      return { ok: false, error: "invalid sender" };360    }361362    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {363      touchAutoLock();364    }365366    switch (msg.type) {367      case "CREATE_VAULT": {368        const { password } = msg.payload as { password: string };369        await vault.createVault(password);370        await setupAutoLock();371        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });372        onVaultUnlocked();373        return { ok: true };374      }375      case "UNLOCK": {376        const { password } = msg.payload as { password: string };377        const ok = await vault.unlock(password);378        if (ok) {379          await setupAutoLock();380          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });381          onVaultUnlocked();382          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());383        }384        return { ok };385      }386      case "VALIDATE_RECOVERY_WORDS": {387        const { words } = msg.payload as { words: string[] };388        const invalid = findInvalidWords(words);389        return { ok: true, data: { valid: invalid.length === 0, invalid } };390      }391      case "GET_RECOVERY_WORDS": {392        // Must be unlocked and have recovery set up (vault must be v2.12+).393        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };394        try {395          const words = await vault.getRecoveryWords();396          return { ok: true, data: words };397        } catch (e) {398          // pre-v2.12 vault that hasn't migrated399          return { ok: false, error: "recovery_not_setup" };400        }401      }402      case "RECOVER_WITH_WORDS": {403        // User has lost their password but has their 12 recovery words.404        // We: (1) validate the words, (2) re-encrypt vault with new password.405        const { words, newPassword } = msg.payload as {406          words: string[];407          newPassword: string;408        };409        const stored = await vault.loadSlotA();410        if (!stored) return { ok: false, error: "no vault" };411        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {412          return { ok: false, error: "recovery_not_setup" };413        }414        // Unwrap the root key from the recovery escrow.415        try {416          await vault.unwrapRootKeyForRecovery(417            stored.recovery_wrapped_root_key,418            stored.recovery_nonce ?? "",419            stored.recovery_tag ?? "",420            stored.recovery_salt,421            words422          );423        } catch {424          return { ok: false, error: "invalid_recovery_words" };425        }426        // Re-key: derive fresh salt + key from new password.427        const newSalt = vault.generateSalt();428        const newKey = await vault.deriveKey(newPassword, newSalt);429        // Re-wrap root key under the new password's derived key so the same430        // recovery words continue to work after the password change.431        await vault.rewrapRootKeyForPassword(newKey, newSalt);432        // Re-encrypt vault entries with the new key.433        await vault.changePasswordWithNewKey(newSalt, newKey);434        await setupAutoLock();435        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });436        return { ok: true };437      }438      case "LOCK":439        vault.lock();440        if (isNativePlatform()) await clearInMemoryVault();441        return { ok: true };442      case "IS_UNLOCKED":443        return { ok: true, data: vault.isUnlocked() };444      case "GET_VAULT_STATUS":445        return { ok: true, unlocked: vault.isUnlocked() };446      case "HAS_VAULT":447        return { ok: true, data: await vault.hasVault() };448      case "GET_ENTRIES":449        return { ok: true, data: vault.getEntries() };450      case "ADD_ENTRY": {451        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };452        const entry = await vault.addEntry(msg.payload as any);453        return { ok: true, data: entry };454      }455      case "BATCH_ADD_ENTRIES": {456        const { entries } = msg.payload as { entries: any[] };457        const added = await vault.batchAddEntries(entries);458        return { ok: true, data: added };459      }460      case "RESTORE_ENTRIES": {461        const { entries, mode, settings } = msg.payload as {462          entries: any[];463          mode: "replace" | "merge";464          settings?: vault.VaultSettings;465        };466        const summary = await vault.restoreEntries(entries, mode);467        if (settings && typeof settings === "object") {468          await vault.updateSettings(settings);469        }470        return { ok: true, data: summary };471      }472      case "CLEAR_VAULT_ENTRIES": {473        await vault.clearVaultEntries("REPLACE_ALL");474        return { ok: true };475      }476      case "GET_VAULT_HISTORY": {477        const snapshots = await vault.getVaultHistory();478        return { ok: true, data: snapshots };479      }480      case "RESTORE_VAULT_SNAPSHOT": {481        const { snapshotId } = msg.payload as { snapshotId: string };482        const result = await vault.restoreVaultSnapshot(snapshotId);483        if (!result.ok) return { ok: false, error: result.error };484        broadcastToContentScripts({ type: "VAULT_LOCKED" });485        return { ok: true };486      }487      case "COUNT_DUPLICATES": {488        return { ok: true, data: vault.countDuplicates() };489      }490      case "DEDUPLICATE_ENTRIES": {491        const removed = await vault.deduplicateEntries();492        return { ok: true, data: removed };493      }494      case "UPDATE_ENTRY": {495        const { id, patch } = msg.payload as any;496        await vault.updateEntry(id, patch);497        return { ok: true };498      }499      case "ADD_ADDITIONAL_URL": {500        const { id, url } = msg.payload as { id: string; url: string };501        const trimmed = typeof url === "string" ? url.trim() : "";502        if (!trimmed) return { ok: false, error: "url required" };503        const existing = vault.getEntryById(id);504        if (!existing) return { ok: false, error: "entry not found" };505        if (existing.type !== "login") return { ok: false, error: "login entries only" };506        const merged = [...(existing.additionalUrls ?? []), trimmed];507        await vault.updateEntry(id, { additionalUrls: merged });508        return { ok: true };509      }510      case "DELETE_ENTRY": {511        const { id } = msg.payload as { id: string };512        await vault.deleteEntry(id);513        return { ok: true };514      }515      case "GET_DELETED_ENTRIES":516        return { ok: true, data: vault.getDeletedEntries() };517      case "RESTORE_ENTRY": {518        const { id } = msg.payload as { id: string };519        await vault.restoreEntry(id);520        return { ok: true };521      }522      case "PURGE_ENTRY": {523        const { id } = msg.payload as { id: string };524        await vault.purgeEntry(id);525        return { ok: true };526      }527      case "PURGE_EXPIRED_TRASH": {528        const { retentionMs } = msg.payload as { retentionMs: number };529        const purged = await vault.purgeExpiredTrash(retentionMs);530        return { ok: true, data: purged };531      }532      case "SAVE_NOTE": {533        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };534        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };535        const now = Date.now();536        if (id) {537          const existing = vault.getEntryById(id);538          if (!existing) return { ok: false, error: "not_found" };539          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });540          return { ok: true, data: vault.getEntryById(id) };541        } else {542          const entry = await vault.addEntry({543            type: "note",544            title: title || "Untitled",545            notes: body,546            createdAt: now,547            modifiedAt: now,548          } as any);549          return { ok: true, data: entry };550        }551      }552      case "DELETE_NOTE": {553        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };554        const { id } = msg.payload as { id: string };555        await vault.deleteEntry(id);556        return { ok: true };557      }558      case "GET_NOTES": {559        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };560        const notes = vault.getEntries().filter(561          (e) => e.type === "note" && !e.deletedAt562        );563        return { ok: true, data: notes } as MessageResponse;564      }565      case "SEARCH_VAULT": {566        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };567        const { query } = msg.payload as { query: string };568        const q = query.toLowerCase();569        const searchResults = vault.getEntries().filter(570          (e) =>571            !e.deletedAt &&572            (e.title.toLowerCase().includes(q) ||573              e.notes?.toLowerCase().includes(q) ||574              e.username?.toLowerCase().includes(q))575        );576        return { ok: true, data: searchResults } as MessageResponse;577      }578      case "PAIRING_COMPLETED": {579        const { deviceName, publicKeyHex, deviceIp } = (msg.payload ?? {}) as {580          deviceName?: string;581          publicKeyHex?: string;582          deviceIp?: string;583        };584        if (!publicKeyHex) return { ok: false, error: "publicKeyHex required" };585        const { setHasPaired: setPaired } = await import("./sync-storage");586        await setPaired();587        try {588          await addPairedDevice({589            deviceId: publicKeyHex,590            displayName: deviceName ?? "Unknown",591            x25519PublicKey: publicKeyHex,592            pairedAt: Date.now(),593            lastSeenAt: Date.now(),594            lastKnownIp: deviceIp,595          });596        } catch {597          // Already paired — update IP if provided598          if (deviceIp) {599            await updatePairedDevice(publicKeyHex, { lastKnownIp: deviceIp, lastSeenAt: Date.now() });600          }601        }602        return { ok: true };603      }604      case "AUTOFILL_QUERY": {605        if (!vault.isUnlocked()) {606          return { ok: false, error: "VAULT_LOCKED" };607        }608        const { domain, includeAll, kind } = msg.payload as {609          domain: string;610          includeAll?: boolean;611          kind?: "login" | "card";612        };613        // kind="card": return saved cards as compact summaries for the614        // inline card silver platter. Cards are not domain-scoped — every615        // saved card is a candidate on every checkout page — so domain is616        // ignored when kind === "card".617        if (kind === "card") {618          const cards = vault.getEntries().filter((e) => e.type === "card");619          return {620            ok: true,621            data: cards.map((e) => ({622              id: e.id,623              title: e.cardNickname || e.title,624              cardholderName: e.cardholderName,625              last4: e.last4,626              expMonth: e.expMonth,627              expYear: e.expYear,628              network: e.network,629            })),630          };631        }632        // The inline selector fills username+password into a form. Passkey-633        // only entries have no password to fill; sign-in for those goes634        // through the WebAuthn path instead. Filter them out everywhere so635        // the user doesn't see four "GitHub" rows that mostly do nothing.636        // Notes and cards never belonged here either.637        const matches = (638          includeAll639            ? vault640                .getEntries()641                .filter((entry) => entry.type !== "note" && entry.type !== "card")642            : vault.queryDomain(domain)643        ).filter((entry) => !isPasskeyOnly(entry));644        return {645          ok: true,646          data: matches.map((e) =>647            includeAll648              ? {649                  id: e.id,650                  title: e.title,651                  hasPasskey: e.passkey !== undefined,652                }653              : {654                  id: e.id,655                  title: e.title,656                  username: e.username,657                  email: e.email,658                  url: e.url,659                  hasTotp: Boolean(e.totp),660                  hasPasskey: e.passkey !== undefined,661                }662          ),663        };664      }665      case "GET_ENTRY_FOR_FILL": {666        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };667        const { id } = msg.payload as { id: string };668        const entry = vault.getEntryById(id);669        if (!entry) return { ok: false, error: "entry not found" };670        // Passkey-only entries (passkey credential, no password) cannot be671        // filled into a form — sign-in goes through the WebAuthn path. A672        // login that ALSO has a passkey is still fillable for its password.673        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey not fillable" };674        // Strip the passkey credential from the response — content scripts675        // never need the private key, and there's no reason to expose the676        // public credential metadata over the boundary either.677        const { passkey: _strippedPasskey, ...safeEntry } = entry;678        return { ok: true, data: safeEntry };679      }680      case "COPY": {681        const { text, label, alreadyWritten } = msg.payload as {682          text: string;683          label: string;684          alreadyWritten?: boolean;685        };686        await copyToClipboard(text, label, Boolean(alreadyWritten));687        return { ok: true };688      }689      case "CHECK_ALL_BREACHES": {690        const allEntries = vault.getEntries();691        const results: Record<string, number> = {};692        for (const entry of allEntries) {693          if (entry.type === "note") continue;694          if (!entry.password) continue;695          results[entry.id] = await vault.checkBreach(entry.password);696          // Small delay — be a good citizen to the HIBP API697          await new Promise((r) => setTimeout(r, 200));698        }699        // Persist any non-zero counts back to entries700        for (const [id, count] of Object.entries(results)) {701          const entry = vault.getEntryById(id);702          if (entry && (entry.breach ?? 0) !== count) {703            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });704          }705        }706        return { ok: true, data: results };707      }708      case "GET_SETTINGS":709        return { ok: true, data: await vault.ensureSettingsLoaded() };710      case "UPDATE_SETTINGS": {711        const patch = msg.payload as Record<string, unknown>;712        await vault.updateSettings(patch as any);713        if (typeof patch.autoLockMinutes === "number") {714          await setupAutoLock();715          if (vault.isUnlocked()) touchAutoLock();716        }717        return { ok: true };718      }719      case "GET_PENDING_PASSKEY":720        return { ok: true, data: await getPendingPasskeyRequest() };721      case "APPROVE_PASSKEY": {722        const { requestId } = msg.payload as { requestId: number };723        await resolvePendingPasskeyRequest(requestId, true);724        return { ok: true };725      }726      case "DENY_PASSKEY": {727        const { requestId } = msg.payload as { requestId: number };728        await resolvePendingPasskeyRequest(requestId, false);729        return { ok: true };730      }731      case "GET_PASSKEY_PROVIDER_STATE":732        return { ok: true, data: await getPasskeyProviderState() };733      case "SET_PASSKEY_PROVIDER_ENABLED": {734        const { enabled } = msg.payload as { enabled: boolean };735        // Disabling is always free; gating fires only when a free user is736        // trying to turn passkey interception on.737        if (enabled) {738          const gate = await requirePro("passkeys");739          if (!gate.allowed) return { ok: false, error: "pro_required" };740        }741        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };742      }743      case "FIRE_CANARY_PING": {744        const { webhookUrl, entryTitle, trigger } = msg.payload as {745          webhookUrl: string;746          entryTitle: string;747          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";748        };749        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {750          return { ok: false, error: "invalid webhook url" };751        }752        const body = JSON.stringify({753          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",754          entry: entryTitle,755          trigger,756          timestamp: new Date().toISOString(),757          source: "peach-extension",758        });759        if (trigger === "test") {760          // Permitted outbound fetch: user-configured canary alert endpoint761          // (validated by isAllowedCanaryWebhookUrl above). This is the762          // only non-HIBP outbound call in the extension — see763          // Projects.md §3.7. Test pings are awaited so the UI can show764          // success/failure.765          try {766            const res = await fetch(webhookUrl, {767              method: "POST",768              headers: { "Content-Type": "application/json" },769              body,770            });771            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };772          } catch (err) {773            return { ok: false, error: err instanceof Error ? err.message : "network error" };774          }775        }776        // Non-test triggers are fire-and-forget777        fetch(webhookUrl, {778          method: "POST",779          headers: { "Content-Type": "application/json" },780          body,781        }).catch(() => {});782        return { ok: true };783      }784      case "ACTIVATE_LICENSE": {785        const { key } = msg.payload as { key: string };786        const licenseInfo = await activateLicense(key);787        return { ok: true, data: licenseInfo };788      }789      case "GET_LICENSE": {790        const licenseInfo = await getLicenseInfo();791        return { ok: true, data: licenseInfo };792      }793      case "GET_LICENSE_KEY": {794        const key = await getLicenseKey();795        return { ok: true, data: key };796      }797      case "DEACTIVATE_LICENSE": {798        await deactivateLicense();799        return { ok: true };800      }801      case "SHOULD_PLAY_CELEBRATION": {802        const should = await shouldPlayCelebration();803        return { ok: true, data: should };804      }805      case "MARK_CELEBRATION_PLAYED": {806        await markCelebrationPlayed();807        return { ok: true };808      }809      case "GET_CODEX_VAULT_DATA": {810        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the811        // popup navigates to the License section without further coordination.812        const gate = await requirePro("codex");813        if (!gate.allowed) return { ok: false, error: "pro_required" };814        return await handleGetCodexVaultData();815      }816      case "ESTIMATE_CODEX_PAGES": {817        const gate = await requirePro("codex");818        if (!gate.allowed) return { ok: false, error: "pro_required" };819        return await handleEstimateCodexPages();820      }821      case "RESTORE_FROM_CODEX": {822        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still823        // be able to restore a vault that was printed by a Pro user.824        // DO NOT add a Pro gate here.825        const payload = msg.payload as CodexRestorePayload;826        return await handleRestoreFromCodex(payload);827      }828      case "OPEN_PRO_GATE": {829        // Content script requests: open popup and navigate to License section.830        const { feature } = (msg.payload ?? {}) as { feature?: string };831        if (chrome.storage.session) {832          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });833        }834        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }835        return { ok: true };836      }837      case "GET_IDENTITIES": {838        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };839        return { ok: true, data: vault.getIdentities() };840      }841      case "TOUCH_AUTO_LOCK": {842        // touchAutoLock() is already called by shouldRefreshAutoLock above;843        // this case just gives the popup a typed message to keep the session alive.844        return { ok: true };845      }846      case "GET_ADVANCED_HEALTH_REPORT": {847        const gate = await requirePro("advanced_health");848        if (!gate.allowed) return { ok: false, error: "pro_required" };849        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };850        const report = await buildAdvancedHealthReport(vault.getEntries());851        return { ok: true, data: report };852      }853      case "INITIATE_PASSWORD_CHANGE": {854        const gate = await requirePro("smart_password_change");855        if (!gate.allowed) return { ok: false, error: "pro_required" };856        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };857        const { id } = msg.payload as { id: string };858        const entry = vault.getEntryById(id);859        if (!entry) return { ok: false, error: "entry not found" };860        const url = resolveResetUrl(entry);861        if (!url) return { ok: false, error: "no reset url" };862        try {863          await chrome.tabs.create({ url });864          return { ok: true, data: { url } };865        } catch (err) {866          return {867            ok: false,868            error: err instanceof Error ? err.message : "failed to open tab",869          };870        }871      }872      case "IS_DURESS_ENABLED": {873        const enabled = await vault.isDuressEnabled();874        return { ok: true, data: enabled };875      }876      case "SETUP_DURESS": {877        const { duressPassword } = msg.payload as { duressPassword: string };878        await vault.setupDuress(duressPassword);879        return { ok: true };880      }881      case "DISABLE_DURESS": {882        await vault.disableDuress();883        return { ok: true };884      }885      case "VERIFY_MAIN_PASSWORD": {886        const { password } = msg.payload as { password: string };887        const ok = await vault.verifyMainPassword(password);888        return { ok: true, data: ok };889      }890      case "CHANGE_PASSWORD": {891        const { currentPassword, newPassword } = msg.payload as {892          currentPassword: string;893          newPassword: string;894        };895        const changed = await vault.changePassword(currentPassword, newPassword);896        return changed897          ? { ok: true }898          : { ok: false, error: "incorrect current password" };899      }900      case "GET_SITE_PASSWORD_POLICY": {901        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });902        if (!tab?.id) return { ok: true, data: null };903        try {904          const response = await chrome.tabs.sendMessage(tab.id, {905            type: "GET_SITE_PASSWORD_POLICY",906          });907          return (response as MessageResponse) ?? { ok: true, data: null };908        } catch {909          return { ok: true, data: null };910        }911      }912      case "GET_SYNC_STATE": {913        const pairedDevices = await getPairedDevices();914        const trustedNetworks = await getTrustedNetworks();915        const tailscale = await isOnTailscale();916        const pro = await isProUser();917918        let status: SyncStatus = "offline";919        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {920          if (pairedDevices.length === 0) {921            status = "no_peers";922          } else {923            status = "synced";924          }925        } else {926          status = "not_trusted";927        }928929        const lastSyncRaw = await storageGet("peach_last_sync_at");930        const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN;931        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined;932933        return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } };934      }935      case "GET_PAIRED_DEVICES": {936        const devices = await getPairedDevices();937        return { ok: true, data: { devices } };938      }939      case "GET_SYNC_STATUS": {940        const lastSyncRaw = await storageGet("peach_last_sync_at");941        const lastSyncParsed = lastSyncRaw ? parseInt(lastSyncRaw, 10) : NaN;942        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : null;943        const status: 'up_to_date' | 'never' = lastSyncAt ? 'up_to_date' : 'never';944        return { ok: true, data: { status, lastSyncAt } };945      }946      case "ACCEPT_PAIRING": {947        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.948        return { ok: true };949      }950      case "REMOVE_PAIRED_DEVICE": {951        const { deviceId } = msg.payload as { deviceId: string };952        await removePairedDevice(deviceId);953        return { ok: true };954      }955      case "REMOVE_TRUSTED_NETWORK": {956        const { ssid, bssid, isTailscale } = msg.payload as any;957        const networks = await getTrustedNetworks();958        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 959          (isTailscale ? n.isTailscale : n.ssid === ssid) && 960          (!bssid || n.bssid === bssid)961        );962        if (network) {963          await removeTrustedNetwork(network.addedAt);964        }965        return { ok: true };966      }967      case "MARK_NETWORK_TRUSTED": {968        const network = await getCurrentNetwork();969        await addTrustedNetwork({970          ssid: network.ssid,971          bssid: network.bssid,972          isTailscale: network.isTailscale,973          addedAt: Date.now(),974        });975        return { ok: true };976      }977      case "GET_INCOMING_PAIRING_REQUEST": {978        const request = await getIncomingPairingRequest();979        return { ok: true, data: request };980      }981      case "RESPOND_INCOMING_PAIRING": {982        const { accept } = msg.payload as { accept: boolean };983        const request = await getIncomingPairingRequest();984        if (!request) return { ok: false, error: "no_pending_request" };985        if (Date.now() > request.expiresAt) {986          await clearIncomingPairingRequest();987          return { ok: false, error: "expired" };988        }989        await clearIncomingPairingRequest();990        if (accept) {991          await addPairedDevice({992            deviceId: request.publicKeyHex,993            displayName: request.deviceName,994            x25519PublicKey: request.publicKeyHex,995            pairedAt: Date.now(),996            lastSeenAt: Date.now(),997          });998        }999        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };1000      }1001      case "START_PAIRING_SERVER": {1002        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.1003        const token = generateSixDigitToken();1004        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;1005        await setActivePairingToken({ token, expiresAt });1006        // Fire-and-forget subnet scan — finds the phone after it scans the QR1007        // and calls SCAN_PAIRING_QR to register the token with SyncPlugin.1008        if (!isNativePlatform()) {1009          void runPairingSubnetScan(token);1010        }1011        return { ok: true, data: { token, expiresAt } };1012      }1013      case "STOP_PAIRING_SERVER": {1014        try {1015          await setActivePairingToken(null);1016        } catch { /* best-effort */ }1017        return { ok: true };1018      }1019      case "GET_RECENT_PAIRING": {1020        const recent = await consumeRecentPairing();1021        return { ok: true, data: recent };1022      }1023      case "DEBUG_INJECT_INCOMING_PAIRING": {1024        // Manual E2E rehearsal hook. Inserts a synthetic incoming pairing1025        // request into session storage so Phase 7 banner UX can be exercised1026        // without a live native host. No Pro gate — this is a no-op in1027        // production unless explicitly invoked from a Settings debug action.1028        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {1029          deviceName?: string;1030          publicKeyHex?: string;1031        };1032        if (!deviceName || !publicKeyHex) {1033          return { ok: false, error: "missing_payload" };1034        }1035        const now = Date.now();1036        await setIncomingPairingRequest({1037          deviceName,1038          publicKeyHex,1039          receivedAt: now,1040          expiresAt: now + 60_000,1041        });1042        return { ok: true };1043      }1044      case "RESET_SYNC_IDENTITY": {1045        const gate = await requirePro("sync");1046        if (!gate.allowed) return { ok: false, error: "pro_required" };1047        const devices = await getPairedDevices();1048        for (const device of devices) {1049          await removePairedDevice(device.deviceId);1050        }1051        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };1052      }1053      case "RECORD_MANUAL_SUMMON": {1054        const { domain } = msg.payload as { domain: string };1055        const settings = vault.getSettings();1056        const existing = settings.manualSummonDomains?.[domain];1057        const now = Date.now();1058        await vault.updateSettings({1059          manualSummonDomains: {1060            ...settings.manualSummonDomains,1061            [domain]: {1062              firstSummonedAt: existing?.firstSummonedAt ?? now,1063              summonCount: (existing?.summonCount ?? 0) + 1,1064              lastSummonedAt: now,1065            },1066          },1067        });1068        return { ok: true };1069      }1070      case "DECLINE_CARD_SAVE": {1071        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1072        await vault.declineCardSaveOffer(last4, expMonth, expYear);1073        return { ok: true };1074      }1075      case "IS_CARD_DECLINED": {1076        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1077        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1078        return { ok: true, data: declined };1079      }1080      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1081        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1082          rpId?: string;1083          rpName?: string;1084          userName?: string;1085          userDisplayName?: string;1086        };1087        if (!rpId || !userName) return { ok: false, error: "rpId and userName required" };1088        return await initiateFirefoxPasskeyCreate({1089          rpId,1090          rpName: rpName ?? rpId,1091          userName,1092          userDisplayName,1093        });1094      }10951096      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1097        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1098        if (!payload) return { ok: false, error: "missing payload" };1099        return await completeFirefoxPasskeyCreate(payload);1100      }11011102      case "PASSKEY_OFFER_DECLINE": {1103        const { domain } = (msg.payload ?? {}) as { domain?: string };1104        if (!domain) return { ok: false, error: "domain required" };1105        await recordPasskeyOfferDecline(domain);1106        return { ok: true };1107      }11081109      case "GET_PASSKEY_OFFER_DECLINED": {1110        const { domain } = (msg.payload ?? {}) as { domain?: string };1111        if (!domain) return { ok: false, error: "domain required" };1112        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1113      }11141115      case "PASSKEY_HAS_CREDENTIALS": {1116        const payload = msg.payload as {1117          rpId?: string;1118          allowCredentials?: Array<{ id: string; type?: string }>;1119        } | undefined;1120        if (!payload?.rpId) return { ok: false, error: "rpId required" };1121        return await handlePasskeyHasCredentials({1122          rpId: payload.rpId,1123          allowCredentials: payload.allowCredentials ?? [],1124        });1125      }11261127      case "PASSKEY_CREATE": {1128        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1129        if (!payload?.rpId || !payload?.userName) {1130          return { ok: false, error: "rpId and userName required" };1131        }1132        return await handleFirefoxPasskeyCreate(payload);1133      }11341135      case "PASSKEY_GET": {1136        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1137        if (!payload?.rpId) return { ok: false, error: "rpId required" };1138        return await handleFirefoxPasskeyGet(payload);1139      }11401141      case "PASSKEY_AUTH_RESPONSE": {1142        const { requestId, approved } = (msg.payload ?? {}) as {1143          requestId?: string | number;1144          approved?: boolean;1145        };1146        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1147          return { ok: false, error: 'requestId and approved required' };1148        }1149        await resolvePendingPasskeyRequest(Number(requestId), approved);1150        return { ok: true };1151      }11521153      case "GET_PASSKEY_FOR_DOMAIN": {1154        const { domain } = (msg.payload ?? {}) as { domain?: string };1155        if (!domain) return { ok: false, error: "domain required" };1156        if (!vault.isUnlocked()) return { ok: true, data: null };1157        const match = vault1158          .getEntries()1159          .find((entry) => entry.passkey?.rpId === domain);1160        if (!match || !match.passkey) return { ok: true, data: null };1161        // Slim shape — only the fields State 11 needs. Never expose private1162        // key material, even though this is locked behind isUnlocked.1163        return {1164          ok: true,1165          data: {1166            rpId: match.passkey.rpId,1167            userName: match.passkey.userName,1168            browser: match.passkey.browser,1169          },1170        };1171      }11721173      case "DESTROY_VAULT": {1174        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1175        // storage.local.clear() wipes every Peach key (slots, settings, license,1176        // onboarded flag, history, sync state, declined cards, recall, etc.);1177        // session.clear() wipes pending passkey requests + pro-notice queues.1178        // Caller (Panic.tsx) handles UI navigation back to onboarding.1179        vault.lock();1180        await storageClear();1181        await vault.clearVaultHistory();1182        if (chrome.storage.session) {1183          await chrome.storage.session.clear();1184        }1185        return { ok: true };1186      }11871188      case "SUBMIT_FEEDBACK": {1189        const { category, message, version, browser } = msg.payload as {1190          category: string;1191          message: string;1192          version: string;1193          browser: string;1194        };1195        if (!message.trim()) return { ok: false, error: "message is empty" };1196        if (!FEEDBACK_ENDPOINT) return { ok: true };1197        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1198          return { ok: false, error: "invalid feedback endpoint" };1199        }1200        try {1201          const res = await fetch(FEEDBACK_ENDPOINT, {1202            method: "POST",1203            headers: { "Content-Type": "application/json" },1204            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1205          });1206          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1207        } catch (err) {1208          return { ok: false, error: err instanceof Error ? err.message : "network error" };1209        }1210      }1211      case "TRIGGER_SYNC": {1212        const gate = await requirePro("sync");1213        if (!gate.allowed) return { ok: false, error: "pro_required" };1214        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };12151216        if (isNativePlatform()) {1217          // Phone is the server — ensure it's listening for desktop connections.1218          syncBridge()?.ensureServerRunning?.();1219          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };1220        }12211222        // Desktop: iterate all paired devices and sync with each.1223        const paired = await getPairedDevices();1224        if (!paired.length) return { ok: true, data: { syncedCount: 0, reason: "no_paired_devices" } };12251226        const subnet = await getLocalSubnet();1227        const results: Array<{ device: string } & SyncResult> = [];12281229        for (const device of paired) {1230          if (!device.x25519PublicKey) continue;12311232          let result: SyncResult;12331234          // Fast path — use last known IP1235          if (device.lastKnownIp) {1236            result = await doVaultSync(device.lastKnownIp, device.x25519PublicKey);1237          } else {1238            result = { status: 'errored', applied: false, error: 'no_ip' };1239          }12401241          // Discovery path — scan if fast path failed1242          if (result.status === 'errored' && subnet) {1243            const newIp = await discoverDevice(subnet, device.x25519PublicKey);1244            if (newIp) {1245              await updatePairedDevice(device.x25519PublicKey, { lastKnownIp: newIp });1246              result = await doVaultSync(newIp, device.x25519PublicKey);1247            }1248          }12491250          if (result.status === 'completed') {1251            await updatePairedDevice(device.x25519PublicKey, {1252              lastSeenAt: Date.now(),1253              lastSyncAt: Date.now(),1254            });1255          }12561257          results.push({ device: device.displayName, ...result });1258        }12591260        const syncedCount = results.filter(r => r.status === 'completed').length;1261        if (syncedCount > 0) {1262          await chrome.storage.local.set({ peach_last_sync_at: String(Date.now()) });1263        }1264        return { ok: true, data: { syncedCount, results } };1265      }1266      // Android-only: biometric unlock with pre-derived key.1267      case "UNLOCK_WITH_KEY": {1268        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1269        if (!isNativePlatform()) {1270          return { ok: false, error: "desktop_only_uses_password" };1271        }1272        try {1273          const result = await vault.unlockWithKey(masterKeyHex);1274          if (result.ok) {1275            onVaultUnlocked();1276            await publishInMemoryVault(result.entries);1277          }1278          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1279        } catch {1280          return { ok: false, error: "invalid_key" };1281        }1282      }1283      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1284      case "GET_DERIVED_KEY": {1285        if (!isNativePlatform()) {1286          return { ok: false, error: "android_only" };1287        }1288        if (!vault.isUnlocked()) {1289          return { ok: false, error: "vault_locked" };1290        }1291        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1292      }1293      // Android: scanned a QR containing a desktop pairing token.1294      case "SCAN_PAIRING_QR": {1295        if (!isNativePlatform()) {1296          return { ok: false, error: "android_only" };1297        }1298        const { token } = msg.payload as { token: string };1299        syncBridge()?.startPairingSession?.({ token });1300        return { ok: true };1301      }1302      // Android: desktop opened a sync connection to the phone's WS server.1303      // Run the responder side of the vault exchange.1304      case "SYNC_SESSION_STARTED": {1305        if (!isNativePlatform()) return { ok: false };1306        if (!vault.isUnlocked()) {1307          return { ok: false, error: "vault_locked" };1308        }1309        const { connectionId } = (msg.payload ?? {}) as { connectionId?: string };1310        if (!connectionId) return { ok: false, error: "missing_connection_id" };13111312        const transport = createAndroidResponderTransport(connectionId);1313        const result = await runBlobSyncSession('responder', transport, buildSyncDeps());1314        if (result.applied) {1315          await publishInMemoryVault(vault.getEntries());1316        }1317        return { ok: true, data: result };1318      }1319      // Android: returns the phone's WiFi IP address.1320      case "GET_LOCAL_IP": {1321        if (!isNativePlatform()) {1322          return { ok: false, error: "android_only" };1323        }1324        const { ip } = (await syncBridge()?.getLocalIp?.()) ?? { ip: "" };1325        return { ok: true, data: { ip } };1326      }1327      case "GET_IDENTITY_SUGGESTIONS": {1328        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1329        const entries = vault.getEntries();1330        const suggestions = buildIdentitySuggestions(entries);1331        return { ok: true, data: { suggestions } };1332      }1333      case "POPULATE_INLINE_VAULT": {1334        if (!isNativePlatform()) return { ok: false };1335        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1336        const entries = vault.getEntries();1337        await publishInMemoryVault(entries);1338        return { ok: true };1339      }1340      case "ML_INIT":1341        return { ok: true };13421343      case "ML_PREDICT_BATCH": {1344        const { featuresArray } = msg.payload as { featuresArray: MLFieldFeatures[] };1345        return { ok: true, data: mlPredictBatch(featuresArray) };1346      }13471348      default:1349        return { ok: false, error: "unknown message type" };1350    }1351  } catch (err) {1352    return {1353      ok: false,1354      error: err instanceof Error ? err.message : "operation failed",1355    };1356  }1357}13581359// --- Mobile platform helpers ---13601361// Android: populates the in-memory vault used by PeachAutofillService.1362async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1363  const plugin = nativePlugin<{1364    setEntries?: (args: {1365      entries: Array<{1366        id: string;1367        title: string;1368        username: string;1369        email: string;1370        password: string;1371        url: string;1372        totp: string;1373        additionalUrls: string[];1374      }>;1375    }) => Promise<void>;1376  }>("InMemoryVaultPlugin");1377  if (!plugin?.setEntries) return;1378  await plugin.setEntries({1379    entries: entries.map((e) => ({1380      id: e.id,1381      title: e.title ?? "",1382      username: e.username ?? "",1383      email: (e as VaultEntry & { email?: string }).email ?? "",1384      password: e.password ?? "",1385      url: e.url ?? "",1386      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1387      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1388    })),1389  });1390}13911392// Android: clear the autofill in-memory store on lock.1393async function clearInMemoryVault(): Promise<void> {1394  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1395  if (!plugin?.clearEntries) return;1396  await plugin.clearEntries();1397}13981399interface SyncBridge {1400  ensureServerRunning?: () => void;1401  startPairingSession?: (args: { token: string }) => void;1402  getLocalIp?: () => Promise<{ ip: string }>;1403  sendToConnection?: (args: { connectionId: string; data: string }) => Promise<void>;1404  addListener?: (event: string, handler: (data: Record<string, string>) => void) => void;1405}14061407// Resolve the Capacitor SyncPlugin at call time — module-load resolution1408// races with Capacitor's plugin registration on the Android WebView.1409function syncBridge(): SyncBridge | null {1410  return nativePlugin<SyncBridge>("SyncPlugin");1411}14121413// Build a SyncTransport for the Android responder path — the phone's WS server1414// already has an open connection from the desktop. We send back via1415// SyncPlugin.sendToConnection and receive via the peach:sync-frame queue.1416const androidSyncFrameQueues = new Map<string, Array<(frame: string) => void>>();14171418export function deliverAndroidSyncFrame(connectionId: string, frame: string): void {1419  const queue = androidSyncFrameQueues.get(connectionId);1420  if (queue?.length) queue.shift()!(frame);1421}14221423function createAndroidResponderTransport(connectionId: string) {1424  const pendingReceivers: Array<(frame: string) => void> = [];1425  androidSyncFrameQueues.set(connectionId, pendingReceivers);14261427  return {1428    send: async (data: Uint8Array) => {1429      await syncBridge()?.sendToConnection?.({ connectionId, data: bytesToBase64(data) });1430    },1431    receive: (): Promise<Uint8Array> => new Promise((res) => {1432      pendingReceivers.push((frame) => {1433        res(frame ? base64ToBytes(frame) : new Uint8Array(0));1434      });1435    }),1436    close: async () => {1437      androidSyncFrameQueues.delete(connectionId);1438    },1439  };1440}14411442// Returns username use-counts from the vault, sorted by frequency. Each row1443// also carries the entry's email so the popup can suggest the email/username1444// pair the user has actually used together.1445function buildIdentitySuggestions(1446  entries: VaultEntry[],1447): Array<{ email: string; username: string; count: number }> {1448  const usernameCounts = new Map<string, number>();1449  const usernameEmail = new Map<string, string>();1450  for (const entry of entries) {1451    const username = entry.username ?? "";1452    const email = (entry as VaultEntry & { email?: string }).email ?? "";1453    if (!username && !email) continue;1454    const key = username || email;1455    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1456    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1457  }1458  return Array.from(usernameCounts.entries())1459    .sort((a, b) => b[1] - a[1])1460    .map(([username, count]) => ({1461      email: usernameEmail.get(username) ?? "",1462      username,1463      count,1464    }));1465}14661467/** Notify all content scripts that the vault just became available. */1468function broadcastToContentScripts(message: { type: string }): void {1469  if (!chrome.tabs?.query) return;1470  chrome.tabs.query({}, (tabs) => {1471    for (const tab of tabs) {1472      if (tab.id !== undefined) {1473        chrome.tabs.sendMessage(tab.id, message).catch(() => {1474          // Tab may not have a content script — silently ignore1475        });1476      }1477    }1478  });1479}14801481function shouldRefreshAutoLock(type: MessageType): boolean {1482  return (1483    type !== "HAS_VAULT" &&1484    type !== "IS_UNLOCKED" &&1485    type !== "GET_VAULT_STATUS" &&1486    type !== "LOCK" &&1487    type !== "UPDATE_SETTINGS" &&1488    type !== "GET_PENDING_PASSKEY" &&1489    type !== "GET_PASSKEY_PROVIDER_STATE" &&1490    type !== "DECLINE_CARD_SAVE" &&1491    type !== "IS_CARD_DECLINED" &&1492    type !== "SUBMIT_FEEDBACK"1493  );1494}14951496function isAllowedCanaryWebhookUrl(value: string): boolean {1497  try {1498    const url = new URL(value);1499    if (url.protocol !== "https:") return false;15001501    const hostname = url.hostname.toLowerCase();1502    if (1503      hostname === "localhost" ||1504      hostname.endsWith(".localhost") ||1505      isPrivateIpv4(hostname) ||1506      isPrivateIpv6(hostname)1507    ) {1508      return false;1509    }15101511    return true;1512  } catch {1513    return false;1514  }1515}15161517function isPrivateIpv4(hostname: string): boolean {1518  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1519    return true;1520  }15211522  const octets = hostname.split(".").map((part) => Number(part));1523  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1524    return false;1525  }15261527  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1528}15291530function isPrivateIpv6(hostname: string): boolean {1531  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1532  return (1533    normalized === "::1" ||1534    normalized.startsWith("fc") ||1535    normalized.startsWith("fd") ||1536    normalized.startsWith("fe80:")1537  );1538}