messages.ts

59.5 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 { predictBatch as mlPredictBatch } from "./ml";74import type { MLFieldFeatures } from "../shared/ml";75import { base64ToBytes, bytesToBase64 } from "../shared/sync-wire";7677/**78 * The single Pro gate. Every gated handler calls this first; the broadcast79 * lets the popup react (navigate to the License section, highlight the80 * relevant feature). Background never touches the popup view directly —81 * the popup owns navigation. See Projects.md "Pro gate rule".82 */83async function requirePro(84  feature: ProFeature,85  trigger: "user" | "background" = "user"86): Promise<{ allowed: boolean }> {87  if (await isProUser()) return { allowed: true };8889  if (trigger === "user") {90    // User deliberately triggered this feature — redirect the popup immediately.91    chrome.runtime92      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })93      .catch(() => {94        // Popup may be closed — the gate signal is best-effort.95      });96  } else {97    // Background trigger (e.g. passive sync initiation) — no popup is open.98    // Queue a notice so the next popup open shows a soft banner instead of99    // silently failing.100    if (chrome.storage.session) {101      chrome.storage.session102        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })103        .catch(() => {});104    }105  }106107  return { allowed: false };108}109110// ---------------------------------------------------------------------------111// Local device name. Peers see this string in PAIR_REQUEST / PAIR_ACCEPT and112// next to the device in their paired-devices list. Default to a platform-aware113// fallback when the user hasn't set one explicitly.114const DEVICE_NAME_KEY = "peach_device_name";115116async function getLocalDeviceName(): Promise<string> {117  try {118    const stored = await chrome.storage.local.get(DEVICE_NAME_KEY);119    const value = (stored as Record<string, string | undefined>)[DEVICE_NAME_KEY];120    if (typeof value === "string" && value.trim()) return value.trim();121  } catch {122    // fall through to default123  }124  return "Peach";125}126127// ---------------------------------------------------------------------------128// 6-digit code pairing.129130const PAIRING_TOKEN_TTL_MS = 5 * 60 * 1000;131132133function generateSixDigitToken(): string {134  // crypto.getRandomValues, not Math.random — the token is the only secret135  // protecting the pairing window from a same-LAN attacker. 6 decimal digits136  // is 1 in 1,000,000; combined with a 5-minute TTL and pairing-mode gating137  // on the responder this is the right tradeoff between UX and security.138  const buf = new Uint32Array(1);139  crypto.getRandomValues(buf);140  const value = buf[0] % 1_000_000;141  return value.toString().padStart(6, "0");142}143144// ---------------------------------------------------------------------------145// Peer discovery glue (Phase 7 popup pairing flow).146147const PRIVATE_IPV4_RANGES = [148  { prefix: "10." },149  { prefix: "127." },150  { prefix: "169.254." },151  { prefix: "192.168." },152];153154// Empty disables network submission while the UI continues to function as a155// no-op (the handler returns ok:true without calling fetch). When set, the156// URL is validated by `isAllowedCanaryWebhookUrl` before any request, so the157// same private-IP/HTTPS rules that gate canary webhooks apply here.158const FEEDBACK_ENDPOINT = "";159160// ---------------------------------------------------------------------------161// Sync helpers162// ---------------------------------------------------------------------------163164function buildSyncDeps(): SyncDeps {165  return {166    isVaultUnlocked: () => vault.isUnlocked(),167    getVaultBlobForSync: async () => {168      const base = await vault.getVaultBlobForSync();169      if (!base) return null;170      const paired = await getPairedDevices();171      return {172        ...base,173        devices: paired174          .filter(d => d.x25519PublicKey)175          .map(d => ({176            publicKeyHex: d.x25519PublicKey,177            deviceName: d.displayName,178            pairedAt: d.pairedAt,179          })),180      };181    },182    applyIncomingVault: async (blob, ts, license, devices) => {183      const applied = await vault.applyIncomingVault(blob, ts, license);184      if (devices?.length) await mergeDeviceRegistry(devices);185      if (applied) await vault.reloadEntriesAfterSync();186      return applied;187    },188  };189}190191async function doVaultSync(ip: string, publicKeyHex: string): Promise<SyncResult> {192  try {193    const transport = await createWebSocketSyncTransport(`ws://${ip}:44100`, publicKeyHex);194    return await runBlobSyncSession('initiator', transport, buildSyncDeps());195  } catch (err) {196    return { status: 'errored', applied: false, error: String(err) };197  }198}199200async function mergeDeviceRegistry(incoming: SyncableDevice[]): Promise<void> {201  const existing = await getPairedDevices();202  const existingKeys = new Set(existing.map(d => d.x25519PublicKey));203  for (const device of incoming) {204    if (!existingKeys.has(device.publicKeyHex)) {205      await addPairedDevice({206        deviceId: device.publicKeyHex,207        displayName: device.deviceName,208        x25519PublicKey: device.publicKeyHex,209        pairedAt: device.pairedAt,210        lastSeenAt: 0,211        lastKnownIp: '',212      }).catch(() => {});213    }214  }215}216217// Background pairing scan — runs after START_PAIRING_SERVER fires on desktop.218// Scans the local subnet for a phone that has accepted the pairing token,219// stores it, runs the initial vault exchange, then notifies the popup.220async function runPairingSubnetScan(token: string): Promise<void> {221  const subnet = await getLocalSubnet();222  if (!subnet) return;223224  const found = await scanForPairingPhone(subnet, token);225  if (!found) return;226227  const { ip, publicKeyHex } = found;228229  try {230    await addPairedDevice({231      deviceId: publicKeyHex,232      displayName: 'Peach',233      x25519PublicKey: publicKeyHex,234      pairedAt: Date.now(),235      lastSeenAt: Date.now(),236      lastKnownIp: ip,237    });238  } catch {239    // Already paired — update IP240    await updatePairedDevice(publicKeyHex, { lastKnownIp: ip, lastSeenAt: Date.now() });241  }242243  // Immediate vault exchange — the free one-time transfer244  await doVaultSync(ip, publicKeyHex);245246  chrome.runtime.sendMessage({247    type: 'PAIRING_COMPLETED',248    payload: { deviceName: 'Peach', publicKeyHex, deviceIp: ip },249  }).catch(() => {});250}251252export function setupMessageHandler(): void {253  chrome.runtime.onMessage.addListener(254    (msg: unknown, sender, sendResponse) => {255      if (!isMessage(msg)) {256        sendResponse({ ok: false, error: "invalid message" });257        return true;258      }259      handleMessage(msg, sender)260        .then(sendResponse)261        .catch((err) =>262          sendResponse({263            ok: false,264            error: err instanceof Error ? err.message : String(err),265          })266        );267      return true;268    }269  );270271  // Android: the chrome shim queues sendMessage calls until this handler is272  // registered. Without this hookup, every message hangs on Capacitor builds.273  // eslint-disable-next-line @typescript-eslint/no-explicit-any274  const reg = (globalThis as any).__peachRegisterMessageHandler;275  if (typeof reg === "function") {276    reg(async (m: unknown) => {277      if (!isMessage(m)) return { ok: false, error: "invalid message" };278      try {279        return await handleMessage(m);280      } catch (err) {281        return {282          ok: false,283          error: err instanceof Error ? err.message : String(err),284        };285      }286    });287  }288289  // Android: subscribe to SyncPlugin events.290  if (isNativePlatform()) {291    const syncPlug = nativePlugin<{292      addListener: (293        event: string,294        handler: (data: Record<string, string>) => void295      ) => void;296    }>("SyncPlugin");297298    // Pairing probe answered — store the paired device (desktop, no IP needed299    // since the desktop never acts as a WS server).300    syncPlug?.addListener?.("peach:pair-probe-answered", (data) => {301      const deviceName = data.deviceName ?? "Peach";302      const publicKeyHex = data.publicKeyHex ?? "";303      void (async () => {304        const { addPairedDevice, setHasPaired: setPaired } = await import("./sync-storage");305        await addPairedDevice({306          deviceId: publicKeyHex || (data.connectionId ?? "unknown"),307          displayName: deviceName,308          x25519PublicKey: publicKeyHex,309          pairedAt: Date.now(),310          lastSeenAt: Date.now(),311        }).catch(() => {});312        await setPaired();313        chrome.runtime.sendMessage({314          type: "PAIRING_COMPLETED",315          payload: { deviceName },316        }).catch(() => {});317      })();318    });319320    // Sync frame received — route to the waiting responder session.321    syncPlug?.addListener?.("peach:sync-frame", (data) => {322      const { connectionId, frame } = data;323      if (connectionId && frame) deliverAndroidSyncFrame(connectionId, frame);324    });325326    // Sync session started (SYNC_HELLO received by SyncPlugin) — dispatch as327    // a background message so SYNC_SESSION_STARTED handler runs the responder.328    syncPlug?.addListener?.("peach:sync-session-started", (data) => {329      const { connectionId } = data;330      if (!connectionId) return;331      void handleMessage({ type: "SYNC_SESSION_STARTED", payload: { connectionId } });332    });333  }334}335336function isMessage(m: unknown): m is Message {337  return typeof m === "object" && m !== null && "type" in m;338}339340export async function handleMessage(341  msg: Message,342  sender: Partial<chrome.runtime.MessageSender> = {}343): Promise<MessageResponse> {344  try {345    // Validate sender — only allow messages from our extension pages/scripts.346    // `sender.id` is undefined for messages originating from extension UI347    // (popup/options), which is legitimate; reject only when it is defined348    // and does not match our extension id.349    if (350      sender.id !== undefined &&351      sender.id !== chrome.runtime.id352    ) {353      return { ok: false, error: "invalid sender" };354    }355356    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {357      touchAutoLock();358    }359360    switch (msg.type) {361      case "CREATE_VAULT": {362        const { password } = msg.payload as { password: string };363        await vault.createVault(password);364        await setupAutoLock();365        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });366        onVaultUnlocked();367        return { ok: true };368      }369      case "UNLOCK": {370        const { password } = msg.payload as { password: string };371        const ok = await vault.unlock(password);372        if (ok) {373          await setupAutoLock();374          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });375          onVaultUnlocked();376          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());377        }378        return { ok };379      }380      case "VALIDATE_RECOVERY_WORDS": {381        const { words } = msg.payload as { words: string[] };382        const invalid = findInvalidWords(words);383        return { ok: true, data: { valid: invalid.length === 0, invalid } };384      }385      case "GET_RECOVERY_WORDS": {386        // Must be unlocked and have recovery set up (vault must be v2.12+).387        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };388        try {389          const words = await vault.getRecoveryWords();390          return { ok: true, data: words };391        } catch (e) {392          // pre-v2.12 vault that hasn't migrated393          return { ok: false, error: "recovery_not_setup" };394        }395      }396      case "RECOVER_WITH_WORDS": {397        // User has lost their password but has their 12 recovery words.398        // We: (1) validate the words, (2) re-encrypt vault with new password.399        const { words, newPassword } = msg.payload as {400          words: string[];401          newPassword: string;402        };403        const stored = await vault.loadSlotA();404        if (!stored) return { ok: false, error: "no vault" };405        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {406          return { ok: false, error: "recovery_not_setup" };407        }408        // Unwrap the root key from the recovery escrow.409        try {410          await vault.unwrapRootKeyForRecovery(411            stored.recovery_wrapped_root_key,412            stored.recovery_nonce ?? "",413            stored.recovery_tag ?? "",414            stored.recovery_salt,415            words416          );417        } catch {418          return { ok: false, error: "invalid_recovery_words" };419        }420        // Re-key: derive fresh salt + key from new password.421        const newSalt = vault.generateSalt();422        const newKey = await vault.deriveKey(newPassword, newSalt);423        // Re-wrap root key under the new password's derived key so the same424        // recovery words continue to work after the password change.425        await vault.rewrapRootKeyForPassword(newKey, newSalt);426        // Re-encrypt vault entries with the new key.427        await vault.changePasswordWithNewKey(newSalt, newKey);428        await setupAutoLock();429        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });430        return { ok: true };431      }432      case "LOCK":433        vault.lock();434        if (isNativePlatform()) await clearInMemoryVault();435        return { ok: true };436      case "IS_UNLOCKED":437        return { ok: true, data: vault.isUnlocked() };438      case "GET_VAULT_STATUS":439        return { ok: true, unlocked: vault.isUnlocked() };440      case "HAS_VAULT":441        return { ok: true, data: await vault.hasVault() };442      case "GET_ENTRIES":443        return { ok: true, data: vault.getEntries() };444      case "ADD_ENTRY": {445        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };446        const entry = await vault.addEntry(msg.payload as any);447        return { ok: true, data: entry };448      }449      case "BATCH_ADD_ENTRIES": {450        const { entries } = msg.payload as { entries: any[] };451        const added = await vault.batchAddEntries(entries);452        return { ok: true, data: added };453      }454      case "RESTORE_ENTRIES": {455        const { entries, mode, settings } = msg.payload as {456          entries: any[];457          mode: "replace" | "merge";458          settings?: vault.VaultSettings;459        };460        const summary = await vault.restoreEntries(entries, mode);461        if (settings && typeof settings === "object") {462          await vault.updateSettings(settings);463        }464        return { ok: true, data: summary };465      }466      case "CLEAR_VAULT_ENTRIES": {467        await vault.clearVaultEntries("REPLACE_ALL");468        return { ok: true };469      }470      case "GET_VAULT_HISTORY": {471        const snapshots = await vault.getVaultHistory();472        return { ok: true, data: snapshots };473      }474      case "RESTORE_VAULT_SNAPSHOT": {475        const { snapshotId } = msg.payload as { snapshotId: string };476        const result = await vault.restoreVaultSnapshot(snapshotId);477        if (!result.ok) return { ok: false, error: result.error };478        broadcastToContentScripts({ type: "VAULT_LOCKED" });479        return { ok: true };480      }481      case "COUNT_DUPLICATES": {482        return { ok: true, data: vault.countDuplicates() };483      }484      case "DEDUPLICATE_ENTRIES": {485        const removed = await vault.deduplicateEntries();486        return { ok: true, data: removed };487      }488      case "UPDATE_ENTRY": {489        const { id, patch } = msg.payload as any;490        await vault.updateEntry(id, patch);491        return { ok: true };492      }493      case "ADD_ADDITIONAL_URL": {494        const { id, url } = msg.payload as { id: string; url: string };495        const trimmed = typeof url === "string" ? url.trim() : "";496        if (!trimmed) return { ok: false, error: "url required" };497        const existing = vault.getEntryById(id);498        if (!existing) return { ok: false, error: "entry not found" };499        if (existing.type !== "login") return { ok: false, error: "login entries only" };500        const merged = [...(existing.additionalUrls ?? []), trimmed];501        await vault.updateEntry(id, { additionalUrls: merged });502        return { ok: true };503      }504      case "DELETE_ENTRY": {505        const { id } = msg.payload as { id: string };506        await vault.deleteEntry(id);507        return { ok: true };508      }509      case "GET_DELETED_ENTRIES":510        return { ok: true, data: vault.getDeletedEntries() };511      case "RESTORE_ENTRY": {512        const { id } = msg.payload as { id: string };513        await vault.restoreEntry(id);514        return { ok: true };515      }516      case "PURGE_ENTRY": {517        const { id } = msg.payload as { id: string };518        await vault.purgeEntry(id);519        return { ok: true };520      }521      case "PURGE_EXPIRED_TRASH": {522        const { retentionMs } = msg.payload as { retentionMs: number };523        const purged = await vault.purgeExpiredTrash(retentionMs);524        return { ok: true, data: purged };525      }526      case "SAVE_NOTE": {527        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };528        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };529        const now = Date.now();530        if (id) {531          const existing = vault.getEntryById(id);532          if (!existing) return { ok: false, error: "not_found" };533          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });534          return { ok: true, data: vault.getEntryById(id) };535        } else {536          const entry = await vault.addEntry({537            type: "note",538            title: title || "Untitled",539            notes: body,540            createdAt: now,541            modifiedAt: now,542          } as any);543          return { ok: true, data: entry };544        }545      }546      case "DELETE_NOTE": {547        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };548        const { id } = msg.payload as { id: string };549        await vault.deleteEntry(id);550        return { ok: true };551      }552      case "AUTOFILL_QUERY": {553        if (!vault.isUnlocked()) {554          return { ok: false, error: "VAULT_LOCKED" };555        }556        const { domain, includeAll, kind } = msg.payload as {557          domain: string;558          includeAll?: boolean;559          kind?: "login" | "card";560        };561        // kind="card": return saved cards as compact summaries for the562        // inline card silver platter. Cards are not domain-scoped — every563        // saved card is a candidate on every checkout page — so domain is564        // ignored when kind === "card".565        if (kind === "card") {566          const cards = vault.getEntries().filter((e) => e.type === "card");567          return {568            ok: true,569            data: cards.map((e) => ({570              id: e.id,571              title: e.cardNickname || e.title,572              cardholderName: e.cardholderName,573              last4: e.last4,574              expMonth: e.expMonth,575              expYear: e.expYear,576              network: e.network,577            })),578          };579        }580        // The inline selector fills username+password into a form. Passkey-581        // only entries have no password to fill; sign-in for those goes582        // through the WebAuthn path instead. Filter them out everywhere so583        // the user doesn't see four "GitHub" rows that mostly do nothing.584        // Notes and cards never belonged here either.585        const matches = (586          includeAll587            ? vault588                .getEntries()589                .filter((entry) => entry.type !== "note" && entry.type !== "card")590            : vault.queryDomain(domain)591        ).filter((entry) => !isPasskeyOnly(entry));592        return {593          ok: true,594          data: matches.map((e) =>595            includeAll596              ? {597                  id: e.id,598                  title: e.title,599                  hasPasskey: e.passkey !== undefined,600                }601              : {602                  id: e.id,603                  title: e.title,604                  username: e.username,605                  email: e.email,606                  url: e.url,607                  hasTotp: Boolean(e.totp),608                  hasPasskey: e.passkey !== undefined,609                }610          ),611        };612      }613      case "GET_ENTRY_FOR_FILL": {614        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };615        const { id } = msg.payload as { id: string };616        const entry = vault.getEntryById(id);617        if (!entry) return { ok: false, error: "entry not found" };618        // Passkey-only entries (passkey credential, no password) cannot be619        // filled into a form — sign-in goes through the WebAuthn path. A620        // login that ALSO has a passkey is still fillable for its password.621        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey not fillable" };622        // Strip the passkey credential from the response — content scripts623        // never need the private key, and there's no reason to expose the624        // public credential metadata over the boundary either.625        const { passkey: _strippedPasskey, ...safeEntry } = entry;626        return { ok: true, data: safeEntry };627      }628      case "COPY": {629        const { text, label, alreadyWritten } = msg.payload as {630          text: string;631          label: string;632          alreadyWritten?: boolean;633        };634        await copyToClipboard(text, label, Boolean(alreadyWritten));635        return { ok: true };636      }637      case "CHECK_ALL_BREACHES": {638        const allEntries = vault.getEntries();639        const results: Record<string, number> = {};640        for (const entry of allEntries) {641          if (entry.type === "note") continue;642          if (!entry.password) continue;643          results[entry.id] = await vault.checkBreach(entry.password);644          // Small delay — be a good citizen to the HIBP API645          await new Promise((r) => setTimeout(r, 200));646        }647        // Persist any non-zero counts back to entries648        for (const [id, count] of Object.entries(results)) {649          const entry = vault.getEntryById(id);650          if (entry && (entry.breach ?? 0) !== count) {651            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });652          }653        }654        return { ok: true, data: results };655      }656      case "GET_SETTINGS":657        return { ok: true, data: await vault.ensureSettingsLoaded() };658      case "UPDATE_SETTINGS": {659        const patch = msg.payload as Record<string, unknown>;660        await vault.updateSettings(patch as any);661        if (typeof patch.autoLockMinutes === "number") {662          await setupAutoLock();663          if (vault.isUnlocked()) touchAutoLock();664        }665        return { ok: true };666      }667      case "GET_PENDING_PASSKEY":668        return { ok: true, data: await getPendingPasskeyRequest() };669      case "APPROVE_PASSKEY": {670        const { requestId } = msg.payload as { requestId: number };671        await resolvePendingPasskeyRequest(requestId, true);672        return { ok: true };673      }674      case "DENY_PASSKEY": {675        const { requestId } = msg.payload as { requestId: number };676        await resolvePendingPasskeyRequest(requestId, false);677        return { ok: true };678      }679      case "GET_PASSKEY_PROVIDER_STATE":680        return { ok: true, data: await getPasskeyProviderState() };681      case "SET_PASSKEY_PROVIDER_ENABLED": {682        const { enabled } = msg.payload as { enabled: boolean };683        // Disabling is always free; gating fires only when a free user is684        // trying to turn passkey interception on.685        if (enabled) {686          const gate = await requirePro("passkeys");687          if (!gate.allowed) return { ok: false, error: "pro_required" };688        }689        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };690      }691      case "FIRE_CANARY_PING": {692        const { webhookUrl, entryTitle, trigger } = msg.payload as {693          webhookUrl: string;694          entryTitle: string;695          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";696        };697        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {698          return { ok: false, error: "invalid webhook url" };699        }700        const body = JSON.stringify({701          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",702          entry: entryTitle,703          trigger,704          timestamp: new Date().toISOString(),705          source: "peach-extension",706        });707        if (trigger === "test") {708          // Permitted outbound fetch: user-configured canary alert endpoint709          // (validated by isAllowedCanaryWebhookUrl above). This is the710          // only non-HIBP outbound call in the extension — see711          // Projects.md §3.7. Test pings are awaited so the UI can show712          // success/failure.713          try {714            const res = await fetch(webhookUrl, {715              method: "POST",716              headers: { "Content-Type": "application/json" },717              body,718            });719            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };720          } catch (err) {721            return { ok: false, error: err instanceof Error ? err.message : "network error" };722          }723        }724        // Non-test triggers are fire-and-forget725        fetch(webhookUrl, {726          method: "POST",727          headers: { "Content-Type": "application/json" },728          body,729        }).catch(() => {});730        return { ok: true };731      }732      case "ACTIVATE_LICENSE": {733        const { key } = msg.payload as { key: string };734        const licenseInfo = await activateLicense(key);735        return { ok: true, data: licenseInfo };736      }737      case "GET_LICENSE": {738        const licenseInfo = await getLicenseInfo();739        return { ok: true, data: licenseInfo };740      }741      case "GET_LICENSE_KEY": {742        const key = await getLicenseKey();743        return { ok: true, data: key };744      }745      case "DEACTIVATE_LICENSE": {746        await deactivateLicense();747        return { ok: true };748      }749      case "SHOULD_PLAY_CELEBRATION": {750        const should = await shouldPlayCelebration();751        return { ok: true, data: should };752      }753      case "MARK_CELEBRATION_PLAYED": {754        await markCelebrationPlayed();755        return { ok: true };756      }757      case "OPEN_PRO_GATE": {758        // Content script requests: open popup and navigate to License section.759        const { feature } = (msg.payload ?? {}) as { feature?: string };760        if (chrome.storage.session) {761          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });762        }763        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }764        return { ok: true };765      }766      case "GET_IDENTITIES": {767        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };768        return { ok: true, data: vault.getIdentities() };769      }770      case "TOUCH_AUTO_LOCK": {771        // touchAutoLock() is already called by shouldRefreshAutoLock above;772        // this case just gives the popup a typed message to keep the session alive.773        return { ok: true };774      }775      case "GET_ADVANCED_HEALTH_REPORT": {776        const gate = await requirePro("advanced_health");777        if (!gate.allowed) return { ok: false, error: "pro_required" };778        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };779        const report = await buildAdvancedHealthReport(vault.getEntries());780        return { ok: true, data: report };781      }782      case "INITIATE_PASSWORD_CHANGE": {783        const gate = await requirePro("smart_password_change");784        if (!gate.allowed) return { ok: false, error: "pro_required" };785        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };786        const { id } = msg.payload as { id: string };787        const entry = vault.getEntryById(id);788        if (!entry) return { ok: false, error: "entry not found" };789        const url = resolveResetUrl(entry);790        if (!url) return { ok: false, error: "no reset url" };791        try {792          await chrome.tabs.create({ url });793          return { ok: true, data: { url } };794        } catch (err) {795          return {796            ok: false,797            error: err instanceof Error ? err.message : "failed to open tab",798          };799        }800      }801      case "IS_DURESS_ENABLED": {802        const enabled = await vault.isDuressEnabled();803        return { ok: true, data: enabled };804      }805      case "SETUP_DURESS": {806        const { duressPassword } = msg.payload as { duressPassword: string };807        await vault.setupDuress(duressPassword);808        return { ok: true };809      }810      case "DISABLE_DURESS": {811        await vault.disableDuress();812        return { ok: true };813      }814      case "VERIFY_MAIN_PASSWORD": {815        const { password } = msg.payload as { password: string };816        const ok = await vault.verifyMainPassword(password);817        return { ok: true, data: ok };818      }819      case "CHANGE_PASSWORD": {820        const { currentPassword, newPassword } = msg.payload as {821          currentPassword: string;822          newPassword: string;823        };824        const changed = await vault.changePassword(currentPassword, newPassword);825        return changed826          ? { ok: true }827          : { ok: false, error: "incorrect current password" };828      }829      case "GET_SITE_PASSWORD_POLICY": {830        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });831        if (!tab?.id) return { ok: true, data: null };832        try {833          const response = await chrome.tabs.sendMessage(tab.id, {834            type: "GET_SITE_PASSWORD_POLICY",835          });836          return (response as MessageResponse) ?? { ok: true, data: null };837        } catch {838          return { ok: true, data: null };839        }840      }841      case "GET_SYNC_STATE": {842        const pairedDevices = await getPairedDevices();843        const trustedNetworks = await getTrustedNetworks();844        const tailscale = await isOnTailscale();845        const pro = await isProUser();846847        let status: SyncStatus = "offline";848        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {849          if (pairedDevices.length === 0) {850            status = "no_peers";851          } else {852            status = "synced";853          }854        } else {855          status = "not_trusted";856        }857858        const lastSyncRaw = await storageGet("peach_last_sync_at");859        const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN;860        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined;861862        return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } };863      }864      case "GET_PAIRED_DEVICES": {865        const devices = await getPairedDevices();866        return { ok: true, data: { devices } };867      }868      case "GET_SYNC_STATUS": {869        const lastSyncRaw = await storageGet("peach_last_sync_at");870        const lastSyncParsed = lastSyncRaw ? parseInt(lastSyncRaw, 10) : NaN;871        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : null;872        const status: 'up_to_date' | 'never' = lastSyncAt ? 'up_to_date' : 'never';873        return { ok: true, data: { status, lastSyncAt } };874      }875      case "ACCEPT_PAIRING": {876        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.877        return { ok: true };878      }879      case "REMOVE_PAIRED_DEVICE": {880        const { deviceId } = msg.payload as { deviceId: string };881        await removePairedDevice(deviceId);882        return { ok: true };883      }884      case "REMOVE_TRUSTED_NETWORK": {885        const { ssid, bssid, isTailscale } = msg.payload as any;886        const networks = await getTrustedNetworks();887        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 888          (isTailscale ? n.isTailscale : n.ssid === ssid) && 889          (!bssid || n.bssid === bssid)890        );891        if (network) {892          await removeTrustedNetwork(network.addedAt);893        }894        return { ok: true };895      }896      case "MARK_NETWORK_TRUSTED": {897        const network = await getCurrentNetwork();898        await addTrustedNetwork({899          ssid: network.ssid,900          bssid: network.bssid,901          isTailscale: network.isTailscale,902          addedAt: Date.now(),903        });904        return { ok: true };905      }906      case "GET_INCOMING_PAIRING_REQUEST": {907        const request = await getIncomingPairingRequest();908        return { ok: true, data: request };909      }910      case "RESPOND_INCOMING_PAIRING": {911        const { accept } = msg.payload as { accept: boolean };912        const request = await getIncomingPairingRequest();913        if (!request) return { ok: false, error: "no_pending_request" };914        if (Date.now() > request.expiresAt) {915          await clearIncomingPairingRequest();916          return { ok: false, error: "expired" };917        }918        await clearIncomingPairingRequest();919        if (accept) {920          await addPairedDevice({921            deviceId: request.publicKeyHex,922            displayName: request.deviceName,923            x25519PublicKey: request.publicKeyHex,924            pairedAt: Date.now(),925            lastSeenAt: Date.now(),926          });927        }928        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };929      }930      case "START_PAIRING_SERVER": {931        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.932        const token = generateSixDigitToken();933        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;934        await setActivePairingToken({ token, expiresAt });935        // Fire-and-forget subnet scan — finds the phone after it scans the QR936        // and calls SCAN_PAIRING_QR to register the token with SyncPlugin.937        if (!isNativePlatform()) {938          void runPairingSubnetScan(token);939        }940        return { ok: true, data: { token, expiresAt } };941      }942      case "STOP_PAIRING_SERVER": {943        try {944          await setActivePairingToken(null);945        } catch { /* best-effort */ }946        return { ok: true };947      }948      case "GET_RECENT_PAIRING": {949        const recent = await consumeRecentPairing();950        return { ok: true, data: recent };951      }952      case "DEBUG_INJECT_INCOMING_PAIRING": {953        // Manual E2E rehearsal hook. Inserts a synthetic incoming pairing954        // request into session storage so Phase 7 banner UX can be exercised955        // without a live native host. No Pro gate — this is a no-op in956        // production unless explicitly invoked from a Settings debug action.957        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {958          deviceName?: string;959          publicKeyHex?: string;960        };961        if (!deviceName || !publicKeyHex) {962          return { ok: false, error: "missing_payload" };963        }964        const now = Date.now();965        await setIncomingPairingRequest({966          deviceName,967          publicKeyHex,968          receivedAt: now,969          expiresAt: now + 60_000,970        });971        return { ok: true };972      }973      case "RESET_SYNC_IDENTITY": {974        const gate = await requirePro("sync");975        if (!gate.allowed) return { ok: false, error: "pro_required" };976        const devices = await getPairedDevices();977        for (const device of devices) {978          await removePairedDevice(device.deviceId);979        }980        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };981      }982      case "RECORD_MANUAL_SUMMON": {983        const { domain } = msg.payload as { domain: string };984        const settings = vault.getSettings();985        const existing = settings.manualSummonDomains?.[domain];986        const now = Date.now();987        await vault.updateSettings({988          manualSummonDomains: {989            ...settings.manualSummonDomains,990            [domain]: {991              firstSummonedAt: existing?.firstSummonedAt ?? now,992              summonCount: (existing?.summonCount ?? 0) + 1,993              lastSummonedAt: now,994            },995          },996        });997        return { ok: true };998      }999      case "DECLINE_CARD_SAVE": {1000        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1001        await vault.declineCardSaveOffer(last4, expMonth, expYear);1002        return { ok: true };1003      }1004      case "IS_CARD_DECLINED": {1005        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1006        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1007        return { ok: true, data: declined };1008      }1009      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1010        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1011          rpId?: string;1012          rpName?: string;1013          userName?: string;1014          userDisplayName?: string;1015        };1016        if (!rpId || !userName) return { ok: false, error: "rpId and userName required" };1017        return await initiateFirefoxPasskeyCreate({1018          rpId,1019          rpName: rpName ?? rpId,1020          userName,1021          userDisplayName,1022        });1023      }10241025      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1026        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1027        if (!payload) return { ok: false, error: "missing payload" };1028        return await completeFirefoxPasskeyCreate(payload);1029      }10301031      case "PASSKEY_OFFER_DECLINE": {1032        const { domain } = (msg.payload ?? {}) as { domain?: string };1033        if (!domain) return { ok: false, error: "domain required" };1034        await recordPasskeyOfferDecline(domain);1035        return { ok: true };1036      }10371038      case "GET_PASSKEY_OFFER_DECLINED": {1039        const { domain } = (msg.payload ?? {}) as { domain?: string };1040        if (!domain) return { ok: false, error: "domain required" };1041        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1042      }10431044      case "PASSKEY_HAS_CREDENTIALS": {1045        const payload = msg.payload as {1046          rpId?: string;1047          allowCredentials?: Array<{ id: string; type?: string }>;1048        } | undefined;1049        if (!payload?.rpId) return { ok: false, error: "rpId required" };1050        return await handlePasskeyHasCredentials({1051          rpId: payload.rpId,1052          allowCredentials: payload.allowCredentials ?? [],1053        });1054      }10551056      case "PASSKEY_CREATE": {1057        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1058        if (!payload?.rpId || !payload?.userName) {1059          return { ok: false, error: "rpId and userName required" };1060        }1061        return await handleFirefoxPasskeyCreate(payload);1062      }10631064      case "PASSKEY_GET": {1065        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1066        if (!payload?.rpId) return { ok: false, error: "rpId required" };1067        return await handleFirefoxPasskeyGet(payload);1068      }10691070      case "PASSKEY_AUTH_RESPONSE": {1071        const { requestId, approved } = (msg.payload ?? {}) as {1072          requestId?: string;1073          approved?: boolean;1074        };1075        if (!requestId || typeof approved !== 'boolean') {1076          return { ok: false, error: 'requestId and approved required' };1077        }1078        await resolvePendingPasskeyRequest(Number(requestId), approved);1079        return { ok: true };1080      }10811082      case "GET_PASSKEY_FOR_DOMAIN": {1083        const { domain } = (msg.payload ?? {}) as { domain?: string };1084        if (!domain) return { ok: false, error: "domain required" };1085        if (!vault.isUnlocked()) return { ok: true, data: null };1086        const match = vault1087          .getEntries()1088          .find((entry) => entry.passkey?.rpId === domain);1089        if (!match || !match.passkey) return { ok: true, data: null };1090        // Slim shape — only the fields State 11 needs. Never expose private1091        // key material, even though this is locked behind isUnlocked.1092        return {1093          ok: true,1094          data: {1095            rpId: match.passkey.rpId,1096            userName: match.passkey.userName,1097            browser: match.passkey.browser,1098          },1099        };1100      }11011102      case "DESTROY_VAULT": {1103        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1104        // storage.local.clear() wipes every Peach key (slots, settings, license,1105        // onboarded flag, history, sync state, declined cards, recall, etc.);1106        // session.clear() wipes pending passkey requests + pro-notice queues.1107        // Caller (Panic.tsx) handles UI navigation back to onboarding.1108        vault.lock();1109        await storageClear();1110        await vault.clearVaultHistory();1111        if (chrome.storage.session) {1112          await chrome.storage.session.clear();1113        }1114        return { ok: true };1115      }11161117      case "SUBMIT_FEEDBACK": {1118        const { category, message, version, browser } = msg.payload as {1119          category: string;1120          message: string;1121          version: string;1122          browser: string;1123        };1124        if (!message.trim()) return { ok: false, error: "message is empty" };1125        if (!FEEDBACK_ENDPOINT) return { ok: true };1126        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1127          return { ok: false, error: "invalid feedback endpoint" };1128        }1129        try {1130          const res = await fetch(FEEDBACK_ENDPOINT, {1131            method: "POST",1132            headers: { "Content-Type": "application/json" },1133            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1134          });1135          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1136        } catch (err) {1137          return { ok: false, error: err instanceof Error ? err.message : "network error" };1138        }1139      }1140      case "TRIGGER_SYNC": {1141        const gate = await requirePro("sync");1142        if (!gate.allowed) return { ok: false, error: "pro_required" };1143        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };11441145        if (isNativePlatform()) {1146          // Phone is the server — ensure it's listening for desktop connections.1147          syncBridge()?.ensureServerRunning?.();1148          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };1149        }11501151        // Desktop: iterate all paired devices and sync with each.1152        const paired = await getPairedDevices();1153        if (!paired.length) return { ok: true, data: { syncedCount: 0, reason: "no_paired_devices" } };11541155        const subnet = await getLocalSubnet();1156        const results: Array<{ device: string } & SyncResult> = [];11571158        for (const device of paired) {1159          if (!device.x25519PublicKey) continue;11601161          let result: SyncResult;11621163          // Fast path — use last known IP1164          if (device.lastKnownIp) {1165            result = await doVaultSync(device.lastKnownIp, device.x25519PublicKey);1166          } else {1167            result = { status: 'errored', applied: false, error: 'no_ip' };1168          }11691170          // Discovery path — scan if fast path failed1171          if (result.status === 'errored' && subnet) {1172            const newIp = await discoverDevice(subnet, device.x25519PublicKey);1173            if (newIp) {1174              await updatePairedDevice(device.x25519PublicKey, { lastKnownIp: newIp });1175              result = await doVaultSync(newIp, device.x25519PublicKey);1176            }1177          }11781179          if (result.status === 'completed') {1180            await updatePairedDevice(device.x25519PublicKey, {1181              lastSeenAt: Date.now(),1182              lastSyncAt: Date.now(),1183            });1184          }11851186          results.push({ device: device.displayName, ...result });1187        }11881189        const syncedCount = results.filter(r => r.status === 'completed').length;1190        if (syncedCount > 0) {1191          await chrome.storage.local.set({ peach_last_sync_at: String(Date.now()) });1192        }1193        return { ok: true, data: { syncedCount, results } };1194      }1195      // Android-only: biometric unlock with pre-derived key.1196      case "UNLOCK_WITH_KEY": {1197        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1198        if (!isNativePlatform()) {1199          return { ok: false, error: "desktop_only_uses_password" };1200        }1201        try {1202          const result = await vault.unlockWithKey(masterKeyHex);1203          if (result.ok) {1204            onVaultUnlocked();1205            await publishInMemoryVault(result.entries);1206          }1207          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1208        } catch {1209          return { ok: false, error: "invalid_key" };1210        }1211      }1212      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1213      case "GET_DERIVED_KEY": {1214        if (!isNativePlatform()) {1215          return { ok: false, error: "android_only" };1216        }1217        if (!vault.isUnlocked()) {1218          return { ok: false, error: "vault_locked" };1219        }1220        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1221      }1222      // Android: scanned a QR containing a desktop pairing token.1223      case "SCAN_PAIRING_QR": {1224        if (!isNativePlatform()) {1225          return { ok: false, error: "android_only" };1226        }1227        const { token } = msg.payload as { token: string };1228        syncBridge()?.startPairingSession?.({ token });1229        return { ok: true };1230      }1231      // Android: desktop opened a sync connection to the phone's WS server.1232      // Run the responder side of the vault exchange.1233      case "SYNC_SESSION_STARTED": {1234        if (!isNativePlatform()) return { ok: false };1235        if (!vault.isUnlocked()) {1236          return { ok: false, error: "vault_locked" };1237        }1238        const { connectionId } = (msg.payload ?? {}) as { connectionId?: string };1239        if (!connectionId) return { ok: false, error: "missing_connection_id" };12401241        const transport = createAndroidResponderTransport(connectionId);1242        const result = await runBlobSyncSession('responder', transport, buildSyncDeps());1243        if (result.applied) {1244          await publishInMemoryVault(vault.getEntries());1245        }1246        return { ok: true, data: result };1247      }1248      // Android: returns the phone's WiFi IP address.1249      case "GET_LOCAL_IP": {1250        if (!isNativePlatform()) {1251          return { ok: false, error: "android_only" };1252        }1253        const { ip } = (await syncBridge()?.getLocalIp?.()) ?? { ip: "" };1254        return { ok: true, data: { ip } };1255      }1256      case "GET_IDENTITY_SUGGESTIONS": {1257        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1258        const entries = vault.getEntries();1259        const suggestions = buildIdentitySuggestions(entries);1260        return { ok: true, data: { suggestions } };1261      }1262      case "POPULATE_INLINE_VAULT": {1263        if (!isNativePlatform()) return { ok: false };1264        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1265        const entries = vault.getEntries();1266        await publishInMemoryVault(entries);1267        return { ok: true };1268      }1269      // --- PNA compatibility test handlers — REMOVE BEFORE RELEASE ---1270      case "TEST_LOCAL_WEBSOCKET": {1271        const { ip } = (msg.payload ?? {}) as { ip?: string };1272        if (!ip) return { ok: false, error: "ip required" };1273        return new Promise((resolve) => {1274          try {1275            const ws = new WebSocket(`ws://${ip}:44100`);1276            ws.onopen = () => { ws.close(); resolve({ ok: true, data: { connected: true } }); };1277            ws.onerror = () => resolve({ ok: false, error: "connection_failed" });1278            setTimeout(() => { ws.close(); resolve({ ok: false, error: "timeout" }); }, 3000);1279          } catch (err) {1280            resolve({ ok: false, error: String(err) });1281          }1282        });1283      }1284      case "TEST_SUBNET_DETECTION": {1285        const subnet = await getLocalSubnet();1286        return { ok: true, data: { subnet } };1287      }1288      case "TEST_SUBNET_SCAN": {1289        const subnet = await getLocalSubnet();1290        if (!subnet) return { ok: false, error: "no_subnet" };1291        const start = Date.now();1292        const result = await discoverDevice(subnet, "000000000000000000000000000000000000000000000000000000000000000000");1293        return { ok: true, data: { elapsed: Date.now() - start, found: !!result } };1294      }1295      case 'TEST_WS_LOCAL': {1296        const { ip } = msg.payload as { ip: string };12971298        return new Promise((resolve) => {1299          const log: string[] = [];1300          log.push(`Attempting ws://${ip}:44100 from service worker...`);13011302          let ws: WebSocket;1303          let settled = false;1304          const settle = (result: MessageResponse) => {1305            if (!settled) { settled = true; resolve(result); }1306          };13071308          try {1309            ws = new WebSocket(`ws://${ip}:44100`);13101311            ws.onopen = () => {1312              log.push('SUCCESS: WebSocket connected');1313              ws.close();1314              settle({ ok: true, data: { log } });1315            };13161317            ws.onerror = (e) => {1318              log.push(`FAILED: onerror fired — ${String(e)}`);1319              settle({ ok: false, error: 'ws_error', data: { log } });1320            };13211322            ws.onclose = (e) => {1323              if (e.code !== 1000) {1324                log.push(`CLOSED unexpectedly: code=${e.code} reason=${e.reason}`);1325                settle({ ok: false, error: 'ws_closed', data: { code: e.code, log } });1326              }1327            };13281329            setTimeout(() => {1330              try { ws.close(); } catch {}1331              log.push('FAILED: 5 second timeout — connection never opened');1332              settle({ ok: false, error: 'timeout', data: { log } });1333            }, 5000);13341335          } catch (err) {1336            log.push(`FAILED: WebSocket constructor threw — ${String(err)}`);1337            settle({ ok: false, error: 'constructor_threw', data: { log } });1338          }1339        });1340      }13411342      case 'TEST_SUBNET_DETECT': {1343        return new Promise((resolve) => {1344          try {1345            // RTCPeerConnection availability varies by context — this is what we're testing1346            // eslint-disable-next-line @typescript-eslint/no-explicit-any1347            const RTC = (globalThis as any).RTCPeerConnection as (new (cfg: object) => RTCPeerConnection) | undefined;1348            if (!RTC) {1349              resolve({ ok: false, error: 'RTCPeerConnection is not defined' });1350              return;1351            }1352            const pc = new RTC({ iceServers: [] });1353            pc.createDataChannel('');1354            pc.createOffer().then((o) => pc.setLocalDescription(o));13551356            const candidates: string[] = [];1357            const timer = setTimeout(() => {1358              pc.close();1359              if (candidates.length === 0) {1360                resolve({ ok: false, error: 'no_candidates', data: { candidates } });1361              } else {1362                const subnet = candidates[0].match(/(\d+\.\d+\.\d+)\.\d+/)?.[1];1363                resolve({ ok: true, data: { subnet, candidates } });1364              }1365            }, 2000);13661367            pc.onicecandidate = (e) => {1368              if (!e.candidate) return;1369              const m = e.candidate.candidate.match(/(\d+\.\d+\.\d+\.\d+)/);1370              if (m && !m[1].startsWith('127')) candidates.push(m[1]);1371            };13721373            pc.onicegatheringstatechange = () => {1374              if (pc.iceGatheringState === 'complete') {1375                clearTimeout(timer);1376                pc.close();1377                const subnet = candidates[0]?.match(/(\d+\.\d+\.\d+)\.\d+/)?.[1];1378                resolve({ ok: candidates.length > 0, data: { subnet, candidates } });1379              }1380            };1381          } catch (err) {1382            resolve({ ok: false, error: String(err) });1383          }1384        });1385      }13861387      // --- end test handlers ---13881389      case "ML_INIT":1390        return { ok: true };13911392      case "ML_PREDICT_BATCH": {1393        const { featuresArray } = msg.payload as { featuresArray: MLFieldFeatures[] };1394        return { ok: true, data: mlPredictBatch(featuresArray) };1395      }13961397      default:1398        return { ok: false, error: "unknown message type" };1399    }1400  } catch (err) {1401    return {1402      ok: false,1403      error: err instanceof Error ? err.message : "operation failed",1404    };1405  }1406}14071408// --- Mobile platform helpers ---14091410// Android: populates the in-memory vault used by PeachAutofillService.1411async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1412  const plugin = nativePlugin<{1413    setEntries?: (args: {1414      entries: Array<{1415        id: string;1416        title: string;1417        username: string;1418        email: string;1419        password: string;1420        url: string;1421        totp: string;1422        additionalUrls: string[];1423      }>;1424    }) => Promise<void>;1425  }>("InMemoryVaultPlugin");1426  if (!plugin?.setEntries) return;1427  await plugin.setEntries({1428    entries: entries.map((e) => ({1429      id: e.id,1430      title: e.title ?? "",1431      username: e.username ?? "",1432      email: (e as VaultEntry & { email?: string }).email ?? "",1433      password: e.password ?? "",1434      url: e.url ?? "",1435      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1436      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1437    })),1438  });1439}14401441// Android: clear the autofill in-memory store on lock.1442async function clearInMemoryVault(): Promise<void> {1443  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1444  if (!plugin?.clearEntries) return;1445  await plugin.clearEntries();1446}14471448interface SyncBridge {1449  ensureServerRunning?: () => void;1450  startPairingSession?: (args: { token: string }) => void;1451  getLocalIp?: () => Promise<{ ip: string }>;1452  sendToConnection?: (args: { connectionId: string; data: string }) => Promise<void>;1453  addListener?: (event: string, handler: (data: Record<string, string>) => void) => void;1454}14551456// Resolve the Capacitor SyncPlugin at call time — module-load resolution1457// races with Capacitor's plugin registration on the Android WebView.1458function syncBridge(): SyncBridge | null {1459  return nativePlugin<SyncBridge>("SyncPlugin");1460}14611462// Build a SyncTransport for the Android responder path — the phone's WS server1463// already has an open connection from the desktop. We send back via1464// SyncPlugin.sendToConnection and receive via the peach:sync-frame queue.1465const androidSyncFrameQueues = new Map<string, Array<(frame: string) => void>>();14661467export function deliverAndroidSyncFrame(connectionId: string, frame: string): void {1468  const queue = androidSyncFrameQueues.get(connectionId);1469  if (queue?.length) queue.shift()!(frame);1470}14711472function createAndroidResponderTransport(connectionId: string) {1473  const pendingReceivers: Array<(frame: string) => void> = [];1474  androidSyncFrameQueues.set(connectionId, pendingReceivers);14751476  return {1477    send: async (data: Uint8Array) => {1478      await syncBridge()?.sendToConnection?.({ connectionId, data: bytesToBase64(data) });1479    },1480    receive: (): Promise<Uint8Array> => new Promise((res) => {1481      pendingReceivers.push((frame) => {1482        res(frame ? base64ToBytes(frame) : new Uint8Array(0));1483      });1484    }),1485    close: async () => {1486      androidSyncFrameQueues.delete(connectionId);1487    },1488  };1489}14901491// Returns username use-counts from the vault, sorted by frequency. Each row1492// also carries the entry's email so the popup can suggest the email/username1493// pair the user has actually used together.1494function buildIdentitySuggestions(1495  entries: VaultEntry[],1496): Array<{ email: string; username: string; count: number }> {1497  const usernameCounts = new Map<string, number>();1498  const usernameEmail = new Map<string, string>();1499  for (const entry of entries) {1500    const username = entry.username ?? "";1501    const email = (entry as VaultEntry & { email?: string }).email ?? "";1502    if (!username && !email) continue;1503    const key = username || email;1504    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1505    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1506  }1507  return Array.from(usernameCounts.entries())1508    .sort((a, b) => b[1] - a[1])1509    .map(([username, count]) => ({1510      email: usernameEmail.get(username) ?? "",1511      username,1512      count,1513    }));1514}15151516/** Notify all content scripts that the vault just became available. */1517function broadcastToContentScripts(message: { type: string }): void {1518  if (!chrome.tabs?.query) return;1519  chrome.tabs.query({}, (tabs) => {1520    for (const tab of tabs) {1521      if (tab.id !== undefined) {1522        chrome.tabs.sendMessage(tab.id, message).catch(() => {1523          // Tab may not have a content script — silently ignore1524        });1525      }1526    }1527  });1528}15291530function shouldRefreshAutoLock(type: MessageType): boolean {1531  return (1532    type !== "HAS_VAULT" &&1533    type !== "IS_UNLOCKED" &&1534    type !== "GET_VAULT_STATUS" &&1535    type !== "LOCK" &&1536    type !== "UPDATE_SETTINGS" &&1537    type !== "GET_PENDING_PASSKEY" &&1538    type !== "GET_PASSKEY_PROVIDER_STATE" &&1539    type !== "DECLINE_CARD_SAVE" &&1540    type !== "IS_CARD_DECLINED" &&1541    type !== "SUBMIT_FEEDBACK"1542  );1543}15441545function isAllowedCanaryWebhookUrl(value: string): boolean {1546  try {1547    const url = new URL(value);1548    if (url.protocol !== "https:") return false;15491550    const hostname = url.hostname.toLowerCase();1551    if (1552      hostname === "localhost" ||1553      hostname.endsWith(".localhost") ||1554      isPrivateIpv4(hostname) ||1555      isPrivateIpv6(hostname)1556    ) {1557      return false;1558    }15591560    return true;1561  } catch {1562    return false;1563  }1564}15651566function isPrivateIpv4(hostname: string): boolean {1567  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1568    return true;1569  }15701571  const octets = hostname.split(".").map((part) => Number(part));1572  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1573    return false;1574  }15751576  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1577}15781579function isPrivateIpv6(hostname: string): boolean {1580  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1581  return (1582    normalized === "::1" ||1583    normalized.startsWith("fc") ||1584    normalized.startsWith("fd") ||1585    normalized.startsWith("fe80:")1586  );1587}