messages.ts

38.4 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 { Capacitor } from "@capacitor/core";40import { storageClear } from "../shared/storage";41import type {42  Message,43  MessageResponse,44  MessageType,45  ProFeature,46} from "../shared/types";47import { isPasskeyOnly } from "../shared/types";48import type { SyncStatus } from "../shared/sync-types";4950/**51 * The single Pro gate. Every gated handler calls this first; the broadcast52 * lets the popup react (navigate to the License section, highlight the53 * relevant feature). Background never touches the popup view directly —54 * the popup owns navigation. See Projects.md "Pro gate rule".55 */56async function requirePro(57  feature: ProFeature,58  trigger: "user" | "background" = "user"59): Promise<{ allowed: boolean }> {60  if (await isProUser()) return { allowed: true };6162  if (trigger === "user") {63    // User deliberately triggered this feature — redirect the popup immediately.64    if (!Capacitor.isNativePlatform()) {65      chrome.runtime66        .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })67        .catch(() => {68          // Popup may be closed — the gate signal is best-effort.69        });70    }71  } else {72    // Background trigger (e.g. passive sync initiation) — no popup is open.73    // Queue a notice so the next popup open shows a soft banner instead of74    // silently failing.75    if (!Capacitor.isNativePlatform() && chrome.storage.session) {76      chrome.storage.session77        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })78        .catch(() => {});79    }80  }8182  return { allowed: false };83}8485// ---------------------------------------------------------------------------86// Peer discovery glue (Phase 7 popup pairing flow).87//88// The popup opens discovery via START_PEER_DISCOVERY. We connect to the89// native sync host, subscribe once, and re-broadcast every PEER_DISCOVERED /90// PEER_LOST event to the popup as a SYNC_PEER_DISCOVERED / SYNC_PEER_LOST91// runtime message. The popup is the only consumer; if it closes, STOP is92// sent on cleanup which tears down subscriptions and the native discovery.93// ---------------------------------------------------------------------------9495let peerDiscoverySubscriptions: Array<() => void> = [];9697async function startPeerDiscoveryForPopup(): Promise<void> {98  await stopPeerDiscoveryForPopup();99  const sync = await import('./sync');100  const { getPairedDevices } = await import('./sync-storage');101  sync.connectSyncHost();102103  const unsubDiscovered = sync.onPeerDiscovered((peer) => {104    void (async () => {105      const paired = await getPairedDevices();106      const alreadyPaired = paired.some((d) => d.deviceId === peer.deviceId);107      if (Capacitor.isNativePlatform()) return;108      chrome.runtime109        .sendMessage({110          type: "SYNC_PEER_DISCOVERED",111          peer: {112            deviceId: peer.deviceId,113            deviceName: peer.name,114            host: peer.host,115            port: peer.port,116            wsPort: peer.wsPort,117            x25519PublicKey: peer.x25519PublicKey,118            alreadyPaired,119          },120        })121        .catch(() => {});122    })();123  });124  const unsubLost = sync.onPeerLost((deviceId) => {125    if (Capacitor.isNativePlatform()) return;126    chrome.runtime127      .sendMessage({ type: "SYNC_PEER_LOST", deviceId })128      .catch(() => {});129  });130  peerDiscoverySubscriptions = [unsubDiscovered, unsubLost];131  sync.discoverPeers();132}133134async function stopPeerDiscoveryForPopup(): Promise<void> {135  for (const unsub of peerDiscoverySubscriptions) unsub();136  peerDiscoverySubscriptions = [];137  try {138    const sync = await import('./sync');139    if (sync.isHostConnected()) {140      await sync.stopDiscovery();141    }142  } catch {143    // best-effort144  }145}146147const PRIVATE_IPV4_RANGES = [148  { prefix: "10." },149  { prefix: "127." },150  { prefix: "169.254." },151  { prefix: "192.168." },152];153154// Empty disables network submission while the UI continues to function as a155// no-op (the handler returns ok:true without calling fetch). When set, the156// URL is validated by `isAllowedCanaryWebhookUrl` before any request, so the157// same private-IP/HTTPS rules that gate canary webhooks apply here.158const FEEDBACK_ENDPOINT = "";159160export function setupMessageHandler(): void {161  chrome.runtime.onMessage.addListener(162    (msg: unknown, sender, sendResponse) => {163      if (!isMessage(msg)) {164        sendResponse({ ok: false, error: "invalid message" });165        return true;166      }167      handleMessage(msg, sender)168        .then(sendResponse)169        .catch((err) =>170          sendResponse({171            ok: false,172            error: err instanceof Error ? err.message : String(err),173          })174        );175      return true;176    }177  );178}179180function isMessage(m: unknown): m is Message {181  return typeof m === "object" && m !== null && "type" in m;182}183184export async function handleMessage(185  msg: Message,186  sender: Partial<chrome.runtime.MessageSender> = {}187): Promise<MessageResponse> {188  try {189    // Validate sender — only allow messages from our extension pages/scripts.190    // `sender.id` is undefined for messages originating from extension UI191    // (popup/options), which is legitimate; reject only when it is defined192    // and does not match our extension id.193    if (194      !Capacitor.isNativePlatform() &&195      sender.id !== undefined &&196      sender.id !== chrome.runtime.id197    ) {198      return { ok: false, error: "invalid sender" };199    }200201    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {202      touchAutoLock();203    }204205    switch (msg.type) {206      case "CREATE_VAULT": {207        const { password } = msg.payload as { password: string };208        await vault.createVault(password);209        await setupAutoLock();210        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });211        return { ok: true };212      }213      case "UNLOCK": {214        const { password } = msg.payload as { password: string };215        const ok = await vault.unlock(password);216        if (ok) {217          await setupAutoLock();218          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });219        }220        return { ok };221      }222      case "LOCK":223        vault.lock();224        return { ok: true };225      case "IS_UNLOCKED":226        return { ok: true, data: vault.isUnlocked() };227      case "GET_VAULT_STATUS":228        return { ok: true, unlocked: vault.isUnlocked() };229      case "HAS_VAULT":230        return { ok: true, data: await vault.hasVault() };231      case "GET_ENTRIES":232        return { ok: true, data: vault.getEntries() };233      case "ADD_ENTRY": {234        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };235        const entry = await vault.addEntry(msg.payload as any);236        return { ok: true, data: entry };237      }238      case "BATCH_ADD_ENTRIES": {239        const { entries } = msg.payload as { entries: any[] };240        const added = await vault.batchAddEntries(entries);241        return { ok: true, data: added };242      }243      case "RESTORE_ENTRIES": {244        const { entries, mode, settings } = msg.payload as {245          entries: any[];246          mode: "replace" | "merge";247          settings?: vault.VaultSettings;248        };249        const summary = await vault.restoreEntries(entries, mode);250        if (settings && typeof settings === "object") {251          await vault.updateSettings(settings);252        }253        return { ok: true, data: summary };254      }255      case "CLEAR_VAULT_ENTRIES": {256        await vault.clearVaultEntries("REPLACE_ALL");257        return { ok: true };258      }259      case "LIST_VAULT_SNAPSHOTS": {260        const snapshots = await vault.listSnapshots();261        return { ok: true, data: snapshots };262      }263      case "RESTORE_VAULT_SNAPSHOT": {264        const { index, password } = msg.payload as { index: number; password: string };265        const ok = await vault.restoreFromSnapshot(index, password);266        if (ok) broadcastToContentScripts({ type: "VAULT_UNLOCKED" });267        return { ok };268      }269      case "COUNT_DUPLICATES": {270        return { ok: true, data: vault.countDuplicates() };271      }272      case "DEDUPLICATE_ENTRIES": {273        const removed = await vault.deduplicateEntries();274        return { ok: true, data: removed };275      }276      case "UPDATE_ENTRY": {277        const { id, patch } = msg.payload as any;278        await vault.updateEntry(id, patch);279        return { ok: true };280      }281      case "ADD_ADDITIONAL_URL": {282        const { id, url } = msg.payload as { id: string; url: string };283        const trimmed = typeof url === "string" ? url.trim() : "";284        if (!trimmed) return { ok: false, error: "url required" };285        const existing = vault.getEntryById(id);286        if (!existing) return { ok: false, error: "entry not found" };287        if (existing.type !== "login") return { ok: false, error: "login entries only" };288        const merged = [...(existing.additionalUrls ?? []), trimmed];289        await vault.updateEntry(id, { additionalUrls: merged });290        return { ok: true };291      }292      case "DELETE_ENTRY": {293        const { id } = msg.payload as { id: string };294        await vault.deleteEntry(id);295        return { ok: true };296      }297      case "GET_DELETED_ENTRIES":298        return { ok: true, data: vault.getDeletedEntries() };299      case "RESTORE_ENTRY": {300        const { id } = msg.payload as { id: string };301        await vault.restoreEntry(id);302        return { ok: true };303      }304      case "PURGE_ENTRY": {305        const { id } = msg.payload as { id: string };306        await vault.purgeEntry(id);307        return { ok: true };308      }309      case "PURGE_EXPIRED_TRASH": {310        const { retentionMs } = msg.payload as { retentionMs: number };311        const purged = await vault.purgeExpiredTrash(retentionMs);312        return { ok: true, data: purged };313      }314      case "AUTOFILL_QUERY": {315        if (!vault.isUnlocked()) {316          return { ok: false, error: "VAULT_LOCKED" };317        }318        const { domain, includeAll, kind } = msg.payload as {319          domain: string;320          includeAll?: boolean;321          kind?: "login" | "card";322        };323        // kind="card": return saved cards as compact summaries for the324        // inline card silver platter. Cards are not domain-scoped — every325        // saved card is a candidate on every checkout page — so domain is326        // ignored when kind === "card".327        if (kind === "card") {328          const cards = vault.getEntries().filter((e) => e.type === "card");329          return {330            ok: true,331            data: cards.map((e) => ({332              id: e.id,333              title: e.cardNickname || e.title,334              cardholderName: e.cardholderName,335              last4: e.last4,336              expMonth: e.expMonth,337              expYear: e.expYear,338              network: e.network,339            })),340          };341        }342        // The inline selector fills username+password into a form. Passkey-343        // only entries have no password to fill; sign-in for those goes344        // through the WebAuthn path instead. Filter them out everywhere so345        // the user doesn't see four "GitHub" rows that mostly do nothing.346        // Notes and cards never belonged here either.347        const matches = (348          includeAll349            ? vault350                .getEntries()351                .filter((entry) => entry.type !== "note" && entry.type !== "card")352            : vault.queryDomain(domain)353        ).filter((entry) => !isPasskeyOnly(entry));354        return {355          ok: true,356          data: matches.map((e) =>357            includeAll358              ? {359                  id: e.id,360                  title: e.title,361                  hasPasskey: e.passkey !== undefined,362                }363              : {364                  id: e.id,365                  title: e.title,366                  username: e.username,367                  url: e.url,368                  hasTotp: Boolean(e.totp),369                  hasPasskey: e.passkey !== undefined,370                }371          ),372        };373      }374      case "GET_ENTRY_FOR_FILL": {375        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };376        const { id } = msg.payload as { id: string };377        const entry = vault.getEntryById(id);378        if (!entry) return { ok: false, error: "entry not found" };379        // Passkey-only entries (passkey credential, no password) cannot be380        // filled into a form — sign-in goes through the WebAuthn path. A381        // login that ALSO has a passkey is still fillable for its password.382        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey not fillable" };383        // Strip the passkey credential from the response — content scripts384        // never need the private key, and there's no reason to expose the385        // public credential metadata over the boundary either.386        const { passkey: _strippedPasskey, ...safeEntry } = entry;387        return { ok: true, data: safeEntry };388      }389      case "COPY": {390        const { text, label, alreadyWritten } = msg.payload as {391          text: string;392          label: string;393          alreadyWritten?: boolean;394        };395        await copyToClipboard(text, label, Boolean(alreadyWritten));396        return { ok: true };397      }398      case "CHECK_BREACH": {399        const { password } = msg.payload as { password: string };400        const count = await vault.checkBreach(password);401        return { ok: true, data: count };402      }403      case "CHECK_ALL_BREACHES": {404        const allEntries = vault.getEntries();405        const results: Record<string, number> = {};406        for (const entry of allEntries) {407          if (entry.type === "note") continue;408          if (!entry.password) continue;409          results[entry.id] = await vault.checkBreach(entry.password);410          // Small delay — be a good citizen to the HIBP API411          await new Promise((r) => setTimeout(r, 200));412        }413        // Persist any non-zero counts back to entries414        for (const [id, count] of Object.entries(results)) {415          const entry = vault.getEntryById(id);416          if (entry && (entry.breach ?? 0) !== count) {417            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });418          }419        }420        return { ok: true, data: results };421      }422      case "GET_SETTINGS":423        return { ok: true, data: await vault.ensureSettingsLoaded() };424      case "UPDATE_SETTINGS": {425        const patch = msg.payload as Record<string, unknown>;426        await vault.updateSettings(patch as any);427        if (typeof patch.autoLockMinutes === "number") {428          await setupAutoLock();429          if (vault.isUnlocked()) touchAutoLock();430        }431        return { ok: true };432      }433      case "GET_PENDING_PASSKEY":434        return { ok: true, data: await getPendingPasskeyRequest() };435      case "APPROVE_PASSKEY": {436        const { requestId } = msg.payload as { requestId: number };437        await resolvePendingPasskeyRequest(requestId, true);438        return { ok: true };439      }440      case "DENY_PASSKEY": {441        const { requestId } = msg.payload as { requestId: number };442        await resolvePendingPasskeyRequest(requestId, false);443        return { ok: true };444      }445      case "GET_PASSKEYS":446        return {447          ok: true,448          data: vault.getEntries().filter((entry) => entry.passkey !== undefined),449        };450      case "DELETE_PASSKEY": {451        const { id } = msg.payload as { id: string };452        await vault.deleteEntry(id);453        return { ok: true };454      }455      case "GET_PASSKEY_PROVIDER_STATE":456        return { ok: true, data: await getPasskeyProviderState() };457      case "SET_PASSKEY_PROVIDER_ENABLED": {458        const { enabled } = msg.payload as { enabled: boolean };459        // Disabling is always free; gating fires only when a free user is460        // trying to turn passkey interception on.461        if (enabled) {462          const gate = await requirePro("passkeys");463          if (!gate.allowed) return { ok: false, error: "pro_required" };464        }465        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };466      }467      case "FIRE_CANARY_PING": {468        const { webhookUrl, entryTitle, trigger } = msg.payload as {469          webhookUrl: string;470          entryTitle: string;471          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";472        };473        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {474          return { ok: false, error: "invalid webhook url" };475        }476        const body = JSON.stringify({477          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",478          entry: entryTitle,479          trigger,480          timestamp: new Date().toISOString(),481          source: "peach-extension",482        });483        if (trigger === "test") {484          // Permitted outbound fetch: user-configured canary alert endpoint485          // (validated by isAllowedCanaryWebhookUrl above). This is the486          // only non-HIBP outbound call in the extension — see487          // Projects.md §3.7. Test pings are awaited so the UI can show488          // success/failure.489          try {490            const res = await fetch(webhookUrl, {491              method: "POST",492              headers: { "Content-Type": "application/json" },493              body,494            });495            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };496          } catch (err) {497            return { ok: false, error: err instanceof Error ? err.message : "network error" };498          }499        }500        // Non-test triggers are fire-and-forget501        fetch(webhookUrl, {502          method: "POST",503          headers: { "Content-Type": "application/json" },504          body,505        }).catch(() => {});506        return { ok: true };507      }508      case "ACTIVATE_LICENSE": {509        const { key } = msg.payload as { key: string };510        const licenseInfo = await activateLicense(key);511        return { ok: true, data: licenseInfo };512      }513      case "GET_LICENSE": {514        const licenseInfo = await getLicenseInfo();515        return { ok: true, data: licenseInfo };516      }517      case "GET_LICENSE_KEY": {518        const key = await getLicenseKey();519        return { ok: true, data: key };520      }521      case "DEACTIVATE_LICENSE": {522        await deactivateLicense();523        return { ok: true };524      }525      case "SHOULD_PLAY_CELEBRATION": {526        const should = await shouldPlayCelebration();527        return { ok: true, data: should };528      }529      case "MARK_CELEBRATION_PLAYED": {530        await markCelebrationPlayed();531        return { ok: true };532      }533      case "OPEN_PRO_GATE": {534        // Content script requests: open popup and navigate to License section.535        const { feature } = (msg.payload ?? {}) as { feature?: string };536        if (chrome.storage.session) {537          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });538        }539        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }540        return { ok: true };541      }542      case "GET_IDENTITIES": {543        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };544        return { ok: true, data: vault.getIdentities() };545      }546      case "GET_ADVANCED_HEALTH_REPORT": {547        const gate = await requirePro("advanced_health");548        if (!gate.allowed) return { ok: false, error: "pro_required" };549        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };550        const report = await buildAdvancedHealthReport(vault.getEntries());551        return { ok: true, data: report };552      }553      case "INITIATE_PASSWORD_CHANGE": {554        const gate = await requirePro("smart_password_change");555        if (!gate.allowed) return { ok: false, error: "pro_required" };556        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };557        const { id } = msg.payload as { id: string };558        const entry = vault.getEntryById(id);559        if (!entry) return { ok: false, error: "entry not found" };560        const url = resolveResetUrl(entry);561        if (!url) return { ok: false, error: "no reset url" };562        try {563          await chrome.tabs.create({ url });564          return { ok: true, data: { url } };565        } catch (err) {566          return {567            ok: false,568            error: err instanceof Error ? err.message : "failed to open tab",569          };570        }571      }572      case "IS_DURESS_ENABLED": {573        const enabled = await vault.isDuressEnabled();574        return { ok: true, data: enabled };575      }576      case "SETUP_DURESS": {577        const { duressPassword } = msg.payload as { duressPassword: string };578        await vault.setupDuress(duressPassword);579        return { ok: true };580      }581      case "DISABLE_DURESS": {582        await vault.disableDuress();583        return { ok: true };584      }585      case "VERIFY_MAIN_PASSWORD": {586        const { password } = msg.payload as { password: string };587        const ok = await vault.verifyMainPassword(password);588        return { ok: true, data: ok };589      }590      case "CHANGE_PASSWORD": {591        const { currentPassword, newPassword } = msg.payload as {592          currentPassword: string;593          newPassword: string;594        };595        const changed = await vault.changePassword(currentPassword, newPassword);596        return changed597          ? { ok: true }598          : { ok: false, error: "incorrect current password" };599      }600      case "GET_SITE_PASSWORD_POLICY": {601        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });602        if (!tab?.id) return { ok: true, data: null };603        try {604          const response = await chrome.tabs.sendMessage(tab.id, {605            type: "GET_SITE_PASSWORD_POLICY",606          });607          return (response as MessageResponse) ?? { ok: true, data: null };608        } catch {609          return { ok: true, data: null };610        }611      }612      case "GET_SYNC_STATE": {613        const { getPairedDevices, getTrustedNetworks } = await import('./sync-storage');614        const { isOnTailscale } = await import('./sync-network');615        const { isProUser } = await import('./license');616        const pairedDevices = await getPairedDevices();617        const trustedNetworks = await getTrustedNetworks();618        const tailscale = await isOnTailscale();619        const pro = await isProUser();620        621        let status: SyncStatus = "offline";622        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {623          if (pairedDevices.length === 0) {624            status = "no_peers";625          } else {626            status = "synced";627          }628        } else {629          status = "not_trusted";630        }631        632        return { ok: true, data: { pairedDevices, trustedNetworks, status, isPro: pro } };633      }634      case "TRIGGER_SYNC": {635        const gate = await requirePro("sync");636        if (!gate.allowed) return { ok: false, error: "pro_required" };637        return { ok: true };638      }639      case "START_PAIRING": {640        const gate = await requirePro("sync");641        if (!gate.allowed) return { ok: false, error: "pro_required" };642        return { ok: true };643      }644      case "CANCEL_PAIRING": {645        return { ok: true };646      }647      case "ACCEPT_PAIRING": {648        const gate = await requirePro("sync");649        if (!gate.allowed) return { ok: false, error: "pro_required" };650        return { ok: true };651      }652      case "REMOVE_PAIRED_DEVICE": {653        const { deviceId } = msg.payload as { deviceId: string };654        const { removePairedDevice } = await import('./sync-storage');655        await removePairedDevice(deviceId);656        return { ok: true };657      }658      case "REMOVE_TRUSTED_NETWORK": {659        const { ssid, bssid, isTailscale } = msg.payload as any;660        const { removeTrustedNetwork, getTrustedNetworks } = await import('./sync-storage');661        const networks = await getTrustedNetworks();662        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 663          (isTailscale ? n.isTailscale : n.ssid === ssid) && 664          (!bssid || n.bssid === bssid)665        );666        if (network) {667          await removeTrustedNetwork(network.addedAt);668        }669        return { ok: true };670      }671      case "MARK_NETWORK_TRUSTED": {672        const { addTrustedNetwork } = await import('./sync-storage');673        const { getCurrentNetwork } = await import('./sync-network');674        const network = await getCurrentNetwork();675        await addTrustedNetwork({676          ssid: network.ssid,677          bssid: network.bssid,678          isTailscale: network.isTailscale,679          addedAt: Date.now(),680        });681        return { ok: true };682      }683      case "GET_INCOMING_PAIRING_REQUEST": {684        const { getIncomingPairingRequest } = await import('./sync-storage');685        const request = await getIncomingPairingRequest();686        return { ok: true, data: request };687      }688      case "RESPOND_INCOMING_PAIRING": {689        const { accept } = msg.payload as { accept: boolean };690        const { getIncomingPairingRequest, clearIncomingPairingRequest } = await import('./sync-storage');691        const request = await getIncomingPairingRequest();692        if (!request) return { ok: false, error: "no_pending_request" };693        await clearIncomingPairingRequest();694        if (accept) {695          // Trust-store wiring lives in src/background/sync.ts (`trustDevice`).696          // It is dormant until the native messaging host installer (Phase 9)697          // ships and runtime trigger paths come online; the user-side accept698          // here clears the banner and records intent for Phase 10 E2E.699          try {700            const { trustDevice } = await import('./sync');701            await trustDevice(request.publicKeyHex, request.deviceName);702          } catch {703            // Native host not installed yet — accept still succeeds locally.704          }705        }706        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };707      }708      case "START_PEER_DISCOVERY": {709        const gate = await requirePro("sync");710        if (!gate.allowed) return { ok: false, error: "pro_required" };711        try {712          await startPeerDiscoveryForPopup();713          return { ok: true };714        } catch (err) {715          return { ok: false, error: err instanceof Error ? err.message : "discovery_failed" };716        }717      }718      case "STOP_PEER_DISCOVERY": {719        try {720          await stopPeerDiscoveryForPopup();721        } catch {722          // best-effort cleanup723        }724        return { ok: true };725      }726      case "INITIATE_PAIR_WITH_PEER": {727        const gate = await requirePro("sync");728        if (!gate.allowed) return { ok: false, error: "pro_required" };729        const { peer } = msg.payload as {730          peer: { deviceId: string; deviceName: string; host: string; port: number; x25519PublicKey: string };731        };732        try {733          const sync = await import('./sync');734          const connectionId = await sync.connectToPeer(peer.host, peer.port, peer.x25519PublicKey);735          // Connection success means the peer accepted the dormant Noise NK736          // pairing handshake. Trust persistence happens once the user-side737          // approval banner on the *peer* device confirms — we record local738          // state here so Settings reflects the new device immediately.739          const { addPairedDevice } = await import('./sync-storage');740          await addPairedDevice({741            deviceId: peer.deviceId,742            displayName: peer.deviceName,743            x25519PublicKey: peer.x25519PublicKey,744            pairedAt: Date.now(),745          });746          return { ok: true, data: { connectionId, deviceName: peer.deviceName } };747        } catch (err) {748          return { ok: false, error: err instanceof Error ? err.message : "pair_failed" };749        }750      }751      case "DEBUG_INJECT_INCOMING_PAIRING": {752        // Manual E2E rehearsal hook. Inserts a synthetic incoming pairing753        // request into session storage so Phase 7 banner UX can be exercised754        // without a live native host. No Pro gate — this is a no-op in755        // production unless explicitly invoked from a Settings debug action.756        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {757          deviceName?: string;758          publicKeyHex?: string;759        };760        if (!deviceName || !publicKeyHex) {761          return { ok: false, error: "missing_payload" };762        }763        const { setIncomingPairingRequest } = await import('./sync-storage');764        const now = Date.now();765        await setIncomingPairingRequest({766          deviceName,767          publicKeyHex,768          receivedAt: now,769          expiresAt: now + 60_000,770        });771        return { ok: true };772      }773      case "RESET_SYNC_IDENTITY": {774        const gate = await requirePro("sync");775        if (!gate.allowed) return { ok: false, error: "pro_required" };776        const { getPairedDevices, removePairedDevice } = await import('./sync-storage');777        const devices = await getPairedDevices();778        for (const device of devices) {779          await removePairedDevice(device.deviceId);780        }781        // Native rotation is best-effort: when the native messaging host is782        // not yet installed (Phase 9), connectNative throws and we still783        // honour the local clear so the UI reflects the reset. The native784        // identity rotates the next time the host starts cleanly anyway.785        let nativePublicKey: string | null = null;786        try {787          const { rotateNativeIdentity, disconnectSyncHost } = await import('./sync');788          nativePublicKey = await rotateNativeIdentity();789          disconnectSyncHost();790        } catch {791          nativePublicKey = null;792        }793        return { ok: true, data: { removedDevices: devices.length, nativePublicKey } };794      }795      case "RECORD_MANUAL_SUMMON": {796        const { domain } = msg.payload as { domain: string };797        const settings = vault.getSettings();798        const existing = settings.manualSummonDomains?.[domain];799        const now = Date.now();800        await vault.updateSettings({801          manualSummonDomains: {802            ...settings.manualSummonDomains,803            [domain]: {804              firstSummonedAt: existing?.firstSummonedAt ?? now,805              summonCount: (existing?.summonCount ?? 0) + 1,806              lastSummonedAt: now,807            },808          },809        });810        return { ok: true };811      }812      case "DECLINE_CARD_SAVE": {813        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };814        await vault.declineCardSaveOffer(last4, expMonth, expYear);815        return { ok: true };816      }817      case "IS_CARD_DECLINED": {818        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };819        const declined = await vault.isCardDeclined(last4, expMonth, expYear);820        return { ok: true, data: declined };821      }822      case "INITIATE_FIREFOX_PASSKEY_CREATE": {823        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {824          rpId?: string;825          rpName?: string;826          userName?: string;827          userDisplayName?: string;828        };829        if (!rpId || !userName) return { ok: false, error: "rpId and userName required" };830        return await initiateFirefoxPasskeyCreate({831          rpId,832          rpName: rpName ?? rpId,833          userName,834          userDisplayName,835        });836      }837838      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {839        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;840        if (!payload) return { ok: false, error: "missing payload" };841        return await completeFirefoxPasskeyCreate(payload);842      }843844      case "PASSKEY_OFFER_DECLINE": {845        const { domain } = (msg.payload ?? {}) as { domain?: string };846        if (!domain) return { ok: false, error: "domain required" };847        await recordPasskeyOfferDecline(domain);848        return { ok: true };849      }850851      case "GET_PASSKEY_OFFER_DECLINED": {852        const { domain } = (msg.payload ?? {}) as { domain?: string };853        if (!domain) return { ok: false, error: "domain required" };854        return { ok: true, data: await isPasskeyOfferDeclined(domain) };855      }856857      case "PASSKEY_HAS_CREDENTIALS": {858        const payload = msg.payload as {859          rpId?: string;860          allowCredentials?: Array<{ id: string; type?: string }>;861        } | undefined;862        if (!payload?.rpId) return { ok: false, error: "rpId required" };863        return await handlePasskeyHasCredentials({864          rpId: payload.rpId,865          allowCredentials: payload.allowCredentials ?? [],866        });867      }868869      case "PASSKEY_CREATE": {870        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;871        if (!payload?.rpId || !payload?.userName) {872          return { ok: false, error: "rpId and userName required" };873        }874        return await handleFirefoxPasskeyCreate(payload);875      }876877      case "PASSKEY_GET": {878        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;879        if (!payload?.rpId) return { ok: false, error: "rpId required" };880        return await handleFirefoxPasskeyGet(payload);881      }882883      case "GET_PASSKEY_FOR_DOMAIN": {884        const { domain } = (msg.payload ?? {}) as { domain?: string };885        if (!domain) return { ok: false, error: "domain required" };886        if (!vault.isUnlocked()) return { ok: true, data: null };887        const match = vault888          .getEntries()889          .find((entry) => entry.passkey?.rpId === domain);890        if (!match || !match.passkey) return { ok: true, data: null };891        // Slim shape — only the fields State 11 needs. Never expose private892        // key material, even though this is locked behind isUnlocked.893        return {894          ok: true,895          data: {896            rpId: match.passkey.rpId,897            userName: match.passkey.userName,898            browser: match.passkey.browser,899          },900        };901      }902903      case "DESTROY_VAULT": {904        // Irreversible by design. Lock zeroes the derived key + in-memory entries;905        // storage.local.clear() wipes every Peach key (slots, settings, license,906        // onboarded flag, snapshots, sync state, declined cards, recall, etc.);907        // session.clear() wipes pending passkey requests + pro-notice queues.908        // Caller (Panic.tsx) handles UI navigation back to onboarding.909        vault.lock();910        await storageClear();911        if (!Capacitor.isNativePlatform() && chrome.storage.session) {912          await chrome.storage.session.clear();913        }914        return { ok: true };915      }916917      case "SUBMIT_FEEDBACK": {918        const { category, message, version, browser } = msg.payload as {919          category: string;920          message: string;921          version: string;922          browser: string;923        };924        if (!message.trim()) return { ok: false, error: "message is empty" };925        if (!FEEDBACK_ENDPOINT) return { ok: true };926        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {927          return { ok: false, error: "invalid feedback endpoint" };928        }929        try {930          const res = await fetch(FEEDBACK_ENDPOINT, {931            method: "POST",932            headers: { "Content-Type": "application/json" },933            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),934          });935          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };936        } catch (err) {937          return { ok: false, error: err instanceof Error ? err.message : "network error" };938        }939      }940      default:941        return { ok: false, error: "unknown message type" };942    }943  } catch (err) {944    return {945      ok: false,946      error: err instanceof Error ? err.message : "operation failed",947    };948  }949}950951/** Notify all content scripts that the vault just became available. */952function broadcastToContentScripts(message: { type: string }): void {953  if (Capacitor.isNativePlatform() || !chrome.tabs?.query) return;954  chrome.tabs.query({}, (tabs) => {955    for (const tab of tabs) {956      if (tab.id !== undefined) {957        chrome.tabs.sendMessage(tab.id, message).catch(() => {958          // Tab may not have a content script — silently ignore959        });960      }961    }962  });963}964965function shouldRefreshAutoLock(type: MessageType): boolean {966  return (967    type !== "HAS_VAULT" &&968    type !== "IS_UNLOCKED" &&969    type !== "GET_VAULT_STATUS" &&970    type !== "LOCK" &&971    type !== "UPDATE_SETTINGS" &&972    type !== "GET_PENDING_PASSKEY" &&973    type !== "GET_PASSKEY_PROVIDER_STATE" &&974    type !== "DECLINE_CARD_SAVE" &&975    type !== "IS_CARD_DECLINED" &&976    type !== "SUBMIT_FEEDBACK"977  );978}979980function isAllowedCanaryWebhookUrl(value: string): boolean {981  try {982    const url = new URL(value);983    if (url.protocol !== "https:") return false;984985    const hostname = url.hostname.toLowerCase();986    if (987      hostname === "localhost" ||988      hostname.endsWith(".localhost") ||989      isPrivateIpv4(hostname) ||990      isPrivateIpv6(hostname)991    ) {992      return false;993    }994995    return true;996  } catch {997    return false;998  }999}10001001function isPrivateIpv4(hostname: string): boolean {1002  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1003    return true;1004  }10051006  const octets = hostname.split(".").map((part) => Number(part));1007  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1008    return false;1009  }10101011  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1012}10131014function isPrivateIpv6(hostname: string): boolean {1015  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1016  return (1017    normalized === "::1" ||1018    normalized.startsWith("fc") ||1019    normalized.startsWith("fd") ||1020    normalized.startsWith("fe80:")1021  );1022}