messages.ts

51.0 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";6566let nativeSyncRunnerBootstrapped = false;6768function unhexBytes(hex: string): Uint8Array {69  if (hex.length % 2 !== 0) throw new Error("invalid hex");70  const out = new Uint8Array(hex.length / 2);71  for (let i = 0; i < out.length; i++) {72    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);73  }74  return out;75}7677/**78 * The single Pro gate. Every gated handler calls this first; the broadcast79 * lets the popup react (navigate to the License section, highlight the80 * relevant feature). Background never touches the popup view directly —81 * the popup owns navigation. See Projects.md "Pro gate rule".82 */83async function requirePro(84  feature: ProFeature,85  trigger: "user" | "background" = "user"86): Promise<{ allowed: boolean }> {87  if (await isProUser()) return { allowed: true };8889  if (trigger === "user") {90    // User deliberately triggered this feature — redirect the popup immediately.91    chrome.runtime92      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })93      .catch(() => {94        // Popup may be closed — the gate signal is best-effort.95      });96  } else {97    // Background trigger (e.g. passive sync initiation) — no popup is open.98    // Queue a notice so the next popup open shows a soft banner instead of99    // silently failing.100    if (chrome.storage.session) {101      chrome.storage.session102        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })103        .catch(() => {});104    }105  }106107  return { allowed: false };108}109110// ---------------------------------------------------------------------------111// Feedback submission target. Empty disables network submission while the UI112// continues to function as a no-op (the handler returns ok:true without113// calling fetch). When set, the URL is validated by114// `isAllowedCanaryWebhookUrl` before any request.115// ---------------------------------------------------------------------------116117const FEEDBACK_ENDPOINT = "";118119const PRIVATE_IPV4_RANGES = [120  { prefix: "10." },121  { prefix: "127." },122  { prefix: "169.254." },123  { prefix: "192.168." },124];125126export function setupMessageHandler(): void {127  chrome.runtime.onMessage.addListener(128    (msg: unknown, sender, sendResponse) => {129      if (!isMessage(msg)) {130        sendResponse({ ok: false, error: "invalid_message" });131        return true;132      }133      handleMessage(msg, sender)134        .then(sendResponse)135        .catch((err) =>136          sendResponse({137            ok: false,138            error: err instanceof Error ? err.message : String(err),139          })140        );141      return true;142    }143  );144145  // Android: the chrome shim queues sendMessage calls until this handler is146  // registered. Without this hookup, every message hangs on Capacitor builds.147  // eslint-disable-next-line @typescript-eslint/no-explicit-any148  const reg = (globalThis as any).__peachRegisterMessageHandler;149  if (typeof reg === "function") {150    reg(async (m: unknown) => {151      if (!isMessage(m)) return { ok: false, error: "invalid_message" };152      try {153        return await handleMessage(m);154      } catch (err) {155        return {156          ok: false,157          error: err instanceof Error ? err.message : String(err),158        };159      }160    });161  }162  if (isNativePlatform()) {163    void bootstrapNativeSyncRunner();164  }165}166167async function bootstrapNativeSyncRunner(): Promise<void> {168  if (nativeSyncRunnerBootstrapped) return;169  nativeSyncRunnerBootstrapped = true;170  try {171    const { setSyncRunner, hydratePersistedSyncState } = await import("./sync-trigger");172    const { productionSyncRunner } = await import("./chirp-sync-runner");173    setSyncRunner(productionSyncRunner);174    await hydratePersistedSyncState();175  } catch (err) {176    nativeSyncRunnerBootstrapped = false;177    console.warn("[Peach] failed to bootstrap native sync runner:", err);178  }179}180181function isMessage(m: unknown): m is Message {182  return typeof m === "object" && m !== null && "type" in m;183}184185export async function handleMessage(186  msg: Message,187  sender: Partial<chrome.runtime.MessageSender> = {}188): Promise<MessageResponse> {189  try {190    // Validate sender — only allow messages from our extension pages/scripts.191    // `sender.id` is undefined for messages originating from extension UI192    // (popup/options), which is legitimate; reject only when it is defined193    // and does not match our extension id.194    if (195      sender.id !== undefined &&196      sender.id !== chrome.runtime.id197    ) {198      return { ok: false, error: "invalid_sender" };199    }200201    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {202      touchAutoLock();203    }204205    switch (msg.type) {206      case "CREATE_VAULT": {207        const { password } = msg.payload as { password: string };208        await vault.createVault(password);209        await setupAutoLock();210        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });211        onVaultUnlocked();212        return { ok: true };213      }214      case "UNLOCK": {215        const { password } = msg.payload as { password: string };216        const ok = await vault.unlock(password);217        if (ok) {218          // KAT: verify the WebCrypto stack is healthy before the user relies on it.219          // Runs after unlock so latency is hidden behind the vault-load time.220          const kat = await runSelfTest();221          if (!kat.ok) {222            console.error("[Peach] Crypto self-test FAILED:", kat.error);223            await vault.lock();224            return { ok: false, error: "self_test_failed" };225          }226          await setupAutoLock();227          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });228          onVaultUnlocked();229          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());230          return { ok: true };231        }232        // Distinguish corruption from wrong password so the popup can offer233        // a history-restore path instead of falsely accusing the user of234        // mistyping (M7/COR-007).235        const failure = vault.consumeLastUnlockFailureReason();236        if (failure) {237          return {238            ok: false,239            error: "vault_corrupted",240            canRestoreFromHistory: true,241          } as MessageResponse;242        }243        return { ok: false };244      }245      case "VALIDATE_RECOVERY_WORDS": {246        const { words } = msg.payload as { words: string[] };247        const invalid = findInvalidWords(words);248        return { ok: true, data: { valid: invalid.length === 0, invalid } };249      }250      case "GET_RECOVERY_WORDS": {251        // Must be unlocked and have recovery set up (vault must be v2.12+).252        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };253        try {254          const words = await vault.getRecoveryWords();255          return { ok: true, data: words };256        } catch (e) {257          // pre-v2.12 vault that hasn't migrated258          return { ok: false, error: "recovery_not_setup" };259        }260      }261      case "RECOVER_WITH_WORDS": {262        // User has lost their password but has their 12 recovery words.263        // We: (1) validate the words, (2) re-encrypt vault with new password.264        const { words, newPassword } = msg.payload as {265          words: string[];266          newPassword: string;267        };268        const stored = await vault.loadSlotA();269        if (!stored) return { ok: false, error: "no_vault" };270        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {271          return { ok: false, error: "recovery_not_setup" };272        }273        // Unwrap the root key from the recovery escrow.274        try {275          await vault.unwrapRootKeyForRecovery(276            stored.recovery_wrapped_root_key,277            stored.recovery_nonce ?? "",278            stored.recovery_tag ?? "",279            stored.recovery_salt,280            words281          );282        } catch {283          return { ok: false, error: "invalid_recovery_words" };284        }285        // Re-key: derive fresh salt + key from new password.286        const newSalt = vault.generateSalt();287        const newKey = await vault.deriveKey(newPassword, newSalt);288        // Re-wrap root key under the new password's derived key so the same289        // recovery words continue to work after the password change.290        await vault.rewrapRootKeyForPassword(newKey, newSalt);291        // Re-encrypt vault entries with the new key.292        await vault.changePasswordWithNewKey(newSalt, newKey);293        await setupAutoLock();294        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });295        return { ok: true };296      }297      case "LOCK":298        vault.lock();299        if (isNativePlatform()) await clearInMemoryVault();300        return { ok: true };301      case "IS_UNLOCKED":302        return { ok: true, data: vault.isUnlocked() };303      case "GET_VAULT_STATUS":304        return { ok: true, unlocked: vault.isUnlocked() };305      case "HAS_VAULT":306        return { ok: true, data: await vault.hasVault() };307      case "GET_ENTRIES":308        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };309        return { ok: true, data: vault.getEntries() };310      case "ADD_ENTRY": {311        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };312        const payload = msg.payload;313        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {314          return { ok: false, error: "invalid_payload" };315        }316        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);317        return { ok: true, data: entry };318      }319      case "BATCH_ADD_ENTRIES": {320        const payload = msg.payload as { entries?: unknown } | null | undefined;321        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {322          return { ok: false, error: "invalid_payload" };323        }324        if (!Array.isArray(payload.entries)) {325          return { ok: false, error: "invalid_payload" };326        }327        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);328        return { ok: true, data: added };329      }330      case "RESTORE_ENTRIES": {331        const payload = msg.payload as332          | { entries?: unknown; mode?: unknown; settings?: unknown }333          | null334          | undefined;335        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {336          return { ok: false, error: "invalid_payload" };337        }338        if (!Array.isArray(payload.entries)) {339          return { ok: false, error: "invalid_payload" };340        }341        if (payload.mode !== "replace" && payload.mode !== "merge") {342          return { ok: false, error: "invalid_payload" };343        }344        const summary = await vault.restoreEntries(345          payload.entries as Parameters<typeof vault.restoreEntries>[0],346          payload.mode347        );348        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {349          await vault.updateSettings(payload.settings as vault.VaultSettings);350        }351        return { ok: true, data: summary };352      }353      case "CLEAR_VAULT_ENTRIES": {354        await vault.clearVaultEntries("REPLACE_ALL");355        return { ok: true };356      }357      case "GET_VAULT_HISTORY": {358        const snapshots = await vault.getVaultHistory();359        return { ok: true, data: snapshots };360      }361      case "RESTORE_VAULT_SNAPSHOT": {362        const { snapshotId } = msg.payload as { snapshotId: string };363        const result = await vault.restoreVaultSnapshot(snapshotId);364        if (!result.ok) return { ok: false, error: result.error };365        broadcastToContentScripts({ type: "VAULT_LOCKED" });366        return { ok: true };367      }368      case "COUNT_DUPLICATES": {369        return { ok: true, data: vault.countDuplicates() };370      }371      case "DEDUPLICATE_ENTRIES": {372        const removed = await vault.deduplicateEntries();373        return { ok: true, data: removed };374      }375      case "UPDATE_ENTRY": {376        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;377        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {378          return { ok: false, error: "invalid_payload" };379        }380        const { id, patch } = payload;381        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {382          return { ok: false, error: "invalid_payload" };383        }384        // Single enforcement point for the Canary Entries Pro gate. Only385        // gates the transition into a canary entry — clearing/disabling a386        // canary (`canary: undefined`) is always allowed, so existing387        // canary entries remain manageable.388        const incomingCanary = (patch as { canary?: unknown }).canary;389        if (incomingCanary && typeof incomingCanary === "object") {390          const existing = vault.getEntryById(id);391          if (!existing?.canary) {392            const gate = await requirePro("canary_entry");393            if (!gate.allowed) return { ok: false, error: "pro_required" };394          }395        }396        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);397        return { ok: true };398      }399      case "ADD_ADDITIONAL_URL": {400        const { id, url } = msg.payload as { id: string; url: string };401        const trimmed = typeof url === "string" ? url.trim() : "";402        if (!trimmed) return { ok: false, error: "url_required" };403        const existing = vault.getEntryById(id);404        if (!existing) return { ok: false, error: "entry_not_found" };405        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };406        const merged = [...(existing.additionalUrls ?? []), trimmed];407        await vault.updateEntry(id, { additionalUrls: merged });408        return { ok: true };409      }410      case "DELETE_ENTRY": {411        const { id } = msg.payload as { id: string };412        await vault.deleteEntry(id);413        return { ok: true };414      }415      case "GET_DELETED_ENTRIES":416        return { ok: true, data: vault.getDeletedEntries() };417      case "RESTORE_ENTRY": {418        const { id } = msg.payload as { id: string };419        await vault.restoreEntry(id);420        return { ok: true };421      }422      case "PURGE_ENTRY": {423        const { id } = msg.payload as { id: string };424        await vault.purgeEntry(id);425        return { ok: true };426      }427      case "PURGE_EXPIRED_TRASH": {428        const { retentionMs } = msg.payload as { retentionMs: number };429        const purged = await vault.purgeExpiredTrash(retentionMs);430        return { ok: true, data: purged };431      }432      case "SAVE_NOTE": {433        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };434        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };435        const now = Date.now();436        if (id) {437          const existing = vault.getEntryById(id);438          if (!existing) return { ok: false, error: "not_found" };439          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });440          return { ok: true, data: vault.getEntryById(id) };441        } else {442          const entry = await vault.addEntry({443            type: "note",444            title: title || "Untitled",445            notes: body,446            createdAt: now,447            modifiedAt: now,448          } as any);449          return { ok: true, data: entry };450        }451      }452      case "DELETE_NOTE": {453        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };454        const { id } = msg.payload as { id: string };455        await vault.deleteEntry(id);456        return { ok: true };457      }458      case "GET_NOTES": {459        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };460        const notes = vault.getEntries().filter(461          (e) => e.type === "note" && !e.deletedAt462        );463        return { ok: true, data: notes } as MessageResponse;464      }465      case "SEARCH_VAULT": {466        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };467        // AUD-002: shape-validate the payload before calling string methods.468        // A raw cast lets a malformed message crash the handler with TypeError.469        const { query } = (msg.payload ?? {}) as { query?: unknown };470        if (typeof query !== "string") {471          return { ok: false, error: "invalid_payload" };472        }473        const q = query.toLowerCase();474        const searchResults = vault.getEntries().filter(475          (e) =>476            !e.deletedAt &&477            (e.title.toLowerCase().includes(q) ||478              e.notes?.toLowerCase().includes(q) ||479              e.username?.toLowerCase().includes(q))480        );481        return { ok: true, data: searchResults } as MessageResponse;482      }483      case "AUTOFILL_QUERY": {484        if (!vault.isUnlocked()) {485          return { ok: false, error: "vault_locked" };486        }487        const { domain, includeAll, kind } = msg.payload as {488          domain: string;489          includeAll?: boolean;490          kind?: "login" | "card" | "totp";491        };492        // kind="card": return saved cards as compact summaries for the493        // inline card silver platter. Cards are not domain-scoped — every494        // saved card is a candidate on every checkout page — so domain is495        // ignored when kind === "card".496        if (kind === "card") {497          const cards = vault.getEntries().filter((e) => e.type === "card");498          return {499            ok: true,500            data: cards.map((e) => ({501              id: e.id,502              title: e.cardNickname || e.title,503              cardholderName: e.cardholderName,504              last4: e.last4,505              expMonth: e.expMonth,506              expYear: e.expYear,507              network: e.network,508            })),509          };510        }511        if (kind === "totp") {512          const matches = (513            includeAll514              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")515              : vault.queryDomain(domain)516          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));517          return {518            ok: true,519            data: matches.map((e) => ({520              id: e.id,521              title: e.title,522              username: e.username,523              email: e.email,524              url: e.url,525              hasTotp: true,526            })),527          };528        }529        // The inline selector fills username+password into a form. Passkey-530        // only entries have no password to fill; sign-in for those goes531        // through the WebAuthn path instead. Filter them out everywhere so532        // the user doesn't see four "GitHub" rows that mostly do nothing.533        // Notes and cards never belonged here either.534        const matches = (535          includeAll536            ? vault537                .getEntries()538                .filter((entry) => entry.type !== "note" && entry.type !== "card")539            : vault.queryDomain(domain)540        ).filter((entry) => !isPasskeyOnly(entry));541        return {542          ok: true,543          data: matches.map((e) =>544            includeAll545              ? {546                  id: e.id,547                  title: e.title,548                  // username/email/url shipped so the inline popup's search549                  // affordance can match on them, not just titles. No secrets550                  // cross the boundary — same shape as the domain-matched551                  // response below minus hasTotp (which the search list552                  // doesn't surface).553                  username: e.username,554                  email: e.email,555                  url: e.url,556                  hasPasskey: e.passkey !== undefined,557                }558              : {559                  id: e.id,560                  title: e.title,561                  username: e.username,562                  email: e.email,563                  url: e.url,564                  hasTotp: Boolean(e.totp),565                  hasPasskey: e.passkey !== undefined,566                }567          ),568        };569      }570      case "GET_ENTRY_FOR_FILL": {571        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };572        const { id } = msg.payload as { id: string };573        const entry = vault.getEntryById(id);574        if (!entry) return { ok: false, error: "entry_not_found" };575        // Passkey-only entries (passkey credential, no password) cannot be576        // filled into a form — sign-in goes through the WebAuthn path. A577        // login that ALSO has a passkey is still fillable for its password.578        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };579        // Strip the passkey credential from the response — content scripts580        // never need the private key, and there's no reason to expose the581        // public credential metadata over the boundary either.582        const { passkey: _strippedPasskey, ...safeEntry } = entry;583        return { ok: true, data: safeEntry };584      }585      case "COPY": {586        // AUD-002: shape-validate the payload before passing to the clipboard587        // helper. A raw cast lets a malformed message reach the clipboard API588        // with a non-string and throw.589        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {590          text?: unknown;591          label?: unknown;592          alreadyWritten?: unknown;593        };594        if (typeof text !== "string" || typeof label !== "string") {595          return { ok: false, error: "invalid_payload" };596        }597        await copyToClipboard(text, label, Boolean(alreadyWritten));598        return { ok: true };599      }600      case "CHECK_ALL_BREACHES": {601        const allEntries = vault.getEntries();602        const results: Record<string, number> = {};603        for (const entry of allEntries) {604          if (entry.type === "note") continue;605          if (!entry.password) continue;606          results[entry.id] = await vault.checkBreach(entry.password);607          // Small delay — be a good citizen to the HIBP API608          await new Promise((r) => setTimeout(r, 200));609        }610        // Persist any non-zero counts back to entries611        for (const [id, count] of Object.entries(results)) {612          const entry = vault.getEntryById(id);613          if (entry && (entry.breach ?? 0) !== count) {614            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });615          }616        }617        return { ok: true, data: results };618      }619      case "GET_SETTINGS":620        return { ok: true, data: await vault.ensureSettingsLoaded() };621      case "UPDATE_SETTINGS": {622        const patch = msg.payload;623        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {624          return { ok: false, error: "invalid_payload" };625        }626        await vault.updateSettings(patch as vault.VaultSettings);627        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {628          await setupAutoLock();629          if (vault.isUnlocked()) touchAutoLock();630        }631        return { ok: true };632      }633      case "GET_PENDING_PASSKEY":634        return { ok: true, data: await getPendingPasskeyRequest() };635      case "APPROVE_PASSKEY": {636        const { requestId } = msg.payload as { requestId: number };637        await resolvePendingPasskeyRequest(requestId, true);638        return { ok: true };639      }640      case "DENY_PASSKEY": {641        const { requestId } = msg.payload as { requestId: number };642        await resolvePendingPasskeyRequest(requestId, false);643        return { ok: true };644      }645      case "GET_PASSKEY_PROVIDER_STATE":646        return { ok: true, data: await getPasskeyProviderState() };647      case "SET_PASSKEY_PROVIDER_ENABLED": {648        const { enabled } = msg.payload as { enabled: boolean };649        // Disabling is always free; gating fires only when a free user is650        // trying to turn passkey interception on.651        if (enabled) {652          const gate = await requirePro("passkeys");653          if (!gate.allowed) return { ok: false, error: "pro_required" };654        }655        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };656      }657      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS658      // endpoint. Intentional product behavior — users configure their own659      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private660      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-661      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to662      // users that the entry title leaves the device when the canary fires.663      case "FIRE_CANARY_PING": {664        // Canary alert fires unconditionally for any entry with canary: true.665        // The Pro gate only governs creation/flagging of canary entries; once666        // an entry is flagged, the alert path is a security property and must667        // never be license-gated.668        const { webhookUrl, entryTitle, trigger } = msg.payload as {669          webhookUrl: string;670          entryTitle: string;671          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";672        };673        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {674          return { ok: false, error: "invalid_webhook_url" };675        }676        const body = JSON.stringify({677          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",678          entry: entryTitle,679          trigger,680          timestamp: new Date().toISOString(),681          source: "peach-extension",682        });683        if (trigger === "test") {684          // Permitted outbound fetch: user-configured canary alert endpoint685          // (validated by isAllowedCanaryWebhookUrl above). This is the686          // only non-HIBP outbound call in the extension — see687          // Projects.md §3.7. Test pings are awaited so the UI can show688          // success/failure.689          try {690            const res = await fetch(webhookUrl, {691              method: "POST",692              headers: { "Content-Type": "application/json" },693              body,694            });695            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };696          } catch (err) {697            return { ok: false, error: err instanceof Error ? err.message : "network_error" };698          }699        }700        // Non-test triggers are fire-and-forget701        fetch(webhookUrl, {702          method: "POST",703          headers: { "Content-Type": "application/json" },704          body,705        }).catch(() => {});706        return { ok: true };707      }708      case "ACTIVATE_LICENSE": {709        const { key } = msg.payload as { key: string };710        const licenseInfo = await activateLicense(key);711        return { ok: true, data: licenseInfo };712      }713      case "GET_LICENSE": {714        const licenseInfo = await getLicenseInfo();715        return { ok: true, data: licenseInfo };716      }717      case "GET_LICENSE_KEY": {718        const key = await getLicenseKey();719        return { ok: true, data: key };720      }721      case "DEACTIVATE_LICENSE": {722        await deactivateLicense();723        return { ok: true };724      }725      case "SHOULD_PLAY_CELEBRATION": {726        const should = await shouldPlayCelebration();727        return { ok: true, data: should };728      }729      case "MARK_CELEBRATION_PLAYED": {730        await markCelebrationPlayed();731        return { ok: true };732      }733      case "GET_CODEX_VAULT_DATA": {734        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the735        // popup navigates to the License section without further coordination.736        const gate = await requirePro("codex");737        if (!gate.allowed) return { ok: false, error: "pro_required" };738        return await handleGetCodexVaultData();739      }740      case "ESTIMATE_CODEX_PAGES": {741        const gate = await requirePro("codex");742        if (!gate.allowed) return { ok: false, error: "pro_required" };743        return await handleEstimateCodexPages();744      }745      case "RESTORE_FROM_CODEX": {746        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still747        // be able to restore a vault that was printed by a Pro user.748        // DO NOT add a Pro gate here.749        const payload = msg.payload as CodexRestorePayload;750        return await handleRestoreFromCodex(payload);751      }752      case "OPEN_PRO_GATE": {753        // Content script requests: open popup and navigate to License section.754        const { feature } = (msg.payload ?? {}) as { feature?: string };755        if (chrome.storage.session) {756          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });757        }758        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }759        return { ok: true };760      }761      case "GET_IDENTITIES": {762        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };763        return { ok: true, data: vault.getIdentities() };764      }765      case "TOUCH_AUTO_LOCK": {766        // touchAutoLock() is already called by shouldRefreshAutoLock above;767        // this case just gives the popup a typed message to keep the session alive.768        return { ok: true };769      }770      case "GET_ADVANCED_HEALTH_REPORT": {771        const gate = await requirePro("advanced_health");772        if (!gate.allowed) return { ok: false, error: "pro_required" };773        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };774        const report = await buildAdvancedHealthReport(vault.getEntries());775        return { ok: true, data: report };776      }777      case "IS_DURESS_ENABLED": {778        const enabled = await vault.isDuressEnabled();779        return { ok: true, data: enabled };780      }781      case "SETUP_DURESS": {782        // Single enforcement point for the Duress Vault Pro gate. Free users783        // who somehow reach this handler are rejected here; the popup also784        // pre-checks isPro() to avoid showing the setup form to free users,785        // but server-side is the actual security boundary.786        const gate = await requirePro("duress_vault");787        if (!gate.allowed) return { ok: false, error: "pro_required" };788        // MV3 service workers restart after inactivity, losing the in-memory789        // derived key. Detect this before calling setupDuress so the popup790        // can show a meaningful prompt to re-lock and re-unlock.791        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };792        const { duressPassword } = msg.payload as { duressPassword: string };793        await vault.setupDuress(duressPassword);794        return { ok: true };795      }796      case "DISABLE_DURESS": {797        await vault.disableDuress();798        return { ok: true };799      }800      case "VERIFY_MAIN_PASSWORD": {801        const { password } = msg.payload as { password: string };802        const ok = await vault.verifyMainPassword(password);803        return { ok: true, data: ok };804      }805      case "CHANGE_PASSWORD": {806        const { currentPassword, newPassword } = msg.payload as {807          currentPassword: string;808          newPassword: string;809        };810        const changed = await vault.changePassword(currentPassword, newPassword);811        return changed812          ? { ok: true }813          : { ok: false, error: "incorrect_current_password" };814      }815      case "GET_SITE_PASSWORD_POLICY": {816        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });817        if (!tab?.id) return { ok: true, data: null };818        try {819          const response = await chrome.tabs.sendMessage(tab.id, {820            type: "GET_SITE_PASSWORD_POLICY",821          });822          return (response as MessageResponse) ?? { ok: true, data: null };823        } catch {824          return { ok: true, data: null };825        }826      }827      case "RECORD_MANUAL_SUMMON": {828        const { domain } = msg.payload as { domain: string };829        const settings = vault.getSettings();830        const existing = settings.manualSummonDomains?.[domain];831        const now = Date.now();832        await vault.updateSettings({833          manualSummonDomains: {834            ...settings.manualSummonDomains,835            [domain]: {836              firstSummonedAt: existing?.firstSummonedAt ?? now,837              summonCount: (existing?.summonCount ?? 0) + 1,838              lastSummonedAt: now,839            },840          },841        });842        return { ok: true };843      }844      case "DECLINE_CARD_SAVE": {845        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };846        await vault.declineCardSaveOffer(last4, expMonth, expYear);847        return { ok: true };848      }849      case "IS_CARD_DECLINED": {850        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };851        const declined = await vault.isCardDeclined(last4, expMonth, expYear);852        return { ok: true, data: declined };853      }854      case "INITIATE_FIREFOX_PASSKEY_CREATE": {855        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {856          rpId?: string;857          rpName?: string;858          userName?: string;859          userDisplayName?: string;860        };861        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };862        return await initiateFirefoxPasskeyCreate({863          rpId,864          rpName: rpName ?? rpId,865          userName,866          userDisplayName,867        });868      }869870      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {871        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;872        if (!payload) return { ok: false, error: "missing_payload" };873        return await completeFirefoxPasskeyCreate(payload);874      }875876      case "PASSKEY_OFFER_DECLINE": {877        const { domain } = (msg.payload ?? {}) as { domain?: string };878        if (!domain) return { ok: false, error: "domain_required" };879        await recordPasskeyOfferDecline(domain);880        return { ok: true };881      }882883      case "GET_PASSKEY_OFFER_DECLINED": {884        const { domain } = (msg.payload ?? {}) as { domain?: string };885        if (!domain) return { ok: false, error: "domain_required" };886        return { ok: true, data: await isPasskeyOfferDeclined(domain) };887      }888889      case "PASSKEY_HAS_CREDENTIALS": {890        const payload = msg.payload as {891          rpId?: string;892          allowCredentials?: Array<{ id: string; type?: string }>;893        } | undefined;894        if (!payload?.rpId) return { ok: false, error: "rpid_required" };895        return await handlePasskeyHasCredentials({896          rpId: payload.rpId,897          allowCredentials: payload.allowCredentials ?? [],898        });899      }900901      case "PASSKEY_CREATE": {902        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;903        if (!payload?.rpId || !payload?.userName) {904          return { ok: false, error: "rpid_and_username_required" };905        }906        return await handleFirefoxPasskeyCreate(payload);907      }908909      case "PASSKEY_GET": {910        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;911        if (!payload?.rpId) return { ok: false, error: "rpid_required" };912        return await handleFirefoxPasskeyGet(payload);913      }914915      case "PASSKEY_AUTH_RESPONSE": {916        const { requestId, approved } = (msg.payload ?? {}) as {917          requestId?: string | number;918          approved?: boolean;919        };920        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {921          return { ok: false, error: 'requestId and approved required' };922        }923        await resolvePendingPasskeyRequest(Number(requestId), approved);924        return { ok: true };925      }926927      case "GET_PASSKEY_FOR_DOMAIN": {928        const { domain } = (msg.payload ?? {}) as { domain?: string };929        if (!domain) return { ok: false, error: "domain_required" };930        if (!vault.isUnlocked()) return { ok: true, data: null };931        const match = vault932          .getEntries()933          .find((entry) => entry.passkey?.rpId === domain);934        if (!match || !match.passkey) return { ok: true, data: null };935        // Slim shape — only the fields State 11 needs. Never expose private936        // key material, even though this is locked behind isUnlocked.937        return {938          ok: true,939          data: {940            rpId: match.passkey.rpId,941            userName: match.passkey.userName,942            browser: match.passkey.browser,943          },944        };945      }946947      case "DESTROY_VAULT": {948        // Irreversible by design. Lock zeroes the derived key + in-memory entries;949        // storage.local.clear() wipes every Peach key (slots, settings, license,950        // onboarded flag, history, sync state, declined cards, recall, etc.);951        // session.clear() wipes pending passkey requests + pro-notice queues.952        // Caller (Panic.tsx) handles UI navigation back to onboarding.953        //954        // The Pro license is the one thing that must survive: the user paid for955        // it, and destroying a vault (panic wipe, fresh start) is not a refund.956        // Capture it before the clear and restore it after. peach_pro_celebrated957        // rides along so the Pro celebration doesn't replay on the next unlock.958        const preserved = await chrome.storage.local.get([959          "peach_license",960          "peach_pro_celebrated",961        ]);962        vault.lock();963        await storageClear();964        await vault.clearVaultHistory();965        const toRestore: Record<string, unknown> = {};966        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;967        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;968        if (Object.keys(toRestore).length > 0) {969          await chrome.storage.local.set(toRestore);970        }971        if (chrome.storage.session) {972          await chrome.storage.session.clear();973        }974        return { ok: true };975      }976977      case "SUBMIT_FEEDBACK": {978        const { category, message, version, browser } = msg.payload as {979          category: string;980          message: string;981          version: string;982          browser: string;983        };984        if (!message.trim()) return { ok: false, error: "message_empty" };985        if (!FEEDBACK_ENDPOINT) return { ok: true };986        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {987          return { ok: false, error: "invalid_feedback_endpoint" };988        }989        try {990          const res = await fetch(FEEDBACK_ENDPOINT, {991            method: "POST",992            headers: { "Content-Type": "application/json" },993            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),994          });995          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };996        } catch (err) {997          return { ok: false, error: err instanceof Error ? err.message : "network_error" };998        }999      }1000      // Android-only: biometric unlock with pre-derived key.1001      case "UNLOCK_WITH_KEY": {1002        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1003        if (!isNativePlatform()) {1004          return { ok: false, error: "desktop_only_uses_password" };1005        }1006        try {1007          const result = await vault.unlockWithKey(masterKeyHex);1008          if (result.ok) {1009            onVaultUnlocked();1010            await publishInMemoryVault(result.entries);1011          }1012          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1013        } catch {1014          return { ok: false, error: "invalid_key" };1015        }1016      }1017      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1018      case "GET_DERIVED_KEY": {1019        if (!isNativePlatform()) {1020          return { ok: false, error: "android_only" };1021        }1022        if (!vault.isUnlocked()) {1023          return { ok: false, error: "vault_locked" };1024        }1025        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1026      }1027      case "GET_IDENTITY_SUGGESTIONS": {1028        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1029        const entries = vault.getEntries();1030        const suggestions = buildIdentitySuggestions(entries);1031        return { ok: true, data: { suggestions } };1032      }1033      case "POPULATE_INLINE_VAULT": {1034        if (!isNativePlatform()) return { ok: false };1035        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1036        const entries = vault.getEntries();1037        await publishInMemoryVault(entries);1038        return { ok: true };1039      }1040      case "ML_INIT":1041        return { ok: true };10421043      case "ML_PREDICT_BATCH": {1044        // AUD-002: shape-validate before forwarding to the ML helper.1045        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1046        if (!Array.isArray(featuresArray)) {1047          return { ok: false, error: "invalid_payload" };1048        }1049        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1050      }10511052      // ── Chirp Sync (v3) ───────────────────────────────────────────────1053      // Returns the public-facing local identity needed by the popup to1054      // drive Phase-1 audio pairing. The private long-term key never1055      // leaves the background.1056      case "CHIRP_GET_LOCAL_IDENTITY": {1057        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1058        const proCheck = await requirePro("sync");1059        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1060        const masterKeyHex = vault.getDerivedKeyHex();1061        const masterKey = unhexBytes(masterKeyHex);1062        try {1063          const identity = await buildLocalIdentity(masterKey);1064          return { ok: true, data: identity };1065        } finally {1066          masterKey.fill(0);1067        }1068      }10691070      case "CHIRP_COMPLETE_PAIRING": {1071        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1072        const proCheck = await requirePro("sync");1073        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1074        const paired = (msg.payload as { paired?: unknown })?.paired;1075        if (typeof paired !== "object" || paired === null) {1076          return { ok: false, error: "invalid_payload" };1077        }1078        const candidate = paired as Record<string, unknown>;1079        if (1080          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1081          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1082          typeof candidate.deviceType !== "string" ||1083          typeof candidate.longTermPublicKeyHex !== "string" ||1084          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1085          (1086            candidate.signingPublicKeyHex !== undefined &&1087            (1088              typeof candidate.signingPublicKeyHex !== "string" ||1089              !/^[0-9a-f]{64}$/.test(candidate.signingPublicKeyHex)1090            )1091          ) ||1092          typeof candidate.pairedAt !== "number"1093        ) {1094          return { ok: false, error: "invalid_paired_device" };1095        }1096        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1097        return { ok: true };1098      }10991100      case "CHIRP_LIST_PAIRED_DEVICES": {1101        const devices = await listPairedDevicesV3();1102        return { ok: true, data: { devices } };1103      }11041105      case "CHIRP_UNPAIR_DEVICE": {1106        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1107        if (typeof deviceId !== "string" || !deviceId) {1108          return { ok: false, error: "invalid_payload" };1109        }1110        await removePairedDeviceByIdV3(deviceId);1111        return { ok: true };1112      }11131114      case "CHIRP_RENAME_LOCAL_DEVICE": {1115        const { name } = (msg.payload ?? {}) as { name?: string };1116        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1117        await setDeviceNameV3(name);1118        return { ok: true };1119      }11201121      case "TRIGGER_SYNC": {1122        const payload = (msg.payload ?? {}) as {1123          reason?: "vault_change" | "foreground" | "manual" | "mdns";1124          force?: boolean;1125          deviceId?: string;1126          discoveredIp?: string;1127          discoveredPort?: number;1128        };1129        const reason = payload.reason ?? "foreground";11301131        // mDNS discovery delivers a fresh (ip, port) resolved by the native1132        // side. Update the cached address before the sync runner tries to1133        // connect — avoids a subnet probe on the very next round.1134        if (1135          reason === "mdns" &&1136          typeof payload.deviceId === "string" &&1137          typeof payload.discoveredIp === "string"1138        ) {1139          const { findPairedDeviceById, setLastKnownIp } = await import("./paired-devices");1140          const device = await findPairedDeviceById(payload.deviceId);1141          if (device?.longTermPublicKeyHex) {1142            await setLastKnownIp(device.longTermPublicKeyHex, payload.discoveredIp).catch(() => undefined);1143          }1144        }11451146        const { triggerSyncIfReachable } = await import("./sync-trigger");1147        void triggerSyncIfReachable({ reason, force: payload.force === true });1148        return { ok: true };1149      }11501151      case "GET_SYNC_STATE": {1152        const { getSyncState } = await import("./sync-trigger");1153        return { ok: true, data: getSyncState() };1154      }11551156      default:1157        return { ok: false, error: "unknown_message_type" };1158    }1159  } catch (err) {1160    return {1161      ok: false,1162      error: err instanceof Error ? err.message : "operation_failed",1163    };1164  }1165}11661167// --- Mobile platform helpers ---11681169// Android: populates the in-memory vault used by PeachAutofillService.1170async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1171  const plugin = nativePlugin<{1172    setEntries?: (args: {1173      entries: Array<{1174        id: string;1175        title: string;1176        username: string;1177        email: string;1178        password: string;1179        url: string;1180        totp: string;1181        additionalUrls: string[];1182      }>;1183    }) => Promise<void>;1184  }>("InMemoryVaultPlugin");1185  if (!plugin?.setEntries) return;1186  await plugin.setEntries({1187    entries: entries.map((e) => ({1188      id: e.id,1189      title: e.title ?? "",1190      username: e.username ?? "",1191      email: (e as VaultEntry & { email?: string }).email ?? "",1192      password: e.password ?? "",1193      url: e.url ?? "",1194      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1195      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1196    })),1197  });1198}11991200// Android: clear the autofill in-memory store on lock.1201async function clearInMemoryVault(): Promise<void> {1202  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1203  if (!plugin?.clearEntries) return;1204  await plugin.clearEntries();1205}12061207// Returns username use-counts from the vault, sorted by frequency. Each row1208// also carries the entry's email so the popup can suggest the email/username1209// pair the user has actually used together.1210function buildIdentitySuggestions(1211  entries: VaultEntry[],1212): Array<{ email: string; username: string; count: number }> {1213  const usernameCounts = new Map<string, number>();1214  const usernameEmail = new Map<string, string>();1215  for (const entry of entries) {1216    const username = entry.username ?? "";1217    const email = (entry as VaultEntry & { email?: string }).email ?? "";1218    if (!username && !email) continue;1219    const key = username || email;1220    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1221    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1222  }1223  return Array.from(usernameCounts.entries())1224    .sort((a, b) => b[1] - a[1])1225    .map(([username, count]) => ({1226      email: usernameEmail.get(username) ?? "",1227      username,1228      count,1229    }));1230}12311232/** Notify all content scripts that the vault just became available. */1233function broadcastToContentScripts(message: { type: string }): void {1234  if (!chrome.tabs?.query) return;1235  chrome.tabs.query({}, (tabs) => {1236    for (const tab of tabs) {1237      if (tab.id !== undefined) {1238        chrome.tabs.sendMessage(tab.id, message).catch(() => {1239          // Tab may not have a content script — silently ignore1240        });1241      }1242    }1243  });1244}12451246function shouldRefreshAutoLock(type: MessageType): boolean {1247  return (1248    type !== "HAS_VAULT" &&1249    type !== "IS_UNLOCKED" &&1250    type !== "GET_VAULT_STATUS" &&1251    type !== "LOCK" &&1252    type !== "UPDATE_SETTINGS" &&1253    type !== "GET_PENDING_PASSKEY" &&1254    type !== "GET_PASSKEY_PROVIDER_STATE" &&1255    type !== "DECLINE_CARD_SAVE" &&1256    type !== "IS_CARD_DECLINED" &&1257    type !== "SUBMIT_FEEDBACK"1258  );1259}12601261function isAllowedCanaryWebhookUrl(value: string): boolean {1262  try {1263    const url = new URL(value);1264    if (url.protocol !== "https:") return false;12651266    const hostname = url.hostname.toLowerCase();1267    if (1268      hostname === "localhost" ||1269      hostname.endsWith(".localhost") ||1270      isPrivateIpv4(hostname) ||1271      isPrivateIpv6(hostname)1272    ) {1273      return false;1274    }12751276    return true;1277  } catch {1278    return false;1279  }1280}12811282function isPrivateIpv4(hostname: string): boolean {1283  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1284    return true;1285  }12861287  const octets = hostname.split(".").map((part) => Number(part));1288  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1289    return false;1290  }12911292  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1293}12941295function isPrivateIpv6(hostname: string): boolean {1296  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1297  return (1298    normalized === "::1" ||1299    normalized.startsWith("fc") ||1300    normalized.startsWith("fd") ||1301    normalized.startsWith("fe80:")1302  );1303}