messages.ts

42.7 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard } from "./clipboard";13import { setupAutoLock, touchAutoLock } from "./alarms";14import * as vault from "./vault";15import {16  activateLicense,17  deactivateLicense,18  getLicenseInfo,19  getLicenseKey,20  isProUser,21  markCelebrationPlayed,22  shouldPlayCelebration,23} from "./license";24import {25  cancelFirefoxPasskeyCreate,26  completeFirefoxPasskeyCreate,27  getPasskeyProviderState,28  getPendingPasskeyRequest,29  handleFirefoxPasskeyCreate,30  handleFirefoxPasskeyGet,31  handlePasskeyHasCredentials,32  initiateFirefoxPasskeyCreate,33  isPasskeyOfferDeclined,34  recordPasskeyOfferDecline,35  resolvePendingPasskeyRequest,36  setPasskeyProviderEnabled,37} from "./passkey";38import { buildAdvancedHealthReport, resolveResetUrl } from "./health";39import { storageClear, storageGet } from "../shared/storage";40import { findInvalidWords } from "../shared/recovery-words";41import {42  addPairedDevice,43  addTrustedNetwork,44  clearIncomingPairingRequest,45  getIncomingPairingRequest,46  getPairedDevices,47  getTrustedNetworks,48  removePairedDevice,49  removeTrustedNetwork,50  setIncomingPairingRequest,51} from "./sync-storage";52import { getCurrentNetwork, isOnTailscale } from "./sync-network";53import {54  consumeRecentPairing,55  setActivePairingToken,56} from "./pairing-server-state";57import type {58  Message,59  MessageResponse,60  MessageType,61  ProFeature,62  VaultEntry,63} from "../shared/types";64import { isPasskeyOnly } from "../shared/types";65import type { SyncStatus } from "../shared/sync-types";6667/**68 * The single Pro gate. Every gated handler calls this first; the broadcast69 * lets the popup react (navigate to the License section, highlight the70 * relevant feature). Background never touches the popup view directly —71 * the popup owns navigation. See Projects.md "Pro gate rule".72 */73async function requirePro(74  feature: ProFeature,75  trigger: "user" | "background" = "user"76): Promise<{ allowed: boolean }> {77  if (await isProUser()) return { allowed: true };7879  if (trigger === "user") {80    // User deliberately triggered this feature — redirect the popup immediately.81    chrome.runtime82      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })83      .catch(() => {84        // Popup may be closed — the gate signal is best-effort.85      });86  } else {87    // Background trigger (e.g. passive sync initiation) — no popup is open.88    // Queue a notice so the next popup open shows a soft banner instead of89    // silently failing.90    if (chrome.storage.session) {91      chrome.storage.session92        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })93        .catch(() => {});94    }95  }9697  return { allowed: false };98}99100// ---------------------------------------------------------------------------101// Local device name. Peers see this string in PAIR_REQUEST / PAIR_ACCEPT and102// next to the device in their paired-devices list. Default to a platform-aware103// fallback when the user hasn't set one explicitly.104const DEVICE_NAME_KEY = "peach_device_name";105106async function getLocalDeviceName(): Promise<string> {107  try {108    const stored = await chrome.storage.local.get(DEVICE_NAME_KEY);109    const value = (stored as Record<string, string | undefined>)[DEVICE_NAME_KEY];110    if (typeof value === "string" && value.trim()) return value.trim();111  } catch {112    // fall through to default113  }114  return "Peach";115}116117// ---------------------------------------------------------------------------118// 6-digit code pairing.119120const PAIRING_TOKEN_TTL_MS = 5 * 60 * 1000;121122123function generateSixDigitToken(): string {124  // crypto.getRandomValues, not Math.random — the token is the only secret125  // protecting the pairing window from a same-LAN attacker. 6 decimal digits126  // is 1 in 1,000,000; combined with a 5-minute TTL and pairing-mode gating127  // on the responder this is the right tradeoff between UX and security.128  const buf = new Uint32Array(1);129  crypto.getRandomValues(buf);130  const value = buf[0] % 1_000_000;131  return value.toString().padStart(6, "0");132}133134// ---------------------------------------------------------------------------135// Peer discovery glue (Phase 7 popup pairing flow).136137const PRIVATE_IPV4_RANGES = [138  { prefix: "10." },139  { prefix: "127." },140  { prefix: "169.254." },141  { prefix: "192.168." },142];143144// Empty disables network submission while the UI continues to function as a145// no-op (the handler returns ok:true without calling fetch). When set, the146// URL is validated by `isAllowedCanaryWebhookUrl` before any request, so the147// same private-IP/HTTPS rules that gate canary webhooks apply here.148const FEEDBACK_ENDPOINT = "";149150export function setupMessageHandler(): void {151  chrome.runtime.onMessage.addListener(152    (msg: unknown, sender, sendResponse) => {153      if (!isMessage(msg)) {154        sendResponse({ ok: false, error: "invalid message" });155        return true;156      }157      handleMessage(msg, sender)158        .then(sendResponse)159        .catch((err) =>160          sendResponse({161            ok: false,162            error: err instanceof Error ? err.message : String(err),163          })164        );165      return true;166    }167  );168169  // Android: the chrome shim queues sendMessage calls until this handler is170  // registered. Without this hookup, every message hangs on Capacitor builds.171  // eslint-disable-next-line @typescript-eslint/no-explicit-any172  const reg = (globalThis as any).__peachRegisterMessageHandler;173  if (typeof reg === "function") {174    reg(async (m: unknown) => {175      if (!isMessage(m)) return { ok: false, error: "invalid message" };176      try {177        return await handleMessage(m);178      } catch (err) {179        return {180          ok: false,181          error: err instanceof Error ? err.message : String(err),182        };183      }184    });185  }186}187188function isMessage(m: unknown): m is Message {189  return typeof m === "object" && m !== null && "type" in m;190}191192export async function handleMessage(193  msg: Message,194  sender: Partial<chrome.runtime.MessageSender> = {}195): Promise<MessageResponse> {196  try {197    // Validate sender — only allow messages from our extension pages/scripts.198    // `sender.id` is undefined for messages originating from extension UI199    // (popup/options), which is legitimate; reject only when it is defined200    // and does not match our extension id.201    if (202      sender.id !== undefined &&203      sender.id !== chrome.runtime.id204    ) {205      return { ok: false, error: "invalid sender" };206    }207208    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {209      touchAutoLock();210    }211212    switch (msg.type) {213      case "CREATE_VAULT": {214        const { password } = msg.payload as { password: string };215        await vault.createVault(password);216        await setupAutoLock();217        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });218        return { ok: true };219      }220      case "UNLOCK": {221        const { password } = msg.payload as { password: string };222        const ok = await vault.unlock(password);223        if (ok) {224          await setupAutoLock();225          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });226          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());227        }228        return { ok };229      }230      case "VALIDATE_RECOVERY_WORDS": {231        const { words } = msg.payload as { words: string[] };232        const invalid = findInvalidWords(words);233        return { ok: true, data: { valid: invalid.length === 0, invalid } };234      }235      case "GET_RECOVERY_WORDS": {236        // Must be unlocked and have recovery set up (vault must be v2.12+).237        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };238        try {239          const words = await vault.getRecoveryWords();240          return { ok: true, data: words };241        } catch (e) {242          // pre-v2.12 vault that hasn't migrated243          return { ok: false, error: "recovery_not_setup" };244        }245      }246      case "RECOVER_WITH_WORDS": {247        // User has lost their password but has their 12 recovery words.248        // We: (1) validate the words, (2) re-encrypt vault with new password.249        const { words, newPassword } = msg.payload as {250          words: string[];251          newPassword: string;252        };253        const stored = await vault.loadSlotA();254        if (!stored) return { ok: false, error: "no vault" };255        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {256          return { ok: false, error: "recovery_not_setup" };257        }258        // Unwrap the root key from the recovery escrow.259        try {260          await vault.unwrapRootKeyForRecovery(261            stored.recovery_wrapped_root_key,262            stored.recovery_nonce ?? "",263            stored.recovery_tag ?? "",264            stored.recovery_salt,265            words266          );267        } catch {268          return { ok: false, error: "invalid_recovery_words" };269        }270        // Re-key: derive fresh salt + key from new password.271        const newSalt = vault.generateSalt();272        const newKey = await vault.deriveKey(newPassword, newSalt);273        // Re-wrap root key under the new password's derived key so the same274        // recovery words continue to work after the password change.275        await vault.rewrapRootKeyForPassword(newKey, newSalt);276        // Re-encrypt vault entries with the new key.277        await vault.changePasswordWithNewKey(newSalt, newKey);278        await setupAutoLock();279        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });280        return { ok: true };281      }282      case "LOCK":283        vault.lock();284        if (isNativePlatform()) await clearInMemoryVault();285        return { ok: true };286      case "IS_UNLOCKED":287        return { ok: true, data: vault.isUnlocked() };288      case "GET_VAULT_STATUS":289        return { ok: true, unlocked: vault.isUnlocked() };290      case "HAS_VAULT":291        return { ok: true, data: await vault.hasVault() };292      case "GET_ENTRIES":293        return { ok: true, data: vault.getEntries() };294      case "ADD_ENTRY": {295        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };296        const entry = await vault.addEntry(msg.payload as any);297        return { ok: true, data: entry };298      }299      case "BATCH_ADD_ENTRIES": {300        const { entries } = msg.payload as { entries: any[] };301        const added = await vault.batchAddEntries(entries);302        return { ok: true, data: added };303      }304      case "RESTORE_ENTRIES": {305        const { entries, mode, settings } = msg.payload as {306          entries: any[];307          mode: "replace" | "merge";308          settings?: vault.VaultSettings;309        };310        const summary = await vault.restoreEntries(entries, mode);311        if (settings && typeof settings === "object") {312          await vault.updateSettings(settings);313        }314        return { ok: true, data: summary };315      }316      case "CLEAR_VAULT_ENTRIES": {317        await vault.clearVaultEntries("REPLACE_ALL");318        return { ok: true };319      }320      case "GET_VAULT_HISTORY": {321        const snapshots = await vault.getVaultHistory();322        return { ok: true, data: snapshots };323      }324      case "RESTORE_VAULT_SNAPSHOT": {325        const { snapshotId } = msg.payload as { snapshotId: string };326        const result = await vault.restoreVaultSnapshot(snapshotId);327        if (!result.ok) return { ok: false, error: result.error };328        broadcastToContentScripts({ type: "VAULT_LOCKED" });329        return { ok: true };330      }331      case "COUNT_DUPLICATES": {332        return { ok: true, data: vault.countDuplicates() };333      }334      case "DEDUPLICATE_ENTRIES": {335        const removed = await vault.deduplicateEntries();336        return { ok: true, data: removed };337      }338      case "UPDATE_ENTRY": {339        const { id, patch } = msg.payload as any;340        await vault.updateEntry(id, patch);341        return { ok: true };342      }343      case "ADD_ADDITIONAL_URL": {344        const { id, url } = msg.payload as { id: string; url: string };345        const trimmed = typeof url === "string" ? url.trim() : "";346        if (!trimmed) return { ok: false, error: "url required" };347        const existing = vault.getEntryById(id);348        if (!existing) return { ok: false, error: "entry not found" };349        if (existing.type !== "login") return { ok: false, error: "login entries only" };350        const merged = [...(existing.additionalUrls ?? []), trimmed];351        await vault.updateEntry(id, { additionalUrls: merged });352        return { ok: true };353      }354      case "DELETE_ENTRY": {355        const { id } = msg.payload as { id: string };356        await vault.deleteEntry(id);357        return { ok: true };358      }359      case "GET_DELETED_ENTRIES":360        return { ok: true, data: vault.getDeletedEntries() };361      case "RESTORE_ENTRY": {362        const { id } = msg.payload as { id: string };363        await vault.restoreEntry(id);364        return { ok: true };365      }366      case "PURGE_ENTRY": {367        const { id } = msg.payload as { id: string };368        await vault.purgeEntry(id);369        return { ok: true };370      }371      case "PURGE_EXPIRED_TRASH": {372        const { retentionMs } = msg.payload as { retentionMs: number };373        const purged = await vault.purgeExpiredTrash(retentionMs);374        return { ok: true, data: purged };375      }376      case "AUTOFILL_QUERY": {377        if (!vault.isUnlocked()) {378          return { ok: false, error: "VAULT_LOCKED" };379        }380        const { domain, includeAll, kind } = msg.payload as {381          domain: string;382          includeAll?: boolean;383          kind?: "login" | "card";384        };385        // kind="card": return saved cards as compact summaries for the386        // inline card silver platter. Cards are not domain-scoped — every387        // saved card is a candidate on every checkout page — so domain is388        // ignored when kind === "card".389        if (kind === "card") {390          const cards = vault.getEntries().filter((e) => e.type === "card");391          return {392            ok: true,393            data: cards.map((e) => ({394              id: e.id,395              title: e.cardNickname || e.title,396              cardholderName: e.cardholderName,397              last4: e.last4,398              expMonth: e.expMonth,399              expYear: e.expYear,400              network: e.network,401            })),402          };403        }404        // The inline selector fills username+password into a form. Passkey-405        // only entries have no password to fill; sign-in for those goes406        // through the WebAuthn path instead. Filter them out everywhere so407        // the user doesn't see four "GitHub" rows that mostly do nothing.408        // Notes and cards never belonged here either.409        const matches = (410          includeAll411            ? vault412                .getEntries()413                .filter((entry) => entry.type !== "note" && entry.type !== "card")414            : vault.queryDomain(domain)415        ).filter((entry) => !isPasskeyOnly(entry));416        return {417          ok: true,418          data: matches.map((e) =>419            includeAll420              ? {421                  id: e.id,422                  title: e.title,423                  hasPasskey: e.passkey !== undefined,424                }425              : {426                  id: e.id,427                  title: e.title,428                  username: e.username,429                  email: e.email,430                  url: e.url,431                  hasTotp: Boolean(e.totp),432                  hasPasskey: e.passkey !== undefined,433                }434          ),435        };436      }437      case "GET_ENTRY_FOR_FILL": {438        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };439        const { id } = msg.payload as { id: string };440        const entry = vault.getEntryById(id);441        if (!entry) return { ok: false, error: "entry not found" };442        // Passkey-only entries (passkey credential, no password) cannot be443        // filled into a form — sign-in goes through the WebAuthn path. A444        // login that ALSO has a passkey is still fillable for its password.445        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey not fillable" };446        // Strip the passkey credential from the response — content scripts447        // never need the private key, and there's no reason to expose the448        // public credential metadata over the boundary either.449        const { passkey: _strippedPasskey, ...safeEntry } = entry;450        return { ok: true, data: safeEntry };451      }452      case "COPY": {453        const { text, label, alreadyWritten } = msg.payload as {454          text: string;455          label: string;456          alreadyWritten?: boolean;457        };458        await copyToClipboard(text, label, Boolean(alreadyWritten));459        return { ok: true };460      }461      case "CHECK_ALL_BREACHES": {462        const allEntries = vault.getEntries();463        const results: Record<string, number> = {};464        for (const entry of allEntries) {465          if (entry.type === "note") continue;466          if (!entry.password) continue;467          results[entry.id] = await vault.checkBreach(entry.password);468          // Small delay — be a good citizen to the HIBP API469          await new Promise((r) => setTimeout(r, 200));470        }471        // Persist any non-zero counts back to entries472        for (const [id, count] of Object.entries(results)) {473          const entry = vault.getEntryById(id);474          if (entry && (entry.breach ?? 0) !== count) {475            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });476          }477        }478        return { ok: true, data: results };479      }480      case "GET_SETTINGS":481        return { ok: true, data: await vault.ensureSettingsLoaded() };482      case "UPDATE_SETTINGS": {483        const patch = msg.payload as Record<string, unknown>;484        await vault.updateSettings(patch as any);485        if (typeof patch.autoLockMinutes === "number") {486          await setupAutoLock();487          if (vault.isUnlocked()) touchAutoLock();488        }489        return { ok: true };490      }491      case "GET_PENDING_PASSKEY":492        return { ok: true, data: await getPendingPasskeyRequest() };493      case "APPROVE_PASSKEY": {494        const { requestId } = msg.payload as { requestId: number };495        await resolvePendingPasskeyRequest(requestId, true);496        return { ok: true };497      }498      case "DENY_PASSKEY": {499        const { requestId } = msg.payload as { requestId: number };500        await resolvePendingPasskeyRequest(requestId, false);501        return { ok: true };502      }503      case "GET_PASSKEY_PROVIDER_STATE":504        return { ok: true, data: await getPasskeyProviderState() };505      case "SET_PASSKEY_PROVIDER_ENABLED": {506        const { enabled } = msg.payload as { enabled: boolean };507        // Disabling is always free; gating fires only when a free user is508        // trying to turn passkey interception on.509        if (enabled) {510          const gate = await requirePro("passkeys");511          if (!gate.allowed) return { ok: false, error: "pro_required" };512        }513        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };514      }515      case "FIRE_CANARY_PING": {516        const { webhookUrl, entryTitle, trigger } = msg.payload as {517          webhookUrl: string;518          entryTitle: string;519          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";520        };521        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {522          return { ok: false, error: "invalid webhook url" };523        }524        const body = JSON.stringify({525          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",526          entry: entryTitle,527          trigger,528          timestamp: new Date().toISOString(),529          source: "peach-extension",530        });531        if (trigger === "test") {532          // Permitted outbound fetch: user-configured canary alert endpoint533          // (validated by isAllowedCanaryWebhookUrl above). This is the534          // only non-HIBP outbound call in the extension — see535          // Projects.md §3.7. Test pings are awaited so the UI can show536          // success/failure.537          try {538            const res = await fetch(webhookUrl, {539              method: "POST",540              headers: { "Content-Type": "application/json" },541              body,542            });543            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };544          } catch (err) {545            return { ok: false, error: err instanceof Error ? err.message : "network error" };546          }547        }548        // Non-test triggers are fire-and-forget549        fetch(webhookUrl, {550          method: "POST",551          headers: { "Content-Type": "application/json" },552          body,553        }).catch(() => {});554        return { ok: true };555      }556      case "ACTIVATE_LICENSE": {557        const { key } = msg.payload as { key: string };558        const licenseInfo = await activateLicense(key);559        return { ok: true, data: licenseInfo };560      }561      case "GET_LICENSE": {562        const licenseInfo = await getLicenseInfo();563        return { ok: true, data: licenseInfo };564      }565      case "GET_LICENSE_KEY": {566        const key = await getLicenseKey();567        return { ok: true, data: key };568      }569      case "DEACTIVATE_LICENSE": {570        await deactivateLicense();571        return { ok: true };572      }573      case "SHOULD_PLAY_CELEBRATION": {574        const should = await shouldPlayCelebration();575        return { ok: true, data: should };576      }577      case "MARK_CELEBRATION_PLAYED": {578        await markCelebrationPlayed();579        return { ok: true };580      }581      case "OPEN_PRO_GATE": {582        // Content script requests: open popup and navigate to License section.583        const { feature } = (msg.payload ?? {}) as { feature?: string };584        if (chrome.storage.session) {585          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });586        }587        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }588        return { ok: true };589      }590      case "GET_IDENTITIES": {591        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };592        return { ok: true, data: vault.getIdentities() };593      }594      case "GET_ADVANCED_HEALTH_REPORT": {595        const gate = await requirePro("advanced_health");596        if (!gate.allowed) return { ok: false, error: "pro_required" };597        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };598        const report = await buildAdvancedHealthReport(vault.getEntries());599        return { ok: true, data: report };600      }601      case "INITIATE_PASSWORD_CHANGE": {602        const gate = await requirePro("smart_password_change");603        if (!gate.allowed) return { ok: false, error: "pro_required" };604        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };605        const { id } = msg.payload as { id: string };606        const entry = vault.getEntryById(id);607        if (!entry) return { ok: false, error: "entry not found" };608        const url = resolveResetUrl(entry);609        if (!url) return { ok: false, error: "no reset url" };610        try {611          await chrome.tabs.create({ url });612          return { ok: true, data: { url } };613        } catch (err) {614          return {615            ok: false,616            error: err instanceof Error ? err.message : "failed to open tab",617          };618        }619      }620      case "IS_DURESS_ENABLED": {621        const enabled = await vault.isDuressEnabled();622        return { ok: true, data: enabled };623      }624      case "SETUP_DURESS": {625        const { duressPassword } = msg.payload as { duressPassword: string };626        await vault.setupDuress(duressPassword);627        return { ok: true };628      }629      case "DISABLE_DURESS": {630        await vault.disableDuress();631        return { ok: true };632      }633      case "VERIFY_MAIN_PASSWORD": {634        const { password } = msg.payload as { password: string };635        const ok = await vault.verifyMainPassword(password);636        return { ok: true, data: ok };637      }638      case "CHANGE_PASSWORD": {639        const { currentPassword, newPassword } = msg.payload as {640          currentPassword: string;641          newPassword: string;642        };643        const changed = await vault.changePassword(currentPassword, newPassword);644        return changed645          ? { ok: true }646          : { ok: false, error: "incorrect current password" };647      }648      case "GET_SITE_PASSWORD_POLICY": {649        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });650        if (!tab?.id) return { ok: true, data: null };651        try {652          const response = await chrome.tabs.sendMessage(tab.id, {653            type: "GET_SITE_PASSWORD_POLICY",654          });655          return (response as MessageResponse) ?? { ok: true, data: null };656        } catch {657          return { ok: true, data: null };658        }659      }660      case "GET_SYNC_STATE": {661        const pairedDevices = await getPairedDevices();662        const trustedNetworks = await getTrustedNetworks();663        const tailscale = await isOnTailscale();664        const pro = await isProUser();665666        let status: SyncStatus = "offline";667        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {668          if (pairedDevices.length === 0) {669            status = "no_peers";670          } else {671            status = "synced";672          }673        } else {674          status = "not_trusted";675        }676677        const lastSyncRaw = await storageGet("peach_last_sync_at");678        const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN;679        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined;680681        return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } };682      }683      case "ACCEPT_PAIRING": {684        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.685        return { ok: true };686      }687      case "REMOVE_PAIRED_DEVICE": {688        const { deviceId } = msg.payload as { deviceId: string };689        await removePairedDevice(deviceId);690        return { ok: true };691      }692      case "REMOVE_TRUSTED_NETWORK": {693        const { ssid, bssid, isTailscale } = msg.payload as any;694        const networks = await getTrustedNetworks();695        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 696          (isTailscale ? n.isTailscale : n.ssid === ssid) && 697          (!bssid || n.bssid === bssid)698        );699        if (network) {700          await removeTrustedNetwork(network.addedAt);701        }702        return { ok: true };703      }704      case "MARK_NETWORK_TRUSTED": {705        const network = await getCurrentNetwork();706        await addTrustedNetwork({707          ssid: network.ssid,708          bssid: network.bssid,709          isTailscale: network.isTailscale,710          addedAt: Date.now(),711        });712        return { ok: true };713      }714      case "GET_INCOMING_PAIRING_REQUEST": {715        const request = await getIncomingPairingRequest();716        return { ok: true, data: request };717      }718      case "RESPOND_INCOMING_PAIRING": {719        const { accept } = msg.payload as { accept: boolean };720        const request = await getIncomingPairingRequest();721        if (!request) return { ok: false, error: "no_pending_request" };722        if (Date.now() > request.expiresAt) {723          await clearIncomingPairingRequest();724          return { ok: false, error: "expired" };725        }726        await clearIncomingPairingRequest();727        if (accept) {728          await addPairedDevice({729            deviceId: request.publicKeyHex,730            displayName: request.deviceName,731            x25519PublicKey: request.publicKeyHex,732            pairedAt: Date.now(),733            lastSeenAt: Date.now(),734          });735        }736        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };737      }738      case "START_PAIRING_SERVER": {739        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.740        const token = generateSixDigitToken();741        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;742        await setActivePairingToken({ token, expiresAt });743        return { ok: true, data: { token, expiresAt } };744      }745      case "STOP_PAIRING_SERVER": {746        try {747          await setActivePairingToken(null);748        } catch { /* best-effort */ }749        return { ok: true };750      }751      case "GET_RECENT_PAIRING": {752        const recent = await consumeRecentPairing();753        return { ok: true, data: recent };754      }755      case "DEBUG_INJECT_INCOMING_PAIRING": {756        // Manual E2E rehearsal hook. Inserts a synthetic incoming pairing757        // request into session storage so Phase 7 banner UX can be exercised758        // without a live native host. No Pro gate — this is a no-op in759        // production unless explicitly invoked from a Settings debug action.760        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {761          deviceName?: string;762          publicKeyHex?: string;763        };764        if (!deviceName || !publicKeyHex) {765          return { ok: false, error: "missing_payload" };766        }767        const now = Date.now();768        await setIncomingPairingRequest({769          deviceName,770          publicKeyHex,771          receivedAt: now,772          expiresAt: now + 60_000,773        });774        return { ok: true };775      }776      case "RESET_SYNC_IDENTITY": {777        const gate = await requirePro("sync");778        if (!gate.allowed) return { ok: false, error: "pro_required" };779        const devices = await getPairedDevices();780        for (const device of devices) {781          await removePairedDevice(device.deviceId);782        }783        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };784      }785      case "RECORD_MANUAL_SUMMON": {786        const { domain } = msg.payload as { domain: string };787        const settings = vault.getSettings();788        const existing = settings.manualSummonDomains?.[domain];789        const now = Date.now();790        await vault.updateSettings({791          manualSummonDomains: {792            ...settings.manualSummonDomains,793            [domain]: {794              firstSummonedAt: existing?.firstSummonedAt ?? now,795              summonCount: (existing?.summonCount ?? 0) + 1,796              lastSummonedAt: now,797            },798          },799        });800        return { ok: true };801      }802      case "DECLINE_CARD_SAVE": {803        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };804        await vault.declineCardSaveOffer(last4, expMonth, expYear);805        return { ok: true };806      }807      case "IS_CARD_DECLINED": {808        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };809        const declined = await vault.isCardDeclined(last4, expMonth, expYear);810        return { ok: true, data: declined };811      }812      case "INITIATE_FIREFOX_PASSKEY_CREATE": {813        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {814          rpId?: string;815          rpName?: string;816          userName?: string;817          userDisplayName?: string;818        };819        if (!rpId || !userName) return { ok: false, error: "rpId and userName required" };820        return await initiateFirefoxPasskeyCreate({821          rpId,822          rpName: rpName ?? rpId,823          userName,824          userDisplayName,825        });826      }827828      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {829        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;830        if (!payload) return { ok: false, error: "missing payload" };831        return await completeFirefoxPasskeyCreate(payload);832      }833834      case "PASSKEY_OFFER_DECLINE": {835        const { domain } = (msg.payload ?? {}) as { domain?: string };836        if (!domain) return { ok: false, error: "domain required" };837        await recordPasskeyOfferDecline(domain);838        return { ok: true };839      }840841      case "GET_PASSKEY_OFFER_DECLINED": {842        const { domain } = (msg.payload ?? {}) as { domain?: string };843        if (!domain) return { ok: false, error: "domain required" };844        return { ok: true, data: await isPasskeyOfferDeclined(domain) };845      }846847      case "PASSKEY_HAS_CREDENTIALS": {848        const payload = msg.payload as {849          rpId?: string;850          allowCredentials?: Array<{ id: string; type?: string }>;851        } | undefined;852        if (!payload?.rpId) return { ok: false, error: "rpId required" };853        return await handlePasskeyHasCredentials({854          rpId: payload.rpId,855          allowCredentials: payload.allowCredentials ?? [],856        });857      }858859      case "PASSKEY_CREATE": {860        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;861        if (!payload?.rpId || !payload?.userName) {862          return { ok: false, error: "rpId and userName required" };863        }864        return await handleFirefoxPasskeyCreate(payload);865      }866867      case "PASSKEY_GET": {868        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;869        if (!payload?.rpId) return { ok: false, error: "rpId required" };870        return await handleFirefoxPasskeyGet(payload);871      }872873      case "GET_PASSKEY_FOR_DOMAIN": {874        const { domain } = (msg.payload ?? {}) as { domain?: string };875        if (!domain) return { ok: false, error: "domain required" };876        if (!vault.isUnlocked()) return { ok: true, data: null };877        const match = vault878          .getEntries()879          .find((entry) => entry.passkey?.rpId === domain);880        if (!match || !match.passkey) return { ok: true, data: null };881        // Slim shape — only the fields State 11 needs. Never expose private882        // key material, even though this is locked behind isUnlocked.883        return {884          ok: true,885          data: {886            rpId: match.passkey.rpId,887            userName: match.passkey.userName,888            browser: match.passkey.browser,889          },890        };891      }892893      case "DESTROY_VAULT": {894        // Irreversible by design. Lock zeroes the derived key + in-memory entries;895        // storage.local.clear() wipes every Peach key (slots, settings, license,896        // onboarded flag, history, sync state, declined cards, recall, etc.);897        // session.clear() wipes pending passkey requests + pro-notice queues.898        // Caller (Panic.tsx) handles UI navigation back to onboarding.899        vault.lock();900        await storageClear();901        await vault.clearVaultHistory();902        if (chrome.storage.session) {903          await chrome.storage.session.clear();904        }905        return { ok: true };906      }907908      case "SUBMIT_FEEDBACK": {909        const { category, message, version, browser } = msg.payload as {910          category: string;911          message: string;912          version: string;913          browser: string;914        };915        if (!message.trim()) return { ok: false, error: "message is empty" };916        if (!FEEDBACK_ENDPOINT) return { ok: true };917        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {918          return { ok: false, error: "invalid feedback endpoint" };919        }920        try {921          const res = await fetch(FEEDBACK_ENDPOINT, {922            method: "POST",923            headers: { "Content-Type": "application/json" },924            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),925          });926          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };927        } catch (err) {928          return { ok: false, error: err instanceof Error ? err.message : "network error" };929        }930      }931      case "TRIGGER_SYNC": {932        const gate = await requirePro("sync");933        if (!gate.allowed) return { ok: false, error: "pro_required" };934        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };935        if (isNativePlatform()) {936          bridge?.ensureServerRunning?.();937          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };938        }939        // Desktop has no outbound sync path — paired devices are mobile, and940        // the mobile side initiates. From desktop, "trigger sync" just means941        // "make sure the pairing server is reachable", which is handled by942        // START_PAIRING_SERVER. Surface no_paired_devices to keep callers tidy.943        return { ok: false, error: "no_paired_devices" };944      }945      // Android-only: biometric unlock with pre-derived key.946      case "UNLOCK_WITH_KEY": {947        const { masterKeyHex } = msg.payload as { masterKeyHex: string };948        if (!isNativePlatform()) {949          return { ok: false, error: "desktop_only_uses_password" };950        }951        try {952          const result = await vault.unlockWithKey(masterKeyHex);953          if (result.ok) await publishInMemoryVault(result.entries);954          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };955        } catch {956          return { ok: false, error: "invalid_key" };957        }958      }959      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.960      case "GET_DERIVED_KEY": {961        if (!isNativePlatform()) {962          return { ok: false, error: "android_only" };963        }964        if (!vault.isUnlocked()) {965          return { ok: false, error: "vault_locked" };966        }967        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };968      }969      // Android: scanned a QR containing a desktop pairing token.970      case "SCAN_PAIRING_QR": {971        if (!isNativePlatform()) {972          return { ok: false, error: "android_only" };973        }974        const { token } = msg.payload as { token: string };975        bridge?.startPairingSession?.({ token });976        return { ok: true };977      }978      // Android: returns the phone's WiFi IP address.979      case "GET_LOCAL_IP": {980        if (!isNativePlatform()) {981          return { ok: false, error: "android_only" };982        }983        const { ip } = (await bridge?.getLocalIp?.()) ?? { ip: "" };984        return { ok: true, data: { ip } };985      }986      case "GET_IDENTITY_SUGGESTIONS": {987        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };988        const entries = vault.getEntries();989        const suggestions = buildIdentitySuggestions(entries);990        return { ok: true, data: { suggestions } };991      }992      case "POPULATE_INLINE_VAULT": {993        if (!isNativePlatform()) return { ok: false };994        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };995        const entries = vault.getEntries();996        await publishInMemoryVault(entries);997        return { ok: true };998      }999      default:1000        return { ok: false, error: "unknown message type" };1001    }1002  } catch (err) {1003    return {1004      ok: false,1005      error: err instanceof Error ? err.message : "operation failed",1006    };1007  }1008}10091010// --- Mobile platform helpers ---10111012// Android: populates the in-memory vault used by PeachAutofillService.1013async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1014  // eslint-disable-next-line @typescript-eslint/no-explicit-any1015  const plugin = (globalThis as any).Capacitor?.Plugins?.InMemoryVaultPlugin;1016  if (!plugin?.setEntries) return;1017  await plugin.setEntries({1018    entries: entries.map((e) => ({1019      id: e.id,1020      title: e.title ?? "",1021      username: e.username ?? "",1022      email: (e as VaultEntry & { email?: string }).email ?? "",1023      password: e.password ?? "",1024      url: e.url ?? "",1025      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1026      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1027    })),1028  });1029}10301031// Android: clear the autofill in-memory store on lock.1032async function clearInMemoryVault(): Promise<void> {1033  // eslint-disable-next-line @typescript-eslint/no-explicit-any1034  const plugin = (globalThis as any).Capacitor?.Plugins?.InMemoryVaultPlugin;1035  if (!plugin?.clearEntries) return;1036  await plugin.clearEntries();1037}10381039// Returns all emails and usernames from the vault, deduped and sorted by frequency.1040function buildIdentitySuggestions(1041  entries: VaultEntry[],1042): Array<{ email: string; username: string; count: number }> {1043  const map = new Map<string, number>();1044  for (const entry of entries) {1045    if (entry.username) map.set(entry.username, (map.get(entry.username) ?? 0) + 1);1046  }1047  return Array.from(map.entries())1048    .sort((a, b) => b[1] - a[1])1049    .map(([username, count]) => ({ email: username, username, count }));1050}10511052// Mobile bridge — runtime check to avoid importing Capacitor at the top level.1053// eslint-disable-next-line @typescript-eslint/no-explicit-any1054const bridge = (typeof (globalThis as any).Capacitor !== "undefined")1055  ? (globalThis as any).Capacitor.Plugins.SyncPlugin1056  : null;10571058// eslint-disable-next-line @typescript-eslint/no-explicit-any1059const isNativePlatform = (): boolean => typeof (globalThis as any).Capacitor !== "undefined" && (globalThis as any).isNativePlatform();10601061/** Notify all content scripts that the vault just became available. */1062function broadcastToContentScripts(message: { type: string }): void {1063  if (!chrome.tabs?.query) return;1064  chrome.tabs.query({}, (tabs) => {1065    for (const tab of tabs) {1066      if (tab.id !== undefined) {1067        chrome.tabs.sendMessage(tab.id, message).catch(() => {1068          // Tab may not have a content script — silently ignore1069        });1070      }1071    }1072  });1073}10741075function shouldRefreshAutoLock(type: MessageType): boolean {1076  return (1077    type !== "HAS_VAULT" &&1078    type !== "IS_UNLOCKED" &&1079    type !== "GET_VAULT_STATUS" &&1080    type !== "LOCK" &&1081    type !== "UPDATE_SETTINGS" &&1082    type !== "GET_PENDING_PASSKEY" &&1083    type !== "GET_PASSKEY_PROVIDER_STATE" &&1084    type !== "DECLINE_CARD_SAVE" &&1085    type !== "IS_CARD_DECLINED" &&1086    type !== "SUBMIT_FEEDBACK"1087  );1088}10891090function isAllowedCanaryWebhookUrl(value: string): boolean {1091  try {1092    const url = new URL(value);1093    if (url.protocol !== "https:") return false;10941095    const hostname = url.hostname.toLowerCase();1096    if (1097      hostname === "localhost" ||1098      hostname.endsWith(".localhost") ||1099      isPrivateIpv4(hostname) ||1100      isPrivateIpv6(hostname)1101    ) {1102      return false;1103    }11041105    return true;1106  } catch {1107    return false;1108  }1109}11101111function isPrivateIpv4(hostname: string): boolean {1112  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1113    return true;1114  }11151116  const octets = hostname.split(".").map((part) => Number(part));1117  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1118    return false;1119  }11201121  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1122}11231124function isPrivateIpv6(hostname: string): boolean {1125  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1126  return (1127    normalized === "::1" ||1128    normalized.startsWith("fc") ||1129    normalized.startsWith("fd") ||1130    normalized.startsWith("fe80:")1131  );1132}