messages.ts

65.1 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 { getPendingSyncAlerts, clearPendingSyncAlerts } from "./sync-alerts";14import { extractDomain } from "../shared/domain";15import {16  getPendingVouchedDevice,17  listPendingVouchedDevices,18  removePendingVouchedDevice,19} from "./pending-vouched-devices";20import { isRecoveryConfirmPending } from "./recovery-pending";21import { setupAutoLock, touchAutoLock } from "./alarms";22import { runSelfTest } from "./self-test";23import * as vault from "./vault";24import {25  handleEstimateCodexPages,26  handleGetCodexVaultData,27  handleRestoreFromCodex,28} from "./codex-handlers";29import type { CodexRestorePayload } from "../shared/codex-types";30import {31  activateLicense,32  deactivateLicense,33  getLicenseInfo,34  getLicenseKey,35  isProUser,36  markCelebrationPlayed,37  shouldPlayCelebration,38} from "./license";39import {40  completeFirefoxPasskeyCreate,41  getPasskeyProviderState,42  getPendingPasskeyRequest,43  handleFirefoxPasskeyCreate,44  handleFirefoxPasskeyGet,45  handlePasskeyHasCredentials,46  initiateFirefoxPasskeyCreate,47  isPasskeyOfferDeclined,48  onVaultUnlocked,49  recordPasskeyOfferDecline,50  resolvePendingPasskeyRequest,51  setPasskeyProviderEnabled,52} from "./passkey";53import { buildAdvancedHealthReport } from "./health";54import { storageClear } from "../shared/storage";55import { findInvalidWords } from "../shared/recovery-words";56import type {57  Message,58  MessageResponse,59  MessageType,60  ProFeature,61  VaultEntry,62} from "../shared/types";63import { isPasskeyOnly } from "../shared/types";64import { generateTOTP } from "../crypto/totp";65import { isValidRpId } from "../shared/passkey-utils";66import { isNativePlatform, nativePlugin } from "../shared/native";67import { predictBatch as mlPredictBatch } from "./ml";68import type { MLFieldFeatures } from "../shared/ml";69import { buildLocalIdentity, setDeviceName as setDeviceNameV3 } from "./chirp-identity";70import {71  listPairedDevices as listPairedDevicesV3,72  removePairedDeviceById as removePairedDeviceByIdV3,73  upsertPairedDevice as upsertPairedDeviceV3,74} from "./paired-devices";7576// Compile-time E2E flag, folded to a literal by Vite's `define` (false in77// every production build — verified in the bundled output). Mirrors the78// create-path bypass in passkey.ts so the Playwright passkey smoke can enable79// the provider without a real Pro licence; the gate is fully intact for users.80declare const __PEACH_E2E_PASSKEYS__: boolean;81const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true;8283let nativeSyncRunnerBootstrapped = false;8485function unhexBytes(hex: string): Uint8Array {86  if (hex.length % 2 !== 0) throw new Error("invalid hex");87  const out = new Uint8Array(hex.length / 2);88  for (let i = 0; i < out.length; i++) {89    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);90  }91  return out;92}9394/**95 * The single Pro gate. Every gated handler calls this first; the broadcast96 * lets the popup react (navigate to the License section, highlight the97 * relevant feature). Background never touches the popup view directly —98 * the popup owns navigation. See Projects.md "Pro gate rule".99 */100async function requirePro(101  feature: ProFeature,102  trigger: "user" | "background" = "user"103): Promise<{ allowed: boolean }> {104  if (PASSKEY_E2E_PRO_BYPASS && feature === "passkeys") return { allowed: true };105  if (await isProUser()) return { allowed: true };106107  if (trigger === "user") {108    // User deliberately triggered this feature — redirect the popup immediately.109    chrome.runtime110      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })111      .catch(() => {112        // Popup may be closed — the gate signal is best-effort.113      });114  } else {115    // Background trigger (e.g. passive sync initiation) — no popup is open.116    // Queue a notice so the next popup open shows a soft banner instead of117    // silently failing.118    if (chrome.storage.session) {119      chrome.storage.session120        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })121        .catch(() => {});122    }123  }124125  return { allowed: false };126}127128// ---------------------------------------------------------------------------129// Feedback submission target. Empty disables network submission while the UI130// continues to function as a no-op (the handler returns ok:true without131// calling fetch). When set, the URL is validated by132// `isAllowedCanaryWebhookUrl` before any request.133// ---------------------------------------------------------------------------134135const FEEDBACK_ENDPOINT = "";136137// LV-3: minimum interval between non-test canary pings per webhook+entry.138const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour139140const PRIVATE_IPV4_RANGES = [141  { prefix: "10." },142  { prefix: "127." },143  { prefix: "169.254." },144  { prefix: "192.168." },145];146147export function setupMessageHandler(): void {148  chrome.runtime.onMessage.addListener(149    (msg: unknown, sender, sendResponse) => {150      if (!isMessage(msg)) {151        sendResponse({ ok: false, error: "invalid_message" });152        return true;153      }154      handleMessage(msg, sender)155        .then(sendResponse)156        .catch((err) =>157          sendResponse({158            ok: false,159            error: err instanceof Error ? err.message : String(err),160          })161        );162      return true;163    }164  );165166  // Android: the chrome shim queues sendMessage calls until this handler is167  // registered. Without this hookup, every message hangs on Capacitor builds.168  // eslint-disable-next-line @typescript-eslint/no-explicit-any169  const reg = (globalThis as any).__peachRegisterMessageHandler;170  if (typeof reg === "function") {171    reg(async (m: unknown) => {172      if (!isMessage(m)) return { ok: false, error: "invalid_message" };173      try {174        return await handleMessage(m);175      } catch (err) {176        return {177          ok: false,178          error: err instanceof Error ? err.message : String(err),179        };180      }181    });182  }183  if (isNativePlatform()) {184    void bootstrapNativeSyncRunner();185  }186}187188async function bootstrapNativeSyncRunner(): Promise<void> {189  if (nativeSyncRunnerBootstrapped) return;190  nativeSyncRunnerBootstrapped = true;191  try {192    const { setSyncRunner, hydratePersistedSyncState } = await import("./sync-trigger");193    const { productionSyncRunner } = await import("./chirp-sync-runner");194    setSyncRunner(productionSyncRunner);195    await hydratePersistedSyncState();196  } catch (err) {197    nativeSyncRunnerBootstrapped = false;198    console.warn("[Peach] failed to bootstrap native sync runner:", err);199  }200}201202function isMessage(m: unknown): m is Message {203  return typeof m === "object" && m !== null && "type" in m;204}205206/**207 * The browser-attested origin of the page that originated this message. A web208 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),209 * so every page-driven message arrives via the content-script relay and the210 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a211 * value the page cannot forge. This is the ONLY trustworthy origin for passkey212 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.213 */214function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {215  if (sender.origin) return sender.origin;216  if (sender.url) {217    try { return new URL(sender.url).origin; } catch { return undefined; }218  }219  return undefined;220}221222// Resolves once restoreFromSession() has run, so handlers see the correct223// post-restore unlock state. entry.ts registers this BEFORE the message224// handler so the onMessage listener is added synchronously at SW startup225// (MV3 requirement) while unlock-dependent handlers still wait for restore.226let restoreReady: Promise<void> = Promise.resolve();227228/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */229export function setRestoreReady(p: Promise<unknown>): void {230  restoreReady = p.then(() => undefined, () => undefined);231}232233export async function handleMessage(234  msg: Message,235  sender: Partial<chrome.runtime.MessageSender> = {}236): Promise<MessageResponse> {237  try {238    // Wait for session-restore to finish before reading any unlock/vault state.239    // On a cold SW start the popup's first message arrives while restore is240    // still in flight; without this gate IS_UNLOCKED would report locked (a241    // spurious lock screen) and the storage reads could race. The onMessage242    // listener itself is registered synchronously (entry.ts) so this gate, not243    // listener registration, is what absorbs the cold-start window.244    await restoreReady;245    // Validate sender — only allow messages from our extension pages/scripts.246    // `sender.id` is undefined for messages originating from extension UI247    // (popup/options), which is legitimate; reject only when it is defined248    // and does not match our extension id.249    if (250      sender.id !== undefined &&251      sender.id !== chrome.runtime.id252    ) {253      return { ok: false, error: "invalid_sender" };254    }255256    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {257      touchAutoLock();258    }259260    switch (msg.type) {261      case "CREATE_VAULT": {262        const { password } = msg.payload as { password: string };263        // Refuse to create a vault under an empty master password — the derived264        // key would be publicly known and the at-rest AES-GCM protection void265        // (audit HIGH; the CSV-import path previously passed ""). Length/strength266        // policy lives in the onboarding UI; this is the non-negotiable floor.267        if (typeof password !== "string" || password.length === 0) {268          return { ok: false, error: "invalid_payload" };269        }270        await vault.createVault(password);271        await setupAutoLock();272        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });273        onVaultUnlocked();274        return { ok: true };275      }276      case "UNLOCK": {277        const { password } = msg.payload as { password: string };278        const ok = await vault.unlock(password);279        if (ok) {280          // KAT: verify the WebCrypto stack is healthy before the user relies on it.281          // Runs after unlock so latency is hidden behind the vault-load time.282          const kat = await runSelfTest();283          if (!kat.ok) {284            console.error("[Peach] Crypto self-test FAILED:", kat.error);285            await vault.lock();286            return { ok: false, error: "self_test_failed" };287          }288          await setupAutoLock();289          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });290          onVaultUnlocked();291          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());292          return { ok: true };293        }294        // Distinguish corruption from wrong password so the popup can offer295        // a history-restore path instead of falsely accusing the user of296        // mistyping (M7/COR-007).297        const failure = vault.consumeLastUnlockFailureReason();298        if (failure) {299          return {300            ok: false,301            error: "vault_corrupted",302            canRestoreFromHistory: true,303          } as MessageResponse;304        }305        return { ok: false };306      }307      case "VALIDATE_RECOVERY_WORDS": {308        const { words } = msg.payload as { words: string[] };309        const invalid = findInvalidWords(words);310        return { ok: true, data: { valid: invalid.length === 0, invalid } };311      }312      case "GET_RECOVERY_WORDS": {313        // Must be unlocked and have recovery set up (vault must be v2.12+).314        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };315        // LV-4: the recovery words re-derive the ROOT KEY — the highest-316        // value secret in the vault. A session unlock (which may be hours317        // old on a shared machine) is not enough; require a fresh password318        // proof, matching the 1Password/Bitwarden pattern for revealing319        // escrow material. EXEMPTION: the create-vault / rotation confirmation320        // window (peach_recovery_pending) shows the words immediately after321        // the user authenticated, and that confirmation UI has no password to322        // resend — skip the re-auth there only.323        if (!(await isRecoveryConfirmPending())) {324          const { password } = (msg.payload ?? {}) as { password?: string };325          if (typeof password !== "string" || !password) {326            return { ok: false, error: "password_required" };327          }328          if (!(await vault.verifyMainPassword(password))) {329            return { ok: false, error: "wrong_password" };330          }331        }332        try {333          const words = await vault.getRecoveryWords();334          return { ok: true, data: words };335        } catch (e) {336          // pre-v2.12 vault that hasn't migrated337          return { ok: false, error: "recovery_not_setup" };338        }339      }340      case "RECOVER_WITH_WORDS": {341        // User has lost their password but has their 12 recovery words.342        // We: (1) validate the words, (2) re-encrypt vault with new password.343        const { words, newPassword } = msg.payload as {344          words: string[];345          newPassword: string;346        };347        const stored = await vault.loadSlotA();348        if (!stored) return { ok: false, error: "no_vault" };349        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {350          return { ok: false, error: "recovery_not_setup" };351        }352        // Unwrap the root key from the recovery escrow.353        try {354          await vault.unwrapRootKeyForRecovery(355            stored.recovery_wrapped_root_key,356            stored.recovery_nonce ?? "",357            stored.recovery_tag ?? "",358            stored.recovery_salt,359            words360          );361        } catch {362          return { ok: false, error: "invalid_recovery_words" };363        }364        // Re-key: derive fresh salt + key from new password.365        const newSalt = vault.generateSalt();366        const newKey = await vault.deriveKey(newPassword, newSalt);367        // Re-wrap root key under the new password's derived key so the same368        // recovery words continue to work after the password change.369        await vault.rewrapRootKeyForPassword(newKey, newSalt);370        // Re-encrypt vault entries with the new key.371        await vault.changePasswordWithNewKey(newSalt, newKey);372        await setupAutoLock();373        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });374        return { ok: true };375      }376      case "LOCK":377        vault.lock();378        if (isNativePlatform()) await clearInMemoryVault();379        return { ok: true };380      case "IS_UNLOCKED":381        return { ok: true, data: vault.isUnlocked() };382      case "GET_VAULT_STATUS":383        return { ok: true, unlocked: vault.isUnlocked() };384      case "HAS_VAULT":385        return { ok: true, data: await vault.hasVault() };386      case "GET_ENTRIES":387        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };388        return { ok: true, data: vault.getEntries() };389      case "ADD_ENTRY": {390        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };391        const payload = msg.payload;392        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {393          return { ok: false, error: "invalid_payload" };394        }395        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);396        return { ok: true, data: entry };397      }398      case "BATCH_ADD_ENTRIES": {399        const payload = msg.payload as { entries?: unknown } | null | undefined;400        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {401          return { ok: false, error: "invalid_payload" };402        }403        if (!Array.isArray(payload.entries)) {404          return { ok: false, error: "invalid_payload" };405        }406        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);407        return { ok: true, data: added };408      }409      case "RESTORE_ENTRIES": {410        const payload = msg.payload as411          | { entries?: unknown; mode?: unknown; settings?: unknown }412          | null413          | undefined;414        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {415          return { ok: false, error: "invalid_payload" };416        }417        if (!Array.isArray(payload.entries)) {418          return { ok: false, error: "invalid_payload" };419        }420        if (payload.mode !== "replace" && payload.mode !== "merge") {421          return { ok: false, error: "invalid_payload" };422        }423        const summary = await vault.restoreEntries(424          payload.entries as Parameters<typeof vault.restoreEntries>[0],425          payload.mode426        );427        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {428          await vault.updateSettings(payload.settings as vault.VaultSettings);429        }430        return { ok: true, data: summary };431      }432      case "CLEAR_VAULT_ENTRIES": {433        await vault.clearVaultEntries("REPLACE_ALL");434        return { ok: true };435      }436      case "GET_VAULT_HISTORY": {437        const snapshots = await vault.getVaultHistory();438        return { ok: true, data: snapshots };439      }440      case "RESTORE_VAULT_SNAPSHOT": {441        const { snapshotId } = msg.payload as { snapshotId: string };442        const result = await vault.restoreVaultSnapshot(snapshotId);443        if (!result.ok) return { ok: false, error: result.error };444        broadcastToContentScripts({ type: "VAULT_LOCKED" });445        return { ok: true };446      }447      case "COUNT_DUPLICATES": {448        return { ok: true, data: vault.countDuplicates() };449      }450      case "DEDUPLICATE_ENTRIES": {451        const removed = await vault.deduplicateEntries();452        return { ok: true, data: removed };453      }454      case "UPDATE_ENTRY": {455        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;456        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {457          return { ok: false, error: "invalid_payload" };458        }459        const { id, patch } = payload;460        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {461          return { ok: false, error: "invalid_payload" };462        }463        // Single enforcement point for the Canary Entries Pro gate. Only464        // gates the transition into a canary entry — clearing/disabling a465        // canary (`canary: undefined`) is always allowed, so existing466        // canary entries remain manageable.467        const incomingCanary = (patch as { canary?: unknown }).canary;468        if (incomingCanary && typeof incomingCanary === "object") {469          const existing = vault.getEntryById(id);470          if (!existing?.canary) {471            const gate = await requirePro("canary_entry");472            if (!gate.allowed) return { ok: false, error: "pro_required" };473          }474        }475        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);476        return { ok: true };477      }478      case "ADD_ADDITIONAL_URL": {479        const { id, url } = msg.payload as { id: string; url: string };480        const trimmed = typeof url === "string" ? url.trim() : "";481        if (!trimmed) return { ok: false, error: "url_required" };482        const existing = vault.getEntryById(id);483        if (!existing) return { ok: false, error: "entry_not_found" };484        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };485        const merged = [...(existing.additionalUrls ?? []), trimmed];486        await vault.updateEntry(id, { additionalUrls: merged });487        return { ok: true };488      }489      case "DELETE_ENTRY": {490        const { id } = msg.payload as { id: string };491        await vault.deleteEntry(id);492        return { ok: true };493      }494      case "GET_DELETED_ENTRIES":495        return { ok: true, data: vault.getDeletedEntries() };496      case "RESTORE_ENTRY": {497        const { id } = msg.payload as { id: string };498        await vault.restoreEntry(id);499        return { ok: true };500      }501      case "PURGE_ENTRY": {502        const { id } = msg.payload as { id: string };503        await vault.purgeEntry(id);504        return { ok: true };505      }506      case "PURGE_EXPIRED_TRASH": {507        const { retentionMs } = msg.payload as { retentionMs: number };508        const purged = await vault.purgeExpiredTrash(retentionMs);509        return { ok: true, data: purged };510      }511      case "SAVE_NOTE": {512        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };513        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };514        const now = Date.now();515        if (id) {516          const existing = vault.getEntryById(id);517          if (!existing) return { ok: false, error: "not_found" };518          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });519          return { ok: true, data: vault.getEntryById(id) };520        } else {521          const entry = await vault.addEntry({522            type: "note",523            title: title || "Untitled",524            notes: body,525            createdAt: now,526            modifiedAt: now,527          } as any);528          return { ok: true, data: entry };529        }530      }531      case "DELETE_NOTE": {532        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };533        const { id } = msg.payload as { id: string };534        await vault.deleteEntry(id);535        return { ok: true };536      }537      case "GET_NOTES": {538        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };539        const notes = vault.getEntries().filter(540          (e) => e.type === "note" && !e.deletedAt541        );542        return { ok: true, data: notes } as MessageResponse;543      }544      case "SEARCH_VAULT": {545        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };546        // AUD-002: shape-validate the payload before calling string methods.547        // A raw cast lets a malformed message crash the handler with TypeError.548        const { query } = (msg.payload ?? {}) as { query?: unknown };549        if (typeof query !== "string") {550          return { ok: false, error: "invalid_payload" };551        }552        const q = query.toLowerCase();553        const searchResults = vault.getEntries().filter(554          (e) =>555            !e.deletedAt &&556            (e.title.toLowerCase().includes(q) ||557              e.notes?.toLowerCase().includes(q) ||558              e.username?.toLowerCase().includes(q))559        );560        return { ok: true, data: searchResults } as MessageResponse;561      }562      case "AUTOFILL_QUERY": {563        if (!vault.isUnlocked()) {564          return { ok: false, error: "vault_locked" };565        }566        let { includeAll } = msg.payload as { includeAll?: boolean };567        const { domain, kind, userGesture } = msg.payload as {568          domain: string;569          kind?: "login" | "card" | "totp";570          userGesture?: boolean;571        };572        // MV-2: the vault-wide inventory (every title/username/email/url)573        // may only leave the background on an explicit user gesture — the574        // user opening the search affordance — never on passive form focus.575        // userGesture is self-declared by our own content script; the value576        // of this gate is that PASSIVE code paths (which never set it)577        // cannot ship the inventory, shrinking what a compromised page that578        // merely triggers focus events can observe.579        if (includeAll && userGesture !== true) {580          includeAll = false;581        }582        // kind="card": return saved cards as compact summaries for the583        // inline card silver platter. Cards are not domain-scoped — every584        // saved card is a candidate on every checkout page — so domain is585        // ignored when kind === "card".586        if (kind === "card") {587          const cards = vault.getEntries().filter((e) => e.type === "card");588          return {589            ok: true,590            data: cards.map((e) => ({591              id: e.id,592              title: e.cardNickname || e.title,593              cardholderName: e.cardholderName,594              last4: e.last4,595              expMonth: e.expMonth,596              expYear: e.expYear,597              network: e.network,598            })),599          };600        }601        if (kind === "totp") {602          const matches = (603            includeAll604              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")605              : vault.queryDomain(domain)606          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));607          return {608            ok: true,609            data: matches.map((e) => ({610              id: e.id,611              title: e.title,612              username: e.username,613              email: e.email,614              url: e.url,615              hasTotp: true,616            })),617          };618        }619        // The inline selector fills username+password into a form. Passkey-620        // only entries have no password to fill; sign-in for those goes621        // through the WebAuthn path instead. Filter them out everywhere so622        // the user doesn't see four "GitHub" rows that mostly do nothing.623        // Notes and cards never belonged here either.624        const matches = (625          includeAll626            ? vault627                .getEntries()628                .filter((entry) => entry.type !== "note" && entry.type !== "card")629            : vault.queryDomain(domain)630        ).filter((entry) => !isPasskeyOnly(entry));631        return {632          ok: true,633          data: matches.map((e) =>634            includeAll635              ? {636                  id: e.id,637                  title: e.title,638                  // username/email/url shipped so the inline popup's search639                  // affordance can match on them, not just titles. No secrets640                  // cross the boundary — same shape as the domain-matched641                  // response below minus hasTotp (which the search list642                  // doesn't surface).643                  username: e.username,644                  email: e.email,645                  url: e.url,646                  hasPasskey: e.passkey !== undefined,647                }648              : {649                  id: e.id,650                  title: e.title,651                  username: e.username,652                  email: e.email,653                  url: e.url,654                  hasTotp: Boolean(e.totp),655                  hasPasskey: e.passkey !== undefined,656                }657          ),658        };659      }660      case "GET_ENTRY_FOR_FILL": {661        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };662        const { id, explicitSummon } = msg.payload as {663          id: string;664          explicitSummon?: boolean;665        };666        const entry = vault.getEntryById(id);667        if (!entry) return { ok: false, error: "entry_not_found" };668        // Passkey-only entries (passkey credential, no password) cannot be669        // filled into a form — sign-in goes through the WebAuthn path. A670        // login that ALSO has a passkey is still fillable for its password.671        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };672673        // MV-1: re-validate the entry against the requesting tab's origin.674        // sender.tab.url is browser-attested — a page cannot forge it. When675        // the request does not come from a tab at all (popup surfaces use676        // GET_ENTRY_FOR_EDIT, not this), refuse.677        if (sender.tab !== undefined || sender.url !== undefined) {678          let senderDomain: string | null = null;679          try {680            const rawUrl = sender.tab?.url ?? sender.url ?? "";681            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;682          } catch {683            senderDomain = null;684          }685          if (!senderDomain) return { ok: false, error: "origin_unverified" };686687          const entryDomains = new Set<string>();688          const primary = extractDomain(entry.url ?? "");689          if (primary) entryDomains.add(primary);690          for (const extra of entry.additionalUrls ?? []) {691            const d = extractDomain(extra);692            if (d) entryDomains.add(d);693          }694695          // explicitSummon=true means the user actively picked this entry696          // from the cross-domain search affordance — an intentional697          // off-domain fill. Passive fill paths must stay domain-bound.698          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {699            // Domain mismatch — refuse silently (no oracle about which ids exist).700            return { ok: false, error: "entry_not_found" };701          }702        }703        // Strip the passkey credential AND the raw base32 TOTP seed from the704        // response. Content scripts never need either: the private key is the705        // authenticator's, and handing over the TOTP seed would let a706        // compromised content script mint valid codes indefinitely (SEV-3-C).707        // Generate the *current* 6-digit code here in the background and send708        // only that, plus the seconds left so the UI can render a countdown.709        // Also drop passwordHistory: filling needs only the *current* password.710        // Handing every past password to a content script during passive711        // autofill on an arbitrary page would widen the blast radius of a712        // compromised page far beyond the one credential being filled.713        const { passkey: _strippedPasskey, totp: seed, passwordHistory: _ph, ...safeEntry } = entry;714        let totpCode: string | undefined;715        let totpRemaining: number | undefined;716        if (seed) {717          try {718            const generated = generateTOTP(seed);719            totpCode = generated.code;720            totpRemaining = generated.remaining;721          } catch {722            totpCode = undefined;723          }724        }725        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };726      }727      // Trusted full-entry fetch for Peach's own inline-popup surfaces that728      // genuinely need the raw TOTP seed: the edit form (which re-saves the729      // seed and would otherwise wipe it) and nothing else. Unlike730      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside731      // the inline popup, never during passive autofill on an arbitrary page.732      // The passkey credential is still stripped — the edit form never touches it.733      case "GET_ENTRY_FOR_EDIT": {734        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };735        const { id, explicitSummon } = msg.payload as {736          id: string;737          explicitSummon?: boolean;738        };739        const entry = vault.getEntryById(id);740        if (!entry) return { ok: false, error: "entry_not_found" };741742        // PCH-01-006: re-validate the browser-attested sender origin, mirroring743        // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and744        // full password history — at least as sensitive as the fill response — so745        // the boundary must be enforced here, not only by UI reachability. Today746        // the sole caller is the popup (no sender.tab, so this is a structural747        // no-op), but a future tab-context caller or an id leak would otherwise748        // inherit a full-credential oracle. Unlike the fill path we SKIP (not749        // refuse) when no sender domain resolves, to keep the popup caller working.750        if (sender.tab !== undefined || sender.url !== undefined) {751          let senderDomain: string | null = null;752          try {753            const rawUrl = sender.tab?.url ?? sender.url ?? "";754            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;755          } catch {756            senderDomain = null;757          }758          if (senderDomain) {759            const entryDomains = new Set<string>();760            const primary = extractDomain(entry.url ?? "");761            if (primary) entryDomains.add(primary);762            for (const extra of entry.additionalUrls ?? []) {763              const d = extractDomain(extra);764              if (d) entryDomains.add(d);765            }766            if (explicitSummon !== true && !entryDomains.has(senderDomain)) {767              return { ok: false, error: "entry_not_found" }; // no id oracle768            }769          }770        }771772        const { passkey: _passkey, ...safeEntry } = entry;773        return { ok: true, data: safeEntry };774      }775      case "COPY": {776        // AUD-002: shape-validate the payload before passing to the clipboard777        // helper. A raw cast lets a malformed message reach the clipboard API778        // with a non-string and throw.779        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {780          text?: unknown;781          label?: unknown;782          alreadyWritten?: unknown;783        };784        if (typeof text !== "string" || typeof label !== "string") {785          return { ok: false, error: "invalid_payload" };786        }787        await copyToClipboard(text, label, Boolean(alreadyWritten));788        return { ok: true };789      }790      case "CHECK_ALL_BREACHES": {791        const allEntries = vault.getEntries();792        const results: Record<string, number> = {};793        for (const entry of allEntries) {794          if (entry.type === "note") continue;795          if (!entry.password) continue;796          results[entry.id] = await vault.checkBreach(entry.password);797          // Small delay — be a good citizen to the HIBP API798          await new Promise((r) => setTimeout(r, 200));799        }800        // Persist any non-zero counts back to entries801        for (const [id, count] of Object.entries(results)) {802          const entry = vault.getEntryById(id);803          if (entry && (entry.breach ?? 0) !== count) {804            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });805          }806        }807        return { ok: true, data: results };808      }809      case "GET_SETTINGS":810        return { ok: true, data: await vault.ensureSettingsLoaded() };811      case "UPDATE_SETTINGS": {812        const patch = msg.payload;813        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {814          return { ok: false, error: "invalid_payload" };815        }816        await vault.updateSettings(patch as vault.VaultSettings);817        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {818          await setupAutoLock();819          if (vault.isUnlocked()) touchAutoLock();820        }821        return { ok: true };822      }823      case "GET_PENDING_PASSKEY":824        return { ok: true, data: await getPendingPasskeyRequest() };825      case "APPROVE_PASSKEY": {826        const { requestId } = msg.payload as { requestId: number };827        await resolvePendingPasskeyRequest(requestId, true);828        return { ok: true };829      }830      case "DENY_PASSKEY": {831        const { requestId } = msg.payload as { requestId: number };832        await resolvePendingPasskeyRequest(requestId, false);833        return { ok: true };834      }835      case "GET_PASSKEY_PROVIDER_STATE":836        return { ok: true, data: await getPasskeyProviderState() };837      case "SET_PASSKEY_PROVIDER_ENABLED": {838        const { enabled } = msg.payload as { enabled: boolean };839        // Disabling is always free; gating fires only when a free user is840        // trying to turn passkey interception on.841        if (enabled) {842          const gate = await requirePro("passkeys");843          if (!gate.allowed) return { ok: false, error: "pro_required" };844        }845        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };846      }847      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS848      // endpoint. Intentional product behavior — users configure their own849      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private850      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-851      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to852      // users that the entry title leaves the device when the canary fires.853      case "FIRE_CANARY_PING": {854        // Canary alert fires unconditionally for any entry with canary: true.855        // The Pro gate only governs creation/flagging of canary entries; once856        // an entry is flagged, the alert path is a security property and must857        // never be license-gated.858        const { webhookUrl, entryTitle, trigger } = msg.payload as {859          webhookUrl: string;860          entryTitle: string;861          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";862        };863        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {864          return { ok: false, error: "invalid_webhook_url" };865        }866        // LV-3: debounce non-test pings per (webhook, entry) so a page that867        // strobes focus/fill events can't turn the canary into a request868        // firehose at the user's endpoint. Test pings are exempt — they are869        // explicit user clicks in the settings UI and are awaited for870        // feedback. The FIRST ping in a window always goes out, so the871        // dead-man's-switch property (canary fires on access) is preserved;872        // only repeats within the window are coalesced.873        if (trigger !== "test") {874          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;875          const stored = await chrome.storage.local.get(rlKey);876          const last = (stored as Record<string, unknown>)[rlKey];877          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {878            return { ok: true, data: { rateLimited: true } };879          }880          await chrome.storage.local.set({ [rlKey]: Date.now() });881        }882        const body = JSON.stringify({883          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",884          entry: entryTitle,885          trigger,886          timestamp: new Date().toISOString(),887          source: "peach-extension",888        });889        if (trigger === "test") {890          // Permitted outbound fetch: user-configured canary alert endpoint891          // (validated by isAllowedCanaryWebhookUrl above). This is the892          // only non-HIBP outbound call in the extension — see893          // Projects.md §3.7. Test pings are awaited so the UI can show894          // success/failure.895          try {896            const res = await fetch(webhookUrl, {897              method: "POST",898              headers: { "Content-Type": "application/json" },899              body,900            });901            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };902          } catch (err) {903            return { ok: false, error: err instanceof Error ? err.message : "network_error" };904          }905        }906        // Non-test triggers are fire-and-forget907        fetch(webhookUrl, {908          method: "POST",909          headers: { "Content-Type": "application/json" },910          body,911        }).catch(() => {});912        return { ok: true };913      }914      case "ACTIVATE_LICENSE": {915        const { key } = msg.payload as { key: string };916        const licenseInfo = await activateLicense(key);917        return { ok: true, data: licenseInfo };918      }919      case "GET_LICENSE": {920        const licenseInfo = await getLicenseInfo();921        return { ok: true, data: licenseInfo };922      }923      case "GET_LICENSE_KEY": {924        const key = await getLicenseKey();925        return { ok: true, data: key };926      }927      case "DEACTIVATE_LICENSE": {928        await deactivateLicense();929        return { ok: true };930      }931      case "SHOULD_PLAY_CELEBRATION": {932        const should = await shouldPlayCelebration();933        return { ok: true, data: should };934      }935      case "MARK_CELEBRATION_PLAYED": {936        await markCelebrationPlayed();937        return { ok: true };938      }939      case "GET_CODEX_VAULT_DATA": {940        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the941        // popup navigates to the License section without further coordination.942        const gate = await requirePro("codex");943        if (!gate.allowed) return { ok: false, error: "pro_required" };944        return await handleGetCodexVaultData();945      }946      case "ESTIMATE_CODEX_PAGES": {947        const gate = await requirePro("codex");948        if (!gate.allowed) return { ok: false, error: "pro_required" };949        return await handleEstimateCodexPages();950      }951      case "RESTORE_FROM_CODEX": {952        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still953        // be able to restore a vault that was printed by a Pro user.954        // DO NOT add a Pro gate here.955        const payload = msg.payload as CodexRestorePayload;956        return await handleRestoreFromCodex(payload);957      }958      case "OPEN_PRO_GATE": {959        // Content script requests: open popup and navigate to License section.960        const { feature } = (msg.payload ?? {}) as { feature?: string };961        if (chrome.storage.session) {962          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });963        }964        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }965        return { ok: true };966      }967      case "OPEN_POPUP": {968        // Content script asks to open the trusted extension popup — used by the969        // inline locked bubble so the master password is entered in the popup,970        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a971        // user gesture + Chrome 127+/Firefox; on failure the user clicks the972        // toolbar icon. The badge already signals Peach needs attention.973        //974        // Set a session flag so the popup knows it was opened for inline unlock975        // and should close itself once the vault is unlocked (returning the user976        // to the inline autofill selector on the page).977        if (chrome.storage.session) {978          await chrome.storage.session.set({ peach_inline_unlock: true });979        }980        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }981        return { ok: true };982      }983      case "GET_IDENTITIES": {984        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };985        return { ok: true, data: vault.getIdentities() };986      }987      case "TOUCH_AUTO_LOCK": {988        // touchAutoLock() is already called by shouldRefreshAutoLock above;989        // this case just gives the popup a typed message to keep the session alive.990        return { ok: true };991      }992      case "GET_ADVANCED_HEALTH_REPORT": {993        const gate = await requirePro("advanced_health");994        if (!gate.allowed) return { ok: false, error: "pro_required" };995        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };996        const report = await buildAdvancedHealthReport(vault.getEntries());997        return { ok: true, data: report };998      }999      case "IS_DURESS_ENABLED": {1000        const enabled = await vault.isDuressEnabled();1001        return { ok: true, data: enabled };1002      }1003      case "SETUP_DURESS": {1004        // Single enforcement point for the Duress Vault Pro gate. Free users1005        // who somehow reach this handler are rejected here; the popup also1006        // pre-checks isPro() to avoid showing the setup form to free users,1007        // but server-side is the actual security boundary.1008        const gate = await requirePro("duress_vault");1009        if (!gate.allowed) return { ok: false, error: "pro_required" };1010        // MV3 service workers restart after inactivity, losing the in-memory1011        // derived key. Detect this before calling setupDuress so the popup1012        // can show a meaningful prompt to re-lock and re-unlock.1013        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1014        const { duressPassword } = msg.payload as { duressPassword: string };1015        await vault.setupDuress(duressPassword);1016        return { ok: true };1017      }1018      case "DISABLE_DURESS": {1019        await vault.disableDuress();1020        return { ok: true };1021      }1022      case "VERIFY_MAIN_PASSWORD": {1023        const { password } = msg.payload as { password: string };1024        const ok = await vault.verifyMainPassword(password);1025        return { ok: true, data: ok };1026      }1027      case "CHANGE_PASSWORD": {1028        const { currentPassword, newPassword } = msg.payload as {1029          currentPassword: string;1030          newPassword: string;1031        };1032        const changed = await vault.changePassword(currentPassword, newPassword);1033        return changed1034          ? { ok: true }1035          : { ok: false, error: "incorrect_current_password" };1036      }1037      case "GET_SITE_PASSWORD_POLICY": {1038        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1039        if (!tab?.id) return { ok: true, data: null };1040        try {1041          const response = await chrome.tabs.sendMessage(tab.id, {1042            type: "GET_SITE_PASSWORD_POLICY",1043          });1044          return (response as MessageResponse) ?? { ok: true, data: null };1045        } catch {1046          return { ok: true, data: null };1047        }1048      }1049      case "RECORD_MANUAL_SUMMON": {1050        const { domain } = msg.payload as { domain: string };1051        const settings = vault.getSettings();1052        const existing = settings.manualSummonDomains?.[domain];1053        const now = Date.now();1054        await vault.updateSettings({1055          manualSummonDomains: {1056            ...settings.manualSummonDomains,1057            [domain]: {1058              firstSummonedAt: existing?.firstSummonedAt ?? now,1059              summonCount: (existing?.summonCount ?? 0) + 1,1060              lastSummonedAt: now,1061            },1062          },1063        });1064        return { ok: true };1065      }1066      case "DECLINE_CARD_SAVE": {1067        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1068        await vault.declineCardSaveOffer(last4, expMonth, expYear);1069        return { ok: true };1070      }1071      case "IS_CARD_DECLINED": {1072        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1073        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1074        return { ok: true, data: declined };1075      }1076      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1077        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1078          rpId?: string;1079          rpName?: string;1080          userName?: string;1081          userDisplayName?: string;1082        };1083        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1084        return await initiateFirefoxPasskeyCreate({1085          rpId,1086          rpName: rpName ?? rpId,1087          userName,1088          userDisplayName,1089        });1090      }10911092      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1093        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1094        if (!payload) return { ok: false, error: "missing_payload" };1095        return await completeFirefoxPasskeyCreate(payload);1096      }10971098      case "PASSKEY_OFFER_DECLINE": {1099        const { domain } = (msg.payload ?? {}) as { domain?: string };1100        if (!domain) return { ok: false, error: "domain_required" };1101        await recordPasskeyOfferDecline(domain);1102        return { ok: true };1103      }11041105      case "GET_PASSKEY_OFFER_DECLINED": {1106        const { domain } = (msg.payload ?? {}) as { domain?: string };1107        if (!domain) return { ok: false, error: "domain_required" };1108        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1109      }11101111      case "PASSKEY_HAS_CREDENTIALS": {1112        const payload = msg.payload as {1113          rpId?: string;1114          allowCredentials?: Array<{ id: string; type?: string }>;1115        } | undefined;1116        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1117        return await handlePasskeyHasCredentials({1118          rpId: payload.rpId,1119          allowCredentials: payload.allowCredentials ?? [],1120        }, attestedSenderOrigin(sender));1121      }11221123      case "PASSKEY_CREATE": {1124        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1125        if (!payload?.rpId || !payload?.userName) {1126          return { ok: false, error: "rpid_and_username_required" };1127        }1128        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1129      }11301131      case "PASSKEY_GET": {1132        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1133        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1134        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1135      }11361137      case "PASSKEY_AUTH_RESPONSE": {1138        const { requestId, approved } = (msg.payload ?? {}) as {1139          requestId?: string | number;1140          approved?: boolean;1141        };1142        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1143          return { ok: false, error: 'requestId and approved required' };1144        }1145        await resolvePendingPasskeyRequest(Number(requestId), approved);1146        return { ok: true };1147      }11481149      case "GET_PASSKEY_FOR_DOMAIN": {1150        const { domain } = (msg.payload ?? {}) as { domain?: string };1151        if (!domain) return { ok: false, error: "domain_required" };1152        // Scope to the caller's own origin: a page may only ask about passkeys1153        // for a domain it actually owns, so an arbitrary page cannot enumerate1154        // which sites the user holds passkeys for or read the username (audit MEDIUM).1155        const origin = attestedSenderOrigin(sender);1156        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1157        if (!vault.isUnlocked()) return { ok: true, data: null };1158        const match = vault1159          .getEntries()1160          .find((entry) => entry.passkey?.rpId === domain);1161        if (!match || !match.passkey) return { ok: true, data: null };1162        // Slim shape — only the fields State 11 needs. Never expose private1163        // key material, even though this is locked behind isUnlocked.1164        return {1165          ok: true,1166          data: {1167            rpId: match.passkey.rpId,1168            userName: match.passkey.userName,1169            browser: match.passkey.browser,1170          },1171        };1172      }11731174      case "DESTROY_VAULT": {1175        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1176        // storage.local.clear() wipes every Peach key (slots, settings, license,1177        // onboarded flag, history, sync state, declined cards, recall, etc.);1178        // session.clear() wipes pending passkey requests + pro-notice queues.1179        // Caller (Panic.tsx) handles UI navigation back to onboarding.1180        //1181        // The Pro license is the one thing that must survive: the user paid for1182        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1183        // Capture it before the clear and restore it after. peach_pro_celebrated1184        // rides along so the Pro celebration doesn't replay on the next unlock.1185        const preserved = await chrome.storage.local.get([1186          "peach_license",1187          "peach_pro_celebrated",1188        ]);1189        vault.lock();1190        await storageClear();1191        await vault.clearVaultHistory();1192        const toRestore: Record<string, unknown> = {};1193        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1194        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1195        if (Object.keys(toRestore).length > 0) {1196          await chrome.storage.local.set(toRestore);1197        }1198        if (chrome.storage.session) {1199          await chrome.storage.session.clear();1200        }1201        return { ok: true };1202      }12031204      case "SUBMIT_FEEDBACK": {1205        const { category, message, version, browser } = msg.payload as {1206          category: string;1207          message: string;1208          version: string;1209          browser: string;1210        };1211        if (!message.trim()) return { ok: false, error: "message_empty" };1212        if (!FEEDBACK_ENDPOINT) return { ok: true };1213        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1214          return { ok: false, error: "invalid_feedback_endpoint" };1215        }1216        try {1217          const res = await fetch(FEEDBACK_ENDPOINT, {1218            method: "POST",1219            headers: { "Content-Type": "application/json" },1220            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1221          });1222          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1223        } catch (err) {1224          return { ok: false, error: err instanceof Error ? err.message : "network_error" };1225        }1226      }1227      // Android-only: biometric unlock with pre-derived key.1228      case "UNLOCK_WITH_KEY": {1229        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1230        if (!isNativePlatform()) {1231          return { ok: false, error: "desktop_only_uses_password" };1232        }1233        try {1234          const result = await vault.unlockWithKey(masterKeyHex);1235          if (result.ok) {1236            onVaultUnlocked();1237            await publishInMemoryVault(result.entries);1238          }1239          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1240        } catch {1241          return { ok: false, error: "invalid_key" };1242        }1243      }1244      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1245      case "GET_DERIVED_KEY": {1246        if (!isNativePlatform()) {1247          return { ok: false, error: "android_only" };1248        }1249        if (!vault.isUnlocked()) {1250          return { ok: false, error: "vault_locked" };1251        }1252        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1253      }1254      case "GET_IDENTITY_SUGGESTIONS": {1255        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1256        const entries = vault.getEntries();1257        const suggestions = buildIdentitySuggestions(entries);1258        return { ok: true, data: { suggestions } };1259      }1260      case "POPULATE_INLINE_VAULT": {1261        if (!isNativePlatform()) return { ok: false };1262        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1263        const entries = vault.getEntries();1264        await publishInMemoryVault(entries);1265        return { ok: true };1266      }1267      case "ML_INIT":1268        return { ok: true };12691270      case "ML_PREDICT_BATCH": {1271        // AUD-002: shape-validate before forwarding to the ML helper.1272        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1273        if (!Array.isArray(featuresArray)) {1274          return { ok: false, error: "invalid_payload" };1275        }1276        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1277      }12781279      // ── Chirp Sync (v3) ───────────────────────────────────────────────1280      // Returns the public-facing local identity needed by the popup to1281      // drive Phase-1 audio pairing. The private long-term key never1282      // leaves the background.1283      case "CHIRP_GET_LOCAL_IDENTITY": {1284        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1285        const proCheck = await requirePro("sync");1286        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1287        // Identity derives from the stable root key, not the password-derived1288        // key, so pairing survives a master-password change (SEV-2-B).1289        const masterKeyHex = vault.getRootKeyHex();1290        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1291        const masterKey = unhexBytes(masterKeyHex);1292        try {1293          const identity = await buildLocalIdentity(masterKey);1294          return { ok: true, data: identity };1295        } finally {1296          masterKey.fill(0);1297        }1298      }12991300      case "CHIRP_COMPLETE_PAIRING": {1301        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1302        const proCheck = await requirePro("sync");1303        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1304        const paired = (msg.payload as { paired?: unknown })?.paired;1305        if (typeof paired !== "object" || paired === null) {1306          return { ok: false, error: "invalid_payload" };1307        }1308        const candidate = paired as Record<string, unknown>;1309        if (1310          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1311          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1312          typeof candidate.deviceType !== "string" ||1313          typeof candidate.longTermPublicKeyHex !== "string" ||1314          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1315          (1316            candidate.signingPublicKeyHex !== undefined &&1317            (1318              typeof candidate.signingPublicKeyHex !== "string" ||1319              !/^[0-9a-f]{64}$/.test(candidate.signingPublicKeyHex)1320            )1321          ) ||1322          typeof candidate.pairedAt !== "number"1323        ) {1324          return { ok: false, error: "invalid_paired_device" };1325        }1326        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1327        return { ok: true };1328      }13291330      case "CHIRP_LIST_PAIRED_DEVICES": {1331        const devices = await listPairedDevicesV3();1332        return { ok: true, data: { devices } };1333      }13341335      case "CHIRP_UNPAIR_DEVICE": {1336        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1337        if (typeof deviceId !== "string" || !deviceId) {1338          return { ok: false, error: "invalid_payload" };1339        }1340        await removePairedDeviceByIdV3(deviceId);1341        return { ok: true };1342      }13431344      case "CHIRP_RENAME_LOCAL_DEVICE": {1345        const { name } = (msg.payload ?? {}) as { name?: string };1346        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1347        await setDeviceNameV3(name);1348        return { ok: true };1349      }13501351      case "TRIGGER_SYNC": {1352        const payload = (msg.payload ?? {}) as {1353          reason?: "vault_change" | "foreground" | "manual" | "mdns";1354          force?: boolean;1355          deviceId?: string;1356          discoveredIp?: string;1357          discoveredPort?: number;1358        };1359        const reason = payload.reason ?? "foreground";13601361        // mDNS discovery delivers a fresh (ip, port) resolved by the native1362        // side. Update the cached address before the sync runner tries to1363        // connect — avoids a subnet probe on the very next round.1364        if (1365          reason === "mdns" &&1366          typeof payload.deviceId === "string" &&1367          typeof payload.discoveredIp === "string"1368        ) {1369          const { findPairedDeviceById, setLastKnownIp } = await import("./paired-devices");1370          const device = await findPairedDeviceById(payload.deviceId);1371          if (device?.longTermPublicKeyHex) {1372            await setLastKnownIp(device.longTermPublicKeyHex, payload.discoveredIp).catch(() => undefined);1373          }1374        }13751376        const { triggerSyncIfReachable } = await import("./sync-trigger");1377        void triggerSyncIfReachable({ reason, force: payload.force === true });1378        return { ok: true };1379      }13801381      case "GET_SYNC_STATE": {1382        const { getSyncState } = await import("./sync-trigger");1383        return { ok: true, data: getSyncState() };1384      }13851386      case "GET_SYNC_ALERTS": {1387        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1388        const alerts = await getPendingSyncAlerts();1389        // The popup reads on open and acknowledges with consume:true after1390        // rendering, so a popup crash between read and render doesn't lose1391        // the alerts.1392        if (consume) await clearPendingSyncAlerts();1393        return { ok: true, data: alerts };1394      }13951396      case "GET_PENDING_VOUCHED_DEVICES": {1397        return { ok: true, data: await listPendingVouchedDevices() };1398      }1399      case "CONFIRM_VOUCHED_DEVICE": {1400        const { deviceId } = msg.payload as { deviceId: string };1401        const pending = await getPendingVouchedDevice(deviceId);1402        if (!pending) return { ok: false, error: "not_pending" };1403        await upsertPairedDeviceV3({1404          deviceId: pending.deviceId,1405          deviceName: pending.deviceName,1406          deviceType:1407            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1408          longTermPublicKeyHex: pending.longTermPublicKeyHex,1409          signingPublicKeyHex: pending.signingPublicKeyHex,1410          wsPort: pending.wsPort,1411          pairedAt: pending.pairedAt,1412          trustSource: "vouched",1413        });1414        await removePendingVouchedDevice(deviceId);1415        return { ok: true };1416      }1417      case "REJECT_VOUCHED_DEVICE": {1418        const { deviceId } = msg.payload as { deviceId: string };1419        await removePendingVouchedDevice(deviceId);1420        return { ok: true };1421      }1422      case "ROTATE_SYNC_IDENTITY": {1423        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1424        const result = await vault.rotateSyncIdentity();1425        return result.ok ? { ok: true } : { ok: false, error: result.error };1426      }14271428      default:1429        return { ok: false, error: "unknown_message_type" };1430    }1431  } catch (err) {1432    return {1433      ok: false,1434      error: err instanceof Error ? err.message : "operation_failed",1435    };1436  }1437}14381439// --- Mobile platform helpers ---14401441// Android: populates the in-memory vault used by PeachAutofillService.1442async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1443  const plugin = nativePlugin<{1444    setEntries?: (args: {1445      entries: Array<{1446        id: string;1447        title: string;1448        username: string;1449        email: string;1450        password: string;1451        url: string;1452        totp: string;1453        additionalUrls: string[];1454      }>;1455    }) => Promise<void>;1456  }>("InMemoryVaultPlugin");1457  if (!plugin?.setEntries) return;1458  await plugin.setEntries({1459    entries: entries.map((e) => ({1460      id: e.id,1461      title: e.title ?? "",1462      username: e.username ?? "",1463      email: (e as VaultEntry & { email?: string }).email ?? "",1464      password: e.password ?? "",1465      url: e.url ?? "",1466      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1467      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1468    })),1469  });1470}14711472// Android: clear the autofill in-memory store on lock.1473async function clearInMemoryVault(): Promise<void> {1474  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1475  if (!plugin?.clearEntries) return;1476  await plugin.clearEntries();1477}14781479// Returns username use-counts from the vault, sorted by frequency. Each row1480// also carries the entry's email so the popup can suggest the email/username1481// pair the user has actually used together.1482function buildIdentitySuggestions(1483  entries: VaultEntry[],1484): Array<{ email: string; username: string; count: number }> {1485  const usernameCounts = new Map<string, number>();1486  const usernameEmail = new Map<string, string>();1487  for (const entry of entries) {1488    const username = entry.username ?? "";1489    const email = (entry as VaultEntry & { email?: string }).email ?? "";1490    if (!username && !email) continue;1491    const key = username || email;1492    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1493    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1494  }1495  return Array.from(usernameCounts.entries())1496    .sort((a, b) => b[1] - a[1])1497    .map(([username, count]) => ({1498      email: usernameEmail.get(username) ?? "",1499      username,1500      count,1501    }));1502}15031504/** Notify all content scripts that the vault just became available. */1505function broadcastToContentScripts(message: { type: string }): void {1506  if (!chrome.tabs?.query) return;1507  chrome.tabs.query({}, (tabs) => {1508    for (const tab of tabs) {1509      if (tab.id !== undefined) {1510        chrome.tabs.sendMessage(tab.id, message).catch(() => {1511          // Tab may not have a content script — silently ignore1512        });1513      }1514    }1515  });1516}15171518function shouldRefreshAutoLock(type: MessageType): boolean {1519  return (1520    type !== "HAS_VAULT" &&1521    type !== "IS_UNLOCKED" &&1522    type !== "GET_VAULT_STATUS" &&1523    type !== "LOCK" &&1524    type !== "UPDATE_SETTINGS" &&1525    type !== "GET_PENDING_PASSKEY" &&1526    type !== "GET_PASSKEY_PROVIDER_STATE" &&1527    type !== "DECLINE_CARD_SAVE" &&1528    type !== "IS_CARD_DECLINED" &&1529    type !== "SUBMIT_FEEDBACK"1530  );1531}15321533function isAllowedCanaryWebhookUrl(value: string): boolean {1534  try {1535    const url = new URL(value);1536    if (url.protocol !== "https:") return false;15371538    const hostname = url.hostname.toLowerCase();1539    if (1540      hostname === "localhost" ||1541      hostname.endsWith(".localhost") ||1542      isPrivateIpv4(hostname) ||1543      isPrivateIpv6(hostname)1544    ) {1545      return false;1546    }15471548    return true;1549  } catch {1550    return false;1551  }1552}15531554function isPrivateIpv4(hostname: string): boolean {1555  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1556    return true;1557  }15581559  const octets = hostname.split(".").map((part) => Number(part));1560  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1561    return false;1562  }15631564  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1565}15661567function isPrivateIpv6(hostname: string): boolean {1568  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1569  return (1570    normalized === "::1" ||1571    normalized.startsWith("fc") ||1572    normalized.startsWith("fd") ||1573    normalized.startsWith("fe80:")1574  );1575}