messages.ts

58.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 "SAVE_NOTE": {522        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };523        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };524        const now = Date.now();525        if (id) {526          const existing = vault.getEntryById(id);527          if (!existing) return { ok: false, error: "not_found" };528          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });529          return { ok: true, data: vault.getEntryById(id) };530        } else {531          const entry = await vault.addEntry({532            type: "note",533            title: title || "Untitled",534            notes: body,535            createdAt: now,536            modifiedAt: now,537          } as any);538          return { ok: true, data: entry };539        }540      }541      case "DELETE_NOTE": {542        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };543        const { id } = msg.payload as { id: string };544        await vault.deleteEntry(id);545        return { ok: true };546      }547      case "AUTOFILL_QUERY": {548        if (!vault.isUnlocked()) {549          return { ok: false, error: "VAULT_LOCKED" };550        }551        const { domain, includeAll, kind } = msg.payload as {552          domain: string;553          includeAll?: boolean;554          kind?: "login" | "card";555        };556        // kind="card": return saved cards as compact summaries for the557        // inline card silver platter. Cards are not domain-scoped — every558        // saved card is a candidate on every checkout page — so domain is559        // ignored when kind === "card".560        if (kind === "card") {561          const cards = vault.getEntries().filter((e) => e.type === "card");562          return {563            ok: true,564            data: cards.map((e) => ({565              id: e.id,566              title: e.cardNickname || e.title,567              cardholderName: e.cardholderName,568              last4: e.last4,569              expMonth: e.expMonth,570              expYear: e.expYear,571              network: e.network,572            })),573          };574        }575        // The inline selector fills username+password into a form. Passkey-576        // only entries have no password to fill; sign-in for those goes577        // through the WebAuthn path instead. Filter them out everywhere so578        // the user doesn't see four "GitHub" rows that mostly do nothing.579        // Notes and cards never belonged here either.580        const matches = (581          includeAll582            ? vault583                .getEntries()584                .filter((entry) => entry.type !== "note" && entry.type !== "card")585            : vault.queryDomain(domain)586        ).filter((entry) => !isPasskeyOnly(entry));587        return {588          ok: true,589          data: matches.map((e) =>590            includeAll591              ? {592                  id: e.id,593                  title: e.title,594                  hasPasskey: e.passkey !== undefined,595                }596              : {597                  id: e.id,598                  title: e.title,599                  username: e.username,600                  email: e.email,601                  url: e.url,602                  hasTotp: Boolean(e.totp),603                  hasPasskey: e.passkey !== undefined,604                }605          ),606        };607      }608      case "GET_ENTRY_FOR_FILL": {609        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };610        const { id } = msg.payload as { id: string };611        const entry = vault.getEntryById(id);612        if (!entry) return { ok: false, error: "entry not found" };613        // Passkey-only entries (passkey credential, no password) cannot be614        // filled into a form — sign-in goes through the WebAuthn path. A615        // login that ALSO has a passkey is still fillable for its password.616        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey not fillable" };617        // Strip the passkey credential from the response — content scripts618        // never need the private key, and there's no reason to expose the619        // public credential metadata over the boundary either.620        const { passkey: _strippedPasskey, ...safeEntry } = entry;621        return { ok: true, data: safeEntry };622      }623      case "COPY": {624        const { text, label, alreadyWritten } = msg.payload as {625          text: string;626          label: string;627          alreadyWritten?: boolean;628        };629        await copyToClipboard(text, label, Boolean(alreadyWritten));630        return { ok: true };631      }632      case "CHECK_ALL_BREACHES": {633        const allEntries = vault.getEntries();634        const results: Record<string, number> = {};635        for (const entry of allEntries) {636          if (entry.type === "note") continue;637          if (!entry.password) continue;638          results[entry.id] = await vault.checkBreach(entry.password);639          // Small delay — be a good citizen to the HIBP API640          await new Promise((r) => setTimeout(r, 200));641        }642        // Persist any non-zero counts back to entries643        for (const [id, count] of Object.entries(results)) {644          const entry = vault.getEntryById(id);645          if (entry && (entry.breach ?? 0) !== count) {646            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });647          }648        }649        return { ok: true, data: results };650      }651      case "GET_SETTINGS":652        return { ok: true, data: await vault.ensureSettingsLoaded() };653      case "UPDATE_SETTINGS": {654        const patch = msg.payload as Record<string, unknown>;655        await vault.updateSettings(patch as any);656        if (typeof patch.autoLockMinutes === "number") {657          await setupAutoLock();658          if (vault.isUnlocked()) touchAutoLock();659        }660        return { ok: true };661      }662      case "GET_PENDING_PASSKEY":663        return { ok: true, data: await getPendingPasskeyRequest() };664      case "APPROVE_PASSKEY": {665        const { requestId } = msg.payload as { requestId: number };666        await resolvePendingPasskeyRequest(requestId, true);667        return { ok: true };668      }669      case "DENY_PASSKEY": {670        const { requestId } = msg.payload as { requestId: number };671        await resolvePendingPasskeyRequest(requestId, false);672        return { ok: true };673      }674      case "GET_PASSKEY_PROVIDER_STATE":675        return { ok: true, data: await getPasskeyProviderState() };676      case "SET_PASSKEY_PROVIDER_ENABLED": {677        const { enabled } = msg.payload as { enabled: boolean };678        // Disabling is always free; gating fires only when a free user is679        // trying to turn passkey interception on.680        if (enabled) {681          const gate = await requirePro("passkeys");682          if (!gate.allowed) return { ok: false, error: "pro_required" };683        }684        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };685      }686      case "FIRE_CANARY_PING": {687        const { webhookUrl, entryTitle, trigger } = msg.payload as {688          webhookUrl: string;689          entryTitle: string;690          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";691        };692        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {693          return { ok: false, error: "invalid webhook url" };694        }695        const body = JSON.stringify({696          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",697          entry: entryTitle,698          trigger,699          timestamp: new Date().toISOString(),700          source: "peach-extension",701        });702        if (trigger === "test") {703          // Permitted outbound fetch: user-configured canary alert endpoint704          // (validated by isAllowedCanaryWebhookUrl above). This is the705          // only non-HIBP outbound call in the extension — see706          // Projects.md §3.7. Test pings are awaited so the UI can show707          // success/failure.708          try {709            const res = await fetch(webhookUrl, {710              method: "POST",711              headers: { "Content-Type": "application/json" },712              body,713            });714            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };715          } catch (err) {716            return { ok: false, error: err instanceof Error ? err.message : "network error" };717          }718        }719        // Non-test triggers are fire-and-forget720        fetch(webhookUrl, {721          method: "POST",722          headers: { "Content-Type": "application/json" },723          body,724        }).catch(() => {});725        return { ok: true };726      }727      case "ACTIVATE_LICENSE": {728        const { key } = msg.payload as { key: string };729        const licenseInfo = await activateLicense(key);730        return { ok: true, data: licenseInfo };731      }732      case "GET_LICENSE": {733        const licenseInfo = await getLicenseInfo();734        return { ok: true, data: licenseInfo };735      }736      case "GET_LICENSE_KEY": {737        const key = await getLicenseKey();738        return { ok: true, data: key };739      }740      case "DEACTIVATE_LICENSE": {741        await deactivateLicense();742        return { ok: true };743      }744      case "SHOULD_PLAY_CELEBRATION": {745        const should = await shouldPlayCelebration();746        return { ok: true, data: should };747      }748      case "MARK_CELEBRATION_PLAYED": {749        await markCelebrationPlayed();750        return { ok: true };751      }752      case "OPEN_PRO_GATE": {753        // Content script requests: open popup and navigate to License section.754        const { feature } = (msg.payload ?? {}) as { feature?: string };755        if (chrome.storage.session) {756          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });757        }758        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }759        return { ok: true };760      }761      case "GET_IDENTITIES": {762        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };763        return { ok: true, data: vault.getIdentities() };764      }765      case "TOUCH_AUTO_LOCK": {766        // touchAutoLock() is already called by shouldRefreshAutoLock above;767        // this case just gives the popup a typed message to keep the session alive.768        return { ok: true };769      }770      case "GET_ADVANCED_HEALTH_REPORT": {771        const gate = await requirePro("advanced_health");772        if (!gate.allowed) return { ok: false, error: "pro_required" };773        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };774        const report = await buildAdvancedHealthReport(vault.getEntries());775        return { ok: true, data: report };776      }777      case "INITIATE_PASSWORD_CHANGE": {778        const gate = await requirePro("smart_password_change");779        if (!gate.allowed) return { ok: false, error: "pro_required" };780        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };781        const { id } = msg.payload as { id: string };782        const entry = vault.getEntryById(id);783        if (!entry) return { ok: false, error: "entry not found" };784        const url = resolveResetUrl(entry);785        if (!url) return { ok: false, error: "no reset url" };786        try {787          await chrome.tabs.create({ url });788          return { ok: true, data: { url } };789        } catch (err) {790          return {791            ok: false,792            error: err instanceof Error ? err.message : "failed to open tab",793          };794        }795      }796      case "IS_DURESS_ENABLED": {797        const enabled = await vault.isDuressEnabled();798        return { ok: true, data: enabled };799      }800      case "SETUP_DURESS": {801        const { duressPassword } = msg.payload as { duressPassword: string };802        await vault.setupDuress(duressPassword);803        return { ok: true };804      }805      case "DISABLE_DURESS": {806        await vault.disableDuress();807        return { ok: true };808      }809      case "VERIFY_MAIN_PASSWORD": {810        const { password } = msg.payload as { password: string };811        const ok = await vault.verifyMainPassword(password);812        return { ok: true, data: ok };813      }814      case "CHANGE_PASSWORD": {815        const { currentPassword, newPassword } = msg.payload as {816          currentPassword: string;817          newPassword: string;818        };819        const changed = await vault.changePassword(currentPassword, newPassword);820        return changed821          ? { ok: true }822          : { ok: false, error: "incorrect current password" };823      }824      case "GET_SITE_PASSWORD_POLICY": {825        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });826        if (!tab?.id) return { ok: true, data: null };827        try {828          const response = await chrome.tabs.sendMessage(tab.id, {829            type: "GET_SITE_PASSWORD_POLICY",830          });831          return (response as MessageResponse) ?? { ok: true, data: null };832        } catch {833          return { ok: true, data: null };834        }835      }836      case "GET_SYNC_STATE": {837        const pairedDevices = await getPairedDevices();838        const trustedNetworks = await getTrustedNetworks();839        const tailscale = await isOnTailscale();840        const pro = await isProUser();841842        let status: SyncStatus = "offline";843        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {844          if (pairedDevices.length === 0) {845            status = "no_peers";846          } else {847            status = "synced";848          }849        } else {850          status = "not_trusted";851        }852853        const lastSyncRaw = await storageGet("peach_last_sync_at");854        const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN;855        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined;856857        return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } };858      }859      case "GET_PAIRED_DEVICES": {860        const devices = await getPairedDevices();861        return { ok: true, data: { devices } };862      }863      case "GET_SYNC_STATUS": {864        const lastSyncRaw = await storageGet("peach_last_sync_at");865        const lastSyncParsed = lastSyncRaw ? parseInt(lastSyncRaw, 10) : NaN;866        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : null;867        const status: 'up_to_date' | 'never' = lastSyncAt ? 'up_to_date' : 'never';868        return { ok: true, data: { status, lastSyncAt } };869      }870      case "ACCEPT_PAIRING": {871        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.872        return { ok: true };873      }874      case "REMOVE_PAIRED_DEVICE": {875        const { deviceId } = msg.payload as { deviceId: string };876        await removePairedDevice(deviceId);877        return { ok: true };878      }879      case "REMOVE_TRUSTED_NETWORK": {880        const { ssid, bssid, isTailscale } = msg.payload as any;881        const networks = await getTrustedNetworks();882        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 883          (isTailscale ? n.isTailscale : n.ssid === ssid) && 884          (!bssid || n.bssid === bssid)885        );886        if (network) {887          await removeTrustedNetwork(network.addedAt);888        }889        return { ok: true };890      }891      case "MARK_NETWORK_TRUSTED": {892        const network = await getCurrentNetwork();893        await addTrustedNetwork({894          ssid: network.ssid,895          bssid: network.bssid,896          isTailscale: network.isTailscale,897          addedAt: Date.now(),898        });899        return { ok: true };900      }901      case "GET_INCOMING_PAIRING_REQUEST": {902        const request = await getIncomingPairingRequest();903        return { ok: true, data: request };904      }905      case "RESPOND_INCOMING_PAIRING": {906        const { accept } = msg.payload as { accept: boolean };907        const request = await getIncomingPairingRequest();908        if (!request) return { ok: false, error: "no_pending_request" };909        if (Date.now() > request.expiresAt) {910          await clearIncomingPairingRequest();911          return { ok: false, error: "expired" };912        }913        await clearIncomingPairingRequest();914        if (accept) {915          await addPairedDevice({916            deviceId: request.publicKeyHex,917            displayName: request.deviceName,918            x25519PublicKey: request.publicKeyHex,919            pairedAt: Date.now(),920            lastSeenAt: Date.now(),921          });922        }923        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };924      }925      case "START_PAIRING_SERVER": {926        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.927        const token = generateSixDigitToken();928        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;929        await setActivePairingToken({ token, expiresAt });930        // Fire-and-forget subnet scan — finds the phone after it scans the QR931        // and calls SCAN_PAIRING_QR to register the token with SyncPlugin.932        if (!isNativePlatform()) {933          void runPairingSubnetScan(token);934        }935        return { ok: true, data: { token, expiresAt } };936      }937      case "STOP_PAIRING_SERVER": {938        try {939          await setActivePairingToken(null);940        } catch { /* best-effort */ }941        return { ok: true };942      }943      case "GET_RECENT_PAIRING": {944        const recent = await consumeRecentPairing();945        return { ok: true, data: recent };946      }947      case "DEBUG_INJECT_INCOMING_PAIRING": {948        // Manual E2E rehearsal hook. Inserts a synthetic incoming pairing949        // request into session storage so Phase 7 banner UX can be exercised950        // without a live native host. No Pro gate — this is a no-op in951        // production unless explicitly invoked from a Settings debug action.952        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {953          deviceName?: string;954          publicKeyHex?: string;955        };956        if (!deviceName || !publicKeyHex) {957          return { ok: false, error: "missing_payload" };958        }959        const now = Date.now();960        await setIncomingPairingRequest({961          deviceName,962          publicKeyHex,963          receivedAt: now,964          expiresAt: now + 60_000,965        });966        return { ok: true };967      }968      case "RESET_SYNC_IDENTITY": {969        const gate = await requirePro("sync");970        if (!gate.allowed) return { ok: false, error: "pro_required" };971        const devices = await getPairedDevices();972        for (const device of devices) {973          await removePairedDevice(device.deviceId);974        }975        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };976      }977      case "RECORD_MANUAL_SUMMON": {978        const { domain } = msg.payload as { domain: string };979        const settings = vault.getSettings();980        const existing = settings.manualSummonDomains?.[domain];981        const now = Date.now();982        await vault.updateSettings({983          manualSummonDomains: {984            ...settings.manualSummonDomains,985            [domain]: {986              firstSummonedAt: existing?.firstSummonedAt ?? now,987              summonCount: (existing?.summonCount ?? 0) + 1,988              lastSummonedAt: now,989            },990          },991        });992        return { ok: true };993      }994      case "DECLINE_CARD_SAVE": {995        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };996        await vault.declineCardSaveOffer(last4, expMonth, expYear);997        return { ok: true };998      }999      case "IS_CARD_DECLINED": {1000        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1001        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1002        return { ok: true, data: declined };1003      }1004      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1005        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1006          rpId?: string;1007          rpName?: string;1008          userName?: string;1009          userDisplayName?: string;1010        };1011        if (!rpId || !userName) return { ok: false, error: "rpId and userName required" };1012        return await initiateFirefoxPasskeyCreate({1013          rpId,1014          rpName: rpName ?? rpId,1015          userName,1016          userDisplayName,1017        });1018      }10191020      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1021        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1022        if (!payload) return { ok: false, error: "missing payload" };1023        return await completeFirefoxPasskeyCreate(payload);1024      }10251026      case "PASSKEY_OFFER_DECLINE": {1027        const { domain } = (msg.payload ?? {}) as { domain?: string };1028        if (!domain) return { ok: false, error: "domain required" };1029        await recordPasskeyOfferDecline(domain);1030        return { ok: true };1031      }10321033      case "GET_PASSKEY_OFFER_DECLINED": {1034        const { domain } = (msg.payload ?? {}) as { domain?: string };1035        if (!domain) return { ok: false, error: "domain required" };1036        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1037      }10381039      case "PASSKEY_HAS_CREDENTIALS": {1040        const payload = msg.payload as {1041          rpId?: string;1042          allowCredentials?: Array<{ id: string; type?: string }>;1043        } | undefined;1044        if (!payload?.rpId) return { ok: false, error: "rpId required" };1045        return await handlePasskeyHasCredentials({1046          rpId: payload.rpId,1047          allowCredentials: payload.allowCredentials ?? [],1048        });1049      }10501051      case "PASSKEY_CREATE": {1052        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1053        if (!payload?.rpId || !payload?.userName) {1054          return { ok: false, error: "rpId and userName required" };1055        }1056        return await handleFirefoxPasskeyCreate(payload);1057      }10581059      case "PASSKEY_GET": {1060        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1061        if (!payload?.rpId) return { ok: false, error: "rpId required" };1062        return await handleFirefoxPasskeyGet(payload);1063      }10641065      case "GET_PASSKEY_FOR_DOMAIN": {1066        const { domain } = (msg.payload ?? {}) as { domain?: string };1067        if (!domain) return { ok: false, error: "domain required" };1068        if (!vault.isUnlocked()) return { ok: true, data: null };1069        const match = vault1070          .getEntries()1071          .find((entry) => entry.passkey?.rpId === domain);1072        if (!match || !match.passkey) return { ok: true, data: null };1073        // Slim shape — only the fields State 11 needs. Never expose private1074        // key material, even though this is locked behind isUnlocked.1075        return {1076          ok: true,1077          data: {1078            rpId: match.passkey.rpId,1079            userName: match.passkey.userName,1080            browser: match.passkey.browser,1081          },1082        };1083      }10841085      case "DESTROY_VAULT": {1086        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1087        // storage.local.clear() wipes every Peach key (slots, settings, license,1088        // onboarded flag, history, sync state, declined cards, recall, etc.);1089        // session.clear() wipes pending passkey requests + pro-notice queues.1090        // Caller (Panic.tsx) handles UI navigation back to onboarding.1091        vault.lock();1092        await storageClear();1093        await vault.clearVaultHistory();1094        if (chrome.storage.session) {1095          await chrome.storage.session.clear();1096        }1097        return { ok: true };1098      }10991100      case "SUBMIT_FEEDBACK": {1101        const { category, message, version, browser } = msg.payload as {1102          category: string;1103          message: string;1104          version: string;1105          browser: string;1106        };1107        if (!message.trim()) return { ok: false, error: "message is empty" };1108        if (!FEEDBACK_ENDPOINT) return { ok: true };1109        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1110          return { ok: false, error: "invalid feedback endpoint" };1111        }1112        try {1113          const res = await fetch(FEEDBACK_ENDPOINT, {1114            method: "POST",1115            headers: { "Content-Type": "application/json" },1116            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1117          });1118          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1119        } catch (err) {1120          return { ok: false, error: err instanceof Error ? err.message : "network error" };1121        }1122      }1123      case "TRIGGER_SYNC": {1124        const gate = await requirePro("sync");1125        if (!gate.allowed) return { ok: false, error: "pro_required" };1126        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };11271128        if (isNativePlatform()) {1129          // Phone is the server — ensure it's listening for desktop connections.1130          syncBridge()?.ensureServerRunning?.();1131          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };1132        }11331134        // Desktop: iterate all paired devices and sync with each.1135        const paired = await getPairedDevices();1136        if (!paired.length) return { ok: true, data: { syncedCount: 0, reason: "no_paired_devices" } };11371138        const subnet = await getLocalSubnet();1139        const results: Array<{ device: string } & SyncResult> = [];11401141        for (const device of paired) {1142          if (!device.x25519PublicKey) continue;11431144          let result: SyncResult;11451146          // Fast path — use last known IP1147          if (device.lastKnownIp) {1148            result = await doVaultSync(device.lastKnownIp, device.x25519PublicKey);1149          } else {1150            result = { status: 'errored', applied: false, error: 'no_ip' };1151          }11521153          // Discovery path — scan if fast path failed1154          if (result.status === 'errored' && subnet) {1155            const newIp = await discoverDevice(subnet, device.x25519PublicKey);1156            if (newIp) {1157              await updatePairedDevice(device.x25519PublicKey, { lastKnownIp: newIp });1158              result = await doVaultSync(newIp, device.x25519PublicKey);1159            }1160          }11611162          if (result.status === 'completed') {1163            await updatePairedDevice(device.x25519PublicKey, {1164              lastSeenAt: Date.now(),1165              lastSyncAt: Date.now(),1166            });1167          }11681169          results.push({ device: device.displayName, ...result });1170        }11711172        const syncedCount = results.filter(r => r.status === 'completed').length;1173        if (syncedCount > 0) {1174          await chrome.storage.local.set({ peach_last_sync_at: String(Date.now()) });1175        }1176        return { ok: true, data: { syncedCount, results } };1177      }1178      // Android-only: biometric unlock with pre-derived key.1179      case "UNLOCK_WITH_KEY": {1180        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1181        if (!isNativePlatform()) {1182          return { ok: false, error: "desktop_only_uses_password" };1183        }1184        try {1185          const result = await vault.unlockWithKey(masterKeyHex);1186          if (result.ok) await publishInMemoryVault(result.entries);1187          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1188        } catch {1189          return { ok: false, error: "invalid_key" };1190        }1191      }1192      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1193      case "GET_DERIVED_KEY": {1194        if (!isNativePlatform()) {1195          return { ok: false, error: "android_only" };1196        }1197        if (!vault.isUnlocked()) {1198          return { ok: false, error: "vault_locked" };1199        }1200        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1201      }1202      // Android: scanned a QR containing a desktop pairing token.1203      case "SCAN_PAIRING_QR": {1204        if (!isNativePlatform()) {1205          return { ok: false, error: "android_only" };1206        }1207        const { token } = msg.payload as { token: string };1208        syncBridge()?.startPairingSession?.({ token });1209        return { ok: true };1210      }1211      // Android: desktop opened a sync connection to the phone's WS server.1212      // Run the responder side of the vault exchange.1213      case "SYNC_SESSION_STARTED": {1214        if (!isNativePlatform()) return { ok: false };1215        if (!vault.isUnlocked()) {1216          return { ok: false, error: "vault_locked" };1217        }1218        const { connectionId } = (msg.payload ?? {}) as { connectionId?: string };1219        if (!connectionId) return { ok: false, error: "missing_connection_id" };12201221        const transport = createAndroidResponderTransport(connectionId);1222        const result = await runBlobSyncSession('responder', transport, buildSyncDeps());1223        if (result.applied) {1224          await publishInMemoryVault(vault.getEntries());1225        }1226        return { ok: true, data: result };1227      }1228      // Android: returns the phone's WiFi IP address.1229      case "GET_LOCAL_IP": {1230        if (!isNativePlatform()) {1231          return { ok: false, error: "android_only" };1232        }1233        const { ip } = (await syncBridge()?.getLocalIp?.()) ?? { ip: "" };1234        return { ok: true, data: { ip } };1235      }1236      case "GET_IDENTITY_SUGGESTIONS": {1237        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1238        const entries = vault.getEntries();1239        const suggestions = buildIdentitySuggestions(entries);1240        return { ok: true, data: { suggestions } };1241      }1242      case "POPULATE_INLINE_VAULT": {1243        if (!isNativePlatform()) return { ok: false };1244        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1245        const entries = vault.getEntries();1246        await publishInMemoryVault(entries);1247        return { ok: true };1248      }1249      // --- PNA compatibility test handlers — REMOVE BEFORE RELEASE ---1250      case "TEST_LOCAL_WEBSOCKET": {1251        const { ip } = (msg.payload ?? {}) as { ip?: string };1252        if (!ip) return { ok: false, error: "ip required" };1253        return new Promise((resolve) => {1254          try {1255            const ws = new WebSocket(`ws://${ip}:44100`);1256            ws.onopen = () => { ws.close(); resolve({ ok: true, data: { connected: true } }); };1257            ws.onerror = () => resolve({ ok: false, error: "connection_failed" });1258            setTimeout(() => { ws.close(); resolve({ ok: false, error: "timeout" }); }, 3000);1259          } catch (err) {1260            resolve({ ok: false, error: String(err) });1261          }1262        });1263      }1264      case "TEST_SUBNET_DETECTION": {1265        const subnet = await getLocalSubnet();1266        return { ok: true, data: { subnet } };1267      }1268      case "TEST_SUBNET_SCAN": {1269        const subnet = await getLocalSubnet();1270        if (!subnet) return { ok: false, error: "no_subnet" };1271        const start = Date.now();1272        const result = await discoverDevice(subnet, "000000000000000000000000000000000000000000000000000000000000000000");1273        return { ok: true, data: { elapsed: Date.now() - start, found: !!result } };1274      }1275      case 'TEST_WS_LOCAL': {1276        const { ip } = msg.payload as { ip: string };12771278        return new Promise((resolve) => {1279          const log: string[] = [];1280          log.push(`Attempting ws://${ip}:44100 from service worker...`);12811282          let ws: WebSocket;1283          let settled = false;1284          const settle = (result: MessageResponse) => {1285            if (!settled) { settled = true; resolve(result); }1286          };12871288          try {1289            ws = new WebSocket(`ws://${ip}:44100`);12901291            ws.onopen = () => {1292              log.push('SUCCESS: WebSocket connected');1293              ws.close();1294              settle({ ok: true, data: { log } });1295            };12961297            ws.onerror = (e) => {1298              log.push(`FAILED: onerror fired — ${String(e)}`);1299              settle({ ok: false, error: 'ws_error', data: { log } });1300            };13011302            ws.onclose = (e) => {1303              if (e.code !== 1000) {1304                log.push(`CLOSED unexpectedly: code=${e.code} reason=${e.reason}`);1305                settle({ ok: false, error: 'ws_closed', data: { code: e.code, log } });1306              }1307            };13081309            setTimeout(() => {1310              try { ws.close(); } catch {}1311              log.push('FAILED: 5 second timeout — connection never opened');1312              settle({ ok: false, error: 'timeout', data: { log } });1313            }, 5000);13141315          } catch (err) {1316            log.push(`FAILED: WebSocket constructor threw — ${String(err)}`);1317            settle({ ok: false, error: 'constructor_threw', data: { log } });1318          }1319        });1320      }13211322      case 'TEST_SUBNET_DETECT': {1323        return new Promise((resolve) => {1324          try {1325            // RTCPeerConnection availability varies by context — this is what we're testing1326            // eslint-disable-next-line @typescript-eslint/no-explicit-any1327            const RTC = (globalThis as any).RTCPeerConnection as (new (cfg: object) => RTCPeerConnection) | undefined;1328            if (!RTC) {1329              resolve({ ok: false, error: 'RTCPeerConnection is not defined' });1330              return;1331            }1332            const pc = new RTC({ iceServers: [] });1333            pc.createDataChannel('');1334            pc.createOffer().then((o) => pc.setLocalDescription(o));13351336            const candidates: string[] = [];1337            const timer = setTimeout(() => {1338              pc.close();1339              if (candidates.length === 0) {1340                resolve({ ok: false, error: 'no_candidates', data: { candidates } });1341              } else {1342                const subnet = candidates[0].match(/(\d+\.\d+\.\d+)\.\d+/)?.[1];1343                resolve({ ok: true, data: { subnet, candidates } });1344              }1345            }, 2000);13461347            pc.onicecandidate = (e) => {1348              if (!e.candidate) return;1349              const m = e.candidate.candidate.match(/(\d+\.\d+\.\d+\.\d+)/);1350              if (m && !m[1].startsWith('127')) candidates.push(m[1]);1351            };13521353            pc.onicegatheringstatechange = () => {1354              if (pc.iceGatheringState === 'complete') {1355                clearTimeout(timer);1356                pc.close();1357                const subnet = candidates[0]?.match(/(\d+\.\d+\.\d+)\.\d+/)?.[1];1358                resolve({ ok: candidates.length > 0, data: { subnet, candidates } });1359              }1360            };1361          } catch (err) {1362            resolve({ ok: false, error: String(err) });1363          }1364        });1365      }13661367      // --- end test handlers ---1368      default:1369        return { ok: false, error: "unknown message type" };1370    }1371  } catch (err) {1372    return {1373      ok: false,1374      error: err instanceof Error ? err.message : "operation failed",1375    };1376  }1377}13781379// --- Mobile platform helpers ---13801381// Android: populates the in-memory vault used by PeachAutofillService.1382async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1383  const plugin = nativePlugin<{1384    setEntries?: (args: {1385      entries: Array<{1386        id: string;1387        title: string;1388        username: string;1389        email: string;1390        password: string;1391        url: string;1392        totp: string;1393        additionalUrls: string[];1394      }>;1395    }) => Promise<void>;1396  }>("InMemoryVaultPlugin");1397  if (!plugin?.setEntries) return;1398  await plugin.setEntries({1399    entries: entries.map((e) => ({1400      id: e.id,1401      title: e.title ?? "",1402      username: e.username ?? "",1403      email: (e as VaultEntry & { email?: string }).email ?? "",1404      password: e.password ?? "",1405      url: e.url ?? "",1406      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1407      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1408    })),1409  });1410}14111412// Android: clear the autofill in-memory store on lock.1413async function clearInMemoryVault(): Promise<void> {1414  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1415  if (!plugin?.clearEntries) return;1416  await plugin.clearEntries();1417}14181419interface SyncBridge {1420  ensureServerRunning?: () => void;1421  startPairingSession?: (args: { token: string }) => void;1422  getLocalIp?: () => Promise<{ ip: string }>;1423  sendToConnection?: (args: { connectionId: string; data: string }) => Promise<void>;1424  addListener?: (event: string, handler: (data: Record<string, string>) => void) => void;1425}14261427// Resolve the Capacitor SyncPlugin at call time — module-load resolution1428// races with Capacitor's plugin registration on the Android WebView.1429function syncBridge(): SyncBridge | null {1430  return nativePlugin<SyncBridge>("SyncPlugin");1431}14321433// Build a SyncTransport for the Android responder path — the phone's WS server1434// already has an open connection from the desktop. We send back via1435// SyncPlugin.sendToConnection and receive via the peach:sync-frame queue.1436const androidSyncFrameQueues = new Map<string, Array<(frame: string) => void>>();14371438export function deliverAndroidSyncFrame(connectionId: string, frame: string): void {1439  const queue = androidSyncFrameQueues.get(connectionId);1440  if (queue?.length) queue.shift()!(frame);1441}14421443function createAndroidResponderTransport(connectionId: string) {1444  const pendingReceivers: Array<(frame: string) => void> = [];1445  androidSyncFrameQueues.set(connectionId, pendingReceivers);14461447  return {1448    send: async (data: Uint8Array) => {1449      await syncBridge()?.sendToConnection?.({ connectionId, data: bytesToBase64(data) });1450    },1451    receive: (): Promise<Uint8Array> => new Promise((res) => {1452      pendingReceivers.push((frame) => {1453        res(frame ? base64ToBytes(frame) : new Uint8Array(0));1454      });1455    }),1456    close: async () => {1457      androidSyncFrameQueues.delete(connectionId);1458    },1459  };1460}14611462// Returns username use-counts from the vault, sorted by frequency. Each row1463// also carries the entry's email so the popup can suggest the email/username1464// pair the user has actually used together.1465function buildIdentitySuggestions(1466  entries: VaultEntry[],1467): Array<{ email: string; username: string; count: number }> {1468  const usernameCounts = new Map<string, number>();1469  const usernameEmail = new Map<string, string>();1470  for (const entry of entries) {1471    const username = entry.username ?? "";1472    const email = (entry as VaultEntry & { email?: string }).email ?? "";1473    if (!username && !email) continue;1474    const key = username || email;1475    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1476    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1477  }1478  return Array.from(usernameCounts.entries())1479    .sort((a, b) => b[1] - a[1])1480    .map(([username, count]) => ({1481      email: usernameEmail.get(username) ?? "",1482      username,1483      count,1484    }));1485}14861487/** Notify all content scripts that the vault just became available. */1488function broadcastToContentScripts(message: { type: string }): void {1489  if (!chrome.tabs?.query) return;1490  chrome.tabs.query({}, (tabs) => {1491    for (const tab of tabs) {1492      if (tab.id !== undefined) {1493        chrome.tabs.sendMessage(tab.id, message).catch(() => {1494          // Tab may not have a content script — silently ignore1495        });1496      }1497    }1498  });1499}15001501function shouldRefreshAutoLock(type: MessageType): boolean {1502  return (1503    type !== "HAS_VAULT" &&1504    type !== "IS_UNLOCKED" &&1505    type !== "GET_VAULT_STATUS" &&1506    type !== "LOCK" &&1507    type !== "UPDATE_SETTINGS" &&1508    type !== "GET_PENDING_PASSKEY" &&1509    type !== "GET_PASSKEY_PROVIDER_STATE" &&1510    type !== "DECLINE_CARD_SAVE" &&1511    type !== "IS_CARD_DECLINED" &&1512    type !== "SUBMIT_FEEDBACK"1513  );1514}15151516function isAllowedCanaryWebhookUrl(value: string): boolean {1517  try {1518    const url = new URL(value);1519    if (url.protocol !== "https:") return false;15201521    const hostname = url.hostname.toLowerCase();1522    if (1523      hostname === "localhost" ||1524      hostname.endsWith(".localhost") ||1525      isPrivateIpv4(hostname) ||1526      isPrivateIpv6(hostname)1527    ) {1528      return false;1529    }15301531    return true;1532  } catch {1533    return false;1534  }1535}15361537function isPrivateIpv4(hostname: string): boolean {1538  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1539    return true;1540  }15411542  const octets = hostname.split(".").map((part) => Number(part));1543  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1544    return false;1545  }15461547  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1548}15491550function isPrivateIpv6(hostname: string): boolean {1551  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1552  return (1553    normalized === "::1" ||1554    normalized.startsWith("fc") ||1555    normalized.startsWith("fd") ||1556    normalized.startsWith("fe80:")1557  );1558}