messages.ts

45.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 "TRIGGER_SYNC": {699        const gate = await requirePro("sync");700        if (!gate.allowed) return { ok: false, error: "pro_required" };701        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };702        return { ok: false, error: "no_native_host" };703      }704      case "START_PAIRING": {705        const gate = await requirePro("sync");706        if (!gate.allowed) return { ok: false, error: "pro_required" };707        return { ok: true };708      }709      case "CANCEL_PAIRING": {710        return { ok: true };711      }712      case "ACCEPT_PAIRING": {713        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.714        return { ok: true };715      }716      case "REMOVE_PAIRED_DEVICE": {717        const { deviceId } = msg.payload as { deviceId: string };718        await removePairedDevice(deviceId);719        return { ok: true };720      }721      case "REMOVE_TRUSTED_NETWORK": {722        const { ssid, bssid, isTailscale } = msg.payload as any;723        const networks = await getTrustedNetworks();724        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 725          (isTailscale ? n.isTailscale : n.ssid === ssid) && 726          (!bssid || n.bssid === bssid)727        );728        if (network) {729          await removeTrustedNetwork(network.addedAt);730        }731        return { ok: true };732      }733      case "MARK_NETWORK_TRUSTED": {734        const network = await getCurrentNetwork();735        await addTrustedNetwork({736          ssid: network.ssid,737          bssid: network.bssid,738          isTailscale: network.isTailscale,739          addedAt: Date.now(),740        });741        return { ok: true };742      }743      case "GET_INCOMING_PAIRING_REQUEST": {744        const request = await getIncomingPairingRequest();745        return { ok: true, data: request };746      }747      case "RESPOND_INCOMING_PAIRING": {748        const { accept } = msg.payload as { accept: boolean };749        const request = await getIncomingPairingRequest();750        if (!request) return { ok: false, error: "no_pending_request" };751        if (Date.now() > request.expiresAt) {752          await clearIncomingPairingRequest();753          return { ok: false, error: "expired" };754        }755        await clearIncomingPairingRequest();756        if (accept) {757          await addPairedDevice({758            deviceId: request.publicKeyHex,759            displayName: request.deviceName,760            x25519PublicKey: request.publicKeyHex,761            pairedAt: Date.now(),762            lastSeenAt: Date.now(),763          });764        }765        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };766      }767      case "START_PEER_DISCOVERY": {768        const gate = await requirePro("sync");769        if (!gate.allowed) return { ok: false, error: "pro_required" };770        return { ok: false, error: "no_native_host" };771      }772      case "STOP_PEER_DISCOVERY": {773        return { ok: true };774      }775      case "START_PAIRING_SERVER": {776        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.777        const token = generateSixDigitToken();778        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;779        await setActivePairingToken({ token, expiresAt });780        return { ok: true, data: { token, expiresAt } };781      }782      case "STOP_PAIRING_SERVER": {783        try {784          await setActivePairingToken(null);785        } catch { /* best-effort */ }786        return { ok: true };787      }788      case "CONNECT_WITH_CODE": {789        const gate = await requirePro("sync");790        if (!gate.allowed) return { ok: false, error: "pro_required" };791        return { ok: false, error: "no_native_host" };792      }793      case "GET_RECENT_PAIRING": {794        const recent = await consumeRecentPairing();795        return { ok: true, data: recent };796      }797      case "INITIATE_PAIR_WITH_PEER": {798        const gate = await requirePro("sync");799        if (!gate.allowed) return { ok: false, error: "pro_required" };800        return { ok: false, error: "no_native_host" };801      }802      case "DEBUG_INJECT_INCOMING_PAIRING": {803        // Manual E2E rehearsal hook. Inserts a synthetic incoming pairing804        // request into session storage so Phase 7 banner UX can be exercised805        // without a live native host. No Pro gate — this is a no-op in806        // production unless explicitly invoked from a Settings debug action.807        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {808          deviceName?: string;809          publicKeyHex?: string;810        };811        if (!deviceName || !publicKeyHex) {812          return { ok: false, error: "missing_payload" };813        }814        const now = Date.now();815        await setIncomingPairingRequest({816          deviceName,817          publicKeyHex,818          receivedAt: now,819          expiresAt: now + 60_000,820        });821        return { ok: true };822      }823      case "RESET_SYNC_IDENTITY": {824        const gate = await requirePro("sync");825        if (!gate.allowed) return { ok: false, error: "pro_required" };826        const devices = await getPairedDevices();827        for (const device of devices) {828          await removePairedDevice(device.deviceId);829        }830        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };831      }832      case "RECORD_MANUAL_SUMMON": {833        const { domain } = msg.payload as { domain: string };834        const settings = vault.getSettings();835        const existing = settings.manualSummonDomains?.[domain];836        const now = Date.now();837        await vault.updateSettings({838          manualSummonDomains: {839            ...settings.manualSummonDomains,840            [domain]: {841              firstSummonedAt: existing?.firstSummonedAt ?? now,842              summonCount: (existing?.summonCount ?? 0) + 1,843              lastSummonedAt: now,844            },845          },846        });847        return { ok: true };848      }849      case "DECLINE_CARD_SAVE": {850        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };851        await vault.declineCardSaveOffer(last4, expMonth, expYear);852        return { ok: true };853      }854      case "IS_CARD_DECLINED": {855        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };856        const declined = await vault.isCardDeclined(last4, expMonth, expYear);857        return { ok: true, data: declined };858      }859      case "INITIATE_FIREFOX_PASSKEY_CREATE": {860        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {861          rpId?: string;862          rpName?: string;863          userName?: string;864          userDisplayName?: string;865        };866        if (!rpId || !userName) return { ok: false, error: "rpId and userName required" };867        return await initiateFirefoxPasskeyCreate({868          rpId,869          rpName: rpName ?? rpId,870          userName,871          userDisplayName,872        });873      }874875      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {876        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;877        if (!payload) return { ok: false, error: "missing payload" };878        return await completeFirefoxPasskeyCreate(payload);879      }880881      case "PASSKEY_OFFER_DECLINE": {882        const { domain } = (msg.payload ?? {}) as { domain?: string };883        if (!domain) return { ok: false, error: "domain required" };884        await recordPasskeyOfferDecline(domain);885        return { ok: true };886      }887888      case "GET_PASSKEY_OFFER_DECLINED": {889        const { domain } = (msg.payload ?? {}) as { domain?: string };890        if (!domain) return { ok: false, error: "domain required" };891        return { ok: true, data: await isPasskeyOfferDeclined(domain) };892      }893894      case "PASSKEY_HAS_CREDENTIALS": {895        const payload = msg.payload as {896          rpId?: string;897          allowCredentials?: Array<{ id: string; type?: string }>;898        } | undefined;899        if (!payload?.rpId) return { ok: false, error: "rpId required" };900        return await handlePasskeyHasCredentials({901          rpId: payload.rpId,902          allowCredentials: payload.allowCredentials ?? [],903        });904      }905906      case "PASSKEY_CREATE": {907        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;908        if (!payload?.rpId || !payload?.userName) {909          return { ok: false, error: "rpId and userName required" };910        }911        return await handleFirefoxPasskeyCreate(payload);912      }913914      case "PASSKEY_GET": {915        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;916        if (!payload?.rpId) return { ok: false, error: "rpId required" };917        return await handleFirefoxPasskeyGet(payload);918      }919920      case "GET_PASSKEY_FOR_DOMAIN": {921        const { domain } = (msg.payload ?? {}) as { domain?: string };922        if (!domain) return { ok: false, error: "domain required" };923        if (!vault.isUnlocked()) return { ok: true, data: null };924        const match = vault925          .getEntries()926          .find((entry) => entry.passkey?.rpId === domain);927        if (!match || !match.passkey) return { ok: true, data: null };928        // Slim shape — only the fields State 11 needs. Never expose private929        // key material, even though this is locked behind isUnlocked.930        return {931          ok: true,932          data: {933            rpId: match.passkey.rpId,934            userName: match.passkey.userName,935            browser: match.passkey.browser,936          },937        };938      }939940      case "DESTROY_VAULT": {941        // Irreversible by design. Lock zeroes the derived key + in-memory entries;942        // storage.local.clear() wipes every Peach key (slots, settings, license,943        // onboarded flag, history, sync state, declined cards, recall, etc.);944        // session.clear() wipes pending passkey requests + pro-notice queues.945        // Caller (Panic.tsx) handles UI navigation back to onboarding.946        vault.lock();947        await storageClear();948        await vault.clearVaultHistory();949        if (chrome.storage.session) {950          await chrome.storage.session.clear();951        }952        return { ok: true };953      }954955      case "SUBMIT_FEEDBACK": {956        const { category, message, version, browser } = msg.payload as {957          category: string;958          message: string;959          version: string;960          browser: string;961        };962        if (!message.trim()) return { ok: false, error: "message is empty" };963        if (!FEEDBACK_ENDPOINT) return { ok: true };964        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {965          return { ok: false, error: "invalid feedback endpoint" };966        }967        try {968          const res = await fetch(FEEDBACK_ENDPOINT, {969            method: "POST",970            headers: { "Content-Type": "application/json" },971            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),972          });973          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };974        } catch (err) {975          return { ok: false, error: err instanceof Error ? err.message : "network error" };976        }977      }978      case "TRIGGER_SYNC": {979        if (isNativePlatform()) {980          bridge?.ensureServerRunning?.();981          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };982        }983        return await desktopTriggerSync({ getLastKnownIp: () => null });984      }985      // Android-only: biometric unlock with pre-derived key.986      case "UNLOCK_WITH_KEY": {987        const { masterKeyHex } = msg.payload as { masterKeyHex: string };988        if (!isNativePlatform()) {989          return { ok: false, error: "desktop_only_uses_password" };990        }991        try {992          const result = await vault.unlockWithKey(masterKeyHex);993          if (result.ok) await publishInMemoryVault(result.entries);994          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };995        } catch {996          return { ok: false, error: "invalid_key" };997        }998      }999      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1000      case "GET_DERIVED_KEY": {1001        if (!isNativePlatform()) {1002          return { ok: false, error: "android_only" };1003        }1004        if (!vault.isUnlocked()) {1005          return { ok: false, error: "vault_locked" };1006        }1007        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1008      }1009      // Android: scanned a QR containing a desktop pairing token.1010      case "SCAN_PAIRING_QR": {1011        if (!isNativePlatform()) {1012          return { ok: false, error: "android_only" };1013        }1014        const { token } = msg.payload as { token: string };1015        bridge?.startPairingSession?.({ token });1016        return { ok: true };1017      }1018      // Android: returns the phone's WiFi IP address.1019      case "GET_LOCAL_IP": {1020        if (!isNativePlatform()) {1021          return { ok: false, error: "android_only" };1022        }1023        const { ip } = (await bridge?.getLocalIp?.()) ?? { ip: "" };1024        return { ok: true, data: { ip } };1025      }1026      // Desktop: generates a pairing token and starts the subnet scan for QR pairing.1027      case "START_PAIRING_SERVER": {1028        if (isNativePlatform()) {1029          return { ok: false, error: "desktop_only" };1030        }1031        const arr = new Uint32Array(1);1032        crypto.getRandomValues(arr);1033        const token = String(100000 + (arr[0] % 900000));1034        activeDesktopPairingToken = token;1035        activeDesktopPairingExpiry = Date.now() + 5 * 60 * 1000;1036        startSubnetScan(token, { getLocalAddress: () => null });1037        return { ok: true, data: { token, expiresIn: 300 } };1038      }1039      case "GET_IDENTITY_SUGGESTIONS": {1040        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1041        const entries = vault.getEntries();1042        const suggestions = buildIdentitySuggestions(entries);1043        return { ok: true, data: { suggestions } };1044      }1045      case "POPULATE_INLINE_VAULT": {1046        if (!isNativePlatform()) return { ok: false };1047        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1048        const entries = vault.getEntries();1049        await publishInMemoryVault(entries);1050        return { ok: true };1051      }1052      default:1053        return { ok: false, error: "unknown message type" };1054    }1055  } catch (err) {1056    return {1057      ok: false,1058      error: err instanceof Error ? err.message : "operation failed",1059    };1060  }1061}10621063// --- Mobile platform helpers ---10641065// Desktop: triggers sync for all paired devices.1066async function desktopTriggerSync(deps: {1067  getLastKnownIp: () => string | null;1068}): Promise<{ ok: true; syncedCount: number } | { ok: false; error: string }> {1069  const ip = deps.getLastKnownIp();1070  if (!ip) return { ok: false, error: "no_paired_devices" };1071  return { ok: true, syncedCount: 0 };1072}10731074// Desktop: starts background subnet scan for QR pairing.1075function startSubnetScan(1076  token: string,1077  _deps: {1078    getLocalAddress: () => string | null;1079  }1080): void {1081  // TODO: implement subnet scan and WebSocket pairing server1082}10831084// Android: populates the in-memory vault used by PeachAutofillService.1085async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1086  // eslint-disable-next-line @typescript-eslint/no-explicit-any1087  const plugin = (globalThis as any).Capacitor?.Plugins?.InMemoryVaultPlugin;1088  if (!plugin?.setEntries) return;1089  await plugin.setEntries({1090    entries: entries.map((e) => ({1091      id: e.id,1092      title: e.title ?? "",1093      username: e.username ?? "",1094      email: (e as VaultEntry & { email?: string }).email ?? "",1095      password: e.password ?? "",1096      url: e.url ?? "",1097      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1098      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1099    })),1100  });1101}11021103// Android: clear the autofill in-memory store on lock.1104async function clearInMemoryVault(): Promise<void> {1105  // eslint-disable-next-line @typescript-eslint/no-explicit-any1106  const plugin = (globalThis as any).Capacitor?.Plugins?.InMemoryVaultPlugin;1107  if (!plugin?.clearEntries) return;1108  await plugin.clearEntries();1109}11101111// Returns all emails and usernames from the vault, deduped and sorted by frequency.1112function buildIdentitySuggestions(1113  entries: VaultEntry[],1114): Array<{ email: string; username: string; count: number }> {1115  const map = new Map<string, number>();1116  for (const entry of entries) {1117    if (entry.username) map.set(entry.username, (map.get(entry.username) ?? 0) + 1);1118  }1119  return Array.from(map.entries())1120    .sort((a, b) => b[1] - a[1])1121    .map(([username, count]) => ({ email: username, username, count }));1122}11231124// Mobile bridge — runtime check to avoid importing Capacitor at the top level.1125// eslint-disable-next-line @typescript-eslint/no-explicit-any1126const bridge = (typeof (globalThis as any).Capacitor !== "undefined")1127  ? (globalThis as any).Capacitor.Plugins.SyncPlugin1128  : null;11291130// eslint-disable-next-line @typescript-eslint/no-explicit-any1131const isNativePlatform = (): boolean => typeof (globalThis as any).Capacitor !== "undefined" && (globalThis as any).isNativePlatform();11321133let activeDesktopPairingToken: string | null = null;1134let activeDesktopPairingExpiry = 0;11351136/** Notify all content scripts that the vault just became available. */1137function broadcastToContentScripts(message: { type: string }): void {1138  if (!chrome.tabs?.query) return;1139  chrome.tabs.query({}, (tabs) => {1140    for (const tab of tabs) {1141      if (tab.id !== undefined) {1142        chrome.tabs.sendMessage(tab.id, message).catch(() => {1143          // Tab may not have a content script — silently ignore1144        });1145      }1146    }1147  });1148}11491150function shouldRefreshAutoLock(type: MessageType): boolean {1151  return (1152    type !== "HAS_VAULT" &&1153    type !== "IS_UNLOCKED" &&1154    type !== "GET_VAULT_STATUS" &&1155    type !== "LOCK" &&1156    type !== "UPDATE_SETTINGS" &&1157    type !== "GET_PENDING_PASSKEY" &&1158    type !== "GET_PASSKEY_PROVIDER_STATE" &&1159    type !== "DECLINE_CARD_SAVE" &&1160    type !== "IS_CARD_DECLINED" &&1161    type !== "SUBMIT_FEEDBACK"1162  );1163}11641165function isAllowedCanaryWebhookUrl(value: string): boolean {1166  try {1167    const url = new URL(value);1168    if (url.protocol !== "https:") return false;11691170    const hostname = url.hostname.toLowerCase();1171    if (1172      hostname === "localhost" ||1173      hostname.endsWith(".localhost") ||1174      isPrivateIpv4(hostname) ||1175      isPrivateIpv6(hostname)1176    ) {1177      return false;1178    }11791180    return true;1181  } catch {1182    return false;1183  }1184}11851186function isPrivateIpv4(hostname: string): boolean {1187  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1188    return true;1189  }11901191  const octets = hostname.split(".").map((part) => Number(part));1192  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1193    return false;1194  }11951196  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1197}11981199function isPrivateIpv6(hostname: string): boolean {1200  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1201  return (1202    normalized === "::1" ||1203    normalized.startsWith("fc") ||1204    normalized.startsWith("fd") ||1205    normalized.startsWith("fe80:")1206  );1207}