messages.ts

44.5 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard } from "./clipboard";13import { setupAutoLock, touchAutoLock } from "./alarms";14import * as vault from "./vault";15import {16  activateLicense,17  deactivateLicense,18  getLicenseInfo,19  getLicenseKey,20  isProUser,21  markCelebrationPlayed,22  shouldPlayCelebration,23} from "./license";24import {25  cancelFirefoxPasskeyCreate,26  completeFirefoxPasskeyCreate,27  getPasskeyProviderState,28  getPendingPasskeyRequest,29  handleFirefoxPasskeyCreate,30  handleFirefoxPasskeyGet,31  handlePasskeyHasCredentials,32  initiateFirefoxPasskeyCreate,33  isPasskeyOfferDeclined,34  recordPasskeyOfferDecline,35  resolvePendingPasskeyRequest,36  setPasskeyProviderEnabled,37} from "./passkey";38import { buildAdvancedHealthReport, resolveResetUrl } from "./health";39import { storageClear } from "../shared/storage";40import type {41  Message,42  MessageResponse,43  MessageType,44  ProFeature,45  VaultEntry,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    chrome.runtime65      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })66      .catch(() => {67        // Popup may be closed — the gate signal is best-effort.68      });69  } else {70    // Background trigger (e.g. passive sync initiation) — no popup is open.71    // Queue a notice so the next popup open shows a soft banner instead of72    // silently failing.73    if (chrome.storage.session) {74      chrome.storage.session75        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })76        .catch(() => {});77    }78  }7980  return { allowed: false };81}8283// ---------------------------------------------------------------------------84// Local device name. Peers see this string in PAIR_REQUEST / PAIR_ACCEPT and85// next to the device in their paired-devices list. Default to a platform-aware86// fallback when the user hasn't set one explicitly.87const DEVICE_NAME_KEY = "peach_device_name";8889async function getLocalDeviceName(): Promise<string> {90  try {91    const stored = await chrome.storage.local.get(DEVICE_NAME_KEY);92    const value = (stored as Record<string, string | undefined>)[DEVICE_NAME_KEY];93    if (typeof value === "string" && value.trim()) return value.trim();94  } catch {95    // fall through to default96  }97  return "Peach";98}99100// ---------------------------------------------------------------------------101// 6-digit code pairing.102103const PAIRING_TOKEN_TTL_MS = 5 * 60 * 1000;104105106function generateSixDigitToken(): string {107  // crypto.getRandomValues, not Math.random — the token is the only secret108  // protecting the pairing window from a same-LAN attacker. 6 decimal digits109  // is 1 in 1,000,000; combined with a 5-minute TTL and pairing-mode gating110  // on the responder this is the right tradeoff between UX and security.111  const buf = new Uint32Array(1);112  crypto.getRandomValues(buf);113  const value = buf[0] % 1_000_000;114  return value.toString().padStart(6, "0");115}116117// ---------------------------------------------------------------------------118// Peer discovery glue (Phase 7 popup pairing flow).119120const PRIVATE_IPV4_RANGES = [121  { prefix: "10." },122  { prefix: "127." },123  { prefix: "169.254." },124  { prefix: "192.168." },125];126127// Empty disables network submission while the UI continues to function as a128// no-op (the handler returns ok:true without calling fetch). When set, the129// URL is validated by `isAllowedCanaryWebhookUrl` before any request, so the130// same private-IP/HTTPS rules that gate canary webhooks apply here.131const FEEDBACK_ENDPOINT = "";132133export function setupMessageHandler(): void {134  chrome.runtime.onMessage.addListener(135    (msg: unknown, sender, sendResponse) => {136      if (!isMessage(msg)) {137        sendResponse({ ok: false, error: "invalid message" });138        return true;139      }140      handleMessage(msg, sender)141        .then(sendResponse)142        .catch((err) =>143          sendResponse({144            ok: false,145            error: err instanceof Error ? err.message : String(err),146          })147        );148      return true;149    }150  );151}152153function isMessage(m: unknown): m is Message {154  return typeof m === "object" && m !== null && "type" in m;155}156157export async function handleMessage(158  msg: Message,159  sender: Partial<chrome.runtime.MessageSender> = {}160): Promise<MessageResponse> {161  try {162    // Validate sender — only allow messages from our extension pages/scripts.163    // `sender.id` is undefined for messages originating from extension UI164    // (popup/options), which is legitimate; reject only when it is defined165    // and does not match our extension id.166    if (167      sender.id !== undefined &&168      sender.id !== chrome.runtime.id169    ) {170      return { ok: false, error: "invalid sender" };171    }172173    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {174      touchAutoLock();175    }176177    switch (msg.type) {178      case "CREATE_VAULT": {179        const { password } = msg.payload as { password: string };180        await vault.createVault(password);181        await setupAutoLock();182        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });183        return { ok: true };184      }185      case "UNLOCK": {186        const { password } = msg.payload as { password: string };187        const ok = await vault.unlock(password);188        if (ok) {189          await setupAutoLock();190          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });191        }192        return { ok };193      }194      case "VALIDATE_RECOVERY_WORDS": {195        const { words } = msg.payload as { words: string[] };196        const { findInvalidWords } = await import("../shared/recovery-words");197        const invalid = findInvalidWords(words);198        return { ok: true, data: { valid: invalid.length === 0, invalid } };199      }200      case "GET_RECOVERY_WORDS": {201        // Must be unlocked and have recovery set up (vault must be v2.12+).202        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };203        try {204          const words = await vault.getRecoveryWords();205          return { ok: true, data: words };206        } catch (e) {207          // pre-v2.12 vault that hasn't migrated208          return { ok: false, error: "recovery_not_setup" };209        }210      }211      case "RECOVER_WITH_WORDS": {212        // User has lost their password but has their 12 recovery words.213        // We: (1) validate the words, (2) re-encrypt vault with new password.214        const { words, newPassword } = msg.payload as {215          words: string[];216          newPassword: string;217        };218        const stored = await vault.loadSlotA();219        if (!stored) return { ok: false, error: "no vault" };220        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {221          return { ok: false, error: "recovery_not_setup" };222        }223        // Unwrap the root key from the recovery escrow.224        try {225          await vault.unwrapRootKeyForRecovery(226            stored.recovery_wrapped_root_key,227            stored.recovery_nonce ?? "",228            stored.recovery_tag ?? "",229            stored.recovery_salt,230            words231          );232        } catch {233          return { ok: false, error: "invalid_recovery_words" };234        }235        // Re-key: derive fresh salt + key from new password.236        const newSalt = vault.generateSalt();237        const newKey = await vault.deriveKey(newPassword, newSalt);238        // Re-wrap root key under the new password's derived key so the same239        // recovery words continue to work after the password change.240        await vault.rewrapRootKeyForPassword(newKey, newSalt);241        // Re-encrypt vault entries with the new key.242        await vault.changePasswordWithNewKey(newSalt, newKey);243        await setupAutoLock();244        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });245        return { ok: true };246      }247      case "LOCK":248        vault.lock();249        return { ok: true };250      case "IS_UNLOCKED":251        return { ok: true, data: vault.isUnlocked() };252      case "GET_VAULT_STATUS":253        return { ok: true, unlocked: vault.isUnlocked() };254      case "HAS_VAULT":255        return { ok: true, data: await vault.hasVault() };256      case "GET_ENTRIES":257        return { ok: true, data: vault.getEntries() };258      case "ADD_ENTRY": {259        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };260        const entry = await vault.addEntry(msg.payload as any);261        return { ok: true, data: entry };262      }263      case "BATCH_ADD_ENTRIES": {264        const { entries } = msg.payload as { entries: any[] };265        const added = await vault.batchAddEntries(entries);266        return { ok: true, data: added };267      }268      case "RESTORE_ENTRIES": {269        const { entries, mode, settings } = msg.payload as {270          entries: any[];271          mode: "replace" | "merge";272          settings?: vault.VaultSettings;273        };274        const summary = await vault.restoreEntries(entries, mode);275        if (settings && typeof settings === "object") {276          await vault.updateSettings(settings);277        }278        return { ok: true, data: summary };279      }280      case "CLEAR_VAULT_ENTRIES": {281        await vault.clearVaultEntries("REPLACE_ALL");282        return { ok: true };283      }284      case "GET_VAULT_HISTORY": {285        const snapshots = await vault.getVaultHistory();286        return { ok: true, data: snapshots };287      }288      case "RESTORE_VAULT_SNAPSHOT": {289        const { snapshotId } = msg.payload as { snapshotId: string };290        const result = await vault.restoreVaultSnapshot(snapshotId);291        if (!result.ok) return { ok: false, error: result.error };292        broadcastToContentScripts({ type: "VAULT_LOCKED" });293        return { ok: true };294      }295      case "COUNT_DUPLICATES": {296        return { ok: true, data: vault.countDuplicates() };297      }298      case "DEDUPLICATE_ENTRIES": {299        const removed = await vault.deduplicateEntries();300        return { ok: true, data: removed };301      }302      case "UPDATE_ENTRY": {303        const { id, patch } = msg.payload as any;304        await vault.updateEntry(id, patch);305        return { ok: true };306      }307      case "ADD_ADDITIONAL_URL": {308        const { id, url } = msg.payload as { id: string; url: string };309        const trimmed = typeof url === "string" ? url.trim() : "";310        if (!trimmed) return { ok: false, error: "url required" };311        const existing = vault.getEntryById(id);312        if (!existing) return { ok: false, error: "entry not found" };313        if (existing.type !== "login") return { ok: false, error: "login entries only" };314        const merged = [...(existing.additionalUrls ?? []), trimmed];315        await vault.updateEntry(id, { additionalUrls: merged });316        return { ok: true };317      }318      case "DELETE_ENTRY": {319        const { id } = msg.payload as { id: string };320        await vault.deleteEntry(id);321        return { ok: true };322      }323      case "GET_DELETED_ENTRIES":324        return { ok: true, data: vault.getDeletedEntries() };325      case "RESTORE_ENTRY": {326        const { id } = msg.payload as { id: string };327        await vault.restoreEntry(id);328        return { ok: true };329      }330      case "PURGE_ENTRY": {331        const { id } = msg.payload as { id: string };332        await vault.purgeEntry(id);333        return { ok: true };334      }335      case "PURGE_EXPIRED_TRASH": {336        const { retentionMs } = msg.payload as { retentionMs: number };337        const purged = await vault.purgeExpiredTrash(retentionMs);338        return { ok: true, data: purged };339      }340      case "AUTOFILL_QUERY": {341        if (!vault.isUnlocked()) {342          return { ok: false, error: "VAULT_LOCKED" };343        }344        const { domain, includeAll, kind } = msg.payload as {345          domain: string;346          includeAll?: boolean;347          kind?: "login" | "card";348        };349        // kind="card": return saved cards as compact summaries for the350        // inline card silver platter. Cards are not domain-scoped — every351        // saved card is a candidate on every checkout page — so domain is352        // ignored when kind === "card".353        if (kind === "card") {354          const cards = vault.getEntries().filter((e) => e.type === "card");355          return {356            ok: true,357            data: cards.map((e) => ({358              id: e.id,359              title: e.cardNickname || e.title,360              cardholderName: e.cardholderName,361              last4: e.last4,362              expMonth: e.expMonth,363              expYear: e.expYear,364              network: e.network,365            })),366          };367        }368        // The inline selector fills username+password into a form. Passkey-369        // only entries have no password to fill; sign-in for those goes370        // through the WebAuthn path instead. Filter them out everywhere so371        // the user doesn't see four "GitHub" rows that mostly do nothing.372        // Notes and cards never belonged here either.373        const matches = (374          includeAll375            ? vault376                .getEntries()377                .filter((entry) => entry.type !== "note" && entry.type !== "card")378            : vault.queryDomain(domain)379        ).filter((entry) => !isPasskeyOnly(entry));380        return {381          ok: true,382          data: matches.map((e) =>383            includeAll384              ? {385                  id: e.id,386                  title: e.title,387                  hasPasskey: e.passkey !== undefined,388                }389              : {390                  id: e.id,391                  title: e.title,392                  username: e.username,393                  email: e.email,394                  url: e.url,395                  hasTotp: Boolean(e.totp),396                  hasPasskey: e.passkey !== undefined,397                }398          ),399        };400      }401      case "GET_ENTRY_FOR_FILL": {402        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };403        const { id } = msg.payload as { id: string };404        const entry = vault.getEntryById(id);405        if (!entry) return { ok: false, error: "entry not found" };406        // Passkey-only entries (passkey credential, no password) cannot be407        // filled into a form — sign-in goes through the WebAuthn path. A408        // login that ALSO has a passkey is still fillable for its password.409        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey not fillable" };410        // Strip the passkey credential from the response — content scripts411        // never need the private key, and there's no reason to expose the412        // public credential metadata over the boundary either.413        const { passkey: _strippedPasskey, ...safeEntry } = entry;414        return { ok: true, data: safeEntry };415      }416      case "COPY": {417        const { text, label, alreadyWritten } = msg.payload as {418          text: string;419          label: string;420          alreadyWritten?: boolean;421        };422        await copyToClipboard(text, label, Boolean(alreadyWritten));423        return { ok: true };424      }425      case "CHECK_BREACH": {426        const { password } = msg.payload as { password: string };427        const count = await vault.checkBreach(password);428        return { ok: true, data: count };429      }430      case "CHECK_ALL_BREACHES": {431        const allEntries = vault.getEntries();432        const results: Record<string, number> = {};433        for (const entry of allEntries) {434          if (entry.type === "note") continue;435          if (!entry.password) continue;436          results[entry.id] = await vault.checkBreach(entry.password);437          // Small delay — be a good citizen to the HIBP API438          await new Promise((r) => setTimeout(r, 200));439        }440        // Persist any non-zero counts back to entries441        for (const [id, count] of Object.entries(results)) {442          const entry = vault.getEntryById(id);443          if (entry && (entry.breach ?? 0) !== count) {444            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });445          }446        }447        return { ok: true, data: results };448      }449      case "GET_SETTINGS":450        return { ok: true, data: await vault.ensureSettingsLoaded() };451      case "UPDATE_SETTINGS": {452        const patch = msg.payload as Record<string, unknown>;453        await vault.updateSettings(patch as any);454        if (typeof patch.autoLockMinutes === "number") {455          await setupAutoLock();456          if (vault.isUnlocked()) touchAutoLock();457        }458        return { ok: true };459      }460      case "GET_PENDING_PASSKEY":461        return { ok: true, data: await getPendingPasskeyRequest() };462      case "APPROVE_PASSKEY": {463        const { requestId } = msg.payload as { requestId: number };464        await resolvePendingPasskeyRequest(requestId, true);465        return { ok: true };466      }467      case "DENY_PASSKEY": {468        const { requestId } = msg.payload as { requestId: number };469        await resolvePendingPasskeyRequest(requestId, false);470        return { ok: true };471      }472      case "GET_PASSKEYS":473        return {474          ok: true,475          data: vault.getEntries().filter((entry) => entry.passkey !== undefined),476        };477      case "DELETE_PASSKEY": {478        const { id } = msg.payload as { id: string };479        await vault.deleteEntry(id);480        return { ok: true };481      }482      case "GET_PASSKEY_PROVIDER_STATE":483        return { ok: true, data: await getPasskeyProviderState() };484      case "SET_PASSKEY_PROVIDER_ENABLED": {485        const { enabled } = msg.payload as { enabled: boolean };486        // Disabling is always free; gating fires only when a free user is487        // trying to turn passkey interception on.488        if (enabled) {489          const gate = await requirePro("passkeys");490          if (!gate.allowed) return { ok: false, error: "pro_required" };491        }492        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };493      }494      case "FIRE_CANARY_PING": {495        const { webhookUrl, entryTitle, trigger } = msg.payload as {496          webhookUrl: string;497          entryTitle: string;498          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";499        };500        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {501          return { ok: false, error: "invalid webhook url" };502        }503        const body = JSON.stringify({504          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",505          entry: entryTitle,506          trigger,507          timestamp: new Date().toISOString(),508          source: "peach-extension",509        });510        if (trigger === "test") {511          // Permitted outbound fetch: user-configured canary alert endpoint512          // (validated by isAllowedCanaryWebhookUrl above). This is the513          // only non-HIBP outbound call in the extension — see514          // Projects.md §3.7. Test pings are awaited so the UI can show515          // success/failure.516          try {517            const res = await fetch(webhookUrl, {518              method: "POST",519              headers: { "Content-Type": "application/json" },520              body,521            });522            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };523          } catch (err) {524            return { ok: false, error: err instanceof Error ? err.message : "network error" };525          }526        }527        // Non-test triggers are fire-and-forget528        fetch(webhookUrl, {529          method: "POST",530          headers: { "Content-Type": "application/json" },531          body,532        }).catch(() => {});533        return { ok: true };534      }535      case "ACTIVATE_LICENSE": {536        const { key } = msg.payload as { key: string };537        const licenseInfo = await activateLicense(key);538        return { ok: true, data: licenseInfo };539      }540      case "GET_LICENSE": {541        const licenseInfo = await getLicenseInfo();542        return { ok: true, data: licenseInfo };543      }544      case "GET_LICENSE_KEY": {545        const key = await getLicenseKey();546        return { ok: true, data: key };547      }548      case "DEACTIVATE_LICENSE": {549        await deactivateLicense();550        return { ok: true };551      }552      case "SHOULD_PLAY_CELEBRATION": {553        const should = await shouldPlayCelebration();554        return { ok: true, data: should };555      }556      case "MARK_CELEBRATION_PLAYED": {557        await markCelebrationPlayed();558        return { ok: true };559      }560      case "OPEN_PRO_GATE": {561        // Content script requests: open popup and navigate to License section.562        const { feature } = (msg.payload ?? {}) as { feature?: string };563        if (chrome.storage.session) {564          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });565        }566        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }567        return { ok: true };568      }569      case "GET_IDENTITIES": {570        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };571        return { ok: true, data: vault.getIdentities() };572      }573      case "GET_ADVANCED_HEALTH_REPORT": {574        const gate = await requirePro("advanced_health");575        if (!gate.allowed) return { ok: false, error: "pro_required" };576        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };577        const report = await buildAdvancedHealthReport(vault.getEntries());578        return { ok: true, data: report };579      }580      case "INITIATE_PASSWORD_CHANGE": {581        const gate = await requirePro("smart_password_change");582        if (!gate.allowed) return { ok: false, error: "pro_required" };583        if (!vault.isUnlocked()) return { ok: false, error: "vault locked" };584        const { id } = msg.payload as { id: string };585        const entry = vault.getEntryById(id);586        if (!entry) return { ok: false, error: "entry not found" };587        const url = resolveResetUrl(entry);588        if (!url) return { ok: false, error: "no reset url" };589        try {590          await chrome.tabs.create({ url });591          return { ok: true, data: { url } };592        } catch (err) {593          return {594            ok: false,595            error: err instanceof Error ? err.message : "failed to open tab",596          };597        }598      }599      case "IS_DURESS_ENABLED": {600        const enabled = await vault.isDuressEnabled();601        return { ok: true, data: enabled };602      }603      case "SETUP_DURESS": {604        const { duressPassword } = msg.payload as { duressPassword: string };605        await vault.setupDuress(duressPassword);606        return { ok: true };607      }608      case "DISABLE_DURESS": {609        await vault.disableDuress();610        return { ok: true };611      }612      case "VERIFY_MAIN_PASSWORD": {613        const { password } = msg.payload as { password: string };614        const ok = await vault.verifyMainPassword(password);615        return { ok: true, data: ok };616      }617      case "CHANGE_PASSWORD": {618        const { currentPassword, newPassword } = msg.payload as {619          currentPassword: string;620          newPassword: string;621        };622        const changed = await vault.changePassword(currentPassword, newPassword);623        return changed624          ? { ok: true }625          : { ok: false, error: "incorrect current password" };626      }627      case "GET_SITE_PASSWORD_POLICY": {628        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });629        if (!tab?.id) return { ok: true, data: null };630        try {631          const response = await chrome.tabs.sendMessage(tab.id, {632            type: "GET_SITE_PASSWORD_POLICY",633          });634          return (response as MessageResponse) ?? { ok: true, data: null };635        } catch {636          return { ok: true, data: null };637        }638      }639      case "GET_SYNC_STATE": {640        const { getPairedDevices, getTrustedNetworks } = await import('./sync-storage');641        const { isOnTailscale } = await import('./sync-network');642        const { isProUser } = await import('./license');643        const { storageGet } = await import('../shared/storage');644        const pairedDevices = await getPairedDevices();645        const trustedNetworks = await getTrustedNetworks();646        const tailscale = await isOnTailscale();647        const pro = await isProUser();648649        let status: SyncStatus = "offline";650        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {651          if (pairedDevices.length === 0) {652            status = "no_peers";653          } else {654            status = "synced";655          }656        } else {657          status = "not_trusted";658        }659660        const lastSyncRaw = await storageGet("peach_last_sync_at");661        const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN;662        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined;663664        return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } };665      }666      case "TRIGGER_SYNC": {667        const gate = await requirePro("sync");668        if (!gate.allowed) return { ok: false, error: "pro_required" };669        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };670        return { ok: false, error: "no_native_host" };671      }672      case "START_PAIRING": {673        const gate = await requirePro("sync");674        if (!gate.allowed) return { ok: false, error: "pro_required" };675        return { ok: true };676      }677      case "CANCEL_PAIRING": {678        return { ok: true };679      }680      case "ACCEPT_PAIRING": {681        const gate = await requirePro("sync");682        if (!gate.allowed) return { ok: false, error: "pro_required" };683        return { ok: true };684      }685      case "REMOVE_PAIRED_DEVICE": {686        const { deviceId } = msg.payload as { deviceId: string };687        const { removePairedDevice } = await import('./sync-storage');688        await removePairedDevice(deviceId);689        return { ok: true };690      }691      case "REMOVE_TRUSTED_NETWORK": {692        const { ssid, bssid, isTailscale } = msg.payload as any;693        const { removeTrustedNetwork, getTrustedNetworks } = await import('./sync-storage');694        const networks = await getTrustedNetworks();695        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 696          (isTailscale ? n.isTailscale : n.ssid === ssid) && 697          (!bssid || n.bssid === bssid)698        );699        if (network) {700          await removeTrustedNetwork(network.addedAt);701        }702        return { ok: true };703      }704      case "MARK_NETWORK_TRUSTED": {705        const { addTrustedNetwork } = await import('./sync-storage');706        const { getCurrentNetwork } = await import('./sync-network');707        const network = await getCurrentNetwork();708        await addTrustedNetwork({709          ssid: network.ssid,710          bssid: network.bssid,711          isTailscale: network.isTailscale,712          addedAt: Date.now(),713        });714        return { ok: true };715      }716      case "GET_INCOMING_PAIRING_REQUEST": {717        const { getIncomingPairingRequest } = await import('./sync-storage');718        const request = await getIncomingPairingRequest();719        return { ok: true, data: request };720      }721      case "RESPOND_INCOMING_PAIRING": {722        const { accept } = msg.payload as { accept: boolean };723        const { getIncomingPairingRequest, clearIncomingPairingRequest, addPairedDevice } =724          await import('./sync-storage');725        const request = await getIncomingPairingRequest();726        if (!request) return { ok: false, error: "no_pending_request" };727        if (Date.now() > request.expiresAt) {728          await clearIncomingPairingRequest();729          return { ok: false, error: "expired" };730        }731        await clearIncomingPairingRequest();732        if (accept) {733          await addPairedDevice({734            deviceId: request.publicKeyHex,735            displayName: request.deviceName,736            x25519PublicKey: request.publicKeyHex,737            pairedAt: Date.now(),738            lastSeenAt: Date.now(),739          });740        }741        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };742      }743      case "START_PEER_DISCOVERY": {744        const gate = await requirePro("sync");745        if (!gate.allowed) return { ok: false, error: "pro_required" };746        return { ok: false, error: "no_native_host" };747      }748      case "STOP_PEER_DISCOVERY": {749        return { ok: true };750      }751      case "START_PAIRING_SERVER": {752        const gate = await requirePro("sync");753        if (!gate.allowed) return { ok: false, error: "pro_required" };754        const token = generateSixDigitToken();755        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;756        const { setActivePairingToken } = await import('./pairing-server-state');757        await setActivePairingToken({ token, expiresAt });758        return { ok: true, data: { token, expiresAt } };759      }760      case "STOP_PAIRING_SERVER": {761        try {762          const { setActivePairingToken } = await import("./pairing-server-state");763          await setActivePairingToken(null);764        } catch { /* best-effort */ }765        return { ok: true };766      }767      case "CONNECT_WITH_CODE": {768        const gate = await requirePro("sync");769        if (!gate.allowed) return { ok: false, error: "pro_required" };770        return { ok: false, error: "no_native_host" };771      }772      case "GET_RECENT_PAIRING": {773        const { consumeRecentPairing } = await import('./pairing-server-state');774        const recent = await consumeRecentPairing();775        return { ok: true, data: recent };776      }777      case "INITIATE_PAIR_WITH_PEER": {778        const gate = await requirePro("sync");779        if (!gate.allowed) return { ok: false, error: "pro_required" };780        return { ok: false, error: "no_native_host" };781      }782      case "DEBUG_INJECT_INCOMING_PAIRING": {783        // Manual E2E rehearsal hook. Inserts a synthetic incoming pairing784        // request into session storage so Phase 7 banner UX can be exercised785        // without a live native host. No Pro gate — this is a no-op in786        // production unless explicitly invoked from a Settings debug action.787        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {788          deviceName?: string;789          publicKeyHex?: string;790        };791        if (!deviceName || !publicKeyHex) {792          return { ok: false, error: "missing_payload" };793        }794        const { setIncomingPairingRequest } = await import('./sync-storage');795        const now = Date.now();796        await setIncomingPairingRequest({797          deviceName,798          publicKeyHex,799          receivedAt: now,800          expiresAt: now + 60_000,801        });802        return { ok: true };803      }804      case "RESET_SYNC_IDENTITY": {805        const gate = await requirePro("sync");806        if (!gate.allowed) return { ok: false, error: "pro_required" };807        const { getPairedDevices, removePairedDevice } = await import('./sync-storage');808        const devices = await getPairedDevices();809        for (const device of devices) {810          await removePairedDevice(device.deviceId);811        }812        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };813      }814      case "RECORD_MANUAL_SUMMON": {815        const { domain } = msg.payload as { domain: string };816        const settings = vault.getSettings();817        const existing = settings.manualSummonDomains?.[domain];818        const now = Date.now();819        await vault.updateSettings({820          manualSummonDomains: {821            ...settings.manualSummonDomains,822            [domain]: {823              firstSummonedAt: existing?.firstSummonedAt ?? now,824              summonCount: (existing?.summonCount ?? 0) + 1,825              lastSummonedAt: now,826            },827          },828        });829        return { ok: true };830      }831      case "DECLINE_CARD_SAVE": {832        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };833        await vault.declineCardSaveOffer(last4, expMonth, expYear);834        return { ok: true };835      }836      case "IS_CARD_DECLINED": {837        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };838        const declined = await vault.isCardDeclined(last4, expMonth, expYear);839        return { ok: true, data: declined };840      }841      case "INITIATE_FIREFOX_PASSKEY_CREATE": {842        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {843          rpId?: string;844          rpName?: string;845          userName?: string;846          userDisplayName?: string;847        };848        if (!rpId || !userName) return { ok: false, error: "rpId and userName required" };849        return await initiateFirefoxPasskeyCreate({850          rpId,851          rpName: rpName ?? rpId,852          userName,853          userDisplayName,854        });855      }856857      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {858        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;859        if (!payload) return { ok: false, error: "missing payload" };860        return await completeFirefoxPasskeyCreate(payload);861      }862863      case "PASSKEY_OFFER_DECLINE": {864        const { domain } = (msg.payload ?? {}) as { domain?: string };865        if (!domain) return { ok: false, error: "domain required" };866        await recordPasskeyOfferDecline(domain);867        return { ok: true };868      }869870      case "GET_PASSKEY_OFFER_DECLINED": {871        const { domain } = (msg.payload ?? {}) as { domain?: string };872        if (!domain) return { ok: false, error: "domain required" };873        return { ok: true, data: await isPasskeyOfferDeclined(domain) };874      }875876      case "PASSKEY_HAS_CREDENTIALS": {877        const payload = msg.payload as {878          rpId?: string;879          allowCredentials?: Array<{ id: string; type?: string }>;880        } | undefined;881        if (!payload?.rpId) return { ok: false, error: "rpId required" };882        return await handlePasskeyHasCredentials({883          rpId: payload.rpId,884          allowCredentials: payload.allowCredentials ?? [],885        });886      }887888      case "PASSKEY_CREATE": {889        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;890        if (!payload?.rpId || !payload?.userName) {891          return { ok: false, error: "rpId and userName required" };892        }893        return await handleFirefoxPasskeyCreate(payload);894      }895896      case "PASSKEY_GET": {897        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;898        if (!payload?.rpId) return { ok: false, error: "rpId required" };899        return await handleFirefoxPasskeyGet(payload);900      }901902      case "GET_PASSKEY_FOR_DOMAIN": {903        const { domain } = (msg.payload ?? {}) as { domain?: string };904        if (!domain) return { ok: false, error: "domain required" };905        if (!vault.isUnlocked()) return { ok: true, data: null };906        const match = vault907          .getEntries()908          .find((entry) => entry.passkey?.rpId === domain);909        if (!match || !match.passkey) return { ok: true, data: null };910        // Slim shape — only the fields State 11 needs. Never expose private911        // key material, even though this is locked behind isUnlocked.912        return {913          ok: true,914          data: {915            rpId: match.passkey.rpId,916            userName: match.passkey.userName,917            browser: match.passkey.browser,918          },919        };920      }921922      case "DESTROY_VAULT": {923        // Irreversible by design. Lock zeroes the derived key + in-memory entries;924        // storage.local.clear() wipes every Peach key (slots, settings, license,925        // onboarded flag, history, sync state, declined cards, recall, etc.);926        // session.clear() wipes pending passkey requests + pro-notice queues.927        // Caller (Panic.tsx) handles UI navigation back to onboarding.928        vault.lock();929        await storageClear();930        await vault.clearVaultHistory();931        if (chrome.storage.session) {932          await chrome.storage.session.clear();933        }934        return { ok: true };935      }936937      case "SUBMIT_FEEDBACK": {938        const { category, message, version, browser } = msg.payload as {939          category: string;940          message: string;941          version: string;942          browser: string;943        };944        if (!message.trim()) return { ok: false, error: "message is empty" };945        if (!FEEDBACK_ENDPOINT) return { ok: true };946        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {947          return { ok: false, error: "invalid feedback endpoint" };948        }949        try {950          const res = await fetch(FEEDBACK_ENDPOINT, {951            method: "POST",952            headers: { "Content-Type": "application/json" },953            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),954          });955          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };956        } catch (err) {957          return { ok: false, error: err instanceof Error ? err.message : "network error" };958        }959      }960      case "TRIGGER_SYNC": {961        if (isNativePlatform()) {962          bridge?.ensureServerRunning?.();963          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };964        }965        return await desktopTriggerSync({ getLastKnownIp: () => null });966      }967      // Android-only: biometric unlock with pre-derived key.968      case "UNLOCK_WITH_KEY": {969        const { masterKeyHex } = msg.payload as { masterKeyHex: string };970        if (!isNativePlatform()) {971          return { ok: false, error: "desktop_only_uses_password" };972        }973        try {974          const result = await vault.unlockWithKey(masterKeyHex);975          if (result.ok) await publishInMemoryVault(result.entries);976          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };977        } catch {978          return { ok: false, error: "invalid_key" };979        }980      }981      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.982      case "GET_DERIVED_KEY": {983        if (!isNativePlatform()) {984          return { ok: false, error: "android_only" };985        }986        if (!vault.isUnlocked()) {987          return { ok: false, error: "vault_locked" };988        }989        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };990      }991      // Android: scanned a QR containing a desktop pairing token.992      case "SCAN_PAIRING_QR": {993        if (!isNativePlatform()) {994          return { ok: false, error: "android_only" };995        }996        const { token } = msg.payload as { token: string };997        bridge?.startPairingSession?.({ token });998        return { ok: true };999      }1000      // Android: returns the phone's WiFi IP address.1001      case "GET_LOCAL_IP": {1002        if (!isNativePlatform()) {1003          return { ok: false, error: "android_only" };1004        }1005        const { ip } = (await bridge?.getLocalIp?.()) ?? { ip: "" };1006        return { ok: true, data: { ip } };1007      }1008      // Desktop: generates a pairing token and starts the subnet scan for QR pairing.1009      case "START_PAIRING_SERVER": {1010        if (isNativePlatform()) {1011          return { ok: false, error: "desktop_only" };1012        }1013        const arr = new Uint32Array(1);1014        crypto.getRandomValues(arr);1015        const token = String(100000 + (arr[0] % 900000));1016        activeDesktopPairingToken = token;1017        activeDesktopPairingExpiry = Date.now() + 5 * 60 * 1000;1018        startSubnetScan(token, { getLocalAddress: () => null });1019        return { ok: true, data: { token, expiresIn: 300 } };1020      }1021      case "GET_IDENTITY_SUGGESTIONS": {1022        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1023        const entries = vault.getEntries();1024        const suggestions = buildIdentitySuggestions(entries);1025        return { ok: true, data: { suggestions } };1026      }1027      case "POPULATE_INLINE_VAULT": {1028        if (!isNativePlatform()) return { ok: false };1029        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1030        const entries = vault.getEntries();1031        await publishInMemoryVault(entries);1032        return { ok: true };1033      }1034      default:1035        return { ok: false, error: "unknown message type" };1036    }1037  } catch (err) {1038    return {1039      ok: false,1040      error: err instanceof Error ? err.message : "operation failed",1041    };1042  }1043}10441045// --- Mobile platform helpers ---10461047// Desktop: triggers sync for all paired devices.1048async function desktopTriggerSync(deps: {1049  getLastKnownIp: () => string | null;1050}): Promise<{ ok: true; syncedCount: number } | { ok: false; error: string }> {1051  const ip = deps.getLastKnownIp();1052  if (!ip) return { ok: false, error: "no_paired_devices" };1053  return { ok: true, syncedCount: 0 };1054}10551056// Desktop: starts background subnet scan for QR pairing.1057function startSubnetScan(1058  token: string,1059  _deps: {1060    getLocalAddress: () => string | null;1061  }1062): void {1063  // TODO: implement subnet scan and WebSocket pairing server1064}10651066// Android: populates the in-memory vault used by PeachAutofillService.1067async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1068  // TODO: wire up to autofill in-memory store (exists in Android, not here)1069}10701071// Returns all emails and usernames from the vault, deduped and sorted by frequency.1072function buildIdentitySuggestions(1073  entries: VaultEntry[],1074): Array<{ email: string; username: string; count: number }> {1075  const map = new Map<string, number>();1076  for (const entry of entries) {1077    if (entry.username) map.set(entry.username, (map.get(entry.username) ?? 0) + 1);1078  }1079  return Array.from(map.entries())1080    .sort((a, b) => b[1] - a[1])1081    .map(([username, count]) => ({ email: username, username, count }));1082}10831084// Mobile bridge — runtime check to avoid importing Capacitor at the top level.1085// eslint-disable-next-line @typescript-eslint/no-explicit-any1086const bridge = (typeof (globalThis as any).Capacitor !== "undefined")1087  ? (globalThis as any).Capacitor.Plugins.SyncPlugin1088  : null;10891090// eslint-disable-next-line @typescript-eslint/no-explicit-any1091const isNativePlatform = (): boolean => typeof (globalThis as any).Capacitor !== "undefined" && (globalThis as any).isNativePlatform();10921093let activeDesktopPairingToken: string | null = null;1094let activeDesktopPairingExpiry = 0;10951096/** Notify all content scripts that the vault just became available. */1097function broadcastToContentScripts(message: { type: string }): void {1098  if (!chrome.tabs?.query) return;1099  chrome.tabs.query({}, (tabs) => {1100    for (const tab of tabs) {1101      if (tab.id !== undefined) {1102        chrome.tabs.sendMessage(tab.id, message).catch(() => {1103          // Tab may not have a content script — silently ignore1104        });1105      }1106    }1107  });1108}11091110function shouldRefreshAutoLock(type: MessageType): boolean {1111  return (1112    type !== "HAS_VAULT" &&1113    type !== "IS_UNLOCKED" &&1114    type !== "GET_VAULT_STATUS" &&1115    type !== "LOCK" &&1116    type !== "UPDATE_SETTINGS" &&1117    type !== "GET_PENDING_PASSKEY" &&1118    type !== "GET_PASSKEY_PROVIDER_STATE" &&1119    type !== "DECLINE_CARD_SAVE" &&1120    type !== "IS_CARD_DECLINED" &&1121    type !== "SUBMIT_FEEDBACK"1122  );1123}11241125function isAllowedCanaryWebhookUrl(value: string): boolean {1126  try {1127    const url = new URL(value);1128    if (url.protocol !== "https:") return false;11291130    const hostname = url.hostname.toLowerCase();1131    if (1132      hostname === "localhost" ||1133      hostname.endsWith(".localhost") ||1134      isPrivateIpv4(hostname) ||1135      isPrivateIpv6(hostname)1136    ) {1137      return false;1138    }11391140    return true;1141  } catch {1142    return false;1143  }1144}11451146function isPrivateIpv4(hostname: string): boolean {1147  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1148    return true;1149  }11501151  const octets = hostname.split(".").map((part) => Number(part));1152  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1153    return false;1154  }11551156  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1157}11581159function isPrivateIpv6(hostname: string): boolean {1160  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1161  return (1162    normalized === "::1" ||1163    normalized.startsWith("fc") ||1164    normalized.startsWith("fd") ||1165    normalized.startsWith("fe80:")1166  );1167}