messages.ts

53.9 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 "GET_ADVANCED_HEALTH_REPORT": {740        const gate = await requirePro("advanced_health");741        if (!gate.allowed) return { ok: false, error: "pro_required" };742        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };743        const report = await buildAdvancedHealthReport(vault.getEntries());744        return { ok: true, data: report };745      }746      case "INITIATE_PASSWORD_CHANGE": {747        const gate = await requirePro("smart_password_change");748        if (!gate.allowed) return { ok: false, error: "pro_required" };749        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };750        const { id } = msg.payload as { id: string };751        const entry = vault.getEntryById(id);752        if (!entry) return { ok: false, error: "entry not found" };753        const url = resolveResetUrl(entry);754        if (!url) return { ok: false, error: "no reset url" };755        try {756          await chrome.tabs.create({ url });757          return { ok: true, data: { url } };758        } catch (err) {759          return {760            ok: false,761            error: err instanceof Error ? err.message : "failed to open tab",762          };763        }764      }765      case "IS_DURESS_ENABLED": {766        const enabled = await vault.isDuressEnabled();767        return { ok: true, data: enabled };768      }769      case "SETUP_DURESS": {770        const { duressPassword } = msg.payload as { duressPassword: string };771        await vault.setupDuress(duressPassword);772        return { ok: true };773      }774      case "DISABLE_DURESS": {775        await vault.disableDuress();776        return { ok: true };777      }778      case "VERIFY_MAIN_PASSWORD": {779        const { password } = msg.payload as { password: string };780        const ok = await vault.verifyMainPassword(password);781        return { ok: true, data: ok };782      }783      case "CHANGE_PASSWORD": {784        const { currentPassword, newPassword } = msg.payload as {785          currentPassword: string;786          newPassword: string;787        };788        const changed = await vault.changePassword(currentPassword, newPassword);789        return changed790          ? { ok: true }791          : { ok: false, error: "incorrect current password" };792      }793      case "GET_SITE_PASSWORD_POLICY": {794        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });795        if (!tab?.id) return { ok: true, data: null };796        try {797          const response = await chrome.tabs.sendMessage(tab.id, {798            type: "GET_SITE_PASSWORD_POLICY",799          });800          return (response as MessageResponse) ?? { ok: true, data: null };801        } catch {802          return { ok: true, data: null };803        }804      }805      case "GET_SYNC_STATE": {806        const pairedDevices = await getPairedDevices();807        const trustedNetworks = await getTrustedNetworks();808        const tailscale = await isOnTailscale();809        const pro = await isProUser();810811        let status: SyncStatus = "offline";812        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {813          if (pairedDevices.length === 0) {814            status = "no_peers";815          } else {816            status = "synced";817          }818        } else {819          status = "not_trusted";820        }821822        const lastSyncRaw = await storageGet("peach_last_sync_at");823        const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN;824        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined;825826        return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } };827      }828      case "GET_PAIRED_DEVICES": {829        const devices = await getPairedDevices();830        return { ok: true, data: { devices } };831      }832      case "GET_SYNC_STATUS": {833        const lastSyncRaw = await storageGet("peach_last_sync_at");834        const lastSyncParsed = lastSyncRaw ? parseInt(lastSyncRaw, 10) : NaN;835        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : null;836        const status: 'up_to_date' | 'never' = lastSyncAt ? 'up_to_date' : 'never';837        return { ok: true, data: { status, lastSyncAt } };838      }839      case "ACCEPT_PAIRING": {840        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.841        return { ok: true };842      }843      case "REMOVE_PAIRED_DEVICE": {844        const { deviceId } = msg.payload as { deviceId: string };845        await removePairedDevice(deviceId);846        return { ok: true };847      }848      case "REMOVE_TRUSTED_NETWORK": {849        const { ssid, bssid, isTailscale } = msg.payload as any;850        const networks = await getTrustedNetworks();851        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 852          (isTailscale ? n.isTailscale : n.ssid === ssid) && 853          (!bssid || n.bssid === bssid)854        );855        if (network) {856          await removeTrustedNetwork(network.addedAt);857        }858        return { ok: true };859      }860      case "MARK_NETWORK_TRUSTED": {861        const network = await getCurrentNetwork();862        await addTrustedNetwork({863          ssid: network.ssid,864          bssid: network.bssid,865          isTailscale: network.isTailscale,866          addedAt: Date.now(),867        });868        return { ok: true };869      }870      case "GET_INCOMING_PAIRING_REQUEST": {871        const request = await getIncomingPairingRequest();872        return { ok: true, data: request };873      }874      case "RESPOND_INCOMING_PAIRING": {875        const { accept } = msg.payload as { accept: boolean };876        const request = await getIncomingPairingRequest();877        if (!request) return { ok: false, error: "no_pending_request" };878        if (Date.now() > request.expiresAt) {879          await clearIncomingPairingRequest();880          return { ok: false, error: "expired" };881        }882        await clearIncomingPairingRequest();883        if (accept) {884          await addPairedDevice({885            deviceId: request.publicKeyHex,886            displayName: request.deviceName,887            x25519PublicKey: request.publicKeyHex,888            pairedAt: Date.now(),889            lastSeenAt: Date.now(),890          });891        }892        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };893      }894      case "START_PAIRING_SERVER": {895        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.896        const token = generateSixDigitToken();897        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;898        await setActivePairingToken({ token, expiresAt });899        // Fire-and-forget subnet scan — finds the phone after it scans the QR900        // and calls SCAN_PAIRING_QR to register the token with SyncPlugin.901        if (!isNativePlatform()) {902          void runPairingSubnetScan(token);903        }904        return { ok: true, data: { token, expiresAt } };905      }906      case "STOP_PAIRING_SERVER": {907        try {908          await setActivePairingToken(null);909        } catch { /* best-effort */ }910        return { ok: true };911      }912      case "GET_RECENT_PAIRING": {913        const recent = await consumeRecentPairing();914        return { ok: true, data: recent };915      }916      case "DEBUG_INJECT_INCOMING_PAIRING": {917        // Manual E2E rehearsal hook. Inserts a synthetic incoming pairing918        // request into session storage so Phase 7 banner UX can be exercised919        // without a live native host. No Pro gate — this is a no-op in920        // production unless explicitly invoked from a Settings debug action.921        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {922          deviceName?: string;923          publicKeyHex?: string;924        };925        if (!deviceName || !publicKeyHex) {926          return { ok: false, error: "missing_payload" };927        }928        const now = Date.now();929        await setIncomingPairingRequest({930          deviceName,931          publicKeyHex,932          receivedAt: now,933          expiresAt: now + 60_000,934        });935        return { ok: true };936      }937      case "RESET_SYNC_IDENTITY": {938        const gate = await requirePro("sync");939        if (!gate.allowed) return { ok: false, error: "pro_required" };940        const devices = await getPairedDevices();941        for (const device of devices) {942          await removePairedDevice(device.deviceId);943        }944        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };945      }946      case "RECORD_MANUAL_SUMMON": {947        const { domain } = msg.payload as { domain: string };948        const settings = vault.getSettings();949        const existing = settings.manualSummonDomains?.[domain];950        const now = Date.now();951        await vault.updateSettings({952          manualSummonDomains: {953            ...settings.manualSummonDomains,954            [domain]: {955              firstSummonedAt: existing?.firstSummonedAt ?? now,956              summonCount: (existing?.summonCount ?? 0) + 1,957              lastSummonedAt: now,958            },959          },960        });961        return { ok: true };962      }963      case "DECLINE_CARD_SAVE": {964        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };965        await vault.declineCardSaveOffer(last4, expMonth, expYear);966        return { ok: true };967      }968      case "IS_CARD_DECLINED": {969        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };970        const declined = await vault.isCardDeclined(last4, expMonth, expYear);971        return { ok: true, data: declined };972      }973      case "INITIATE_FIREFOX_PASSKEY_CREATE": {974        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {975          rpId?: string;976          rpName?: string;977          userName?: string;978          userDisplayName?: string;979        };980        if (!rpId || !userName) return { ok: false, error: "rpId and userName required" };981        return await initiateFirefoxPasskeyCreate({982          rpId,983          rpName: rpName ?? rpId,984          userName,985          userDisplayName,986        });987      }988989      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {990        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;991        if (!payload) return { ok: false, error: "missing payload" };992        return await completeFirefoxPasskeyCreate(payload);993      }994995      case "PASSKEY_OFFER_DECLINE": {996        const { domain } = (msg.payload ?? {}) as { domain?: string };997        if (!domain) return { ok: false, error: "domain required" };998        await recordPasskeyOfferDecline(domain);999        return { ok: true };1000      }10011002      case "GET_PASSKEY_OFFER_DECLINED": {1003        const { domain } = (msg.payload ?? {}) as { domain?: string };1004        if (!domain) return { ok: false, error: "domain required" };1005        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1006      }10071008      case "PASSKEY_HAS_CREDENTIALS": {1009        const payload = msg.payload as {1010          rpId?: string;1011          allowCredentials?: Array<{ id: string; type?: string }>;1012        } | undefined;1013        if (!payload?.rpId) return { ok: false, error: "rpId required" };1014        return await handlePasskeyHasCredentials({1015          rpId: payload.rpId,1016          allowCredentials: payload.allowCredentials ?? [],1017        });1018      }10191020      case "PASSKEY_CREATE": {1021        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1022        if (!payload?.rpId || !payload?.userName) {1023          return { ok: false, error: "rpId and userName required" };1024        }1025        return await handleFirefoxPasskeyCreate(payload);1026      }10271028      case "PASSKEY_GET": {1029        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1030        if (!payload?.rpId) return { ok: false, error: "rpId required" };1031        return await handleFirefoxPasskeyGet(payload);1032      }10331034      case "GET_PASSKEY_FOR_DOMAIN": {1035        const { domain } = (msg.payload ?? {}) as { domain?: string };1036        if (!domain) return { ok: false, error: "domain required" };1037        if (!vault.isUnlocked()) return { ok: true, data: null };1038        const match = vault1039          .getEntries()1040          .find((entry) => entry.passkey?.rpId === domain);1041        if (!match || !match.passkey) return { ok: true, data: null };1042        // Slim shape — only the fields State 11 needs. Never expose private1043        // key material, even though this is locked behind isUnlocked.1044        return {1045          ok: true,1046          data: {1047            rpId: match.passkey.rpId,1048            userName: match.passkey.userName,1049            browser: match.passkey.browser,1050          },1051        };1052      }10531054      case "DESTROY_VAULT": {1055        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1056        // storage.local.clear() wipes every Peach key (slots, settings, license,1057        // onboarded flag, history, sync state, declined cards, recall, etc.);1058        // session.clear() wipes pending passkey requests + pro-notice queues.1059        // Caller (Panic.tsx) handles UI navigation back to onboarding.1060        vault.lock();1061        await storageClear();1062        await vault.clearVaultHistory();1063        if (chrome.storage.session) {1064          await chrome.storage.session.clear();1065        }1066        return { ok: true };1067      }10681069      case "SUBMIT_FEEDBACK": {1070        const { category, message, version, browser } = msg.payload as {1071          category: string;1072          message: string;1073          version: string;1074          browser: string;1075        };1076        if (!message.trim()) return { ok: false, error: "message is empty" };1077        if (!FEEDBACK_ENDPOINT) return { ok: true };1078        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1079          return { ok: false, error: "invalid feedback endpoint" };1080        }1081        try {1082          const res = await fetch(FEEDBACK_ENDPOINT, {1083            method: "POST",1084            headers: { "Content-Type": "application/json" },1085            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1086          });1087          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1088        } catch (err) {1089          return { ok: false, error: err instanceof Error ? err.message : "network error" };1090        }1091      }1092      case "TRIGGER_SYNC": {1093        const gate = await requirePro("sync");1094        if (!gate.allowed) return { ok: false, error: "pro_required" };1095        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };10961097        if (isNativePlatform()) {1098          // Phone is the server — ensure it's listening for desktop connections.1099          syncBridge()?.ensureServerRunning?.();1100          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };1101        }11021103        // Desktop: iterate all paired devices and sync with each.1104        const paired = await getPairedDevices();1105        if (!paired.length) return { ok: true, data: { syncedCount: 0, reason: "no_paired_devices" } };11061107        const subnet = await getLocalSubnet();1108        const results: Array<{ device: string } & SyncResult> = [];11091110        for (const device of paired) {1111          if (!device.x25519PublicKey) continue;11121113          let result: SyncResult;11141115          // Fast path — use last known IP1116          if (device.lastKnownIp) {1117            result = await doVaultSync(device.lastKnownIp, device.x25519PublicKey);1118          } else {1119            result = { status: 'errored', applied: false, error: 'no_ip' };1120          }11211122          // Discovery path — scan if fast path failed1123          if (result.status === 'errored' && subnet) {1124            const newIp = await discoverDevice(subnet, device.x25519PublicKey);1125            if (newIp) {1126              await updatePairedDevice(device.x25519PublicKey, { lastKnownIp: newIp });1127              result = await doVaultSync(newIp, device.x25519PublicKey);1128            }1129          }11301131          if (result.status === 'completed') {1132            await updatePairedDevice(device.x25519PublicKey, {1133              lastSeenAt: Date.now(),1134              lastSyncAt: Date.now(),1135            });1136          }11371138          results.push({ device: device.displayName, ...result });1139        }11401141        const syncedCount = results.filter(r => r.status === 'completed').length;1142        if (syncedCount > 0) {1143          await chrome.storage.local.set({ peach_last_sync_at: String(Date.now()) });1144        }1145        return { ok: true, data: { syncedCount, results } };1146      }1147      // Android-only: biometric unlock with pre-derived key.1148      case "UNLOCK_WITH_KEY": {1149        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1150        if (!isNativePlatform()) {1151          return { ok: false, error: "desktop_only_uses_password" };1152        }1153        try {1154          const result = await vault.unlockWithKey(masterKeyHex);1155          if (result.ok) await publishInMemoryVault(result.entries);1156          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1157        } catch {1158          return { ok: false, error: "invalid_key" };1159        }1160      }1161      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1162      case "GET_DERIVED_KEY": {1163        if (!isNativePlatform()) {1164          return { ok: false, error: "android_only" };1165        }1166        if (!vault.isUnlocked()) {1167          return { ok: false, error: "vault_locked" };1168        }1169        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1170      }1171      // Android: scanned a QR containing a desktop pairing token.1172      case "SCAN_PAIRING_QR": {1173        if (!isNativePlatform()) {1174          return { ok: false, error: "android_only" };1175        }1176        const { token } = msg.payload as { token: string };1177        syncBridge()?.startPairingSession?.({ token });1178        return { ok: true };1179      }1180      // Android: desktop opened a sync connection to the phone's WS server.1181      // Run the responder side of the vault exchange.1182      case "SYNC_SESSION_STARTED": {1183        if (!isNativePlatform()) return { ok: false };1184        if (!vault.isUnlocked()) {1185          return { ok: false, error: "vault_locked" };1186        }1187        const { connectionId } = (msg.payload ?? {}) as { connectionId?: string };1188        if (!connectionId) return { ok: false, error: "missing_connection_id" };11891190        const transport = createAndroidResponderTransport(connectionId);1191        const result = await runBlobSyncSession('responder', transport, buildSyncDeps());1192        if (result.applied) {1193          await publishInMemoryVault(vault.getEntries());1194        }1195        return { ok: true, data: result };1196      }1197      // Android: returns the phone's WiFi IP address.1198      case "GET_LOCAL_IP": {1199        if (!isNativePlatform()) {1200          return { ok: false, error: "android_only" };1201        }1202        const { ip } = (await syncBridge()?.getLocalIp?.()) ?? { ip: "" };1203        return { ok: true, data: { ip } };1204      }1205      case "GET_IDENTITY_SUGGESTIONS": {1206        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1207        const entries = vault.getEntries();1208        const suggestions = buildIdentitySuggestions(entries);1209        return { ok: true, data: { suggestions } };1210      }1211      case "POPULATE_INLINE_VAULT": {1212        if (!isNativePlatform()) return { ok: false };1213        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1214        const entries = vault.getEntries();1215        await publishInMemoryVault(entries);1216        return { ok: true };1217      }1218      // --- PNA compatibility test handlers — REMOVE BEFORE RELEASE ---1219      case "TEST_LOCAL_WEBSOCKET": {1220        const { ip } = (msg.payload ?? {}) as { ip?: string };1221        if (!ip) return { ok: false, error: "ip required" };1222        return new Promise((resolve) => {1223          try {1224            const ws = new WebSocket(`ws://${ip}:44100`);1225            ws.onopen = () => { ws.close(); resolve({ ok: true, data: { connected: true } }); };1226            ws.onerror = () => resolve({ ok: false, error: "connection_failed" });1227            setTimeout(() => { ws.close(); resolve({ ok: false, error: "timeout" }); }, 3000);1228          } catch (err) {1229            resolve({ ok: false, error: String(err) });1230          }1231        });1232      }1233      case "TEST_SUBNET_DETECTION": {1234        const subnet = await getLocalSubnet();1235        return { ok: true, data: { subnet } };1236      }1237      case "TEST_SUBNET_SCAN": {1238        const subnet = await getLocalSubnet();1239        if (!subnet) return { ok: false, error: "no_subnet" };1240        const start = Date.now();1241        const result = await discoverDevice(subnet, "000000000000000000000000000000000000000000000000000000000000000000");1242        return { ok: true, data: { elapsed: Date.now() - start, found: !!result } };1243      }1244      // --- end test handlers ---1245      default:1246        return { ok: false, error: "unknown message type" };1247    }1248  } catch (err) {1249    return {1250      ok: false,1251      error: err instanceof Error ? err.message : "operation failed",1252    };1253  }1254}12551256// --- Mobile platform helpers ---12571258// Android: populates the in-memory vault used by PeachAutofillService.1259async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1260  const plugin = nativePlugin<{1261    setEntries?: (args: {1262      entries: Array<{1263        id: string;1264        title: string;1265        username: string;1266        email: string;1267        password: string;1268        url: string;1269        totp: string;1270        additionalUrls: string[];1271      }>;1272    }) => Promise<void>;1273  }>("InMemoryVaultPlugin");1274  if (!plugin?.setEntries) return;1275  await plugin.setEntries({1276    entries: entries.map((e) => ({1277      id: e.id,1278      title: e.title ?? "",1279      username: e.username ?? "",1280      email: (e as VaultEntry & { email?: string }).email ?? "",1281      password: e.password ?? "",1282      url: e.url ?? "",1283      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1284      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1285    })),1286  });1287}12881289// Android: clear the autofill in-memory store on lock.1290async function clearInMemoryVault(): Promise<void> {1291  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1292  if (!plugin?.clearEntries) return;1293  await plugin.clearEntries();1294}12951296interface SyncBridge {1297  ensureServerRunning?: () => void;1298  startPairingSession?: (args: { token: string }) => void;1299  getLocalIp?: () => Promise<{ ip: string }>;1300  sendToConnection?: (args: { connectionId: string; data: string }) => Promise<void>;1301  addListener?: (event: string, handler: (data: Record<string, string>) => void) => void;1302}13031304// Resolve the Capacitor SyncPlugin at call time — module-load resolution1305// races with Capacitor's plugin registration on the Android WebView.1306function syncBridge(): SyncBridge | null {1307  return nativePlugin<SyncBridge>("SyncPlugin");1308}13091310// Build a SyncTransport for the Android responder path — the phone's WS server1311// already has an open connection from the desktop. We send back via1312// SyncPlugin.sendToConnection and receive via the peach:sync-frame queue.1313const androidSyncFrameQueues = new Map<string, Array<(frame: string) => void>>();13141315export function deliverAndroidSyncFrame(connectionId: string, frame: string): void {1316  const queue = androidSyncFrameQueues.get(connectionId);1317  if (queue?.length) queue.shift()!(frame);1318}13191320function createAndroidResponderTransport(connectionId: string) {1321  const pendingReceivers: Array<(frame: string) => void> = [];1322  androidSyncFrameQueues.set(connectionId, pendingReceivers);13231324  return {1325    send: async (data: Uint8Array) => {1326      await syncBridge()?.sendToConnection?.({ connectionId, data: bytesToBase64(data) });1327    },1328    receive: (): Promise<Uint8Array> => new Promise((res) => {1329      pendingReceivers.push((frame) => {1330        res(frame ? base64ToBytes(frame) : new Uint8Array(0));1331      });1332    }),1333    close: async () => {1334      androidSyncFrameQueues.delete(connectionId);1335    },1336  };1337}13381339// Returns username use-counts from the vault, sorted by frequency. Each row1340// also carries the entry's email so the popup can suggest the email/username1341// pair the user has actually used together.1342function buildIdentitySuggestions(1343  entries: VaultEntry[],1344): Array<{ email: string; username: string; count: number }> {1345  const usernameCounts = new Map<string, number>();1346  const usernameEmail = new Map<string, string>();1347  for (const entry of entries) {1348    const username = entry.username ?? "";1349    const email = (entry as VaultEntry & { email?: string }).email ?? "";1350    if (!username && !email) continue;1351    const key = username || email;1352    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1353    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1354  }1355  return Array.from(usernameCounts.entries())1356    .sort((a, b) => b[1] - a[1])1357    .map(([username, count]) => ({1358      email: usernameEmail.get(username) ?? "",1359      username,1360      count,1361    }));1362}13631364/** Notify all content scripts that the vault just became available. */1365function broadcastToContentScripts(message: { type: string }): void {1366  if (!chrome.tabs?.query) return;1367  chrome.tabs.query({}, (tabs) => {1368    for (const tab of tabs) {1369      if (tab.id !== undefined) {1370        chrome.tabs.sendMessage(tab.id, message).catch(() => {1371          // Tab may not have a content script — silently ignore1372        });1373      }1374    }1375  });1376}13771378function shouldRefreshAutoLock(type: MessageType): boolean {1379  return (1380    type !== "HAS_VAULT" &&1381    type !== "IS_UNLOCKED" &&1382    type !== "GET_VAULT_STATUS" &&1383    type !== "LOCK" &&1384    type !== "UPDATE_SETTINGS" &&1385    type !== "GET_PENDING_PASSKEY" &&1386    type !== "GET_PASSKEY_PROVIDER_STATE" &&1387    type !== "DECLINE_CARD_SAVE" &&1388    type !== "IS_CARD_DECLINED" &&1389    type !== "SUBMIT_FEEDBACK"1390  );1391}13921393function isAllowedCanaryWebhookUrl(value: string): boolean {1394  try {1395    const url = new URL(value);1396    if (url.protocol !== "https:") return false;13971398    const hostname = url.hostname.toLowerCase();1399    if (1400      hostname === "localhost" ||1401      hostname.endsWith(".localhost") ||1402      isPrivateIpv4(hostname) ||1403      isPrivateIpv6(hostname)1404    ) {1405      return false;1406    }14071408    return true;1409  } catch {1410    return false;1411  }1412}14131414function isPrivateIpv4(hostname: string): boolean {1415  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1416    return true;1417  }14181419  const octets = hostname.split(".").map((part) => Number(part));1420  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1421    return false;1422  }14231424  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1425}14261427function isPrivateIpv6(hostname: string): boolean {1428  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1429  return (1430    normalized === "::1" ||1431    normalized.startsWith("fc") ||1432    normalized.startsWith("fd") ||1433    normalized.startsWith("fe80:")1434  );1435}