messages.ts

75.7 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  "UNLOCK_WITH_PIN",176  "SETUP_PIN",177  "DISABLE_PIN",178]);179180// LV-3: minimum interval between non-test canary pings per webhook+entry.181const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour182183const PRIVATE_IPV4_RANGES = [184  { prefix: "10." },185  { prefix: "127." },186  { prefix: "169.254." },187  { prefix: "192.168." },188];189190export function setupMessageHandler(): void {191  chrome.runtime.onMessage.addListener(192    (msg: unknown, sender, sendResponse) => {193      if (!isMessage(msg)) {194        sendResponse({ ok: false, error: "invalid_message" });195        return true;196      }197      handleMessage(msg, sender)198        .then(sendResponse)199        .catch((err) =>200          sendResponse({201            ok: false,202            error: err instanceof Error ? err.message : String(err),203          })204        );205      return true;206    }207  );208209  // Android: the chrome shim queues sendMessage calls until this handler is210  // registered. Without this hookup, every message hangs on Capacitor builds.211  // eslint-disable-next-line @typescript-eslint/no-explicit-any212  const reg = (globalThis as any).__peachRegisterMessageHandler;213  if (typeof reg === "function") {214    reg(async (m: unknown) => {215      if (!isMessage(m)) return { ok: false, error: "invalid_message" };216      try {217        return await handleMessage(m);218      } catch (err) {219        return {220          ok: false,221          error: err instanceof Error ? err.message : String(err),222        };223      }224    });225  }226  if (isNativePlatform()) {227    void bootstrapNativeSyncRunner();228  }229}230231async function bootstrapNativeSyncRunner(): Promise<void> {232  if (nativeSyncRunnerBootstrapped) return;233  nativeSyncRunnerBootstrapped = true;234  try {235    setSyncRunner(productionSyncRunner);236    await hydratePersistedSyncState();237  } catch (err) {238    nativeSyncRunnerBootstrapped = false;239    console.warn("[Peach] failed to bootstrap native sync runner:", err);240  }241}242243function isMessage(m: unknown): m is Message {244  return typeof m === "object" && m !== null && "type" in m;245}246247/**248 * The browser-attested origin of the page that originated this message. A web249 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),250 * so every page-driven message arrives via the content-script relay and the251 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a252 * value the page cannot forge. This is the ONLY trustworthy origin for passkey253 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.254 */255function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {256  if (sender.origin) return sender.origin;257  if (sender.url) {258    try { return new URL(sender.url).origin; } catch { return undefined; }259  }260  return undefined;261}262263// Resolves once restoreFromSession() has run, so handlers see the correct264// post-restore unlock state. entry.ts registers this BEFORE the message265// handler so the onMessage listener is added synchronously at SW startup266// (MV3 requirement) while unlock-dependent handlers still wait for restore.267let restoreReady: Promise<void> = Promise.resolve();268269/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */270export function setRestoreReady(p: Promise<unknown>): void {271  restoreReady = p.then(() => undefined, () => undefined);272}273274export async function handleMessage(275  msg: Message,276  sender: Partial<chrome.runtime.MessageSender> = {}277): Promise<MessageResponse> {278  try {279    // Wait for session-restore to finish before reading any unlock/vault state.280    // On a cold SW start the popup's first message arrives while restore is281    // still in flight; without this gate IS_UNLOCKED would report locked (a282    // spurious lock screen) and the storage reads could race. The onMessage283    // listener itself is registered synchronously (entry.ts) so this gate, not284    // listener registration, is what absorbs the cold-start window.285    await restoreReady;286    // Validate sender — only allow messages from our extension pages/scripts.287    // `sender.id` is undefined for messages originating from extension UI288    // (popup/options), which is legitimate; reject only when it is defined289    // and does not match our extension id.290    if (291      sender.id !== undefined &&292      sender.id !== chrome.runtime.id293    ) {294      return { ok: false, error: "invalid_sender" };295    }296297    // PCH-01-018: destructive and sensitive operations must originate from a298    // trusted extension page (popup/options), never from a content script. The299    // sender.id check above only proves the message came from *our* extension —300    // a content script injected into an attacker page passes it. A single301    // XSS-class bug in the injected UI would otherwise escalate to vault302    // destruction, root-key exfiltration, or attacker device registration.303    // Extension pages carry an extension-origin sender.url; content scripts304    // carry a page URL.305    if (PRIVILEGED_MESSAGE_TYPES.has(msg.type)) {306      const extensionOrigin = chrome.runtime.getURL("");307      if (!sender.url?.startsWith(extensionOrigin)) {308        return { ok: false, error: "invalid_sender" };309      }310    }311312    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {313      touchAutoLock();314    }315316    switch (msg.type) {317      case "CREATE_VAULT": {318        const { password } = msg.payload as { password: string };319        // Refuse to create a vault under an empty master password — the derived320        // key would be publicly known and the at-rest AES-GCM protection void321        // (audit HIGH; the CSV-import path previously passed ""). Length/strength322        // policy lives in the onboarding UI; this is the non-negotiable floor.323        if (typeof password !== "string" || password.length === 0) {324          return { ok: false, error: "invalid_payload" };325        }326        await vault.createVault(password);327        await setupAutoLock();328        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });329        onVaultUnlocked();330        return { ok: true };331      }332      case "CREATE_VAULT_FROM_ROOT_KEY": {333        console.log("[Peach diag] CREATE_VAULT_FROM_ROOT_KEY handler entered");334        const { password, rootKeyHex } = (msg.payload ?? {}) as {335          password?: unknown;336          rootKeyHex?: unknown;337        };338        console.log("[Peach diag] payload types:", typeof password, typeof rootKeyHex, "lengths:", (password as string)?.length, (rootKeyHex as string)?.length);339        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {340          console.log("[Peach diag] payload invalid, returning invalid_payload");341          return { ok: false, error: "invalid_payload" };342        }343344        try {345          console.log("[Peach diag] calling vault.createVaultFromRootKey");346          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);347          console.log("[Peach diag] createVaultFromRootKey returned vaultId", vaultId);348          await setupAutoLock();349          console.log("[Peach diag] setupAutoLock done");350          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });351          onVaultUnlocked();352          console.log("[Peach diag] handler completing successfully");353          return { ok: true, vaultId };354        } catch (err) {355          console.error("[Peach diag] handler caught error:", err);356          return { ok: false, error: err instanceof Error ? err.message : String(err) };357        }358      }359      case "UNLOCK": {360        const { password } = msg.payload as { password: string };361        const ok = await vault.unlock(password);362        if (ok) {363          // KAT: verify the WebCrypto stack is healthy before the user relies on it.364          // Runs after unlock so latency is hidden behind the vault-load time.365          const kat = await runSelfTest();366          if (!kat.ok) {367            console.error("[Peach] Crypto self-test FAILED:", kat.error);368            await vault.lock();369            return { ok: false, error: "self_test_failed" };370          }371          await vault.updateSettings({ pinPreferred: false });372          await setupAutoLock();373          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });374          onVaultUnlocked();375          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());376          return { ok: true };377        }378        // Distinguish corruption from wrong password so the popup can offer379        // a history-restore path instead of falsely accusing the user of380        // mistyping (M7/COR-007).381        const failure = vault.consumeLastUnlockFailureReason();382        if (failure) {383          return {384            ok: false,385            error: "vault_corrupted",386            canRestoreFromHistory: true,387          } as MessageResponse;388        }389        return { ok: false };390      }391      case "UNLOCK_WITH_PIN": {392        const { pin } = (msg.payload ?? {}) as { pin?: unknown };393        if (typeof pin !== "string") return { ok: false, error: "invalid_payload" };394        const ok = await vault.unlockWithPin(pin);395        if (!ok) return { ok: false };396        const kat = await runSelfTest();397        if (!kat.ok) {398          await vault.lock();399          return { ok: false, error: "self_test_failed" };400        }401        await vault.updateSettings({ pinPreferred: true });402        await setupAutoLock();403        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });404        onVaultUnlocked();405        if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());406        return { ok: true };407      }408      case "VALIDATE_RECOVERY_WORDS": {409        const { words } = msg.payload as { words: string[] };410        const invalid = findInvalidWords(words);411        return { ok: true, data: { valid: invalid.length === 0, invalid } };412      }413      case "GET_RECOVERY_WORDS": {414        // Must be unlocked and have recovery set up (vault must be v2.12+).415        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };416        // LV-4: the recovery words re-derive the ROOT KEY — the highest-417        // value secret in the vault. A session unlock (which may be hours418        // old on a shared machine) is not enough; require a fresh password419        // proof, matching the 1Password/Bitwarden pattern for revealing420        // escrow material. EXEMPTION: the create-vault / rotation confirmation421        // window (peach_recovery_pending) shows the words immediately after422        // the user authenticated, and that confirmation UI has no password to423        // resend — skip the re-auth there only.424        if (!(await isRecoveryConfirmPending())) {425          const { password } = (msg.payload ?? {}) as { password?: string };426          if (typeof password !== "string" || !password) {427            return { ok: false, error: "password_required" };428          }429          if (!(await vault.verifyMainPassword(password))) {430            return { ok: false, error: "wrong_password" };431          }432        }433        try {434          const words = await vault.getRecoveryWords();435          return { ok: true, data: words };436        } catch {437          // pre-v2.12 vault that hasn't migrated438          return { ok: false, error: "recovery_not_setup" };439        }440      }441      case "RECOVER_WITH_WORDS": {442        // User has lost their password but has their 12 recovery words.443        // We: (1) validate the words, (2) re-encrypt vault with new password.444        const { words, newPassword } = msg.payload as {445          words: string[];446          newPassword: string;447        };448        const stored = await vault.loadSlotA();449        if (!stored) return { ok: false, error: "no_vault" };450        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {451          return { ok: false, error: "recovery_not_setup" };452        }453        // Unwrap the root key from the recovery escrow.454        try {455          await vault.unwrapRootKeyForRecovery(456            stored.recovery_wrapped_root_key,457            stored.recovery_nonce ?? "",458            stored.recovery_tag ?? "",459            stored.recovery_salt,460            words461          );462        } catch {463          return { ok: false, error: "invalid_recovery_words" };464        }465        // Re-key: derive fresh salt + key from new password.466        const newSalt = vault.generateSalt();467        const newKey = await vault.deriveKey(newPassword, newSalt);468        // Re-wrap root key under the new password's derived key so the same469        // recovery words continue to work after the password change.470        await vault.rewrapRootKeyForPassword(newKey, newSalt);471        // Re-encrypt vault entries with the new key.472        await vault.changePasswordWithNewKey(newSalt, newKey);473        await setupAutoLock();474        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });475        return { ok: true };476      }477      case "LOCK":478        vault.lock();479        if (isNativePlatform()) await clearInMemoryVault();480        return { ok: true };481      case "IS_UNLOCKED":482        return { ok: true, data: vault.isUnlocked() };483      case "GET_VAULT_STATUS":484        return { ok: true, unlocked: vault.isUnlocked() };485      case "HAS_VAULT":486        return { ok: true, data: await vault.hasVault() };487      case "GET_ENTRIES":488        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };489        return { ok: true, data: vault.getEntries() };490      case "ADD_ENTRY": {491        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };492        const payload = msg.payload;493        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {494          return { ok: false, error: "invalid_payload" };495        }496        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);497        return { ok: true, data: entry };498      }499      case "BATCH_ADD_ENTRIES": {500        const payload = msg.payload as { entries?: unknown } | null | undefined;501        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {502          return { ok: false, error: "invalid_payload" };503        }504        if (!Array.isArray(payload.entries)) {505          return { ok: false, error: "invalid_payload" };506        }507        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);508        return { ok: true, data: added };509      }510      case "RESTORE_ENTRIES": {511        const payload = msg.payload as512          | { entries?: unknown; mode?: unknown; settings?: unknown }513          | null514          | undefined;515        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {516          return { ok: false, error: "invalid_payload" };517        }518        if (!Array.isArray(payload.entries)) {519          return { ok: false, error: "invalid_payload" };520        }521        if (payload.mode !== "replace" && payload.mode !== "merge") {522          return { ok: false, error: "invalid_payload" };523        }524        const summary = await vault.restoreEntries(525          payload.entries as Parameters<typeof vault.restoreEntries>[0],526          payload.mode527        );528        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {529          await vault.updateSettings(payload.settings as vault.VaultSettings);530        }531        return { ok: true, data: summary };532      }533      case "CLEAR_VAULT_ENTRIES": {534        await vault.clearVaultEntries("REPLACE_ALL");535        return { ok: true };536      }537      case "GET_VAULT_HISTORY": {538        const snapshots = await vault.getVaultHistory();539        return { ok: true, data: snapshots };540      }541      case "RESTORE_VAULT_SNAPSHOT": {542        const { snapshotId } = msg.payload as { snapshotId: string };543        const result = await vault.restoreVaultSnapshot(snapshotId);544        if (!result.ok) return { ok: false, error: result.error };545        broadcastToContentScripts({ type: "VAULT_LOCKED" });546        return { ok: true };547      }548      case "COUNT_DUPLICATES": {549        return { ok: true, data: vault.countDuplicates() };550      }551      case "DEDUPLICATE_ENTRIES": {552        const removed = await vault.deduplicateEntries();553        return { ok: true, data: removed };554      }555      case "UPDATE_ENTRY": {556        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;557        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {558          return { ok: false, error: "invalid_payload" };559        }560        const { id, patch } = payload;561        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {562          return { ok: false, error: "invalid_payload" };563        }564        // Single enforcement point for the Canary Entries Pro gate. Only565        // gates the transition into a canary entry — clearing/disabling a566        // canary (`canary: undefined`) is always allowed, so existing567        // canary entries remain manageable.568        const incomingCanary = (patch as { canary?: unknown }).canary;569        if (incomingCanary && typeof incomingCanary === "object") {570          const existing = vault.getEntryById(id);571          if (!existing?.canary) {572            const gate = await requirePro("canary_entry");573            if (!gate.allowed) return { ok: false, error: "pro_required" };574          }575        }576        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);577        return { ok: true };578      }579      case "ADD_ADDITIONAL_URL": {580        const { id, url } = msg.payload as { id: string; url: string };581        const trimmed = typeof url === "string" ? url.trim() : "";582        if (!trimmed) return { ok: false, error: "url_required" };583        const existing = vault.getEntryById(id);584        if (!existing) return { ok: false, error: "entry_not_found" };585        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };586        const merged = [...(existing.additionalUrls ?? []), trimmed];587        await vault.updateEntry(id, { additionalUrls: merged });588        return { ok: true };589      }590      case "DELETE_ENTRY": {591        const { id } = msg.payload as { id: string };592        await vault.deleteEntry(id);593        return { ok: true };594      }595      case "GET_DELETED_ENTRIES":596        return { ok: true, data: vault.getDeletedEntries() };597      case "RESTORE_ENTRY": {598        const { id } = msg.payload as { id: string };599        await vault.restoreEntry(id);600        return { ok: true };601      }602      case "PURGE_ENTRY": {603        const { id } = msg.payload as { id: string };604        await vault.purgeEntry(id);605        return { ok: true };606      }607      case "PURGE_EXPIRED_TRASH": {608        const { retentionMs } = msg.payload as { retentionMs: number };609        const purged = await vault.purgeExpiredTrash(retentionMs);610        return { ok: true, data: purged };611      }612      case "SAVE_NOTE": {613        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };614        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };615        const now = Date.now();616        if (id) {617          const existing = vault.getEntryById(id);618          if (!existing) return { ok: false, error: "not_found" };619          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });620          return { ok: true, data: vault.getEntryById(id) };621        } else {622          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt623          // (EntryDraft omits both), so passing them was the only reason the624          // `as any` cast existed. Dropping them makes the call type-check.625          const entry = await vault.addEntry({626            type: "note",627            title: title || "Untitled",628            notes: body,629          });630          return { ok: true, data: entry };631        }632      }633      case "DELETE_NOTE": {634        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };635        const { id } = msg.payload as { id: string };636        await vault.deleteEntry(id);637        return { ok: true };638      }639      case "GET_NOTES": {640        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };641        const notes = vault.getEntries().filter(642          (e) => e.type === "note" && !e.deletedAt643        );644        return { ok: true, data: notes } as MessageResponse;645      }646      case "SEARCH_VAULT": {647        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };648        // AUD-002: shape-validate the payload before calling string methods.649        // A raw cast lets a malformed message crash the handler with TypeError.650        const { query } = (msg.payload ?? {}) as { query?: unknown };651        if (typeof query !== "string") {652          return { ok: false, error: "invalid_payload" };653        }654        const q = query.toLowerCase();655        const searchResults = vault.getEntries().filter(656          (e) =>657            !e.deletedAt &&658            (e.title.toLowerCase().includes(q) ||659              e.notes?.toLowerCase().includes(q) ||660              e.username?.toLowerCase().includes(q))661        );662        return { ok: true, data: searchResults } as MessageResponse;663      }664      case "AUTOFILL_QUERY": {665        if (!vault.isUnlocked()) {666          return { ok: false, error: "vault_locked" };667        }668        let { includeAll } = msg.payload as { includeAll?: boolean };669        const { domain, kind, userGesture } = msg.payload as {670          domain: string;671          kind?: "login" | "card" | "totp";672          userGesture?: boolean;673        };674        // MV-2: the vault-wide inventory (every title/username/email/url)675        // may only leave the background on an explicit user gesture — the676        // user opening the search affordance — never on passive form focus.677        // userGesture is self-declared by our own content script; the value678        // of this gate is that PASSIVE code paths (which never set it)679        // cannot ship the inventory, shrinking what a compromised page that680        // merely triggers focus events can observe.681        if (includeAll && userGesture !== true) {682          includeAll = false;683        }684        // kind="card": return saved cards as compact summaries for the685        // inline card silver platter. Cards are not domain-scoped — every686        // saved card is a candidate on every checkout page — so domain is687        // ignored when kind === "card".688        if (kind === "card") {689          const cards = vault.getEntries().filter((e) => e.type === "card");690          return {691            ok: true,692            data: cards.map((e) => ({693              id: e.id,694              title: e.cardNickname || e.title,695              cardholderName: e.cardholderName,696              last4: e.last4,697              expMonth: e.expMonth,698              expYear: e.expYear,699              network: e.network,700            })),701          };702        }703        if (kind === "totp") {704          const matches = (705            includeAll706              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")707              : vault.queryDomain(domain)708          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));709          return {710            ok: true,711            data: matches.map((e) => ({712              id: e.id,713              title: e.title,714              username: e.username,715              email: e.email,716              url: e.url,717              hasTotp: true,718            })),719          };720        }721        // The inline selector fills username+password into a form. Passkey-722        // only entries have no password to fill; sign-in for those goes723        // through the WebAuthn path instead. Filter them out everywhere so724        // the user doesn't see four "GitHub" rows that mostly do nothing.725        // Notes and cards never belonged here either.726        const matches = (727          includeAll728            ? vault729                .getEntries()730                .filter((entry) => entry.type !== "note" && entry.type !== "card")731            : vault.queryDomain(domain)732        ).filter((entry) => !isPasskeyOnly(entry));733        return {734          ok: true,735          data: matches.map((e) =>736            includeAll737              ? {738                  id: e.id,739                  title: e.title,740                  // username/email/url shipped so the inline popup's search741                  // affordance can match on them, not just titles. No secrets742                  // cross the boundary — same shape as the domain-matched743                  // response below minus hasTotp (which the search list744                  // doesn't surface).745                  username: e.username,746                  email: e.email,747                  url: e.url,748                  hasPasskey: e.passkey !== undefined,749                }750              : {751                  id: e.id,752                  title: e.title,753                  username: e.username,754                  email: e.email,755                  url: e.url,756                  hasTotp: Boolean(e.totp),757                  hasPasskey: e.passkey !== undefined,758                }759          ),760        };761      }762      case "GET_ENTRY_FOR_FILL": {763        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };764        const { id, explicitSummon } = msg.payload as {765          id: string;766          explicitSummon?: boolean;767        };768        const entry = vault.getEntryById(id);769        if (!entry) return { ok: false, error: "entry_not_found" };770        // Passkey-only entries (passkey credential, no password) cannot be771        // filled into a form — sign-in goes through the WebAuthn path. A772        // login that ALSO has a passkey is still fillable for its password.773        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };774775        // MV-1: re-validate the entry against the requesting tab's origin.776        // sender.tab.url is browser-attested — a page cannot forge it. When777        // the request does not come from a tab at all (popup surfaces use778        // GET_ENTRY_FOR_EDIT, not this), refuse.779        if (sender.tab !== undefined || sender.url !== undefined) {780          let senderDomain: string | null = null;781          try {782            const rawUrl = sender.tab?.url ?? sender.url ?? "";783            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;784          } catch {785            senderDomain = null;786          }787          if (!senderDomain) return { ok: false, error: "origin_unverified" };788789          const entryDomains = new Set<string>();790          const primary = extractDomain(entry.url ?? "");791          if (primary) entryDomains.add(primary);792          for (const extra of entry.additionalUrls ?? []) {793            const d = extractDomain(extra);794            if (d) entryDomains.add(d);795          }796797          // explicitSummon=true means the user actively picked this entry798          // from the cross-domain search affordance — an intentional799          // off-domain fill. Passive fill paths must stay domain-bound.800          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {801            // Domain mismatch — refuse silently (no oracle about which ids exist).802            return { ok: false, error: "entry_not_found" };803          }804        }805        // Strip the passkey credential AND the raw base32 TOTP seed from the806        // response. Content scripts never need either: the private key is the807        // authenticator's, and handing over the TOTP seed would let a808        // compromised content script mint valid codes indefinitely (SEV-3-C).809        // Generate the *current* 6-digit code here in the background and send810        // only that, plus the seconds left so the UI can render a countdown.811        // Also drop passwordHistory: filling needs only the *current* password.812        // Handing every past password to a content script during passive813        // autofill on an arbitrary page would widen the blast radius of a814        // compromised page far beyond the one credential being filled.815        const {816          passkey: _strippedPasskey,817          totp: seed,818          totpAlgorithm,819          totpDigits,820          totpPeriod,821          passwordHistory: _ph,822          ...safeEntry823        } = entry;824        let totpCode: string | undefined;825        let totpRemaining: number | undefined;826        if (seed) {827          try {828            // PCH-01-019: honour stored algorithm/digits/period (defaults apply829            // when these are undefined, i.e. legacy bare-seed entries).830            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);831            totpCode = generated.code;832            totpRemaining = generated.remaining;833          } catch {834            totpCode = undefined;835          }836        }837        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };838      }839      // Trusted full-entry fetch for Peach's own inline-popup surfaces that840      // genuinely need the raw TOTP seed: the edit form (which re-saves the841      // seed and would otherwise wipe it) and nothing else. Unlike842      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside843      // the inline popup, never during passive autofill on an arbitrary page.844      // The passkey credential is still stripped — the edit form never touches it.845      case "GET_ENTRY_FOR_EDIT": {846        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };847        const { id, explicitSummon } = msg.payload as {848          id: string;849          explicitSummon?: boolean;850        };851        const entry = vault.getEntryById(id);852        if (!entry) return { ok: false, error: "entry_not_found" };853854        // PCH-01-006: re-validate the browser-attested sender origin, mirroring855        // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and856        // full password history — at least as sensitive as the fill response — so857        // the boundary must be enforced here, not only by UI reachability. Today858        // the sole caller is the popup (no sender.tab, so this is a structural859        // no-op), but a future tab-context caller or an id leak would otherwise860        // inherit a full-credential oracle. Unlike the fill path we SKIP (not861        // refuse) when no sender domain resolves, to keep the popup caller working.862        if (sender.tab !== undefined || sender.url !== undefined) {863          let senderDomain: string | null = null;864          try {865            const rawUrl = sender.tab?.url ?? sender.url ?? "";866            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;867          } catch {868            senderDomain = null;869          }870          if (senderDomain) {871            const entryDomains = new Set<string>();872            const primary = extractDomain(entry.url ?? "");873            if (primary) entryDomains.add(primary);874            for (const extra of entry.additionalUrls ?? []) {875              const d = extractDomain(extra);876              if (d) entryDomains.add(d);877            }878            if (explicitSummon !== true && !entryDomains.has(senderDomain)) {879              return { ok: false, error: "entry_not_found" }; // no id oracle880            }881          }882        }883884        const { passkey: _passkey, ...safeEntry } = entry;885        return { ok: true, data: safeEntry };886      }887      case "COPY": {888        // AUD-002: shape-validate the payload before passing to the clipboard889        // helper. A raw cast lets a malformed message reach the clipboard API890        // with a non-string and throw.891        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {892          text?: unknown;893          label?: unknown;894          alreadyWritten?: unknown;895        };896        if (typeof text !== "string" || typeof label !== "string") {897          return { ok: false, error: "invalid_payload" };898        }899        await copyToClipboard(text, label, Boolean(alreadyWritten));900        return { ok: true, clearSeconds: getEffectiveClearSeconds() };901      }902      case "CHECK_ALL_BREACHES": {903        const allEntries = vault.getEntries();904        const results: Record<string, number> = {};905        for (const entry of allEntries) {906          if (entry.type === "note") continue;907          if (!entry.password) continue;908          results[entry.id] = await vault.checkBreach(entry.password);909          // Small delay — be a good citizen to the HIBP API910          await new Promise((r) => setTimeout(r, 200));911        }912        // Persist any non-zero counts back to entries913        for (const [id, count] of Object.entries(results)) {914          const entry = vault.getEntryById(id);915          if (entry && (entry.breach ?? 0) !== count) {916            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });917          }918        }919        return { ok: true, data: results };920      }921      case "GET_SETTINGS":922        return { ok: true, data: await vault.ensureSettingsLoaded() };923      case "UPDATE_SETTINGS": {924        const patch = msg.payload;925        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {926          return { ok: false, error: "invalid_payload" };927        }928        await vault.updateSettings(patch as vault.VaultSettings);929        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {930          await setupAutoLock();931          if (vault.isUnlocked()) touchAutoLock();932        }933        return { ok: true };934      }935      case "SETUP_PIN": {936        const { currentPassword, pin } = (msg.payload ?? {}) as {937          currentPassword?: unknown;938          pin?: unknown;939        };940        if (typeof currentPassword !== "string" || typeof pin !== "string") {941          return { ok: false, error: "invalid_payload" };942        }943        return (await vault.setupPinUnlock(currentPassword, pin))944          ? { ok: true }945          : { ok: false, error: "incorrect_current_password" };946      }947      case "DISABLE_PIN": {948        const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown };949        if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" };950        return (await vault.disablePinUnlock(currentPassword))951          ? { ok: true }952          : { ok: false, error: "incorrect_current_password" };953      }954      case "GET_PENDING_PASSKEY":955        return { ok: true, data: await getPendingPasskeyRequest() };956      case "APPROVE_PASSKEY": {957        const { requestId } = msg.payload as { requestId: number };958        await resolvePendingPasskeyRequest(requestId, true);959        return { ok: true };960      }961      case "DENY_PASSKEY": {962        const { requestId } = msg.payload as { requestId: number };963        await resolvePendingPasskeyRequest(requestId, false);964        return { ok: true };965      }966      case "GET_PASSKEY_PROVIDER_STATE":967        return { ok: true, data: await getPasskeyProviderState() };968      case "SET_PASSKEY_PROVIDER_ENABLED": {969        const { enabled } = msg.payload as { enabled: boolean };970        // Disabling is always free; gating fires only when a free user is971        // trying to turn passkey interception on.972        if (enabled) {973          const gate = await requirePro("passkeys");974          if (!gate.allowed) return { ok: false, error: "pro_required" };975        }976        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };977      }978      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS979      // endpoint. Intentional product behavior — users configure their own980      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private981      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-982      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to983      // users that the entry title leaves the device when the canary fires.984      case "FIRE_CANARY_PING": {985        // Canary alert fires unconditionally for any entry with canary: true.986        // The Pro gate only governs creation/flagging of canary entries; once987        // an entry is flagged, the alert path is a security property and must988        // never be license-gated.989        const { webhookUrl, entryTitle, trigger } = msg.payload as {990          webhookUrl: string;991          entryTitle: string;992          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";993        };994        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {995          return { ok: false, error: "invalid_webhook_url" };996        }997        // LV-3: debounce non-test pings per (webhook, entry) so a page that998        // strobes focus/fill events can't turn the canary into a request999        // firehose at the user's endpoint. Test pings are exempt — they are1000        // explicit user clicks in the settings UI and are awaited for1001        // feedback. The FIRST ping in a window always goes out, so the1002        // dead-man's-switch property (canary fires on access) is preserved;1003        // only repeats within the window are coalesced.1004        if (trigger !== "test") {1005          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;1006          const stored = await chrome.storage.local.get(rlKey);1007          const last = (stored as Record<string, unknown>)[rlKey];1008          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {1009            return { ok: true, data: { rateLimited: true } };1010          }1011          await chrome.storage.local.set({ [rlKey]: Date.now() });1012        }1013        const body = JSON.stringify({1014          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",1015          entry: entryTitle,1016          trigger,1017          timestamp: new Date().toISOString(),1018          source: "peach-extension",1019        });1020        if (trigger === "test") {1021          // Permitted outbound fetch: user-configured canary alert endpoint1022          // (validated by isAllowedCanaryWebhookUrl above). This is the1023          // only non-HIBP outbound call in the extension — see1024          // Projects.md §3.7. Test pings are awaited so the UI can show1025          // success/failure.1026          try {1027            const res = await fetch(webhookUrl, {1028              method: "POST",1029              headers: { "Content-Type": "application/json" },1030              body,1031            });1032            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1033          } catch (err) {1034            return { ok: false, error: err instanceof Error ? err.message : "network_error" };1035          }1036        }1037        // Non-test triggers are fire-and-forget1038        fetch(webhookUrl, {1039          method: "POST",1040          headers: { "Content-Type": "application/json" },1041          body,1042        }).catch(() => {});1043        return { ok: true };1044      }1045      case "ACTIVATE_LICENSE": {1046        const { key } = msg.payload as { key: string };1047        const licenseInfo = await activateLicense(key);1048        return { ok: true, data: licenseInfo };1049      }1050      case "GET_LICENSE": {1051        const licenseInfo = await getLicenseInfo();1052        return { ok: true, data: licenseInfo };1053      }1054      case "GET_LICENSE_KEY": {1055        const key = await getLicenseKey();1056        return { ok: true, data: key };1057      }1058      case "DEACTIVATE_LICENSE": {1059        await deactivateLicense();1060        return { ok: true };1061      }1062      case "SHOULD_PLAY_CELEBRATION": {1063        const should = await shouldPlayCelebration();1064        return { ok: true, data: should };1065      }1066      case "MARK_CELEBRATION_PLAYED": {1067        await markCelebrationPlayed();1068        return { ok: true };1069      }1070      case "GET_CODEX_VAULT_DATA": {1071        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1072        // popup navigates to the License section without further coordination.1073        const gate = await requirePro("codex");1074        if (!gate.allowed) return { ok: false, error: "pro_required" };1075        return await handleGetCodexVaultData();1076      }1077      case "ESTIMATE_CODEX_PAGES": {1078        const gate = await requirePro("codex");1079        if (!gate.allowed) return { ok: false, error: "pro_required" };1080        return await handleEstimateCodexPages();1081      }1082      case "RESTORE_FROM_CODEX": {1083        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1084        // be able to restore a vault that was printed by a Pro user.1085        // DO NOT add a Pro gate here.1086        const payload = msg.payload as CodexRestorePayload;1087        return await handleRestoreFromCodex(payload);1088      }1089      case "OPEN_PRO_GATE": {1090        // Content script requests: open popup and navigate to License section.1091        const { feature } = (msg.payload ?? {}) as { feature?: string };1092        if (chrome.storage.session) {1093          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1094        }1095        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1096        return { ok: true };1097      }1098      case "OPEN_POPUP": {1099        // Content script asks to open the trusted extension popup — used by the1100        // inline locked bubble so the master password is entered in the popup,1101        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1102        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1103        // toolbar icon. The badge already signals Peach needs attention.1104        //1105        // Set a session flag so the popup knows it was opened for inline unlock1106        // and should close itself once the vault is unlocked (returning the user1107        // to the inline autofill selector on the page).1108        if (chrome.storage.session) {1109          await chrome.storage.session.set({ peach_inline_unlock: true });1110        }1111        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1112        return { ok: true };1113      }1114      case "OPEN_DETACHED_POPUP": {1115        // A window created by the action popup and then orphaned with1116        // window.close() is cascaded shut by Chrome, so the file-picker1117        // flows (OS dialogs that dismiss the popup on focus loss) ask the SW1118        // to open the standalone window instead — the SW has no window to be1119        // associated with. The query string is allowlisted so this can never1120        // open an arbitrary URL.1121        const { route } = (msg.payload ?? {}) as { route?: string };1122        const search = route === "peachscript"1123          ? "?restore=peachscript"1124          : route === "csv"1125            ? "?restore=csv"1126            : route === "codex-pdf"1127              ? "?codex=pdf"1128              : null;1129        if (!search) return { ok: false, error: "bad_route" };1130        try {1131          const popupHtml =1132            chrome.runtime.getManifest().action?.default_popup ?? "src/popup/index.html";1133          await chrome.windows.create({1134            url: chrome.runtime.getURL(`${popupHtml}${search}`),1135            type: "popup",1136            width: 320,1137            height: 550,1138          });1139          return { ok: true, data: { detached: true } };1140        } catch {1141          return { ok: false };1142        }1143      }1144      case "GET_IDENTITIES": {1145        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1146        return { ok: true, data: vault.getIdentities() };1147      }1148      case "TOUCH_AUTO_LOCK": {1149        // touchAutoLock() is already called by shouldRefreshAutoLock above;1150        // this case just gives the popup a typed message to keep the session alive.1151        return { ok: true };1152      }1153      case "GET_ADVANCED_HEALTH_REPORT": {1154        const gate = await requirePro("advanced_health");1155        if (!gate.allowed) return { ok: false, error: "pro_required" };1156        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1157        const report = await buildAdvancedHealthReport(vault.getEntries());1158        return { ok: true, data: report };1159      }1160      case "IS_DURESS_ENABLED": {1161        const enabled = await vault.isDuressEnabled();1162        return { ok: true, data: enabled };1163      }1164      case "SETUP_DURESS": {1165        // Single enforcement point for the Duress Vault Pro gate. Free users1166        // who somehow reach this handler are rejected here; the popup also1167        // pre-checks isPro() to avoid showing the setup form to free users,1168        // but server-side is the actual security boundary.1169        const gate = await requirePro("duress_vault");1170        if (!gate.allowed) return { ok: false, error: "pro_required" };1171        // MV3 service workers restart after inactivity, losing the in-memory1172        // derived key. Detect this before calling setupDuress so the popup1173        // can show a meaningful prompt to re-lock and re-unlock.1174        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1175        const { duressPassword } = msg.payload as { duressPassword: string };1176        await vault.setupDuress(duressPassword);1177        return { ok: true };1178      }1179      case "DISABLE_DURESS": {1180        await vault.disableDuress();1181        return { ok: true };1182      }1183      case "VERIFY_MAIN_PASSWORD": {1184        const { password } = msg.payload as { password: string };1185        const ok = await vault.verifyMainPassword(password);1186        return { ok: true, data: ok };1187      }1188      case "CHANGE_PASSWORD": {1189        const { currentPassword, newPassword } = msg.payload as {1190          currentPassword: string;1191          newPassword: string;1192        };1193        const changed = await vault.changePassword(currentPassword, newPassword);1194        return changed1195          ? { ok: true }1196          : { ok: false, error: "incorrect_current_password" };1197      }1198      case "GET_SITE_PASSWORD_POLICY": {1199        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1200        if (!tab?.id) return { ok: true, data: null };1201        try {1202          const response = await chrome.tabs.sendMessage(tab.id, {1203            type: "GET_SITE_PASSWORD_POLICY",1204          });1205          return (response as MessageResponse) ?? { ok: true, data: null };1206        } catch {1207          return { ok: true, data: null };1208        }1209      }1210      case "RECORD_MANUAL_SUMMON": {1211        const { domain } = msg.payload as { domain: string };1212        const settings = vault.getSettings();1213        const existing = settings.manualSummonDomains?.[domain];1214        const now = Date.now();1215        await vault.updateSettings({1216          manualSummonDomains: {1217            ...settings.manualSummonDomains,1218            [domain]: {1219              firstSummonedAt: existing?.firstSummonedAt ?? now,1220              summonCount: (existing?.summonCount ?? 0) + 1,1221              lastSummonedAt: now,1222            },1223          },1224        });1225        return { ok: true };1226      }1227      case "DECLINE_CARD_SAVE": {1228        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1229        await vault.declineCardSaveOffer(last4, expMonth, expYear);1230        return { ok: true };1231      }1232      case "IS_CARD_DECLINED": {1233        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1234        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1235        return { ok: true, data: declined };1236      }1237      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1238        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1239          rpId?: string;1240          rpName?: string;1241          userName?: string;1242          userDisplayName?: string;1243        };1244        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1245        return await initiateFirefoxPasskeyCreate({1246          rpId,1247          rpName: rpName ?? rpId,1248          userName,1249          userDisplayName,1250        }, attestedSenderOrigin(sender));1251      }12521253      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1254        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1255        if (!payload) return { ok: false, error: "missing_payload" };1256        return await completeFirefoxPasskeyCreate(payload);1257      }12581259      case "PASSKEY_OFFER_DECLINE": {1260        const { domain } = (msg.payload ?? {}) as { domain?: string };1261        if (!domain) return { ok: false, error: "domain_required" };1262        await recordPasskeyOfferDecline(domain);1263        return { ok: true };1264      }12651266      case "GET_PASSKEY_OFFER_DECLINED": {1267        const { domain } = (msg.payload ?? {}) as { domain?: string };1268        if (!domain) return { ok: false, error: "domain_required" };1269        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1270      }12711272      case "PASSKEY_HAS_CREDENTIALS": {1273        const payload = msg.payload as {1274          rpId?: string;1275          allowCredentials?: Array<{ id: string; type?: string }>;1276        } | undefined;1277        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1278        return await handlePasskeyHasCredentials({1279          rpId: payload.rpId,1280          allowCredentials: payload.allowCredentials ?? [],1281        }, attestedSenderOrigin(sender));1282      }12831284      case "PASSKEY_CREATE": {1285        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1286        if (!payload?.rpId || !payload?.userName) {1287          return { ok: false, error: "rpid_and_username_required" };1288        }1289        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1290      }12911292      case "PASSKEY_GET": {1293        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1294        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1295        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1296      }12971298      case "PASSKEY_AUTH_RESPONSE": {1299        const { requestId, approved } = (msg.payload ?? {}) as {1300          requestId?: string | number;1301          approved?: boolean;1302        };1303        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1304          return { ok: false, error: 'requestId and approved required' };1305        }1306        await resolvePendingPasskeyRequest(Number(requestId), approved);1307        return { ok: true };1308      }13091310      case "GET_PASSKEY_FOR_DOMAIN": {1311        const { domain } = (msg.payload ?? {}) as { domain?: string };1312        if (!domain) return { ok: false, error: "domain_required" };1313        // Scope to the caller's own origin: a page may only ask about passkeys1314        // for a domain it actually owns, so an arbitrary page cannot enumerate1315        // which sites the user holds passkeys for or read the username (audit MEDIUM).1316        const origin = attestedSenderOrigin(sender);1317        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1318        if (!vault.isUnlocked()) return { ok: true, data: null };1319        const match = vault1320          .getEntries()1321          .find((entry) => entry.passkey?.rpId === domain);1322        if (!match || !match.passkey) return { ok: true, data: null };1323        // Slim shape — only the fields State 11 needs. Never expose private1324        // key material, even though this is locked behind isUnlocked.1325        return {1326          ok: true,1327          data: {1328            rpId: match.passkey.rpId,1329            userName: match.passkey.userName,1330            browser: match.passkey.browser,1331          },1332        };1333      }13341335      case "DESTROY_VAULT": {1336        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1337        // storage.local.clear() wipes every Peach key (slots, settings, license,1338        // onboarded flag, history, sync state, declined cards, recall, etc.);1339        // session.clear() wipes pending passkey requests + pro-notice queues.1340        // Caller (Panic.tsx) handles UI navigation back to onboarding.1341        //1342        // The Pro license is the one thing that must survive: the user paid for1343        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1344        // Capture it before the clear and restore it after. peach_pro_celebrated1345        // rides along so the Pro celebration doesn't replay on the next unlock.1346        const preserved = await chrome.storage.local.get([1347          "peach_license",1348          "peach_pro_celebrated",1349        ]);1350        vault.lock();1351        await storageClear();1352        await vault.clearVaultHistory();1353        const toRestore: Record<string, unknown> = {};1354        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1355        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1356        if (Object.keys(toRestore).length > 0) {1357          await chrome.storage.local.set(toRestore);1358        }1359        if (chrome.storage.session) {1360          await chrome.storage.session.clear();1361        }1362        return { ok: true };1363      }13641365      // Android-only: biometric unlock with pre-derived key.1366      case "UNLOCK_WITH_KEY": {1367        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1368        if (!isNativePlatform()) {1369          return { ok: false, error: "desktop_only_uses_password" };1370        }1371        try {1372          const result = await vault.unlockWithKey(masterKeyHex);1373          if (result.ok) {1374            onVaultUnlocked();1375            await publishInMemoryVault(result.entries);1376          }1377          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1378        } catch {1379          return { ok: false, error: "invalid_key" };1380        }1381      }1382      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1383      case "GET_DERIVED_KEY": {1384        if (!isNativePlatform()) {1385          return { ok: false, error: "android_only" };1386        }1387        if (!vault.isUnlocked()) {1388          return { ok: false, error: "vault_locked" };1389        }1390        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1391      }1392      case "GET_IDENTITY_SUGGESTIONS": {1393        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1394        const entries = vault.getEntries();1395        const suggestions = buildIdentitySuggestions(entries);1396        return { ok: true, data: { suggestions } };1397      }1398      case "POPULATE_INLINE_VAULT": {1399        if (!isNativePlatform()) return { ok: false };1400        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1401        const entries = vault.getEntries();1402        await publishInMemoryVault(entries);1403        return { ok: true };1404      }1405      case "ML_INIT":1406        return { ok: true };14071408      case "ML_PREDICT_BATCH": {1409        // AUD-002: shape-validate before forwarding to the ML helper.1410        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1411        if (!Array.isArray(featuresArray)) {1412          return { ok: false, error: "invalid_payload" };1413        }1414        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1415      }14161417      // ── Vault sync (v3) ───────────────────────────────────────────────1418      // Returns the public-facing local identity needed by the popup to1419      // drive Phase-1 audio pairing. The private long-term key never1420      // leaves the background.1421      case "GET_LOCAL_IDENTITY": {1422        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1423        // Pro license from an already-Pro peer (at least one device must be Pro).1424        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1425        // Identity derives from the stable root key, not the password-derived1426        // key, so pairing survives a master-password change (SEV-2-B).1427        const masterKeyHex = vault.getRootKeyHex();1428        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1429        const masterKey = unhexBytes(masterKeyHex);1430        try {1431          const identity = await buildLocalIdentity(masterKey);1432          // If this device is Pro, advertise the signed license so the peer can1433          // activate it after SAS confirmation — pairing carries Pro across.1434          if (await isProUser()) {1435            const license = await getLicenseKey();1436            if (license) (identity as { license?: string }).license = license;1437          }1438          return { ok: true, data: identity };1439        } finally {1440          masterKey.fill(0);1441        }1442      }14431444      case "LIST_PAIRED_DEVICES": {1445        const devices = await listPairedDevicesV3();1446        return { ok: true, data: { devices } };1447      }14481449      case "RENAME_PAIRED_DEVICE": {1450        const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string };1451        if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") {1452          return { ok: false, error: "invalid_payload" };1453        }1454        await renamePairedDeviceV3(deviceId, name);1455        return { ok: true };1456      }14571458      case "UNPAIR_DEVICE": {1459        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1460        if (typeof deviceId !== "string" || !deviceId) {1461          return { ok: false, error: "invalid_payload" };1462        }1463        // Removing a device REVOKES it rather than just dropping the local1464        // row: a plain removal is undone the moment any other peer vouches it1465        // back through a manifest, which is exactly what the relay makes easy.1466        await revokeDeviceByIdV3(deviceId, await getOrCreateDeviceId());1467        // Sync against the remaining hosts — the unpaired device no longer1468        // matters but the next alarm tick is up to ten minutes away.1469        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1470        return { ok: true };1471      }14721473      case "RENAME_LOCAL_DEVICE": {1474        const { name } = (msg.payload ?? {}) as { name?: string };1475        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1476        await setDeviceNameV3(name);1477        return { ok: true };1478      }14791480      // ── Relay pairing ─────────────────────────────────────────────────────1481      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1482      // session runs in the background; the SAS and the terminal result reach1483      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1484      case "START_ADOPTION_SOURCE": {1485        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1486        if (isRelayAdoptionSourceInFlight()) {1487          return { ok: false, error: "adoption_source_in_progress" };1488        }1489        try {1490          return { ok: true, data: await startRelayAdoptionSource() };1491        } catch (error) {1492          return {1493            ok: false,1494            error: error instanceof Error ? error.message : "adoption_source_failed",1495          };1496        }1497      }14981499      // Onboarding receiver — empty extension shows a QR, phone scans and1500      // sends the vault. The popup supplies the local-only password here so1501      // the background can wrap the adopted root key at rest without ever1502      // asking the user to retype it.1503      case "START_ADOPTION_RECEIVER": {1504        if (isRelayAdoptionSourceInFlight()) {1505          return { ok: false, error: "adoption_receiver_in_progress" };1506        }1507        const password = (msg.payload as { password?: unknown } | undefined)?.password;1508        if (typeof password !== "string" || password.length === 0) {1509          return { ok: false, error: "invalid_payload" };1510        }1511        try {1512          return { ok: true, data: await startRelayAdoptionReceiver(password) };1513        } catch (error) {1514          return {1515            ok: false,1516            error: error instanceof Error ? error.message : "adoption_receiver_failed",1517          };1518        }1519      }15201521      // Popup→bg counterpart to ADOPTION_SOURCE_SAS (receiver flow).1522      // The receiver now auto-accepts the SAS (both sides derive it from the1523      // same Noise handshake hash, so the codes match by construction) so1524      // the popup never has a SAS screen to tap on. The id round-trips the1525      // same way so a stale late response can't approve the wrong session.1526      // Popup→bg counterpart for the source flow: Confirm/Cancel on the1527      // source's SAS screen.15281529      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1530      // on the source's SAS screen. The id round-trips the same way so a stale1531      // late response can't approve the wrong session.1532      case "SOURCE_SAS_DECISION": {1533        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1534        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1535          return { ok: false, error: "invalid_payload" };1536        }1537        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1538      }15391540      case "CANCEL_ADOPTION_SOURCE": {1541        cancelRelayAdoptionSource();1542        return { ok: true };1543      }15441545      case "TRIGGER_SYNC": {1546        const payload = (msg.payload ?? {}) as {1547          reason?: "vault_change" | "foreground" | "manual";1548          force?: boolean;1549        };1550        const reason = payload.reason ?? "foreground";15511552        void triggerSyncIfReachable({ reason, force: payload.force === true });1553        return { ok: true };1554      }15551556      case "GET_SYNC_STATE": {1557        return { ok: true, data: getSyncState() };1558      }15591560      case "GET_SYNC_SETTINGS": {1561        return { ok: true, data: await getSyncSettings() };1562      }15631564      case "SET_SYNC_SETTINGS": {1565        const payload = (msg.payload ?? {}) as {1566          mode?: unknown;1567          relayUrl?: unknown;1568        };1569        try {1570          // A custom relay URL implies private mode; Peach's own relay stays1571          // public. See setRelayUrl.1572          if (payload.relayUrl !== undefined) {1573            if (typeof payload.relayUrl !== "string") {1574              return { ok: false, error: "invalid_relay_url" };1575            }1576            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1577          }1578          if (payload.mode !== undefined) {1579            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1580              return { ok: false, error: "invalid_sync_mode" };1581            }1582            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1583          }1584          return { ok: true, data: await getSyncSettings() };1585        } catch (error) {1586          return {1587            ok: false,1588            error: error instanceof Error ? error.message : "invalid_relay_url",1589          };1590        }1591      }15921593      case "GET_SYNC_ALERTS": {1594        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1595        const alerts = await getPendingSyncAlerts();1596        // The popup reads on open and acknowledges with consume:true after1597        // rendering, so a popup crash between read and render doesn't lose1598        // the alerts.1599        if (consume) await clearPendingSyncAlerts();1600        return { ok: true, data: alerts };1601      }16021603      case "GET_PENDING_VOUCHED_DEVICES": {1604        return { ok: true, data: await listPendingVouchedDevices() };1605      }1606      case "CONFIRM_VOUCHED_DEVICE": {1607        const { deviceId } = msg.payload as { deviceId: string };1608        const pending = await getPendingVouchedDevice(deviceId);1609        if (!pending) return { ok: false, error: "not_pending" };1610        // Last gate before a vouched device becomes a sync peer. A queue entry1611        // can predate the revocation that names it, so revocation is re-checked1612        // here rather than trusted to have swept the queue.1613        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {1614          await removePendingVouchedDevice(deviceId);1615          return { ok: false, error: "device_revoked" };1616        }1617        await upsertPairedDeviceV3({1618          deviceId: pending.deviceId,1619          deviceName: pending.deviceName,1620          deviceType:1621            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1622          longTermPublicKeyHex: pending.longTermPublicKeyHex,1623          signingPublicKeyHex: pending.signingPublicKeyHex,1624          wsPort: pending.wsPort,1625          pairedAt: pending.pairedAt,1626          trustSource: "vouched",1627        });1628        await removePendingVouchedDevice(deviceId);1629        // Newly confirmed vouched device is now a sync target — kick a round1630        // so the mesh introduction pays off without a 10-minute wait.1631        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1632        return { ok: true };1633      }1634      case "REJECT_VOUCHED_DEVICE": {1635        const { deviceId } = msg.payload as { deviceId: string };1636        await removePendingVouchedDevice(deviceId);1637        return { ok: true };1638      }1639      case "ROTATE_SYNC_IDENTITY": {1640        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1641        const result = await vault.rotateSyncIdentity();1642        return result.ok ? { ok: true } : { ok: false, error: result.error };1643      }16441645      default:1646        return { ok: false, error: "unknown_message_type" };1647    }1648  } catch (err) {1649    return {1650      ok: false,1651      error: err instanceof Error ? err.message : "operation_failed",1652    };1653  }1654}16551656// --- Mobile platform helpers ---16571658// Android: populates the in-memory vault used by PeachAutofillService.1659async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1660  const plugin = nativePlugin<{1661    setEntries?: (args: {1662      entries: Array<{1663        id: string;1664        title: string;1665        username: string;1666        email: string;1667        password: string;1668        url: string;1669        totp: string;1670        additionalUrls: string[];1671      }>;1672    }) => Promise<void>;1673  }>("InMemoryVaultPlugin");1674  if (!plugin?.setEntries) return;1675  await plugin.setEntries({1676    entries: entries.map((e) => ({1677      id: e.id,1678      title: e.title ?? "",1679      username: e.username ?? "",1680      email: (e as VaultEntry & { email?: string }).email ?? "",1681      password: e.password ?? "",1682      url: e.url ?? "",1683      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1684      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1685    })),1686  });1687}16881689// Android: clear the autofill in-memory store on lock.1690async function clearInMemoryVault(): Promise<void> {1691  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1692  if (!plugin?.clearEntries) return;1693  await plugin.clearEntries();1694}16951696// Returns username use-counts from the vault, sorted by frequency. Each row1697// also carries the entry's email so the popup can suggest the email/username1698// pair the user has actually used together.1699function buildIdentitySuggestions(1700  entries: VaultEntry[],1701): Array<{ email: string; username: string; count: number }> {1702  const usernameCounts = new Map<string, number>();1703  const usernameEmail = new Map<string, string>();1704  for (const entry of entries) {1705    const username = entry.username ?? "";1706    const email = (entry as VaultEntry & { email?: string }).email ?? "";1707    if (!username && !email) continue;1708    const key = username || email;1709    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1710    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1711  }1712  return Array.from(usernameCounts.entries())1713    .sort((a, b) => b[1] - a[1])1714    .map(([username, count]) => ({1715      email: usernameEmail.get(username) ?? "",1716      username,1717      count,1718    }));1719}17201721/** Notify all content scripts that the vault just became available. */1722function broadcastToContentScripts(message: { type: string }): void {1723  if (!chrome.tabs?.query) return;1724  chrome.tabs.query({}, (tabs) => {1725    for (const tab of tabs) {1726      if (tab.id !== undefined) {1727        chrome.tabs.sendMessage(tab.id, message).catch(() => {1728          // Tab may not have a content script — silently ignore1729        });1730      }1731    }1732  });1733}17341735function shouldRefreshAutoLock(type: MessageType): boolean {1736  return (1737    type !== "HAS_VAULT" &&1738    type !== "IS_UNLOCKED" &&1739    type !== "GET_VAULT_STATUS" &&1740    type !== "LOCK" &&1741    type !== "UPDATE_SETTINGS" &&1742    type !== "GET_PENDING_PASSKEY" &&1743    type !== "GET_PASSKEY_PROVIDER_STATE" &&1744    type !== "DECLINE_CARD_SAVE" &&1745    type !== "IS_CARD_DECLINED"1746  );1747}17481749function isAllowedCanaryWebhookUrl(value: string): boolean {1750  try {1751    const url = new URL(value);1752    if (url.protocol !== "https:") return false;17531754    const hostname = url.hostname.toLowerCase();1755    if (1756      hostname === "localhost" ||1757      hostname.endsWith(".localhost") ||1758      isPrivateIpv4(hostname) ||1759      isPrivateIpv6(hostname)1760    ) {1761      return false;1762    }17631764    return true;1765  } catch {1766    return false;1767  }1768}17691770function isPrivateIpv4(hostname: string): boolean {1771  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1772    return true;1773  }17741775  const octets = hostname.split(".").map((part) => Number(part));1776  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1777    return false;1778  }17791780  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1781}17821783function isPrivateIpv6(hostname: string): boolean {1784  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1785  // IPv4-mapped IPv6 literals embed a plain IPv4 address that the prefix1786  // list below can never match (WHATWG URL serializes [::ffff:192.168.0.1]1787  // as ::ffff:c0a8:1). Unwrap and test the embedded IPv4; unparseable mapped1788  // tails fail closed. (Codex Security 2026-08-04 LOW,1789  // ssrf.webhook-url-private-ip-filter.) DNS rebinding is out of scope for a1790  // one-shot host check.1791  const mapped = /^::ffff:(.+)$/.exec(normalized);1792  if (mapped) {1793    const tail = mapped[1] ?? "";1794    if (tail.includes(".")) return isPrivateIpv4(tail);1795    const parts = tail.split(":");1796    const [hi, lo] = parts;1797    if (1798      parts.length !== 2 ||1799      !hi ||1800      !lo ||1801      !/^[0-9a-f]{1,4}$/.test(hi) ||1802      !/^[0-9a-f]{1,4}$/.test(lo)1803    ) {1804      return true;1805    }1806    const octets = [1807      (Number.parseInt(hi, 16) >>> 8) & 0xff,1808      Number.parseInt(hi, 16) & 0xff,1809      (Number.parseInt(lo, 16) >>> 8) & 0xff,1810      Number.parseInt(lo, 16) & 0xff,1811    ];1812    return isPrivateIpv4(octets.join("."));1813  }1814  return (1815    normalized === "::1" ||1816    normalized.startsWith("fc") ||1817    normalized.startsWith("fd") ||1818    normalized.startsWith("fe80:")1819  );1820}