messages.ts

57.6 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard } from "./clipboard";13import { setupAutoLock, touchAutoLock } from "./alarms";14import * as vault from "./vault";15import {16  activateLicense,17  deactivateLicense,18  getLicenseInfo,19  getLicenseKey,20  isProUser,21  markCelebrationPlayed,22  shouldPlayCelebration,23} from "./license";24import {25  cancelFirefoxPasskeyCreate,26  completeFirefoxPasskeyCreate,27  getPasskeyProviderState,28  getPendingPasskeyRequest,29  handleFirefoxPasskeyCreate,30  handleFirefoxPasskeyGet,31  handlePasskeyHasCredentials,32  initiateFirefoxPasskeyCreate,33  isPasskeyOfferDeclined,34  recordPasskeyOfferDecline,35  resolvePendingPasskeyRequest,36  setPasskeyProviderEnabled,37} from "./passkey";38import { buildAdvancedHealthReport, resolveResetUrl } from "./health";39import { storageClear, storageGet } from "../shared/storage";40import { findInvalidWords } from "../shared/recovery-words";41import {42  addPairedDevice,43  addTrustedNetwork,44  clearIncomingPairingRequest,45  getIncomingPairingRequest,46  getPairedDevices,47  getTrustedNetworks,48  removePairedDevice,49  removeTrustedNetwork,50  setIncomingPairingRequest,51  updatePairedDevice,52} from "./sync-storage";53import { getCurrentNetwork, isOnTailscale } from "./sync-network";54import {55  consumeRecentPairing,56  setActivePairingToken,57} from "./pairing-server-state";58import type {59  Message,60  MessageResponse,61  MessageType,62  ProFeature,63  VaultEntry,64} from "../shared/types";65import { isPasskeyOnly } from "../shared/types";66import type { SyncStatus, SyncableDevice } from "../shared/sync-types";67import { isNativePlatform, nativePlugin } from "../shared/native";68import { runBlobSyncSession, type SyncResult } from "./sync-coordinator";69import type { SyncDeps } from "./sync-coordinator";70import { createWebSocketSyncTransport } from "../shared/websocket-sync-transport";71import { getLocalSubnet, discoverDevice, scanForPairingPhone } from "../shared/local-network";72import { base64ToBytes, bytesToBase64 } from "../shared/sync-wire";7374/**75 * The single Pro gate. Every gated handler calls this first; the broadcast76 * lets the popup react (navigate to the License section, highlight the77 * relevant feature). Background never touches the popup view directly —78 * the popup owns navigation. See Projects.md "Pro gate rule".79 */80async function requirePro(81  feature: ProFeature,82  trigger: "user" | "background" = "user"83): Promise<{ allowed: boolean }> {84  if (await isProUser()) return { allowed: true };8586  if (trigger === "user") {87    // User deliberately triggered this feature — redirect the popup immediately.88    chrome.runtime89      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })90      .catch(() => {91        // Popup may be closed — the gate signal is best-effort.92      });93  } else {94    // Background trigger (e.g. passive sync initiation) — no popup is open.95    // Queue a notice so the next popup open shows a soft banner instead of96    // silently failing.97    if (chrome.storage.session) {98      chrome.storage.session99        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })100        .catch(() => {});101    }102  }103104  return { allowed: false };105}106107// ---------------------------------------------------------------------------108// Local device name. Peers see this string in PAIR_REQUEST / PAIR_ACCEPT and109// next to the device in their paired-devices list. Default to a platform-aware110// fallback when the user hasn't set one explicitly.111const DEVICE_NAME_KEY = "peach_device_name";112113async function getLocalDeviceName(): Promise<string> {114  try {115    const stored = await chrome.storage.local.get(DEVICE_NAME_KEY);116    const value = (stored as Record<string, string | undefined>)[DEVICE_NAME_KEY];117    if (typeof value === "string" && value.trim()) return value.trim();118  } catch {119    // fall through to default120  }121  return "Peach";122}123124// ---------------------------------------------------------------------------125// 6-digit code pairing.126127const PAIRING_TOKEN_TTL_MS = 5 * 60 * 1000;128129130function generateSixDigitToken(): string {131  // crypto.getRandomValues, not Math.random — the token is the only secret132  // protecting the pairing window from a same-LAN attacker. 6 decimal digits133  // is 1 in 1,000,000; combined with a 5-minute TTL and pairing-mode gating134  // on the responder this is the right tradeoff between UX and security.135  const buf = new Uint32Array(1);136  crypto.getRandomValues(buf);137  const value = buf[0] % 1_000_000;138  return value.toString().padStart(6, "0");139}140141// ---------------------------------------------------------------------------142// Peer discovery glue (Phase 7 popup pairing flow).143144const PRIVATE_IPV4_RANGES = [145  { prefix: "10." },146  { prefix: "127." },147  { prefix: "169.254." },148  { prefix: "192.168." },149];150151// Empty disables network submission while the UI continues to function as a152// no-op (the handler returns ok:true without calling fetch). When set, the153// URL is validated by `isAllowedCanaryWebhookUrl` before any request, so the154// same private-IP/HTTPS rules that gate canary webhooks apply here.155const FEEDBACK_ENDPOINT = "";156157// ---------------------------------------------------------------------------158// Sync helpers159// ---------------------------------------------------------------------------160161function buildSyncDeps(): SyncDeps {162  return {163    isVaultUnlocked: () => vault.isUnlocked(),164    getVaultBlobForSync: async () => {165      const base = await vault.getVaultBlobForSync();166      if (!base) return null;167      const paired = await getPairedDevices();168      return {169        ...base,170        devices: paired171          .filter(d => d.x25519PublicKey)172          .map(d => ({173            publicKeyHex: d.x25519PublicKey,174            deviceName: d.displayName,175            pairedAt: d.pairedAt,176          })),177      };178    },179    applyIncomingVault: async (blob, ts, license, devices) => {180      const applied = await vault.applyIncomingVault(blob, ts, license);181      if (devices?.length) await mergeDeviceRegistry(devices);182      if (applied) await vault.reloadEntriesAfterSync();183      return applied;184    },185  };186}187188async function doVaultSync(ip: string, publicKeyHex: string): Promise<SyncResult> {189  try {190    const transport = await createWebSocketSyncTransport(`ws://${ip}:44100`, publicKeyHex);191    return await runBlobSyncSession('initiator', transport, buildSyncDeps());192  } catch (err) {193    return { status: 'errored', applied: false, error: String(err) };194  }195}196197async function mergeDeviceRegistry(incoming: SyncableDevice[]): Promise<void> {198  const existing = await getPairedDevices();199  const existingKeys = new Set(existing.map(d => d.x25519PublicKey));200  for (const device of incoming) {201    if (!existingKeys.has(device.publicKeyHex)) {202      await addPairedDevice({203        deviceId: device.publicKeyHex,204        displayName: device.deviceName,205        x25519PublicKey: device.publicKeyHex,206        pairedAt: device.pairedAt,207        lastSeenAt: 0,208        lastKnownIp: '',209      }).catch(() => {});210    }211  }212}213214// Background pairing scan — runs after START_PAIRING_SERVER fires on desktop.215// Scans the local subnet for a phone that has accepted the pairing token,216// stores it, runs the initial vault exchange, then notifies the popup.217async function runPairingSubnetScan(token: string): Promise<void> {218  const subnet = await getLocalSubnet();219  if (!subnet) return;220221  const found = await scanForPairingPhone(subnet, token);222  if (!found) return;223224  const { ip, publicKeyHex } = found;225226  try {227    await addPairedDevice({228      deviceId: publicKeyHex,229      displayName: 'Peach',230      x25519PublicKey: publicKeyHex,231      pairedAt: Date.now(),232      lastSeenAt: Date.now(),233      lastKnownIp: ip,234    });235  } catch {236    // Already paired — update IP237    await updatePairedDevice(publicKeyHex, { lastKnownIp: ip, lastSeenAt: Date.now() });238  }239240  // Immediate vault exchange — the free one-time transfer241  await doVaultSync(ip, publicKeyHex);242243  chrome.runtime.sendMessage({244    type: 'PAIRING_COMPLETED',245    payload: { deviceName: 'Peach', publicKeyHex, deviceIp: ip },246  }).catch(() => {});247}248249export function setupMessageHandler(): void {250  chrome.runtime.onMessage.addListener(251    (msg: unknown, sender, sendResponse) => {252      if (!isMessage(msg)) {253        sendResponse({ ok: false, error: "invalid message" });254        return true;255      }256      handleMessage(msg, sender)257        .then(sendResponse)258        .catch((err) =>259          sendResponse({260            ok: false,261            error: err instanceof Error ? err.message : String(err),262          })263        );264      return true;265    }266  );267268  // Android: the chrome shim queues sendMessage calls until this handler is269  // registered. Without this hookup, every message hangs on Capacitor builds.270  // eslint-disable-next-line @typescript-eslint/no-explicit-any271  const reg = (globalThis as any).__peachRegisterMessageHandler;272  if (typeof reg === "function") {273    reg(async (m: unknown) => {274      if (!isMessage(m)) return { ok: false, error: "invalid message" };275      try {276        return await handleMessage(m);277      } catch (err) {278        return {279          ok: false,280          error: err instanceof Error ? err.message : String(err),281        };282      }283    });284  }285286  // Android: subscribe to SyncPlugin events.287  if (isNativePlatform()) {288    const syncPlug = nativePlugin<{289      addListener: (290        event: string,291        handler: (data: Record<string, string>) => void292      ) => void;293    }>("SyncPlugin");294295    // Pairing probe answered — store the paired device (desktop, no IP needed296    // since the desktop never acts as a WS server).297    syncPlug?.addListener?.("peach:pair-probe-answered", (data) => {298      const deviceName = data.deviceName ?? "Peach";299      const publicKeyHex = data.publicKeyHex ?? "";300      void (async () => {301        const { addPairedDevice, setHasPaired: setPaired } = await import("./sync-storage");302        await addPairedDevice({303          deviceId: publicKeyHex || (data.connectionId ?? "unknown"),304          displayName: deviceName,305          x25519PublicKey: publicKeyHex,306          pairedAt: Date.now(),307          lastSeenAt: Date.now(),308        }).catch(() => {});309        await setPaired();310        chrome.runtime.sendMessage({311          type: "PAIRING_COMPLETED",312          payload: { deviceName },313        }).catch(() => {});314      })();315    });316317    // Sync frame received — route to the waiting responder session.318    syncPlug?.addListener?.("peach:sync-frame", (data) => {319      const { connectionId, frame } = data;320      if (connectionId && frame) deliverAndroidSyncFrame(connectionId, frame);321    });322323    // Sync session started (SYNC_HELLO received by SyncPlugin) — dispatch as324    // a background message so SYNC_SESSION_STARTED handler runs the responder.325    syncPlug?.addListener?.("peach:sync-session-started", (data) => {326      const { connectionId } = data;327      if (!connectionId) return;328      void handleMessage({ type: "SYNC_SESSION_STARTED", payload: { connectionId } });329    });330  }331}332333function isMessage(m: unknown): m is Message {334  return typeof m === "object" && m !== null && "type" in m;335}336337export async function handleMessage(338  msg: Message,339  sender: Partial<chrome.runtime.MessageSender> = {}340): Promise<MessageResponse> {341  try {342    // Validate sender — only allow messages from our extension pages/scripts.343    // `sender.id` is undefined for messages originating from extension UI344    // (popup/options), which is legitimate; reject only when it is defined345    // and does not match our extension id.346    if (347      sender.id !== undefined &&348      sender.id !== chrome.runtime.id349    ) {350      return { ok: false, error: "invalid sender" };351    }352353    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {354      touchAutoLock();355    }356357    switch (msg.type) {358      case "CREATE_VAULT": {359        const { password } = msg.payload as { password: string };360        await vault.createVault(password);361        await setupAutoLock();362        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });363        return { ok: true };364      }365      case "UNLOCK": {366        const { password } = msg.payload as { password: string };367        const ok = await vault.unlock(password);368        if (ok) {369          await setupAutoLock();370          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });371          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());372        }373        return { ok };374      }375      case "VALIDATE_RECOVERY_WORDS": {376        const { words } = msg.payload as { words: string[] };377        const invalid = findInvalidWords(words);378        return { ok: true, data: { valid: invalid.length === 0, invalid } };379      }380      case "GET_RECOVERY_WORDS": {381        // Must be unlocked and have recovery set up (vault must be v2.12+).382        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };383        try {384          const words = await vault.getRecoveryWords();385          return { ok: true, data: words };386        } catch (e) {387          // pre-v2.12 vault that hasn't migrated388          return { ok: false, error: "recovery_not_setup" };389        }390      }391      case "RECOVER_WITH_WORDS": {392        // User has lost their password but has their 12 recovery words.393        // We: (1) validate the words, (2) re-encrypt vault with new password.394        const { words, newPassword } = msg.payload as {395          words: string[];396          newPassword: string;397        };398        const stored = await vault.loadSlotA();399        if (!stored) return { ok: false, error: "no vault" };400        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {401          return { ok: false, error: "recovery_not_setup" };402        }403        // Unwrap the root key from the recovery escrow.404        try {405          await vault.unwrapRootKeyForRecovery(406            stored.recovery_wrapped_root_key,407            stored.recovery_nonce ?? "",408            stored.recovery_tag ?? "",409            stored.recovery_salt,410            words411          );412        } catch {413          return { ok: false, error: "invalid_recovery_words" };414        }415        // Re-key: derive fresh salt + key from new password.416        const newSalt = vault.generateSalt();417        const newKey = await vault.deriveKey(newPassword, newSalt);418        // Re-wrap root key under the new password's derived key so the same419        // recovery words continue to work after the password change.420        await vault.rewrapRootKeyForPassword(newKey, newSalt);421        // Re-encrypt vault entries with the new key.422        await vault.changePasswordWithNewKey(newSalt, newKey);423        await setupAutoLock();424        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });425        return { ok: true };426      }427      case "LOCK":428        vault.lock();429        if (isNativePlatform()) await clearInMemoryVault();430        return { ok: true };431      case "IS_UNLOCKED":432        return { ok: true, data: vault.isUnlocked() };433      case "GET_VAULT_STATUS":434        return { ok: true, unlocked: vault.isUnlocked() };435      case "HAS_VAULT":436        return { ok: true, data: await vault.hasVault() };437      case "GET_ENTRIES":438        return { ok: true, data: vault.getEntries() };439      case "ADD_ENTRY": {440        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };441        const entry = await vault.addEntry(msg.payload as any);442        return { ok: true, data: entry };443      }444      case "BATCH_ADD_ENTRIES": {445        const { entries } = msg.payload as { entries: any[] };446        const added = await vault.batchAddEntries(entries);447        return { ok: true, data: added };448      }449      case "RESTORE_ENTRIES": {450        const { entries, mode, settings } = msg.payload as {451          entries: any[];452          mode: "replace" | "merge";453          settings?: vault.VaultSettings;454        };455        const summary = await vault.restoreEntries(entries, mode);456        if (settings && typeof settings === "object") {457          await vault.updateSettings(settings);458        }459        return { ok: true, data: summary };460      }461      case "CLEAR_VAULT_ENTRIES": {462        await vault.clearVaultEntries("REPLACE_ALL");463        return { ok: true };464      }465      case "GET_VAULT_HISTORY": {466        const snapshots = await vault.getVaultHistory();467        return { ok: true, data: snapshots };468      }469      case "RESTORE_VAULT_SNAPSHOT": {470        const { snapshotId } = msg.payload as { snapshotId: string };471        const result = await vault.restoreVaultSnapshot(snapshotId);472        if (!result.ok) return { ok: false, error: result.error };473        broadcastToContentScripts({ type: "VAULT_LOCKED" });474        return { ok: true };475      }476      case "COUNT_DUPLICATES": {477        return { ok: true, data: vault.countDuplicates() };478      }479      case "DEDUPLICATE_ENTRIES": {480        const removed = await vault.deduplicateEntries();481        return { ok: true, data: removed };482      }483      case "UPDATE_ENTRY": {484        const { id, patch } = msg.payload as any;485        await vault.updateEntry(id, patch);486        return { ok: true };487      }488      case "ADD_ADDITIONAL_URL": {489        const { id, url } = msg.payload as { id: string; url: string };490        const trimmed = typeof url === "string" ? url.trim() : "";491        if (!trimmed) return { ok: false, error: "url required" };492        const existing = vault.getEntryById(id);493        if (!existing) return { ok: false, error: "entry not found" };494        if (existing.type !== "login") return { ok: false, error: "login entries only" };495        const merged = [...(existing.additionalUrls ?? []), trimmed];496        await vault.updateEntry(id, { additionalUrls: merged });497        return { ok: true };498      }499      case "DELETE_ENTRY": {500        const { id } = msg.payload as { id: string };501        await vault.deleteEntry(id);502        return { ok: true };503      }504      case "GET_DELETED_ENTRIES":505        return { ok: true, data: vault.getDeletedEntries() };506      case "RESTORE_ENTRY": {507        const { id } = msg.payload as { id: string };508        await vault.restoreEntry(id);509        return { ok: true };510      }511      case "PURGE_ENTRY": {512        const { id } = msg.payload as { id: string };513        await vault.purgeEntry(id);514        return { ok: true };515      }516      case "PURGE_EXPIRED_TRASH": {517        const { retentionMs } = msg.payload as { retentionMs: number };518        const purged = await vault.purgeExpiredTrash(retentionMs);519        return { ok: true, data: purged };520      }521      case "AUTOFILL_QUERY": {522        if (!vault.isUnlocked()) {523          return { ok: false, error: "VAULT_LOCKED" };524        }525        const { domain, includeAll, kind } = msg.payload as {526          domain: string;527          includeAll?: boolean;528          kind?: "login" | "card";529        };530        // kind="card": return saved cards as compact summaries for the531        // inline card silver platter. Cards are not domain-scoped — every532        // saved card is a candidate on every checkout page — so domain is533        // ignored when kind === "card".534        if (kind === "card") {535          const cards = vault.getEntries().filter((e) => e.type === "card");536          return {537            ok: true,538            data: cards.map((e) => ({539              id: e.id,540              title: e.cardNickname || e.title,541              cardholderName: e.cardholderName,542              last4: e.last4,543              expMonth: e.expMonth,544              expYear: e.expYear,545              network: e.network,546            })),547          };548        }549        // The inline selector fills username+password into a form. Passkey-550        // only entries have no password to fill; sign-in for those goes551        // through the WebAuthn path instead. Filter them out everywhere so552        // the user doesn't see four "GitHub" rows that mostly do nothing.553        // Notes and cards never belonged here either.554        const matches = (555          includeAll556            ? vault557                .getEntries()558                .filter((entry) => entry.type !== "note" && entry.type !== "card")559            : vault.queryDomain(domain)560        ).filter((entry) => !isPasskeyOnly(entry));561        return {562          ok: true,563          data: matches.map((e) =>564            includeAll565              ? {566                  id: e.id,567                  title: e.title,568                  hasPasskey: e.passkey !== undefined,569                }570              : {571                  id: e.id,572                  title: e.title,573                  username: e.username,574                  email: e.email,575                  url: e.url,576                  hasTotp: Boolean(e.totp),577                  hasPasskey: e.passkey !== undefined,578                }579          ),580        };581      }582      case "GET_ENTRY_FOR_FILL": {583        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };584        const { id } = msg.payload as { id: string };585        const entry = vault.getEntryById(id);586        if (!entry) return { ok: false, error: "entry not found" };587        // Passkey-only entries (passkey credential, no password) cannot be588        // filled into a form — sign-in goes through the WebAuthn path. A589        // login that ALSO has a passkey is still fillable for its password.590        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey not fillable" };591        // Strip the passkey credential from the response — content scripts592        // never need the private key, and there's no reason to expose the593        // public credential metadata over the boundary either.594        const { passkey: _strippedPasskey, ...safeEntry } = entry;595        return { ok: true, data: safeEntry };596      }597      case "COPY": {598        const { text, label, alreadyWritten } = msg.payload as {599          text: string;600          label: string;601          alreadyWritten?: boolean;602        };603        await copyToClipboard(text, label, Boolean(alreadyWritten));604        return { ok: true };605      }606      case "CHECK_ALL_BREACHES": {607        const allEntries = vault.getEntries();608        const results: Record<string, number> = {};609        for (const entry of allEntries) {610          if (entry.type === "note") continue;611          if (!entry.password) continue;612          results[entry.id] = await vault.checkBreach(entry.password);613          // Small delay — be a good citizen to the HIBP API614          await new Promise((r) => setTimeout(r, 200));615        }616        // Persist any non-zero counts back to entries617        for (const [id, count] of Object.entries(results)) {618          const entry = vault.getEntryById(id);619          if (entry && (entry.breach ?? 0) !== count) {620            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });621          }622        }623        return { ok: true, data: results };624      }625      case "GET_SETTINGS":626        return { ok: true, data: await vault.ensureSettingsLoaded() };627      case "UPDATE_SETTINGS": {628        const patch = msg.payload as Record<string, unknown>;629        await vault.updateSettings(patch as any);630        if (typeof patch.autoLockMinutes === "number") {631          await setupAutoLock();632          if (vault.isUnlocked()) touchAutoLock();633        }634        return { ok: true };635      }636      case "GET_PENDING_PASSKEY":637        return { ok: true, data: await getPendingPasskeyRequest() };638      case "APPROVE_PASSKEY": {639        const { requestId } = msg.payload as { requestId: number };640        await resolvePendingPasskeyRequest(requestId, true);641        return { ok: true };642      }643      case "DENY_PASSKEY": {644        const { requestId } = msg.payload as { requestId: number };645        await resolvePendingPasskeyRequest(requestId, false);646        return { ok: true };647      }648      case "GET_PASSKEY_PROVIDER_STATE":649        return { ok: true, data: await getPasskeyProviderState() };650      case "SET_PASSKEY_PROVIDER_ENABLED": {651        const { enabled } = msg.payload as { enabled: boolean };652        // Disabling is always free; gating fires only when a free user is653        // trying to turn passkey interception on.654        if (enabled) {655          const gate = await requirePro("passkeys");656          if (!gate.allowed) return { ok: false, error: "pro_required" };657        }658        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };659      }660      case "FIRE_CANARY_PING": {661        const { webhookUrl, entryTitle, trigger } = msg.payload as {662          webhookUrl: string;663          entryTitle: string;664          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";665        };666        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {667          return { ok: false, error: "invalid webhook url" };668        }669        const body = JSON.stringify({670          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",671          entry: entryTitle,672          trigger,673          timestamp: new Date().toISOString(),674          source: "peach-extension",675        });676        if (trigger === "test") {677          // Permitted outbound fetch: user-configured canary alert endpoint678          // (validated by isAllowedCanaryWebhookUrl above). This is the679          // only non-HIBP outbound call in the extension — see680          // Projects.md §3.7. Test pings are awaited so the UI can show681          // success/failure.682          try {683            const res = await fetch(webhookUrl, {684              method: "POST",685              headers: { "Content-Type": "application/json" },686              body,687            });688            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };689          } catch (err) {690            return { ok: false, error: err instanceof Error ? err.message : "network error" };691          }692        }693        // Non-test triggers are fire-and-forget694        fetch(webhookUrl, {695          method: "POST",696          headers: { "Content-Type": "application/json" },697          body,698        }).catch(() => {});699        return { ok: true };700      }701      case "ACTIVATE_LICENSE": {702        const { key } = msg.payload as { key: string };703        const licenseInfo = await activateLicense(key);704        return { ok: true, data: licenseInfo };705      }706      case "GET_LICENSE": {707        const licenseInfo = await getLicenseInfo();708        return { ok: true, data: licenseInfo };709      }710      case "GET_LICENSE_KEY": {711        const key = await getLicenseKey();712        return { ok: true, data: key };713      }714      case "DEACTIVATE_LICENSE": {715        await deactivateLicense();716        return { ok: true };717      }718      case "SHOULD_PLAY_CELEBRATION": {719        const should = await shouldPlayCelebration();720        return { ok: true, data: should };721      }722      case "MARK_CELEBRATION_PLAYED": {723        await markCelebrationPlayed();724        return { ok: true };725      }726      case "OPEN_PRO_GATE": {727        // Content script requests: open popup and navigate to License section.728        const { feature } = (msg.payload ?? {}) as { feature?: string };729        if (chrome.storage.session) {730          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });731        }732        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }733        return { ok: true };734      }735      case "GET_IDENTITIES": {736        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };737        return { ok: true, data: vault.getIdentities() };738      }739      case "TOUCH_AUTO_LOCK": {740        // touchAutoLock() is already called by shouldRefreshAutoLock above;741        // this case just gives the popup a typed message to keep the session alive.742        return { ok: true };743      }744      case "GET_ADVANCED_HEALTH_REPORT": {745        const gate = await requirePro("advanced_health");746        if (!gate.allowed) return { ok: false, error: "pro_required" };747        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };748        const report = await buildAdvancedHealthReport(vault.getEntries());749        return { ok: true, data: report };750      }751      case "INITIATE_PASSWORD_CHANGE": {752        const gate = await requirePro("smart_password_change");753        if (!gate.allowed) return { ok: false, error: "pro_required" };754        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };755        const { id } = msg.payload as { id: string };756        const entry = vault.getEntryById(id);757        if (!entry) return { ok: false, error: "entry not found" };758        const url = resolveResetUrl(entry);759        if (!url) return { ok: false, error: "no reset url" };760        try {761          await chrome.tabs.create({ url });762          return { ok: true, data: { url } };763        } catch (err) {764          return {765            ok: false,766            error: err instanceof Error ? err.message : "failed to open tab",767          };768        }769      }770      case "IS_DURESS_ENABLED": {771        const enabled = await vault.isDuressEnabled();772        return { ok: true, data: enabled };773      }774      case "SETUP_DURESS": {775        const { duressPassword } = msg.payload as { duressPassword: string };776        await vault.setupDuress(duressPassword);777        return { ok: true };778      }779      case "DISABLE_DURESS": {780        await vault.disableDuress();781        return { ok: true };782      }783      case "VERIFY_MAIN_PASSWORD": {784        const { password } = msg.payload as { password: string };785        const ok = await vault.verifyMainPassword(password);786        return { ok: true, data: ok };787      }788      case "CHANGE_PASSWORD": {789        const { currentPassword, newPassword } = msg.payload as {790          currentPassword: string;791          newPassword: string;792        };793        const changed = await vault.changePassword(currentPassword, newPassword);794        return changed795          ? { ok: true }796          : { ok: false, error: "incorrect current password" };797      }798      case "GET_SITE_PASSWORD_POLICY": {799        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });800        if (!tab?.id) return { ok: true, data: null };801        try {802          const response = await chrome.tabs.sendMessage(tab.id, {803            type: "GET_SITE_PASSWORD_POLICY",804          });805          return (response as MessageResponse) ?? { ok: true, data: null };806        } catch {807          return { ok: true, data: null };808        }809      }810      case "GET_SYNC_STATE": {811        const pairedDevices = await getPairedDevices();812        const trustedNetworks = await getTrustedNetworks();813        const tailscale = await isOnTailscale();814        const pro = await isProUser();815816        let status: SyncStatus = "offline";817        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {818          if (pairedDevices.length === 0) {819            status = "no_peers";820          } else {821            status = "synced";822          }823        } else {824          status = "not_trusted";825        }826827        const lastSyncRaw = await storageGet("peach_last_sync_at");828        const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN;829        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined;830831        return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } };832      }833      case "GET_PAIRED_DEVICES": {834        const devices = await getPairedDevices();835        return { ok: true, data: { devices } };836      }837      case "GET_SYNC_STATUS": {838        const lastSyncRaw = await storageGet("peach_last_sync_at");839        const lastSyncParsed = lastSyncRaw ? parseInt(lastSyncRaw, 10) : NaN;840        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : null;841        const status: 'up_to_date' | 'never' = lastSyncAt ? 'up_to_date' : 'never';842        return { ok: true, data: { status, lastSyncAt } };843      }844      case "ACCEPT_PAIRING": {845        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.846        return { ok: true };847      }848      case "REMOVE_PAIRED_DEVICE": {849        const { deviceId } = msg.payload as { deviceId: string };850        await removePairedDevice(deviceId);851        return { ok: true };852      }853      case "REMOVE_TRUSTED_NETWORK": {854        const { ssid, bssid, isTailscale } = msg.payload as any;855        const networks = await getTrustedNetworks();856        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 857          (isTailscale ? n.isTailscale : n.ssid === ssid) && 858          (!bssid || n.bssid === bssid)859        );860        if (network) {861          await removeTrustedNetwork(network.addedAt);862        }863        return { ok: true };864      }865      case "MARK_NETWORK_TRUSTED": {866        const network = await getCurrentNetwork();867        await addTrustedNetwork({868          ssid: network.ssid,869          bssid: network.bssid,870          isTailscale: network.isTailscale,871          addedAt: Date.now(),872        });873        return { ok: true };874      }875      case "GET_INCOMING_PAIRING_REQUEST": {876        const request = await getIncomingPairingRequest();877        return { ok: true, data: request };878      }879      case "RESPOND_INCOMING_PAIRING": {880        const { accept } = msg.payload as { accept: boolean };881        const request = await getIncomingPairingRequest();882        if (!request) return { ok: false, error: "no_pending_request" };883        if (Date.now() > request.expiresAt) {884          await clearIncomingPairingRequest();885          return { ok: false, error: "expired" };886        }887        await clearIncomingPairingRequest();888        if (accept) {889          await addPairedDevice({890            deviceId: request.publicKeyHex,891            displayName: request.deviceName,892            x25519PublicKey: request.publicKeyHex,893            pairedAt: Date.now(),894            lastSeenAt: Date.now(),895          });896        }897        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };898      }899      case "START_PAIRING_SERVER": {900        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.901        const token = generateSixDigitToken();902        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;903        await setActivePairingToken({ token, expiresAt });904        // Fire-and-forget subnet scan — finds the phone after it scans the QR905        // and calls SCAN_PAIRING_QR to register the token with SyncPlugin.906        if (!isNativePlatform()) {907          void runPairingSubnetScan(token);908        }909        return { ok: true, data: { token, expiresAt } };910      }911      case "STOP_PAIRING_SERVER": {912        try {913          await setActivePairingToken(null);914        } catch { /* best-effort */ }915        return { ok: true };916      }917      case "GET_RECENT_PAIRING": {918        const recent = await consumeRecentPairing();919        return { ok: true, data: recent };920      }921      case "DEBUG_INJECT_INCOMING_PAIRING": {922        // Manual E2E rehearsal hook. Inserts a synthetic incoming pairing923        // request into session storage so Phase 7 banner UX can be exercised924        // without a live native host. No Pro gate — this is a no-op in925        // production unless explicitly invoked from a Settings debug action.926        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {927          deviceName?: string;928          publicKeyHex?: string;929        };930        if (!deviceName || !publicKeyHex) {931          return { ok: false, error: "missing_payload" };932        }933        const now = Date.now();934        await setIncomingPairingRequest({935          deviceName,936          publicKeyHex,937          receivedAt: now,938          expiresAt: now + 60_000,939        });940        return { ok: true };941      }942      case "RESET_SYNC_IDENTITY": {943        const gate = await requirePro("sync");944        if (!gate.allowed) return { ok: false, error: "pro_required" };945        const devices = await getPairedDevices();946        for (const device of devices) {947          await removePairedDevice(device.deviceId);948        }949        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };950      }951      case "RECORD_MANUAL_SUMMON": {952        const { domain } = msg.payload as { domain: string };953        const settings = vault.getSettings();954        const existing = settings.manualSummonDomains?.[domain];955        const now = Date.now();956        await vault.updateSettings({957          manualSummonDomains: {958            ...settings.manualSummonDomains,959            [domain]: {960              firstSummonedAt: existing?.firstSummonedAt ?? now,961              summonCount: (existing?.summonCount ?? 0) + 1,962              lastSummonedAt: now,963            },964          },965        });966        return { ok: true };967      }968      case "DECLINE_CARD_SAVE": {969        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };970        await vault.declineCardSaveOffer(last4, expMonth, expYear);971        return { ok: true };972      }973      case "IS_CARD_DECLINED": {974        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };975        const declined = await vault.isCardDeclined(last4, expMonth, expYear);976        return { ok: true, data: declined };977      }978      case "INITIATE_FIREFOX_PASSKEY_CREATE": {979        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {980          rpId?: string;981          rpName?: string;982          userName?: string;983          userDisplayName?: string;984        };985        if (!rpId || !userName) return { ok: false, error: "rpId and userName required" };986        return await initiateFirefoxPasskeyCreate({987          rpId,988          rpName: rpName ?? rpId,989          userName,990          userDisplayName,991        });992      }993994      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {995        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;996        if (!payload) return { ok: false, error: "missing payload" };997        return await completeFirefoxPasskeyCreate(payload);998      }9991000      case "PASSKEY_OFFER_DECLINE": {1001        const { domain } = (msg.payload ?? {}) as { domain?: string };1002        if (!domain) return { ok: false, error: "domain required" };1003        await recordPasskeyOfferDecline(domain);1004        return { ok: true };1005      }10061007      case "GET_PASSKEY_OFFER_DECLINED": {1008        const { domain } = (msg.payload ?? {}) as { domain?: string };1009        if (!domain) return { ok: false, error: "domain required" };1010        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1011      }10121013      case "PASSKEY_HAS_CREDENTIALS": {1014        const payload = msg.payload as {1015          rpId?: string;1016          allowCredentials?: Array<{ id: string; type?: string }>;1017        } | undefined;1018        if (!payload?.rpId) return { ok: false, error: "rpId required" };1019        return await handlePasskeyHasCredentials({1020          rpId: payload.rpId,1021          allowCredentials: payload.allowCredentials ?? [],1022        });1023      }10241025      case "PASSKEY_CREATE": {1026        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1027        if (!payload?.rpId || !payload?.userName) {1028          return { ok: false, error: "rpId and userName required" };1029        }1030        return await handleFirefoxPasskeyCreate(payload);1031      }10321033      case "PASSKEY_GET": {1034        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1035        if (!payload?.rpId) return { ok: false, error: "rpId required" };1036        return await handleFirefoxPasskeyGet(payload);1037      }10381039      case "GET_PASSKEY_FOR_DOMAIN": {1040        const { domain } = (msg.payload ?? {}) as { domain?: string };1041        if (!domain) return { ok: false, error: "domain required" };1042        if (!vault.isUnlocked()) return { ok: true, data: null };1043        const match = vault1044          .getEntries()1045          .find((entry) => entry.passkey?.rpId === domain);1046        if (!match || !match.passkey) return { ok: true, data: null };1047        // Slim shape — only the fields State 11 needs. Never expose private1048        // key material, even though this is locked behind isUnlocked.1049        return {1050          ok: true,1051          data: {1052            rpId: match.passkey.rpId,1053            userName: match.passkey.userName,1054            browser: match.passkey.browser,1055          },1056        };1057      }10581059      case "DESTROY_VAULT": {1060        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1061        // storage.local.clear() wipes every Peach key (slots, settings, license,1062        // onboarded flag, history, sync state, declined cards, recall, etc.);1063        // session.clear() wipes pending passkey requests + pro-notice queues.1064        // Caller (Panic.tsx) handles UI navigation back to onboarding.1065        vault.lock();1066        await storageClear();1067        await vault.clearVaultHistory();1068        if (chrome.storage.session) {1069          await chrome.storage.session.clear();1070        }1071        return { ok: true };1072      }10731074      case "SUBMIT_FEEDBACK": {1075        const { category, message, version, browser } = msg.payload as {1076          category: string;1077          message: string;1078          version: string;1079          browser: string;1080        };1081        if (!message.trim()) return { ok: false, error: "message is empty" };1082        if (!FEEDBACK_ENDPOINT) return { ok: true };1083        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1084          return { ok: false, error: "invalid feedback endpoint" };1085        }1086        try {1087          const res = await fetch(FEEDBACK_ENDPOINT, {1088            method: "POST",1089            headers: { "Content-Type": "application/json" },1090            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1091          });1092          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1093        } catch (err) {1094          return { ok: false, error: err instanceof Error ? err.message : "network error" };1095        }1096      }1097      case "TRIGGER_SYNC": {1098        const gate = await requirePro("sync");1099        if (!gate.allowed) return { ok: false, error: "pro_required" };1100        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };11011102        if (isNativePlatform()) {1103          // Phone is the server — ensure it's listening for desktop connections.1104          syncBridge()?.ensureServerRunning?.();1105          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };1106        }11071108        // Desktop: iterate all paired devices and sync with each.1109        const paired = await getPairedDevices();1110        if (!paired.length) return { ok: true, data: { syncedCount: 0, reason: "no_paired_devices" } };11111112        const subnet = await getLocalSubnet();1113        const results: Array<{ device: string } & SyncResult> = [];11141115        for (const device of paired) {1116          if (!device.x25519PublicKey) continue;11171118          let result: SyncResult;11191120          // Fast path — use last known IP1121          if (device.lastKnownIp) {1122            result = await doVaultSync(device.lastKnownIp, device.x25519PublicKey);1123          } else {1124            result = { status: 'errored', applied: false, error: 'no_ip' };1125          }11261127          // Discovery path — scan if fast path failed1128          if (result.status === 'errored' && subnet) {1129            const newIp = await discoverDevice(subnet, device.x25519PublicKey);1130            if (newIp) {1131              await updatePairedDevice(device.x25519PublicKey, { lastKnownIp: newIp });1132              result = await doVaultSync(newIp, device.x25519PublicKey);1133            }1134          }11351136          if (result.status === 'completed') {1137            await updatePairedDevice(device.x25519PublicKey, {1138              lastSeenAt: Date.now(),1139              lastSyncAt: Date.now(),1140            });1141          }11421143          results.push({ device: device.displayName, ...result });1144        }11451146        const syncedCount = results.filter(r => r.status === 'completed').length;1147        if (syncedCount > 0) {1148          await chrome.storage.local.set({ peach_last_sync_at: String(Date.now()) });1149        }1150        return { ok: true, data: { syncedCount, results } };1151      }1152      // Android-only: biometric unlock with pre-derived key.1153      case "UNLOCK_WITH_KEY": {1154        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1155        if (!isNativePlatform()) {1156          return { ok: false, error: "desktop_only_uses_password" };1157        }1158        try {1159          const result = await vault.unlockWithKey(masterKeyHex);1160          if (result.ok) await publishInMemoryVault(result.entries);1161          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1162        } catch {1163          return { ok: false, error: "invalid_key" };1164        }1165      }1166      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1167      case "GET_DERIVED_KEY": {1168        if (!isNativePlatform()) {1169          return { ok: false, error: "android_only" };1170        }1171        if (!vault.isUnlocked()) {1172          return { ok: false, error: "vault_locked" };1173        }1174        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1175      }1176      // Android: scanned a QR containing a desktop pairing token.1177      case "SCAN_PAIRING_QR": {1178        if (!isNativePlatform()) {1179          return { ok: false, error: "android_only" };1180        }1181        const { token } = msg.payload as { token: string };1182        syncBridge()?.startPairingSession?.({ token });1183        return { ok: true };1184      }1185      // Android: desktop opened a sync connection to the phone's WS server.1186      // Run the responder side of the vault exchange.1187      case "SYNC_SESSION_STARTED": {1188        if (!isNativePlatform()) return { ok: false };1189        if (!vault.isUnlocked()) {1190          return { ok: false, error: "vault_locked" };1191        }1192        const { connectionId } = (msg.payload ?? {}) as { connectionId?: string };1193        if (!connectionId) return { ok: false, error: "missing_connection_id" };11941195        const transport = createAndroidResponderTransport(connectionId);1196        const result = await runBlobSyncSession('responder', transport, buildSyncDeps());1197        if (result.applied) {1198          await publishInMemoryVault(vault.getEntries());1199        }1200        return { ok: true, data: result };1201      }1202      // Android: returns the phone's WiFi IP address.1203      case "GET_LOCAL_IP": {1204        if (!isNativePlatform()) {1205          return { ok: false, error: "android_only" };1206        }1207        const { ip } = (await syncBridge()?.getLocalIp?.()) ?? { ip: "" };1208        return { ok: true, data: { ip } };1209      }1210      case "GET_IDENTITY_SUGGESTIONS": {1211        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1212        const entries = vault.getEntries();1213        const suggestions = buildIdentitySuggestions(entries);1214        return { ok: true, data: { suggestions } };1215      }1216      case "POPULATE_INLINE_VAULT": {1217        if (!isNativePlatform()) return { ok: false };1218        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1219        const entries = vault.getEntries();1220        await publishInMemoryVault(entries);1221        return { ok: true };1222      }1223      // --- PNA compatibility test handlers — REMOVE BEFORE RELEASE ---1224      case "TEST_LOCAL_WEBSOCKET": {1225        const { ip } = (msg.payload ?? {}) as { ip?: string };1226        if (!ip) return { ok: false, error: "ip required" };1227        return new Promise((resolve) => {1228          try {1229            const ws = new WebSocket(`ws://${ip}:44100`);1230            ws.onopen = () => { ws.close(); resolve({ ok: true, data: { connected: true } }); };1231            ws.onerror = () => resolve({ ok: false, error: "connection_failed" });1232            setTimeout(() => { ws.close(); resolve({ ok: false, error: "timeout" }); }, 3000);1233          } catch (err) {1234            resolve({ ok: false, error: String(err) });1235          }1236        });1237      }1238      case "TEST_SUBNET_DETECTION": {1239        const subnet = await getLocalSubnet();1240        return { ok: true, data: { subnet } };1241      }1242      case "TEST_SUBNET_SCAN": {1243        const subnet = await getLocalSubnet();1244        if (!subnet) return { ok: false, error: "no_subnet" };1245        const start = Date.now();1246        const result = await discoverDevice(subnet, "000000000000000000000000000000000000000000000000000000000000000000");1247        return { ok: true, data: { elapsed: Date.now() - start, found: !!result } };1248      }1249      case 'TEST_WS_LOCAL': {1250        const { ip } = msg.payload as { ip: string };12511252        return new Promise((resolve) => {1253          const log: string[] = [];1254          log.push(`Attempting ws://${ip}:44100 from service worker...`);12551256          let ws: WebSocket;1257          let settled = false;1258          const settle = (result: MessageResponse) => {1259            if (!settled) { settled = true; resolve(result); }1260          };12611262          try {1263            ws = new WebSocket(`ws://${ip}:44100`);12641265            ws.onopen = () => {1266              log.push('SUCCESS: WebSocket connected');1267              ws.close();1268              settle({ ok: true, data: { log } });1269            };12701271            ws.onerror = (e) => {1272              log.push(`FAILED: onerror fired — ${String(e)}`);1273              settle({ ok: false, error: 'ws_error', data: { log } });1274            };12751276            ws.onclose = (e) => {1277              if (e.code !== 1000) {1278                log.push(`CLOSED unexpectedly: code=${e.code} reason=${e.reason}`);1279                settle({ ok: false, error: 'ws_closed', data: { code: e.code, log } });1280              }1281            };12821283            setTimeout(() => {1284              try { ws.close(); } catch {}1285              log.push('FAILED: 5 second timeout — connection never opened');1286              settle({ ok: false, error: 'timeout', data: { log } });1287            }, 5000);12881289          } catch (err) {1290            log.push(`FAILED: WebSocket constructor threw — ${String(err)}`);1291            settle({ ok: false, error: 'constructor_threw', data: { log } });1292          }1293        });1294      }12951296      case 'TEST_SUBNET_DETECT': {1297        return new Promise((resolve) => {1298          try {1299            // RTCPeerConnection availability varies by context — this is what we're testing1300            // eslint-disable-next-line @typescript-eslint/no-explicit-any1301            const RTC = (globalThis as any).RTCPeerConnection as (new (cfg: object) => RTCPeerConnection) | undefined;1302            if (!RTC) {1303              resolve({ ok: false, error: 'RTCPeerConnection is not defined' });1304              return;1305            }1306            const pc = new RTC({ iceServers: [] });1307            pc.createDataChannel('');1308            pc.createOffer().then((o) => pc.setLocalDescription(o));13091310            const candidates: string[] = [];1311            const timer = setTimeout(() => {1312              pc.close();1313              if (candidates.length === 0) {1314                resolve({ ok: false, error: 'no_candidates', data: { candidates } });1315              } else {1316                const subnet = candidates[0].match(/(\d+\.\d+\.\d+)\.\d+/)?.[1];1317                resolve({ ok: true, data: { subnet, candidates } });1318              }1319            }, 2000);13201321            pc.onicecandidate = (e) => {1322              if (!e.candidate) return;1323              const m = e.candidate.candidate.match(/(\d+\.\d+\.\d+\.\d+)/);1324              if (m && !m[1].startsWith('127')) candidates.push(m[1]);1325            };13261327            pc.onicegatheringstatechange = () => {1328              if (pc.iceGatheringState === 'complete') {1329                clearTimeout(timer);1330                pc.close();1331                const subnet = candidates[0]?.match(/(\d+\.\d+\.\d+)\.\d+/)?.[1];1332                resolve({ ok: candidates.length > 0, data: { subnet, candidates } });1333              }1334            };1335          } catch (err) {1336            resolve({ ok: false, error: String(err) });1337          }1338        });1339      }13401341      // --- end test handlers ---1342      default:1343        return { ok: false, error: "unknown message type" };1344    }1345  } catch (err) {1346    return {1347      ok: false,1348      error: err instanceof Error ? err.message : "operation failed",1349    };1350  }1351}13521353// --- Mobile platform helpers ---13541355// Android: populates the in-memory vault used by PeachAutofillService.1356async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1357  const plugin = nativePlugin<{1358    setEntries?: (args: {1359      entries: Array<{1360        id: string;1361        title: string;1362        username: string;1363        email: string;1364        password: string;1365        url: string;1366        totp: string;1367        additionalUrls: string[];1368      }>;1369    }) => Promise<void>;1370  }>("InMemoryVaultPlugin");1371  if (!plugin?.setEntries) return;1372  await plugin.setEntries({1373    entries: entries.map((e) => ({1374      id: e.id,1375      title: e.title ?? "",1376      username: e.username ?? "",1377      email: (e as VaultEntry & { email?: string }).email ?? "",1378      password: e.password ?? "",1379      url: e.url ?? "",1380      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1381      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1382    })),1383  });1384}13851386// Android: clear the autofill in-memory store on lock.1387async function clearInMemoryVault(): Promise<void> {1388  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1389  if (!plugin?.clearEntries) return;1390  await plugin.clearEntries();1391}13921393interface SyncBridge {1394  ensureServerRunning?: () => void;1395  startPairingSession?: (args: { token: string }) => void;1396  getLocalIp?: () => Promise<{ ip: string }>;1397  sendToConnection?: (args: { connectionId: string; data: string }) => Promise<void>;1398  addListener?: (event: string, handler: (data: Record<string, string>) => void) => void;1399}14001401// Resolve the Capacitor SyncPlugin at call time — module-load resolution1402// races with Capacitor's plugin registration on the Android WebView.1403function syncBridge(): SyncBridge | null {1404  return nativePlugin<SyncBridge>("SyncPlugin");1405}14061407// Build a SyncTransport for the Android responder path — the phone's WS server1408// already has an open connection from the desktop. We send back via1409// SyncPlugin.sendToConnection and receive via the peach:sync-frame queue.1410const androidSyncFrameQueues = new Map<string, Array<(frame: string) => void>>();14111412export function deliverAndroidSyncFrame(connectionId: string, frame: string): void {1413  const queue = androidSyncFrameQueues.get(connectionId);1414  if (queue?.length) queue.shift()!(frame);1415}14161417function createAndroidResponderTransport(connectionId: string) {1418  const pendingReceivers: Array<(frame: string) => void> = [];1419  androidSyncFrameQueues.set(connectionId, pendingReceivers);14201421  return {1422    send: async (data: Uint8Array) => {1423      await syncBridge()?.sendToConnection?.({ connectionId, data: bytesToBase64(data) });1424    },1425    receive: (): Promise<Uint8Array> => new Promise((res) => {1426      pendingReceivers.push((frame) => {1427        res(frame ? base64ToBytes(frame) : new Uint8Array(0));1428      });1429    }),1430    close: async () => {1431      androidSyncFrameQueues.delete(connectionId);1432    },1433  };1434}14351436// Returns username use-counts from the vault, sorted by frequency. Each row1437// also carries the entry's email so the popup can suggest the email/username1438// pair the user has actually used together.1439function buildIdentitySuggestions(1440  entries: VaultEntry[],1441): Array<{ email: string; username: string; count: number }> {1442  const usernameCounts = new Map<string, number>();1443  const usernameEmail = new Map<string, string>();1444  for (const entry of entries) {1445    const username = entry.username ?? "";1446    const email = (entry as VaultEntry & { email?: string }).email ?? "";1447    if (!username && !email) continue;1448    const key = username || email;1449    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1450    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1451  }1452  return Array.from(usernameCounts.entries())1453    .sort((a, b) => b[1] - a[1])1454    .map(([username, count]) => ({1455      email: usernameEmail.get(username) ?? "",1456      username,1457      count,1458    }));1459}14601461/** Notify all content scripts that the vault just became available. */1462function broadcastToContentScripts(message: { type: string }): void {1463  if (!chrome.tabs?.query) return;1464  chrome.tabs.query({}, (tabs) => {1465    for (const tab of tabs) {1466      if (tab.id !== undefined) {1467        chrome.tabs.sendMessage(tab.id, message).catch(() => {1468          // Tab may not have a content script — silently ignore1469        });1470      }1471    }1472  });1473}14741475function shouldRefreshAutoLock(type: MessageType): boolean {1476  return (1477    type !== "HAS_VAULT" &&1478    type !== "IS_UNLOCKED" &&1479    type !== "GET_VAULT_STATUS" &&1480    type !== "LOCK" &&1481    type !== "UPDATE_SETTINGS" &&1482    type !== "GET_PENDING_PASSKEY" &&1483    type !== "GET_PASSKEY_PROVIDER_STATE" &&1484    type !== "DECLINE_CARD_SAVE" &&1485    type !== "IS_CARD_DECLINED" &&1486    type !== "SUBMIT_FEEDBACK"1487  );1488}14891490function isAllowedCanaryWebhookUrl(value: string): boolean {1491  try {1492    const url = new URL(value);1493    if (url.protocol !== "https:") return false;14941495    const hostname = url.hostname.toLowerCase();1496    if (1497      hostname === "localhost" ||1498      hostname.endsWith(".localhost") ||1499      isPrivateIpv4(hostname) ||1500      isPrivateIpv6(hostname)1501    ) {1502      return false;1503    }15041505    return true;1506  } catch {1507    return false;1508  }1509}15101511function isPrivateIpv4(hostname: string): boolean {1512  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1513    return true;1514  }15151516  const octets = hostname.split(".").map((part) => Number(part));1517  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1518    return false;1519  }15201521  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1522}15231524function isPrivateIpv6(hostname: string): boolean {1525  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1526  return (1527    normalized === "::1" ||1528    normalized.startsWith("fc") ||1529    normalized.startsWith("fd") ||1530    normalized.startsWith("fe80:")1531  );1532}