messages.ts

49.8 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard } from "./clipboard";13import { setupAutoLock, touchAutoLock } from "./alarms";14import { 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                  hasPasskey: e.passkey !== undefined,549                }550              : {551                  id: e.id,552                  title: e.title,553                  username: e.username,554                  email: e.email,555                  url: e.url,556                  hasTotp: Boolean(e.totp),557                  hasPasskey: e.passkey !== undefined,558                }559          ),560        };561      }562      case "GET_ENTRY_FOR_FILL": {563        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };564        const { id } = msg.payload as { id: string };565        const entry = vault.getEntryById(id);566        if (!entry) return { ok: false, error: "entry_not_found" };567        // Passkey-only entries (passkey credential, no password) cannot be568        // filled into a form — sign-in goes through the WebAuthn path. A569        // login that ALSO has a passkey is still fillable for its password.570        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };571        // Strip the passkey credential from the response — content scripts572        // never need the private key, and there's no reason to expose the573        // public credential metadata over the boundary either.574        const { passkey: _strippedPasskey, ...safeEntry } = entry;575        return { ok: true, data: safeEntry };576      }577      case "COPY": {578        // AUD-002: shape-validate the payload before passing to the clipboard579        // helper. A raw cast lets a malformed message reach the clipboard API580        // with a non-string and throw.581        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {582          text?: unknown;583          label?: unknown;584          alreadyWritten?: unknown;585        };586        if (typeof text !== "string" || typeof label !== "string") {587          return { ok: false, error: "invalid_payload" };588        }589        await copyToClipboard(text, label, Boolean(alreadyWritten));590        return { ok: true };591      }592      case "CHECK_ALL_BREACHES": {593        const allEntries = vault.getEntries();594        const results: Record<string, number> = {};595        for (const entry of allEntries) {596          if (entry.type === "note") continue;597          if (!entry.password) continue;598          results[entry.id] = await vault.checkBreach(entry.password);599          // Small delay — be a good citizen to the HIBP API600          await new Promise((r) => setTimeout(r, 200));601        }602        // Persist any non-zero counts back to entries603        for (const [id, count] of Object.entries(results)) {604          const entry = vault.getEntryById(id);605          if (entry && (entry.breach ?? 0) !== count) {606            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });607          }608        }609        return { ok: true, data: results };610      }611      case "GET_SETTINGS":612        return { ok: true, data: await vault.ensureSettingsLoaded() };613      case "UPDATE_SETTINGS": {614        const patch = msg.payload;615        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {616          return { ok: false, error: "invalid_payload" };617        }618        await vault.updateSettings(patch as vault.VaultSettings);619        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {620          await setupAutoLock();621          if (vault.isUnlocked()) touchAutoLock();622        }623        return { ok: true };624      }625      case "GET_PENDING_PASSKEY":626        return { ok: true, data: await getPendingPasskeyRequest() };627      case "APPROVE_PASSKEY": {628        const { requestId } = msg.payload as { requestId: number };629        await resolvePendingPasskeyRequest(requestId, true);630        return { ok: true };631      }632      case "DENY_PASSKEY": {633        const { requestId } = msg.payload as { requestId: number };634        await resolvePendingPasskeyRequest(requestId, false);635        return { ok: true };636      }637      case "GET_PASSKEY_PROVIDER_STATE":638        return { ok: true, data: await getPasskeyProviderState() };639      case "SET_PASSKEY_PROVIDER_ENABLED": {640        const { enabled } = msg.payload as { enabled: boolean };641        // Disabling is always free; gating fires only when a free user is642        // trying to turn passkey interception on.643        if (enabled) {644          const gate = await requirePro("passkeys");645          if (!gate.allowed) return { ok: false, error: "pro_required" };646        }647        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };648      }649      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS650      // endpoint. Intentional product behavior — users configure their own651      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private652      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-653      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to654      // users that the entry title leaves the device when the canary fires.655      case "FIRE_CANARY_PING": {656        // Canary alert fires unconditionally for any entry with canary: true.657        // The Pro gate only governs creation/flagging of canary entries; once658        // an entry is flagged, the alert path is a security property and must659        // never be license-gated.660        const { webhookUrl, entryTitle, trigger } = msg.payload as {661          webhookUrl: string;662          entryTitle: string;663          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";664        };665        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {666          return { ok: false, error: "invalid_webhook_url" };667        }668        const body = JSON.stringify({669          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",670          entry: entryTitle,671          trigger,672          timestamp: new Date().toISOString(),673          source: "peach-extension",674        });675        if (trigger === "test") {676          // Permitted outbound fetch: user-configured canary alert endpoint677          // (validated by isAllowedCanaryWebhookUrl above). This is the678          // only non-HIBP outbound call in the extension — see679          // Projects.md §3.7. Test pings are awaited so the UI can show680          // success/failure.681          try {682            const res = await fetch(webhookUrl, {683              method: "POST",684              headers: { "Content-Type": "application/json" },685              body,686            });687            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };688          } catch (err) {689            return { ok: false, error: err instanceof Error ? err.message : "network_error" };690          }691        }692        // Non-test triggers are fire-and-forget693        fetch(webhookUrl, {694          method: "POST",695          headers: { "Content-Type": "application/json" },696          body,697        }).catch(() => {});698        return { ok: true };699      }700      case "ACTIVATE_LICENSE": {701        const { key } = msg.payload as { key: string };702        const licenseInfo = await activateLicense(key);703        return { ok: true, data: licenseInfo };704      }705      case "GET_LICENSE": {706        const licenseInfo = await getLicenseInfo();707        return { ok: true, data: licenseInfo };708      }709      case "GET_LICENSE_KEY": {710        const key = await getLicenseKey();711        return { ok: true, data: key };712      }713      case "DEACTIVATE_LICENSE": {714        await deactivateLicense();715        return { ok: true };716      }717      case "SHOULD_PLAY_CELEBRATION": {718        const should = await shouldPlayCelebration();719        return { ok: true, data: should };720      }721      case "MARK_CELEBRATION_PLAYED": {722        await markCelebrationPlayed();723        return { ok: true };724      }725      case "GET_CODEX_VAULT_DATA": {726        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the727        // popup navigates to the License section without further coordination.728        const gate = await requirePro("codex");729        if (!gate.allowed) return { ok: false, error: "pro_required" };730        return await handleGetCodexVaultData();731      }732      case "ESTIMATE_CODEX_PAGES": {733        const gate = await requirePro("codex");734        if (!gate.allowed) return { ok: false, error: "pro_required" };735        return await handleEstimateCodexPages();736      }737      case "RESTORE_FROM_CODEX": {738        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still739        // be able to restore a vault that was printed by a Pro user.740        // DO NOT add a Pro gate here.741        const payload = msg.payload as CodexRestorePayload;742        return await handleRestoreFromCodex(payload);743      }744      case "OPEN_PRO_GATE": {745        // Content script requests: open popup and navigate to License section.746        const { feature } = (msg.payload ?? {}) as { feature?: string };747        if (chrome.storage.session) {748          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });749        }750        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }751        return { ok: true };752      }753      case "GET_IDENTITIES": {754        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };755        return { ok: true, data: vault.getIdentities() };756      }757      case "TOUCH_AUTO_LOCK": {758        // touchAutoLock() is already called by shouldRefreshAutoLock above;759        // this case just gives the popup a typed message to keep the session alive.760        return { ok: true };761      }762      case "GET_ADVANCED_HEALTH_REPORT": {763        const gate = await requirePro("advanced_health");764        if (!gate.allowed) return { ok: false, error: "pro_required" };765        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };766        const report = await buildAdvancedHealthReport(vault.getEntries());767        return { ok: true, data: report };768      }769      case "IS_DURESS_ENABLED": {770        const enabled = await vault.isDuressEnabled();771        return { ok: true, data: enabled };772      }773      case "SETUP_DURESS": {774        // Single enforcement point for the Duress Vault Pro gate. Free users775        // who somehow reach this handler are rejected here; the popup also776        // pre-checks isPro() to avoid showing the setup form to free users,777        // but server-side is the actual security boundary.778        const gate = await requirePro("duress_vault");779        if (!gate.allowed) return { ok: false, error: "pro_required" };780        // MV3 service workers restart after inactivity, losing the in-memory781        // derived key. Detect this before calling setupDuress so the popup782        // can show a meaningful prompt to re-lock and re-unlock.783        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };784        const { duressPassword } = msg.payload as { duressPassword: string };785        await vault.setupDuress(duressPassword);786        return { ok: true };787      }788      case "DISABLE_DURESS": {789        await vault.disableDuress();790        return { ok: true };791      }792      case "VERIFY_MAIN_PASSWORD": {793        const { password } = msg.payload as { password: string };794        const ok = await vault.verifyMainPassword(password);795        return { ok: true, data: ok };796      }797      case "CHANGE_PASSWORD": {798        const { currentPassword, newPassword } = msg.payload as {799          currentPassword: string;800          newPassword: string;801        };802        const changed = await vault.changePassword(currentPassword, newPassword);803        return changed804          ? { ok: true }805          : { ok: false, error: "incorrect_current_password" };806      }807      case "GET_SITE_PASSWORD_POLICY": {808        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });809        if (!tab?.id) return { ok: true, data: null };810        try {811          const response = await chrome.tabs.sendMessage(tab.id, {812            type: "GET_SITE_PASSWORD_POLICY",813          });814          return (response as MessageResponse) ?? { ok: true, data: null };815        } catch {816          return { ok: true, data: null };817        }818      }819      case "RECORD_MANUAL_SUMMON": {820        const { domain } = msg.payload as { domain: string };821        const settings = vault.getSettings();822        const existing = settings.manualSummonDomains?.[domain];823        const now = Date.now();824        await vault.updateSettings({825          manualSummonDomains: {826            ...settings.manualSummonDomains,827            [domain]: {828              firstSummonedAt: existing?.firstSummonedAt ?? now,829              summonCount: (existing?.summonCount ?? 0) + 1,830              lastSummonedAt: now,831            },832          },833        });834        return { ok: true };835      }836      case "DECLINE_CARD_SAVE": {837        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };838        await vault.declineCardSaveOffer(last4, expMonth, expYear);839        return { ok: true };840      }841      case "IS_CARD_DECLINED": {842        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };843        const declined = await vault.isCardDeclined(last4, expMonth, expYear);844        return { ok: true, data: declined };845      }846      case "INITIATE_FIREFOX_PASSKEY_CREATE": {847        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {848          rpId?: string;849          rpName?: string;850          userName?: string;851          userDisplayName?: string;852        };853        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };854        return await initiateFirefoxPasskeyCreate({855          rpId,856          rpName: rpName ?? rpId,857          userName,858          userDisplayName,859        });860      }861862      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {863        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;864        if (!payload) return { ok: false, error: "missing_payload" };865        return await completeFirefoxPasskeyCreate(payload);866      }867868      case "PASSKEY_OFFER_DECLINE": {869        const { domain } = (msg.payload ?? {}) as { domain?: string };870        if (!domain) return { ok: false, error: "domain_required" };871        await recordPasskeyOfferDecline(domain);872        return { ok: true };873      }874875      case "GET_PASSKEY_OFFER_DECLINED": {876        const { domain } = (msg.payload ?? {}) as { domain?: string };877        if (!domain) return { ok: false, error: "domain_required" };878        return { ok: true, data: await isPasskeyOfferDeclined(domain) };879      }880881      case "PASSKEY_HAS_CREDENTIALS": {882        const payload = msg.payload as {883          rpId?: string;884          allowCredentials?: Array<{ id: string; type?: string }>;885        } | undefined;886        if (!payload?.rpId) return { ok: false, error: "rpid_required" };887        return await handlePasskeyHasCredentials({888          rpId: payload.rpId,889          allowCredentials: payload.allowCredentials ?? [],890        });891      }892893      case "PASSKEY_CREATE": {894        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;895        if (!payload?.rpId || !payload?.userName) {896          return { ok: false, error: "rpid_and_username_required" };897        }898        return await handleFirefoxPasskeyCreate(payload);899      }900901      case "PASSKEY_GET": {902        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;903        if (!payload?.rpId) return { ok: false, error: "rpid_required" };904        return await handleFirefoxPasskeyGet(payload);905      }906907      case "PASSKEY_AUTH_RESPONSE": {908        const { requestId, approved } = (msg.payload ?? {}) as {909          requestId?: string | number;910          approved?: boolean;911        };912        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {913          return { ok: false, error: 'requestId and approved required' };914        }915        await resolvePendingPasskeyRequest(Number(requestId), approved);916        return { ok: true };917      }918919      case "GET_PASSKEY_FOR_DOMAIN": {920        const { domain } = (msg.payload ?? {}) as { domain?: string };921        if (!domain) return { ok: false, error: "domain_required" };922        if (!vault.isUnlocked()) return { ok: true, data: null };923        const match = vault924          .getEntries()925          .find((entry) => entry.passkey?.rpId === domain);926        if (!match || !match.passkey) return { ok: true, data: null };927        // Slim shape — only the fields State 11 needs. Never expose private928        // key material, even though this is locked behind isUnlocked.929        return {930          ok: true,931          data: {932            rpId: match.passkey.rpId,933            userName: match.passkey.userName,934            browser: match.passkey.browser,935          },936        };937      }938939      case "DESTROY_VAULT": {940        // Irreversible by design. Lock zeroes the derived key + in-memory entries;941        // storage.local.clear() wipes every Peach key (slots, settings, license,942        // onboarded flag, history, sync state, declined cards, recall, etc.);943        // session.clear() wipes pending passkey requests + pro-notice queues.944        // Caller (Panic.tsx) handles UI navigation back to onboarding.945        vault.lock();946        await storageClear();947        await vault.clearVaultHistory();948        if (chrome.storage.session) {949          await chrome.storage.session.clear();950        }951        return { ok: true };952      }953954      case "SUBMIT_FEEDBACK": {955        const { category, message, version, browser } = msg.payload as {956          category: string;957          message: string;958          version: string;959          browser: string;960        };961        if (!message.trim()) return { ok: false, error: "message_empty" };962        if (!FEEDBACK_ENDPOINT) return { ok: true };963        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {964          return { ok: false, error: "invalid_feedback_endpoint" };965        }966        try {967          const res = await fetch(FEEDBACK_ENDPOINT, {968            method: "POST",969            headers: { "Content-Type": "application/json" },970            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),971          });972          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };973        } catch (err) {974          return { ok: false, error: err instanceof Error ? err.message : "network_error" };975        }976      }977      // Android-only: biometric unlock with pre-derived key.978      case "UNLOCK_WITH_KEY": {979        const { masterKeyHex } = msg.payload as { masterKeyHex: string };980        if (!isNativePlatform()) {981          return { ok: false, error: "desktop_only_uses_password" };982        }983        try {984          const result = await vault.unlockWithKey(masterKeyHex);985          if (result.ok) {986            onVaultUnlocked();987            await publishInMemoryVault(result.entries);988          }989          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };990        } catch {991          return { ok: false, error: "invalid_key" };992        }993      }994      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.995      case "GET_DERIVED_KEY": {996        if (!isNativePlatform()) {997          return { ok: false, error: "android_only" };998        }999        if (!vault.isUnlocked()) {1000          return { ok: false, error: "vault_locked" };1001        }1002        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1003      }1004      case "GET_IDENTITY_SUGGESTIONS": {1005        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1006        const entries = vault.getEntries();1007        const suggestions = buildIdentitySuggestions(entries);1008        return { ok: true, data: { suggestions } };1009      }1010      case "POPULATE_INLINE_VAULT": {1011        if (!isNativePlatform()) return { ok: false };1012        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1013        const entries = vault.getEntries();1014        await publishInMemoryVault(entries);1015        return { ok: true };1016      }1017      case "ML_INIT":1018        return { ok: true };10191020      case "ML_PREDICT_BATCH": {1021        // AUD-002: shape-validate before forwarding to the ML helper.1022        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1023        if (!Array.isArray(featuresArray)) {1024          return { ok: false, error: "invalid_payload" };1025        }1026        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1027      }10281029      // ── Chirp Sync (v3) ───────────────────────────────────────────────1030      // Returns the public-facing local identity needed by the popup to1031      // drive Phase-1 audio pairing. The private long-term key never1032      // leaves the background.1033      case "CHIRP_GET_LOCAL_IDENTITY": {1034        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1035        const proCheck = await requirePro("sync");1036        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1037        const masterKeyHex = vault.getDerivedKeyHex();1038        const masterKey = unhexBytes(masterKeyHex);1039        try {1040          const identity = await buildLocalIdentity(masterKey);1041          return { ok: true, data: identity };1042        } finally {1043          masterKey.fill(0);1044        }1045      }10461047      case "CHIRP_COMPLETE_PAIRING": {1048        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1049        const proCheck = await requirePro("sync");1050        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1051        const paired = (msg.payload as { paired?: unknown })?.paired;1052        if (typeof paired !== "object" || paired === null) {1053          return { ok: false, error: "invalid_payload" };1054        }1055        const candidate = paired as Record<string, unknown>;1056        if (1057          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1058          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1059          typeof candidate.deviceType !== "string" ||1060          typeof candidate.longTermPublicKeyHex !== "string" ||1061          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1062          (1063            candidate.signingPublicKeyHex !== undefined &&1064            (1065              typeof candidate.signingPublicKeyHex !== "string" ||1066              !/^[0-9a-f]{64}$/.test(candidate.signingPublicKeyHex)1067            )1068          ) ||1069          typeof candidate.pairedAt !== "number"1070        ) {1071          return { ok: false, error: "invalid_paired_device" };1072        }1073        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1074        return { ok: true };1075      }10761077      case "CHIRP_LIST_PAIRED_DEVICES": {1078        const devices = await listPairedDevicesV3();1079        return { ok: true, data: { devices } };1080      }10811082      case "CHIRP_UNPAIR_DEVICE": {1083        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1084        if (typeof deviceId !== "string" || !deviceId) {1085          return { ok: false, error: "invalid_payload" };1086        }1087        await removePairedDeviceByIdV3(deviceId);1088        return { ok: true };1089      }10901091      case "CHIRP_RENAME_LOCAL_DEVICE": {1092        const { name } = (msg.payload ?? {}) as { name?: string };1093        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1094        await setDeviceNameV3(name);1095        return { ok: true };1096      }10971098      case "TRIGGER_SYNC": {1099        const payload = (msg.payload ?? {}) as {1100          reason?: "vault_change" | "foreground" | "manual" | "mdns";1101          force?: boolean;1102          deviceId?: string;1103          discoveredIp?: string;1104          discoveredPort?: number;1105        };1106        const reason = payload.reason ?? "foreground";11071108        // mDNS discovery delivers a fresh (ip, port) resolved by the native1109        // side. Update the cached address before the sync runner tries to1110        // connect — avoids a subnet probe on the very next round.1111        if (1112          reason === "mdns" &&1113          typeof payload.deviceId === "string" &&1114          typeof payload.discoveredIp === "string"1115        ) {1116          const { findPairedDeviceById, setLastKnownIp } = await import("./paired-devices");1117          const device = await findPairedDeviceById(payload.deviceId);1118          if (device?.longTermPublicKeyHex) {1119            await setLastKnownIp(device.longTermPublicKeyHex, payload.discoveredIp).catch(() => undefined);1120          }1121        }11221123        const { triggerSyncIfReachable } = await import("./sync-trigger");1124        void triggerSyncIfReachable({ reason, force: payload.force === true });1125        return { ok: true };1126      }11271128      case "GET_SYNC_STATE": {1129        const { getSyncState } = await import("./sync-trigger");1130        return { ok: true, data: getSyncState() };1131      }11321133      default:1134        return { ok: false, error: "unknown_message_type" };1135    }1136  } catch (err) {1137    return {1138      ok: false,1139      error: err instanceof Error ? err.message : "operation_failed",1140    };1141  }1142}11431144// --- Mobile platform helpers ---11451146// Android: populates the in-memory vault used by PeachAutofillService.1147async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1148  const plugin = nativePlugin<{1149    setEntries?: (args: {1150      entries: Array<{1151        id: string;1152        title: string;1153        username: string;1154        email: string;1155        password: string;1156        url: string;1157        totp: string;1158        additionalUrls: string[];1159      }>;1160    }) => Promise<void>;1161  }>("InMemoryVaultPlugin");1162  if (!plugin?.setEntries) return;1163  await plugin.setEntries({1164    entries: entries.map((e) => ({1165      id: e.id,1166      title: e.title ?? "",1167      username: e.username ?? "",1168      email: (e as VaultEntry & { email?: string }).email ?? "",1169      password: e.password ?? "",1170      url: e.url ?? "",1171      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1172      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1173    })),1174  });1175}11761177// Android: clear the autofill in-memory store on lock.1178async function clearInMemoryVault(): Promise<void> {1179  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1180  if (!plugin?.clearEntries) return;1181  await plugin.clearEntries();1182}11831184// Returns username use-counts from the vault, sorted by frequency. Each row1185// also carries the entry's email so the popup can suggest the email/username1186// pair the user has actually used together.1187function buildIdentitySuggestions(1188  entries: VaultEntry[],1189): Array<{ email: string; username: string; count: number }> {1190  const usernameCounts = new Map<string, number>();1191  const usernameEmail = new Map<string, string>();1192  for (const entry of entries) {1193    const username = entry.username ?? "";1194    const email = (entry as VaultEntry & { email?: string }).email ?? "";1195    if (!username && !email) continue;1196    const key = username || email;1197    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1198    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1199  }1200  return Array.from(usernameCounts.entries())1201    .sort((a, b) => b[1] - a[1])1202    .map(([username, count]) => ({1203      email: usernameEmail.get(username) ?? "",1204      username,1205      count,1206    }));1207}12081209/** Notify all content scripts that the vault just became available. */1210function broadcastToContentScripts(message: { type: string }): void {1211  if (!chrome.tabs?.query) return;1212  chrome.tabs.query({}, (tabs) => {1213    for (const tab of tabs) {1214      if (tab.id !== undefined) {1215        chrome.tabs.sendMessage(tab.id, message).catch(() => {1216          // Tab may not have a content script — silently ignore1217        });1218      }1219    }1220  });1221}12221223function shouldRefreshAutoLock(type: MessageType): boolean {1224  return (1225    type !== "HAS_VAULT" &&1226    type !== "IS_UNLOCKED" &&1227    type !== "GET_VAULT_STATUS" &&1228    type !== "LOCK" &&1229    type !== "UPDATE_SETTINGS" &&1230    type !== "GET_PENDING_PASSKEY" &&1231    type !== "GET_PASSKEY_PROVIDER_STATE" &&1232    type !== "DECLINE_CARD_SAVE" &&1233    type !== "IS_CARD_DECLINED" &&1234    type !== "SUBMIT_FEEDBACK"1235  );1236}12371238function isAllowedCanaryWebhookUrl(value: string): boolean {1239  try {1240    const url = new URL(value);1241    if (url.protocol !== "https:") return false;12421243    const hostname = url.hostname.toLowerCase();1244    if (1245      hostname === "localhost" ||1246      hostname.endsWith(".localhost") ||1247      isPrivateIpv4(hostname) ||1248      isPrivateIpv6(hostname)1249    ) {1250      return false;1251    }12521253    return true;1254  } catch {1255    return false;1256  }1257}12581259function isPrivateIpv4(hostname: string): boolean {1260  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1261    return true;1262  }12631264  const octets = hostname.split(".").map((part) => Number(part));1265  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1266    return false;1267  }12681269  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1270}12711272function isPrivateIpv6(hostname: string): boolean {1273  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1274  return (1275    normalized === "::1" ||1276    normalized.startsWith("fc") ||1277    normalized.startsWith("fd") ||1278    normalized.startsWith("fe80:")1279  );1280}