messages.ts

44.3 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_BREACH": {462        const { password } = msg.payload as { password: string };463        const count = await vault.checkBreach(password);464        return { ok: true, data: count };465      }466      case "CHECK_ALL_BREACHES": {467        const allEntries = vault.getEntries();468        const results: Record<string, number> = {};469        for (const entry of allEntries) {470          if (entry.type === "note") continue;471          if (!entry.password) continue;472          results[entry.id] = await vault.checkBreach(entry.password);473          // Small delay — be a good citizen to the HIBP API474          await new Promise((r) => setTimeout(r, 200));475        }476        // Persist any non-zero counts back to entries477        for (const [id, count] of Object.entries(results)) {478          const entry = vault.getEntryById(id);479          if (entry && (entry.breach ?? 0) !== count) {480            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });481          }482        }483        return { ok: true, data: results };484      }485      case "GET_SETTINGS":486        return { ok: true, data: await vault.ensureSettingsLoaded() };487      case "UPDATE_SETTINGS": {488        const patch = msg.payload as Record<string, unknown>;489        await vault.updateSettings(patch as any);490        if (typeof patch.autoLockMinutes === "number") {491          await setupAutoLock();492          if (vault.isUnlocked()) touchAutoLock();493        }494        return { ok: true };495      }496      case "GET_PENDING_PASSKEY":497        return { ok: true, data: await getPendingPasskeyRequest() };498      case "APPROVE_PASSKEY": {499        const { requestId } = msg.payload as { requestId: number };500        await resolvePendingPasskeyRequest(requestId, true);501        return { ok: true };502      }503      case "DENY_PASSKEY": {504        const { requestId } = msg.payload as { requestId: number };505        await resolvePendingPasskeyRequest(requestId, false);506        return { ok: true };507      }508      case "GET_PASSKEYS":509        return {510          ok: true,511          data: vault.getEntries().filter((entry) => entry.passkey !== undefined),512        };513      case "DELETE_PASSKEY": {514        const { id } = msg.payload as { id: string };515        await vault.deleteEntry(id);516        return { ok: true };517      }518      case "GET_PASSKEY_PROVIDER_STATE":519        return { ok: true, data: await getPasskeyProviderState() };520      case "SET_PASSKEY_PROVIDER_ENABLED": {521        const { enabled } = msg.payload as { enabled: boolean };522        // Disabling is always free; gating fires only when a free user is523        // trying to turn passkey interception on.524        if (enabled) {525          const gate = await requirePro("passkeys");526          if (!gate.allowed) return { ok: false, error: "pro_required" };527        }528        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };529      }530      case "FIRE_CANARY_PING": {531        const { webhookUrl, entryTitle, trigger } = msg.payload as {532          webhookUrl: string;533          entryTitle: string;534          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";535        };536        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {537          return { ok: false, error: "invalid webhook url" };538        }539        const body = JSON.stringify({540          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",541          entry: entryTitle,542          trigger,543          timestamp: new Date().toISOString(),544          source: "peach-extension",545        });546        if (trigger === "test") {547          // Permitted outbound fetch: user-configured canary alert endpoint548          // (validated by isAllowedCanaryWebhookUrl above). This is the549          // only non-HIBP outbound call in the extension — see550          // Projects.md §3.7. Test pings are awaited so the UI can show551          // success/failure.552          try {553            const res = await fetch(webhookUrl, {554              method: "POST",555              headers: { "Content-Type": "application/json" },556              body,557            });558            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };559          } catch (err) {560            return { ok: false, error: err instanceof Error ? err.message : "network error" };561          }562        }563        // Non-test triggers are fire-and-forget564        fetch(webhookUrl, {565          method: "POST",566          headers: { "Content-Type": "application/json" },567          body,568        }).catch(() => {});569        return { ok: true };570      }571      case "ACTIVATE_LICENSE": {572        const { key } = msg.payload as { key: string };573        const licenseInfo = await activateLicense(key);574        return { ok: true, data: licenseInfo };575      }576      case "GET_LICENSE": {577        const licenseInfo = await getLicenseInfo();578        return { ok: true, data: licenseInfo };579      }580      case "GET_LICENSE_KEY": {581        const key = await getLicenseKey();582        return { ok: true, data: key };583      }584      case "DEACTIVATE_LICENSE": {585        await deactivateLicense();586        return { ok: true };587      }588      case "SHOULD_PLAY_CELEBRATION": {589        const should = await shouldPlayCelebration();590        return { ok: true, data: should };591      }592      case "MARK_CELEBRATION_PLAYED": {593        await markCelebrationPlayed();594        return { ok: true };595      }596      case "OPEN_PRO_GATE": {597        // Content script requests: open popup and navigate to License section.598        const { feature } = (msg.payload ?? {}) as { feature?: string };599        if (chrome.storage.session) {600          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });601        }602        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }603        return { ok: true };604      }605      case "GET_IDENTITIES": {606        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };607        return { ok: true, data: vault.getIdentities() };608      }609      case "GET_ADVANCED_HEALTH_REPORT": {610        const gate = await requirePro("advanced_health");611        if (!gate.allowed) return { ok: false, error: "pro_required" };612        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };613        const report = await buildAdvancedHealthReport(vault.getEntries());614        return { ok: true, data: report };615      }616      case "INITIATE_PASSWORD_CHANGE": {617        const gate = await requirePro("smart_password_change");618        if (!gate.allowed) return { ok: false, error: "pro_required" };619        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };620        const { id } = msg.payload as { id: string };621        const entry = vault.getEntryById(id);622        if (!entry) return { ok: false, error: "entry not found" };623        const url = resolveResetUrl(entry);624        if (!url) return { ok: false, error: "no reset url" };625        try {626          await chrome.tabs.create({ url });627          return { ok: true, data: { url } };628        } catch (err) {629          return {630            ok: false,631            error: err instanceof Error ? err.message : "failed to open tab",632          };633        }634      }635      case "IS_DURESS_ENABLED": {636        const enabled = await vault.isDuressEnabled();637        return { ok: true, data: enabled };638      }639      case "SETUP_DURESS": {640        const { duressPassword } = msg.payload as { duressPassword: string };641        await vault.setupDuress(duressPassword);642        return { ok: true };643      }644      case "DISABLE_DURESS": {645        await vault.disableDuress();646        return { ok: true };647      }648      case "VERIFY_MAIN_PASSWORD": {649        const { password } = msg.payload as { password: string };650        const ok = await vault.verifyMainPassword(password);651        return { ok: true, data: ok };652      }653      case "CHANGE_PASSWORD": {654        const { currentPassword, newPassword } = msg.payload as {655          currentPassword: string;656          newPassword: string;657        };658        const changed = await vault.changePassword(currentPassword, newPassword);659        return changed660          ? { ok: true }661          : { ok: false, error: "incorrect current password" };662      }663      case "GET_SITE_PASSWORD_POLICY": {664        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });665        if (!tab?.id) return { ok: true, data: null };666        try {667          const response = await chrome.tabs.sendMessage(tab.id, {668            type: "GET_SITE_PASSWORD_POLICY",669          });670          return (response as MessageResponse) ?? { ok: true, data: null };671        } catch {672          return { ok: true, data: null };673        }674      }675      case "GET_SYNC_STATE": {676        const pairedDevices = await getPairedDevices();677        const trustedNetworks = await getTrustedNetworks();678        const tailscale = await isOnTailscale();679        const pro = await isProUser();680681        let status: SyncStatus = "offline";682        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {683          if (pairedDevices.length === 0) {684            status = "no_peers";685          } else {686            status = "synced";687          }688        } else {689          status = "not_trusted";690        }691692        const lastSyncRaw = await storageGet("peach_last_sync_at");693        const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN;694        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined;695696        return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } };697      }698      case "START_PAIRING": {699        const gate = await requirePro("sync");700        if (!gate.allowed) return { ok: false, error: "pro_required" };701        return { ok: true };702      }703      case "CANCEL_PAIRING": {704        return { ok: true };705      }706      case "ACCEPT_PAIRING": {707        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.708        return { ok: true };709      }710      case "REMOVE_PAIRED_DEVICE": {711        const { deviceId } = msg.payload as { deviceId: string };712        await removePairedDevice(deviceId);713        return { ok: true };714      }715      case "REMOVE_TRUSTED_NETWORK": {716        const { ssid, bssid, isTailscale } = msg.payload as any;717        const networks = await getTrustedNetworks();718        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 719          (isTailscale ? n.isTailscale : n.ssid === ssid) && 720          (!bssid || n.bssid === bssid)721        );722        if (network) {723          await removeTrustedNetwork(network.addedAt);724        }725        return { ok: true };726      }727      case "MARK_NETWORK_TRUSTED": {728        const network = await getCurrentNetwork();729        await addTrustedNetwork({730          ssid: network.ssid,731          bssid: network.bssid,732          isTailscale: network.isTailscale,733          addedAt: Date.now(),734        });735        return { ok: true };736      }737      case "GET_INCOMING_PAIRING_REQUEST": {738        const request = await getIncomingPairingRequest();739        return { ok: true, data: request };740      }741      case "RESPOND_INCOMING_PAIRING": {742        const { accept } = msg.payload as { accept: boolean };743        const request = await getIncomingPairingRequest();744        if (!request) return { ok: false, error: "no_pending_request" };745        if (Date.now() > request.expiresAt) {746          await clearIncomingPairingRequest();747          return { ok: false, error: "expired" };748        }749        await clearIncomingPairingRequest();750        if (accept) {751          await addPairedDevice({752            deviceId: request.publicKeyHex,753            displayName: request.deviceName,754            x25519PublicKey: request.publicKeyHex,755            pairedAt: Date.now(),756            lastSeenAt: Date.now(),757          });758        }759        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };760      }761      case "START_PEER_DISCOVERY": {762        const gate = await requirePro("sync");763        if (!gate.allowed) return { ok: false, error: "pro_required" };764        return { ok: false, error: "no_native_host" };765      }766      case "STOP_PEER_DISCOVERY": {767        return { ok: true };768      }769      case "START_PAIRING_SERVER": {770        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.771        const token = generateSixDigitToken();772        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;773        await setActivePairingToken({ token, expiresAt });774        return { ok: true, data: { token, expiresAt } };775      }776      case "STOP_PAIRING_SERVER": {777        try {778          await setActivePairingToken(null);779        } catch { /* best-effort */ }780        return { ok: true };781      }782      case "CONNECT_WITH_CODE": {783        const gate = await requirePro("sync");784        if (!gate.allowed) return { ok: false, error: "pro_required" };785        return { ok: false, error: "no_native_host" };786      }787      case "GET_RECENT_PAIRING": {788        const recent = await consumeRecentPairing();789        return { ok: true, data: recent };790      }791      case "INITIATE_PAIR_WITH_PEER": {792        const gate = await requirePro("sync");793        if (!gate.allowed) return { ok: false, error: "pro_required" };794        return { ok: false, error: "no_native_host" };795      }796      case "DEBUG_INJECT_INCOMING_PAIRING": {797        // Manual E2E rehearsal hook. Inserts a synthetic incoming pairing798        // request into session storage so Phase 7 banner UX can be exercised799        // without a live native host. No Pro gate — this is a no-op in800        // production unless explicitly invoked from a Settings debug action.801        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {802          deviceName?: string;803          publicKeyHex?: string;804        };805        if (!deviceName || !publicKeyHex) {806          return { ok: false, error: "missing_payload" };807        }808        const now = Date.now();809        await setIncomingPairingRequest({810          deviceName,811          publicKeyHex,812          receivedAt: now,813          expiresAt: now + 60_000,814        });815        return { ok: true };816      }817      case "RESET_SYNC_IDENTITY": {818        const gate = await requirePro("sync");819        if (!gate.allowed) return { ok: false, error: "pro_required" };820        const devices = await getPairedDevices();821        for (const device of devices) {822          await removePairedDevice(device.deviceId);823        }824        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };825      }826      case "RECORD_MANUAL_SUMMON": {827        const { domain } = msg.payload as { domain: string };828        const settings = vault.getSettings();829        const existing = settings.manualSummonDomains?.[domain];830        const now = Date.now();831        await vault.updateSettings({832          manualSummonDomains: {833            ...settings.manualSummonDomains,834            [domain]: {835              firstSummonedAt: existing?.firstSummonedAt ?? now,836              summonCount: (existing?.summonCount ?? 0) + 1,837              lastSummonedAt: now,838            },839          },840        });841        return { ok: true };842      }843      case "DECLINE_CARD_SAVE": {844        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };845        await vault.declineCardSaveOffer(last4, expMonth, expYear);846        return { ok: true };847      }848      case "IS_CARD_DECLINED": {849        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };850        const declined = await vault.isCardDeclined(last4, expMonth, expYear);851        return { ok: true, data: declined };852      }853      case "INITIATE_FIREFOX_PASSKEY_CREATE": {854        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {855          rpId?: string;856          rpName?: string;857          userName?: string;858          userDisplayName?: string;859        };860        if (!rpId || !userName) return { ok: false, error: "rpId and userName required" };861        return await initiateFirefoxPasskeyCreate({862          rpId,863          rpName: rpName ?? rpId,864          userName,865          userDisplayName,866        });867      }868869      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {870        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;871        if (!payload) return { ok: false, error: "missing payload" };872        return await completeFirefoxPasskeyCreate(payload);873      }874875      case "PASSKEY_OFFER_DECLINE": {876        const { domain } = (msg.payload ?? {}) as { domain?: string };877        if (!domain) return { ok: false, error: "domain required" };878        await recordPasskeyOfferDecline(domain);879        return { ok: true };880      }881882      case "GET_PASSKEY_OFFER_DECLINED": {883        const { domain } = (msg.payload ?? {}) as { domain?: string };884        if (!domain) return { ok: false, error: "domain required" };885        return { ok: true, data: await isPasskeyOfferDeclined(domain) };886      }887888      case "PASSKEY_HAS_CREDENTIALS": {889        const payload = msg.payload as {890          rpId?: string;891          allowCredentials?: Array<{ id: string; type?: string }>;892        } | undefined;893        if (!payload?.rpId) return { ok: false, error: "rpId required" };894        return await handlePasskeyHasCredentials({895          rpId: payload.rpId,896          allowCredentials: payload.allowCredentials ?? [],897        });898      }899900      case "PASSKEY_CREATE": {901        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;902        if (!payload?.rpId || !payload?.userName) {903          return { ok: false, error: "rpId and userName required" };904        }905        return await handleFirefoxPasskeyCreate(payload);906      }907908      case "PASSKEY_GET": {909        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;910        if (!payload?.rpId) return { ok: false, error: "rpId required" };911        return await handleFirefoxPasskeyGet(payload);912      }913914      case "GET_PASSKEY_FOR_DOMAIN": {915        const { domain } = (msg.payload ?? {}) as { domain?: string };916        if (!domain) return { ok: false, error: "domain required" };917        if (!vault.isUnlocked()) return { ok: true, data: null };918        const match = vault919          .getEntries()920          .find((entry) => entry.passkey?.rpId === domain);921        if (!match || !match.passkey) return { ok: true, data: null };922        // Slim shape — only the fields State 11 needs. Never expose private923        // key material, even though this is locked behind isUnlocked.924        return {925          ok: true,926          data: {927            rpId: match.passkey.rpId,928            userName: match.passkey.userName,929            browser: match.passkey.browser,930          },931        };932      }933934      case "DESTROY_VAULT": {935        // Irreversible by design. Lock zeroes the derived key + in-memory entries;936        // storage.local.clear() wipes every Peach key (slots, settings, license,937        // onboarded flag, history, sync state, declined cards, recall, etc.);938        // session.clear() wipes pending passkey requests + pro-notice queues.939        // Caller (Panic.tsx) handles UI navigation back to onboarding.940        vault.lock();941        await storageClear();942        await vault.clearVaultHistory();943        if (chrome.storage.session) {944          await chrome.storage.session.clear();945        }946        return { ok: true };947      }948949      case "SUBMIT_FEEDBACK": {950        const { category, message, version, browser } = msg.payload as {951          category: string;952          message: string;953          version: string;954          browser: string;955        };956        if (!message.trim()) return { ok: false, error: "message is empty" };957        if (!FEEDBACK_ENDPOINT) return { ok: true };958        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {959          return { ok: false, error: "invalid feedback endpoint" };960        }961        try {962          const res = await fetch(FEEDBACK_ENDPOINT, {963            method: "POST",964            headers: { "Content-Type": "application/json" },965            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),966          });967          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };968        } catch (err) {969          return { ok: false, error: err instanceof Error ? err.message : "network error" };970        }971      }972      case "TRIGGER_SYNC": {973        const gate = await requirePro("sync");974        if (!gate.allowed) return { ok: false, error: "pro_required" };975        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };976        if (isNativePlatform()) {977          bridge?.ensureServerRunning?.();978          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };979        }980        return await desktopTriggerSync({ getLastKnownIp: () => null });981      }982      // Android-only: biometric unlock with pre-derived key.983      case "UNLOCK_WITH_KEY": {984        const { masterKeyHex } = msg.payload as { masterKeyHex: string };985        if (!isNativePlatform()) {986          return { ok: false, error: "desktop_only_uses_password" };987        }988        try {989          const result = await vault.unlockWithKey(masterKeyHex);990          if (result.ok) await publishInMemoryVault(result.entries);991          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };992        } catch {993          return { ok: false, error: "invalid_key" };994        }995      }996      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.997      case "GET_DERIVED_KEY": {998        if (!isNativePlatform()) {999          return { ok: false, error: "android_only" };1000        }1001        if (!vault.isUnlocked()) {1002          return { ok: false, error: "vault_locked" };1003        }1004        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1005      }1006      // Android: scanned a QR containing a desktop pairing token.1007      case "SCAN_PAIRING_QR": {1008        if (!isNativePlatform()) {1009          return { ok: false, error: "android_only" };1010        }1011        const { token } = msg.payload as { token: string };1012        bridge?.startPairingSession?.({ token });1013        return { ok: true };1014      }1015      // Android: returns the phone's WiFi IP address.1016      case "GET_LOCAL_IP": {1017        if (!isNativePlatform()) {1018          return { ok: false, error: "android_only" };1019        }1020        const { ip } = (await bridge?.getLocalIp?.()) ?? { ip: "" };1021        return { ok: true, data: { ip } };1022      }1023      case "GET_IDENTITY_SUGGESTIONS": {1024        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1025        const entries = vault.getEntries();1026        const suggestions = buildIdentitySuggestions(entries);1027        return { ok: true, data: { suggestions } };1028      }1029      case "POPULATE_INLINE_VAULT": {1030        if (!isNativePlatform()) return { ok: false };1031        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1032        const entries = vault.getEntries();1033        await publishInMemoryVault(entries);1034        return { ok: true };1035      }1036      default:1037        return { ok: false, error: "unknown message type" };1038    }1039  } catch (err) {1040    return {1041      ok: false,1042      error: err instanceof Error ? err.message : "operation failed",1043    };1044  }1045}10461047// --- Mobile platform helpers ---10481049// Desktop: triggers sync for all paired devices.1050async function desktopTriggerSync(deps: {1051  getLastKnownIp: () => string | null;1052}): Promise<{ ok: true; syncedCount: number } | { ok: false; error: string }> {1053  const ip = deps.getLastKnownIp();1054  if (!ip) return { ok: false, error: "no_paired_devices" };1055  return { ok: true, syncedCount: 0 };1056}10571058// Android: populates the in-memory vault used by PeachAutofillService.1059async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1060  // eslint-disable-next-line @typescript-eslint/no-explicit-any1061  const plugin = (globalThis as any).Capacitor?.Plugins?.InMemoryVaultPlugin;1062  if (!plugin?.setEntries) return;1063  await plugin.setEntries({1064    entries: entries.map((e) => ({1065      id: e.id,1066      title: e.title ?? "",1067      username: e.username ?? "",1068      email: (e as VaultEntry & { email?: string }).email ?? "",1069      password: e.password ?? "",1070      url: e.url ?? "",1071      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1072      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1073    })),1074  });1075}10761077// Android: clear the autofill in-memory store on lock.1078async function clearInMemoryVault(): Promise<void> {1079  // eslint-disable-next-line @typescript-eslint/no-explicit-any1080  const plugin = (globalThis as any).Capacitor?.Plugins?.InMemoryVaultPlugin;1081  if (!plugin?.clearEntries) return;1082  await plugin.clearEntries();1083}10841085// Returns all emails and usernames from the vault, deduped and sorted by frequency.1086function buildIdentitySuggestions(1087  entries: VaultEntry[],1088): Array<{ email: string; username: string; count: number }> {1089  const map = new Map<string, number>();1090  for (const entry of entries) {1091    if (entry.username) map.set(entry.username, (map.get(entry.username) ?? 0) + 1);1092  }1093  return Array.from(map.entries())1094    .sort((a, b) => b[1] - a[1])1095    .map(([username, count]) => ({ email: username, username, count }));1096}10971098// Mobile bridge — runtime check to avoid importing Capacitor at the top level.1099// eslint-disable-next-line @typescript-eslint/no-explicit-any1100const bridge = (typeof (globalThis as any).Capacitor !== "undefined")1101  ? (globalThis as any).Capacitor.Plugins.SyncPlugin1102  : null;11031104// eslint-disable-next-line @typescript-eslint/no-explicit-any1105const isNativePlatform = (): boolean => typeof (globalThis as any).Capacitor !== "undefined" && (globalThis as any).isNativePlatform();11061107/** Notify all content scripts that the vault just became available. */1108function broadcastToContentScripts(message: { type: string }): void {1109  if (!chrome.tabs?.query) return;1110  chrome.tabs.query({}, (tabs) => {1111    for (const tab of tabs) {1112      if (tab.id !== undefined) {1113        chrome.tabs.sendMessage(tab.id, message).catch(() => {1114          // Tab may not have a content script — silently ignore1115        });1116      }1117    }1118  });1119}11201121function shouldRefreshAutoLock(type: MessageType): boolean {1122  return (1123    type !== "HAS_VAULT" &&1124    type !== "IS_UNLOCKED" &&1125    type !== "GET_VAULT_STATUS" &&1126    type !== "LOCK" &&1127    type !== "UPDATE_SETTINGS" &&1128    type !== "GET_PENDING_PASSKEY" &&1129    type !== "GET_PASSKEY_PROVIDER_STATE" &&1130    type !== "DECLINE_CARD_SAVE" &&1131    type !== "IS_CARD_DECLINED" &&1132    type !== "SUBMIT_FEEDBACK"1133  );1134}11351136function isAllowedCanaryWebhookUrl(value: string): boolean {1137  try {1138    const url = new URL(value);1139    if (url.protocol !== "https:") return false;11401141    const hostname = url.hostname.toLowerCase();1142    if (1143      hostname === "localhost" ||1144      hostname.endsWith(".localhost") ||1145      isPrivateIpv4(hostname) ||1146      isPrivateIpv6(hostname)1147    ) {1148      return false;1149    }11501151    return true;1152  } catch {1153    return false;1154  }1155}11561157function isPrivateIpv4(hostname: string): boolean {1158  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1159    return true;1160  }11611162  const octets = hostname.split(".").map((part) => Number(part));1163  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1164    return false;1165  }11661167  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1168}11691170function isPrivateIpv6(hostname: string): boolean {1171  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1172  return (1173    normalized === "::1" ||1174    normalized.startsWith("fc") ||1175    normalized.startsWith("fd") ||1176    normalized.startsWith("fe80:")1177  );1178}