messages.ts

50.8 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 * as syncLifecycle from "./sync-lifecycle";16import {17  activateLicense,18  deactivateLicense,19  getLicenseInfo,20  getLicenseKey,21  isProUser,22  markCelebrationPlayed,23  shouldPlayCelebration,24} from "./license";25import {26  cancelFirefoxPasskeyCreate,27  completeFirefoxPasskeyCreate,28  getPasskeyProviderState,29  getPendingPasskeyRequest,30  handleFirefoxPasskeyCreate,31  handleFirefoxPasskeyGet,32  handlePasskeyHasCredentials,33  initiateFirefoxPasskeyCreate,34  isPasskeyOfferDeclined,35  recordPasskeyOfferDecline,36  resolvePendingPasskeyRequest,37  setPasskeyProviderEnabled,38} from "./passkey";39import { buildAdvancedHealthReport, resolveResetUrl } from "./health";40import { Capacitor } from "@capacitor/core";41import { storageClear } from "../shared/storage";42import type {43  Message,44  MessageResponse,45  MessageType,46  ProFeature,47} from "../shared/types";48import { isPasskeyOnly } from "../shared/types";49import type { SyncStatus } from "../shared/sync-types";5051/**52 * The single Pro gate. Every gated handler calls this first; the broadcast53 * lets the popup react (navigate to the License section, highlight the54 * relevant feature). Background never touches the popup view directly —55 * the popup owns navigation. See Projects.md "Pro gate rule".56 */57async function requirePro(58  feature: ProFeature,59  trigger: "user" | "background" = "user"60): Promise<{ allowed: boolean }> {61  if (await isProUser()) return { allowed: true };6263  if (trigger === "user") {64    // User deliberately triggered this feature — redirect the popup immediately.65    if (!Capacitor.isNativePlatform()) {66      chrome.runtime67        .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })68        .catch(() => {69          // Popup may be closed — the gate signal is best-effort.70        });71    }72  } else {73    // Background trigger (e.g. passive sync initiation) — no popup is open.74    // Queue a notice so the next popup open shows a soft banner instead of75    // silently failing.76    if (!Capacitor.isNativePlatform() && chrome.storage.session) {77      chrome.storage.session78        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })79        .catch(() => {});80    }81  }8283  return { allowed: false };84}8586// ---------------------------------------------------------------------------87// Local device name. Peers see this string in PAIR_REQUEST / PAIR_ACCEPT and88// next to the device in their paired-devices list. Default to a platform-aware89// fallback when the user hasn't set one explicitly.90const DEVICE_NAME_KEY = "peach_device_name";9192async function getLocalDeviceName(): Promise<string> {93  try {94    const stored = await chrome.storage.local.get(DEVICE_NAME_KEY);95    const value = (stored as Record<string, string | undefined>)[DEVICE_NAME_KEY];96    if (typeof value === "string" && value.trim()) return value.trim();97  } catch {98    // fall through to default99  }100  if (Capacitor.getPlatform() === "android") return "Peach Android";101  if (Capacitor.getPlatform() === "ios") return "Peach iOS";102  return "Peach";103}104105// ---------------------------------------------------------------------------106// 6-digit code pairing.107108const PAIRING_TOKEN_TTL_MS = 5 * 60 * 1000;109110function generateSixDigitToken(): string {111  // crypto.getRandomValues, not Math.random — the token is the only secret112  // protecting the pairing window from a same-LAN attacker. 6 decimal digits113  // is 1 in 1,000,000; combined with a 5-minute TTL and pairing-mode gating114  // on the responder this is the right tradeoff between UX and security.115  const buf = new Uint32Array(1);116  crypto.getRandomValues(buf);117  const value = buf[0] % 1_000_000;118  return value.toString().padStart(6, "0");119}120121// ---------------------------------------------------------------------------122// Peer discovery glue (Phase 7 popup pairing flow).123//124// The popup opens discovery via START_PEER_DISCOVERY. We connect to the125// native sync host, subscribe once, and re-broadcast every PEER_DISCOVERED /126// PEER_LOST event to the popup as a SYNC_PEER_DISCOVERED / SYNC_PEER_LOST127// runtime message. The popup is the only consumer; if it closes, STOP is128// sent on cleanup which tears down subscriptions and the native discovery.129// ---------------------------------------------------------------------------130131let peerDiscoverySubscriptions: Array<() => void> = [];132133async function startPeerDiscoveryForPopup(): Promise<void> {134  await stopPeerDiscoveryForPopup();135  const sync = await import('./sync');136  const { getPairedDevices } = await import('./sync-storage');137  sync.connectSyncHost();138139  const unsubDiscovered = sync.onPeerDiscovered((peer) => {140    void (async () => {141      const paired = await getPairedDevices();142      const alreadyPaired = paired.some((d) => d.deviceId === peer.deviceId);143      if (Capacitor.isNativePlatform()) return;144      chrome.runtime145        .sendMessage({146          type: "SYNC_PEER_DISCOVERED",147          peer: {148            deviceId: peer.deviceId,149            deviceName: peer.name,150            host: peer.host,151            port: peer.port,152            wsPort: peer.wsPort,153            x25519PublicKey: peer.x25519PublicKey,154            alreadyPaired,155          },156        })157        .catch(() => {});158    })();159  });160  const unsubLost = sync.onPeerLost((deviceId) => {161    if (Capacitor.isNativePlatform()) return;162    chrome.runtime163      .sendMessage({ type: "SYNC_PEER_LOST", deviceId })164      .catch(() => {});165  });166  peerDiscoverySubscriptions = [unsubDiscovered, unsubLost];167  sync.discoverPeers();168}169170async function stopPeerDiscoveryForPopup(): Promise<void> {171  for (const unsub of peerDiscoverySubscriptions) unsub();172  peerDiscoverySubscriptions = [];173  try {174    const sync = await import('./sync');175    if (sync.isHostConnected()) {176      await sync.stopDiscovery();177    }178  } catch {179    // best-effort180  }181}182183const PRIVATE_IPV4_RANGES = [184  { prefix: "10." },185  { prefix: "127." },186  { prefix: "169.254." },187  { prefix: "192.168." },188];189190// Empty disables network submission while the UI continues to function as a191// no-op (the handler returns ok:true without calling fetch). When set, the192// URL is validated by `isAllowedCanaryWebhookUrl` before any request, so the193// same private-IP/HTTPS rules that gate canary webhooks apply here.194const FEEDBACK_ENDPOINT = "";195196export function setupMessageHandler(): void {197  chrome.runtime.onMessage.addListener(198    (msg: unknown, sender, sendResponse) => {199      if (!isMessage(msg)) {200        sendResponse({ ok: false, error: "invalid message" });201        return true;202      }203      handleMessage(msg, sender)204        .then(sendResponse)205        .catch((err) =>206          sendResponse({207            ok: false,208            error: err instanceof Error ? err.message : String(err),209          })210        );211      return true;212    }213  );214}215216function isMessage(m: unknown): m is Message {217  return typeof m === "object" && m !== null && "type" in m;218}219220export async function handleMessage(221  msg: Message,222  sender: Partial<chrome.runtime.MessageSender> = {}223): Promise<MessageResponse> {224  try {225    // Validate sender — only allow messages from our extension pages/scripts.226    // `sender.id` is undefined for messages originating from extension UI227    // (popup/options), which is legitimate; reject only when it is defined228    // and does not match our extension id.229    if (230      !Capacitor.isNativePlatform() &&231      sender.id !== undefined &&232      sender.id !== chrome.runtime.id233    ) {234      return { ok: false, error: "invalid sender" };235    }236237    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {238      touchAutoLock();239    }240241    switch (msg.type) {242      case "CREATE_VAULT": {243        const { password } = msg.payload as { password: string };244        await vault.createVault(password);245        await setupAutoLock();246        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });247        void syncLifecycle.onVaultUnlocked();248        return { ok: true };249      }250      case "UNLOCK": {251        const { password } = msg.payload as { password: string };252        const ok = await vault.unlock(password);253        if (ok) {254          await setupAutoLock();255          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });256          void syncLifecycle.onVaultUnlocked();257        }258        return { ok };259      }260      case "LOCK":261        vault.lock();262        void syncLifecycle.onVaultLocked();263        return { ok: true };264      case "IS_UNLOCKED":265        return { ok: true, data: vault.isUnlocked() };266      case "GET_VAULT_STATUS":267        return { ok: true, unlocked: vault.isUnlocked() };268      case "HAS_VAULT":269        return { ok: true, data: await vault.hasVault() };270      case "GET_ENTRIES":271        return { ok: true, data: vault.getEntries() };272      case "ADD_ENTRY": {273        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };274        const entry = await vault.addEntry(msg.payload as any);275        return { ok: true, data: entry };276      }277      case "BATCH_ADD_ENTRIES": {278        const { entries } = msg.payload as { entries: any[] };279        const added = await vault.batchAddEntries(entries);280        return { ok: true, data: added };281      }282      case "RESTORE_ENTRIES": {283        const { entries, mode, settings } = msg.payload as {284          entries: any[];285          mode: "replace" | "merge";286          settings?: vault.VaultSettings;287        };288        const summary = await vault.restoreEntries(entries, mode);289        if (settings && typeof settings === "object") {290          await vault.updateSettings(settings);291        }292        return { ok: true, data: summary };293      }294      case "CLEAR_VAULT_ENTRIES": {295        await vault.clearVaultEntries("REPLACE_ALL");296        return { ok: true };297      }298      case "GET_VAULT_HISTORY": {299        const snapshots = await vault.getVaultHistory();300        return { ok: true, data: snapshots };301      }302      case "RESTORE_VAULT_SNAPSHOT": {303        const { snapshotId } = msg.payload as { snapshotId: string };304        const result = await vault.restoreVaultSnapshot(snapshotId);305        if (!result.ok) return { ok: false, error: result.error };306        broadcastToContentScripts({ type: "VAULT_LOCKED" });307        return { ok: true };308      }309      case "COUNT_DUPLICATES": {310        return { ok: true, data: vault.countDuplicates() };311      }312      case "DEDUPLICATE_ENTRIES": {313        const removed = await vault.deduplicateEntries();314        return { ok: true, data: removed };315      }316      case "UPDATE_ENTRY": {317        const { id, patch } = msg.payload as any;318        await vault.updateEntry(id, patch);319        return { ok: true };320      }321      case "ADD_ADDITIONAL_URL": {322        const { id, url } = msg.payload as { id: string; url: string };323        const trimmed = typeof url === "string" ? url.trim() : "";324        if (!trimmed) return { ok: false, error: "url required" };325        const existing = vault.getEntryById(id);326        if (!existing) return { ok: false, error: "entry not found" };327        if (existing.type !== "login") return { ok: false, error: "login entries only" };328        const merged = [...(existing.additionalUrls ?? []), trimmed];329        await vault.updateEntry(id, { additionalUrls: merged });330        return { ok: true };331      }332      case "DELETE_ENTRY": {333        const { id } = msg.payload as { id: string };334        await vault.deleteEntry(id);335        return { ok: true };336      }337      case "GET_DELETED_ENTRIES":338        return { ok: true, data: vault.getDeletedEntries() };339      case "RESTORE_ENTRY": {340        const { id } = msg.payload as { id: string };341        await vault.restoreEntry(id);342        return { ok: true };343      }344      case "PURGE_ENTRY": {345        const { id } = msg.payload as { id: string };346        await vault.purgeEntry(id);347        return { ok: true };348      }349      case "PURGE_EXPIRED_TRASH": {350        const { retentionMs } = msg.payload as { retentionMs: number };351        const purged = await vault.purgeExpiredTrash(retentionMs);352        return { ok: true, data: purged };353      }354      case "AUTOFILL_QUERY": {355        if (!vault.isUnlocked()) {356          return { ok: false, error: "VAULT_LOCKED" };357        }358        const { domain, includeAll, kind } = msg.payload as {359          domain: string;360          includeAll?: boolean;361          kind?: "login" | "card";362        };363        // kind="card": return saved cards as compact summaries for the364        // inline card silver platter. Cards are not domain-scoped — every365        // saved card is a candidate on every checkout page — so domain is366        // ignored when kind === "card".367        if (kind === "card") {368          const cards = vault.getEntries().filter((e) => e.type === "card");369          return {370            ok: true,371            data: cards.map((e) => ({372              id: e.id,373              title: e.cardNickname || e.title,374              cardholderName: e.cardholderName,375              last4: e.last4,376              expMonth: e.expMonth,377              expYear: e.expYear,378              network: e.network,379            })),380          };381        }382        // The inline selector fills username+password into a form. Passkey-383        // only entries have no password to fill; sign-in for those goes384        // through the WebAuthn path instead. Filter them out everywhere so385        // the user doesn't see four "GitHub" rows that mostly do nothing.386        // Notes and cards never belonged here either.387        const matches = (388          includeAll389            ? vault390                .getEntries()391                .filter((entry) => entry.type !== "note" && entry.type !== "card")392            : vault.queryDomain(domain)393        ).filter((entry) => !isPasskeyOnly(entry));394        return {395          ok: true,396          data: matches.map((e) =>397            includeAll398              ? {399                  id: e.id,400                  title: e.title,401                  hasPasskey: e.passkey !== undefined,402                }403              : {404                  id: e.id,405                  title: e.title,406                  username: e.username,407                  url: e.url,408                  hasTotp: Boolean(e.totp),409                  hasPasskey: e.passkey !== undefined,410                }411          ),412        };413      }414      case "GET_ENTRY_FOR_FILL": {415        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };416        const { id } = msg.payload as { id: string };417        const entry = vault.getEntryById(id);418        if (!entry) return { ok: false, error: "entry not found" };419        // Passkey-only entries (passkey credential, no password) cannot be420        // filled into a form — sign-in goes through the WebAuthn path. A421        // login that ALSO has a passkey is still fillable for its password.422        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey not fillable" };423        // Strip the passkey credential from the response — content scripts424        // never need the private key, and there's no reason to expose the425        // public credential metadata over the boundary either.426        const { passkey: _strippedPasskey, ...safeEntry } = entry;427        return { ok: true, data: safeEntry };428      }429      case "COPY": {430        const { text, label, alreadyWritten } = msg.payload as {431          text: string;432          label: string;433          alreadyWritten?: boolean;434        };435        await copyToClipboard(text, label, Boolean(alreadyWritten));436        return { ok: true };437      }438      case "CHECK_BREACH": {439        const { password } = msg.payload as { password: string };440        const count = await vault.checkBreach(password);441        return { ok: true, data: count };442      }443      case "CHECK_ALL_BREACHES": {444        const allEntries = vault.getEntries();445        const results: Record<string, number> = {};446        for (const entry of allEntries) {447          if (entry.type === "note") continue;448          if (!entry.password) continue;449          results[entry.id] = await vault.checkBreach(entry.password);450          // Small delay — be a good citizen to the HIBP API451          await new Promise((r) => setTimeout(r, 200));452        }453        // Persist any non-zero counts back to entries454        for (const [id, count] of Object.entries(results)) {455          const entry = vault.getEntryById(id);456          if (entry && (entry.breach ?? 0) !== count) {457            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });458          }459        }460        return { ok: true, data: results };461      }462      case "GET_SETTINGS":463        return { ok: true, data: await vault.ensureSettingsLoaded() };464      case "UPDATE_SETTINGS": {465        const patch = msg.payload as Record<string, unknown>;466        await vault.updateSettings(patch as any);467        if (typeof patch.autoLockMinutes === "number") {468          await setupAutoLock();469          if (vault.isUnlocked()) touchAutoLock();470        }471        return { ok: true };472      }473      case "GET_PENDING_PASSKEY":474        return { ok: true, data: await getPendingPasskeyRequest() };475      case "APPROVE_PASSKEY": {476        const { requestId } = msg.payload as { requestId: number };477        await resolvePendingPasskeyRequest(requestId, true);478        return { ok: true };479      }480      case "DENY_PASSKEY": {481        const { requestId } = msg.payload as { requestId: number };482        await resolvePendingPasskeyRequest(requestId, false);483        return { ok: true };484      }485      case "GET_PASSKEYS":486        return {487          ok: true,488          data: vault.getEntries().filter((entry) => entry.passkey !== undefined),489        };490      case "DELETE_PASSKEY": {491        const { id } = msg.payload as { id: string };492        await vault.deleteEntry(id);493        return { ok: true };494      }495      case "GET_PASSKEY_PROVIDER_STATE":496        return { ok: true, data: await getPasskeyProviderState() };497      case "SET_PASSKEY_PROVIDER_ENABLED": {498        const { enabled } = msg.payload as { enabled: boolean };499        // Disabling is always free; gating fires only when a free user is500        // trying to turn passkey interception on.501        if (enabled) {502          const gate = await requirePro("passkeys");503          if (!gate.allowed) return { ok: false, error: "pro_required" };504        }505        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };506      }507      case "FIRE_CANARY_PING": {508        const { webhookUrl, entryTitle, trigger } = msg.payload as {509          webhookUrl: string;510          entryTitle: string;511          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";512        };513        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {514          return { ok: false, error: "invalid webhook url" };515        }516        const body = JSON.stringify({517          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",518          entry: entryTitle,519          trigger,520          timestamp: new Date().toISOString(),521          source: "peach-extension",522        });523        if (trigger === "test") {524          // Permitted outbound fetch: user-configured canary alert endpoint525          // (validated by isAllowedCanaryWebhookUrl above). This is the526          // only non-HIBP outbound call in the extension — see527          // Projects.md §3.7. Test pings are awaited so the UI can show528          // success/failure.529          try {530            const res = await fetch(webhookUrl, {531              method: "POST",532              headers: { "Content-Type": "application/json" },533              body,534            });535            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };536          } catch (err) {537            return { ok: false, error: err instanceof Error ? err.message : "network error" };538          }539        }540        // Non-test triggers are fire-and-forget541        fetch(webhookUrl, {542          method: "POST",543          headers: { "Content-Type": "application/json" },544          body,545        }).catch(() => {});546        return { ok: true };547      }548      case "ACTIVATE_LICENSE": {549        const { key } = msg.payload as { key: string };550        const licenseInfo = await activateLicense(key);551        return { ok: true, data: licenseInfo };552      }553      case "GET_LICENSE": {554        const licenseInfo = await getLicenseInfo();555        return { ok: true, data: licenseInfo };556      }557      case "GET_LICENSE_KEY": {558        const key = await getLicenseKey();559        return { ok: true, data: key };560      }561      case "DEACTIVATE_LICENSE": {562        await deactivateLicense();563        return { ok: true };564      }565      case "SHOULD_PLAY_CELEBRATION": {566        const should = await shouldPlayCelebration();567        return { ok: true, data: should };568      }569      case "MARK_CELEBRATION_PLAYED": {570        await markCelebrationPlayed();571        return { ok: true };572      }573      case "OPEN_PRO_GATE": {574        // Content script requests: open popup and navigate to License section.575        const { feature } = (msg.payload ?? {}) as { feature?: string };576        if (chrome.storage.session) {577          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });578        }579        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }580        return { ok: true };581      }582      case "GET_IDENTITIES": {583        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };584        return { ok: true, data: vault.getIdentities() };585      }586      case "GET_ADVANCED_HEALTH_REPORT": {587        const gate = await requirePro("advanced_health");588        if (!gate.allowed) return { ok: false, error: "pro_required" };589        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };590        const report = await buildAdvancedHealthReport(vault.getEntries());591        return { ok: true, data: report };592      }593      case "INITIATE_PASSWORD_CHANGE": {594        const gate = await requirePro("smart_password_change");595        if (!gate.allowed) return { ok: false, error: "pro_required" };596        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };597        const { id } = msg.payload as { id: string };598        const entry = vault.getEntryById(id);599        if (!entry) return { ok: false, error: "entry not found" };600        const url = resolveResetUrl(entry);601        if (!url) return { ok: false, error: "no reset url" };602        try {603          await chrome.tabs.create({ url });604          return { ok: true, data: { url } };605        } catch (err) {606          return {607            ok: false,608            error: err instanceof Error ? err.message : "failed to open tab",609          };610        }611      }612      case "IS_DURESS_ENABLED": {613        const enabled = await vault.isDuressEnabled();614        return { ok: true, data: enabled };615      }616      case "SETUP_DURESS": {617        const { duressPassword } = msg.payload as { duressPassword: string };618        await vault.setupDuress(duressPassword);619        return { ok: true };620      }621      case "DISABLE_DURESS": {622        await vault.disableDuress();623        return { ok: true };624      }625      case "VERIFY_MAIN_PASSWORD": {626        const { password } = msg.payload as { password: string };627        const ok = await vault.verifyMainPassword(password);628        return { ok: true, data: ok };629      }630      case "CHANGE_PASSWORD": {631        const { currentPassword, newPassword } = msg.payload as {632          currentPassword: string;633          newPassword: string;634        };635        const changed = await vault.changePassword(currentPassword, newPassword);636        return changed637          ? { ok: true }638          : { ok: false, error: "incorrect current password" };639      }640      case "GET_SITE_PASSWORD_POLICY": {641        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });642        if (!tab?.id) return { ok: true, data: null };643        try {644          const response = await chrome.tabs.sendMessage(tab.id, {645            type: "GET_SITE_PASSWORD_POLICY",646          });647          return (response as MessageResponse) ?? { ok: true, data: null };648        } catch {649          return { ok: true, data: null };650        }651      }652      case "GET_SYNC_STATE": {653        const { getPairedDevices, getTrustedNetworks } = await import('./sync-storage');654        const { isOnTailscale } = await import('./sync-network');655        const { isProUser } = await import('./license');656        const { storageGet } = await import('../shared/storage');657        const pairedDevices = await getPairedDevices();658        const trustedNetworks = await getTrustedNetworks();659        const tailscale = await isOnTailscale();660        const pro = await isProUser();661662        let status: SyncStatus = "offline";663        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {664          if (pairedDevices.length === 0) {665            status = "no_peers";666          } else {667            status = "synced";668          }669        } else {670          status = "not_trusted";671        }672673        const lastSyncRaw = await storageGet("peach_last_sync_at");674        const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN;675        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined;676677        return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } };678      }679      case "TRIGGER_SYNC": {680        const gate = await requirePro("sync");681        if (!gate.allowed) return { ok: false, error: "pro_required" };682        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };683684        const { getPairedDevices, updatePairedDevice } = await import('./sync-storage');685        const paired = await getPairedDevices();686        if (paired.length === 0) return { ok: false, error: "no_paired_devices" };687688        const lifecycle = await import('./sync-lifecycle');689        const sync = await import('./sync');690        const { storageGet, storageSet } = await import('../shared/storage');691        const { createNativeSyncTransport, runBlobSyncSession } = await import('./sync-coordinator');692693        const discovered = lifecycle.getDiscoveredPeerCache();694        const reachable = paired.filter((device) =>695          discovered.some((peer) => peer.x25519PublicKey === device.x25519PublicKey),696        );697        if (reachable.length === 0) return { ok: false, error: "no_devices_reachable" };698699        // Sequential — each session may update peach_vault_a, and the next700        // peer should receive the freshest blob (which may already include701        // changes from the previous device in this same pass).702        const results: Array<{703          deviceName: string;704          status: "completed" | "errored" | "closed";705          error?: string;706        }> = [];707        for (const device of reachable) {708          const peer = discovered.find((p) => p.x25519PublicKey === device.x25519PublicKey)!;709          try {710            const connectionId = await sync.connectToPeer(peer.host, peer.port, peer.x25519PublicKey);711            const transport = await createNativeSyncTransport(connectionId);712            const result = await runBlobSyncSession("initiator", transport, {713              isPro: async () => true,714              isUnlocked: () => vault.isUnlocked(),715              getVaultBlobs: async () => ({716                vault_a: (await storageGet("peach_vault_a")) ?? "",717                vault_b: (await storageGet("peach_vault_b")) ?? "",718              }),719            });720            results.push({721              deviceName: device.displayName,722              status: result.status,723              error: result.error,724            });725            if (result.status === "completed") {726              await updatePairedDevice(device.deviceId, {727                lastSeenAt: Date.now(),728                lastSyncAt: Date.now(),729              });730            }731          } catch (err) {732            results.push({733              deviceName: device.displayName,734              status: "errored",735              error: err instanceof Error ? err.message : String(err),736            });737          }738        }739740        await storageSet("peach_last_sync_at", String(Date.now()));741        return {742          ok: true,743          data: {744            results,745            syncedCount: results.filter((r) => r.status === "completed").length,746            totalReachable: reachable.length,747          },748        };749      }750      case "START_PAIRING": {751        const gate = await requirePro("sync");752        if (!gate.allowed) return { ok: false, error: "pro_required" };753        return { ok: true };754      }755      case "CANCEL_PAIRING": {756        return { ok: true };757      }758      case "ACCEPT_PAIRING": {759        const gate = await requirePro("sync");760        if (!gate.allowed) return { ok: false, error: "pro_required" };761        return { ok: true };762      }763      case "REMOVE_PAIRED_DEVICE": {764        const { deviceId } = msg.payload as { deviceId: string };765        const { removePairedDevice } = await import('./sync-storage');766        await removePairedDevice(deviceId);767        return { ok: true };768      }769      case "REMOVE_TRUSTED_NETWORK": {770        const { ssid, bssid, isTailscale } = msg.payload as any;771        const { removeTrustedNetwork, getTrustedNetworks } = await import('./sync-storage');772        const networks = await getTrustedNetworks();773        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 774          (isTailscale ? n.isTailscale : n.ssid === ssid) && 775          (!bssid || n.bssid === bssid)776        );777        if (network) {778          await removeTrustedNetwork(network.addedAt);779        }780        return { ok: true };781      }782      case "MARK_NETWORK_TRUSTED": {783        const { addTrustedNetwork } = await import('./sync-storage');784        const { getCurrentNetwork } = await import('./sync-network');785        const network = await getCurrentNetwork();786        await addTrustedNetwork({787          ssid: network.ssid,788          bssid: network.bssid,789          isTailscale: network.isTailscale,790          addedAt: Date.now(),791        });792        return { ok: true };793      }794      case "GET_INCOMING_PAIRING_REQUEST": {795        const { getIncomingPairingRequest } = await import('./sync-storage');796        const request = await getIncomingPairingRequest();797        return { ok: true, data: request };798      }799      case "RESPOND_INCOMING_PAIRING": {800        const { accept } = msg.payload as { accept: boolean };801        const { getIncomingPairingRequest, clearIncomingPairingRequest, addPairedDevice } =802          await import('./sync-storage');803        const request = await getIncomingPairingRequest();804        if (!request) return { ok: false, error: "no_pending_request" };805        if (Date.now() > request.expiresAt) {806          await clearIncomingPairingRequest();807          return { ok: false, error: "expired" };808        }809810        const sync = await import('./sync');811        const { encodeSyncMessage } = await import('../shared/sync-wire');812813        // Always clear the pending request — UI must not show the banner twice814        // even if the wire-level send below fails.815        await clearIncomingPairingRequest();816817        if (request.connectionId) {818          try {819            if (accept) {820              const ourKey = await sync.getIdentityPublicKey();821              const ourName = await getLocalDeviceName();822              sync.sendSyncData(823                request.connectionId,824                encodeSyncMessage({825                  type: "PAIR_ACCEPT",826                  public_key_hex: ourKey,827                  device_name: ourName,828                }),829              );830              await sync.trustDevice(request.publicKeyHex, request.deviceName);831              await addPairedDevice({832                deviceId: request.publicKeyHex,833                displayName: request.deviceName,834                x25519PublicKey: request.publicKeyHex,835                pairedAt: Date.now(),836                lastSeenAt: Date.now(),837              });838            } else {839              sync.sendSyncData(840                request.connectionId,841                encodeSyncMessage({ type: "PAIR_REJECT", reason: "user_declined" }),842              );843            }844          } catch (err) {845            // Wire failure is non-fatal for the local trust update — the846            // initiator will time out cleanly on its end.847            void err;848          }849          try { sync.disconnectFromPeer(request.connectionId); } catch { /* best-effort */ }850        } else if (accept) {851          // Test-injected request without a real connection: still record local trust.852          try {853            await sync.trustDevice(request.publicKeyHex, request.deviceName);854          } catch {855            // Native host may not be installed in test contexts.856          }857        }858859        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };860      }861      case "START_PEER_DISCOVERY": {862        const gate = await requirePro("sync");863        if (!gate.allowed) return { ok: false, error: "pro_required" };864        try {865          await startPeerDiscoveryForPopup();866          return { ok: true };867        } catch (err) {868          return { ok: false, error: err instanceof Error ? err.message : "discovery_failed" };869        }870      }871      case "STOP_PEER_DISCOVERY": {872        try {873          await stopPeerDiscoveryForPopup();874        } catch {875          // best-effort cleanup876        }877        return { ok: true };878      }879      case "START_PAIRING_SERVER": {880        const gate = await requirePro("sync");881        if (!gate.allowed) return { ok: false, error: "pro_required" };882        try {883          const sync = await import('./sync');884          const { setActivePairingToken } = await import('./pairing-server-state');885          const { getOrCreateLocalDeviceId } = await import('./sync-identity-glue');886          sync.connectSyncHost();887          const token = generateSixDigitToken();888          const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;889          const deviceId = await getOrCreateLocalDeviceId();890          const name = await getLocalDeviceName();891          await sync.startPairingServer({ token, deviceId, name });892          await setActivePairingToken({ token, expiresAt });893          return { ok: true, data: { token, expiresAt } };894        } catch (err) {895          return { ok: false, error: err instanceof Error ? err.message : "pairing_server_failed" };896        }897      }898      case "STOP_PAIRING_SERVER": {899        try {900          const sync = await import('./sync');901          const { setActivePairingToken } = await import('./pairing-server-state');902          await setActivePairingToken(null);903          if (sync.isHostConnected()) {904            await sync.stopPairingServer();905          }906        } catch {907          // best-effort cleanup908        }909        return { ok: true };910      }911      case "CONNECT_WITH_CODE": {912        const gate = await requirePro("sync");913        if (!gate.allowed) return { ok: false, error: "pro_required" };914        const { token: rawToken } = msg.payload as { token: string };915        const token = String(rawToken).replace(/\D/g, "");916        if (token.length !== 6) return { ok: false, error: "invalid_code" };917918        const sync = await import('./sync');919        const { encodeSyncMessage } = await import('../shared/sync-wire');920        const { waitForPairingResponse } = await import('./sync-coordinator');921        const { addPairedDevice } = await import('./sync-storage');922        const { setRecentPairing } = await import('./pairing-server-state');923924        sync.connectSyncHost();925        let connectionId: string | undefined;926        try {927          const peer = await sync.resolvePeerByCode(token, 8_000);928          connectionId = await sync.connectToPeer(peer.host, peer.port, peer.x25519PublicKey);929930          const ourPublicKeyHex = await sync.getIdentityPublicKey();931          const deviceName = await getLocalDeviceName();932933          sync.sendSyncData(934            connectionId,935            encodeSyncMessage({936              type: "PAIR_REQUEST",937              public_key_hex: ourPublicKeyHex,938              device_name: deviceName,939            }),940          );941942          const response = await waitForPairingResponse(connectionId, 30_000);943944          if (response.type === "PAIR_ACCEPT") {945            await sync.trustDevice(response.public_key_hex, response.device_name);946            await addPairedDevice({947              deviceId: peer.deviceId,948              displayName: response.device_name || peer.name,949              x25519PublicKey: response.public_key_hex,950              pairedAt: Date.now(),951              lastSeenAt: Date.now(),952            });953            sync.disconnectFromPeer(connectionId);954            // Stash for the popup so a popup-close mid-handshake still surfaces955            // a confirmation on next open.956            await setRecentPairing({957              deviceName: response.device_name || peer.name,958              pairedAt: Date.now(),959              side: "entering",960            });961            return { ok: true, data: { deviceName: response.device_name || peer.name } };962          }963964          if (response.type === "PAIR_REJECT") {965            sync.disconnectFromPeer(connectionId);966            return { ok: false, error: "pair_rejected", data: { reason: response.reason } };967          }968969          sync.disconnectFromPeer(connectionId);970          return { ok: false, error: "unexpected_response" };971        } catch (err) {972          if (connectionId) {973            try { sync.disconnectFromPeer(connectionId); } catch { /* best-effort */ }974          }975          return { ok: false, error: err instanceof Error ? err.message : "connect_failed" };976        }977      }978      case "GET_RECENT_PAIRING": {979        const { consumeRecentPairing } = await import('./pairing-server-state');980        const recent = await consumeRecentPairing();981        return { ok: true, data: recent };982      }983      case "INITIATE_PAIR_WITH_PEER": {984        const gate = await requirePro("sync");985        if (!gate.allowed) return { ok: false, error: "pro_required" };986        const { peer } = msg.payload as {987          peer: { deviceId: string; deviceName: string; host: string; port: number; x25519PublicKey: string };988        };989990        const sync = await import('./sync');991        const { encodeSyncMessage } = await import('../shared/sync-wire');992        const { waitForPairingResponse } = await import('./sync-coordinator');993        const { addPairedDevice } = await import('./sync-storage');994995        let connectionId: string | undefined;996        try {997          // The responder accepts this connection only because pairing mode is998          // active on its side — Noise NK still authenticates the *transport*,999          // and the responder verifies our auth proof, but our public key is1000          // not yet in their trust store. The PAIR_ACCEPT we receive is the1001          // user's confirmation on the peer device that we should be added.1002          connectionId = await sync.connectToPeer(peer.host, peer.port, peer.x25519PublicKey);10031004          const ourPublicKeyHex = await sync.getIdentityPublicKey();1005          const deviceName = await getLocalDeviceName();10061007          sync.sendSyncData(1008            connectionId,1009            encodeSyncMessage({1010              type: "PAIR_REQUEST",1011              public_key_hex: ourPublicKeyHex,1012              device_name: deviceName,1013            }),1014          );10151016          const response = await waitForPairingResponse(connectionId, 30_000);10171018          if (response.type === "PAIR_ACCEPT") {1019            await sync.trustDevice(response.public_key_hex, response.device_name);1020            await addPairedDevice({1021              deviceId: peer.deviceId,1022              displayName: response.device_name || peer.deviceName,1023              x25519PublicKey: response.public_key_hex,1024              pairedAt: Date.now(),1025              lastSeenAt: Date.now(),1026            });1027            sync.disconnectFromPeer(connectionId);1028            return { ok: true, data: { connectionId, deviceName: response.device_name } };1029          }10301031          if (response.type === "PAIR_REJECT") {1032            sync.disconnectFromPeer(connectionId);1033            return { ok: false, error: "pair_rejected", data: { reason: response.reason } };1034          }10351036          sync.disconnectFromPeer(connectionId);1037          return { ok: false, error: "unexpected_response" };1038        } catch (err) {1039          if (connectionId) {1040            try { sync.disconnectFromPeer(connectionId); } catch { /* best-effort */ }1041          }1042          return { ok: false, error: err instanceof Error ? err.message : "pair_failed" };1043        }1044      }1045      case "DEBUG_INJECT_INCOMING_PAIRING": {1046        // Manual E2E rehearsal hook. Inserts a synthetic incoming pairing1047        // request into session storage so Phase 7 banner UX can be exercised1048        // without a live native host. No Pro gate — this is a no-op in1049        // production unless explicitly invoked from a Settings debug action.1050        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {1051          deviceName?: string;1052          publicKeyHex?: string;1053        };1054        if (!deviceName || !publicKeyHex) {1055          return { ok: false, error: "missing_payload" };1056        }1057        const { setIncomingPairingRequest } = await import('./sync-storage');1058        const now = Date.now();1059        await setIncomingPairingRequest({1060          deviceName,1061          publicKeyHex,1062          receivedAt: now,1063          expiresAt: now + 60_000,1064        });1065        return { ok: true };1066      }1067      case "RESET_SYNC_IDENTITY": {1068        const gate = await requirePro("sync");1069        if (!gate.allowed) return { ok: false, error: "pro_required" };1070        const { getPairedDevices, removePairedDevice } = await import('./sync-storage');1071        const devices = await getPairedDevices();1072        for (const device of devices) {1073          await removePairedDevice(device.deviceId);1074        }1075        // Native rotation is best-effort: when the native messaging host is1076        // not yet installed (Phase 9), connectNative throws and we still1077        // honour the local clear so the UI reflects the reset. The native1078        // identity rotates the next time the host starts cleanly anyway.1079        let nativePublicKey: string | null = null;1080        try {1081          const { rotateNativeIdentity, disconnectSyncHost } = await import('./sync');1082          nativePublicKey = await rotateNativeIdentity();1083          disconnectSyncHost();1084        } catch {1085          nativePublicKey = null;1086        }1087        return { ok: true, data: { removedDevices: devices.length, nativePublicKey } };1088      }1089      case "RECORD_MANUAL_SUMMON": {1090        const { domain } = msg.payload as { domain: string };1091        const settings = vault.getSettings();1092        const existing = settings.manualSummonDomains?.[domain];1093        const now = Date.now();1094        await vault.updateSettings({1095          manualSummonDomains: {1096            ...settings.manualSummonDomains,1097            [domain]: {1098              firstSummonedAt: existing?.firstSummonedAt ?? now,1099              summonCount: (existing?.summonCount ?? 0) + 1,1100              lastSummonedAt: now,1101            },1102          },1103        });1104        return { ok: true };1105      }1106      case "DECLINE_CARD_SAVE": {1107        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1108        await vault.declineCardSaveOffer(last4, expMonth, expYear);1109        return { ok: true };1110      }1111      case "IS_CARD_DECLINED": {1112        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1113        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1114        return { ok: true, data: declined };1115      }1116      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1117        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1118          rpId?: string;1119          rpName?: string;1120          userName?: string;1121          userDisplayName?: string;1122        };1123        if (!rpId || !userName) return { ok: false, error: "rpId and userName required" };1124        return await initiateFirefoxPasskeyCreate({1125          rpId,1126          rpName: rpName ?? rpId,1127          userName,1128          userDisplayName,1129        });1130      }11311132      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1133        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1134        if (!payload) return { ok: false, error: "missing payload" };1135        return await completeFirefoxPasskeyCreate(payload);1136      }11371138      case "PASSKEY_OFFER_DECLINE": {1139        const { domain } = (msg.payload ?? {}) as { domain?: string };1140        if (!domain) return { ok: false, error: "domain required" };1141        await recordPasskeyOfferDecline(domain);1142        return { ok: true };1143      }11441145      case "GET_PASSKEY_OFFER_DECLINED": {1146        const { domain } = (msg.payload ?? {}) as { domain?: string };1147        if (!domain) return { ok: false, error: "domain required" };1148        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1149      }11501151      case "PASSKEY_HAS_CREDENTIALS": {1152        const payload = msg.payload as {1153          rpId?: string;1154          allowCredentials?: Array<{ id: string; type?: string }>;1155        } | undefined;1156        if (!payload?.rpId) return { ok: false, error: "rpId required" };1157        return await handlePasskeyHasCredentials({1158          rpId: payload.rpId,1159          allowCredentials: payload.allowCredentials ?? [],1160        });1161      }11621163      case "PASSKEY_CREATE": {1164        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1165        if (!payload?.rpId || !payload?.userName) {1166          return { ok: false, error: "rpId and userName required" };1167        }1168        return await handleFirefoxPasskeyCreate(payload);1169      }11701171      case "PASSKEY_GET": {1172        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1173        if (!payload?.rpId) return { ok: false, error: "rpId required" };1174        return await handleFirefoxPasskeyGet(payload);1175      }11761177      case "GET_PASSKEY_FOR_DOMAIN": {1178        const { domain } = (msg.payload ?? {}) as { domain?: string };1179        if (!domain) return { ok: false, error: "domain required" };1180        if (!vault.isUnlocked()) return { ok: true, data: null };1181        const match = vault1182          .getEntries()1183          .find((entry) => entry.passkey?.rpId === domain);1184        if (!match || !match.passkey) return { ok: true, data: null };1185        // Slim shape — only the fields State 11 needs. Never expose private1186        // key material, even though this is locked behind isUnlocked.1187        return {1188          ok: true,1189          data: {1190            rpId: match.passkey.rpId,1191            userName: match.passkey.userName,1192            browser: match.passkey.browser,1193          },1194        };1195      }11961197      case "DESTROY_VAULT": {1198        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1199        // storage.local.clear() wipes every Peach key (slots, settings, license,1200        // onboarded flag, history, sync state, declined cards, recall, etc.);1201        // session.clear() wipes pending passkey requests + pro-notice queues.1202        // Caller (Panic.tsx) handles UI navigation back to onboarding.1203        vault.lock();1204        await storageClear();1205        // Belt-and-suspenders: storage.local.clear() already wipes1206        // peach_vault_history, but if storage.ts ever routes history to a1207        // different backend (e.g. Capacitor secure storage on Android) the1208        // explicit clear keeps the invariant that Panic leaves no recoverable1209        // vault state behind.1210        await vault.clearVaultHistory();1211        if (!Capacitor.isNativePlatform() && chrome.storage.session) {1212          await chrome.storage.session.clear();1213        }1214        return { ok: true };1215      }12161217      case "SUBMIT_FEEDBACK": {1218        const { category, message, version, browser } = msg.payload as {1219          category: string;1220          message: string;1221          version: string;1222          browser: string;1223        };1224        if (!message.trim()) return { ok: false, error: "message is empty" };1225        if (!FEEDBACK_ENDPOINT) return { ok: true };1226        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1227          return { ok: false, error: "invalid feedback endpoint" };1228        }1229        try {1230          const res = await fetch(FEEDBACK_ENDPOINT, {1231            method: "POST",1232            headers: { "Content-Type": "application/json" },1233            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1234          });1235          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1236        } catch (err) {1237          return { ok: false, error: err instanceof Error ? err.message : "network error" };1238        }1239      }1240      default:1241        return { ok: false, error: "unknown message type" };1242    }1243  } catch (err) {1244    return {1245      ok: false,1246      error: err instanceof Error ? err.message : "operation failed",1247    };1248  }1249}12501251/** Notify all content scripts that the vault just became available. */1252function broadcastToContentScripts(message: { type: string }): void {1253  if (Capacitor.isNativePlatform() || !chrome.tabs?.query) return;1254  chrome.tabs.query({}, (tabs) => {1255    for (const tab of tabs) {1256      if (tab.id !== undefined) {1257        chrome.tabs.sendMessage(tab.id, message).catch(() => {1258          // Tab may not have a content script — silently ignore1259        });1260      }1261    }1262  });1263}12641265function shouldRefreshAutoLock(type: MessageType): boolean {1266  return (1267    type !== "HAS_VAULT" &&1268    type !== "IS_UNLOCKED" &&1269    type !== "GET_VAULT_STATUS" &&1270    type !== "LOCK" &&1271    type !== "UPDATE_SETTINGS" &&1272    type !== "GET_PENDING_PASSKEY" &&1273    type !== "GET_PASSKEY_PROVIDER_STATE" &&1274    type !== "DECLINE_CARD_SAVE" &&1275    type !== "IS_CARD_DECLINED" &&1276    type !== "SUBMIT_FEEDBACK"1277  );1278}12791280function isAllowedCanaryWebhookUrl(value: string): boolean {1281  try {1282    const url = new URL(value);1283    if (url.protocol !== "https:") return false;12841285    const hostname = url.hostname.toLowerCase();1286    if (1287      hostname === "localhost" ||1288      hostname.endsWith(".localhost") ||1289      isPrivateIpv4(hostname) ||1290      isPrivateIpv6(hostname)1291    ) {1292      return false;1293    }12941295    return true;1296  } catch {1297    return false;1298  }1299}13001301function isPrivateIpv4(hostname: string): boolean {1302  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1303    return true;1304  }13051306  const octets = hostname.split(".").map((part) => Number(part));1307  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1308    return false;1309  }13101311  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1312}13131314function isPrivateIpv6(hostname: string): boolean {1315  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1316  return (1317    normalized === "::1" ||1318    normalized.startsWith("fc") ||1319    normalized.startsWith("fd") ||1320    normalized.startsWith("fe80:")1321  );1322}