messages.ts

47.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 { runSelfTest } from "./self-test";15import * as vault from "./vault";16import {17  handleEstimateCodexPages,18  handleGetCodexVaultData,19  handleRestoreFromCodex,20} from "./codex-handlers";21import type { CodexRestorePayload } from "../shared/codex-types";22import {23  activateLicense,24  deactivateLicense,25  getLicenseInfo,26  getLicenseKey,27  isProUser,28  markCelebrationPlayed,29  shouldPlayCelebration,30} from "./license";31import {32  completeFirefoxPasskeyCreate,33  getPasskeyProviderState,34  getPendingPasskeyRequest,35  handleFirefoxPasskeyCreate,36  handleFirefoxPasskeyGet,37  handlePasskeyHasCredentials,38  initiateFirefoxPasskeyCreate,39  isPasskeyOfferDeclined,40  onVaultUnlocked,41  recordPasskeyOfferDecline,42  resolvePendingPasskeyRequest,43  setPasskeyProviderEnabled,44} from "./passkey";45import { buildAdvancedHealthReport } from "./health";46import { storageClear } from "../shared/storage";47import { findInvalidWords } from "../shared/recovery-words";48import type {49  Message,50  MessageResponse,51  MessageType,52  ProFeature,53  VaultEntry,54} from "../shared/types";55import { isPasskeyOnly } from "../shared/types";56import { isNativePlatform, nativePlugin } from "../shared/native";57import { predictBatch as mlPredictBatch } from "./ml";58import type { MLFieldFeatures } from "../shared/ml";59import { buildLocalIdentity, setDeviceName as setDeviceNameV3 } from "./chirp-identity";60import {61  listPairedDevices as listPairedDevicesV3,62  removePairedDeviceById as removePairedDeviceByIdV3,63  upsertPairedDevice as upsertPairedDeviceV3,64} from "./paired-devices";6566function unhexBytes(hex: string): Uint8Array {67  if (hex.length % 2 !== 0) throw new Error("invalid hex");68  const out = new Uint8Array(hex.length / 2);69  for (let i = 0; i < out.length; i++) {70    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);71  }72  return out;73}7475/**76 * The single Pro gate. Every gated handler calls this first; the broadcast77 * lets the popup react (navigate to the License section, highlight the78 * relevant feature). Background never touches the popup view directly —79 * the popup owns navigation. See Projects.md "Pro gate rule".80 */81async function requirePro(82  feature: ProFeature,83  trigger: "user" | "background" = "user"84): Promise<{ allowed: boolean }> {85  if (await isProUser()) return { allowed: true };8687  if (trigger === "user") {88    // User deliberately triggered this feature — redirect the popup immediately.89    chrome.runtime90      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })91      .catch(() => {92        // Popup may be closed — the gate signal is best-effort.93      });94  } else {95    // Background trigger (e.g. passive sync initiation) — no popup is open.96    // Queue a notice so the next popup open shows a soft banner instead of97    // silently failing.98    if (chrome.storage.session) {99      chrome.storage.session100        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })101        .catch(() => {});102    }103  }104105  return { allowed: false };106}107108// ---------------------------------------------------------------------------109// Feedback submission target. Empty disables network submission while the UI110// continues to function as a no-op (the handler returns ok:true without111// calling fetch). When set, the URL is validated by112// `isAllowedCanaryWebhookUrl` before any request.113// ---------------------------------------------------------------------------114115const FEEDBACK_ENDPOINT = "";116117const PRIVATE_IPV4_RANGES = [118  { prefix: "10." },119  { prefix: "127." },120  { prefix: "169.254." },121  { prefix: "192.168." },122];123124export function setupMessageHandler(): void {125  chrome.runtime.onMessage.addListener(126    (msg: unknown, sender, sendResponse) => {127      if (!isMessage(msg)) {128        sendResponse({ ok: false, error: "invalid_message" });129        return true;130      }131      handleMessage(msg, sender)132        .then(sendResponse)133        .catch((err) =>134          sendResponse({135            ok: false,136            error: err instanceof Error ? err.message : String(err),137          })138        );139      return true;140    }141  );142143  // Android: the chrome shim queues sendMessage calls until this handler is144  // registered. Without this hookup, every message hangs on Capacitor builds.145  // eslint-disable-next-line @typescript-eslint/no-explicit-any146  const reg = (globalThis as any).__peachRegisterMessageHandler;147  if (typeof reg === "function") {148    reg(async (m: unknown) => {149      if (!isMessage(m)) return { ok: false, error: "invalid_message" };150      try {151        return await handleMessage(m);152      } catch (err) {153        return {154          ok: false,155          error: err instanceof Error ? err.message : String(err),156        };157      }158    });159  }160161}162163function isMessage(m: unknown): m is Message {164  return typeof m === "object" && m !== null && "type" in m;165}166167export async function handleMessage(168  msg: Message,169  sender: Partial<chrome.runtime.MessageSender> = {}170): Promise<MessageResponse> {171  try {172    // Validate sender — only allow messages from our extension pages/scripts.173    // `sender.id` is undefined for messages originating from extension UI174    // (popup/options), which is legitimate; reject only when it is defined175    // and does not match our extension id.176    if (177      sender.id !== undefined &&178      sender.id !== chrome.runtime.id179    ) {180      return { ok: false, error: "invalid_sender" };181    }182183    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {184      touchAutoLock();185    }186187    switch (msg.type) {188      case "CREATE_VAULT": {189        const { password } = msg.payload as { password: string };190        await vault.createVault(password);191        await setupAutoLock();192        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });193        onVaultUnlocked();194        return { ok: true };195      }196      case "UNLOCK": {197        const { password } = msg.payload as { password: string };198        const ok = await vault.unlock(password);199        if (ok) {200          // KAT: verify the WebCrypto stack is healthy before the user relies on it.201          // Runs after unlock so latency is hidden behind the vault-load time.202          const kat = await runSelfTest();203          if (!kat.ok) {204            console.error("[Peach] Crypto self-test FAILED:", kat.error);205            await vault.lock();206            return { ok: false, error: "self_test_failed" };207          }208          await setupAutoLock();209          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });210          onVaultUnlocked();211          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());212          return { ok: true };213        }214        // Distinguish corruption from wrong password so the popup can offer215        // a history-restore path instead of falsely accusing the user of216        // mistyping (M7/COR-007).217        const failure = vault.consumeLastUnlockFailureReason();218        if (failure) {219          return {220            ok: false,221            error: "vault_corrupted",222            canRestoreFromHistory: true,223          } as MessageResponse;224        }225        return { ok: false };226      }227      case "VALIDATE_RECOVERY_WORDS": {228        const { words } = msg.payload as { words: string[] };229        const invalid = findInvalidWords(words);230        return { ok: true, data: { valid: invalid.length === 0, invalid } };231      }232      case "GET_RECOVERY_WORDS": {233        // Must be unlocked and have recovery set up (vault must be v2.12+).234        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };235        try {236          const words = await vault.getRecoveryWords();237          return { ok: true, data: words };238        } catch (e) {239          // pre-v2.12 vault that hasn't migrated240          return { ok: false, error: "recovery_not_setup" };241        }242      }243      case "RECOVER_WITH_WORDS": {244        // User has lost their password but has their 12 recovery words.245        // We: (1) validate the words, (2) re-encrypt vault with new password.246        const { words, newPassword } = msg.payload as {247          words: string[];248          newPassword: string;249        };250        const stored = await vault.loadSlotA();251        if (!stored) return { ok: false, error: "no_vault" };252        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {253          return { ok: false, error: "recovery_not_setup" };254        }255        // Unwrap the root key from the recovery escrow.256        try {257          await vault.unwrapRootKeyForRecovery(258            stored.recovery_wrapped_root_key,259            stored.recovery_nonce ?? "",260            stored.recovery_tag ?? "",261            stored.recovery_salt,262            words263          );264        } catch {265          return { ok: false, error: "invalid_recovery_words" };266        }267        // Re-key: derive fresh salt + key from new password.268        const newSalt = vault.generateSalt();269        const newKey = await vault.deriveKey(newPassword, newSalt);270        // Re-wrap root key under the new password's derived key so the same271        // recovery words continue to work after the password change.272        await vault.rewrapRootKeyForPassword(newKey, newSalt);273        // Re-encrypt vault entries with the new key.274        await vault.changePasswordWithNewKey(newSalt, newKey);275        await setupAutoLock();276        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });277        return { ok: true };278      }279      case "LOCK":280        vault.lock();281        if (isNativePlatform()) await clearInMemoryVault();282        return { ok: true };283      case "IS_UNLOCKED":284        return { ok: true, data: vault.isUnlocked() };285      case "GET_VAULT_STATUS":286        return { ok: true, unlocked: vault.isUnlocked() };287      case "HAS_VAULT":288        return { ok: true, data: await vault.hasVault() };289      case "GET_ENTRIES":290        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };291        return { ok: true, data: vault.getEntries() };292      case "ADD_ENTRY": {293        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };294        const payload = msg.payload;295        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {296          return { ok: false, error: "invalid_payload" };297        }298        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);299        return { ok: true, data: entry };300      }301      case "BATCH_ADD_ENTRIES": {302        const payload = msg.payload as { entries?: unknown } | null | undefined;303        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {304          return { ok: false, error: "invalid_payload" };305        }306        if (!Array.isArray(payload.entries)) {307          return { ok: false, error: "invalid_payload" };308        }309        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);310        return { ok: true, data: added };311      }312      case "RESTORE_ENTRIES": {313        const payload = msg.payload as314          | { entries?: unknown; mode?: unknown; settings?: unknown }315          | null316          | undefined;317        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {318          return { ok: false, error: "invalid_payload" };319        }320        if (!Array.isArray(payload.entries)) {321          return { ok: false, error: "invalid_payload" };322        }323        if (payload.mode !== "replace" && payload.mode !== "merge") {324          return { ok: false, error: "invalid_payload" };325        }326        const summary = await vault.restoreEntries(327          payload.entries as Parameters<typeof vault.restoreEntries>[0],328          payload.mode329        );330        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {331          await vault.updateSettings(payload.settings as vault.VaultSettings);332        }333        return { ok: true, data: summary };334      }335      case "CLEAR_VAULT_ENTRIES": {336        await vault.clearVaultEntries("REPLACE_ALL");337        return { ok: true };338      }339      case "GET_VAULT_HISTORY": {340        const snapshots = await vault.getVaultHistory();341        return { ok: true, data: snapshots };342      }343      case "RESTORE_VAULT_SNAPSHOT": {344        const { snapshotId } = msg.payload as { snapshotId: string };345        const result = await vault.restoreVaultSnapshot(snapshotId);346        if (!result.ok) return { ok: false, error: result.error };347        broadcastToContentScripts({ type: "VAULT_LOCKED" });348        return { ok: true };349      }350      case "COUNT_DUPLICATES": {351        return { ok: true, data: vault.countDuplicates() };352      }353      case "DEDUPLICATE_ENTRIES": {354        const removed = await vault.deduplicateEntries();355        return { ok: true, data: removed };356      }357      case "UPDATE_ENTRY": {358        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;359        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {360          return { ok: false, error: "invalid_payload" };361        }362        const { id, patch } = payload;363        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {364          return { ok: false, error: "invalid_payload" };365        }366        // Single enforcement point for the Canary Entries Pro gate. Only367        // gates the transition into a canary entry — clearing/disabling a368        // canary (`canary: undefined`) is always allowed, so existing369        // canary entries remain manageable.370        const incomingCanary = (patch as { canary?: unknown }).canary;371        if (incomingCanary && typeof incomingCanary === "object") {372          const existing = vault.getEntryById(id);373          if (!existing?.canary) {374            const gate = await requirePro("canary_entry");375            if (!gate.allowed) return { ok: false, error: "pro_required" };376          }377        }378        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);379        return { ok: true };380      }381      case "ADD_ADDITIONAL_URL": {382        const { id, url } = msg.payload as { id: string; url: string };383        const trimmed = typeof url === "string" ? url.trim() : "";384        if (!trimmed) return { ok: false, error: "url_required" };385        const existing = vault.getEntryById(id);386        if (!existing) return { ok: false, error: "entry_not_found" };387        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };388        const merged = [...(existing.additionalUrls ?? []), trimmed];389        await vault.updateEntry(id, { additionalUrls: merged });390        return { ok: true };391      }392      case "DELETE_ENTRY": {393        const { id } = msg.payload as { id: string };394        await vault.deleteEntry(id);395        return { ok: true };396      }397      case "GET_DELETED_ENTRIES":398        return { ok: true, data: vault.getDeletedEntries() };399      case "RESTORE_ENTRY": {400        const { id } = msg.payload as { id: string };401        await vault.restoreEntry(id);402        return { ok: true };403      }404      case "PURGE_ENTRY": {405        const { id } = msg.payload as { id: string };406        await vault.purgeEntry(id);407        return { ok: true };408      }409      case "PURGE_EXPIRED_TRASH": {410        const { retentionMs } = msg.payload as { retentionMs: number };411        const purged = await vault.purgeExpiredTrash(retentionMs);412        return { ok: true, data: purged };413      }414      case "SAVE_NOTE": {415        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };416        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };417        const now = Date.now();418        if (id) {419          const existing = vault.getEntryById(id);420          if (!existing) return { ok: false, error: "not_found" };421          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });422          return { ok: true, data: vault.getEntryById(id) };423        } else {424          const entry = await vault.addEntry({425            type: "note",426            title: title || "Untitled",427            notes: body,428            createdAt: now,429            modifiedAt: now,430          } as any);431          return { ok: true, data: entry };432        }433      }434      case "DELETE_NOTE": {435        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };436        const { id } = msg.payload as { id: string };437        await vault.deleteEntry(id);438        return { ok: true };439      }440      case "GET_NOTES": {441        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };442        const notes = vault.getEntries().filter(443          (e) => e.type === "note" && !e.deletedAt444        );445        return { ok: true, data: notes } as MessageResponse;446      }447      case "SEARCH_VAULT": {448        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };449        // AUD-002: shape-validate the payload before calling string methods.450        // A raw cast lets a malformed message crash the handler with TypeError.451        const { query } = (msg.payload ?? {}) as { query?: unknown };452        if (typeof query !== "string") {453          return { ok: false, error: "invalid_payload" };454        }455        const q = query.toLowerCase();456        const searchResults = vault.getEntries().filter(457          (e) =>458            !e.deletedAt &&459            (e.title.toLowerCase().includes(q) ||460              e.notes?.toLowerCase().includes(q) ||461              e.username?.toLowerCase().includes(q))462        );463        return { ok: true, data: searchResults } as MessageResponse;464      }465      case "AUTOFILL_QUERY": {466        if (!vault.isUnlocked()) {467          return { ok: false, error: "vault_locked" };468        }469        const { domain, includeAll, kind } = msg.payload as {470          domain: string;471          includeAll?: boolean;472          kind?: "login" | "card" | "totp";473        };474        // kind="card": return saved cards as compact summaries for the475        // inline card silver platter. Cards are not domain-scoped — every476        // saved card is a candidate on every checkout page — so domain is477        // ignored when kind === "card".478        if (kind === "card") {479          const cards = vault.getEntries().filter((e) => e.type === "card");480          return {481            ok: true,482            data: cards.map((e) => ({483              id: e.id,484              title: e.cardNickname || e.title,485              cardholderName: e.cardholderName,486              last4: e.last4,487              expMonth: e.expMonth,488              expYear: e.expYear,489              network: e.network,490            })),491          };492        }493        if (kind === "totp") {494          const matches = (495            includeAll496              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")497              : vault.queryDomain(domain)498          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));499          return {500            ok: true,501            data: matches.map((e) => ({502              id: e.id,503              title: e.title,504              username: e.username,505              email: e.email,506              url: e.url,507              hasTotp: true,508            })),509          };510        }511        // The inline selector fills username+password into a form. Passkey-512        // only entries have no password to fill; sign-in for those goes513        // through the WebAuthn path instead. Filter them out everywhere so514        // the user doesn't see four "GitHub" rows that mostly do nothing.515        // Notes and cards never belonged here either.516        const matches = (517          includeAll518            ? vault519                .getEntries()520                .filter((entry) => entry.type !== "note" && entry.type !== "card")521            : vault.queryDomain(domain)522        ).filter((entry) => !isPasskeyOnly(entry));523        return {524          ok: true,525          data: matches.map((e) =>526            includeAll527              ? {528                  id: e.id,529                  title: e.title,530                  hasPasskey: e.passkey !== undefined,531                }532              : {533                  id: e.id,534                  title: e.title,535                  username: e.username,536                  email: e.email,537                  url: e.url,538                  hasTotp: Boolean(e.totp),539                  hasPasskey: e.passkey !== undefined,540                }541          ),542        };543      }544      case "GET_ENTRY_FOR_FILL": {545        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };546        const { id } = msg.payload as { id: string };547        const entry = vault.getEntryById(id);548        if (!entry) return { ok: false, error: "entry_not_found" };549        // Passkey-only entries (passkey credential, no password) cannot be550        // filled into a form — sign-in goes through the WebAuthn path. A551        // login that ALSO has a passkey is still fillable for its password.552        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };553        // Strip the passkey credential from the response — content scripts554        // never need the private key, and there's no reason to expose the555        // public credential metadata over the boundary either.556        const { passkey: _strippedPasskey, ...safeEntry } = entry;557        return { ok: true, data: safeEntry };558      }559      case "COPY": {560        // AUD-002: shape-validate the payload before passing to the clipboard561        // helper. A raw cast lets a malformed message reach the clipboard API562        // with a non-string and throw.563        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {564          text?: unknown;565          label?: unknown;566          alreadyWritten?: unknown;567        };568        if (typeof text !== "string" || typeof label !== "string") {569          return { ok: false, error: "invalid_payload" };570        }571        await copyToClipboard(text, label, Boolean(alreadyWritten));572        return { ok: true };573      }574      case "CHECK_ALL_BREACHES": {575        const allEntries = vault.getEntries();576        const results: Record<string, number> = {};577        for (const entry of allEntries) {578          if (entry.type === "note") continue;579          if (!entry.password) continue;580          results[entry.id] = await vault.checkBreach(entry.password);581          // Small delay — be a good citizen to the HIBP API582          await new Promise((r) => setTimeout(r, 200));583        }584        // Persist any non-zero counts back to entries585        for (const [id, count] of Object.entries(results)) {586          const entry = vault.getEntryById(id);587          if (entry && (entry.breach ?? 0) !== count) {588            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });589          }590        }591        return { ok: true, data: results };592      }593      case "GET_SETTINGS":594        return { ok: true, data: await vault.ensureSettingsLoaded() };595      case "UPDATE_SETTINGS": {596        const patch = msg.payload;597        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {598          return { ok: false, error: "invalid_payload" };599        }600        await vault.updateSettings(patch as vault.VaultSettings);601        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {602          await setupAutoLock();603          if (vault.isUnlocked()) touchAutoLock();604        }605        return { ok: true };606      }607      case "GET_PENDING_PASSKEY":608        return { ok: true, data: await getPendingPasskeyRequest() };609      case "APPROVE_PASSKEY": {610        const { requestId } = msg.payload as { requestId: number };611        await resolvePendingPasskeyRequest(requestId, true);612        return { ok: true };613      }614      case "DENY_PASSKEY": {615        const { requestId } = msg.payload as { requestId: number };616        await resolvePendingPasskeyRequest(requestId, false);617        return { ok: true };618      }619      case "GET_PASSKEY_PROVIDER_STATE":620        return { ok: true, data: await getPasskeyProviderState() };621      case "SET_PASSKEY_PROVIDER_ENABLED": {622        const { enabled } = msg.payload as { enabled: boolean };623        // Disabling is always free; gating fires only when a free user is624        // trying to turn passkey interception on.625        if (enabled) {626          const gate = await requirePro("passkeys");627          if (!gate.allowed) return { ok: false, error: "pro_required" };628        }629        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };630      }631      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS632      // endpoint. Intentional product behavior — users configure their own633      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private634      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-635      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to636      // users that the entry title leaves the device when the canary fires.637      case "FIRE_CANARY_PING": {638        // Canary alert fires unconditionally for any entry with canary: true.639        // The Pro gate only governs creation/flagging of canary entries; once640        // an entry is flagged, the alert path is a security property and must641        // never be license-gated.642        const { webhookUrl, entryTitle, trigger } = msg.payload as {643          webhookUrl: string;644          entryTitle: string;645          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";646        };647        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {648          return { ok: false, error: "invalid_webhook_url" };649        }650        const body = JSON.stringify({651          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",652          entry: entryTitle,653          trigger,654          timestamp: new Date().toISOString(),655          source: "peach-extension",656        });657        if (trigger === "test") {658          // Permitted outbound fetch: user-configured canary alert endpoint659          // (validated by isAllowedCanaryWebhookUrl above). This is the660          // only non-HIBP outbound call in the extension — see661          // Projects.md §3.7. Test pings are awaited so the UI can show662          // success/failure.663          try {664            const res = await fetch(webhookUrl, {665              method: "POST",666              headers: { "Content-Type": "application/json" },667              body,668            });669            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };670          } catch (err) {671            return { ok: false, error: err instanceof Error ? err.message : "network_error" };672          }673        }674        // Non-test triggers are fire-and-forget675        fetch(webhookUrl, {676          method: "POST",677          headers: { "Content-Type": "application/json" },678          body,679        }).catch(() => {});680        return { ok: true };681      }682      case "ACTIVATE_LICENSE": {683        const { key } = msg.payload as { key: string };684        const licenseInfo = await activateLicense(key);685        return { ok: true, data: licenseInfo };686      }687      case "GET_LICENSE": {688        const licenseInfo = await getLicenseInfo();689        return { ok: true, data: licenseInfo };690      }691      case "GET_LICENSE_KEY": {692        const key = await getLicenseKey();693        return { ok: true, data: key };694      }695      case "DEACTIVATE_LICENSE": {696        await deactivateLicense();697        return { ok: true };698      }699      case "SHOULD_PLAY_CELEBRATION": {700        const should = await shouldPlayCelebration();701        return { ok: true, data: should };702      }703      case "MARK_CELEBRATION_PLAYED": {704        await markCelebrationPlayed();705        return { ok: true };706      }707      case "GET_CODEX_VAULT_DATA": {708        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the709        // popup navigates to the License section without further coordination.710        const gate = await requirePro("codex");711        if (!gate.allowed) return { ok: false, error: "pro_required" };712        return await handleGetCodexVaultData();713      }714      case "ESTIMATE_CODEX_PAGES": {715        const gate = await requirePro("codex");716        if (!gate.allowed) return { ok: false, error: "pro_required" };717        return await handleEstimateCodexPages();718      }719      case "RESTORE_FROM_CODEX": {720        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still721        // be able to restore a vault that was printed by a Pro user.722        // DO NOT add a Pro gate here.723        const payload = msg.payload as CodexRestorePayload;724        return await handleRestoreFromCodex(payload);725      }726      case "OPEN_PRO_GATE": {727        // Content script requests: open popup and navigate to License section.728        const { feature } = (msg.payload ?? {}) as { feature?: string };729        if (chrome.storage.session) {730          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });731        }732        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }733        return { ok: true };734      }735      case "GET_IDENTITIES": {736        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };737        return { ok: true, data: vault.getIdentities() };738      }739      case "TOUCH_AUTO_LOCK": {740        // touchAutoLock() is already called by shouldRefreshAutoLock above;741        // this case just gives the popup a typed message to keep the session alive.742        return { ok: true };743      }744      case "GET_ADVANCED_HEALTH_REPORT": {745        const gate = await requirePro("advanced_health");746        if (!gate.allowed) return { ok: false, error: "pro_required" };747        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };748        const report = await buildAdvancedHealthReport(vault.getEntries());749        return { ok: true, data: report };750      }751      case "IS_DURESS_ENABLED": {752        const enabled = await vault.isDuressEnabled();753        return { ok: true, data: enabled };754      }755      case "SETUP_DURESS": {756        // Single enforcement point for the Duress Vault Pro gate. Free users757        // who somehow reach this handler are rejected here; the popup also758        // pre-checks isPro() to avoid showing the setup form to free users,759        // but server-side is the actual security boundary.760        const gate = await requirePro("duress_vault");761        if (!gate.allowed) return { ok: false, error: "pro_required" };762        // MV3 service workers restart after inactivity, losing the in-memory763        // derived key. Detect this before calling setupDuress so the popup764        // can show a meaningful prompt to re-lock and re-unlock.765        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };766        const { duressPassword } = msg.payload as { duressPassword: string };767        await vault.setupDuress(duressPassword);768        return { ok: true };769      }770      case "DISABLE_DURESS": {771        await vault.disableDuress();772        return { ok: true };773      }774      case "VERIFY_MAIN_PASSWORD": {775        const { password } = msg.payload as { password: string };776        const ok = await vault.verifyMainPassword(password);777        return { ok: true, data: ok };778      }779      case "CHANGE_PASSWORD": {780        const { currentPassword, newPassword } = msg.payload as {781          currentPassword: string;782          newPassword: string;783        };784        const changed = await vault.changePassword(currentPassword, newPassword);785        return changed786          ? { ok: true }787          : { ok: false, error: "incorrect_current_password" };788      }789      case "GET_SITE_PASSWORD_POLICY": {790        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });791        if (!tab?.id) return { ok: true, data: null };792        try {793          const response = await chrome.tabs.sendMessage(tab.id, {794            type: "GET_SITE_PASSWORD_POLICY",795          });796          return (response as MessageResponse) ?? { ok: true, data: null };797        } catch {798          return { ok: true, data: null };799        }800      }801      case "RECORD_MANUAL_SUMMON": {802        const { domain } = msg.payload as { domain: string };803        const settings = vault.getSettings();804        const existing = settings.manualSummonDomains?.[domain];805        const now = Date.now();806        await vault.updateSettings({807          manualSummonDomains: {808            ...settings.manualSummonDomains,809            [domain]: {810              firstSummonedAt: existing?.firstSummonedAt ?? now,811              summonCount: (existing?.summonCount ?? 0) + 1,812              lastSummonedAt: now,813            },814          },815        });816        return { ok: true };817      }818      case "DECLINE_CARD_SAVE": {819        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };820        await vault.declineCardSaveOffer(last4, expMonth, expYear);821        return { ok: true };822      }823      case "IS_CARD_DECLINED": {824        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };825        const declined = await vault.isCardDeclined(last4, expMonth, expYear);826        return { ok: true, data: declined };827      }828      case "INITIATE_FIREFOX_PASSKEY_CREATE": {829        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {830          rpId?: string;831          rpName?: string;832          userName?: string;833          userDisplayName?: string;834        };835        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };836        return await initiateFirefoxPasskeyCreate({837          rpId,838          rpName: rpName ?? rpId,839          userName,840          userDisplayName,841        });842      }843844      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {845        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;846        if (!payload) return { ok: false, error: "missing_payload" };847        return await completeFirefoxPasskeyCreate(payload);848      }849850      case "PASSKEY_OFFER_DECLINE": {851        const { domain } = (msg.payload ?? {}) as { domain?: string };852        if (!domain) return { ok: false, error: "domain_required" };853        await recordPasskeyOfferDecline(domain);854        return { ok: true };855      }856857      case "GET_PASSKEY_OFFER_DECLINED": {858        const { domain } = (msg.payload ?? {}) as { domain?: string };859        if (!domain) return { ok: false, error: "domain_required" };860        return { ok: true, data: await isPasskeyOfferDeclined(domain) };861      }862863      case "PASSKEY_HAS_CREDENTIALS": {864        const payload = msg.payload as {865          rpId?: string;866          allowCredentials?: Array<{ id: string; type?: string }>;867        } | undefined;868        if (!payload?.rpId) return { ok: false, error: "rpid_required" };869        return await handlePasskeyHasCredentials({870          rpId: payload.rpId,871          allowCredentials: payload.allowCredentials ?? [],872        });873      }874875      case "PASSKEY_CREATE": {876        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;877        if (!payload?.rpId || !payload?.userName) {878          return { ok: false, error: "rpid_and_username_required" };879        }880        return await handleFirefoxPasskeyCreate(payload);881      }882883      case "PASSKEY_GET": {884        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;885        if (!payload?.rpId) return { ok: false, error: "rpid_required" };886        return await handleFirefoxPasskeyGet(payload);887      }888889      case "PASSKEY_AUTH_RESPONSE": {890        const { requestId, approved } = (msg.payload ?? {}) as {891          requestId?: string | number;892          approved?: boolean;893        };894        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {895          return { ok: false, error: 'requestId and approved required' };896        }897        await resolvePendingPasskeyRequest(Number(requestId), approved);898        return { ok: true };899      }900901      case "GET_PASSKEY_FOR_DOMAIN": {902        const { domain } = (msg.payload ?? {}) as { domain?: string };903        if (!domain) return { ok: false, error: "domain_required" };904        if (!vault.isUnlocked()) return { ok: true, data: null };905        const match = vault906          .getEntries()907          .find((entry) => entry.passkey?.rpId === domain);908        if (!match || !match.passkey) return { ok: true, data: null };909        // Slim shape — only the fields State 11 needs. Never expose private910        // key material, even though this is locked behind isUnlocked.911        return {912          ok: true,913          data: {914            rpId: match.passkey.rpId,915            userName: match.passkey.userName,916            browser: match.passkey.browser,917          },918        };919      }920921      case "DESTROY_VAULT": {922        // Irreversible by design. Lock zeroes the derived key + in-memory entries;923        // storage.local.clear() wipes every Peach key (slots, settings, license,924        // onboarded flag, history, sync state, declined cards, recall, etc.);925        // session.clear() wipes pending passkey requests + pro-notice queues.926        // Caller (Panic.tsx) handles UI navigation back to onboarding.927        vault.lock();928        await storageClear();929        await vault.clearVaultHistory();930        if (chrome.storage.session) {931          await chrome.storage.session.clear();932        }933        return { ok: true };934      }935936      case "SUBMIT_FEEDBACK": {937        const { category, message, version, browser } = msg.payload as {938          category: string;939          message: string;940          version: string;941          browser: string;942        };943        if (!message.trim()) return { ok: false, error: "message_empty" };944        if (!FEEDBACK_ENDPOINT) return { ok: true };945        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {946          return { ok: false, error: "invalid_feedback_endpoint" };947        }948        try {949          const res = await fetch(FEEDBACK_ENDPOINT, {950            method: "POST",951            headers: { "Content-Type": "application/json" },952            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),953          });954          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };955        } catch (err) {956          return { ok: false, error: err instanceof Error ? err.message : "network_error" };957        }958      }959      // Android-only: biometric unlock with pre-derived key.960      case "UNLOCK_WITH_KEY": {961        const { masterKeyHex } = msg.payload as { masterKeyHex: string };962        if (!isNativePlatform()) {963          return { ok: false, error: "desktop_only_uses_password" };964        }965        try {966          const result = await vault.unlockWithKey(masterKeyHex);967          if (result.ok) {968            onVaultUnlocked();969            await publishInMemoryVault(result.entries);970          }971          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };972        } catch {973          return { ok: false, error: "invalid_key" };974        }975      }976      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.977      case "GET_DERIVED_KEY": {978        if (!isNativePlatform()) {979          return { ok: false, error: "android_only" };980        }981        if (!vault.isUnlocked()) {982          return { ok: false, error: "vault_locked" };983        }984        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };985      }986      case "GET_IDENTITY_SUGGESTIONS": {987        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };988        const entries = vault.getEntries();989        const suggestions = buildIdentitySuggestions(entries);990        return { ok: true, data: { suggestions } };991      }992      case "POPULATE_INLINE_VAULT": {993        if (!isNativePlatform()) return { ok: false };994        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };995        const entries = vault.getEntries();996        await publishInMemoryVault(entries);997        return { ok: true };998      }999      case "ML_INIT":1000        return { ok: true };10011002      case "ML_PREDICT_BATCH": {1003        // AUD-002: shape-validate before forwarding to the ML helper.1004        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1005        if (!Array.isArray(featuresArray)) {1006          return { ok: false, error: "invalid_payload" };1007        }1008        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1009      }10101011      // ── Chirp Sync (v3) ───────────────────────────────────────────────1012      // Returns the public-facing local identity needed by the popup to1013      // drive Phase-1 audio pairing. The private long-term key never1014      // leaves the background.1015      case "CHIRP_GET_LOCAL_IDENTITY": {1016        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1017        const proCheck = await requirePro("sync");1018        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1019        const masterKeyHex = vault.getDerivedKeyHex();1020        const masterKey = unhexBytes(masterKeyHex);1021        try {1022          const identity = await buildLocalIdentity(masterKey);1023          return { ok: true, data: identity };1024        } finally {1025          masterKey.fill(0);1026        }1027      }10281029      case "CHIRP_COMPLETE_PAIRING": {1030        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1031        const proCheck = await requirePro("sync");1032        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1033        const paired = (msg.payload as { paired?: unknown })?.paired;1034        if (typeof paired !== "object" || paired === null) {1035          return { ok: false, error: "invalid_payload" };1036        }1037        const candidate = paired as Record<string, unknown>;1038        if (1039          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1040          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1041          typeof candidate.deviceType !== "string" ||1042          typeof candidate.longTermPublicKeyHex !== "string" ||1043          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1044          typeof candidate.pairedAt !== "number"1045        ) {1046          return { ok: false, error: "invalid_paired_device" };1047        }1048        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1049        return { ok: true };1050      }10511052      case "CHIRP_LIST_PAIRED_DEVICES": {1053        const devices = await listPairedDevicesV3();1054        return { ok: true, data: { devices } };1055      }10561057      case "CHIRP_UNPAIR_DEVICE": {1058        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1059        if (typeof deviceId !== "string" || !deviceId) {1060          return { ok: false, error: "invalid_payload" };1061        }1062        await removePairedDeviceByIdV3(deviceId);1063        return { ok: true };1064      }10651066      case "CHIRP_RENAME_LOCAL_DEVICE": {1067        const { name } = (msg.payload ?? {}) as { name?: string };1068        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1069        await setDeviceNameV3(name);1070        return { ok: true };1071      }10721073      default:1074        return { ok: false, error: "unknown_message_type" };1075    }1076  } catch (err) {1077    return {1078      ok: false,1079      error: err instanceof Error ? err.message : "operation_failed",1080    };1081  }1082}10831084// --- Mobile platform helpers ---10851086// Android: populates the in-memory vault used by PeachAutofillService.1087async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1088  const plugin = nativePlugin<{1089    setEntries?: (args: {1090      entries: Array<{1091        id: string;1092        title: string;1093        username: string;1094        email: string;1095        password: string;1096        url: string;1097        totp: string;1098        additionalUrls: string[];1099      }>;1100    }) => Promise<void>;1101  }>("InMemoryVaultPlugin");1102  if (!plugin?.setEntries) return;1103  await plugin.setEntries({1104    entries: entries.map((e) => ({1105      id: e.id,1106      title: e.title ?? "",1107      username: e.username ?? "",1108      email: (e as VaultEntry & { email?: string }).email ?? "",1109      password: e.password ?? "",1110      url: e.url ?? "",1111      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1112      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1113    })),1114  });1115}11161117// Android: clear the autofill in-memory store on lock.1118async function clearInMemoryVault(): Promise<void> {1119  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1120  if (!plugin?.clearEntries) return;1121  await plugin.clearEntries();1122}11231124// Returns username use-counts from the vault, sorted by frequency. Each row1125// also carries the entry's email so the popup can suggest the email/username1126// pair the user has actually used together.1127function buildIdentitySuggestions(1128  entries: VaultEntry[],1129): Array<{ email: string; username: string; count: number }> {1130  const usernameCounts = new Map<string, number>();1131  const usernameEmail = new Map<string, string>();1132  for (const entry of entries) {1133    const username = entry.username ?? "";1134    const email = (entry as VaultEntry & { email?: string }).email ?? "";1135    if (!username && !email) continue;1136    const key = username || email;1137    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1138    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1139  }1140  return Array.from(usernameCounts.entries())1141    .sort((a, b) => b[1] - a[1])1142    .map(([username, count]) => ({1143      email: usernameEmail.get(username) ?? "",1144      username,1145      count,1146    }));1147}11481149/** Notify all content scripts that the vault just became available. */1150function broadcastToContentScripts(message: { type: string }): void {1151  if (!chrome.tabs?.query) return;1152  chrome.tabs.query({}, (tabs) => {1153    for (const tab of tabs) {1154      if (tab.id !== undefined) {1155        chrome.tabs.sendMessage(tab.id, message).catch(() => {1156          // Tab may not have a content script — silently ignore1157        });1158      }1159    }1160  });1161}11621163function shouldRefreshAutoLock(type: MessageType): boolean {1164  return (1165    type !== "HAS_VAULT" &&1166    type !== "IS_UNLOCKED" &&1167    type !== "GET_VAULT_STATUS" &&1168    type !== "LOCK" &&1169    type !== "UPDATE_SETTINGS" &&1170    type !== "GET_PENDING_PASSKEY" &&1171    type !== "GET_PASSKEY_PROVIDER_STATE" &&1172    type !== "DECLINE_CARD_SAVE" &&1173    type !== "IS_CARD_DECLINED" &&1174    type !== "SUBMIT_FEEDBACK"1175  );1176}11771178function isAllowedCanaryWebhookUrl(value: string): boolean {1179  try {1180    const url = new URL(value);1181    if (url.protocol !== "https:") return false;11821183    const hostname = url.hostname.toLowerCase();1184    if (1185      hostname === "localhost" ||1186      hostname.endsWith(".localhost") ||1187      isPrivateIpv4(hostname) ||1188      isPrivateIpv6(hostname)1189    ) {1190      return false;1191    }11921193    return true;1194  } catch {1195    return false;1196  }1197}11981199function isPrivateIpv4(hostname: string): boolean {1200  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1201    return true;1202  }12031204  const octets = hostname.split(".").map((part) => Number(part));1205  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1206    return false;1207  }12081209  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1210}12111212function isPrivateIpv6(hostname: string): boolean {1213  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1214  return (1215    normalized === "::1" ||1216    normalized.startsWith("fc") ||1217    normalized.startsWith("fd") ||1218    normalized.startsWith("fe80:")1219  );1220}