messages.ts

72.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, getEffectiveClearSeconds } 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 {70  buildLocalIdentity,71  getOrCreateDeviceId,72  setDeviceName as setDeviceNameV3,73} from "./device-identity";74import {75  isDeviceRevoked,76  listPairedDevices as listPairedDevicesV3,77  renamePairedDevice as renamePairedDeviceV3,78  revokeDeviceById as revokeDeviceByIdV3,79  upsertPairedDevice as upsertPairedDeviceV3,80} from "./paired-devices";81// Sync and pairing are imported statically, never with `await import()`.82// `import()` throws `TypeError: import() is disallowed on83// ServiceWorkerGlobalScope` at runtime in MV3, and Vite's preload helper84// reports the failure through `window.dispatchEvent`, which does not exist in85// a worker either — so the real reason was replaced by "window is not defined"86// and the pairing UI just stopped. scripts/check-sw-static-imports.mjs fails87// the build if a runtime import() reappears anywhere in the worker's graph.88import {89  cancelRelayAdoptionSource,90  isRelayAdoptionSourceInFlight,91  resolveSourceSasConfirmation,92  startRelayAdoptionReceiver,93  startRelayAdoptionSource,94} from "./relay-adoption-bg";95import {96  getSyncSettings,97  setRelayUrl,98  setSyncMode,99  type SyncMode,100} from "./sync-settings";101import {102  getSyncState,103  hydratePersistedSyncState,104  setSyncRunner,105  triggerSyncIfReachable,106} from "./sync-trigger";107import { productionSyncRunner } from "./sync-runner";108109// Compile-time E2E flag, folded to a literal by Vite's `define` (false in110// every production build — verified in the bundled output). Mirrors the111// create-path bypass in passkey.ts so the Playwright passkey smoke can enable112// the provider without a real Pro licence; the gate is fully intact for users.113declare const __PEACH_E2E_PASSKEYS__: boolean;114const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true;115116let nativeSyncRunnerBootstrapped = false;117118function unhexBytes(hex: string): Uint8Array {119  if (hex.length % 2 !== 0) throw new Error("invalid hex");120  const out = new Uint8Array(hex.length / 2);121  for (let i = 0; i < out.length; i++) {122    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);123  }124  return out;125}126127/**128 * The single Pro gate. Every gated handler calls this first; the broadcast129 * lets the popup react (navigate to the License section, highlight the130 * relevant feature). Background never touches the popup view directly —131 * the popup owns navigation. See Projects.md "Pro gate rule".132 */133async function requirePro(134  feature: ProFeature,135  trigger: "user" | "background" = "user"136): Promise<{ allowed: boolean }> {137  if (PASSKEY_E2E_PRO_BYPASS && feature === "passkeys") return { allowed: true };138  if (await isProUser()) return { allowed: true };139140  if (trigger === "user") {141    // User deliberately triggered this feature — redirect the popup immediately.142    chrome.runtime143      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })144      .catch(() => {145        // Popup may be closed — the gate signal is best-effort.146      });147  } else {148    // Background trigger (e.g. passive sync initiation) — no popup is open.149    // Queue a notice so the next popup open shows a soft banner instead of150    // silently failing.151    if (chrome.storage.session) {152      chrome.storage.session153        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })154        .catch(() => {});155    }156  }157158  return { allowed: false };159}160161// ---------------------------------------------------------------------------162// PCH-01-018: operations that irreversibly destroy or replace vault contents,163// plus handlers that store passkey material. These are gated to trusted164// extension-page senders in handleMessage; the confirmation UX otherwise165// lives only in the popup. Keep this in sync when adding new destructive or166// sensitive handlers. (Codex Security 2026-08-04: GET_ADOPTION_MATERIAL and167// COMPLETE_PAIRING were gated here, then deleted outright — they had no168// legitimate senders; adoption runs in-background via relay-adoption-bg.ts.)169const PRIVILEGED_MESSAGE_TYPES: ReadonlySet<string> = new Set([170  "DESTROY_VAULT",171  "CLEAR_VAULT_ENTRIES",172  "RESTORE_VAULT_SNAPSHOT",173  "RESTORE_FROM_CODEX",174  "COMPLETE_FIREFOX_PASSKEY_CREATE",175]);176177// LV-3: minimum interval between non-test canary pings per webhook+entry.178const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour179180const PRIVATE_IPV4_RANGES = [181  { prefix: "10." },182  { prefix: "127." },183  { prefix: "169.254." },184  { prefix: "192.168." },185];186187export function setupMessageHandler(): void {188  chrome.runtime.onMessage.addListener(189    (msg: unknown, sender, sendResponse) => {190      if (!isMessage(msg)) {191        sendResponse({ ok: false, error: "invalid_message" });192        return true;193      }194      handleMessage(msg, sender)195        .then(sendResponse)196        .catch((err) =>197          sendResponse({198            ok: false,199            error: err instanceof Error ? err.message : String(err),200          })201        );202      return true;203    }204  );205206  // Android: the chrome shim queues sendMessage calls until this handler is207  // registered. Without this hookup, every message hangs on Capacitor builds.208  // eslint-disable-next-line @typescript-eslint/no-explicit-any209  const reg = (globalThis as any).__peachRegisterMessageHandler;210  if (typeof reg === "function") {211    reg(async (m: unknown) => {212      if (!isMessage(m)) return { ok: false, error: "invalid_message" };213      try {214        return await handleMessage(m);215      } catch (err) {216        return {217          ok: false,218          error: err instanceof Error ? err.message : String(err),219        };220      }221    });222  }223  if (isNativePlatform()) {224    void bootstrapNativeSyncRunner();225  }226}227228async function bootstrapNativeSyncRunner(): Promise<void> {229  if (nativeSyncRunnerBootstrapped) return;230  nativeSyncRunnerBootstrapped = true;231  try {232    setSyncRunner(productionSyncRunner);233    await hydratePersistedSyncState();234  } catch (err) {235    nativeSyncRunnerBootstrapped = false;236    console.warn("[Peach] failed to bootstrap native sync runner:", err);237  }238}239240function isMessage(m: unknown): m is Message {241  return typeof m === "object" && m !== null && "type" in m;242}243244/**245 * The browser-attested origin of the page that originated this message. A web246 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),247 * so every page-driven message arrives via the content-script relay and the248 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a249 * value the page cannot forge. This is the ONLY trustworthy origin for passkey250 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.251 */252function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {253  if (sender.origin) return sender.origin;254  if (sender.url) {255    try { return new URL(sender.url).origin; } catch { return undefined; }256  }257  return undefined;258}259260// Resolves once restoreFromSession() has run, so handlers see the correct261// post-restore unlock state. entry.ts registers this BEFORE the message262// handler so the onMessage listener is added synchronously at SW startup263// (MV3 requirement) while unlock-dependent handlers still wait for restore.264let restoreReady: Promise<void> = Promise.resolve();265266/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */267export function setRestoreReady(p: Promise<unknown>): void {268  restoreReady = p.then(() => undefined, () => undefined);269}270271export async function handleMessage(272  msg: Message,273  sender: Partial<chrome.runtime.MessageSender> = {}274): Promise<MessageResponse> {275  try {276    // Wait for session-restore to finish before reading any unlock/vault state.277    // On a cold SW start the popup's first message arrives while restore is278    // still in flight; without this gate IS_UNLOCKED would report locked (a279    // spurious lock screen) and the storage reads could race. The onMessage280    // listener itself is registered synchronously (entry.ts) so this gate, not281    // listener registration, is what absorbs the cold-start window.282    await restoreReady;283    // Validate sender — only allow messages from our extension pages/scripts.284    // `sender.id` is undefined for messages originating from extension UI285    // (popup/options), which is legitimate; reject only when it is defined286    // and does not match our extension id.287    if (288      sender.id !== undefined &&289      sender.id !== chrome.runtime.id290    ) {291      return { ok: false, error: "invalid_sender" };292    }293294    // PCH-01-018: destructive and sensitive operations must originate from a295    // trusted extension page (popup/options), never from a content script. The296    // sender.id check above only proves the message came from *our* extension —297    // a content script injected into an attacker page passes it. A single298    // XSS-class bug in the injected UI would otherwise escalate to vault299    // destruction, root-key exfiltration, or attacker device registration.300    // Extension pages carry an extension-origin sender.url; content scripts301    // carry a page URL.302    if (PRIVILEGED_MESSAGE_TYPES.has(msg.type)) {303      const extensionOrigin = chrome.runtime.getURL("");304      if (!sender.url?.startsWith(extensionOrigin)) {305        return { ok: false, error: "invalid_sender" };306      }307    }308309    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {310      touchAutoLock();311    }312313    switch (msg.type) {314      case "CREATE_VAULT": {315        const { password } = msg.payload as { password: string };316        // Refuse to create a vault under an empty master password — the derived317        // key would be publicly known and the at-rest AES-GCM protection void318        // (audit HIGH; the CSV-import path previously passed ""). Length/strength319        // policy lives in the onboarding UI; this is the non-negotiable floor.320        if (typeof password !== "string" || password.length === 0) {321          return { ok: false, error: "invalid_payload" };322        }323        await vault.createVault(password);324        await setupAutoLock();325        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });326        onVaultUnlocked();327        return { ok: true };328      }329      case "CREATE_VAULT_FROM_ROOT_KEY": {330        console.log("[Peach diag] CREATE_VAULT_FROM_ROOT_KEY handler entered");331        const { password, rootKeyHex } = (msg.payload ?? {}) as {332          password?: unknown;333          rootKeyHex?: unknown;334        };335        console.log("[Peach diag] payload types:", typeof password, typeof rootKeyHex, "lengths:", (password as string)?.length, (rootKeyHex as string)?.length);336        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {337          console.log("[Peach diag] payload invalid, returning invalid_payload");338          return { ok: false, error: "invalid_payload" };339        }340341        try {342          console.log("[Peach diag] calling vault.createVaultFromRootKey");343          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);344          console.log("[Peach diag] createVaultFromRootKey returned vaultId", vaultId);345          await setupAutoLock();346          console.log("[Peach diag] setupAutoLock done");347          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });348          onVaultUnlocked();349          console.log("[Peach diag] handler completing successfully");350          return { ok: true, vaultId };351        } catch (err) {352          console.error("[Peach diag] handler caught error:", err);353          return { ok: false, error: err instanceof Error ? err.message : String(err) };354        }355      }356      case "UNLOCK": {357        const { password } = msg.payload as { password: string };358        const ok = await vault.unlock(password);359        if (ok) {360          // KAT: verify the WebCrypto stack is healthy before the user relies on it.361          // Runs after unlock so latency is hidden behind the vault-load time.362          const kat = await runSelfTest();363          if (!kat.ok) {364            console.error("[Peach] Crypto self-test FAILED:", kat.error);365            await vault.lock();366            return { ok: false, error: "self_test_failed" };367          }368          await setupAutoLock();369          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });370          onVaultUnlocked();371          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());372          return { ok: true };373        }374        // Distinguish corruption from wrong password so the popup can offer375        // a history-restore path instead of falsely accusing the user of376        // mistyping (M7/COR-007).377        const failure = vault.consumeLastUnlockFailureReason();378        if (failure) {379          return {380            ok: false,381            error: "vault_corrupted",382            canRestoreFromHistory: true,383          } as MessageResponse;384        }385        return { ok: false };386      }387      case "VALIDATE_RECOVERY_WORDS": {388        const { words } = msg.payload as { words: string[] };389        const invalid = findInvalidWords(words);390        return { ok: true, data: { valid: invalid.length === 0, invalid } };391      }392      case "GET_RECOVERY_WORDS": {393        // Must be unlocked and have recovery set up (vault must be v2.12+).394        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };395        // LV-4: the recovery words re-derive the ROOT KEY — the highest-396        // value secret in the vault. A session unlock (which may be hours397        // old on a shared machine) is not enough; require a fresh password398        // proof, matching the 1Password/Bitwarden pattern for revealing399        // escrow material. EXEMPTION: the create-vault / rotation confirmation400        // window (peach_recovery_pending) shows the words immediately after401        // the user authenticated, and that confirmation UI has no password to402        // resend — skip the re-auth there only.403        if (!(await isRecoveryConfirmPending())) {404          const { password } = (msg.payload ?? {}) as { password?: string };405          if (typeof password !== "string" || !password) {406            return { ok: false, error: "password_required" };407          }408          if (!(await vault.verifyMainPassword(password))) {409            return { ok: false, error: "wrong_password" };410          }411        }412        try {413          const words = await vault.getRecoveryWords();414          return { ok: true, data: words };415        } catch {416          // pre-v2.12 vault that hasn't migrated417          return { ok: false, error: "recovery_not_setup" };418        }419      }420      case "RECOVER_WITH_WORDS": {421        // User has lost their password but has their 12 recovery words.422        // We: (1) validate the words, (2) re-encrypt vault with new password.423        const { words, newPassword } = msg.payload as {424          words: string[];425          newPassword: string;426        };427        const stored = await vault.loadSlotA();428        if (!stored) return { ok: false, error: "no_vault" };429        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {430          return { ok: false, error: "recovery_not_setup" };431        }432        // Unwrap the root key from the recovery escrow.433        try {434          await vault.unwrapRootKeyForRecovery(435            stored.recovery_wrapped_root_key,436            stored.recovery_nonce ?? "",437            stored.recovery_tag ?? "",438            stored.recovery_salt,439            words440          );441        } catch {442          return { ok: false, error: "invalid_recovery_words" };443        }444        // Re-key: derive fresh salt + key from new password.445        const newSalt = vault.generateSalt();446        const newKey = await vault.deriveKey(newPassword, newSalt);447        // Re-wrap root key under the new password's derived key so the same448        // recovery words continue to work after the password change.449        await vault.rewrapRootKeyForPassword(newKey, newSalt);450        // Re-encrypt vault entries with the new key.451        await vault.changePasswordWithNewKey(newSalt, newKey);452        await setupAutoLock();453        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });454        return { ok: true };455      }456      case "LOCK":457        vault.lock();458        if (isNativePlatform()) await clearInMemoryVault();459        return { ok: true };460      case "IS_UNLOCKED":461        return { ok: true, data: vault.isUnlocked() };462      case "GET_VAULT_STATUS":463        return { ok: true, unlocked: vault.isUnlocked() };464      case "HAS_VAULT":465        return { ok: true, data: await vault.hasVault() };466      case "GET_ENTRIES":467        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };468        return { ok: true, data: vault.getEntries() };469      case "ADD_ENTRY": {470        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };471        const payload = msg.payload;472        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {473          return { ok: false, error: "invalid_payload" };474        }475        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);476        return { ok: true, data: entry };477      }478      case "BATCH_ADD_ENTRIES": {479        const payload = msg.payload as { entries?: unknown } | null | undefined;480        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {481          return { ok: false, error: "invalid_payload" };482        }483        if (!Array.isArray(payload.entries)) {484          return { ok: false, error: "invalid_payload" };485        }486        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);487        return { ok: true, data: added };488      }489      case "RESTORE_ENTRIES": {490        const payload = msg.payload as491          | { entries?: unknown; mode?: unknown; settings?: unknown }492          | null493          | undefined;494        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {495          return { ok: false, error: "invalid_payload" };496        }497        if (!Array.isArray(payload.entries)) {498          return { ok: false, error: "invalid_payload" };499        }500        if (payload.mode !== "replace" && payload.mode !== "merge") {501          return { ok: false, error: "invalid_payload" };502        }503        const summary = await vault.restoreEntries(504          payload.entries as Parameters<typeof vault.restoreEntries>[0],505          payload.mode506        );507        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {508          await vault.updateSettings(payload.settings as vault.VaultSettings);509        }510        return { ok: true, data: summary };511      }512      case "CLEAR_VAULT_ENTRIES": {513        await vault.clearVaultEntries("REPLACE_ALL");514        return { ok: true };515      }516      case "GET_VAULT_HISTORY": {517        const snapshots = await vault.getVaultHistory();518        return { ok: true, data: snapshots };519      }520      case "RESTORE_VAULT_SNAPSHOT": {521        const { snapshotId } = msg.payload as { snapshotId: string };522        const result = await vault.restoreVaultSnapshot(snapshotId);523        if (!result.ok) return { ok: false, error: result.error };524        broadcastToContentScripts({ type: "VAULT_LOCKED" });525        return { ok: true };526      }527      case "COUNT_DUPLICATES": {528        return { ok: true, data: vault.countDuplicates() };529      }530      case "DEDUPLICATE_ENTRIES": {531        const removed = await vault.deduplicateEntries();532        return { ok: true, data: removed };533      }534      case "UPDATE_ENTRY": {535        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;536        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {537          return { ok: false, error: "invalid_payload" };538        }539        const { id, patch } = payload;540        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {541          return { ok: false, error: "invalid_payload" };542        }543        // Single enforcement point for the Canary Entries Pro gate. Only544        // gates the transition into a canary entry — clearing/disabling a545        // canary (`canary: undefined`) is always allowed, so existing546        // canary entries remain manageable.547        const incomingCanary = (patch as { canary?: unknown }).canary;548        if (incomingCanary && typeof incomingCanary === "object") {549          const existing = vault.getEntryById(id);550          if (!existing?.canary) {551            const gate = await requirePro("canary_entry");552            if (!gate.allowed) return { ok: false, error: "pro_required" };553          }554        }555        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);556        return { ok: true };557      }558      case "ADD_ADDITIONAL_URL": {559        const { id, url } = msg.payload as { id: string; url: string };560        const trimmed = typeof url === "string" ? url.trim() : "";561        if (!trimmed) return { ok: false, error: "url_required" };562        const existing = vault.getEntryById(id);563        if (!existing) return { ok: false, error: "entry_not_found" };564        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };565        const merged = [...(existing.additionalUrls ?? []), trimmed];566        await vault.updateEntry(id, { additionalUrls: merged });567        return { ok: true };568      }569      case "DELETE_ENTRY": {570        const { id } = msg.payload as { id: string };571        await vault.deleteEntry(id);572        return { ok: true };573      }574      case "GET_DELETED_ENTRIES":575        return { ok: true, data: vault.getDeletedEntries() };576      case "RESTORE_ENTRY": {577        const { id } = msg.payload as { id: string };578        await vault.restoreEntry(id);579        return { ok: true };580      }581      case "PURGE_ENTRY": {582        const { id } = msg.payload as { id: string };583        await vault.purgeEntry(id);584        return { ok: true };585      }586      case "PURGE_EXPIRED_TRASH": {587        const { retentionMs } = msg.payload as { retentionMs: number };588        const purged = await vault.purgeExpiredTrash(retentionMs);589        return { ok: true, data: purged };590      }591      case "SAVE_NOTE": {592        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };593        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };594        const now = Date.now();595        if (id) {596          const existing = vault.getEntryById(id);597          if (!existing) return { ok: false, error: "not_found" };598          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });599          return { ok: true, data: vault.getEntryById(id) };600        } else {601          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt602          // (EntryDraft omits both), so passing them was the only reason the603          // `as any` cast existed. Dropping them makes the call type-check.604          const entry = await vault.addEntry({605            type: "note",606            title: title || "Untitled",607            notes: body,608          });609          return { ok: true, data: entry };610        }611      }612      case "DELETE_NOTE": {613        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };614        const { id } = msg.payload as { id: string };615        await vault.deleteEntry(id);616        return { ok: true };617      }618      case "GET_NOTES": {619        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };620        const notes = vault.getEntries().filter(621          (e) => e.type === "note" && !e.deletedAt622        );623        return { ok: true, data: notes } as MessageResponse;624      }625      case "SEARCH_VAULT": {626        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };627        // AUD-002: shape-validate the payload before calling string methods.628        // A raw cast lets a malformed message crash the handler with TypeError.629        const { query } = (msg.payload ?? {}) as { query?: unknown };630        if (typeof query !== "string") {631          return { ok: false, error: "invalid_payload" };632        }633        const q = query.toLowerCase();634        const searchResults = vault.getEntries().filter(635          (e) =>636            !e.deletedAt &&637            (e.title.toLowerCase().includes(q) ||638              e.notes?.toLowerCase().includes(q) ||639              e.username?.toLowerCase().includes(q))640        );641        return { ok: true, data: searchResults } as MessageResponse;642      }643      case "AUTOFILL_QUERY": {644        if (!vault.isUnlocked()) {645          return { ok: false, error: "vault_locked" };646        }647        let { includeAll } = msg.payload as { includeAll?: boolean };648        const { domain, kind, userGesture } = msg.payload as {649          domain: string;650          kind?: "login" | "card" | "totp";651          userGesture?: boolean;652        };653        // MV-2: the vault-wide inventory (every title/username/email/url)654        // may only leave the background on an explicit user gesture — the655        // user opening the search affordance — never on passive form focus.656        // userGesture is self-declared by our own content script; the value657        // of this gate is that PASSIVE code paths (which never set it)658        // cannot ship the inventory, shrinking what a compromised page that659        // merely triggers focus events can observe.660        if (includeAll && userGesture !== true) {661          includeAll = false;662        }663        // kind="card": return saved cards as compact summaries for the664        // inline card silver platter. Cards are not domain-scoped — every665        // saved card is a candidate on every checkout page — so domain is666        // ignored when kind === "card".667        if (kind === "card") {668          const cards = vault.getEntries().filter((e) => e.type === "card");669          return {670            ok: true,671            data: cards.map((e) => ({672              id: e.id,673              title: e.cardNickname || e.title,674              cardholderName: e.cardholderName,675              last4: e.last4,676              expMonth: e.expMonth,677              expYear: e.expYear,678              network: e.network,679            })),680          };681        }682        if (kind === "totp") {683          const matches = (684            includeAll685              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")686              : vault.queryDomain(domain)687          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));688          return {689            ok: true,690            data: matches.map((e) => ({691              id: e.id,692              title: e.title,693              username: e.username,694              email: e.email,695              url: e.url,696              hasTotp: true,697            })),698          };699        }700        // The inline selector fills username+password into a form. Passkey-701        // only entries have no password to fill; sign-in for those goes702        // through the WebAuthn path instead. Filter them out everywhere so703        // the user doesn't see four "GitHub" rows that mostly do nothing.704        // Notes and cards never belonged here either.705        const matches = (706          includeAll707            ? vault708                .getEntries()709                .filter((entry) => entry.type !== "note" && entry.type !== "card")710            : vault.queryDomain(domain)711        ).filter((entry) => !isPasskeyOnly(entry));712        return {713          ok: true,714          data: matches.map((e) =>715            includeAll716              ? {717                  id: e.id,718                  title: e.title,719                  // username/email/url shipped so the inline popup's search720                  // affordance can match on them, not just titles. No secrets721                  // cross the boundary — same shape as the domain-matched722                  // response below minus hasTotp (which the search list723                  // doesn't surface).724                  username: e.username,725                  email: e.email,726                  url: e.url,727                  hasPasskey: e.passkey !== undefined,728                }729              : {730                  id: e.id,731                  title: e.title,732                  username: e.username,733                  email: e.email,734                  url: e.url,735                  hasTotp: Boolean(e.totp),736                  hasPasskey: e.passkey !== undefined,737                }738          ),739        };740      }741      case "GET_ENTRY_FOR_FILL": {742        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };743        const { id, explicitSummon } = msg.payload as {744          id: string;745          explicitSummon?: boolean;746        };747        const entry = vault.getEntryById(id);748        if (!entry) return { ok: false, error: "entry_not_found" };749        // Passkey-only entries (passkey credential, no password) cannot be750        // filled into a form — sign-in goes through the WebAuthn path. A751        // login that ALSO has a passkey is still fillable for its password.752        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };753754        // MV-1: re-validate the entry against the requesting tab's origin.755        // sender.tab.url is browser-attested — a page cannot forge it. When756        // the request does not come from a tab at all (popup surfaces use757        // GET_ENTRY_FOR_EDIT, not this), refuse.758        if (sender.tab !== undefined || sender.url !== undefined) {759          let senderDomain: string | null = null;760          try {761            const rawUrl = sender.tab?.url ?? sender.url ?? "";762            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;763          } catch {764            senderDomain = null;765          }766          if (!senderDomain) return { ok: false, error: "origin_unverified" };767768          const entryDomains = new Set<string>();769          const primary = extractDomain(entry.url ?? "");770          if (primary) entryDomains.add(primary);771          for (const extra of entry.additionalUrls ?? []) {772            const d = extractDomain(extra);773            if (d) entryDomains.add(d);774          }775776          // explicitSummon=true means the user actively picked this entry777          // from the cross-domain search affordance — an intentional778          // off-domain fill. Passive fill paths must stay domain-bound.779          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {780            // Domain mismatch — refuse silently (no oracle about which ids exist).781            return { ok: false, error: "entry_not_found" };782          }783        }784        // Strip the passkey credential AND the raw base32 TOTP seed from the785        // response. Content scripts never need either: the private key is the786        // authenticator's, and handing over the TOTP seed would let a787        // compromised content script mint valid codes indefinitely (SEV-3-C).788        // Generate the *current* 6-digit code here in the background and send789        // only that, plus the seconds left so the UI can render a countdown.790        // Also drop passwordHistory: filling needs only the *current* password.791        // Handing every past password to a content script during passive792        // autofill on an arbitrary page would widen the blast radius of a793        // compromised page far beyond the one credential being filled.794        const {795          passkey: _strippedPasskey,796          totp: seed,797          totpAlgorithm,798          totpDigits,799          totpPeriod,800          passwordHistory: _ph,801          ...safeEntry802        } = entry;803        let totpCode: string | undefined;804        let totpRemaining: number | undefined;805        if (seed) {806          try {807            // PCH-01-019: honour stored algorithm/digits/period (defaults apply808            // when these are undefined, i.e. legacy bare-seed entries).809            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);810            totpCode = generated.code;811            totpRemaining = generated.remaining;812          } catch {813            totpCode = undefined;814          }815        }816        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };817      }818      // Trusted full-entry fetch for Peach's own inline-popup surfaces that819      // genuinely need the raw TOTP seed: the edit form (which re-saves the820      // seed and would otherwise wipe it) and nothing else. Unlike821      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside822      // the inline popup, never during passive autofill on an arbitrary page.823      // The passkey credential is still stripped — the edit form never touches it.824      case "GET_ENTRY_FOR_EDIT": {825        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };826        const { id, explicitSummon } = msg.payload as {827          id: string;828          explicitSummon?: boolean;829        };830        const entry = vault.getEntryById(id);831        if (!entry) return { ok: false, error: "entry_not_found" };832833        // PCH-01-006: re-validate the browser-attested sender origin, mirroring834        // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and835        // full password history — at least as sensitive as the fill response — so836        // the boundary must be enforced here, not only by UI reachability. Today837        // the sole caller is the popup (no sender.tab, so this is a structural838        // no-op), but a future tab-context caller or an id leak would otherwise839        // inherit a full-credential oracle. Unlike the fill path we SKIP (not840        // refuse) when no sender domain resolves, to keep the popup caller working.841        if (sender.tab !== undefined || sender.url !== undefined) {842          let senderDomain: string | null = null;843          try {844            const rawUrl = sender.tab?.url ?? sender.url ?? "";845            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;846          } catch {847            senderDomain = null;848          }849          if (senderDomain) {850            const entryDomains = new Set<string>();851            const primary = extractDomain(entry.url ?? "");852            if (primary) entryDomains.add(primary);853            for (const extra of entry.additionalUrls ?? []) {854              const d = extractDomain(extra);855              if (d) entryDomains.add(d);856            }857            if (explicitSummon !== true && !entryDomains.has(senderDomain)) {858              return { ok: false, error: "entry_not_found" }; // no id oracle859            }860          }861        }862863        const { passkey: _passkey, ...safeEntry } = entry;864        return { ok: true, data: safeEntry };865      }866      case "COPY": {867        // AUD-002: shape-validate the payload before passing to the clipboard868        // helper. A raw cast lets a malformed message reach the clipboard API869        // with a non-string and throw.870        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {871          text?: unknown;872          label?: unknown;873          alreadyWritten?: unknown;874        };875        if (typeof text !== "string" || typeof label !== "string") {876          return { ok: false, error: "invalid_payload" };877        }878        await copyToClipboard(text, label, Boolean(alreadyWritten));879        return { ok: true, clearSeconds: getEffectiveClearSeconds() };880      }881      case "CHECK_ALL_BREACHES": {882        const allEntries = vault.getEntries();883        const results: Record<string, number> = {};884        for (const entry of allEntries) {885          if (entry.type === "note") continue;886          if (!entry.password) continue;887          results[entry.id] = await vault.checkBreach(entry.password);888          // Small delay — be a good citizen to the HIBP API889          await new Promise((r) => setTimeout(r, 200));890        }891        // Persist any non-zero counts back to entries892        for (const [id, count] of Object.entries(results)) {893          const entry = vault.getEntryById(id);894          if (entry && (entry.breach ?? 0) !== count) {895            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });896          }897        }898        return { ok: true, data: results };899      }900      case "GET_SETTINGS":901        return { ok: true, data: await vault.ensureSettingsLoaded() };902      case "UPDATE_SETTINGS": {903        const patch = msg.payload;904        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {905          return { ok: false, error: "invalid_payload" };906        }907        await vault.updateSettings(patch as vault.VaultSettings);908        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {909          await setupAutoLock();910          if (vault.isUnlocked()) touchAutoLock();911        }912        return { ok: true };913      }914      case "GET_PENDING_PASSKEY":915        return { ok: true, data: await getPendingPasskeyRequest() };916      case "APPROVE_PASSKEY": {917        const { requestId } = msg.payload as { requestId: number };918        await resolvePendingPasskeyRequest(requestId, true);919        return { ok: true };920      }921      case "DENY_PASSKEY": {922        const { requestId } = msg.payload as { requestId: number };923        await resolvePendingPasskeyRequest(requestId, false);924        return { ok: true };925      }926      case "GET_PASSKEY_PROVIDER_STATE":927        return { ok: true, data: await getPasskeyProviderState() };928      case "SET_PASSKEY_PROVIDER_ENABLED": {929        const { enabled } = msg.payload as { enabled: boolean };930        // Disabling is always free; gating fires only when a free user is931        // trying to turn passkey interception on.932        if (enabled) {933          const gate = await requirePro("passkeys");934          if (!gate.allowed) return { ok: false, error: "pro_required" };935        }936        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };937      }938      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS939      // endpoint. Intentional product behavior — users configure their own940      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private941      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-942      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to943      // users that the entry title leaves the device when the canary fires.944      case "FIRE_CANARY_PING": {945        // Canary alert fires unconditionally for any entry with canary: true.946        // The Pro gate only governs creation/flagging of canary entries; once947        // an entry is flagged, the alert path is a security property and must948        // never be license-gated.949        const { webhookUrl, entryTitle, trigger } = msg.payload as {950          webhookUrl: string;951          entryTitle: string;952          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";953        };954        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {955          return { ok: false, error: "invalid_webhook_url" };956        }957        // LV-3: debounce non-test pings per (webhook, entry) so a page that958        // strobes focus/fill events can't turn the canary into a request959        // firehose at the user's endpoint. Test pings are exempt — they are960        // explicit user clicks in the settings UI and are awaited for961        // feedback. The FIRST ping in a window always goes out, so the962        // dead-man's-switch property (canary fires on access) is preserved;963        // only repeats within the window are coalesced.964        if (trigger !== "test") {965          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;966          const stored = await chrome.storage.local.get(rlKey);967          const last = (stored as Record<string, unknown>)[rlKey];968          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {969            return { ok: true, data: { rateLimited: true } };970          }971          await chrome.storage.local.set({ [rlKey]: Date.now() });972        }973        const body = JSON.stringify({974          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",975          entry: entryTitle,976          trigger,977          timestamp: new Date().toISOString(),978          source: "peach-extension",979        });980        if (trigger === "test") {981          // Permitted outbound fetch: user-configured canary alert endpoint982          // (validated by isAllowedCanaryWebhookUrl above). This is the983          // only non-HIBP outbound call in the extension — see984          // Projects.md §3.7. Test pings are awaited so the UI can show985          // success/failure.986          try {987            const res = await fetch(webhookUrl, {988              method: "POST",989              headers: { "Content-Type": "application/json" },990              body,991            });992            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };993          } catch (err) {994            return { ok: false, error: err instanceof Error ? err.message : "network_error" };995          }996        }997        // Non-test triggers are fire-and-forget998        fetch(webhookUrl, {999          method: "POST",1000          headers: { "Content-Type": "application/json" },1001          body,1002        }).catch(() => {});1003        return { ok: true };1004      }1005      case "ACTIVATE_LICENSE": {1006        const { key } = msg.payload as { key: string };1007        const licenseInfo = await activateLicense(key);1008        return { ok: true, data: licenseInfo };1009      }1010      case "GET_LICENSE": {1011        const licenseInfo = await getLicenseInfo();1012        return { ok: true, data: licenseInfo };1013      }1014      case "GET_LICENSE_KEY": {1015        const key = await getLicenseKey();1016        return { ok: true, data: key };1017      }1018      case "DEACTIVATE_LICENSE": {1019        await deactivateLicense();1020        return { ok: true };1021      }1022      case "SHOULD_PLAY_CELEBRATION": {1023        const should = await shouldPlayCelebration();1024        return { ok: true, data: should };1025      }1026      case "MARK_CELEBRATION_PLAYED": {1027        await markCelebrationPlayed();1028        return { ok: true };1029      }1030      case "GET_CODEX_VAULT_DATA": {1031        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1032        // popup navigates to the License section without further coordination.1033        const gate = await requirePro("codex");1034        if (!gate.allowed) return { ok: false, error: "pro_required" };1035        return await handleGetCodexVaultData();1036      }1037      case "ESTIMATE_CODEX_PAGES": {1038        const gate = await requirePro("codex");1039        if (!gate.allowed) return { ok: false, error: "pro_required" };1040        return await handleEstimateCodexPages();1041      }1042      case "RESTORE_FROM_CODEX": {1043        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1044        // be able to restore a vault that was printed by a Pro user.1045        // DO NOT add a Pro gate here.1046        const payload = msg.payload as CodexRestorePayload;1047        return await handleRestoreFromCodex(payload);1048      }1049      case "OPEN_PRO_GATE": {1050        // Content script requests: open popup and navigate to License section.1051        const { feature } = (msg.payload ?? {}) as { feature?: string };1052        if (chrome.storage.session) {1053          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1054        }1055        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1056        return { ok: true };1057      }1058      case "OPEN_POPUP": {1059        // Content script asks to open the trusted extension popup — used by the1060        // inline locked bubble so the master password is entered in the popup,1061        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1062        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1063        // toolbar icon. The badge already signals Peach needs attention.1064        //1065        // Set a session flag so the popup knows it was opened for inline unlock1066        // and should close itself once the vault is unlocked (returning the user1067        // to the inline autofill selector on the page).1068        if (chrome.storage.session) {1069          await chrome.storage.session.set({ peach_inline_unlock: true });1070        }1071        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1072        return { ok: true };1073      }1074      case "GET_IDENTITIES": {1075        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1076        return { ok: true, data: vault.getIdentities() };1077      }1078      case "TOUCH_AUTO_LOCK": {1079        // touchAutoLock() is already called by shouldRefreshAutoLock above;1080        // this case just gives the popup a typed message to keep the session alive.1081        return { ok: true };1082      }1083      case "GET_ADVANCED_HEALTH_REPORT": {1084        const gate = await requirePro("advanced_health");1085        if (!gate.allowed) return { ok: false, error: "pro_required" };1086        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1087        const report = await buildAdvancedHealthReport(vault.getEntries());1088        return { ok: true, data: report };1089      }1090      case "IS_DURESS_ENABLED": {1091        const enabled = await vault.isDuressEnabled();1092        return { ok: true, data: enabled };1093      }1094      case "SETUP_DURESS": {1095        // Single enforcement point for the Duress Vault Pro gate. Free users1096        // who somehow reach this handler are rejected here; the popup also1097        // pre-checks isPro() to avoid showing the setup form to free users,1098        // but server-side is the actual security boundary.1099        const gate = await requirePro("duress_vault");1100        if (!gate.allowed) return { ok: false, error: "pro_required" };1101        // MV3 service workers restart after inactivity, losing the in-memory1102        // derived key. Detect this before calling setupDuress so the popup1103        // can show a meaningful prompt to re-lock and re-unlock.1104        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1105        const { duressPassword } = msg.payload as { duressPassword: string };1106        await vault.setupDuress(duressPassword);1107        return { ok: true };1108      }1109      case "DISABLE_DURESS": {1110        await vault.disableDuress();1111        return { ok: true };1112      }1113      case "VERIFY_MAIN_PASSWORD": {1114        const { password } = msg.payload as { password: string };1115        const ok = await vault.verifyMainPassword(password);1116        return { ok: true, data: ok };1117      }1118      case "CHANGE_PASSWORD": {1119        const { currentPassword, newPassword } = msg.payload as {1120          currentPassword: string;1121          newPassword: string;1122        };1123        const changed = await vault.changePassword(currentPassword, newPassword);1124        return changed1125          ? { ok: true }1126          : { ok: false, error: "incorrect_current_password" };1127      }1128      case "GET_SITE_PASSWORD_POLICY": {1129        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1130        if (!tab?.id) return { ok: true, data: null };1131        try {1132          const response = await chrome.tabs.sendMessage(tab.id, {1133            type: "GET_SITE_PASSWORD_POLICY",1134          });1135          return (response as MessageResponse) ?? { ok: true, data: null };1136        } catch {1137          return { ok: true, data: null };1138        }1139      }1140      case "RECORD_MANUAL_SUMMON": {1141        const { domain } = msg.payload as { domain: string };1142        const settings = vault.getSettings();1143        const existing = settings.manualSummonDomains?.[domain];1144        const now = Date.now();1145        await vault.updateSettings({1146          manualSummonDomains: {1147            ...settings.manualSummonDomains,1148            [domain]: {1149              firstSummonedAt: existing?.firstSummonedAt ?? now,1150              summonCount: (existing?.summonCount ?? 0) + 1,1151              lastSummonedAt: now,1152            },1153          },1154        });1155        return { ok: true };1156      }1157      case "DECLINE_CARD_SAVE": {1158        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1159        await vault.declineCardSaveOffer(last4, expMonth, expYear);1160        return { ok: true };1161      }1162      case "IS_CARD_DECLINED": {1163        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1164        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1165        return { ok: true, data: declined };1166      }1167      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1168        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1169          rpId?: string;1170          rpName?: string;1171          userName?: string;1172          userDisplayName?: string;1173        };1174        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1175        return await initiateFirefoxPasskeyCreate({1176          rpId,1177          rpName: rpName ?? rpId,1178          userName,1179          userDisplayName,1180        }, attestedSenderOrigin(sender));1181      }11821183      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1184        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1185        if (!payload) return { ok: false, error: "missing_payload" };1186        return await completeFirefoxPasskeyCreate(payload);1187      }11881189      case "PASSKEY_OFFER_DECLINE": {1190        const { domain } = (msg.payload ?? {}) as { domain?: string };1191        if (!domain) return { ok: false, error: "domain_required" };1192        await recordPasskeyOfferDecline(domain);1193        return { ok: true };1194      }11951196      case "GET_PASSKEY_OFFER_DECLINED": {1197        const { domain } = (msg.payload ?? {}) as { domain?: string };1198        if (!domain) return { ok: false, error: "domain_required" };1199        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1200      }12011202      case "PASSKEY_HAS_CREDENTIALS": {1203        const payload = msg.payload as {1204          rpId?: string;1205          allowCredentials?: Array<{ id: string; type?: string }>;1206        } | undefined;1207        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1208        return await handlePasskeyHasCredentials({1209          rpId: payload.rpId,1210          allowCredentials: payload.allowCredentials ?? [],1211        }, attestedSenderOrigin(sender));1212      }12131214      case "PASSKEY_CREATE": {1215        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1216        if (!payload?.rpId || !payload?.userName) {1217          return { ok: false, error: "rpid_and_username_required" };1218        }1219        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1220      }12211222      case "PASSKEY_GET": {1223        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1224        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1225        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1226      }12271228      case "PASSKEY_AUTH_RESPONSE": {1229        const { requestId, approved } = (msg.payload ?? {}) as {1230          requestId?: string | number;1231          approved?: boolean;1232        };1233        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1234          return { ok: false, error: 'requestId and approved required' };1235        }1236        await resolvePendingPasskeyRequest(Number(requestId), approved);1237        return { ok: true };1238      }12391240      case "GET_PASSKEY_FOR_DOMAIN": {1241        const { domain } = (msg.payload ?? {}) as { domain?: string };1242        if (!domain) return { ok: false, error: "domain_required" };1243        // Scope to the caller's own origin: a page may only ask about passkeys1244        // for a domain it actually owns, so an arbitrary page cannot enumerate1245        // which sites the user holds passkeys for or read the username (audit MEDIUM).1246        const origin = attestedSenderOrigin(sender);1247        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1248        if (!vault.isUnlocked()) return { ok: true, data: null };1249        const match = vault1250          .getEntries()1251          .find((entry) => entry.passkey?.rpId === domain);1252        if (!match || !match.passkey) return { ok: true, data: null };1253        // Slim shape — only the fields State 11 needs. Never expose private1254        // key material, even though this is locked behind isUnlocked.1255        return {1256          ok: true,1257          data: {1258            rpId: match.passkey.rpId,1259            userName: match.passkey.userName,1260            browser: match.passkey.browser,1261          },1262        };1263      }12641265      case "DESTROY_VAULT": {1266        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1267        // storage.local.clear() wipes every Peach key (slots, settings, license,1268        // onboarded flag, history, sync state, declined cards, recall, etc.);1269        // session.clear() wipes pending passkey requests + pro-notice queues.1270        // Caller (Panic.tsx) handles UI navigation back to onboarding.1271        //1272        // The Pro license is the one thing that must survive: the user paid for1273        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1274        // Capture it before the clear and restore it after. peach_pro_celebrated1275        // rides along so the Pro celebration doesn't replay on the next unlock.1276        const preserved = await chrome.storage.local.get([1277          "peach_license",1278          "peach_pro_celebrated",1279        ]);1280        vault.lock();1281        await storageClear();1282        await vault.clearVaultHistory();1283        const toRestore: Record<string, unknown> = {};1284        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1285        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1286        if (Object.keys(toRestore).length > 0) {1287          await chrome.storage.local.set(toRestore);1288        }1289        if (chrome.storage.session) {1290          await chrome.storage.session.clear();1291        }1292        return { ok: true };1293      }12941295      // Android-only: biometric unlock with pre-derived key.1296      case "UNLOCK_WITH_KEY": {1297        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1298        if (!isNativePlatform()) {1299          return { ok: false, error: "desktop_only_uses_password" };1300        }1301        try {1302          const result = await vault.unlockWithKey(masterKeyHex);1303          if (result.ok) {1304            onVaultUnlocked();1305            await publishInMemoryVault(result.entries);1306          }1307          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1308        } catch {1309          return { ok: false, error: "invalid_key" };1310        }1311      }1312      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1313      case "GET_DERIVED_KEY": {1314        if (!isNativePlatform()) {1315          return { ok: false, error: "android_only" };1316        }1317        if (!vault.isUnlocked()) {1318          return { ok: false, error: "vault_locked" };1319        }1320        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1321      }1322      case "GET_IDENTITY_SUGGESTIONS": {1323        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1324        const entries = vault.getEntries();1325        const suggestions = buildIdentitySuggestions(entries);1326        return { ok: true, data: { suggestions } };1327      }1328      case "POPULATE_INLINE_VAULT": {1329        if (!isNativePlatform()) return { ok: false };1330        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1331        const entries = vault.getEntries();1332        await publishInMemoryVault(entries);1333        return { ok: true };1334      }1335      case "ML_INIT":1336        return { ok: true };13371338      case "ML_PREDICT_BATCH": {1339        // AUD-002: shape-validate before forwarding to the ML helper.1340        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1341        if (!Array.isArray(featuresArray)) {1342          return { ok: false, error: "invalid_payload" };1343        }1344        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1345      }13461347      // ── Vault sync (v3) ───────────────────────────────────────────────1348      // Returns the public-facing local identity needed by the popup to1349      // drive Phase-1 audio pairing. The private long-term key never1350      // leaves the background.1351      case "GET_LOCAL_IDENTITY": {1352        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1353        // Pro license from an already-Pro peer (at least one device must be Pro).1354        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1355        // Identity derives from the stable root key, not the password-derived1356        // key, so pairing survives a master-password change (SEV-2-B).1357        const masterKeyHex = vault.getRootKeyHex();1358        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1359        const masterKey = unhexBytes(masterKeyHex);1360        try {1361          const identity = await buildLocalIdentity(masterKey);1362          // If this device is Pro, advertise the signed license so the peer can1363          // activate it after SAS confirmation — pairing carries Pro across.1364          if (await isProUser()) {1365            const license = await getLicenseKey();1366            if (license) (identity as { license?: string }).license = license;1367          }1368          return { ok: true, data: identity };1369        } finally {1370          masterKey.fill(0);1371        }1372      }13731374      case "LIST_PAIRED_DEVICES": {1375        const devices = await listPairedDevicesV3();1376        return { ok: true, data: { devices } };1377      }13781379      case "RENAME_PAIRED_DEVICE": {1380        const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string };1381        if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") {1382          return { ok: false, error: "invalid_payload" };1383        }1384        await renamePairedDeviceV3(deviceId, name);1385        return { ok: true };1386      }13871388      case "UNPAIR_DEVICE": {1389        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1390        if (typeof deviceId !== "string" || !deviceId) {1391          return { ok: false, error: "invalid_payload" };1392        }1393        // Removing a device REVOKES it rather than just dropping the local1394        // row: a plain removal is undone the moment any other peer vouches it1395        // back through a manifest, which is exactly what the relay makes easy.1396        await revokeDeviceByIdV3(deviceId, await getOrCreateDeviceId());1397        // Sync against the remaining hosts — the unpaired device no longer1398        // matters but the next alarm tick is up to ten minutes away.1399        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1400        return { ok: true };1401      }14021403      case "RENAME_LOCAL_DEVICE": {1404        const { name } = (msg.payload ?? {}) as { name?: string };1405        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1406        await setDeviceNameV3(name);1407        return { ok: true };1408      }14091410      // ── Relay pairing ─────────────────────────────────────────────────────1411      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1412      // session runs in the background; the SAS and the terminal result reach1413      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1414      case "START_ADOPTION_SOURCE": {1415        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1416        if (isRelayAdoptionSourceInFlight()) {1417          return { ok: false, error: "adoption_source_in_progress" };1418        }1419        try {1420          return { ok: true, data: await startRelayAdoptionSource() };1421        } catch (error) {1422          return {1423            ok: false,1424            error: error instanceof Error ? error.message : "adoption_source_failed",1425          };1426        }1427      }14281429      // Onboarding receiver — empty extension shows a QR, phone scans and1430      // sends the vault. The popup supplies the local-only password here so1431      // the background can wrap the adopted root key at rest without ever1432      // asking the user to retype it.1433      case "START_ADOPTION_RECEIVER": {1434        if (isRelayAdoptionSourceInFlight()) {1435          return { ok: false, error: "adoption_receiver_in_progress" };1436        }1437        const password = (msg.payload as { password?: unknown } | undefined)?.password;1438        if (typeof password !== "string" || password.length === 0) {1439          return { ok: false, error: "invalid_payload" };1440        }1441        try {1442          return { ok: true, data: await startRelayAdoptionReceiver(password) };1443        } catch (error) {1444          return {1445            ok: false,1446            error: error instanceof Error ? error.message : "adoption_receiver_failed",1447          };1448        }1449      }14501451      // Popup→bg counterpart to ADOPTION_SOURCE_SAS (receiver flow).1452      // The receiver now auto-accepts the SAS (both sides derive it from the1453      // same Noise handshake hash, so the codes match by construction) so1454      // the popup never has a SAS screen to tap on. The id round-trips the1455      // same way so a stale late response can't approve the wrong session.1456      // Popup→bg counterpart for the source flow: Confirm/Cancel on the1457      // source's SAS screen.14581459      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1460      // on the source's SAS screen. The id round-trips the same way so a stale1461      // late response can't approve the wrong session.1462      case "SOURCE_SAS_DECISION": {1463        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1464        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1465          return { ok: false, error: "invalid_payload" };1466        }1467        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1468      }14691470      case "CANCEL_ADOPTION_SOURCE": {1471        cancelRelayAdoptionSource();1472        return { ok: true };1473      }14741475      case "TRIGGER_SYNC": {1476        const payload = (msg.payload ?? {}) as {1477          reason?: "vault_change" | "foreground" | "manual";1478          force?: boolean;1479        };1480        const reason = payload.reason ?? "foreground";14811482        void triggerSyncIfReachable({ reason, force: payload.force === true });1483        return { ok: true };1484      }14851486      case "GET_SYNC_STATE": {1487        return { ok: true, data: getSyncState() };1488      }14891490      case "GET_SYNC_SETTINGS": {1491        return { ok: true, data: await getSyncSettings() };1492      }14931494      case "SET_SYNC_SETTINGS": {1495        const payload = (msg.payload ?? {}) as {1496          mode?: unknown;1497          relayUrl?: unknown;1498        };1499        try {1500          // A custom relay URL implies private mode; Peach's own relay stays1501          // public. See setRelayUrl.1502          if (payload.relayUrl !== undefined) {1503            if (typeof payload.relayUrl !== "string") {1504              return { ok: false, error: "invalid_relay_url" };1505            }1506            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1507          }1508          if (payload.mode !== undefined) {1509            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1510              return { ok: false, error: "invalid_sync_mode" };1511            }1512            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1513          }1514          return { ok: true, data: await getSyncSettings() };1515        } catch (error) {1516          return {1517            ok: false,1518            error: error instanceof Error ? error.message : "invalid_relay_url",1519          };1520        }1521      }15221523      case "GET_SYNC_ALERTS": {1524        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1525        const alerts = await getPendingSyncAlerts();1526        // The popup reads on open and acknowledges with consume:true after1527        // rendering, so a popup crash between read and render doesn't lose1528        // the alerts.1529        if (consume) await clearPendingSyncAlerts();1530        return { ok: true, data: alerts };1531      }15321533      case "GET_PENDING_VOUCHED_DEVICES": {1534        return { ok: true, data: await listPendingVouchedDevices() };1535      }1536      case "CONFIRM_VOUCHED_DEVICE": {1537        const { deviceId } = msg.payload as { deviceId: string };1538        const pending = await getPendingVouchedDevice(deviceId);1539        if (!pending) return { ok: false, error: "not_pending" };1540        // Last gate before a vouched device becomes a sync peer. A queue entry1541        // can predate the revocation that names it, so revocation is re-checked1542        // here rather than trusted to have swept the queue.1543        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {1544          await removePendingVouchedDevice(deviceId);1545          return { ok: false, error: "device_revoked" };1546        }1547        await upsertPairedDeviceV3({1548          deviceId: pending.deviceId,1549          deviceName: pending.deviceName,1550          deviceType:1551            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1552          longTermPublicKeyHex: pending.longTermPublicKeyHex,1553          signingPublicKeyHex: pending.signingPublicKeyHex,1554          wsPort: pending.wsPort,1555          pairedAt: pending.pairedAt,1556          trustSource: "vouched",1557        });1558        await removePendingVouchedDevice(deviceId);1559        // Newly confirmed vouched device is now a sync target — kick a round1560        // so the mesh introduction pays off without a 10-minute wait.1561        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1562        return { ok: true };1563      }1564      case "REJECT_VOUCHED_DEVICE": {1565        const { deviceId } = msg.payload as { deviceId: string };1566        await removePendingVouchedDevice(deviceId);1567        return { ok: true };1568      }1569      case "ROTATE_SYNC_IDENTITY": {1570        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1571        const result = await vault.rotateSyncIdentity();1572        return result.ok ? { ok: true } : { ok: false, error: result.error };1573      }15741575      default:1576        return { ok: false, error: "unknown_message_type" };1577    }1578  } catch (err) {1579    return {1580      ok: false,1581      error: err instanceof Error ? err.message : "operation_failed",1582    };1583  }1584}15851586// --- Mobile platform helpers ---15871588// Android: populates the in-memory vault used by PeachAutofillService.1589async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1590  const plugin = nativePlugin<{1591    setEntries?: (args: {1592      entries: Array<{1593        id: string;1594        title: string;1595        username: string;1596        email: string;1597        password: string;1598        url: string;1599        totp: string;1600        additionalUrls: string[];1601      }>;1602    }) => Promise<void>;1603  }>("InMemoryVaultPlugin");1604  if (!plugin?.setEntries) return;1605  await plugin.setEntries({1606    entries: entries.map((e) => ({1607      id: e.id,1608      title: e.title ?? "",1609      username: e.username ?? "",1610      email: (e as VaultEntry & { email?: string }).email ?? "",1611      password: e.password ?? "",1612      url: e.url ?? "",1613      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1614      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1615    })),1616  });1617}16181619// Android: clear the autofill in-memory store on lock.1620async function clearInMemoryVault(): Promise<void> {1621  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1622  if (!plugin?.clearEntries) return;1623  await plugin.clearEntries();1624}16251626// Returns username use-counts from the vault, sorted by frequency. Each row1627// also carries the entry's email so the popup can suggest the email/username1628// pair the user has actually used together.1629function buildIdentitySuggestions(1630  entries: VaultEntry[],1631): Array<{ email: string; username: string; count: number }> {1632  const usernameCounts = new Map<string, number>();1633  const usernameEmail = new Map<string, string>();1634  for (const entry of entries) {1635    const username = entry.username ?? "";1636    const email = (entry as VaultEntry & { email?: string }).email ?? "";1637    if (!username && !email) continue;1638    const key = username || email;1639    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1640    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1641  }1642  return Array.from(usernameCounts.entries())1643    .sort((a, b) => b[1] - a[1])1644    .map(([username, count]) => ({1645      email: usernameEmail.get(username) ?? "",1646      username,1647      count,1648    }));1649}16501651/** Notify all content scripts that the vault just became available. */1652function broadcastToContentScripts(message: { type: string }): void {1653  if (!chrome.tabs?.query) return;1654  chrome.tabs.query({}, (tabs) => {1655    for (const tab of tabs) {1656      if (tab.id !== undefined) {1657        chrome.tabs.sendMessage(tab.id, message).catch(() => {1658          // Tab may not have a content script — silently ignore1659        });1660      }1661    }1662  });1663}16641665function shouldRefreshAutoLock(type: MessageType): boolean {1666  return (1667    type !== "HAS_VAULT" &&1668    type !== "IS_UNLOCKED" &&1669    type !== "GET_VAULT_STATUS" &&1670    type !== "LOCK" &&1671    type !== "UPDATE_SETTINGS" &&1672    type !== "GET_PENDING_PASSKEY" &&1673    type !== "GET_PASSKEY_PROVIDER_STATE" &&1674    type !== "DECLINE_CARD_SAVE" &&1675    type !== "IS_CARD_DECLINED"1676  );1677}16781679function isAllowedCanaryWebhookUrl(value: string): boolean {1680  try {1681    const url = new URL(value);1682    if (url.protocol !== "https:") return false;16831684    const hostname = url.hostname.toLowerCase();1685    if (1686      hostname === "localhost" ||1687      hostname.endsWith(".localhost") ||1688      isPrivateIpv4(hostname) ||1689      isPrivateIpv6(hostname)1690    ) {1691      return false;1692    }16931694    return true;1695  } catch {1696    return false;1697  }1698}16991700function isPrivateIpv4(hostname: string): boolean {1701  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1702    return true;1703  }17041705  const octets = hostname.split(".").map((part) => Number(part));1706  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1707    return false;1708  }17091710  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1711}17121713function isPrivateIpv6(hostname: string): boolean {1714  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1715  // IPv4-mapped IPv6 literals embed a plain IPv4 address that the prefix1716  // list below can never match (WHATWG URL serializes [::ffff:192.168.0.1]1717  // as ::ffff:c0a8:1). Unwrap and test the embedded IPv4; unparseable mapped1718  // tails fail closed. (Codex Security 2026-08-04 LOW,1719  // ssrf.webhook-url-private-ip-filter.) DNS rebinding is out of scope for a1720  // one-shot host check.1721  const mapped = /^::ffff:(.+)$/.exec(normalized);1722  if (mapped) {1723    const tail = mapped[1] ?? "";1724    if (tail.includes(".")) return isPrivateIpv4(tail);1725    const parts = tail.split(":");1726    const [hi, lo] = parts;1727    if (1728      parts.length !== 2 ||1729      !hi ||1730      !lo ||1731      !/^[0-9a-f]{1,4}$/.test(hi) ||1732      !/^[0-9a-f]{1,4}$/.test(lo)1733    ) {1734      return true;1735    }1736    const octets = [1737      (Number.parseInt(hi, 16) >>> 8) & 0xff,1738      Number.parseInt(hi, 16) & 0xff,1739      (Number.parseInt(lo, 16) >>> 8) & 0xff,1740      Number.parseInt(lo, 16) & 0xff,1741    ];1742    return isPrivateIpv4(octets.join("."));1743  }1744  return (1745    normalized === "::1" ||1746    normalized.startsWith("fc") ||1747    normalized.startsWith("fd") ||1748    normalized.startsWith("fe80:")1749  );1750}