messages.ts

60.6 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard } from "./clipboard";13import { setupAutoLock, touchAutoLock } from "./alarms";14import * as vault from "./vault";15import {16  handleEstimateCodexPages,17  handleGetCodexVaultData,18  handleRestoreFromCodex,19} from "./codex-handlers";20import type { CodexRestorePayload } from "../shared/codex-types";21import {22  activateLicense,23  deactivateLicense,24  getLicenseInfo,25  getLicenseKey,26  isProUser,27  markCelebrationPlayed,28  shouldPlayCelebration,29} from "./license";30import {31  cancelFirefoxPasskeyCreate,32  completeFirefoxPasskeyCreate,33  getPasskeyProviderState,34  getPendingPasskeyRequest,35  handleFirefoxPasskeyCreate,36  handleFirefoxPasskeyGet,37  handlePasskeyHasCredentials,38  initiateFirefoxPasskeyCreate,39  isPasskeyOfferDeclined,40  onVaultUnlocked,41  recordPasskeyOfferDecline,42  resolvePendingPasskeyRequest,43  setPasskeyProviderEnabled,44} from "./passkey";45import { buildAdvancedHealthReport, resolveResetUrl } from "./health";46import { storageClear, storageGet } from "../shared/storage";47import { findInvalidWords } from "../shared/recovery-words";48import {49  addPairedDevice,50  addTrustedNetwork,51  clearIncomingPairingRequest,52  getIncomingPairingRequest,53  getPairedDevices,54  getTrustedNetworks,55  removePairedDevice,56  removeTrustedNetwork,57  setIncomingPairingRequest,58  updatePairedDevice,59} from "./sync-storage";60import { getCurrentNetwork, isOnTailscale } from "./sync-network";61import {62  consumeRecentPairing,63  setActivePairingToken,64} from "./pairing-server-state";65import type {66  Message,67  MessageResponse,68  MessageType,69  ProFeature,70  VaultEntry,71} from "../shared/types";72import { isPasskeyOnly } from "../shared/types";73import type { SyncStatus, SyncableDevice } from "../shared/sync-types";74import { isNativePlatform, nativePlugin } from "../shared/native";75import { runBlobSyncSession, type SyncResult } from "./sync-coordinator";76import type { SyncDeps } from "./sync-coordinator";77import { createWebSocketSyncTransport } from "../shared/websocket-sync-transport";78import { getLocalSubnet, discoverDevice, scanForPairingPhone } from "../shared/local-network";79import { predictBatch as mlPredictBatch } from "./ml";80import type { MLFieldFeatures } from "../shared/ml";81import { base64ToBytes, bytesToBase64 } from "../shared/sync-wire";8283/**84 * The single Pro gate. Every gated handler calls this first; the broadcast85 * lets the popup react (navigate to the License section, highlight the86 * relevant feature). Background never touches the popup view directly —87 * the popup owns navigation. See Projects.md "Pro gate rule".88 */89async function requirePro(90  feature: ProFeature,91  trigger: "user" | "background" = "user"92): Promise<{ allowed: boolean }> {93  if (await isProUser()) return { allowed: true };9495  if (trigger === "user") {96    // User deliberately triggered this feature — redirect the popup immediately.97    chrome.runtime98      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })99      .catch(() => {100        // Popup may be closed — the gate signal is best-effort.101      });102  } else {103    // Background trigger (e.g. passive sync initiation) — no popup is open.104    // Queue a notice so the next popup open shows a soft banner instead of105    // silently failing.106    if (chrome.storage.session) {107      chrome.storage.session108        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })109        .catch(() => {});110    }111  }112113  return { allowed: false };114}115116// ---------------------------------------------------------------------------117// Local device name. Peers see this string in PAIR_REQUEST / PAIR_ACCEPT and118// next to the device in their paired-devices list. Default to a platform-aware119// fallback when the user hasn't set one explicitly.120const DEVICE_NAME_KEY = "peach_device_name";121122async function getLocalDeviceName(): Promise<string> {123  try {124    const stored = await chrome.storage.local.get(DEVICE_NAME_KEY);125    const value = (stored as Record<string, string | undefined>)[DEVICE_NAME_KEY];126    if (typeof value === "string" && value.trim()) return value.trim();127  } catch {128    // fall through to default129  }130  return "Peach";131}132133// ---------------------------------------------------------------------------134// 6-digit code pairing.135136const PAIRING_TOKEN_TTL_MS = 5 * 60 * 1000;137138139function generateSixDigitToken(): string {140  // crypto.getRandomValues, not Math.random — the token is the only secret141  // protecting the pairing window from a same-LAN attacker. 6 decimal digits142  // is 1 in 1,000,000; combined with a 5-minute TTL and pairing-mode gating143  // on the responder this is the right tradeoff between UX and security.144  const buf = new Uint32Array(1);145  crypto.getRandomValues(buf);146  const value = buf[0] % 1_000_000;147  return value.toString().padStart(6, "0");148}149150// ---------------------------------------------------------------------------151// Peer discovery glue (Phase 7 popup pairing flow).152153const PRIVATE_IPV4_RANGES = [154  { prefix: "10." },155  { prefix: "127." },156  { prefix: "169.254." },157  { prefix: "192.168." },158];159160// Empty disables network submission while the UI continues to function as a161// no-op (the handler returns ok:true without calling fetch). When set, the162// URL is validated by `isAllowedCanaryWebhookUrl` before any request, so the163// same private-IP/HTTPS rules that gate canary webhooks apply here.164const FEEDBACK_ENDPOINT = "";165166// ---------------------------------------------------------------------------167// Sync helpers168// ---------------------------------------------------------------------------169170function buildSyncDeps(): SyncDeps {171  return {172    isVaultUnlocked: () => vault.isUnlocked(),173    getVaultBlobForSync: async () => {174      const base = await vault.getVaultBlobForSync();175      if (!base) return null;176      const paired = await getPairedDevices();177      return {178        ...base,179        devices: paired180          .filter(d => d.x25519PublicKey)181          .map(d => ({182            publicKeyHex: d.x25519PublicKey,183            deviceName: d.displayName,184            pairedAt: d.pairedAt,185          })),186      };187    },188    applyIncomingVault: async (blob, ts, license, devices) => {189      const applied = await vault.applyIncomingVault(blob, ts, license);190      if (devices?.length) await mergeDeviceRegistry(devices);191      if (applied) await vault.reloadEntriesAfterSync();192      return applied;193    },194  };195}196197async function doVaultSync(ip: string, publicKeyHex: string): Promise<SyncResult> {198  try {199    const transport = await createWebSocketSyncTransport(`ws://${ip}:44100`, publicKeyHex);200    return await runBlobSyncSession('initiator', transport, buildSyncDeps());201  } catch (err) {202    return { status: 'errored', applied: false, error: String(err) };203  }204}205206async function mergeDeviceRegistry(incoming: SyncableDevice[]): Promise<void> {207  const existing = await getPairedDevices();208  const existingKeys = new Set(existing.map(d => d.x25519PublicKey));209  for (const device of incoming) {210    if (!existingKeys.has(device.publicKeyHex)) {211      await addPairedDevice({212        deviceId: device.publicKeyHex,213        displayName: device.deviceName,214        x25519PublicKey: device.publicKeyHex,215        pairedAt: device.pairedAt,216        lastSeenAt: 0,217        lastKnownIp: '',218      }).catch(() => {});219    }220  }221}222223// Background pairing scan — runs after START_PAIRING_SERVER fires on desktop.224// Scans the local subnet for a phone that has accepted the pairing token,225// stores it, runs the initial vault exchange, then notifies the popup.226async function runPairingSubnetScan(token: string): Promise<void> {227  const subnet = await getLocalSubnet();228  if (!subnet) return;229230  const found = await scanForPairingPhone(subnet, token);231  if (!found) return;232233  const { ip, publicKeyHex } = found;234235  try {236    await addPairedDevice({237      deviceId: publicKeyHex,238      displayName: 'Peach',239      x25519PublicKey: publicKeyHex,240      pairedAt: Date.now(),241      lastSeenAt: Date.now(),242      lastKnownIp: ip,243    });244  } catch {245    // Already paired — update IP246    await updatePairedDevice(publicKeyHex, { lastKnownIp: ip, lastSeenAt: Date.now() });247  }248249  // Immediate vault exchange — the free one-time transfer250  await doVaultSync(ip, publicKeyHex);251252  chrome.runtime.sendMessage({253    type: 'PAIRING_COMPLETED',254    payload: { deviceName: 'Peach', publicKeyHex, deviceIp: ip },255  }).catch(() => {});256}257258export function setupMessageHandler(): void {259  chrome.runtime.onMessage.addListener(260    (msg: unknown, sender, sendResponse) => {261      if (!isMessage(msg)) {262        sendResponse({ ok: false, error: "invalid message" });263        return true;264      }265      handleMessage(msg, sender)266        .then(sendResponse)267        .catch((err) =>268          sendResponse({269            ok: false,270            error: err instanceof Error ? err.message : String(err),271          })272        );273      return true;274    }275  );276277  // Android: the chrome shim queues sendMessage calls until this handler is278  // registered. Without this hookup, every message hangs on Capacitor builds.279  // eslint-disable-next-line @typescript-eslint/no-explicit-any280  const reg = (globalThis as any).__peachRegisterMessageHandler;281  if (typeof reg === "function") {282    reg(async (m: unknown) => {283      if (!isMessage(m)) return { ok: false, error: "invalid message" };284      try {285        return await handleMessage(m);286      } catch (err) {287        return {288          ok: false,289          error: err instanceof Error ? err.message : String(err),290        };291      }292    });293  }294295  // Android: subscribe to SyncPlugin events.296  if (isNativePlatform()) {297    const syncPlug = nativePlugin<{298      addListener: (299        event: string,300        handler: (data: Record<string, string>) => void301      ) => void;302    }>("SyncPlugin");303304    // Pairing probe answered — store the paired device (desktop, no IP needed305    // since the desktop never acts as a WS server).306    syncPlug?.addListener?.("peach:pair-probe-answered", (data) => {307      const deviceName = data.deviceName ?? "Peach";308      const publicKeyHex = data.publicKeyHex ?? "";309      void (async () => {310        const { addPairedDevice, setHasPaired: setPaired } = await import("./sync-storage");311        await addPairedDevice({312          deviceId: publicKeyHex || (data.connectionId ?? "unknown"),313          displayName: deviceName,314          x25519PublicKey: publicKeyHex,315          pairedAt: Date.now(),316          lastSeenAt: Date.now(),317        }).catch(() => {});318        await setPaired();319        chrome.runtime.sendMessage({320          type: "PAIRING_COMPLETED",321          payload: { deviceName },322        }).catch(() => {});323      })();324    });325326    // Sync frame received — route to the waiting responder session.327    syncPlug?.addListener?.("peach:sync-frame", (data) => {328      const { connectionId, frame } = data;329      if (connectionId && frame) deliverAndroidSyncFrame(connectionId, frame);330    });331332    // Sync session started (SYNC_HELLO received by SyncPlugin) — dispatch as333    // a background message so SYNC_SESSION_STARTED handler runs the responder.334    syncPlug?.addListener?.("peach:sync-session-started", (data) => {335      const { connectionId } = data;336      if (!connectionId) return;337      void handleMessage({ type: "SYNC_SESSION_STARTED", payload: { connectionId } });338    });339  }340}341342function isMessage(m: unknown): m is Message {343  return typeof m === "object" && m !== null && "type" in m;344}345346export async function handleMessage(347  msg: Message,348  sender: Partial<chrome.runtime.MessageSender> = {}349): Promise<MessageResponse> {350  try {351    // Validate sender — only allow messages from our extension pages/scripts.352    // `sender.id` is undefined for messages originating from extension UI353    // (popup/options), which is legitimate; reject only when it is defined354    // and does not match our extension id.355    if (356      sender.id !== undefined &&357      sender.id !== chrome.runtime.id358    ) {359      return { ok: false, error: "invalid sender" };360    }361362    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {363      touchAutoLock();364    }365366    switch (msg.type) {367      case "CREATE_VAULT": {368        const { password } = msg.payload as { password: string };369        await vault.createVault(password);370        await setupAutoLock();371        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });372        onVaultUnlocked();373        return { ok: true };374      }375      case "UNLOCK": {376        const { password } = msg.payload as { password: string };377        const ok = await vault.unlock(password);378        if (ok) {379          await setupAutoLock();380          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });381          onVaultUnlocked();382          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());383        }384        return { ok };385      }386      case "VALIDATE_RECOVERY_WORDS": {387        const { words } = msg.payload as { words: string[] };388        const invalid = findInvalidWords(words);389        return { ok: true, data: { valid: invalid.length === 0, invalid } };390      }391      case "GET_RECOVERY_WORDS": {392        // Must be unlocked and have recovery set up (vault must be v2.12+).393        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };394        try {395          const words = await vault.getRecoveryWords();396          return { ok: true, data: words };397        } catch (e) {398          // pre-v2.12 vault that hasn't migrated399          return { ok: false, error: "recovery_not_setup" };400        }401      }402      case "RECOVER_WITH_WORDS": {403        // User has lost their password but has their 12 recovery words.404        // We: (1) validate the words, (2) re-encrypt vault with new password.405        const { words, newPassword } = msg.payload as {406          words: string[];407          newPassword: string;408        };409        const stored = await vault.loadSlotA();410        if (!stored) return { ok: false, error: "no vault" };411        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {412          return { ok: false, error: "recovery_not_setup" };413        }414        // Unwrap the root key from the recovery escrow.415        try {416          await vault.unwrapRootKeyForRecovery(417            stored.recovery_wrapped_root_key,418            stored.recovery_nonce ?? "",419            stored.recovery_tag ?? "",420            stored.recovery_salt,421            words422          );423        } catch {424          return { ok: false, error: "invalid_recovery_words" };425        }426        // Re-key: derive fresh salt + key from new password.427        const newSalt = vault.generateSalt();428        const newKey = await vault.deriveKey(newPassword, newSalt);429        // Re-wrap root key under the new password's derived key so the same430        // recovery words continue to work after the password change.431        await vault.rewrapRootKeyForPassword(newKey, newSalt);432        // Re-encrypt vault entries with the new key.433        await vault.changePasswordWithNewKey(newSalt, newKey);434        await setupAutoLock();435        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });436        return { ok: true };437      }438      case "LOCK":439        vault.lock();440        if (isNativePlatform()) await clearInMemoryVault();441        return { ok: true };442      case "IS_UNLOCKED":443        return { ok: true, data: vault.isUnlocked() };444      case "GET_VAULT_STATUS":445        return { ok: true, unlocked: vault.isUnlocked() };446      case "HAS_VAULT":447        return { ok: true, data: await vault.hasVault() };448      case "GET_ENTRIES":449        return { ok: true, data: vault.getEntries() };450      case "ADD_ENTRY": {451        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };452        const entry = await vault.addEntry(msg.payload as any);453        return { ok: true, data: entry };454      }455      case "BATCH_ADD_ENTRIES": {456        const { entries } = msg.payload as { entries: any[] };457        const added = await vault.batchAddEntries(entries);458        return { ok: true, data: added };459      }460      case "RESTORE_ENTRIES": {461        const { entries, mode, settings } = msg.payload as {462          entries: any[];463          mode: "replace" | "merge";464          settings?: vault.VaultSettings;465        };466        const summary = await vault.restoreEntries(entries, mode);467        if (settings && typeof settings === "object") {468          await vault.updateSettings(settings);469        }470        return { ok: true, data: summary };471      }472      case "CLEAR_VAULT_ENTRIES": {473        await vault.clearVaultEntries("REPLACE_ALL");474        return { ok: true };475      }476      case "GET_VAULT_HISTORY": {477        const snapshots = await vault.getVaultHistory();478        return { ok: true, data: snapshots };479      }480      case "RESTORE_VAULT_SNAPSHOT": {481        const { snapshotId } = msg.payload as { snapshotId: string };482        const result = await vault.restoreVaultSnapshot(snapshotId);483        if (!result.ok) return { ok: false, error: result.error };484        broadcastToContentScripts({ type: "VAULT_LOCKED" });485        return { ok: true };486      }487      case "COUNT_DUPLICATES": {488        return { ok: true, data: vault.countDuplicates() };489      }490      case "DEDUPLICATE_ENTRIES": {491        const removed = await vault.deduplicateEntries();492        return { ok: true, data: removed };493      }494      case "UPDATE_ENTRY": {495        const { id, patch } = msg.payload as any;496        await vault.updateEntry(id, patch);497        return { ok: true };498      }499      case "ADD_ADDITIONAL_URL": {500        const { id, url } = msg.payload as { id: string; url: string };501        const trimmed = typeof url === "string" ? url.trim() : "";502        if (!trimmed) return { ok: false, error: "url required" };503        const existing = vault.getEntryById(id);504        if (!existing) return { ok: false, error: "entry not found" };505        if (existing.type !== "login") return { ok: false, error: "login entries only" };506        const merged = [...(existing.additionalUrls ?? []), trimmed];507        await vault.updateEntry(id, { additionalUrls: merged });508        return { ok: true };509      }510      case "DELETE_ENTRY": {511        const { id } = msg.payload as { id: string };512        await vault.deleteEntry(id);513        return { ok: true };514      }515      case "GET_DELETED_ENTRIES":516        return { ok: true, data: vault.getDeletedEntries() };517      case "RESTORE_ENTRY": {518        const { id } = msg.payload as { id: string };519        await vault.restoreEntry(id);520        return { ok: true };521      }522      case "PURGE_ENTRY": {523        const { id } = msg.payload as { id: string };524        await vault.purgeEntry(id);525        return { ok: true };526      }527      case "PURGE_EXPIRED_TRASH": {528        const { retentionMs } = msg.payload as { retentionMs: number };529        const purged = await vault.purgeExpiredTrash(retentionMs);530        return { ok: true, data: purged };531      }532      case "SAVE_NOTE": {533        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };534        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };535        const now = Date.now();536        if (id) {537          const existing = vault.getEntryById(id);538          if (!existing) return { ok: false, error: "not_found" };539          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });540          return { ok: true, data: vault.getEntryById(id) };541        } else {542          const entry = await vault.addEntry({543            type: "note",544            title: title || "Untitled",545            notes: body,546            createdAt: now,547            modifiedAt: now,548          } as any);549          return { ok: true, data: entry };550        }551      }552      case "DELETE_NOTE": {553        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };554        const { id } = msg.payload as { id: string };555        await vault.deleteEntry(id);556        return { ok: true };557      }558      case "AUTOFILL_QUERY": {559        if (!vault.isUnlocked()) {560          return { ok: false, error: "VAULT_LOCKED" };561        }562        const { domain, includeAll, kind } = msg.payload as {563          domain: string;564          includeAll?: boolean;565          kind?: "login" | "card";566        };567        // kind="card": return saved cards as compact summaries for the568        // inline card silver platter. Cards are not domain-scoped — every569        // saved card is a candidate on every checkout page — so domain is570        // ignored when kind === "card".571        if (kind === "card") {572          const cards = vault.getEntries().filter((e) => e.type === "card");573          return {574            ok: true,575            data: cards.map((e) => ({576              id: e.id,577              title: e.cardNickname || e.title,578              cardholderName: e.cardholderName,579              last4: e.last4,580              expMonth: e.expMonth,581              expYear: e.expYear,582              network: e.network,583            })),584          };585        }586        // The inline selector fills username+password into a form. Passkey-587        // only entries have no password to fill; sign-in for those goes588        // through the WebAuthn path instead. Filter them out everywhere so589        // the user doesn't see four "GitHub" rows that mostly do nothing.590        // Notes and cards never belonged here either.591        const matches = (592          includeAll593            ? vault594                .getEntries()595                .filter((entry) => entry.type !== "note" && entry.type !== "card")596            : vault.queryDomain(domain)597        ).filter((entry) => !isPasskeyOnly(entry));598        return {599          ok: true,600          data: matches.map((e) =>601            includeAll602              ? {603                  id: e.id,604                  title: e.title,605                  hasPasskey: e.passkey !== undefined,606                }607              : {608                  id: e.id,609                  title: e.title,610                  username: e.username,611                  email: e.email,612                  url: e.url,613                  hasTotp: Boolean(e.totp),614                  hasPasskey: e.passkey !== undefined,615                }616          ),617        };618      }619      case "GET_ENTRY_FOR_FILL": {620        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };621        const { id } = msg.payload as { id: string };622        const entry = vault.getEntryById(id);623        if (!entry) return { ok: false, error: "entry not found" };624        // Passkey-only entries (passkey credential, no password) cannot be625        // filled into a form — sign-in goes through the WebAuthn path. A626        // login that ALSO has a passkey is still fillable for its password.627        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey not fillable" };628        // Strip the passkey credential from the response — content scripts629        // never need the private key, and there's no reason to expose the630        // public credential metadata over the boundary either.631        const { passkey: _strippedPasskey, ...safeEntry } = entry;632        return { ok: true, data: safeEntry };633      }634      case "COPY": {635        const { text, label, alreadyWritten } = msg.payload as {636          text: string;637          label: string;638          alreadyWritten?: boolean;639        };640        await copyToClipboard(text, label, Boolean(alreadyWritten));641        return { ok: true };642      }643      case "CHECK_ALL_BREACHES": {644        const allEntries = vault.getEntries();645        const results: Record<string, number> = {};646        for (const entry of allEntries) {647          if (entry.type === "note") continue;648          if (!entry.password) continue;649          results[entry.id] = await vault.checkBreach(entry.password);650          // Small delay — be a good citizen to the HIBP API651          await new Promise((r) => setTimeout(r, 200));652        }653        // Persist any non-zero counts back to entries654        for (const [id, count] of Object.entries(results)) {655          const entry = vault.getEntryById(id);656          if (entry && (entry.breach ?? 0) !== count) {657            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });658          }659        }660        return { ok: true, data: results };661      }662      case "GET_SETTINGS":663        return { ok: true, data: await vault.ensureSettingsLoaded() };664      case "UPDATE_SETTINGS": {665        const patch = msg.payload as Record<string, unknown>;666        await vault.updateSettings(patch as any);667        if (typeof patch.autoLockMinutes === "number") {668          await setupAutoLock();669          if (vault.isUnlocked()) touchAutoLock();670        }671        return { ok: true };672      }673      case "GET_PENDING_PASSKEY":674        return { ok: true, data: await getPendingPasskeyRequest() };675      case "APPROVE_PASSKEY": {676        const { requestId } = msg.payload as { requestId: number };677        await resolvePendingPasskeyRequest(requestId, true);678        return { ok: true };679      }680      case "DENY_PASSKEY": {681        const { requestId } = msg.payload as { requestId: number };682        await resolvePendingPasskeyRequest(requestId, false);683        return { ok: true };684      }685      case "GET_PASSKEY_PROVIDER_STATE":686        return { ok: true, data: await getPasskeyProviderState() };687      case "SET_PASSKEY_PROVIDER_ENABLED": {688        const { enabled } = msg.payload as { enabled: boolean };689        // Disabling is always free; gating fires only when a free user is690        // trying to turn passkey interception on.691        if (enabled) {692          const gate = await requirePro("passkeys");693          if (!gate.allowed) return { ok: false, error: "pro_required" };694        }695        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };696      }697      case "FIRE_CANARY_PING": {698        const { webhookUrl, entryTitle, trigger } = msg.payload as {699          webhookUrl: string;700          entryTitle: string;701          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";702        };703        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {704          return { ok: false, error: "invalid webhook url" };705        }706        const body = JSON.stringify({707          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",708          entry: entryTitle,709          trigger,710          timestamp: new Date().toISOString(),711          source: "peach-extension",712        });713        if (trigger === "test") {714          // Permitted outbound fetch: user-configured canary alert endpoint715          // (validated by isAllowedCanaryWebhookUrl above). This is the716          // only non-HIBP outbound call in the extension — see717          // Projects.md §3.7. Test pings are awaited so the UI can show718          // success/failure.719          try {720            const res = await fetch(webhookUrl, {721              method: "POST",722              headers: { "Content-Type": "application/json" },723              body,724            });725            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };726          } catch (err) {727            return { ok: false, error: err instanceof Error ? err.message : "network error" };728          }729        }730        // Non-test triggers are fire-and-forget731        fetch(webhookUrl, {732          method: "POST",733          headers: { "Content-Type": "application/json" },734          body,735        }).catch(() => {});736        return { ok: true };737      }738      case "ACTIVATE_LICENSE": {739        const { key } = msg.payload as { key: string };740        const licenseInfo = await activateLicense(key);741        return { ok: true, data: licenseInfo };742      }743      case "GET_LICENSE": {744        const licenseInfo = await getLicenseInfo();745        return { ok: true, data: licenseInfo };746      }747      case "GET_LICENSE_KEY": {748        const key = await getLicenseKey();749        return { ok: true, data: key };750      }751      case "DEACTIVATE_LICENSE": {752        await deactivateLicense();753        return { ok: true };754      }755      case "SHOULD_PLAY_CELEBRATION": {756        const should = await shouldPlayCelebration();757        return { ok: true, data: should };758      }759      case "MARK_CELEBRATION_PLAYED": {760        await markCelebrationPlayed();761        return { ok: true };762      }763      case "GET_CODEX_VAULT_DATA": {764        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the765        // popup navigates to the License section without further coordination.766        const gate = await requirePro("codex");767        if (!gate.allowed) return { ok: false, error: "pro_required" };768        return await handleGetCodexVaultData();769      }770      case "ESTIMATE_CODEX_PAGES": {771        const gate = await requirePro("codex");772        if (!gate.allowed) return { ok: false, error: "pro_required" };773        return await handleEstimateCodexPages();774      }775      case "RESTORE_FROM_CODEX": {776        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still777        // be able to restore a vault that was printed by a Pro user.778        // DO NOT add a Pro gate here.779        const payload = msg.payload as CodexRestorePayload;780        return await handleRestoreFromCodex(payload);781      }782      case "OPEN_PRO_GATE": {783        // Content script requests: open popup and navigate to License section.784        const { feature } = (msg.payload ?? {}) as { feature?: string };785        if (chrome.storage.session) {786          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });787        }788        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }789        return { ok: true };790      }791      case "GET_IDENTITIES": {792        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };793        return { ok: true, data: vault.getIdentities() };794      }795      case "TOUCH_AUTO_LOCK": {796        // touchAutoLock() is already called by shouldRefreshAutoLock above;797        // this case just gives the popup a typed message to keep the session alive.798        return { ok: true };799      }800      case "GET_ADVANCED_HEALTH_REPORT": {801        const gate = await requirePro("advanced_health");802        if (!gate.allowed) return { ok: false, error: "pro_required" };803        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };804        const report = await buildAdvancedHealthReport(vault.getEntries());805        return { ok: true, data: report };806      }807      case "INITIATE_PASSWORD_CHANGE": {808        const gate = await requirePro("smart_password_change");809        if (!gate.allowed) return { ok: false, error: "pro_required" };810        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };811        const { id } = msg.payload as { id: string };812        const entry = vault.getEntryById(id);813        if (!entry) return { ok: false, error: "entry not found" };814        const url = resolveResetUrl(entry);815        if (!url) return { ok: false, error: "no reset url" };816        try {817          await chrome.tabs.create({ url });818          return { ok: true, data: { url } };819        } catch (err) {820          return {821            ok: false,822            error: err instanceof Error ? err.message : "failed to open tab",823          };824        }825      }826      case "IS_DURESS_ENABLED": {827        const enabled = await vault.isDuressEnabled();828        return { ok: true, data: enabled };829      }830      case "SETUP_DURESS": {831        const { duressPassword } = msg.payload as { duressPassword: string };832        await vault.setupDuress(duressPassword);833        return { ok: true };834      }835      case "DISABLE_DURESS": {836        await vault.disableDuress();837        return { ok: true };838      }839      case "VERIFY_MAIN_PASSWORD": {840        const { password } = msg.payload as { password: string };841        const ok = await vault.verifyMainPassword(password);842        return { ok: true, data: ok };843      }844      case "CHANGE_PASSWORD": {845        const { currentPassword, newPassword } = msg.payload as {846          currentPassword: string;847          newPassword: string;848        };849        const changed = await vault.changePassword(currentPassword, newPassword);850        return changed851          ? { ok: true }852          : { ok: false, error: "incorrect current password" };853      }854      case "GET_SITE_PASSWORD_POLICY": {855        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });856        if (!tab?.id) return { ok: true, data: null };857        try {858          const response = await chrome.tabs.sendMessage(tab.id, {859            type: "GET_SITE_PASSWORD_POLICY",860          });861          return (response as MessageResponse) ?? { ok: true, data: null };862        } catch {863          return { ok: true, data: null };864        }865      }866      case "GET_SYNC_STATE": {867        const pairedDevices = await getPairedDevices();868        const trustedNetworks = await getTrustedNetworks();869        const tailscale = await isOnTailscale();870        const pro = await isProUser();871872        let status: SyncStatus = "offline";873        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {874          if (pairedDevices.length === 0) {875            status = "no_peers";876          } else {877            status = "synced";878          }879        } else {880          status = "not_trusted";881        }882883        const lastSyncRaw = await storageGet("peach_last_sync_at");884        const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN;885        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined;886887        return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } };888      }889      case "GET_PAIRED_DEVICES": {890        const devices = await getPairedDevices();891        return { ok: true, data: { devices } };892      }893      case "GET_SYNC_STATUS": {894        const lastSyncRaw = await storageGet("peach_last_sync_at");895        const lastSyncParsed = lastSyncRaw ? parseInt(lastSyncRaw, 10) : NaN;896        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : null;897        const status: 'up_to_date' | 'never' = lastSyncAt ? 'up_to_date' : 'never';898        return { ok: true, data: { status, lastSyncAt } };899      }900      case "ACCEPT_PAIRING": {901        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.902        return { ok: true };903      }904      case "REMOVE_PAIRED_DEVICE": {905        const { deviceId } = msg.payload as { deviceId: string };906        await removePairedDevice(deviceId);907        return { ok: true };908      }909      case "REMOVE_TRUSTED_NETWORK": {910        const { ssid, bssid, isTailscale } = msg.payload as any;911        const networks = await getTrustedNetworks();912        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 913          (isTailscale ? n.isTailscale : n.ssid === ssid) && 914          (!bssid || n.bssid === bssid)915        );916        if (network) {917          await removeTrustedNetwork(network.addedAt);918        }919        return { ok: true };920      }921      case "MARK_NETWORK_TRUSTED": {922        const network = await getCurrentNetwork();923        await addTrustedNetwork({924          ssid: network.ssid,925          bssid: network.bssid,926          isTailscale: network.isTailscale,927          addedAt: Date.now(),928        });929        return { ok: true };930      }931      case "GET_INCOMING_PAIRING_REQUEST": {932        const request = await getIncomingPairingRequest();933        return { ok: true, data: request };934      }935      case "RESPOND_INCOMING_PAIRING": {936        const { accept } = msg.payload as { accept: boolean };937        const request = await getIncomingPairingRequest();938        if (!request) return { ok: false, error: "no_pending_request" };939        if (Date.now() > request.expiresAt) {940          await clearIncomingPairingRequest();941          return { ok: false, error: "expired" };942        }943        await clearIncomingPairingRequest();944        if (accept) {945          await addPairedDevice({946            deviceId: request.publicKeyHex,947            displayName: request.deviceName,948            x25519PublicKey: request.publicKeyHex,949            pairedAt: Date.now(),950            lastSeenAt: Date.now(),951          });952        }953        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };954      }955      case "START_PAIRING_SERVER": {956        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.957        const token = generateSixDigitToken();958        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;959        await setActivePairingToken({ token, expiresAt });960        // Fire-and-forget subnet scan — finds the phone after it scans the QR961        // and calls SCAN_PAIRING_QR to register the token with SyncPlugin.962        if (!isNativePlatform()) {963          void runPairingSubnetScan(token);964        }965        return { ok: true, data: { token, expiresAt } };966      }967      case "STOP_PAIRING_SERVER": {968        try {969          await setActivePairingToken(null);970        } catch { /* best-effort */ }971        return { ok: true };972      }973      case "GET_RECENT_PAIRING": {974        const recent = await consumeRecentPairing();975        return { ok: true, data: recent };976      }977      case "DEBUG_INJECT_INCOMING_PAIRING": {978        // Manual E2E rehearsal hook. Inserts a synthetic incoming pairing979        // request into session storage so Phase 7 banner UX can be exercised980        // without a live native host. No Pro gate — this is a no-op in981        // production unless explicitly invoked from a Settings debug action.982        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {983          deviceName?: string;984          publicKeyHex?: string;985        };986        if (!deviceName || !publicKeyHex) {987          return { ok: false, error: "missing_payload" };988        }989        const now = Date.now();990        await setIncomingPairingRequest({991          deviceName,992          publicKeyHex,993          receivedAt: now,994          expiresAt: now + 60_000,995        });996        return { ok: true };997      }998      case "RESET_SYNC_IDENTITY": {999        const gate = await requirePro("sync");1000        if (!gate.allowed) return { ok: false, error: "pro_required" };1001        const devices = await getPairedDevices();1002        for (const device of devices) {1003          await removePairedDevice(device.deviceId);1004        }1005        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };1006      }1007      case "RECORD_MANUAL_SUMMON": {1008        const { domain } = msg.payload as { domain: string };1009        const settings = vault.getSettings();1010        const existing = settings.manualSummonDomains?.[domain];1011        const now = Date.now();1012        await vault.updateSettings({1013          manualSummonDomains: {1014            ...settings.manualSummonDomains,1015            [domain]: {1016              firstSummonedAt: existing?.firstSummonedAt ?? now,1017              summonCount: (existing?.summonCount ?? 0) + 1,1018              lastSummonedAt: now,1019            },1020          },1021        });1022        return { ok: true };1023      }1024      case "DECLINE_CARD_SAVE": {1025        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1026        await vault.declineCardSaveOffer(last4, expMonth, expYear);1027        return { ok: true };1028      }1029      case "IS_CARD_DECLINED": {1030        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1031        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1032        return { ok: true, data: declined };1033      }1034      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1035        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1036          rpId?: string;1037          rpName?: string;1038          userName?: string;1039          userDisplayName?: string;1040        };1041        if (!rpId || !userName) return { ok: false, error: "rpId and userName required" };1042        return await initiateFirefoxPasskeyCreate({1043          rpId,1044          rpName: rpName ?? rpId,1045          userName,1046          userDisplayName,1047        });1048      }10491050      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1051        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1052        if (!payload) return { ok: false, error: "missing payload" };1053        return await completeFirefoxPasskeyCreate(payload);1054      }10551056      case "PASSKEY_OFFER_DECLINE": {1057        const { domain } = (msg.payload ?? {}) as { domain?: string };1058        if (!domain) return { ok: false, error: "domain required" };1059        await recordPasskeyOfferDecline(domain);1060        return { ok: true };1061      }10621063      case "GET_PASSKEY_OFFER_DECLINED": {1064        const { domain } = (msg.payload ?? {}) as { domain?: string };1065        if (!domain) return { ok: false, error: "domain required" };1066        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1067      }10681069      case "PASSKEY_HAS_CREDENTIALS": {1070        const payload = msg.payload as {1071          rpId?: string;1072          allowCredentials?: Array<{ id: string; type?: string }>;1073        } | undefined;1074        if (!payload?.rpId) return { ok: false, error: "rpId required" };1075        return await handlePasskeyHasCredentials({1076          rpId: payload.rpId,1077          allowCredentials: payload.allowCredentials ?? [],1078        });1079      }10801081      case "PASSKEY_CREATE": {1082        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1083        if (!payload?.rpId || !payload?.userName) {1084          return { ok: false, error: "rpId and userName required" };1085        }1086        return await handleFirefoxPasskeyCreate(payload);1087      }10881089      case "PASSKEY_GET": {1090        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1091        if (!payload?.rpId) return { ok: false, error: "rpId required" };1092        return await handleFirefoxPasskeyGet(payload);1093      }10941095      case "PASSKEY_AUTH_RESPONSE": {1096        const { requestId, approved } = (msg.payload ?? {}) as {1097          requestId?: string;1098          approved?: boolean;1099        };1100        if (!requestId || typeof approved !== 'boolean') {1101          return { ok: false, error: 'requestId and approved required' };1102        }1103        await resolvePendingPasskeyRequest(Number(requestId), approved);1104        return { ok: true };1105      }11061107      case "GET_PASSKEY_FOR_DOMAIN": {1108        const { domain } = (msg.payload ?? {}) as { domain?: string };1109        if (!domain) return { ok: false, error: "domain required" };1110        if (!vault.isUnlocked()) return { ok: true, data: null };1111        const match = vault1112          .getEntries()1113          .find((entry) => entry.passkey?.rpId === domain);1114        if (!match || !match.passkey) return { ok: true, data: null };1115        // Slim shape — only the fields State 11 needs. Never expose private1116        // key material, even though this is locked behind isUnlocked.1117        return {1118          ok: true,1119          data: {1120            rpId: match.passkey.rpId,1121            userName: match.passkey.userName,1122            browser: match.passkey.browser,1123          },1124        };1125      }11261127      case "DESTROY_VAULT": {1128        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1129        // storage.local.clear() wipes every Peach key (slots, settings, license,1130        // onboarded flag, history, sync state, declined cards, recall, etc.);1131        // session.clear() wipes pending passkey requests + pro-notice queues.1132        // Caller (Panic.tsx) handles UI navigation back to onboarding.1133        vault.lock();1134        await storageClear();1135        await vault.clearVaultHistory();1136        if (chrome.storage.session) {1137          await chrome.storage.session.clear();1138        }1139        return { ok: true };1140      }11411142      case "SUBMIT_FEEDBACK": {1143        const { category, message, version, browser } = msg.payload as {1144          category: string;1145          message: string;1146          version: string;1147          browser: string;1148        };1149        if (!message.trim()) return { ok: false, error: "message is empty" };1150        if (!FEEDBACK_ENDPOINT) return { ok: true };1151        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1152          return { ok: false, error: "invalid feedback endpoint" };1153        }1154        try {1155          const res = await fetch(FEEDBACK_ENDPOINT, {1156            method: "POST",1157            headers: { "Content-Type": "application/json" },1158            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1159          });1160          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1161        } catch (err) {1162          return { ok: false, error: err instanceof Error ? err.message : "network error" };1163        }1164      }1165      case "TRIGGER_SYNC": {1166        const gate = await requirePro("sync");1167        if (!gate.allowed) return { ok: false, error: "pro_required" };1168        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };11691170        if (isNativePlatform()) {1171          // Phone is the server — ensure it's listening for desktop connections.1172          syncBridge()?.ensureServerRunning?.();1173          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };1174        }11751176        // Desktop: iterate all paired devices and sync with each.1177        const paired = await getPairedDevices();1178        if (!paired.length) return { ok: true, data: { syncedCount: 0, reason: "no_paired_devices" } };11791180        const subnet = await getLocalSubnet();1181        const results: Array<{ device: string } & SyncResult> = [];11821183        for (const device of paired) {1184          if (!device.x25519PublicKey) continue;11851186          let result: SyncResult;11871188          // Fast path — use last known IP1189          if (device.lastKnownIp) {1190            result = await doVaultSync(device.lastKnownIp, device.x25519PublicKey);1191          } else {1192            result = { status: 'errored', applied: false, error: 'no_ip' };1193          }11941195          // Discovery path — scan if fast path failed1196          if (result.status === 'errored' && subnet) {1197            const newIp = await discoverDevice(subnet, device.x25519PublicKey);1198            if (newIp) {1199              await updatePairedDevice(device.x25519PublicKey, { lastKnownIp: newIp });1200              result = await doVaultSync(newIp, device.x25519PublicKey);1201            }1202          }12031204          if (result.status === 'completed') {1205            await updatePairedDevice(device.x25519PublicKey, {1206              lastSeenAt: Date.now(),1207              lastSyncAt: Date.now(),1208            });1209          }12101211          results.push({ device: device.displayName, ...result });1212        }12131214        const syncedCount = results.filter(r => r.status === 'completed').length;1215        if (syncedCount > 0) {1216          await chrome.storage.local.set({ peach_last_sync_at: String(Date.now()) });1217        }1218        return { ok: true, data: { syncedCount, results } };1219      }1220      // Android-only: biometric unlock with pre-derived key.1221      case "UNLOCK_WITH_KEY": {1222        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1223        if (!isNativePlatform()) {1224          return { ok: false, error: "desktop_only_uses_password" };1225        }1226        try {1227          const result = await vault.unlockWithKey(masterKeyHex);1228          if (result.ok) {1229            onVaultUnlocked();1230            await publishInMemoryVault(result.entries);1231          }1232          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1233        } catch {1234          return { ok: false, error: "invalid_key" };1235        }1236      }1237      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1238      case "GET_DERIVED_KEY": {1239        if (!isNativePlatform()) {1240          return { ok: false, error: "android_only" };1241        }1242        if (!vault.isUnlocked()) {1243          return { ok: false, error: "vault_locked" };1244        }1245        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1246      }1247      // Android: scanned a QR containing a desktop pairing token.1248      case "SCAN_PAIRING_QR": {1249        if (!isNativePlatform()) {1250          return { ok: false, error: "android_only" };1251        }1252        const { token } = msg.payload as { token: string };1253        syncBridge()?.startPairingSession?.({ token });1254        return { ok: true };1255      }1256      // Android: desktop opened a sync connection to the phone's WS server.1257      // Run the responder side of the vault exchange.1258      case "SYNC_SESSION_STARTED": {1259        if (!isNativePlatform()) return { ok: false };1260        if (!vault.isUnlocked()) {1261          return { ok: false, error: "vault_locked" };1262        }1263        const { connectionId } = (msg.payload ?? {}) as { connectionId?: string };1264        if (!connectionId) return { ok: false, error: "missing_connection_id" };12651266        const transport = createAndroidResponderTransport(connectionId);1267        const result = await runBlobSyncSession('responder', transport, buildSyncDeps());1268        if (result.applied) {1269          await publishInMemoryVault(vault.getEntries());1270        }1271        return { ok: true, data: result };1272      }1273      // Android: returns the phone's WiFi IP address.1274      case "GET_LOCAL_IP": {1275        if (!isNativePlatform()) {1276          return { ok: false, error: "android_only" };1277        }1278        const { ip } = (await syncBridge()?.getLocalIp?.()) ?? { ip: "" };1279        return { ok: true, data: { ip } };1280      }1281      case "GET_IDENTITY_SUGGESTIONS": {1282        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1283        const entries = vault.getEntries();1284        const suggestions = buildIdentitySuggestions(entries);1285        return { ok: true, data: { suggestions } };1286      }1287      case "POPULATE_INLINE_VAULT": {1288        if (!isNativePlatform()) return { ok: false };1289        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1290        const entries = vault.getEntries();1291        await publishInMemoryVault(entries);1292        return { ok: true };1293      }1294      // --- PNA compatibility test handlers — REMOVE BEFORE RELEASE ---1295      case "TEST_LOCAL_WEBSOCKET": {1296        const { ip } = (msg.payload ?? {}) as { ip?: string };1297        if (!ip) return { ok: false, error: "ip required" };1298        return new Promise((resolve) => {1299          try {1300            const ws = new WebSocket(`ws://${ip}:44100`);1301            ws.onopen = () => { ws.close(); resolve({ ok: true, data: { connected: true } }); };1302            ws.onerror = () => resolve({ ok: false, error: "connection_failed" });1303            setTimeout(() => { ws.close(); resolve({ ok: false, error: "timeout" }); }, 3000);1304          } catch (err) {1305            resolve({ ok: false, error: String(err) });1306          }1307        });1308      }1309      case "TEST_SUBNET_DETECTION": {1310        const subnet = await getLocalSubnet();1311        return { ok: true, data: { subnet } };1312      }1313      case "TEST_SUBNET_SCAN": {1314        const subnet = await getLocalSubnet();1315        if (!subnet) return { ok: false, error: "no_subnet" };1316        const start = Date.now();1317        const result = await discoverDevice(subnet, "000000000000000000000000000000000000000000000000000000000000000000");1318        return { ok: true, data: { elapsed: Date.now() - start, found: !!result } };1319      }1320      case 'TEST_WS_LOCAL': {1321        const { ip } = msg.payload as { ip: string };13221323        return new Promise((resolve) => {1324          const log: string[] = [];1325          log.push(`Attempting ws://${ip}:44100 from service worker...`);13261327          let ws: WebSocket;1328          let settled = false;1329          const settle = (result: MessageResponse) => {1330            if (!settled) { settled = true; resolve(result); }1331          };13321333          try {1334            ws = new WebSocket(`ws://${ip}:44100`);13351336            ws.onopen = () => {1337              log.push('SUCCESS: WebSocket connected');1338              ws.close();1339              settle({ ok: true, data: { log } });1340            };13411342            ws.onerror = (e) => {1343              log.push(`FAILED: onerror fired — ${String(e)}`);1344              settle({ ok: false, error: 'ws_error', data: { log } });1345            };13461347            ws.onclose = (e) => {1348              if (e.code !== 1000) {1349                log.push(`CLOSED unexpectedly: code=${e.code} reason=${e.reason}`);1350                settle({ ok: false, error: 'ws_closed', data: { code: e.code, log } });1351              }1352            };13531354            setTimeout(() => {1355              try { ws.close(); } catch {}1356              log.push('FAILED: 5 second timeout — connection never opened');1357              settle({ ok: false, error: 'timeout', data: { log } });1358            }, 5000);13591360          } catch (err) {1361            log.push(`FAILED: WebSocket constructor threw — ${String(err)}`);1362            settle({ ok: false, error: 'constructor_threw', data: { log } });1363          }1364        });1365      }13661367      case 'TEST_SUBNET_DETECT': {1368        return new Promise((resolve) => {1369          try {1370            // RTCPeerConnection availability varies by context — this is what we're testing1371            // eslint-disable-next-line @typescript-eslint/no-explicit-any1372            const RTC = (globalThis as any).RTCPeerConnection as (new (cfg: object) => RTCPeerConnection) | undefined;1373            if (!RTC) {1374              resolve({ ok: false, error: 'RTCPeerConnection is not defined' });1375              return;1376            }1377            const pc = new RTC({ iceServers: [] });1378            pc.createDataChannel('');1379            pc.createOffer().then((o) => pc.setLocalDescription(o));13801381            const candidates: string[] = [];1382            const timer = setTimeout(() => {1383              pc.close();1384              if (candidates.length === 0) {1385                resolve({ ok: false, error: 'no_candidates', data: { candidates } });1386              } else {1387                const subnet = candidates[0].match(/(\d+\.\d+\.\d+)\.\d+/)?.[1];1388                resolve({ ok: true, data: { subnet, candidates } });1389              }1390            }, 2000);13911392            pc.onicecandidate = (e) => {1393              if (!e.candidate) return;1394              const m = e.candidate.candidate.match(/(\d+\.\d+\.\d+\.\d+)/);1395              if (m && !m[1].startsWith('127')) candidates.push(m[1]);1396            };13971398            pc.onicegatheringstatechange = () => {1399              if (pc.iceGatheringState === 'complete') {1400                clearTimeout(timer);1401                pc.close();1402                const subnet = candidates[0]?.match(/(\d+\.\d+\.\d+)\.\d+/)?.[1];1403                resolve({ ok: candidates.length > 0, data: { subnet, candidates } });1404              }1405            };1406          } catch (err) {1407            resolve({ ok: false, error: String(err) });1408          }1409        });1410      }14111412      // --- end test handlers ---14131414      case "ML_INIT":1415        return { ok: true };14161417      case "ML_PREDICT_BATCH": {1418        const { featuresArray } = msg.payload as { featuresArray: MLFieldFeatures[] };1419        return { ok: true, data: mlPredictBatch(featuresArray) };1420      }14211422      default:1423        return { ok: false, error: "unknown message type" };1424    }1425  } catch (err) {1426    return {1427      ok: false,1428      error: err instanceof Error ? err.message : "operation failed",1429    };1430  }1431}14321433// --- Mobile platform helpers ---14341435// Android: populates the in-memory vault used by PeachAutofillService.1436async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1437  const plugin = nativePlugin<{1438    setEntries?: (args: {1439      entries: Array<{1440        id: string;1441        title: string;1442        username: string;1443        email: string;1444        password: string;1445        url: string;1446        totp: string;1447        additionalUrls: string[];1448      }>;1449    }) => Promise<void>;1450  }>("InMemoryVaultPlugin");1451  if (!plugin?.setEntries) return;1452  await plugin.setEntries({1453    entries: entries.map((e) => ({1454      id: e.id,1455      title: e.title ?? "",1456      username: e.username ?? "",1457      email: (e as VaultEntry & { email?: string }).email ?? "",1458      password: e.password ?? "",1459      url: e.url ?? "",1460      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1461      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1462    })),1463  });1464}14651466// Android: clear the autofill in-memory store on lock.1467async function clearInMemoryVault(): Promise<void> {1468  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1469  if (!plugin?.clearEntries) return;1470  await plugin.clearEntries();1471}14721473interface SyncBridge {1474  ensureServerRunning?: () => void;1475  startPairingSession?: (args: { token: string }) => void;1476  getLocalIp?: () => Promise<{ ip: string }>;1477  sendToConnection?: (args: { connectionId: string; data: string }) => Promise<void>;1478  addListener?: (event: string, handler: (data: Record<string, string>) => void) => void;1479}14801481// Resolve the Capacitor SyncPlugin at call time — module-load resolution1482// races with Capacitor's plugin registration on the Android WebView.1483function syncBridge(): SyncBridge | null {1484  return nativePlugin<SyncBridge>("SyncPlugin");1485}14861487// Build a SyncTransport for the Android responder path — the phone's WS server1488// already has an open connection from the desktop. We send back via1489// SyncPlugin.sendToConnection and receive via the peach:sync-frame queue.1490const androidSyncFrameQueues = new Map<string, Array<(frame: string) => void>>();14911492export function deliverAndroidSyncFrame(connectionId: string, frame: string): void {1493  const queue = androidSyncFrameQueues.get(connectionId);1494  if (queue?.length) queue.shift()!(frame);1495}14961497function createAndroidResponderTransport(connectionId: string) {1498  const pendingReceivers: Array<(frame: string) => void> = [];1499  androidSyncFrameQueues.set(connectionId, pendingReceivers);15001501  return {1502    send: async (data: Uint8Array) => {1503      await syncBridge()?.sendToConnection?.({ connectionId, data: bytesToBase64(data) });1504    },1505    receive: (): Promise<Uint8Array> => new Promise((res) => {1506      pendingReceivers.push((frame) => {1507        res(frame ? base64ToBytes(frame) : new Uint8Array(0));1508      });1509    }),1510    close: async () => {1511      androidSyncFrameQueues.delete(connectionId);1512    },1513  };1514}15151516// Returns username use-counts from the vault, sorted by frequency. Each row1517// also carries the entry's email so the popup can suggest the email/username1518// pair the user has actually used together.1519function buildIdentitySuggestions(1520  entries: VaultEntry[],1521): Array<{ email: string; username: string; count: number }> {1522  const usernameCounts = new Map<string, number>();1523  const usernameEmail = new Map<string, string>();1524  for (const entry of entries) {1525    const username = entry.username ?? "";1526    const email = (entry as VaultEntry & { email?: string }).email ?? "";1527    if (!username && !email) continue;1528    const key = username || email;1529    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1530    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1531  }1532  return Array.from(usernameCounts.entries())1533    .sort((a, b) => b[1] - a[1])1534    .map(([username, count]) => ({1535      email: usernameEmail.get(username) ?? "",1536      username,1537      count,1538    }));1539}15401541/** Notify all content scripts that the vault just became available. */1542function broadcastToContentScripts(message: { type: string }): void {1543  if (!chrome.tabs?.query) return;1544  chrome.tabs.query({}, (tabs) => {1545    for (const tab of tabs) {1546      if (tab.id !== undefined) {1547        chrome.tabs.sendMessage(tab.id, message).catch(() => {1548          // Tab may not have a content script — silently ignore1549        });1550      }1551    }1552  });1553}15541555function shouldRefreshAutoLock(type: MessageType): boolean {1556  return (1557    type !== "HAS_VAULT" &&1558    type !== "IS_UNLOCKED" &&1559    type !== "GET_VAULT_STATUS" &&1560    type !== "LOCK" &&1561    type !== "UPDATE_SETTINGS" &&1562    type !== "GET_PENDING_PASSKEY" &&1563    type !== "GET_PASSKEY_PROVIDER_STATE" &&1564    type !== "DECLINE_CARD_SAVE" &&1565    type !== "IS_CARD_DECLINED" &&1566    type !== "SUBMIT_FEEDBACK"1567  );1568}15691570function isAllowedCanaryWebhookUrl(value: string): boolean {1571  try {1572    const url = new URL(value);1573    if (url.protocol !== "https:") return false;15741575    const hostname = url.hostname.toLowerCase();1576    if (1577      hostname === "localhost" ||1578      hostname.endsWith(".localhost") ||1579      isPrivateIpv4(hostname) ||1580      isPrivateIpv6(hostname)1581    ) {1582      return false;1583    }15841585    return true;1586  } catch {1587    return false;1588  }1589}15901591function isPrivateIpv4(hostname: string): boolean {1592  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1593    return true;1594  }15951596  const octets = hostname.split(".").map((part) => Number(part));1597  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1598    return false;1599  }16001601  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1602}16031604function isPrivateIpv6(hostname: string): boolean {1605  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1606  return (1607    normalized === "::1" ||1608    normalized.startsWith("fc") ||1609    normalized.startsWith("fd") ||1610    normalized.startsWith("fe80:")1611  );1612}