messages.ts

59.2 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  onVaultUnlocked,35  recordPasskeyOfferDecline,36  resolvePendingPasskeyRequest,37  setPasskeyProviderEnabled,38} from "./passkey";39import { buildAdvancedHealthReport, resolveResetUrl } from "./health";40import { storageClear, storageGet } from "../shared/storage";41import { findInvalidWords } from "../shared/recovery-words";42import {43  addPairedDevice,44  addTrustedNetwork,45  clearIncomingPairingRequest,46  getIncomingPairingRequest,47  getPairedDevices,48  getTrustedNetworks,49  removePairedDevice,50  removeTrustedNetwork,51  setIncomingPairingRequest,52  updatePairedDevice,53} from "./sync-storage";54import { getCurrentNetwork, isOnTailscale } from "./sync-network";55import {56  consumeRecentPairing,57  setActivePairingToken,58} from "./pairing-server-state";59import type {60  Message,61  MessageResponse,62  MessageType,63  ProFeature,64  VaultEntry,65} from "../shared/types";66import { isPasskeyOnly } from "../shared/types";67import type { SyncStatus, SyncableDevice } from "../shared/sync-types";68import { isNativePlatform, nativePlugin } from "../shared/native";69import { runBlobSyncSession, type SyncResult } from "./sync-coordinator";70import type { SyncDeps } from "./sync-coordinator";71import { createWebSocketSyncTransport } from "../shared/websocket-sync-transport";72import { getLocalSubnet, discoverDevice, scanForPairingPhone } from "../shared/local-network";73import { base64ToBytes, bytesToBase64 } from "../shared/sync-wire";7475/**76 * The single Pro gate. Every gated handler calls this first; the broadcast77 * lets the popup react (navigate to the License section, highlight the78 * relevant feature). Background never touches the popup view directly —79 * the popup owns navigation. See Projects.md "Pro gate rule".80 */81async function requirePro(82  feature: ProFeature,83  trigger: "user" | "background" = "user"84): Promise<{ allowed: boolean }> {85  if (await isProUser()) return { allowed: true };8687  if (trigger === "user") {88    // User deliberately triggered this feature — redirect the popup immediately.89    chrome.runtime90      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })91      .catch(() => {92        // Popup may be closed — the gate signal is best-effort.93      });94  } else {95    // Background trigger (e.g. passive sync initiation) — no popup is open.96    // Queue a notice so the next popup open shows a soft banner instead of97    // silently failing.98    if (chrome.storage.session) {99      chrome.storage.session100        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })101        .catch(() => {});102    }103  }104105  return { allowed: false };106}107108// ---------------------------------------------------------------------------109// Local device name. Peers see this string in PAIR_REQUEST / PAIR_ACCEPT and110// next to the device in their paired-devices list. Default to a platform-aware111// fallback when the user hasn't set one explicitly.112const DEVICE_NAME_KEY = "peach_device_name";113114async function getLocalDeviceName(): Promise<string> {115  try {116    const stored = await chrome.storage.local.get(DEVICE_NAME_KEY);117    const value = (stored as Record<string, string | undefined>)[DEVICE_NAME_KEY];118    if (typeof value === "string" && value.trim()) return value.trim();119  } catch {120    // fall through to default121  }122  return "Peach";123}124125// ---------------------------------------------------------------------------126// 6-digit code pairing.127128const PAIRING_TOKEN_TTL_MS = 5 * 60 * 1000;129130131function generateSixDigitToken(): string {132  // crypto.getRandomValues, not Math.random — the token is the only secret133  // protecting the pairing window from a same-LAN attacker. 6 decimal digits134  // is 1 in 1,000,000; combined with a 5-minute TTL and pairing-mode gating135  // on the responder this is the right tradeoff between UX and security.136  const buf = new Uint32Array(1);137  crypto.getRandomValues(buf);138  const value = buf[0] % 1_000_000;139  return value.toString().padStart(6, "0");140}141142// ---------------------------------------------------------------------------143// Peer discovery glue (Phase 7 popup pairing flow).144145const PRIVATE_IPV4_RANGES = [146  { prefix: "10." },147  { prefix: "127." },148  { prefix: "169.254." },149  { prefix: "192.168." },150];151152// Empty disables network submission while the UI continues to function as a153// no-op (the handler returns ok:true without calling fetch). When set, the154// URL is validated by `isAllowedCanaryWebhookUrl` before any request, so the155// same private-IP/HTTPS rules that gate canary webhooks apply here.156const FEEDBACK_ENDPOINT = "";157158// ---------------------------------------------------------------------------159// Sync helpers160// ---------------------------------------------------------------------------161162function buildSyncDeps(): SyncDeps {163  return {164    isVaultUnlocked: () => vault.isUnlocked(),165    getVaultBlobForSync: async () => {166      const base = await vault.getVaultBlobForSync();167      if (!base) return null;168      const paired = await getPairedDevices();169      return {170        ...base,171        devices: paired172          .filter(d => d.x25519PublicKey)173          .map(d => ({174            publicKeyHex: d.x25519PublicKey,175            deviceName: d.displayName,176            pairedAt: d.pairedAt,177          })),178      };179    },180    applyIncomingVault: async (blob, ts, license, devices) => {181      const applied = await vault.applyIncomingVault(blob, ts, license);182      if (devices?.length) await mergeDeviceRegistry(devices);183      if (applied) await vault.reloadEntriesAfterSync();184      return applied;185    },186  };187}188189async function doVaultSync(ip: string, publicKeyHex: string): Promise<SyncResult> {190  try {191    const transport = await createWebSocketSyncTransport(`ws://${ip}:44100`, publicKeyHex);192    return await runBlobSyncSession('initiator', transport, buildSyncDeps());193  } catch (err) {194    return { status: 'errored', applied: false, error: String(err) };195  }196}197198async function mergeDeviceRegistry(incoming: SyncableDevice[]): Promise<void> {199  const existing = await getPairedDevices();200  const existingKeys = new Set(existing.map(d => d.x25519PublicKey));201  for (const device of incoming) {202    if (!existingKeys.has(device.publicKeyHex)) {203      await addPairedDevice({204        deviceId: device.publicKeyHex,205        displayName: device.deviceName,206        x25519PublicKey: device.publicKeyHex,207        pairedAt: device.pairedAt,208        lastSeenAt: 0,209        lastKnownIp: '',210      }).catch(() => {});211    }212  }213}214215// Background pairing scan — runs after START_PAIRING_SERVER fires on desktop.216// Scans the local subnet for a phone that has accepted the pairing token,217// stores it, runs the initial vault exchange, then notifies the popup.218async function runPairingSubnetScan(token: string): Promise<void> {219  const subnet = await getLocalSubnet();220  if (!subnet) return;221222  const found = await scanForPairingPhone(subnet, token);223  if (!found) return;224225  const { ip, publicKeyHex } = found;226227  try {228    await addPairedDevice({229      deviceId: publicKeyHex,230      displayName: 'Peach',231      x25519PublicKey: publicKeyHex,232      pairedAt: Date.now(),233      lastSeenAt: Date.now(),234      lastKnownIp: ip,235    });236  } catch {237    // Already paired — update IP238    await updatePairedDevice(publicKeyHex, { lastKnownIp: ip, lastSeenAt: Date.now() });239  }240241  // Immediate vault exchange — the free one-time transfer242  await doVaultSync(ip, publicKeyHex);243244  chrome.runtime.sendMessage({245    type: 'PAIRING_COMPLETED',246    payload: { deviceName: 'Peach', publicKeyHex, deviceIp: ip },247  }).catch(() => {});248}249250export function setupMessageHandler(): void {251  chrome.runtime.onMessage.addListener(252    (msg: unknown, sender, sendResponse) => {253      if (!isMessage(msg)) {254        sendResponse({ ok: false, error: "invalid message" });255        return true;256      }257      handleMessage(msg, sender)258        .then(sendResponse)259        .catch((err) =>260          sendResponse({261            ok: false,262            error: err instanceof Error ? err.message : String(err),263          })264        );265      return true;266    }267  );268269  // Android: the chrome shim queues sendMessage calls until this handler is270  // registered. Without this hookup, every message hangs on Capacitor builds.271  // eslint-disable-next-line @typescript-eslint/no-explicit-any272  const reg = (globalThis as any).__peachRegisterMessageHandler;273  if (typeof reg === "function") {274    reg(async (m: unknown) => {275      if (!isMessage(m)) return { ok: false, error: "invalid message" };276      try {277        return await handleMessage(m);278      } catch (err) {279        return {280          ok: false,281          error: err instanceof Error ? err.message : String(err),282        };283      }284    });285  }286287  // Android: subscribe to SyncPlugin events.288  if (isNativePlatform()) {289    const syncPlug = nativePlugin<{290      addListener: (291        event: string,292        handler: (data: Record<string, string>) => void293      ) => void;294    }>("SyncPlugin");295296    // Pairing probe answered — store the paired device (desktop, no IP needed297    // since the desktop never acts as a WS server).298    syncPlug?.addListener?.("peach:pair-probe-answered", (data) => {299      const deviceName = data.deviceName ?? "Peach";300      const publicKeyHex = data.publicKeyHex ?? "";301      void (async () => {302        const { addPairedDevice, setHasPaired: setPaired } = await import("./sync-storage");303        await addPairedDevice({304          deviceId: publicKeyHex || (data.connectionId ?? "unknown"),305          displayName: deviceName,306          x25519PublicKey: publicKeyHex,307          pairedAt: Date.now(),308          lastSeenAt: Date.now(),309        }).catch(() => {});310        await setPaired();311        chrome.runtime.sendMessage({312          type: "PAIRING_COMPLETED",313          payload: { deviceName },314        }).catch(() => {});315      })();316    });317318    // Sync frame received — route to the waiting responder session.319    syncPlug?.addListener?.("peach:sync-frame", (data) => {320      const { connectionId, frame } = data;321      if (connectionId && frame) deliverAndroidSyncFrame(connectionId, frame);322    });323324    // Sync session started (SYNC_HELLO received by SyncPlugin) — dispatch as325    // a background message so SYNC_SESSION_STARTED handler runs the responder.326    syncPlug?.addListener?.("peach:sync-session-started", (data) => {327      const { connectionId } = data;328      if (!connectionId) return;329      void handleMessage({ type: "SYNC_SESSION_STARTED", payload: { connectionId } });330    });331  }332}333334function isMessage(m: unknown): m is Message {335  return typeof m === "object" && m !== null && "type" in m;336}337338export async function handleMessage(339  msg: Message,340  sender: Partial<chrome.runtime.MessageSender> = {}341): Promise<MessageResponse> {342  try {343    // Validate sender — only allow messages from our extension pages/scripts.344    // `sender.id` is undefined for messages originating from extension UI345    // (popup/options), which is legitimate; reject only when it is defined346    // and does not match our extension id.347    if (348      sender.id !== undefined &&349      sender.id !== chrome.runtime.id350    ) {351      return { ok: false, error: "invalid sender" };352    }353354    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {355      touchAutoLock();356    }357358    switch (msg.type) {359      case "CREATE_VAULT": {360        const { password } = msg.payload as { password: string };361        await vault.createVault(password);362        await setupAutoLock();363        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });364        onVaultUnlocked();365        return { ok: true };366      }367      case "UNLOCK": {368        const { password } = msg.payload as { password: string };369        const ok = await vault.unlock(password);370        if (ok) {371          await setupAutoLock();372          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });373          onVaultUnlocked();374          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());375        }376        return { ok };377      }378      case "VALIDATE_RECOVERY_WORDS": {379        const { words } = msg.payload as { words: string[] };380        const invalid = findInvalidWords(words);381        return { ok: true, data: { valid: invalid.length === 0, invalid } };382      }383      case "GET_RECOVERY_WORDS": {384        // Must be unlocked and have recovery set up (vault must be v2.12+).385        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };386        try {387          const words = await vault.getRecoveryWords();388          return { ok: true, data: words };389        } catch (e) {390          // pre-v2.12 vault that hasn't migrated391          return { ok: false, error: "recovery_not_setup" };392        }393      }394      case "RECOVER_WITH_WORDS": {395        // User has lost their password but has their 12 recovery words.396        // We: (1) validate the words, (2) re-encrypt vault with new password.397        const { words, newPassword } = msg.payload as {398          words: string[];399          newPassword: string;400        };401        const stored = await vault.loadSlotA();402        if (!stored) return { ok: false, error: "no vault" };403        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {404          return { ok: false, error: "recovery_not_setup" };405        }406        // Unwrap the root key from the recovery escrow.407        try {408          await vault.unwrapRootKeyForRecovery(409            stored.recovery_wrapped_root_key,410            stored.recovery_nonce ?? "",411            stored.recovery_tag ?? "",412            stored.recovery_salt,413            words414          );415        } catch {416          return { ok: false, error: "invalid_recovery_words" };417        }418        // Re-key: derive fresh salt + key from new password.419        const newSalt = vault.generateSalt();420        const newKey = await vault.deriveKey(newPassword, newSalt);421        // Re-wrap root key under the new password's derived key so the same422        // recovery words continue to work after the password change.423        await vault.rewrapRootKeyForPassword(newKey, newSalt);424        // Re-encrypt vault entries with the new key.425        await vault.changePasswordWithNewKey(newSalt, newKey);426        await setupAutoLock();427        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });428        return { ok: true };429      }430      case "LOCK":431        vault.lock();432        if (isNativePlatform()) await clearInMemoryVault();433        return { ok: true };434      case "IS_UNLOCKED":435        return { ok: true, data: vault.isUnlocked() };436      case "GET_VAULT_STATUS":437        return { ok: true, unlocked: vault.isUnlocked() };438      case "HAS_VAULT":439        return { ok: true, data: await vault.hasVault() };440      case "GET_ENTRIES":441        return { ok: true, data: vault.getEntries() };442      case "ADD_ENTRY": {443        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };444        const entry = await vault.addEntry(msg.payload as any);445        return { ok: true, data: entry };446      }447      case "BATCH_ADD_ENTRIES": {448        const { entries } = msg.payload as { entries: any[] };449        const added = await vault.batchAddEntries(entries);450        return { ok: true, data: added };451      }452      case "RESTORE_ENTRIES": {453        const { entries, mode, settings } = msg.payload as {454          entries: any[];455          mode: "replace" | "merge";456          settings?: vault.VaultSettings;457        };458        const summary = await vault.restoreEntries(entries, mode);459        if (settings && typeof settings === "object") {460          await vault.updateSettings(settings);461        }462        return { ok: true, data: summary };463      }464      case "CLEAR_VAULT_ENTRIES": {465        await vault.clearVaultEntries("REPLACE_ALL");466        return { ok: true };467      }468      case "GET_VAULT_HISTORY": {469        const snapshots = await vault.getVaultHistory();470        return { ok: true, data: snapshots };471      }472      case "RESTORE_VAULT_SNAPSHOT": {473        const { snapshotId } = msg.payload as { snapshotId: string };474        const result = await vault.restoreVaultSnapshot(snapshotId);475        if (!result.ok) return { ok: false, error: result.error };476        broadcastToContentScripts({ type: "VAULT_LOCKED" });477        return { ok: true };478      }479      case "COUNT_DUPLICATES": {480        return { ok: true, data: vault.countDuplicates() };481      }482      case "DEDUPLICATE_ENTRIES": {483        const removed = await vault.deduplicateEntries();484        return { ok: true, data: removed };485      }486      case "UPDATE_ENTRY": {487        const { id, patch } = msg.payload as any;488        await vault.updateEntry(id, patch);489        return { ok: true };490      }491      case "ADD_ADDITIONAL_URL": {492        const { id, url } = msg.payload as { id: string; url: string };493        const trimmed = typeof url === "string" ? url.trim() : "";494        if (!trimmed) return { ok: false, error: "url required" };495        const existing = vault.getEntryById(id);496        if (!existing) return { ok: false, error: "entry not found" };497        if (existing.type !== "login") return { ok: false, error: "login entries only" };498        const merged = [...(existing.additionalUrls ?? []), trimmed];499        await vault.updateEntry(id, { additionalUrls: merged });500        return { ok: true };501      }502      case "DELETE_ENTRY": {503        const { id } = msg.payload as { id: string };504        await vault.deleteEntry(id);505        return { ok: true };506      }507      case "GET_DELETED_ENTRIES":508        return { ok: true, data: vault.getDeletedEntries() };509      case "RESTORE_ENTRY": {510        const { id } = msg.payload as { id: string };511        await vault.restoreEntry(id);512        return { ok: true };513      }514      case "PURGE_ENTRY": {515        const { id } = msg.payload as { id: string };516        await vault.purgeEntry(id);517        return { ok: true };518      }519      case "PURGE_EXPIRED_TRASH": {520        const { retentionMs } = msg.payload as { retentionMs: number };521        const purged = await vault.purgeExpiredTrash(retentionMs);522        return { ok: true, data: purged };523      }524      case "SAVE_NOTE": {525        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };526        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };527        const now = Date.now();528        if (id) {529          const existing = vault.getEntryById(id);530          if (!existing) return { ok: false, error: "not_found" };531          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });532          return { ok: true, data: vault.getEntryById(id) };533        } else {534          const entry = await vault.addEntry({535            type: "note",536            title: title || "Untitled",537            notes: body,538            createdAt: now,539            modifiedAt: now,540          } as any);541          return { ok: true, data: entry };542        }543      }544      case "DELETE_NOTE": {545        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };546        const { id } = msg.payload as { id: string };547        await vault.deleteEntry(id);548        return { ok: true };549      }550      case "AUTOFILL_QUERY": {551        if (!vault.isUnlocked()) {552          return { ok: false, error: "VAULT_LOCKED" };553        }554        const { domain, includeAll, kind } = msg.payload as {555          domain: string;556          includeAll?: boolean;557          kind?: "login" | "card";558        };559        // kind="card": return saved cards as compact summaries for the560        // inline card silver platter. Cards are not domain-scoped — every561        // saved card is a candidate on every checkout page — so domain is562        // ignored when kind === "card".563        if (kind === "card") {564          const cards = vault.getEntries().filter((e) => e.type === "card");565          return {566            ok: true,567            data: cards.map((e) => ({568              id: e.id,569              title: e.cardNickname || e.title,570              cardholderName: e.cardholderName,571              last4: e.last4,572              expMonth: e.expMonth,573              expYear: e.expYear,574              network: e.network,575            })),576          };577        }578        // The inline selector fills username+password into a form. Passkey-579        // only entries have no password to fill; sign-in for those goes580        // through the WebAuthn path instead. Filter them out everywhere so581        // the user doesn't see four "GitHub" rows that mostly do nothing.582        // Notes and cards never belonged here either.583        const matches = (584          includeAll585            ? vault586                .getEntries()587                .filter((entry) => entry.type !== "note" && entry.type !== "card")588            : vault.queryDomain(domain)589        ).filter((entry) => !isPasskeyOnly(entry));590        return {591          ok: true,592          data: matches.map((e) =>593            includeAll594              ? {595                  id: e.id,596                  title: e.title,597                  hasPasskey: e.passkey !== undefined,598                }599              : {600                  id: e.id,601                  title: e.title,602                  username: e.username,603                  email: e.email,604                  url: e.url,605                  hasTotp: Boolean(e.totp),606                  hasPasskey: e.passkey !== undefined,607                }608          ),609        };610      }611      case "GET_ENTRY_FOR_FILL": {612        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };613        const { id } = msg.payload as { id: string };614        const entry = vault.getEntryById(id);615        if (!entry) return { ok: false, error: "entry not found" };616        // Passkey-only entries (passkey credential, no password) cannot be617        // filled into a form — sign-in goes through the WebAuthn path. A618        // login that ALSO has a passkey is still fillable for its password.619        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey not fillable" };620        // Strip the passkey credential from the response — content scripts621        // never need the private key, and there's no reason to expose the622        // public credential metadata over the boundary either.623        const { passkey: _strippedPasskey, ...safeEntry } = entry;624        return { ok: true, data: safeEntry };625      }626      case "COPY": {627        const { text, label, alreadyWritten } = msg.payload as {628          text: string;629          label: string;630          alreadyWritten?: boolean;631        };632        await copyToClipboard(text, label, Boolean(alreadyWritten));633        return { ok: true };634      }635      case "CHECK_ALL_BREACHES": {636        const allEntries = vault.getEntries();637        const results: Record<string, number> = {};638        for (const entry of allEntries) {639          if (entry.type === "note") continue;640          if (!entry.password) continue;641          results[entry.id] = await vault.checkBreach(entry.password);642          // Small delay — be a good citizen to the HIBP API643          await new Promise((r) => setTimeout(r, 200));644        }645        // Persist any non-zero counts back to entries646        for (const [id, count] of Object.entries(results)) {647          const entry = vault.getEntryById(id);648          if (entry && (entry.breach ?? 0) !== count) {649            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });650          }651        }652        return { ok: true, data: results };653      }654      case "GET_SETTINGS":655        return { ok: true, data: await vault.ensureSettingsLoaded() };656      case "UPDATE_SETTINGS": {657        const patch = msg.payload as Record<string, unknown>;658        await vault.updateSettings(patch as any);659        if (typeof patch.autoLockMinutes === "number") {660          await setupAutoLock();661          if (vault.isUnlocked()) touchAutoLock();662        }663        return { ok: true };664      }665      case "GET_PENDING_PASSKEY":666        return { ok: true, data: await getPendingPasskeyRequest() };667      case "APPROVE_PASSKEY": {668        const { requestId } = msg.payload as { requestId: number };669        await resolvePendingPasskeyRequest(requestId, true);670        return { ok: true };671      }672      case "DENY_PASSKEY": {673        const { requestId } = msg.payload as { requestId: number };674        await resolvePendingPasskeyRequest(requestId, false);675        return { ok: true };676      }677      case "GET_PASSKEY_PROVIDER_STATE":678        return { ok: true, data: await getPasskeyProviderState() };679      case "SET_PASSKEY_PROVIDER_ENABLED": {680        const { enabled } = msg.payload as { enabled: boolean };681        // Disabling is always free; gating fires only when a free user is682        // trying to turn passkey interception on.683        if (enabled) {684          const gate = await requirePro("passkeys");685          if (!gate.allowed) return { ok: false, error: "pro_required" };686        }687        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };688      }689      case "FIRE_CANARY_PING": {690        const { webhookUrl, entryTitle, trigger } = msg.payload as {691          webhookUrl: string;692          entryTitle: string;693          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";694        };695        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {696          return { ok: false, error: "invalid webhook url" };697        }698        const body = JSON.stringify({699          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",700          entry: entryTitle,701          trigger,702          timestamp: new Date().toISOString(),703          source: "peach-extension",704        });705        if (trigger === "test") {706          // Permitted outbound fetch: user-configured canary alert endpoint707          // (validated by isAllowedCanaryWebhookUrl above). This is the708          // only non-HIBP outbound call in the extension — see709          // Projects.md §3.7. Test pings are awaited so the UI can show710          // success/failure.711          try {712            const res = await fetch(webhookUrl, {713              method: "POST",714              headers: { "Content-Type": "application/json" },715              body,716            });717            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };718          } catch (err) {719            return { ok: false, error: err instanceof Error ? err.message : "network error" };720          }721        }722        // Non-test triggers are fire-and-forget723        fetch(webhookUrl, {724          method: "POST",725          headers: { "Content-Type": "application/json" },726          body,727        }).catch(() => {});728        return { ok: true };729      }730      case "ACTIVATE_LICENSE": {731        const { key } = msg.payload as { key: string };732        const licenseInfo = await activateLicense(key);733        return { ok: true, data: licenseInfo };734      }735      case "GET_LICENSE": {736        const licenseInfo = await getLicenseInfo();737        return { ok: true, data: licenseInfo };738      }739      case "GET_LICENSE_KEY": {740        const key = await getLicenseKey();741        return { ok: true, data: key };742      }743      case "DEACTIVATE_LICENSE": {744        await deactivateLicense();745        return { ok: true };746      }747      case "SHOULD_PLAY_CELEBRATION": {748        const should = await shouldPlayCelebration();749        return { ok: true, data: should };750      }751      case "MARK_CELEBRATION_PLAYED": {752        await markCelebrationPlayed();753        return { ok: true };754      }755      case "OPEN_PRO_GATE": {756        // Content script requests: open popup and navigate to License section.757        const { feature } = (msg.payload ?? {}) as { feature?: string };758        if (chrome.storage.session) {759          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });760        }761        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }762        return { ok: true };763      }764      case "GET_IDENTITIES": {765        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };766        return { ok: true, data: vault.getIdentities() };767      }768      case "TOUCH_AUTO_LOCK": {769        // touchAutoLock() is already called by shouldRefreshAutoLock above;770        // this case just gives the popup a typed message to keep the session alive.771        return { ok: true };772      }773      case "GET_ADVANCED_HEALTH_REPORT": {774        const gate = await requirePro("advanced_health");775        if (!gate.allowed) return { ok: false, error: "pro_required" };776        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };777        const report = await buildAdvancedHealthReport(vault.getEntries());778        return { ok: true, data: report };779      }780      case "INITIATE_PASSWORD_CHANGE": {781        const gate = await requirePro("smart_password_change");782        if (!gate.allowed) return { ok: false, error: "pro_required" };783        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };784        const { id } = msg.payload as { id: string };785        const entry = vault.getEntryById(id);786        if (!entry) return { ok: false, error: "entry not found" };787        const url = resolveResetUrl(entry);788        if (!url) return { ok: false, error: "no reset url" };789        try {790          await chrome.tabs.create({ url });791          return { ok: true, data: { url } };792        } catch (err) {793          return {794            ok: false,795            error: err instanceof Error ? err.message : "failed to open tab",796          };797        }798      }799      case "IS_DURESS_ENABLED": {800        const enabled = await vault.isDuressEnabled();801        return { ok: true, data: enabled };802      }803      case "SETUP_DURESS": {804        const { duressPassword } = msg.payload as { duressPassword: string };805        await vault.setupDuress(duressPassword);806        return { ok: true };807      }808      case "DISABLE_DURESS": {809        await vault.disableDuress();810        return { ok: true };811      }812      case "VERIFY_MAIN_PASSWORD": {813        const { password } = msg.payload as { password: string };814        const ok = await vault.verifyMainPassword(password);815        return { ok: true, data: ok };816      }817      case "CHANGE_PASSWORD": {818        const { currentPassword, newPassword } = msg.payload as {819          currentPassword: string;820          newPassword: string;821        };822        const changed = await vault.changePassword(currentPassword, newPassword);823        return changed824          ? { ok: true }825          : { ok: false, error: "incorrect current password" };826      }827      case "GET_SITE_PASSWORD_POLICY": {828        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });829        if (!tab?.id) return { ok: true, data: null };830        try {831          const response = await chrome.tabs.sendMessage(tab.id, {832            type: "GET_SITE_PASSWORD_POLICY",833          });834          return (response as MessageResponse) ?? { ok: true, data: null };835        } catch {836          return { ok: true, data: null };837        }838      }839      case "GET_SYNC_STATE": {840        const pairedDevices = await getPairedDevices();841        const trustedNetworks = await getTrustedNetworks();842        const tailscale = await isOnTailscale();843        const pro = await isProUser();844845        let status: SyncStatus = "offline";846        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {847          if (pairedDevices.length === 0) {848            status = "no_peers";849          } else {850            status = "synced";851          }852        } else {853          status = "not_trusted";854        }855856        const lastSyncRaw = await storageGet("peach_last_sync_at");857        const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN;858        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined;859860        return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } };861      }862      case "GET_PAIRED_DEVICES": {863        const devices = await getPairedDevices();864        return { ok: true, data: { devices } };865      }866      case "GET_SYNC_STATUS": {867        const lastSyncRaw = await storageGet("peach_last_sync_at");868        const lastSyncParsed = lastSyncRaw ? parseInt(lastSyncRaw, 10) : NaN;869        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : null;870        const status: 'up_to_date' | 'never' = lastSyncAt ? 'up_to_date' : 'never';871        return { ok: true, data: { status, lastSyncAt } };872      }873      case "ACCEPT_PAIRING": {874        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.875        return { ok: true };876      }877      case "REMOVE_PAIRED_DEVICE": {878        const { deviceId } = msg.payload as { deviceId: string };879        await removePairedDevice(deviceId);880        return { ok: true };881      }882      case "REMOVE_TRUSTED_NETWORK": {883        const { ssid, bssid, isTailscale } = msg.payload as any;884        const networks = await getTrustedNetworks();885        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 886          (isTailscale ? n.isTailscale : n.ssid === ssid) && 887          (!bssid || n.bssid === bssid)888        );889        if (network) {890          await removeTrustedNetwork(network.addedAt);891        }892        return { ok: true };893      }894      case "MARK_NETWORK_TRUSTED": {895        const network = await getCurrentNetwork();896        await addTrustedNetwork({897          ssid: network.ssid,898          bssid: network.bssid,899          isTailscale: network.isTailscale,900          addedAt: Date.now(),901        });902        return { ok: true };903      }904      case "GET_INCOMING_PAIRING_REQUEST": {905        const request = await getIncomingPairingRequest();906        return { ok: true, data: request };907      }908      case "RESPOND_INCOMING_PAIRING": {909        const { accept } = msg.payload as { accept: boolean };910        const request = await getIncomingPairingRequest();911        if (!request) return { ok: false, error: "no_pending_request" };912        if (Date.now() > request.expiresAt) {913          await clearIncomingPairingRequest();914          return { ok: false, error: "expired" };915        }916        await clearIncomingPairingRequest();917        if (accept) {918          await addPairedDevice({919            deviceId: request.publicKeyHex,920            displayName: request.deviceName,921            x25519PublicKey: request.publicKeyHex,922            pairedAt: Date.now(),923            lastSeenAt: Date.now(),924          });925        }926        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };927      }928      case "START_PAIRING_SERVER": {929        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.930        const token = generateSixDigitToken();931        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;932        await setActivePairingToken({ token, expiresAt });933        // Fire-and-forget subnet scan — finds the phone after it scans the QR934        // and calls SCAN_PAIRING_QR to register the token with SyncPlugin.935        if (!isNativePlatform()) {936          void runPairingSubnetScan(token);937        }938        return { ok: true, data: { token, expiresAt } };939      }940      case "STOP_PAIRING_SERVER": {941        try {942          await setActivePairingToken(null);943        } catch { /* best-effort */ }944        return { ok: true };945      }946      case "GET_RECENT_PAIRING": {947        const recent = await consumeRecentPairing();948        return { ok: true, data: recent };949      }950      case "DEBUG_INJECT_INCOMING_PAIRING": {951        // Manual E2E rehearsal hook. Inserts a synthetic incoming pairing952        // request into session storage so Phase 7 banner UX can be exercised953        // without a live native host. No Pro gate — this is a no-op in954        // production unless explicitly invoked from a Settings debug action.955        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {956          deviceName?: string;957          publicKeyHex?: string;958        };959        if (!deviceName || !publicKeyHex) {960          return { ok: false, error: "missing_payload" };961        }962        const now = Date.now();963        await setIncomingPairingRequest({964          deviceName,965          publicKeyHex,966          receivedAt: now,967          expiresAt: now + 60_000,968        });969        return { ok: true };970      }971      case "RESET_SYNC_IDENTITY": {972        const gate = await requirePro("sync");973        if (!gate.allowed) return { ok: false, error: "pro_required" };974        const devices = await getPairedDevices();975        for (const device of devices) {976          await removePairedDevice(device.deviceId);977        }978        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };979      }980      case "RECORD_MANUAL_SUMMON": {981        const { domain } = msg.payload as { domain: string };982        const settings = vault.getSettings();983        const existing = settings.manualSummonDomains?.[domain];984        const now = Date.now();985        await vault.updateSettings({986          manualSummonDomains: {987            ...settings.manualSummonDomains,988            [domain]: {989              firstSummonedAt: existing?.firstSummonedAt ?? now,990              summonCount: (existing?.summonCount ?? 0) + 1,991              lastSummonedAt: now,992            },993          },994        });995        return { ok: true };996      }997      case "DECLINE_CARD_SAVE": {998        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };999        await vault.declineCardSaveOffer(last4, expMonth, expYear);1000        return { ok: true };1001      }1002      case "IS_CARD_DECLINED": {1003        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1004        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1005        return { ok: true, data: declined };1006      }1007      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1008        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1009          rpId?: string;1010          rpName?: string;1011          userName?: string;1012          userDisplayName?: string;1013        };1014        if (!rpId || !userName) return { ok: false, error: "rpId and userName required" };1015        return await initiateFirefoxPasskeyCreate({1016          rpId,1017          rpName: rpName ?? rpId,1018          userName,1019          userDisplayName,1020        });1021      }10221023      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1024        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1025        if (!payload) return { ok: false, error: "missing payload" };1026        return await completeFirefoxPasskeyCreate(payload);1027      }10281029      case "PASSKEY_OFFER_DECLINE": {1030        const { domain } = (msg.payload ?? {}) as { domain?: string };1031        if (!domain) return { ok: false, error: "domain required" };1032        await recordPasskeyOfferDecline(domain);1033        return { ok: true };1034      }10351036      case "GET_PASSKEY_OFFER_DECLINED": {1037        const { domain } = (msg.payload ?? {}) as { domain?: string };1038        if (!domain) return { ok: false, error: "domain required" };1039        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1040      }10411042      case "PASSKEY_HAS_CREDENTIALS": {1043        const payload = msg.payload as {1044          rpId?: string;1045          allowCredentials?: Array<{ id: string; type?: string }>;1046        } | undefined;1047        if (!payload?.rpId) return { ok: false, error: "rpId required" };1048        return await handlePasskeyHasCredentials({1049          rpId: payload.rpId,1050          allowCredentials: payload.allowCredentials ?? [],1051        });1052      }10531054      case "PASSKEY_CREATE": {1055        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1056        if (!payload?.rpId || !payload?.userName) {1057          return { ok: false, error: "rpId and userName required" };1058        }1059        return await handleFirefoxPasskeyCreate(payload);1060      }10611062      case "PASSKEY_GET": {1063        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1064        if (!payload?.rpId) return { ok: false, error: "rpId required" };1065        return await handleFirefoxPasskeyGet(payload);1066      }10671068      case "PASSKEY_AUTH_RESPONSE": {1069        const { requestId, approved } = (msg.payload ?? {}) as {1070          requestId?: string;1071          approved?: boolean;1072        };1073        if (!requestId || typeof approved !== 'boolean') {1074          return { ok: false, error: 'requestId and approved required' };1075        }1076        await resolvePendingPasskeyRequest(Number(requestId), approved);1077        return { ok: true };1078      }10791080      case "GET_PASSKEY_FOR_DOMAIN": {1081        const { domain } = (msg.payload ?? {}) as { domain?: string };1082        if (!domain) return { ok: false, error: "domain required" };1083        if (!vault.isUnlocked()) return { ok: true, data: null };1084        const match = vault1085          .getEntries()1086          .find((entry) => entry.passkey?.rpId === domain);1087        if (!match || !match.passkey) return { ok: true, data: null };1088        // Slim shape — only the fields State 11 needs. Never expose private1089        // key material, even though this is locked behind isUnlocked.1090        return {1091          ok: true,1092          data: {1093            rpId: match.passkey.rpId,1094            userName: match.passkey.userName,1095            browser: match.passkey.browser,1096          },1097        };1098      }10991100      case "DESTROY_VAULT": {1101        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1102        // storage.local.clear() wipes every Peach key (slots, settings, license,1103        // onboarded flag, history, sync state, declined cards, recall, etc.);1104        // session.clear() wipes pending passkey requests + pro-notice queues.1105        // Caller (Panic.tsx) handles UI navigation back to onboarding.1106        vault.lock();1107        await storageClear();1108        await vault.clearVaultHistory();1109        if (chrome.storage.session) {1110          await chrome.storage.session.clear();1111        }1112        return { ok: true };1113      }11141115      case "SUBMIT_FEEDBACK": {1116        const { category, message, version, browser } = msg.payload as {1117          category: string;1118          message: string;1119          version: string;1120          browser: string;1121        };1122        if (!message.trim()) return { ok: false, error: "message is empty" };1123        if (!FEEDBACK_ENDPOINT) return { ok: true };1124        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1125          return { ok: false, error: "invalid feedback endpoint" };1126        }1127        try {1128          const res = await fetch(FEEDBACK_ENDPOINT, {1129            method: "POST",1130            headers: { "Content-Type": "application/json" },1131            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1132          });1133          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1134        } catch (err) {1135          return { ok: false, error: err instanceof Error ? err.message : "network error" };1136        }1137      }1138      case "TRIGGER_SYNC": {1139        const gate = await requirePro("sync");1140        if (!gate.allowed) return { ok: false, error: "pro_required" };1141        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };11421143        if (isNativePlatform()) {1144          // Phone is the server — ensure it's listening for desktop connections.1145          syncBridge()?.ensureServerRunning?.();1146          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };1147        }11481149        // Desktop: iterate all paired devices and sync with each.1150        const paired = await getPairedDevices();1151        if (!paired.length) return { ok: true, data: { syncedCount: 0, reason: "no_paired_devices" } };11521153        const subnet = await getLocalSubnet();1154        const results: Array<{ device: string } & SyncResult> = [];11551156        for (const device of paired) {1157          if (!device.x25519PublicKey) continue;11581159          let result: SyncResult;11601161          // Fast path — use last known IP1162          if (device.lastKnownIp) {1163            result = await doVaultSync(device.lastKnownIp, device.x25519PublicKey);1164          } else {1165            result = { status: 'errored', applied: false, error: 'no_ip' };1166          }11671168          // Discovery path — scan if fast path failed1169          if (result.status === 'errored' && subnet) {1170            const newIp = await discoverDevice(subnet, device.x25519PublicKey);1171            if (newIp) {1172              await updatePairedDevice(device.x25519PublicKey, { lastKnownIp: newIp });1173              result = await doVaultSync(newIp, device.x25519PublicKey);1174            }1175          }11761177          if (result.status === 'completed') {1178            await updatePairedDevice(device.x25519PublicKey, {1179              lastSeenAt: Date.now(),1180              lastSyncAt: Date.now(),1181            });1182          }11831184          results.push({ device: device.displayName, ...result });1185        }11861187        const syncedCount = results.filter(r => r.status === 'completed').length;1188        if (syncedCount > 0) {1189          await chrome.storage.local.set({ peach_last_sync_at: String(Date.now()) });1190        }1191        return { ok: true, data: { syncedCount, results } };1192      }1193      // Android-only: biometric unlock with pre-derived key.1194      case "UNLOCK_WITH_KEY": {1195        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1196        if (!isNativePlatform()) {1197          return { ok: false, error: "desktop_only_uses_password" };1198        }1199        try {1200          const result = await vault.unlockWithKey(masterKeyHex);1201          if (result.ok) {1202            onVaultUnlocked();1203            await publishInMemoryVault(result.entries);1204          }1205          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1206        } catch {1207          return { ok: false, error: "invalid_key" };1208        }1209      }1210      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1211      case "GET_DERIVED_KEY": {1212        if (!isNativePlatform()) {1213          return { ok: false, error: "android_only" };1214        }1215        if (!vault.isUnlocked()) {1216          return { ok: false, error: "vault_locked" };1217        }1218        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1219      }1220      // Android: scanned a QR containing a desktop pairing token.1221      case "SCAN_PAIRING_QR": {1222        if (!isNativePlatform()) {1223          return { ok: false, error: "android_only" };1224        }1225        const { token } = msg.payload as { token: string };1226        syncBridge()?.startPairingSession?.({ token });1227        return { ok: true };1228      }1229      // Android: desktop opened a sync connection to the phone's WS server.1230      // Run the responder side of the vault exchange.1231      case "SYNC_SESSION_STARTED": {1232        if (!isNativePlatform()) return { ok: false };1233        if (!vault.isUnlocked()) {1234          return { ok: false, error: "vault_locked" };1235        }1236        const { connectionId } = (msg.payload ?? {}) as { connectionId?: string };1237        if (!connectionId) return { ok: false, error: "missing_connection_id" };12381239        const transport = createAndroidResponderTransport(connectionId);1240        const result = await runBlobSyncSession('responder', transport, buildSyncDeps());1241        if (result.applied) {1242          await publishInMemoryVault(vault.getEntries());1243        }1244        return { ok: true, data: result };1245      }1246      // Android: returns the phone's WiFi IP address.1247      case "GET_LOCAL_IP": {1248        if (!isNativePlatform()) {1249          return { ok: false, error: "android_only" };1250        }1251        const { ip } = (await syncBridge()?.getLocalIp?.()) ?? { ip: "" };1252        return { ok: true, data: { ip } };1253      }1254      case "GET_IDENTITY_SUGGESTIONS": {1255        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1256        const entries = vault.getEntries();1257        const suggestions = buildIdentitySuggestions(entries);1258        return { ok: true, data: { suggestions } };1259      }1260      case "POPULATE_INLINE_VAULT": {1261        if (!isNativePlatform()) return { ok: false };1262        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1263        const entries = vault.getEntries();1264        await publishInMemoryVault(entries);1265        return { ok: true };1266      }1267      // --- PNA compatibility test handlers — REMOVE BEFORE RELEASE ---1268      case "TEST_LOCAL_WEBSOCKET": {1269        const { ip } = (msg.payload ?? {}) as { ip?: string };1270        if (!ip) return { ok: false, error: "ip required" };1271        return new Promise((resolve) => {1272          try {1273            const ws = new WebSocket(`ws://${ip}:44100`);1274            ws.onopen = () => { ws.close(); resolve({ ok: true, data: { connected: true } }); };1275            ws.onerror = () => resolve({ ok: false, error: "connection_failed" });1276            setTimeout(() => { ws.close(); resolve({ ok: false, error: "timeout" }); }, 3000);1277          } catch (err) {1278            resolve({ ok: false, error: String(err) });1279          }1280        });1281      }1282      case "TEST_SUBNET_DETECTION": {1283        const subnet = await getLocalSubnet();1284        return { ok: true, data: { subnet } };1285      }1286      case "TEST_SUBNET_SCAN": {1287        const subnet = await getLocalSubnet();1288        if (!subnet) return { ok: false, error: "no_subnet" };1289        const start = Date.now();1290        const result = await discoverDevice(subnet, "000000000000000000000000000000000000000000000000000000000000000000");1291        return { ok: true, data: { elapsed: Date.now() - start, found: !!result } };1292      }1293      case 'TEST_WS_LOCAL': {1294        const { ip } = msg.payload as { ip: string };12951296        return new Promise((resolve) => {1297          const log: string[] = [];1298          log.push(`Attempting ws://${ip}:44100 from service worker...`);12991300          let ws: WebSocket;1301          let settled = false;1302          const settle = (result: MessageResponse) => {1303            if (!settled) { settled = true; resolve(result); }1304          };13051306          try {1307            ws = new WebSocket(`ws://${ip}:44100`);13081309            ws.onopen = () => {1310              log.push('SUCCESS: WebSocket connected');1311              ws.close();1312              settle({ ok: true, data: { log } });1313            };13141315            ws.onerror = (e) => {1316              log.push(`FAILED: onerror fired — ${String(e)}`);1317              settle({ ok: false, error: 'ws_error', data: { log } });1318            };13191320            ws.onclose = (e) => {1321              if (e.code !== 1000) {1322                log.push(`CLOSED unexpectedly: code=${e.code} reason=${e.reason}`);1323                settle({ ok: false, error: 'ws_closed', data: { code: e.code, log } });1324              }1325            };13261327            setTimeout(() => {1328              try { ws.close(); } catch {}1329              log.push('FAILED: 5 second timeout — connection never opened');1330              settle({ ok: false, error: 'timeout', data: { log } });1331            }, 5000);13321333          } catch (err) {1334            log.push(`FAILED: WebSocket constructor threw — ${String(err)}`);1335            settle({ ok: false, error: 'constructor_threw', data: { log } });1336          }1337        });1338      }13391340      case 'TEST_SUBNET_DETECT': {1341        return new Promise((resolve) => {1342          try {1343            // RTCPeerConnection availability varies by context — this is what we're testing1344            // eslint-disable-next-line @typescript-eslint/no-explicit-any1345            const RTC = (globalThis as any).RTCPeerConnection as (new (cfg: object) => RTCPeerConnection) | undefined;1346            if (!RTC) {1347              resolve({ ok: false, error: 'RTCPeerConnection is not defined' });1348              return;1349            }1350            const pc = new RTC({ iceServers: [] });1351            pc.createDataChannel('');1352            pc.createOffer().then((o) => pc.setLocalDescription(o));13531354            const candidates: string[] = [];1355            const timer = setTimeout(() => {1356              pc.close();1357              if (candidates.length === 0) {1358                resolve({ ok: false, error: 'no_candidates', data: { candidates } });1359              } else {1360                const subnet = candidates[0].match(/(\d+\.\d+\.\d+)\.\d+/)?.[1];1361                resolve({ ok: true, data: { subnet, candidates } });1362              }1363            }, 2000);13641365            pc.onicecandidate = (e) => {1366              if (!e.candidate) return;1367              const m = e.candidate.candidate.match(/(\d+\.\d+\.\d+\.\d+)/);1368              if (m && !m[1].startsWith('127')) candidates.push(m[1]);1369            };13701371            pc.onicegatheringstatechange = () => {1372              if (pc.iceGatheringState === 'complete') {1373                clearTimeout(timer);1374                pc.close();1375                const subnet = candidates[0]?.match(/(\d+\.\d+\.\d+)\.\d+/)?.[1];1376                resolve({ ok: candidates.length > 0, data: { subnet, candidates } });1377              }1378            };1379          } catch (err) {1380            resolve({ ok: false, error: String(err) });1381          }1382        });1383      }13841385      // --- end test handlers ---1386      default:1387        return { ok: false, error: "unknown message type" };1388    }1389  } catch (err) {1390    return {1391      ok: false,1392      error: err instanceof Error ? err.message : "operation failed",1393    };1394  }1395}13961397// --- Mobile platform helpers ---13981399// Android: populates the in-memory vault used by PeachAutofillService.1400async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1401  const plugin = nativePlugin<{1402    setEntries?: (args: {1403      entries: Array<{1404        id: string;1405        title: string;1406        username: string;1407        email: string;1408        password: string;1409        url: string;1410        totp: string;1411        additionalUrls: string[];1412      }>;1413    }) => Promise<void>;1414  }>("InMemoryVaultPlugin");1415  if (!plugin?.setEntries) return;1416  await plugin.setEntries({1417    entries: entries.map((e) => ({1418      id: e.id,1419      title: e.title ?? "",1420      username: e.username ?? "",1421      email: (e as VaultEntry & { email?: string }).email ?? "",1422      password: e.password ?? "",1423      url: e.url ?? "",1424      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1425      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1426    })),1427  });1428}14291430// Android: clear the autofill in-memory store on lock.1431async function clearInMemoryVault(): Promise<void> {1432  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1433  if (!plugin?.clearEntries) return;1434  await plugin.clearEntries();1435}14361437interface SyncBridge {1438  ensureServerRunning?: () => void;1439  startPairingSession?: (args: { token: string }) => void;1440  getLocalIp?: () => Promise<{ ip: string }>;1441  sendToConnection?: (args: { connectionId: string; data: string }) => Promise<void>;1442  addListener?: (event: string, handler: (data: Record<string, string>) => void) => void;1443}14441445// Resolve the Capacitor SyncPlugin at call time — module-load resolution1446// races with Capacitor's plugin registration on the Android WebView.1447function syncBridge(): SyncBridge | null {1448  return nativePlugin<SyncBridge>("SyncPlugin");1449}14501451// Build a SyncTransport for the Android responder path — the phone's WS server1452// already has an open connection from the desktop. We send back via1453// SyncPlugin.sendToConnection and receive via the peach:sync-frame queue.1454const androidSyncFrameQueues = new Map<string, Array<(frame: string) => void>>();14551456export function deliverAndroidSyncFrame(connectionId: string, frame: string): void {1457  const queue = androidSyncFrameQueues.get(connectionId);1458  if (queue?.length) queue.shift()!(frame);1459}14601461function createAndroidResponderTransport(connectionId: string) {1462  const pendingReceivers: Array<(frame: string) => void> = [];1463  androidSyncFrameQueues.set(connectionId, pendingReceivers);14641465  return {1466    send: async (data: Uint8Array) => {1467      await syncBridge()?.sendToConnection?.({ connectionId, data: bytesToBase64(data) });1468    },1469    receive: (): Promise<Uint8Array> => new Promise((res) => {1470      pendingReceivers.push((frame) => {1471        res(frame ? base64ToBytes(frame) : new Uint8Array(0));1472      });1473    }),1474    close: async () => {1475      androidSyncFrameQueues.delete(connectionId);1476    },1477  };1478}14791480// Returns username use-counts from the vault, sorted by frequency. Each row1481// also carries the entry's email so the popup can suggest the email/username1482// pair the user has actually used together.1483function buildIdentitySuggestions(1484  entries: VaultEntry[],1485): Array<{ email: string; username: string; count: number }> {1486  const usernameCounts = new Map<string, number>();1487  const usernameEmail = new Map<string, string>();1488  for (const entry of entries) {1489    const username = entry.username ?? "";1490    const email = (entry as VaultEntry & { email?: string }).email ?? "";1491    if (!username && !email) continue;1492    const key = username || email;1493    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1494    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1495  }1496  return Array.from(usernameCounts.entries())1497    .sort((a, b) => b[1] - a[1])1498    .map(([username, count]) => ({1499      email: usernameEmail.get(username) ?? "",1500      username,1501      count,1502    }));1503}15041505/** Notify all content scripts that the vault just became available. */1506function broadcastToContentScripts(message: { type: string }): void {1507  if (!chrome.tabs?.query) return;1508  chrome.tabs.query({}, (tabs) => {1509    for (const tab of tabs) {1510      if (tab.id !== undefined) {1511        chrome.tabs.sendMessage(tab.id, message).catch(() => {1512          // Tab may not have a content script — silently ignore1513        });1514      }1515    }1516  });1517}15181519function shouldRefreshAutoLock(type: MessageType): boolean {1520  return (1521    type !== "HAS_VAULT" &&1522    type !== "IS_UNLOCKED" &&1523    type !== "GET_VAULT_STATUS" &&1524    type !== "LOCK" &&1525    type !== "UPDATE_SETTINGS" &&1526    type !== "GET_PENDING_PASSKEY" &&1527    type !== "GET_PASSKEY_PROVIDER_STATE" &&1528    type !== "DECLINE_CARD_SAVE" &&1529    type !== "IS_CARD_DECLINED" &&1530    type !== "SUBMIT_FEEDBACK"1531  );1532}15331534function isAllowedCanaryWebhookUrl(value: string): boolean {1535  try {1536    const url = new URL(value);1537    if (url.protocol !== "https:") return false;15381539    const hostname = url.hostname.toLowerCase();1540    if (1541      hostname === "localhost" ||1542      hostname.endsWith(".localhost") ||1543      isPrivateIpv4(hostname) ||1544      isPrivateIpv6(hostname)1545    ) {1546      return false;1547    }15481549    return true;1550  } catch {1551    return false;1552  }1553}15541555function isPrivateIpv4(hostname: string): boolean {1556  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1557    return true;1558  }15591560  const octets = hostname.split(".").map((part) => Number(part));1561  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1562    return false;1563  }15641565  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1566}15671568function isPrivateIpv6(hostname: string): boolean {1569  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1570  return (1571    normalized === "::1" ||1572    normalized.startsWith("fc") ||1573    normalized.startsWith("fd") ||1574    normalized.startsWith("fe80:")1575  );1576}