messages.ts

43.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 "START_PAIRING": {684        const gate = await requirePro("sync");685        if (!gate.allowed) return { ok: false, error: "pro_required" };686        return { ok: true };687      }688      case "ACCEPT_PAIRING": {689        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.690        return { ok: true };691      }692      case "REMOVE_PAIRED_DEVICE": {693        const { deviceId } = msg.payload as { deviceId: string };694        await removePairedDevice(deviceId);695        return { ok: true };696      }697      case "REMOVE_TRUSTED_NETWORK": {698        const { ssid, bssid, isTailscale } = msg.payload as any;699        const networks = await getTrustedNetworks();700        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 701          (isTailscale ? n.isTailscale : n.ssid === ssid) && 702          (!bssid || n.bssid === bssid)703        );704        if (network) {705          await removeTrustedNetwork(network.addedAt);706        }707        return { ok: true };708      }709      case "MARK_NETWORK_TRUSTED": {710        const network = await getCurrentNetwork();711        await addTrustedNetwork({712          ssid: network.ssid,713          bssid: network.bssid,714          isTailscale: network.isTailscale,715          addedAt: Date.now(),716        });717        return { ok: true };718      }719      case "GET_INCOMING_PAIRING_REQUEST": {720        const request = await getIncomingPairingRequest();721        return { ok: true, data: request };722      }723      case "RESPOND_INCOMING_PAIRING": {724        const { accept } = msg.payload as { accept: boolean };725        const request = await getIncomingPairingRequest();726        if (!request) return { ok: false, error: "no_pending_request" };727        if (Date.now() > request.expiresAt) {728          await clearIncomingPairingRequest();729          return { ok: false, error: "expired" };730        }731        await clearIncomingPairingRequest();732        if (accept) {733          await addPairedDevice({734            deviceId: request.publicKeyHex,735            displayName: request.deviceName,736            x25519PublicKey: request.publicKeyHex,737            pairedAt: Date.now(),738            lastSeenAt: Date.now(),739          });740        }741        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };742      }743      case "START_PEER_DISCOVERY": {744        const gate = await requirePro("sync");745        if (!gate.allowed) return { ok: false, error: "pro_required" };746        return { ok: false, error: "no_native_host" };747      }748      case "STOP_PEER_DISCOVERY": {749        return { ok: true };750      }751      case "START_PAIRING_SERVER": {752        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.753        const token = generateSixDigitToken();754        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;755        await setActivePairingToken({ token, expiresAt });756        return { ok: true, data: { token, expiresAt } };757      }758      case "STOP_PAIRING_SERVER": {759        try {760          await setActivePairingToken(null);761        } catch { /* best-effort */ }762        return { ok: true };763      }764      case "CONNECT_WITH_CODE": {765        const gate = await requirePro("sync");766        if (!gate.allowed) return { ok: false, error: "pro_required" };767        return { ok: false, error: "no_native_host" };768      }769      case "GET_RECENT_PAIRING": {770        const recent = await consumeRecentPairing();771        return { ok: true, data: recent };772      }773      case "INITIATE_PAIR_WITH_PEER": {774        const gate = await requirePro("sync");775        if (!gate.allowed) return { ok: false, error: "pro_required" };776        return { ok: false, error: "no_native_host" };777      }778      case "DEBUG_INJECT_INCOMING_PAIRING": {779        // Manual E2E rehearsal hook. Inserts a synthetic incoming pairing780        // request into session storage so Phase 7 banner UX can be exercised781        // without a live native host. No Pro gate — this is a no-op in782        // production unless explicitly invoked from a Settings debug action.783        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {784          deviceName?: string;785          publicKeyHex?: string;786        };787        if (!deviceName || !publicKeyHex) {788          return { ok: false, error: "missing_payload" };789        }790        const now = Date.now();791        await setIncomingPairingRequest({792          deviceName,793          publicKeyHex,794          receivedAt: now,795          expiresAt: now + 60_000,796        });797        return { ok: true };798      }799      case "RESET_SYNC_IDENTITY": {800        const gate = await requirePro("sync");801        if (!gate.allowed) return { ok: false, error: "pro_required" };802        const devices = await getPairedDevices();803        for (const device of devices) {804          await removePairedDevice(device.deviceId);805        }806        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };807      }808      case "RECORD_MANUAL_SUMMON": {809        const { domain } = msg.payload as { domain: string };810        const settings = vault.getSettings();811        const existing = settings.manualSummonDomains?.[domain];812        const now = Date.now();813        await vault.updateSettings({814          manualSummonDomains: {815            ...settings.manualSummonDomains,816            [domain]: {817              firstSummonedAt: existing?.firstSummonedAt ?? now,818              summonCount: (existing?.summonCount ?? 0) + 1,819              lastSummonedAt: now,820            },821          },822        });823        return { ok: true };824      }825      case "DECLINE_CARD_SAVE": {826        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };827        await vault.declineCardSaveOffer(last4, expMonth, expYear);828        return { ok: true };829      }830      case "IS_CARD_DECLINED": {831        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };832        const declined = await vault.isCardDeclined(last4, expMonth, expYear);833        return { ok: true, data: declined };834      }835      case "INITIATE_FIREFOX_PASSKEY_CREATE": {836        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {837          rpId?: string;838          rpName?: string;839          userName?: string;840          userDisplayName?: string;841        };842        if (!rpId || !userName) return { ok: false, error: "rpId and userName required" };843        return await initiateFirefoxPasskeyCreate({844          rpId,845          rpName: rpName ?? rpId,846          userName,847          userDisplayName,848        });849      }850851      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {852        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;853        if (!payload) return { ok: false, error: "missing payload" };854        return await completeFirefoxPasskeyCreate(payload);855      }856857      case "PASSKEY_OFFER_DECLINE": {858        const { domain } = (msg.payload ?? {}) as { domain?: string };859        if (!domain) return { ok: false, error: "domain required" };860        await recordPasskeyOfferDecline(domain);861        return { ok: true };862      }863864      case "GET_PASSKEY_OFFER_DECLINED": {865        const { domain } = (msg.payload ?? {}) as { domain?: string };866        if (!domain) return { ok: false, error: "domain required" };867        return { ok: true, data: await isPasskeyOfferDeclined(domain) };868      }869870      case "PASSKEY_HAS_CREDENTIALS": {871        const payload = msg.payload as {872          rpId?: string;873          allowCredentials?: Array<{ id: string; type?: string }>;874        } | undefined;875        if (!payload?.rpId) return { ok: false, error: "rpId required" };876        return await handlePasskeyHasCredentials({877          rpId: payload.rpId,878          allowCredentials: payload.allowCredentials ?? [],879        });880      }881882      case "PASSKEY_CREATE": {883        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;884        if (!payload?.rpId || !payload?.userName) {885          return { ok: false, error: "rpId and userName required" };886        }887        return await handleFirefoxPasskeyCreate(payload);888      }889890      case "PASSKEY_GET": {891        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;892        if (!payload?.rpId) return { ok: false, error: "rpId required" };893        return await handleFirefoxPasskeyGet(payload);894      }895896      case "GET_PASSKEY_FOR_DOMAIN": {897        const { domain } = (msg.payload ?? {}) as { domain?: string };898        if (!domain) return { ok: false, error: "domain required" };899        if (!vault.isUnlocked()) return { ok: true, data: null };900        const match = vault901          .getEntries()902          .find((entry) => entry.passkey?.rpId === domain);903        if (!match || !match.passkey) return { ok: true, data: null };904        // Slim shape — only the fields State 11 needs. Never expose private905        // key material, even though this is locked behind isUnlocked.906        return {907          ok: true,908          data: {909            rpId: match.passkey.rpId,910            userName: match.passkey.userName,911            browser: match.passkey.browser,912          },913        };914      }915916      case "DESTROY_VAULT": {917        // Irreversible by design. Lock zeroes the derived key + in-memory entries;918        // storage.local.clear() wipes every Peach key (slots, settings, license,919        // onboarded flag, history, sync state, declined cards, recall, etc.);920        // session.clear() wipes pending passkey requests + pro-notice queues.921        // Caller (Panic.tsx) handles UI navigation back to onboarding.922        vault.lock();923        await storageClear();924        await vault.clearVaultHistory();925        if (chrome.storage.session) {926          await chrome.storage.session.clear();927        }928        return { ok: true };929      }930931      case "SUBMIT_FEEDBACK": {932        const { category, message, version, browser } = msg.payload as {933          category: string;934          message: string;935          version: string;936          browser: string;937        };938        if (!message.trim()) return { ok: false, error: "message is empty" };939        if (!FEEDBACK_ENDPOINT) return { ok: true };940        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {941          return { ok: false, error: "invalid feedback endpoint" };942        }943        try {944          const res = await fetch(FEEDBACK_ENDPOINT, {945            method: "POST",946            headers: { "Content-Type": "application/json" },947            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),948          });949          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };950        } catch (err) {951          return { ok: false, error: err instanceof Error ? err.message : "network error" };952        }953      }954      case "TRIGGER_SYNC": {955        const gate = await requirePro("sync");956        if (!gate.allowed) return { ok: false, error: "pro_required" };957        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };958        if (isNativePlatform()) {959          bridge?.ensureServerRunning?.();960          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };961        }962        return await desktopTriggerSync({ getLastKnownIp: () => null });963      }964      // Android-only: biometric unlock with pre-derived key.965      case "UNLOCK_WITH_KEY": {966        const { masterKeyHex } = msg.payload as { masterKeyHex: string };967        if (!isNativePlatform()) {968          return { ok: false, error: "desktop_only_uses_password" };969        }970        try {971          const result = await vault.unlockWithKey(masterKeyHex);972          if (result.ok) await publishInMemoryVault(result.entries);973          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };974        } catch {975          return { ok: false, error: "invalid_key" };976        }977      }978      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.979      case "GET_DERIVED_KEY": {980        if (!isNativePlatform()) {981          return { ok: false, error: "android_only" };982        }983        if (!vault.isUnlocked()) {984          return { ok: false, error: "vault_locked" };985        }986        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };987      }988      // Android: scanned a QR containing a desktop pairing token.989      case "SCAN_PAIRING_QR": {990        if (!isNativePlatform()) {991          return { ok: false, error: "android_only" };992        }993        const { token } = msg.payload as { token: string };994        bridge?.startPairingSession?.({ token });995        return { ok: true };996      }997      // Android: returns the phone's WiFi IP address.998      case "GET_LOCAL_IP": {999        if (!isNativePlatform()) {1000          return { ok: false, error: "android_only" };1001        }1002        const { ip } = (await bridge?.getLocalIp?.()) ?? { ip: "" };1003        return { ok: true, data: { ip } };1004      }1005      case "GET_IDENTITY_SUGGESTIONS": {1006        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1007        const entries = vault.getEntries();1008        const suggestions = buildIdentitySuggestions(entries);1009        return { ok: true, data: { suggestions } };1010      }1011      case "POPULATE_INLINE_VAULT": {1012        if (!isNativePlatform()) return { ok: false };1013        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1014        const entries = vault.getEntries();1015        await publishInMemoryVault(entries);1016        return { ok: true };1017      }1018      default:1019        return { ok: false, error: "unknown message type" };1020    }1021  } catch (err) {1022    return {1023      ok: false,1024      error: err instanceof Error ? err.message : "operation failed",1025    };1026  }1027}10281029// --- Mobile platform helpers ---10301031// Desktop: triggers sync for all paired devices.1032async function desktopTriggerSync(deps: {1033  getLastKnownIp: () => string | null;1034}): Promise<{ ok: true; syncedCount: number } | { ok: false; error: string }> {1035  const ip = deps.getLastKnownIp();1036  if (!ip) return { ok: false, error: "no_paired_devices" };1037  return { ok: true, syncedCount: 0 };1038}10391040// Android: populates the in-memory vault used by PeachAutofillService.1041async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1042  // eslint-disable-next-line @typescript-eslint/no-explicit-any1043  const plugin = (globalThis as any).Capacitor?.Plugins?.InMemoryVaultPlugin;1044  if (!plugin?.setEntries) return;1045  await plugin.setEntries({1046    entries: entries.map((e) => ({1047      id: e.id,1048      title: e.title ?? "",1049      username: e.username ?? "",1050      email: (e as VaultEntry & { email?: string }).email ?? "",1051      password: e.password ?? "",1052      url: e.url ?? "",1053      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1054      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1055    })),1056  });1057}10581059// Android: clear the autofill in-memory store on lock.1060async function clearInMemoryVault(): Promise<void> {1061  // eslint-disable-next-line @typescript-eslint/no-explicit-any1062  const plugin = (globalThis as any).Capacitor?.Plugins?.InMemoryVaultPlugin;1063  if (!plugin?.clearEntries) return;1064  await plugin.clearEntries();1065}10661067// Returns all emails and usernames from the vault, deduped and sorted by frequency.1068function buildIdentitySuggestions(1069  entries: VaultEntry[],1070): Array<{ email: string; username: string; count: number }> {1071  const map = new Map<string, number>();1072  for (const entry of entries) {1073    if (entry.username) map.set(entry.username, (map.get(entry.username) ?? 0) + 1);1074  }1075  return Array.from(map.entries())1076    .sort((a, b) => b[1] - a[1])1077    .map(([username, count]) => ({ email: username, username, count }));1078}10791080// Mobile bridge — runtime check to avoid importing Capacitor at the top level.1081// eslint-disable-next-line @typescript-eslint/no-explicit-any1082const bridge = (typeof (globalThis as any).Capacitor !== "undefined")1083  ? (globalThis as any).Capacitor.Plugins.SyncPlugin1084  : null;10851086// eslint-disable-next-line @typescript-eslint/no-explicit-any1087const isNativePlatform = (): boolean => typeof (globalThis as any).Capacitor !== "undefined" && (globalThis as any).isNativePlatform();10881089/** Notify all content scripts that the vault just became available. */1090function broadcastToContentScripts(message: { type: string }): void {1091  if (!chrome.tabs?.query) return;1092  chrome.tabs.query({}, (tabs) => {1093    for (const tab of tabs) {1094      if (tab.id !== undefined) {1095        chrome.tabs.sendMessage(tab.id, message).catch(() => {1096          // Tab may not have a content script — silently ignore1097        });1098      }1099    }1100  });1101}11021103function shouldRefreshAutoLock(type: MessageType): boolean {1104  return (1105    type !== "HAS_VAULT" &&1106    type !== "IS_UNLOCKED" &&1107    type !== "GET_VAULT_STATUS" &&1108    type !== "LOCK" &&1109    type !== "UPDATE_SETTINGS" &&1110    type !== "GET_PENDING_PASSKEY" &&1111    type !== "GET_PASSKEY_PROVIDER_STATE" &&1112    type !== "DECLINE_CARD_SAVE" &&1113    type !== "IS_CARD_DECLINED" &&1114    type !== "SUBMIT_FEEDBACK"1115  );1116}11171118function isAllowedCanaryWebhookUrl(value: string): boolean {1119  try {1120    const url = new URL(value);1121    if (url.protocol !== "https:") return false;11221123    const hostname = url.hostname.toLowerCase();1124    if (1125      hostname === "localhost" ||1126      hostname.endsWith(".localhost") ||1127      isPrivateIpv4(hostname) ||1128      isPrivateIpv6(hostname)1129    ) {1130      return false;1131    }11321133    return true;1134  } catch {1135    return false;1136  }1137}11381139function isPrivateIpv4(hostname: string): boolean {1140  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1141    return true;1142  }11431144  const octets = hostname.split(".").map((part) => Number(part));1145  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1146    return false;1147  }11481149  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1150}11511152function isPrivateIpv6(hostname: string): boolean {1153  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1154  return (1155    normalized === "::1" ||1156    normalized.startsWith("fc") ||1157    normalized.startsWith("fd") ||1158    normalized.startsWith("fe80:")1159  );1160}