messages.ts

72.4 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  revokeDeviceById as revokeDeviceByIdV3,78  upsertPairedDevice as upsertPairedDeviceV3,79} from "./paired-devices";80// Sync and pairing are imported statically, never with `await import()`.81// `import()` throws `TypeError: import() is disallowed on82// ServiceWorkerGlobalScope` at runtime in MV3, and Vite's preload helper83// reports the failure through `window.dispatchEvent`, which does not exist in84// a worker either — so the real reason was replaced by "window is not defined"85// and the pairing UI just stopped. scripts/check-sw-static-imports.mjs fails86// the build if a runtime import() reappears anywhere in the worker's graph.87import {88  cancelRelayAdoptionSource,89  isRelayAdoptionSourceInFlight,90  resolveSourceSasConfirmation,91  startRelayAdoptionReceiver,92  startRelayAdoptionSource,93} from "./relay-adoption-bg";94import {95  getSyncSettings,96  setRelayUrl,97  setSyncMode,98  type SyncMode,99} from "./sync-settings";100import {101  getSyncState,102  hydratePersistedSyncState,103  setSyncRunner,104  triggerSyncIfReachable,105} from "./sync-trigger";106import { productionSyncRunner } from "./sync-runner";107108// Compile-time E2E flag, folded to a literal by Vite's `define` (false in109// every production build — verified in the bundled output). Mirrors the110// create-path bypass in passkey.ts so the Playwright passkey smoke can enable111// the provider without a real Pro licence; the gate is fully intact for users.112declare const __PEACH_E2E_PASSKEYS__: boolean;113const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true;114115let nativeSyncRunnerBootstrapped = false;116117function unhexBytes(hex: string): Uint8Array {118  if (hex.length % 2 !== 0) throw new Error("invalid hex");119  const out = new Uint8Array(hex.length / 2);120  for (let i = 0; i < out.length; i++) {121    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);122  }123  return out;124}125126/**127 * The single Pro gate. Every gated handler calls this first; the broadcast128 * lets the popup react (navigate to the License section, highlight the129 * relevant feature). Background never touches the popup view directly —130 * the popup owns navigation. See Projects.md "Pro gate rule".131 */132async function requirePro(133  feature: ProFeature,134  trigger: "user" | "background" = "user"135): Promise<{ allowed: boolean }> {136  if (PASSKEY_E2E_PRO_BYPASS && feature === "passkeys") return { allowed: true };137  if (await isProUser()) return { allowed: true };138139  if (trigger === "user") {140    // User deliberately triggered this feature — redirect the popup immediately.141    chrome.runtime142      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })143      .catch(() => {144        // Popup may be closed — the gate signal is best-effort.145      });146  } else {147    // Background trigger (e.g. passive sync initiation) — no popup is open.148    // Queue a notice so the next popup open shows a soft banner instead of149    // silently failing.150    if (chrome.storage.session) {151      chrome.storage.session152        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })153        .catch(() => {});154    }155  }156157  return { allowed: false };158}159160// ---------------------------------------------------------------------------161// PCH-01-018: operations that irreversibly destroy or replace vault contents,162// plus handlers that store passkey material. These are gated to trusted163// extension-page senders in handleMessage; the confirmation UX otherwise164// lives only in the popup. Keep this in sync when adding new destructive or165// sensitive handlers. (Codex Security 2026-08-04: GET_ADOPTION_MATERIAL and166// COMPLETE_PAIRING were gated here, then deleted outright — they had no167// legitimate senders; adoption runs in-background via relay-adoption-bg.ts.)168const PRIVILEGED_MESSAGE_TYPES: ReadonlySet<string> = new Set([169  "DESTROY_VAULT",170  "CLEAR_VAULT_ENTRIES",171  "RESTORE_VAULT_SNAPSHOT",172  "RESTORE_FROM_CODEX",173  "COMPLETE_FIREFOX_PASSKEY_CREATE",174]);175176// LV-3: minimum interval between non-test canary pings per webhook+entry.177const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour178179const PRIVATE_IPV4_RANGES = [180  { prefix: "10." },181  { prefix: "127." },182  { prefix: "169.254." },183  { prefix: "192.168." },184];185186export function setupMessageHandler(): void {187  chrome.runtime.onMessage.addListener(188    (msg: unknown, sender, sendResponse) => {189      if (!isMessage(msg)) {190        sendResponse({ ok: false, error: "invalid_message" });191        return true;192      }193      handleMessage(msg, sender)194        .then(sendResponse)195        .catch((err) =>196          sendResponse({197            ok: false,198            error: err instanceof Error ? err.message : String(err),199          })200        );201      return true;202    }203  );204205  // Android: the chrome shim queues sendMessage calls until this handler is206  // registered. Without this hookup, every message hangs on Capacitor builds.207  // eslint-disable-next-line @typescript-eslint/no-explicit-any208  const reg = (globalThis as any).__peachRegisterMessageHandler;209  if (typeof reg === "function") {210    reg(async (m: unknown) => {211      if (!isMessage(m)) return { ok: false, error: "invalid_message" };212      try {213        return await handleMessage(m);214      } catch (err) {215        return {216          ok: false,217          error: err instanceof Error ? err.message : String(err),218        };219      }220    });221  }222  if (isNativePlatform()) {223    void bootstrapNativeSyncRunner();224  }225}226227async function bootstrapNativeSyncRunner(): Promise<void> {228  if (nativeSyncRunnerBootstrapped) return;229  nativeSyncRunnerBootstrapped = true;230  try {231    setSyncRunner(productionSyncRunner);232    await hydratePersistedSyncState();233  } catch (err) {234    nativeSyncRunnerBootstrapped = false;235    console.warn("[Peach] failed to bootstrap native sync runner:", err);236  }237}238239function isMessage(m: unknown): m is Message {240  return typeof m === "object" && m !== null && "type" in m;241}242243/**244 * The browser-attested origin of the page that originated this message. A web245 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),246 * so every page-driven message arrives via the content-script relay and the247 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a248 * value the page cannot forge. This is the ONLY trustworthy origin for passkey249 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.250 */251function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {252  if (sender.origin) return sender.origin;253  if (sender.url) {254    try { return new URL(sender.url).origin; } catch { return undefined; }255  }256  return undefined;257}258259// Resolves once restoreFromSession() has run, so handlers see the correct260// post-restore unlock state. entry.ts registers this BEFORE the message261// handler so the onMessage listener is added synchronously at SW startup262// (MV3 requirement) while unlock-dependent handlers still wait for restore.263let restoreReady: Promise<void> = Promise.resolve();264265/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */266export function setRestoreReady(p: Promise<unknown>): void {267  restoreReady = p.then(() => undefined, () => undefined);268}269270export async function handleMessage(271  msg: Message,272  sender: Partial<chrome.runtime.MessageSender> = {}273): Promise<MessageResponse> {274  try {275    // Wait for session-restore to finish before reading any unlock/vault state.276    // On a cold SW start the popup's first message arrives while restore is277    // still in flight; without this gate IS_UNLOCKED would report locked (a278    // spurious lock screen) and the storage reads could race. The onMessage279    // listener itself is registered synchronously (entry.ts) so this gate, not280    // listener registration, is what absorbs the cold-start window.281    await restoreReady;282    // Validate sender — only allow messages from our extension pages/scripts.283    // `sender.id` is undefined for messages originating from extension UI284    // (popup/options), which is legitimate; reject only when it is defined285    // and does not match our extension id.286    if (287      sender.id !== undefined &&288      sender.id !== chrome.runtime.id289    ) {290      return { ok: false, error: "invalid_sender" };291    }292293    // PCH-01-018: destructive and sensitive operations must originate from a294    // trusted extension page (popup/options), never from a content script. The295    // sender.id check above only proves the message came from *our* extension —296    // a content script injected into an attacker page passes it. A single297    // XSS-class bug in the injected UI would otherwise escalate to vault298    // destruction, root-key exfiltration, or attacker device registration.299    // Extension pages carry an extension-origin sender.url; content scripts300    // carry a page URL.301    if (PRIVILEGED_MESSAGE_TYPES.has(msg.type)) {302      const extensionOrigin = chrome.runtime.getURL("");303      if (!sender.url?.startsWith(extensionOrigin)) {304        return { ok: false, error: "invalid_sender" };305      }306    }307308    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {309      touchAutoLock();310    }311312    switch (msg.type) {313      case "CREATE_VAULT": {314        const { password } = msg.payload as { password: string };315        // Refuse to create a vault under an empty master password — the derived316        // key would be publicly known and the at-rest AES-GCM protection void317        // (audit HIGH; the CSV-import path previously passed ""). Length/strength318        // policy lives in the onboarding UI; this is the non-negotiable floor.319        if (typeof password !== "string" || password.length === 0) {320          return { ok: false, error: "invalid_payload" };321        }322        await vault.createVault(password);323        await setupAutoLock();324        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });325        onVaultUnlocked();326        return { ok: true };327      }328      case "CREATE_VAULT_FROM_ROOT_KEY": {329        console.log("[Peach diag] CREATE_VAULT_FROM_ROOT_KEY handler entered");330        const { password, rootKeyHex } = (msg.payload ?? {}) as {331          password?: unknown;332          rootKeyHex?: unknown;333        };334        console.log("[Peach diag] payload types:", typeof password, typeof rootKeyHex, "lengths:", (password as string)?.length, (rootKeyHex as string)?.length);335        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {336          console.log("[Peach diag] payload invalid, returning invalid_payload");337          return { ok: false, error: "invalid_payload" };338        }339340        try {341          console.log("[Peach diag] calling vault.createVaultFromRootKey");342          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);343          console.log("[Peach diag] createVaultFromRootKey returned vaultId", vaultId);344          await setupAutoLock();345          console.log("[Peach diag] setupAutoLock done");346          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });347          onVaultUnlocked();348          console.log("[Peach diag] handler completing successfully");349          return { ok: true, vaultId };350        } catch (err) {351          console.error("[Peach diag] handler caught error:", err);352          return { ok: false, error: err instanceof Error ? err.message : String(err) };353        }354      }355      case "UNLOCK": {356        const { password } = msg.payload as { password: string };357        const ok = await vault.unlock(password);358        if (ok) {359          // KAT: verify the WebCrypto stack is healthy before the user relies on it.360          // Runs after unlock so latency is hidden behind the vault-load time.361          const kat = await runSelfTest();362          if (!kat.ok) {363            console.error("[Peach] Crypto self-test FAILED:", kat.error);364            await vault.lock();365            return { ok: false, error: "self_test_failed" };366          }367          await setupAutoLock();368          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });369          onVaultUnlocked();370          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());371          return { ok: true };372        }373        // Distinguish corruption from wrong password so the popup can offer374        // a history-restore path instead of falsely accusing the user of375        // mistyping (M7/COR-007).376        const failure = vault.consumeLastUnlockFailureReason();377        if (failure) {378          return {379            ok: false,380            error: "vault_corrupted",381            canRestoreFromHistory: true,382          } as MessageResponse;383        }384        return { ok: false };385      }386      case "VALIDATE_RECOVERY_WORDS": {387        const { words } = msg.payload as { words: string[] };388        const invalid = findInvalidWords(words);389        return { ok: true, data: { valid: invalid.length === 0, invalid } };390      }391      case "GET_RECOVERY_WORDS": {392        // Must be unlocked and have recovery set up (vault must be v2.12+).393        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };394        // LV-4: the recovery words re-derive the ROOT KEY — the highest-395        // value secret in the vault. A session unlock (which may be hours396        // old on a shared machine) is not enough; require a fresh password397        // proof, matching the 1Password/Bitwarden pattern for revealing398        // escrow material. EXEMPTION: the create-vault / rotation confirmation399        // window (peach_recovery_pending) shows the words immediately after400        // the user authenticated, and that confirmation UI has no password to401        // resend — skip the re-auth there only.402        if (!(await isRecoveryConfirmPending())) {403          const { password } = (msg.payload ?? {}) as { password?: string };404          if (typeof password !== "string" || !password) {405            return { ok: false, error: "password_required" };406          }407          if (!(await vault.verifyMainPassword(password))) {408            return { ok: false, error: "wrong_password" };409          }410        }411        try {412          const words = await vault.getRecoveryWords();413          return { ok: true, data: words };414        } catch (e) {415          // pre-v2.12 vault that hasn't migrated416          return { ok: false, error: "recovery_not_setup" };417        }418      }419      case "RECOVER_WITH_WORDS": {420        // User has lost their password but has their 12 recovery words.421        // We: (1) validate the words, (2) re-encrypt vault with new password.422        const { words, newPassword } = msg.payload as {423          words: string[];424          newPassword: string;425        };426        const stored = await vault.loadSlotA();427        if (!stored) return { ok: false, error: "no_vault" };428        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {429          return { ok: false, error: "recovery_not_setup" };430        }431        // Unwrap the root key from the recovery escrow.432        try {433          await vault.unwrapRootKeyForRecovery(434            stored.recovery_wrapped_root_key,435            stored.recovery_nonce ?? "",436            stored.recovery_tag ?? "",437            stored.recovery_salt,438            words439          );440        } catch {441          return { ok: false, error: "invalid_recovery_words" };442        }443        // Re-key: derive fresh salt + key from new password.444        const newSalt = vault.generateSalt();445        const newKey = await vault.deriveKey(newPassword, newSalt);446        // Re-wrap root key under the new password's derived key so the same447        // recovery words continue to work after the password change.448        await vault.rewrapRootKeyForPassword(newKey, newSalt);449        // Re-encrypt vault entries with the new key.450        await vault.changePasswordWithNewKey(newSalt, newKey);451        await setupAutoLock();452        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });453        return { ok: true };454      }455      case "LOCK":456        vault.lock();457        if (isNativePlatform()) await clearInMemoryVault();458        return { ok: true };459      case "IS_UNLOCKED":460        return { ok: true, data: vault.isUnlocked() };461      case "GET_VAULT_STATUS":462        return { ok: true, unlocked: vault.isUnlocked() };463      case "HAS_VAULT":464        return { ok: true, data: await vault.hasVault() };465      case "GET_ENTRIES":466        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };467        return { ok: true, data: vault.getEntries() };468      case "ADD_ENTRY": {469        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };470        const payload = msg.payload;471        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {472          return { ok: false, error: "invalid_payload" };473        }474        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);475        return { ok: true, data: entry };476      }477      case "BATCH_ADD_ENTRIES": {478        const payload = msg.payload as { entries?: unknown } | null | undefined;479        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {480          return { ok: false, error: "invalid_payload" };481        }482        if (!Array.isArray(payload.entries)) {483          return { ok: false, error: "invalid_payload" };484        }485        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);486        return { ok: true, data: added };487      }488      case "RESTORE_ENTRIES": {489        const payload = msg.payload as490          | { entries?: unknown; mode?: unknown; settings?: unknown }491          | null492          | undefined;493        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {494          return { ok: false, error: "invalid_payload" };495        }496        if (!Array.isArray(payload.entries)) {497          return { ok: false, error: "invalid_payload" };498        }499        if (payload.mode !== "replace" && payload.mode !== "merge") {500          return { ok: false, error: "invalid_payload" };501        }502        const summary = await vault.restoreEntries(503          payload.entries as Parameters<typeof vault.restoreEntries>[0],504          payload.mode505        );506        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {507          await vault.updateSettings(payload.settings as vault.VaultSettings);508        }509        return { ok: true, data: summary };510      }511      case "CLEAR_VAULT_ENTRIES": {512        await vault.clearVaultEntries("REPLACE_ALL");513        return { ok: true };514      }515      case "GET_VAULT_HISTORY": {516        const snapshots = await vault.getVaultHistory();517        return { ok: true, data: snapshots };518      }519      case "RESTORE_VAULT_SNAPSHOT": {520        const { snapshotId } = msg.payload as { snapshotId: string };521        const result = await vault.restoreVaultSnapshot(snapshotId);522        if (!result.ok) return { ok: false, error: result.error };523        broadcastToContentScripts({ type: "VAULT_LOCKED" });524        return { ok: true };525      }526      case "COUNT_DUPLICATES": {527        return { ok: true, data: vault.countDuplicates() };528      }529      case "DEDUPLICATE_ENTRIES": {530        const removed = await vault.deduplicateEntries();531        return { ok: true, data: removed };532      }533      case "UPDATE_ENTRY": {534        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;535        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {536          return { ok: false, error: "invalid_payload" };537        }538        const { id, patch } = payload;539        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {540          return { ok: false, error: "invalid_payload" };541        }542        // Single enforcement point for the Canary Entries Pro gate. Only543        // gates the transition into a canary entry — clearing/disabling a544        // canary (`canary: undefined`) is always allowed, so existing545        // canary entries remain manageable.546        const incomingCanary = (patch as { canary?: unknown }).canary;547        if (incomingCanary && typeof incomingCanary === "object") {548          const existing = vault.getEntryById(id);549          if (!existing?.canary) {550            const gate = await requirePro("canary_entry");551            if (!gate.allowed) return { ok: false, error: "pro_required" };552          }553        }554        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);555        return { ok: true };556      }557      case "ADD_ADDITIONAL_URL": {558        const { id, url } = msg.payload as { id: string; url: string };559        const trimmed = typeof url === "string" ? url.trim() : "";560        if (!trimmed) return { ok: false, error: "url_required" };561        const existing = vault.getEntryById(id);562        if (!existing) return { ok: false, error: "entry_not_found" };563        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };564        const merged = [...(existing.additionalUrls ?? []), trimmed];565        await vault.updateEntry(id, { additionalUrls: merged });566        return { ok: true };567      }568      case "DELETE_ENTRY": {569        const { id } = msg.payload as { id: string };570        await vault.deleteEntry(id);571        return { ok: true };572      }573      case "GET_DELETED_ENTRIES":574        return { ok: true, data: vault.getDeletedEntries() };575      case "RESTORE_ENTRY": {576        const { id } = msg.payload as { id: string };577        await vault.restoreEntry(id);578        return { ok: true };579      }580      case "PURGE_ENTRY": {581        const { id } = msg.payload as { id: string };582        await vault.purgeEntry(id);583        return { ok: true };584      }585      case "PURGE_EXPIRED_TRASH": {586        const { retentionMs } = msg.payload as { retentionMs: number };587        const purged = await vault.purgeExpiredTrash(retentionMs);588        return { ok: true, data: purged };589      }590      case "SAVE_NOTE": {591        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };592        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };593        const now = Date.now();594        if (id) {595          const existing = vault.getEntryById(id);596          if (!existing) return { ok: false, error: "not_found" };597          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });598          return { ok: true, data: vault.getEntryById(id) };599        } else {600          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt601          // (EntryDraft omits both), so passing them was the only reason the602          // `as any` cast existed. Dropping them makes the call type-check.603          const entry = await vault.addEntry({604            type: "note",605            title: title || "Untitled",606            notes: body,607          });608          return { ok: true, data: entry };609        }610      }611      case "DELETE_NOTE": {612        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };613        const { id } = msg.payload as { id: string };614        await vault.deleteEntry(id);615        return { ok: true };616      }617      case "GET_NOTES": {618        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };619        const notes = vault.getEntries().filter(620          (e) => e.type === "note" && !e.deletedAt621        );622        return { ok: true, data: notes } as MessageResponse;623      }624      case "SEARCH_VAULT": {625        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };626        // AUD-002: shape-validate the payload before calling string methods.627        // A raw cast lets a malformed message crash the handler with TypeError.628        const { query } = (msg.payload ?? {}) as { query?: unknown };629        if (typeof query !== "string") {630          return { ok: false, error: "invalid_payload" };631        }632        const q = query.toLowerCase();633        const searchResults = vault.getEntries().filter(634          (e) =>635            !e.deletedAt &&636            (e.title.toLowerCase().includes(q) ||637              e.notes?.toLowerCase().includes(q) ||638              e.username?.toLowerCase().includes(q))639        );640        return { ok: true, data: searchResults } as MessageResponse;641      }642      case "AUTOFILL_QUERY": {643        if (!vault.isUnlocked()) {644          return { ok: false, error: "vault_locked" };645        }646        let { includeAll } = msg.payload as { includeAll?: boolean };647        const { domain, kind, userGesture } = msg.payload as {648          domain: string;649          kind?: "login" | "card" | "totp";650          userGesture?: boolean;651        };652        // MV-2: the vault-wide inventory (every title/username/email/url)653        // may only leave the background on an explicit user gesture — the654        // user opening the search affordance — never on passive form focus.655        // userGesture is self-declared by our own content script; the value656        // of this gate is that PASSIVE code paths (which never set it)657        // cannot ship the inventory, shrinking what a compromised page that658        // merely triggers focus events can observe.659        if (includeAll && userGesture !== true) {660          includeAll = false;661        }662        // kind="card": return saved cards as compact summaries for the663        // inline card silver platter. Cards are not domain-scoped — every664        // saved card is a candidate on every checkout page — so domain is665        // ignored when kind === "card".666        if (kind === "card") {667          const cards = vault.getEntries().filter((e) => e.type === "card");668          return {669            ok: true,670            data: cards.map((e) => ({671              id: e.id,672              title: e.cardNickname || e.title,673              cardholderName: e.cardholderName,674              last4: e.last4,675              expMonth: e.expMonth,676              expYear: e.expYear,677              network: e.network,678            })),679          };680        }681        if (kind === "totp") {682          const matches = (683            includeAll684              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")685              : vault.queryDomain(domain)686          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));687          return {688            ok: true,689            data: matches.map((e) => ({690              id: e.id,691              title: e.title,692              username: e.username,693              email: e.email,694              url: e.url,695              hasTotp: true,696            })),697          };698        }699        // The inline selector fills username+password into a form. Passkey-700        // only entries have no password to fill; sign-in for those goes701        // through the WebAuthn path instead. Filter them out everywhere so702        // the user doesn't see four "GitHub" rows that mostly do nothing.703        // Notes and cards never belonged here either.704        const matches = (705          includeAll706            ? vault707                .getEntries()708                .filter((entry) => entry.type !== "note" && entry.type !== "card")709            : vault.queryDomain(domain)710        ).filter((entry) => !isPasskeyOnly(entry));711        return {712          ok: true,713          data: matches.map((e) =>714            includeAll715              ? {716                  id: e.id,717                  title: e.title,718                  // username/email/url shipped so the inline popup's search719                  // affordance can match on them, not just titles. No secrets720                  // cross the boundary — same shape as the domain-matched721                  // response below minus hasTotp (which the search list722                  // doesn't surface).723                  username: e.username,724                  email: e.email,725                  url: e.url,726                  hasPasskey: e.passkey !== undefined,727                }728              : {729                  id: e.id,730                  title: e.title,731                  username: e.username,732                  email: e.email,733                  url: e.url,734                  hasTotp: Boolean(e.totp),735                  hasPasskey: e.passkey !== undefined,736                }737          ),738        };739      }740      case "GET_ENTRY_FOR_FILL": {741        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };742        const { id, explicitSummon } = msg.payload as {743          id: string;744          explicitSummon?: boolean;745        };746        const entry = vault.getEntryById(id);747        if (!entry) return { ok: false, error: "entry_not_found" };748        // Passkey-only entries (passkey credential, no password) cannot be749        // filled into a form — sign-in goes through the WebAuthn path. A750        // login that ALSO has a passkey is still fillable for its password.751        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };752753        // MV-1: re-validate the entry against the requesting tab's origin.754        // sender.tab.url is browser-attested — a page cannot forge it. When755        // the request does not come from a tab at all (popup surfaces use756        // GET_ENTRY_FOR_EDIT, not this), refuse.757        if (sender.tab !== undefined || sender.url !== undefined) {758          let senderDomain: string | null = null;759          try {760            const rawUrl = sender.tab?.url ?? sender.url ?? "";761            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;762          } catch {763            senderDomain = null;764          }765          if (!senderDomain) return { ok: false, error: "origin_unverified" };766767          const entryDomains = new Set<string>();768          const primary = extractDomain(entry.url ?? "");769          if (primary) entryDomains.add(primary);770          for (const extra of entry.additionalUrls ?? []) {771            const d = extractDomain(extra);772            if (d) entryDomains.add(d);773          }774775          // explicitSummon=true means the user actively picked this entry776          // from the cross-domain search affordance — an intentional777          // off-domain fill. Passive fill paths must stay domain-bound.778          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {779            // Domain mismatch — refuse silently (no oracle about which ids exist).780            return { ok: false, error: "entry_not_found" };781          }782        }783        // Strip the passkey credential AND the raw base32 TOTP seed from the784        // response. Content scripts never need either: the private key is the785        // authenticator's, and handing over the TOTP seed would let a786        // compromised content script mint valid codes indefinitely (SEV-3-C).787        // Generate the *current* 6-digit code here in the background and send788        // only that, plus the seconds left so the UI can render a countdown.789        // Also drop passwordHistory: filling needs only the *current* password.790        // Handing every past password to a content script during passive791        // autofill on an arbitrary page would widen the blast radius of a792        // compromised page far beyond the one credential being filled.793        const {794          passkey: _strippedPasskey,795          totp: seed,796          totpAlgorithm,797          totpDigits,798          totpPeriod,799          passwordHistory: _ph,800          ...safeEntry801        } = entry;802        let totpCode: string | undefined;803        let totpRemaining: number | undefined;804        if (seed) {805          try {806            // PCH-01-019: honour stored algorithm/digits/period (defaults apply807            // when these are undefined, i.e. legacy bare-seed entries).808            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);809            totpCode = generated.code;810            totpRemaining = generated.remaining;811          } catch {812            totpCode = undefined;813          }814        }815        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };816      }817      // Trusted full-entry fetch for Peach's own inline-popup surfaces that818      // genuinely need the raw TOTP seed: the edit form (which re-saves the819      // seed and would otherwise wipe it) and nothing else. Unlike820      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside821      // the inline popup, never during passive autofill on an arbitrary page.822      // The passkey credential is still stripped — the edit form never touches it.823      case "GET_ENTRY_FOR_EDIT": {824        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };825        const { id, explicitSummon } = msg.payload as {826          id: string;827          explicitSummon?: boolean;828        };829        const entry = vault.getEntryById(id);830        if (!entry) return { ok: false, error: "entry_not_found" };831832        // PCH-01-006: re-validate the browser-attested sender origin, mirroring833        // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and834        // full password history — at least as sensitive as the fill response — so835        // the boundary must be enforced here, not only by UI reachability. Today836        // the sole caller is the popup (no sender.tab, so this is a structural837        // no-op), but a future tab-context caller or an id leak would otherwise838        // inherit a full-credential oracle. Unlike the fill path we SKIP (not839        // refuse) when no sender domain resolves, to keep the popup caller working.840        if (sender.tab !== undefined || sender.url !== undefined) {841          let senderDomain: string | null = null;842          try {843            const rawUrl = sender.tab?.url ?? sender.url ?? "";844            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;845          } catch {846            senderDomain = null;847          }848          if (senderDomain) {849            const entryDomains = new Set<string>();850            const primary = extractDomain(entry.url ?? "");851            if (primary) entryDomains.add(primary);852            for (const extra of entry.additionalUrls ?? []) {853              const d = extractDomain(extra);854              if (d) entryDomains.add(d);855            }856            if (explicitSummon !== true && !entryDomains.has(senderDomain)) {857              return { ok: false, error: "entry_not_found" }; // no id oracle858            }859          }860        }861862        const { passkey: _passkey, ...safeEntry } = entry;863        return { ok: true, data: safeEntry };864      }865      case "COPY": {866        // AUD-002: shape-validate the payload before passing to the clipboard867        // helper. A raw cast lets a malformed message reach the clipboard API868        // with a non-string and throw.869        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {870          text?: unknown;871          label?: unknown;872          alreadyWritten?: unknown;873        };874        if (typeof text !== "string" || typeof label !== "string") {875          return { ok: false, error: "invalid_payload" };876        }877        await copyToClipboard(text, label, Boolean(alreadyWritten));878        return { ok: true, clearSeconds: getEffectiveClearSeconds() };879      }880      case "CHECK_ALL_BREACHES": {881        const allEntries = vault.getEntries();882        const results: Record<string, number> = {};883        for (const entry of allEntries) {884          if (entry.type === "note") continue;885          if (!entry.password) continue;886          results[entry.id] = await vault.checkBreach(entry.password);887          // Small delay — be a good citizen to the HIBP API888          await new Promise((r) => setTimeout(r, 200));889        }890        // Persist any non-zero counts back to entries891        for (const [id, count] of Object.entries(results)) {892          const entry = vault.getEntryById(id);893          if (entry && (entry.breach ?? 0) !== count) {894            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });895          }896        }897        return { ok: true, data: results };898      }899      case "GET_SETTINGS":900        return { ok: true, data: await vault.ensureSettingsLoaded() };901      case "UPDATE_SETTINGS": {902        const patch = msg.payload;903        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {904          return { ok: false, error: "invalid_payload" };905        }906        await vault.updateSettings(patch as vault.VaultSettings);907        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {908          await setupAutoLock();909          if (vault.isUnlocked()) touchAutoLock();910        }911        return { ok: true };912      }913      case "GET_PENDING_PASSKEY":914        return { ok: true, data: await getPendingPasskeyRequest() };915      case "APPROVE_PASSKEY": {916        const { requestId } = msg.payload as { requestId: number };917        await resolvePendingPasskeyRequest(requestId, true);918        return { ok: true };919      }920      case "DENY_PASSKEY": {921        const { requestId } = msg.payload as { requestId: number };922        await resolvePendingPasskeyRequest(requestId, false);923        return { ok: true };924      }925      case "GET_PASSKEY_PROVIDER_STATE":926        return { ok: true, data: await getPasskeyProviderState() };927      case "SET_PASSKEY_PROVIDER_ENABLED": {928        const { enabled } = msg.payload as { enabled: boolean };929        // Disabling is always free; gating fires only when a free user is930        // trying to turn passkey interception on.931        if (enabled) {932          const gate = await requirePro("passkeys");933          if (!gate.allowed) return { ok: false, error: "pro_required" };934        }935        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };936      }937      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS938      // endpoint. Intentional product behavior — users configure their own939      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private940      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-941      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to942      // users that the entry title leaves the device when the canary fires.943      case "FIRE_CANARY_PING": {944        // Canary alert fires unconditionally for any entry with canary: true.945        // The Pro gate only governs creation/flagging of canary entries; once946        // an entry is flagged, the alert path is a security property and must947        // never be license-gated.948        const { webhookUrl, entryTitle, trigger } = msg.payload as {949          webhookUrl: string;950          entryTitle: string;951          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";952        };953        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {954          return { ok: false, error: "invalid_webhook_url" };955        }956        // LV-3: debounce non-test pings per (webhook, entry) so a page that957        // strobes focus/fill events can't turn the canary into a request958        // firehose at the user's endpoint. Test pings are exempt — they are959        // explicit user clicks in the settings UI and are awaited for960        // feedback. The FIRST ping in a window always goes out, so the961        // dead-man's-switch property (canary fires on access) is preserved;962        // only repeats within the window are coalesced.963        if (trigger !== "test") {964          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;965          const stored = await chrome.storage.local.get(rlKey);966          const last = (stored as Record<string, unknown>)[rlKey];967          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {968            return { ok: true, data: { rateLimited: true } };969          }970          await chrome.storage.local.set({ [rlKey]: Date.now() });971        }972        const body = JSON.stringify({973          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",974          entry: entryTitle,975          trigger,976          timestamp: new Date().toISOString(),977          source: "peach-extension",978        });979        if (trigger === "test") {980          // Permitted outbound fetch: user-configured canary alert endpoint981          // (validated by isAllowedCanaryWebhookUrl above). This is the982          // only non-HIBP outbound call in the extension — see983          // Projects.md §3.7. Test pings are awaited so the UI can show984          // success/failure.985          try {986            const res = await fetch(webhookUrl, {987              method: "POST",988              headers: { "Content-Type": "application/json" },989              body,990            });991            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };992          } catch (err) {993            return { ok: false, error: err instanceof Error ? err.message : "network_error" };994          }995        }996        // Non-test triggers are fire-and-forget997        fetch(webhookUrl, {998          method: "POST",999          headers: { "Content-Type": "application/json" },1000          body,1001        }).catch(() => {});1002        return { ok: true };1003      }1004      case "ACTIVATE_LICENSE": {1005        const { key } = msg.payload as { key: string };1006        const licenseInfo = await activateLicense(key);1007        return { ok: true, data: licenseInfo };1008      }1009      case "GET_LICENSE": {1010        const licenseInfo = await getLicenseInfo();1011        return { ok: true, data: licenseInfo };1012      }1013      case "GET_LICENSE_KEY": {1014        const key = await getLicenseKey();1015        return { ok: true, data: key };1016      }1017      case "DEACTIVATE_LICENSE": {1018        await deactivateLicense();1019        return { ok: true };1020      }1021      case "SHOULD_PLAY_CELEBRATION": {1022        const should = await shouldPlayCelebration();1023        return { ok: true, data: should };1024      }1025      case "MARK_CELEBRATION_PLAYED": {1026        await markCelebrationPlayed();1027        return { ok: true };1028      }1029      case "GET_CODEX_VAULT_DATA": {1030        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1031        // popup navigates to the License section without further coordination.1032        const gate = await requirePro("codex");1033        if (!gate.allowed) return { ok: false, error: "pro_required" };1034        return await handleGetCodexVaultData();1035      }1036      case "ESTIMATE_CODEX_PAGES": {1037        const gate = await requirePro("codex");1038        if (!gate.allowed) return { ok: false, error: "pro_required" };1039        return await handleEstimateCodexPages();1040      }1041      case "RESTORE_FROM_CODEX": {1042        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1043        // be able to restore a vault that was printed by a Pro user.1044        // DO NOT add a Pro gate here.1045        const payload = msg.payload as CodexRestorePayload;1046        return await handleRestoreFromCodex(payload);1047      }1048      case "OPEN_PRO_GATE": {1049        // Content script requests: open popup and navigate to License section.1050        const { feature } = (msg.payload ?? {}) as { feature?: string };1051        if (chrome.storage.session) {1052          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1053        }1054        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1055        return { ok: true };1056      }1057      case "OPEN_POPUP": {1058        // Content script asks to open the trusted extension popup — used by the1059        // inline locked bubble so the master password is entered in the popup,1060        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1061        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1062        // toolbar icon. The badge already signals Peach needs attention.1063        //1064        // Set a session flag so the popup knows it was opened for inline unlock1065        // and should close itself once the vault is unlocked (returning the user1066        // to the inline autofill selector on the page).1067        if (chrome.storage.session) {1068          await chrome.storage.session.set({ peach_inline_unlock: true });1069        }1070        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1071        return { ok: true };1072      }1073      case "GET_IDENTITIES": {1074        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1075        return { ok: true, data: vault.getIdentities() };1076      }1077      case "TOUCH_AUTO_LOCK": {1078        // touchAutoLock() is already called by shouldRefreshAutoLock above;1079        // this case just gives the popup a typed message to keep the session alive.1080        return { ok: true };1081      }1082      case "GET_ADVANCED_HEALTH_REPORT": {1083        const gate = await requirePro("advanced_health");1084        if (!gate.allowed) return { ok: false, error: "pro_required" };1085        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1086        const report = await buildAdvancedHealthReport(vault.getEntries());1087        return { ok: true, data: report };1088      }1089      case "IS_DURESS_ENABLED": {1090        const enabled = await vault.isDuressEnabled();1091        return { ok: true, data: enabled };1092      }1093      case "SETUP_DURESS": {1094        // Single enforcement point for the Duress Vault Pro gate. Free users1095        // who somehow reach this handler are rejected here; the popup also1096        // pre-checks isPro() to avoid showing the setup form to free users,1097        // but server-side is the actual security boundary.1098        const gate = await requirePro("duress_vault");1099        if (!gate.allowed) return { ok: false, error: "pro_required" };1100        // MV3 service workers restart after inactivity, losing the in-memory1101        // derived key. Detect this before calling setupDuress so the popup1102        // can show a meaningful prompt to re-lock and re-unlock.1103        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1104        const { duressPassword } = msg.payload as { duressPassword: string };1105        await vault.setupDuress(duressPassword);1106        return { ok: true };1107      }1108      case "DISABLE_DURESS": {1109        await vault.disableDuress();1110        return { ok: true };1111      }1112      case "VERIFY_MAIN_PASSWORD": {1113        const { password } = msg.payload as { password: string };1114        const ok = await vault.verifyMainPassword(password);1115        return { ok: true, data: ok };1116      }1117      case "CHANGE_PASSWORD": {1118        const { currentPassword, newPassword } = msg.payload as {1119          currentPassword: string;1120          newPassword: string;1121        };1122        const changed = await vault.changePassword(currentPassword, newPassword);1123        return changed1124          ? { ok: true }1125          : { ok: false, error: "incorrect_current_password" };1126      }1127      case "GET_SITE_PASSWORD_POLICY": {1128        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1129        if (!tab?.id) return { ok: true, data: null };1130        try {1131          const response = await chrome.tabs.sendMessage(tab.id, {1132            type: "GET_SITE_PASSWORD_POLICY",1133          });1134          return (response as MessageResponse) ?? { ok: true, data: null };1135        } catch {1136          return { ok: true, data: null };1137        }1138      }1139      case "RECORD_MANUAL_SUMMON": {1140        const { domain } = msg.payload as { domain: string };1141        const settings = vault.getSettings();1142        const existing = settings.manualSummonDomains?.[domain];1143        const now = Date.now();1144        await vault.updateSettings({1145          manualSummonDomains: {1146            ...settings.manualSummonDomains,1147            [domain]: {1148              firstSummonedAt: existing?.firstSummonedAt ?? now,1149              summonCount: (existing?.summonCount ?? 0) + 1,1150              lastSummonedAt: now,1151            },1152          },1153        });1154        return { ok: true };1155      }1156      case "DECLINE_CARD_SAVE": {1157        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1158        await vault.declineCardSaveOffer(last4, expMonth, expYear);1159        return { ok: true };1160      }1161      case "IS_CARD_DECLINED": {1162        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1163        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1164        return { ok: true, data: declined };1165      }1166      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1167        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1168          rpId?: string;1169          rpName?: string;1170          userName?: string;1171          userDisplayName?: string;1172        };1173        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1174        return await initiateFirefoxPasskeyCreate({1175          rpId,1176          rpName: rpName ?? rpId,1177          userName,1178          userDisplayName,1179        }, attestedSenderOrigin(sender));1180      }11811182      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1183        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1184        if (!payload) return { ok: false, error: "missing_payload" };1185        return await completeFirefoxPasskeyCreate(payload);1186      }11871188      case "PASSKEY_OFFER_DECLINE": {1189        const { domain } = (msg.payload ?? {}) as { domain?: string };1190        if (!domain) return { ok: false, error: "domain_required" };1191        await recordPasskeyOfferDecline(domain);1192        return { ok: true };1193      }11941195      case "GET_PASSKEY_OFFER_DECLINED": {1196        const { domain } = (msg.payload ?? {}) as { domain?: string };1197        if (!domain) return { ok: false, error: "domain_required" };1198        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1199      }12001201      case "PASSKEY_HAS_CREDENTIALS": {1202        const payload = msg.payload as {1203          rpId?: string;1204          allowCredentials?: Array<{ id: string; type?: string }>;1205        } | undefined;1206        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1207        return await handlePasskeyHasCredentials({1208          rpId: payload.rpId,1209          allowCredentials: payload.allowCredentials ?? [],1210        }, attestedSenderOrigin(sender));1211      }12121213      case "PASSKEY_CREATE": {1214        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1215        if (!payload?.rpId || !payload?.userName) {1216          return { ok: false, error: "rpid_and_username_required" };1217        }1218        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1219      }12201221      case "PASSKEY_GET": {1222        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1223        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1224        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1225      }12261227      case "PASSKEY_AUTH_RESPONSE": {1228        const { requestId, approved } = (msg.payload ?? {}) as {1229          requestId?: string | number;1230          approved?: boolean;1231        };1232        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1233          return { ok: false, error: 'requestId and approved required' };1234        }1235        await resolvePendingPasskeyRequest(Number(requestId), approved);1236        return { ok: true };1237      }12381239      case "GET_PASSKEY_FOR_DOMAIN": {1240        const { domain } = (msg.payload ?? {}) as { domain?: string };1241        if (!domain) return { ok: false, error: "domain_required" };1242        // Scope to the caller's own origin: a page may only ask about passkeys1243        // for a domain it actually owns, so an arbitrary page cannot enumerate1244        // which sites the user holds passkeys for or read the username (audit MEDIUM).1245        const origin = attestedSenderOrigin(sender);1246        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1247        if (!vault.isUnlocked()) return { ok: true, data: null };1248        const match = vault1249          .getEntries()1250          .find((entry) => entry.passkey?.rpId === domain);1251        if (!match || !match.passkey) return { ok: true, data: null };1252        // Slim shape — only the fields State 11 needs. Never expose private1253        // key material, even though this is locked behind isUnlocked.1254        return {1255          ok: true,1256          data: {1257            rpId: match.passkey.rpId,1258            userName: match.passkey.userName,1259            browser: match.passkey.browser,1260          },1261        };1262      }12631264      case "DESTROY_VAULT": {1265        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1266        // storage.local.clear() wipes every Peach key (slots, settings, license,1267        // onboarded flag, history, sync state, declined cards, recall, etc.);1268        // session.clear() wipes pending passkey requests + pro-notice queues.1269        // Caller (Panic.tsx) handles UI navigation back to onboarding.1270        //1271        // The Pro license is the one thing that must survive: the user paid for1272        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1273        // Capture it before the clear and restore it after. peach_pro_celebrated1274        // rides along so the Pro celebration doesn't replay on the next unlock.1275        const preserved = await chrome.storage.local.get([1276          "peach_license",1277          "peach_pro_celebrated",1278        ]);1279        vault.lock();1280        await storageClear();1281        await vault.clearVaultHistory();1282        const toRestore: Record<string, unknown> = {};1283        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1284        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1285        if (Object.keys(toRestore).length > 0) {1286          await chrome.storage.local.set(toRestore);1287        }1288        if (chrome.storage.session) {1289          await chrome.storage.session.clear();1290        }1291        return { ok: true };1292      }12931294      // Android-only: biometric unlock with pre-derived key.1295      case "UNLOCK_WITH_KEY": {1296        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1297        if (!isNativePlatform()) {1298          return { ok: false, error: "desktop_only_uses_password" };1299        }1300        try {1301          const result = await vault.unlockWithKey(masterKeyHex);1302          if (result.ok) {1303            onVaultUnlocked();1304            await publishInMemoryVault(result.entries);1305          }1306          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1307        } catch {1308          return { ok: false, error: "invalid_key" };1309        }1310      }1311      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1312      case "GET_DERIVED_KEY": {1313        if (!isNativePlatform()) {1314          return { ok: false, error: "android_only" };1315        }1316        if (!vault.isUnlocked()) {1317          return { ok: false, error: "vault_locked" };1318        }1319        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1320      }1321      case "GET_IDENTITY_SUGGESTIONS": {1322        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1323        const entries = vault.getEntries();1324        const suggestions = buildIdentitySuggestions(entries);1325        return { ok: true, data: { suggestions } };1326      }1327      case "POPULATE_INLINE_VAULT": {1328        if (!isNativePlatform()) return { ok: false };1329        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1330        const entries = vault.getEntries();1331        await publishInMemoryVault(entries);1332        return { ok: true };1333      }1334      case "ML_INIT":1335        return { ok: true };13361337      case "ML_PREDICT_BATCH": {1338        // AUD-002: shape-validate before forwarding to the ML helper.1339        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1340        if (!Array.isArray(featuresArray)) {1341          return { ok: false, error: "invalid_payload" };1342        }1343        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1344      }13451346      // ── Vault sync (v3) ───────────────────────────────────────────────1347      // Returns the public-facing local identity needed by the popup to1348      // drive Phase-1 audio pairing. The private long-term key never1349      // leaves the background.1350      case "GET_LOCAL_IDENTITY": {1351        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1352        // Pro license from an already-Pro peer (at least one device must be Pro).1353        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1354        // Identity derives from the stable root key, not the password-derived1355        // key, so pairing survives a master-password change (SEV-2-B).1356        const masterKeyHex = vault.getRootKeyHex();1357        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1358        const masterKey = unhexBytes(masterKeyHex);1359        try {1360          const identity = await buildLocalIdentity(masterKey);1361          // If this device is Pro, advertise the signed license so the peer can1362          // activate it after SAS confirmation — pairing carries Pro across.1363          if (await isProUser()) {1364            const license = await getLicenseKey();1365            if (license) (identity as { license?: string }).license = license;1366          }1367          return { ok: true, data: identity };1368        } finally {1369          masterKey.fill(0);1370        }1371      }13721373      case "LIST_PAIRED_DEVICES": {1374        const devices = await listPairedDevicesV3();1375        return { ok: true, data: { devices } };1376      }13771378      case "UNPAIR_DEVICE": {1379        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1380        if (typeof deviceId !== "string" || !deviceId) {1381          return { ok: false, error: "invalid_payload" };1382        }1383        // Removing a device REVOKES it rather than just dropping the local1384        // row: a plain removal is undone the moment any other peer vouches it1385        // back through a manifest, which is exactly what the relay makes easy.1386        await revokeDeviceByIdV3(deviceId, await getOrCreateDeviceId());1387        // Sync against the remaining hosts — the unpaired device no longer1388        // matters but the next alarm tick is up to ten minutes away.1389        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1390        return { ok: true };1391      }13921393      case "RENAME_LOCAL_DEVICE": {1394        const { name } = (msg.payload ?? {}) as { name?: string };1395        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1396        await setDeviceNameV3(name);1397        return { ok: true };1398      }13991400      // ── Relay pairing ─────────────────────────────────────────────────────1401      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1402      // session runs in the background; the SAS and the terminal result reach1403      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1404      case "START_ADOPTION_SOURCE": {1405        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1406        if (isRelayAdoptionSourceInFlight()) {1407          return { ok: false, error: "adoption_source_in_progress" };1408        }1409        try {1410          return { ok: true, data: await startRelayAdoptionSource() };1411        } catch (error) {1412          return {1413            ok: false,1414            error: error instanceof Error ? error.message : "adoption_source_failed",1415          };1416        }1417      }14181419      // Onboarding receiver — empty extension shows a QR, phone scans and1420      // sends the vault. The popup supplies the local-only password here so1421      // the background can wrap the adopted root key at rest without ever1422      // asking the user to retype it.1423      case "START_ADOPTION_RECEIVER": {1424        if (isRelayAdoptionSourceInFlight()) {1425          return { ok: false, error: "adoption_receiver_in_progress" };1426        }1427        const password = (msg.payload as { password?: unknown } | undefined)?.password;1428        if (typeof password !== "string" || password.length === 0) {1429          return { ok: false, error: "invalid_payload" };1430        }1431        try {1432          return { ok: true, data: await startRelayAdoptionReceiver(password) };1433        } catch (error) {1434          return {1435            ok: false,1436            error: error instanceof Error ? error.message : "adoption_receiver_failed",1437          };1438        }1439      }14401441      // Popup→bg counterpart to ADOPTION_SOURCE_SAS (receiver flow).1442      // The receiver now auto-accepts the SAS (both sides derive it from the1443      // same Noise handshake hash, so the codes match by construction) so1444      // the popup never has a SAS screen to tap on. The id round-trips the1445      // same way so a stale late response can't approve the wrong session.1446      // Popup→bg counterpart for the source flow: Confirm/Cancel on the1447      // source's SAS screen.14481449      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1450      // on the source's SAS screen. The id round-trips the same way so a stale1451      // late response can't approve the wrong session.1452      case "SOURCE_SAS_DECISION": {1453        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1454        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1455          return { ok: false, error: "invalid_payload" };1456        }1457        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1458      }14591460      case "CANCEL_ADOPTION_SOURCE": {1461        cancelRelayAdoptionSource();1462        return { ok: true };1463      }14641465      case "TRIGGER_SYNC": {1466        const payload = (msg.payload ?? {}) as {1467          reason?: "vault_change" | "foreground" | "manual";1468          force?: boolean;1469        };1470        const reason = payload.reason ?? "foreground";14711472        void triggerSyncIfReachable({ reason, force: payload.force === true });1473        return { ok: true };1474      }14751476      case "GET_SYNC_STATE": {1477        return { ok: true, data: getSyncState() };1478      }14791480      case "GET_SYNC_SETTINGS": {1481        return { ok: true, data: await getSyncSettings() };1482      }14831484      case "SET_SYNC_SETTINGS": {1485        const payload = (msg.payload ?? {}) as {1486          mode?: unknown;1487          relayUrl?: unknown;1488        };1489        try {1490          // A custom relay URL implies private mode; Peach's own relay stays1491          // public. See setRelayUrl.1492          if (payload.relayUrl !== undefined) {1493            if (typeof payload.relayUrl !== "string") {1494              return { ok: false, error: "invalid_relay_url" };1495            }1496            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1497          }1498          if (payload.mode !== undefined) {1499            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1500              return { ok: false, error: "invalid_sync_mode" };1501            }1502            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1503          }1504          return { ok: true, data: await getSyncSettings() };1505        } catch (error) {1506          return {1507            ok: false,1508            error: error instanceof Error ? error.message : "invalid_relay_url",1509          };1510        }1511      }15121513      case "GET_SYNC_ALERTS": {1514        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1515        const alerts = await getPendingSyncAlerts();1516        // The popup reads on open and acknowledges with consume:true after1517        // rendering, so a popup crash between read and render doesn't lose1518        // the alerts.1519        if (consume) await clearPendingSyncAlerts();1520        return { ok: true, data: alerts };1521      }15221523      case "GET_PENDING_VOUCHED_DEVICES": {1524        return { ok: true, data: await listPendingVouchedDevices() };1525      }1526      case "CONFIRM_VOUCHED_DEVICE": {1527        const { deviceId } = msg.payload as { deviceId: string };1528        const pending = await getPendingVouchedDevice(deviceId);1529        if (!pending) return { ok: false, error: "not_pending" };1530        // Last gate before a vouched device becomes a sync peer. A queue entry1531        // can predate the revocation that names it, so revocation is re-checked1532        // here rather than trusted to have swept the queue.1533        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {1534          await removePendingVouchedDevice(deviceId);1535          return { ok: false, error: "device_revoked" };1536        }1537        await upsertPairedDeviceV3({1538          deviceId: pending.deviceId,1539          deviceName: pending.deviceName,1540          deviceType:1541            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1542          longTermPublicKeyHex: pending.longTermPublicKeyHex,1543          signingPublicKeyHex: pending.signingPublicKeyHex,1544          wsPort: pending.wsPort,1545          pairedAt: pending.pairedAt,1546          trustSource: "vouched",1547        });1548        await removePendingVouchedDevice(deviceId);1549        // Newly confirmed vouched device is now a sync target — kick a round1550        // so the mesh introduction pays off without a 10-minute wait.1551        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1552        return { ok: true };1553      }1554      case "REJECT_VOUCHED_DEVICE": {1555        const { deviceId } = msg.payload as { deviceId: string };1556        await removePendingVouchedDevice(deviceId);1557        return { ok: true };1558      }1559      case "ROTATE_SYNC_IDENTITY": {1560        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1561        const result = await vault.rotateSyncIdentity();1562        return result.ok ? { ok: true } : { ok: false, error: result.error };1563      }15641565      default:1566        return { ok: false, error: "unknown_message_type" };1567    }1568  } catch (err) {1569    return {1570      ok: false,1571      error: err instanceof Error ? err.message : "operation_failed",1572    };1573  }1574}15751576// --- Mobile platform helpers ---15771578// Android: populates the in-memory vault used by PeachAutofillService.1579async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1580  const plugin = nativePlugin<{1581    setEntries?: (args: {1582      entries: Array<{1583        id: string;1584        title: string;1585        username: string;1586        email: string;1587        password: string;1588        url: string;1589        totp: string;1590        additionalUrls: string[];1591      }>;1592    }) => Promise<void>;1593  }>("InMemoryVaultPlugin");1594  if (!plugin?.setEntries) return;1595  await plugin.setEntries({1596    entries: entries.map((e) => ({1597      id: e.id,1598      title: e.title ?? "",1599      username: e.username ?? "",1600      email: (e as VaultEntry & { email?: string }).email ?? "",1601      password: e.password ?? "",1602      url: e.url ?? "",1603      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1604      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1605    })),1606  });1607}16081609// Android: clear the autofill in-memory store on lock.1610async function clearInMemoryVault(): Promise<void> {1611  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1612  if (!plugin?.clearEntries) return;1613  await plugin.clearEntries();1614}16151616// Returns username use-counts from the vault, sorted by frequency. Each row1617// also carries the entry's email so the popup can suggest the email/username1618// pair the user has actually used together.1619function buildIdentitySuggestions(1620  entries: VaultEntry[],1621): Array<{ email: string; username: string; count: number }> {1622  const usernameCounts = new Map<string, number>();1623  const usernameEmail = new Map<string, string>();1624  for (const entry of entries) {1625    const username = entry.username ?? "";1626    const email = (entry as VaultEntry & { email?: string }).email ?? "";1627    if (!username && !email) continue;1628    const key = username || email;1629    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1630    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1631  }1632  return Array.from(usernameCounts.entries())1633    .sort((a, b) => b[1] - a[1])1634    .map(([username, count]) => ({1635      email: usernameEmail.get(username) ?? "",1636      username,1637      count,1638    }));1639}16401641/** Notify all content scripts that the vault just became available. */1642function broadcastToContentScripts(message: { type: string }): void {1643  if (!chrome.tabs?.query) return;1644  chrome.tabs.query({}, (tabs) => {1645    for (const tab of tabs) {1646      if (tab.id !== undefined) {1647        chrome.tabs.sendMessage(tab.id, message).catch(() => {1648          // Tab may not have a content script — silently ignore1649        });1650      }1651    }1652  });1653}16541655function shouldRefreshAutoLock(type: MessageType): boolean {1656  return (1657    type !== "HAS_VAULT" &&1658    type !== "IS_UNLOCKED" &&1659    type !== "GET_VAULT_STATUS" &&1660    type !== "LOCK" &&1661    type !== "UPDATE_SETTINGS" &&1662    type !== "GET_PENDING_PASSKEY" &&1663    type !== "GET_PASSKEY_PROVIDER_STATE" &&1664    type !== "DECLINE_CARD_SAVE" &&1665    type !== "IS_CARD_DECLINED"1666  );1667}16681669function isAllowedCanaryWebhookUrl(value: string): boolean {1670  try {1671    const url = new URL(value);1672    if (url.protocol !== "https:") return false;16731674    const hostname = url.hostname.toLowerCase();1675    if (1676      hostname === "localhost" ||1677      hostname.endsWith(".localhost") ||1678      isPrivateIpv4(hostname) ||1679      isPrivateIpv6(hostname)1680    ) {1681      return false;1682    }16831684    return true;1685  } catch {1686    return false;1687  }1688}16891690function isPrivateIpv4(hostname: string): boolean {1691  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1692    return true;1693  }16941695  const octets = hostname.split(".").map((part) => Number(part));1696  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1697    return false;1698  }16991700  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1701}17021703function isPrivateIpv6(hostname: string): boolean {1704  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1705  // IPv4-mapped IPv6 literals embed a plain IPv4 address that the prefix1706  // list below can never match (WHATWG URL serializes [::ffff:192.168.0.1]1707  // as ::ffff:c0a8:1). Unwrap and test the embedded IPv4; unparseable mapped1708  // tails fail closed. (Codex Security 2026-08-04 LOW,1709  // ssrf.webhook-url-private-ip-filter.) DNS rebinding is out of scope for a1710  // one-shot host check.1711  const mapped = /^::ffff:(.+)$/.exec(normalized);1712  if (mapped) {1713    const tail = mapped[1] ?? "";1714    if (tail.includes(".")) return isPrivateIpv4(tail);1715    const parts = tail.split(":");1716    const [hi, lo] = parts;1717    if (1718      parts.length !== 2 ||1719      !hi ||1720      !lo ||1721      !/^[0-9a-f]{1,4}$/.test(hi) ||1722      !/^[0-9a-f]{1,4}$/.test(lo)1723    ) {1724      return true;1725    }1726    const octets = [1727      (Number.parseInt(hi, 16) >>> 8) & 0xff,1728      Number.parseInt(hi, 16) & 0xff,1729      (Number.parseInt(lo, 16) >>> 8) & 0xff,1730      Number.parseInt(lo, 16) & 0xff,1731    ];1732    return isPrivateIpv4(octets.join("."));1733  }1734  return (1735    normalized === "::1" ||1736    normalized.startsWith("fc") ||1737    normalized.startsWith("fd") ||1738    normalized.startsWith("fe80:")1739  );1740}