messages.ts

75.9 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// handlers that store passkey material, and handlers that return sensitive164// credential material (e.g. the Pro license key). These are gated to trusted165// extension-page senders in handleMessage; the confirmation UX otherwise166// lives only in the popup. Keep this in sync when adding new destructive or167// sensitive handlers. (Codex Security 2026-08-04: GET_ADOPTION_MATERIAL and168// COMPLETE_PAIRING were gated here, then deleted outright — they had no169// legitimate senders; adoption runs in-background via relay-adoption-bg.ts.170// Audit 2026-08-20 #4: GET_LOCAL_IDENTITY gated here — it returns the Pro171// license key, which a compromised content script could exfiltrate.)172const PRIVILEGED_MESSAGE_TYPES: ReadonlySet<string> = new Set([173  "DESTROY_VAULT",174  "CLEAR_VAULT_ENTRIES",175  "RESTORE_VAULT_SNAPSHOT",176  "RESTORE_FROM_CODEX",177  "COMPLETE_FIREFOX_PASSKEY_CREATE",178  "UNLOCK_WITH_PIN",179  "SETUP_PIN",180  "DISABLE_PIN",181  "GET_LOCAL_IDENTITY",182]);183184// LV-3: minimum interval between non-test canary pings per webhook+entry.185const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour186187const PRIVATE_IPV4_RANGES = [188  { prefix: "10." },189  { prefix: "127." },190  { prefix: "169.254." },191  { prefix: "192.168." },192];193194export function setupMessageHandler(): void {195  chrome.runtime.onMessage.addListener(196    (msg: unknown, sender, sendResponse) => {197      if (!isMessage(msg)) {198        sendResponse({ ok: false, error: "invalid_message" });199        return true;200      }201      handleMessage(msg, sender)202        .then(sendResponse)203        .catch((err) =>204          sendResponse({205            ok: false,206            error: err instanceof Error ? err.message : String(err),207          })208        );209      return true;210    }211  );212213  // Android: the chrome shim queues sendMessage calls until this handler is214  // registered. Without this hookup, every message hangs on Capacitor builds.215  // eslint-disable-next-line @typescript-eslint/no-explicit-any216  const reg = (globalThis as any).__peachRegisterMessageHandler;217  if (typeof reg === "function") {218    reg(async (m: unknown) => {219      if (!isMessage(m)) return { ok: false, error: "invalid_message" };220      try {221        return await handleMessage(m);222      } catch (err) {223        return {224          ok: false,225          error: err instanceof Error ? err.message : String(err),226        };227      }228    });229  }230  if (isNativePlatform()) {231    void bootstrapNativeSyncRunner();232  }233}234235async function bootstrapNativeSyncRunner(): Promise<void> {236  if (nativeSyncRunnerBootstrapped) return;237  nativeSyncRunnerBootstrapped = true;238  try {239    setSyncRunner(productionSyncRunner);240    await hydratePersistedSyncState();241  } catch (err) {242    nativeSyncRunnerBootstrapped = false;243    console.warn("[Peach] failed to bootstrap native sync runner:", err);244  }245}246247function isMessage(m: unknown): m is Message {248  return typeof m === "object" && m !== null && "type" in m;249}250251/**252 * The browser-attested origin of the page that originated this message. A web253 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),254 * so every page-driven message arrives via the content-script relay and the255 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a256 * value the page cannot forge. This is the ONLY trustworthy origin for passkey257 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.258 */259function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {260  if (sender.origin) return sender.origin;261  if (sender.url) {262    try { return new URL(sender.url).origin; } catch { return undefined; }263  }264  return undefined;265}266267// Resolves once restoreFromSession() has run, so handlers see the correct268// post-restore unlock state. entry.ts registers this BEFORE the message269// handler so the onMessage listener is added synchronously at SW startup270// (MV3 requirement) while unlock-dependent handlers still wait for restore.271let restoreReady: Promise<void> = Promise.resolve();272273/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */274export function setRestoreReady(p: Promise<unknown>): void {275  restoreReady = p.then(() => undefined, () => undefined);276}277278export async function handleMessage(279  msg: Message,280  sender: Partial<chrome.runtime.MessageSender> = {}281): Promise<MessageResponse> {282  try {283    // Wait for session-restore to finish before reading any unlock/vault state.284    // On a cold SW start the popup's first message arrives while restore is285    // still in flight; without this gate IS_UNLOCKED would report locked (a286    // spurious lock screen) and the storage reads could race. The onMessage287    // listener itself is registered synchronously (entry.ts) so this gate, not288    // listener registration, is what absorbs the cold-start window.289    await restoreReady;290    // Validate sender — only allow messages from our extension pages/scripts.291    // `sender.id` is undefined for messages originating from extension UI292    // (popup/options), which is legitimate; reject only when it is defined293    // and does not match our extension id.294    if (295      sender.id !== undefined &&296      sender.id !== chrome.runtime.id297    ) {298      return { ok: false, error: "invalid_sender" };299    }300301    // PCH-01-018: destructive and sensitive operations must originate from a302    // trusted extension page (popup/options), never from a content script. The303    // sender.id check above only proves the message came from *our* extension —304    // a content script injected into an attacker page passes it. A single305    // XSS-class bug in the injected UI would otherwise escalate to vault306    // destruction, root-key exfiltration, or attacker device registration.307    // Extension pages carry an extension-origin sender.url; content scripts308    // carry a page URL.309    if (PRIVILEGED_MESSAGE_TYPES.has(msg.type)) {310      const extensionOrigin = chrome.runtime.getURL("");311      if (!sender.url?.startsWith(extensionOrigin)) {312        return { ok: false, error: "invalid_sender" };313      }314    }315316    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {317      touchAutoLock();318    }319320    switch (msg.type) {321      case "CREATE_VAULT": {322        const { password } = msg.payload as { password: string };323        // Refuse to create a vault under an empty master password — the derived324        // key would be publicly known and the at-rest AES-GCM protection void325        // (audit HIGH; the CSV-import path previously passed ""). Length/strength326        // policy lives in the onboarding UI; this is the non-negotiable floor.327        if (typeof password !== "string" || password.length === 0) {328          return { ok: false, error: "invalid_payload" };329        }330        await vault.createVault(password);331        await setupAutoLock();332        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });333        onVaultUnlocked();334        return { ok: true };335      }336      case "CREATE_VAULT_FROM_ROOT_KEY": {337        console.log("[Peach diag] CREATE_VAULT_FROM_ROOT_KEY handler entered");338        const { password, rootKeyHex } = (msg.payload ?? {}) as {339          password?: unknown;340          rootKeyHex?: unknown;341        };342        console.log("[Peach diag] payload types:", typeof password, typeof rootKeyHex, "lengths:", (password as string)?.length, (rootKeyHex as string)?.length);343        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {344          console.log("[Peach diag] payload invalid, returning invalid_payload");345          return { ok: false, error: "invalid_payload" };346        }347348        try {349          console.log("[Peach diag] calling vault.createVaultFromRootKey");350          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);351          console.log("[Peach diag] createVaultFromRootKey returned vaultId", vaultId);352          await setupAutoLock();353          console.log("[Peach diag] setupAutoLock done");354          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });355          onVaultUnlocked();356          console.log("[Peach diag] handler completing successfully");357          return { ok: true, vaultId };358        } catch (err) {359          console.error("[Peach diag] handler caught error:", err);360          return { ok: false, error: err instanceof Error ? err.message : String(err) };361        }362      }363      case "UNLOCK": {364        const { password } = msg.payload as { password: string };365        const ok = await vault.unlock(password);366        if (ok) {367          // KAT: verify the WebCrypto stack is healthy before the user relies on it.368          // Runs after unlock so latency is hidden behind the vault-load time.369          const kat = await runSelfTest();370          if (!kat.ok) {371            console.error("[Peach] Crypto self-test FAILED:", kat.error);372            await vault.lock();373            return { ok: false, error: "self_test_failed" };374          }375          await vault.updateSettings({ pinPreferred: false });376          await setupAutoLock();377          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });378          onVaultUnlocked();379          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());380          return { ok: true };381        }382        // Distinguish corruption from wrong password so the popup can offer383        // a history-restore path instead of falsely accusing the user of384        // mistyping (M7/COR-007).385        const failure = vault.consumeLastUnlockFailureReason();386        if (failure) {387          return {388            ok: false,389            error: "vault_corrupted",390            canRestoreFromHistory: true,391          } as MessageResponse;392        }393        return { ok: false };394      }395      case "UNLOCK_WITH_PIN": {396        const { pin } = (msg.payload ?? {}) as { pin?: unknown };397        if (typeof pin !== "string") return { ok: false, error: "invalid_payload" };398        const ok = await vault.unlockWithPin(pin);399        if (!ok) return { ok: false };400        const kat = await runSelfTest();401        if (!kat.ok) {402          await vault.lock();403          return { ok: false, error: "self_test_failed" };404        }405        await vault.updateSettings({ pinPreferred: true });406        await setupAutoLock();407        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });408        onVaultUnlocked();409        if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());410        return { ok: true };411      }412      case "VALIDATE_RECOVERY_WORDS": {413        const { words } = msg.payload as { words: string[] };414        const invalid = findInvalidWords(words);415        return { ok: true, data: { valid: invalid.length === 0, invalid } };416      }417      case "GET_RECOVERY_WORDS": {418        // Must be unlocked and have recovery set up (vault must be v2.12+).419        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };420        // LV-4: the recovery words re-derive the ROOT KEY — the highest-421        // value secret in the vault. A session unlock (which may be hours422        // old on a shared machine) is not enough; require a fresh password423        // proof, matching the 1Password/Bitwarden pattern for revealing424        // escrow material. EXEMPTION: the create-vault / rotation confirmation425        // window (peach_recovery_pending) shows the words immediately after426        // the user authenticated, and that confirmation UI has no password to427        // resend — skip the re-auth there only.428        if (!(await isRecoveryConfirmPending())) {429          const { password } = (msg.payload ?? {}) as { password?: string };430          if (typeof password !== "string" || !password) {431            return { ok: false, error: "password_required" };432          }433          if (!(await vault.verifyMainPassword(password))) {434            return { ok: false, error: "wrong_password" };435          }436        }437        try {438          const words = await vault.getRecoveryWords();439          return { ok: true, data: words };440        } catch {441          // pre-v2.12 vault that hasn't migrated442          return { ok: false, error: "recovery_not_setup" };443        }444      }445      case "RECOVER_WITH_WORDS": {446        // User has lost their password but has their 12 recovery words.447        // We: (1) validate the words, (2) re-encrypt vault with new password.448        const { words, newPassword } = msg.payload as {449          words: string[];450          newPassword: string;451        };452        const stored = await vault.loadSlotA();453        if (!stored) return { ok: false, error: "no_vault" };454        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {455          return { ok: false, error: "recovery_not_setup" };456        }457        // Unwrap the root key from the recovery escrow.458        try {459          await vault.unwrapRootKeyForRecovery(460            stored.recovery_wrapped_root_key,461            stored.recovery_nonce ?? "",462            stored.recovery_tag ?? "",463            stored.recovery_salt,464            words465          );466        } catch {467          return { ok: false, error: "invalid_recovery_words" };468        }469        // Re-key: derive fresh salt + key from new password.470        const newSalt = vault.generateSalt();471        const newKey = await vault.deriveKey(newPassword, newSalt);472        // Re-wrap root key under the new password's derived key so the same473        // recovery words continue to work after the password change.474        await vault.rewrapRootKeyForPassword(newKey, newSalt);475        // Re-encrypt vault entries with the new key.476        await vault.changePasswordWithNewKey(newSalt, newKey);477        await setupAutoLock();478        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });479        return { ok: true };480      }481      case "LOCK":482        vault.lock();483        if (isNativePlatform()) await clearInMemoryVault();484        return { ok: true };485      case "IS_UNLOCKED":486        return { ok: true, data: vault.isUnlocked() };487      case "GET_VAULT_STATUS":488        return { ok: true, unlocked: vault.isUnlocked() };489      case "HAS_VAULT":490        return { ok: true, data: await vault.hasVault() };491      case "GET_ENTRIES":492        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };493        return { ok: true, data: vault.getEntries() };494      case "ADD_ENTRY": {495        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };496        const payload = msg.payload;497        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {498          return { ok: false, error: "invalid_payload" };499        }500        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);501        return { ok: true, data: entry };502      }503      case "BATCH_ADD_ENTRIES": {504        const payload = msg.payload as { entries?: unknown } | null | undefined;505        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {506          return { ok: false, error: "invalid_payload" };507        }508        if (!Array.isArray(payload.entries)) {509          return { ok: false, error: "invalid_payload" };510        }511        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);512        return { ok: true, data: added };513      }514      case "RESTORE_ENTRIES": {515        const payload = msg.payload as516          | { entries?: unknown; mode?: unknown; settings?: unknown }517          | null518          | undefined;519        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {520          return { ok: false, error: "invalid_payload" };521        }522        if (!Array.isArray(payload.entries)) {523          return { ok: false, error: "invalid_payload" };524        }525        if (payload.mode !== "replace" && payload.mode !== "merge") {526          return { ok: false, error: "invalid_payload" };527        }528        const summary = await vault.restoreEntries(529          payload.entries as Parameters<typeof vault.restoreEntries>[0],530          payload.mode531        );532        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {533          await vault.updateSettings(payload.settings as vault.VaultSettings);534        }535        return { ok: true, data: summary };536      }537      case "CLEAR_VAULT_ENTRIES": {538        await vault.clearVaultEntries("REPLACE_ALL");539        return { ok: true };540      }541      case "GET_VAULT_HISTORY": {542        const snapshots = await vault.getVaultHistory();543        return { ok: true, data: snapshots };544      }545      case "RESTORE_VAULT_SNAPSHOT": {546        const { snapshotId } = msg.payload as { snapshotId: string };547        const result = await vault.restoreVaultSnapshot(snapshotId);548        if (!result.ok) return { ok: false, error: result.error };549        broadcastToContentScripts({ type: "VAULT_LOCKED" });550        return { ok: true };551      }552      case "COUNT_DUPLICATES": {553        return { ok: true, data: vault.countDuplicates() };554      }555      case "DEDUPLICATE_ENTRIES": {556        const removed = await vault.deduplicateEntries();557        return { ok: true, data: removed };558      }559      case "UPDATE_ENTRY": {560        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;561        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {562          return { ok: false, error: "invalid_payload" };563        }564        const { id, patch } = payload;565        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {566          return { ok: false, error: "invalid_payload" };567        }568        // Single enforcement point for the Canary Entries Pro gate. Only569        // gates the transition into a canary entry — clearing/disabling a570        // canary (`canary: undefined`) is always allowed, so existing571        // canary entries remain manageable.572        const incomingCanary = (patch as { canary?: unknown }).canary;573        if (incomingCanary && typeof incomingCanary === "object") {574          const existing = vault.getEntryById(id);575          if (!existing?.canary) {576            const gate = await requirePro("canary_entry");577            if (!gate.allowed) return { ok: false, error: "pro_required" };578          }579        }580        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);581        return { ok: true };582      }583      case "ADD_ADDITIONAL_URL": {584        const { id, url } = msg.payload as { id: string; url: string };585        const trimmed = typeof url === "string" ? url.trim() : "";586        if (!trimmed) return { ok: false, error: "url_required" };587        const existing = vault.getEntryById(id);588        if (!existing) return { ok: false, error: "entry_not_found" };589        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };590        const merged = [...(existing.additionalUrls ?? []), trimmed];591        await vault.updateEntry(id, { additionalUrls: merged });592        return { ok: true };593      }594      case "DELETE_ENTRY": {595        const { id } = msg.payload as { id: string };596        await vault.deleteEntry(id);597        return { ok: true };598      }599      case "GET_DELETED_ENTRIES":600        return { ok: true, data: vault.getDeletedEntries() };601      case "RESTORE_ENTRY": {602        const { id } = msg.payload as { id: string };603        await vault.restoreEntry(id);604        return { ok: true };605      }606      case "PURGE_ENTRY": {607        const { id } = msg.payload as { id: string };608        await vault.purgeEntry(id);609        return { ok: true };610      }611      case "PURGE_EXPIRED_TRASH": {612        const { retentionMs } = msg.payload as { retentionMs: number };613        const purged = await vault.purgeExpiredTrash(retentionMs);614        return { ok: true, data: purged };615      }616      case "SAVE_NOTE": {617        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };618        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };619        const now = Date.now();620        if (id) {621          const existing = vault.getEntryById(id);622          if (!existing) return { ok: false, error: "not_found" };623          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });624          return { ok: true, data: vault.getEntryById(id) };625        } else {626          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt627          // (EntryDraft omits both), so passing them was the only reason the628          // `as any` cast existed. Dropping them makes the call type-check.629          const entry = await vault.addEntry({630            type: "note",631            title: title || "Untitled",632            notes: body,633          });634          return { ok: true, data: entry };635        }636      }637      case "DELETE_NOTE": {638        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };639        const { id } = msg.payload as { id: string };640        await vault.deleteEntry(id);641        return { ok: true };642      }643      case "GET_NOTES": {644        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };645        const notes = vault.getEntries().filter(646          (e) => e.type === "note" && !e.deletedAt647        );648        return { ok: true, data: notes } as MessageResponse;649      }650      case "SEARCH_VAULT": {651        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };652        // AUD-002: shape-validate the payload before calling string methods.653        // A raw cast lets a malformed message crash the handler with TypeError.654        const { query } = (msg.payload ?? {}) as { query?: unknown };655        if (typeof query !== "string") {656          return { ok: false, error: "invalid_payload" };657        }658        const q = query.toLowerCase();659        const searchResults = vault.getEntries().filter(660          (e) =>661            !e.deletedAt &&662            (e.title.toLowerCase().includes(q) ||663              e.notes?.toLowerCase().includes(q) ||664              e.username?.toLowerCase().includes(q))665        );666        return { ok: true, data: searchResults } as MessageResponse;667      }668      case "AUTOFILL_QUERY": {669        if (!vault.isUnlocked()) {670          return { ok: false, error: "vault_locked" };671        }672        let { includeAll } = msg.payload as { includeAll?: boolean };673        const { domain, kind, userGesture } = msg.payload as {674          domain: string;675          kind?: "login" | "card" | "totp";676          userGesture?: boolean;677        };678        // MV-2: the vault-wide inventory (every title/username/email/url)679        // may only leave the background on an explicit user gesture — the680        // user opening the search affordance — never on passive form focus.681        // userGesture is self-declared by our own content script; the value682        // of this gate is that PASSIVE code paths (which never set it)683        // cannot ship the inventory, shrinking what a compromised page that684        // merely triggers focus events can observe.685        if (includeAll && userGesture !== true) {686          includeAll = false;687        }688        // kind="card": return saved cards as compact summaries for the689        // inline card silver platter. Cards are not domain-scoped — every690        // saved card is a candidate on every checkout page — so domain is691        // ignored when kind === "card".692        if (kind === "card") {693          const cards = vault.getEntries().filter((e) => e.type === "card");694          return {695            ok: true,696            data: cards.map((e) => ({697              id: e.id,698              title: e.cardNickname || e.title,699              cardholderName: e.cardholderName,700              last4: e.last4,701              expMonth: e.expMonth,702              expYear: e.expYear,703              network: e.network,704            })),705          };706        }707        if (kind === "totp") {708          const matches = (709            includeAll710              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")711              : vault.queryDomain(domain)712          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));713          return {714            ok: true,715            data: matches.map((e) => ({716              id: e.id,717              title: e.title,718              username: e.username,719              email: e.email,720              url: e.url,721              hasTotp: true,722            })),723          };724        }725        // The inline selector fills username+password into a form. Passkey-726        // only entries have no password to fill; sign-in for those goes727        // through the WebAuthn path instead. Filter them out everywhere so728        // the user doesn't see four "GitHub" rows that mostly do nothing.729        // Notes and cards never belonged here either.730        const matches = (731          includeAll732            ? vault733                .getEntries()734                .filter((entry) => entry.type !== "note" && entry.type !== "card")735            : vault.queryDomain(domain)736        ).filter((entry) => !isPasskeyOnly(entry));737        return {738          ok: true,739          data: matches.map((e) =>740            includeAll741              ? {742                  id: e.id,743                  title: e.title,744                  // username/email/url shipped so the inline popup's search745                  // affordance can match on them, not just titles. No secrets746                  // cross the boundary — same shape as the domain-matched747                  // response below minus hasTotp (which the search list748                  // doesn't surface).749                  username: e.username,750                  email: e.email,751                  url: e.url,752                  hasPasskey: e.passkey !== undefined,753                }754              : {755                  id: e.id,756                  title: e.title,757                  username: e.username,758                  email: e.email,759                  url: e.url,760                  hasTotp: Boolean(e.totp),761                  hasPasskey: e.passkey !== undefined,762                }763          ),764        };765      }766      case "GET_ENTRY_FOR_FILL": {767        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };768        const { id, explicitSummon } = msg.payload as {769          id: string;770          explicitSummon?: boolean;771        };772        const entry = vault.getEntryById(id);773        if (!entry) return { ok: false, error: "entry_not_found" };774        // Passkey-only entries (passkey credential, no password) cannot be775        // filled into a form — sign-in goes through the WebAuthn path. A776        // login that ALSO has a passkey is still fillable for its password.777        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };778779        // MV-1: re-validate the entry against the requesting tab's origin.780        // sender.tab.url is browser-attested — a page cannot forge it. When781        // the request does not come from a tab at all (popup surfaces use782        // GET_ENTRY_FOR_EDIT, not this), refuse.783        if (sender.tab !== undefined || sender.url !== undefined) {784          let senderDomain: string | null = null;785          try {786            const rawUrl = sender.tab?.url ?? sender.url ?? "";787            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;788          } catch {789            senderDomain = null;790          }791          if (!senderDomain) return { ok: false, error: "origin_unverified" };792793          const entryDomains = new Set<string>();794          const primary = extractDomain(entry.url ?? "");795          if (primary) entryDomains.add(primary);796          for (const extra of entry.additionalUrls ?? []) {797            const d = extractDomain(extra);798            if (d) entryDomains.add(d);799          }800801          // explicitSummon=true means the user actively picked this entry802          // from the cross-domain search affordance — an intentional803          // off-domain fill. Passive fill paths must stay domain-bound.804          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {805            // Domain mismatch — refuse silently (no oracle about which ids exist).806            return { ok: false, error: "entry_not_found" };807          }808        }809        // Strip the passkey credential AND the raw base32 TOTP seed from the810        // response. Content scripts never need either: the private key is the811        // authenticator's, and handing over the TOTP seed would let a812        // compromised content script mint valid codes indefinitely (SEV-3-C).813        // Generate the *current* 6-digit code here in the background and send814        // only that, plus the seconds left so the UI can render a countdown.815        // Also drop passwordHistory: filling needs only the *current* password.816        // Handing every past password to a content script during passive817        // autofill on an arbitrary page would widen the blast radius of a818        // compromised page far beyond the one credential being filled.819        const {820          passkey: _strippedPasskey,821          totp: seed,822          totpAlgorithm,823          totpDigits,824          totpPeriod,825          passwordHistory: _ph,826          ...safeEntry827        } = entry;828        let totpCode: string | undefined;829        let totpRemaining: number | undefined;830        if (seed) {831          try {832            // PCH-01-019: honour stored algorithm/digits/period (defaults apply833            // when these are undefined, i.e. legacy bare-seed entries).834            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);835            totpCode = generated.code;836            totpRemaining = generated.remaining;837          } catch {838            totpCode = undefined;839          }840        }841        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };842      }843      // Trusted full-entry fetch for Peach's own inline-popup surfaces that844      // genuinely need the raw TOTP seed: the edit form (which re-saves the845      // seed and would otherwise wipe it) and nothing else. Unlike846      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside847      // the inline popup, never during passive autofill on an arbitrary page.848      // The passkey credential is still stripped — the edit form never touches it.849      case "GET_ENTRY_FOR_EDIT": {850        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };851        const { id, explicitSummon } = msg.payload as {852          id: string;853          explicitSummon?: boolean;854        };855        const entry = vault.getEntryById(id);856        if (!entry) return { ok: false, error: "entry_not_found" };857858        // PCH-01-006: re-validate the browser-attested sender origin, mirroring859        // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and860        // full password history — at least as sensitive as the fill response — so861        // the boundary must be enforced here, not only by UI reachability. Today862        // the sole caller is the popup (no sender.tab, so this is a structural863        // no-op), but a future tab-context caller or an id leak would otherwise864        // inherit a full-credential oracle. Unlike the fill path we SKIP (not865        // refuse) when no sender domain resolves, to keep the popup caller working.866        if (sender.tab !== undefined || sender.url !== undefined) {867          let senderDomain: string | null = null;868          try {869            const rawUrl = sender.tab?.url ?? sender.url ?? "";870            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;871          } catch {872            senderDomain = null;873          }874          if (senderDomain) {875            const entryDomains = new Set<string>();876            const primary = extractDomain(entry.url ?? "");877            if (primary) entryDomains.add(primary);878            for (const extra of entry.additionalUrls ?? []) {879              const d = extractDomain(extra);880              if (d) entryDomains.add(d);881            }882            if (explicitSummon !== true && !entryDomains.has(senderDomain)) {883              return { ok: false, error: "entry_not_found" }; // no id oracle884            }885          }886        }887888        const { passkey: _passkey, ...safeEntry } = entry;889        return { ok: true, data: safeEntry };890      }891      case "COPY": {892        // AUD-002: shape-validate the payload before passing to the clipboard893        // helper. A raw cast lets a malformed message reach the clipboard API894        // with a non-string and throw.895        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {896          text?: unknown;897          label?: unknown;898          alreadyWritten?: unknown;899        };900        if (typeof text !== "string" || typeof label !== "string") {901          return { ok: false, error: "invalid_payload" };902        }903        await copyToClipboard(text, label, Boolean(alreadyWritten));904        return { ok: true, clearSeconds: getEffectiveClearSeconds() };905      }906      case "CHECK_ALL_BREACHES": {907        const allEntries = vault.getEntries();908        const results: Record<string, number> = {};909        for (const entry of allEntries) {910          if (entry.type === "note") continue;911          if (!entry.password) continue;912          results[entry.id] = await vault.checkBreach(entry.password);913          // Small delay — be a good citizen to the HIBP API914          await new Promise((r) => setTimeout(r, 200));915        }916        // Persist any non-zero counts back to entries917        for (const [id, count] of Object.entries(results)) {918          const entry = vault.getEntryById(id);919          if (entry && (entry.breach ?? 0) !== count) {920            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });921          }922        }923        return { ok: true, data: results };924      }925      case "GET_SETTINGS":926        return { ok: true, data: await vault.ensureSettingsLoaded() };927      case "UPDATE_SETTINGS": {928        const patch = msg.payload;929        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {930          return { ok: false, error: "invalid_payload" };931        }932        await vault.updateSettings(patch as vault.VaultSettings);933        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {934          await setupAutoLock();935          if (vault.isUnlocked()) touchAutoLock();936        }937        return { ok: true };938      }939      case "SETUP_PIN": {940        const { currentPassword, pin } = (msg.payload ?? {}) as {941          currentPassword?: unknown;942          pin?: unknown;943        };944        if (typeof currentPassword !== "string" || typeof pin !== "string") {945          return { ok: false, error: "invalid_payload" };946        }947        return (await vault.setupPinUnlock(currentPassword, pin))948          ? { ok: true }949          : { ok: false, error: "incorrect_current_password" };950      }951      case "DISABLE_PIN": {952        const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown };953        if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" };954        return (await vault.disablePinUnlock(currentPassword))955          ? { ok: true }956          : { ok: false, error: "incorrect_current_password" };957      }958      case "GET_PENDING_PASSKEY":959        return { ok: true, data: await getPendingPasskeyRequest() };960      case "APPROVE_PASSKEY": {961        const { requestId } = msg.payload as { requestId: number };962        await resolvePendingPasskeyRequest(requestId, true);963        return { ok: true };964      }965      case "DENY_PASSKEY": {966        const { requestId } = msg.payload as { requestId: number };967        await resolvePendingPasskeyRequest(requestId, false);968        return { ok: true };969      }970      case "GET_PASSKEY_PROVIDER_STATE":971        return { ok: true, data: await getPasskeyProviderState() };972      case "SET_PASSKEY_PROVIDER_ENABLED": {973        const { enabled } = msg.payload as { enabled: boolean };974        // Disabling is always free; gating fires only when a free user is975        // trying to turn passkey interception on.976        if (enabled) {977          const gate = await requirePro("passkeys");978          if (!gate.allowed) return { ok: false, error: "pro_required" };979        }980        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };981      }982      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS983      // endpoint. Intentional product behavior — users configure their own984      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private985      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-986      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to987      // users that the entry title leaves the device when the canary fires.988      case "FIRE_CANARY_PING": {989        // Canary alert fires unconditionally for any entry with canary: true.990        // The Pro gate only governs creation/flagging of canary entries; once991        // an entry is flagged, the alert path is a security property and must992        // never be license-gated.993        const { webhookUrl, entryTitle, trigger } = msg.payload as {994          webhookUrl: string;995          entryTitle: string;996          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";997        };998        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {999          return { ok: false, error: "invalid_webhook_url" };1000        }1001        // LV-3: debounce non-test pings per (webhook, entry) so a page that1002        // strobes focus/fill events can't turn the canary into a request1003        // firehose at the user's endpoint. Test pings are exempt — they are1004        // explicit user clicks in the settings UI and are awaited for1005        // feedback. The FIRST ping in a window always goes out, so the1006        // dead-man's-switch property (canary fires on access) is preserved;1007        // only repeats within the window are coalesced.1008        if (trigger !== "test") {1009          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;1010          const stored = await chrome.storage.local.get(rlKey);1011          const last = (stored as Record<string, unknown>)[rlKey];1012          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {1013            return { ok: true, data: { rateLimited: true } };1014          }1015          await chrome.storage.local.set({ [rlKey]: Date.now() });1016        }1017        const body = JSON.stringify({1018          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",1019          entry: entryTitle,1020          trigger,1021          timestamp: new Date().toISOString(),1022          source: "peach-extension",1023        });1024        if (trigger === "test") {1025          // Permitted outbound fetch: user-configured canary alert endpoint1026          // (validated by isAllowedCanaryWebhookUrl above). This is the1027          // only non-HIBP outbound call in the extension — see1028          // Projects.md §3.7. Test pings are awaited so the UI can show1029          // success/failure.1030          try {1031            const res = await fetch(webhookUrl, {1032              method: "POST",1033              headers: { "Content-Type": "application/json" },1034              body,1035            });1036            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1037          } catch (err) {1038            return { ok: false, error: err instanceof Error ? err.message : "network_error" };1039          }1040        }1041        // Non-test triggers are fire-and-forget1042        fetch(webhookUrl, {1043          method: "POST",1044          headers: { "Content-Type": "application/json" },1045          body,1046        }).catch(() => {});1047        return { ok: true };1048      }1049      case "ACTIVATE_LICENSE": {1050        const { key } = msg.payload as { key: string };1051        const licenseInfo = await activateLicense(key);1052        return { ok: true, data: licenseInfo };1053      }1054      case "GET_LICENSE": {1055        const licenseInfo = await getLicenseInfo();1056        return { ok: true, data: licenseInfo };1057      }1058      case "GET_LICENSE_KEY": {1059        const key = await getLicenseKey();1060        return { ok: true, data: key };1061      }1062      case "DEACTIVATE_LICENSE": {1063        await deactivateLicense();1064        return { ok: true };1065      }1066      case "SHOULD_PLAY_CELEBRATION": {1067        const should = await shouldPlayCelebration();1068        return { ok: true, data: should };1069      }1070      case "MARK_CELEBRATION_PLAYED": {1071        await markCelebrationPlayed();1072        return { ok: true };1073      }1074      case "GET_CODEX_VAULT_DATA": {1075        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1076        // popup navigates to the License section without further coordination.1077        const gate = await requirePro("codex");1078        if (!gate.allowed) return { ok: false, error: "pro_required" };1079        return await handleGetCodexVaultData();1080      }1081      case "ESTIMATE_CODEX_PAGES": {1082        const gate = await requirePro("codex");1083        if (!gate.allowed) return { ok: false, error: "pro_required" };1084        return await handleEstimateCodexPages();1085      }1086      case "RESTORE_FROM_CODEX": {1087        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1088        // be able to restore a vault that was printed by a Pro user.1089        // DO NOT add a Pro gate here.1090        const payload = msg.payload as CodexRestorePayload;1091        return await handleRestoreFromCodex(payload);1092      }1093      case "OPEN_PRO_GATE": {1094        // Content script requests: open popup and navigate to License section.1095        const { feature } = (msg.payload ?? {}) as { feature?: string };1096        if (chrome.storage.session) {1097          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1098        }1099        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1100        return { ok: true };1101      }1102      case "OPEN_POPUP": {1103        // Content script asks to open the trusted extension popup — used by the1104        // inline locked bubble so the master password is entered in the popup,1105        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1106        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1107        // toolbar icon. The badge already signals Peach needs attention.1108        //1109        // Set a session flag so the popup knows it was opened for inline unlock1110        // and should close itself once the vault is unlocked (returning the user1111        // to the inline autofill selector on the page).1112        if (chrome.storage.session) {1113          await chrome.storage.session.set({ peach_inline_unlock: true });1114        }1115        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1116        return { ok: true };1117      }1118      case "OPEN_DETACHED_POPUP": {1119        // A window created by the action popup and then orphaned with1120        // window.close() is cascaded shut by Chrome, so the file-picker1121        // flows (OS dialogs that dismiss the popup on focus loss) ask the SW1122        // to open the standalone window instead — the SW has no window to be1123        // associated with. The query string is allowlisted so this can never1124        // open an arbitrary URL.1125        const { route } = (msg.payload ?? {}) as { route?: string };1126        const search = route === "peachscript"1127          ? "?restore=peachscript"1128          : route === "csv"1129            ? "?restore=csv"1130            : route === "codex-pdf"1131              ? "?codex=pdf"1132              : null;1133        if (!search) return { ok: false, error: "bad_route" };1134        try {1135          const popupHtml =1136            chrome.runtime.getManifest().action?.default_popup ?? "src/popup/index.html";1137          await chrome.windows.create({1138            url: chrome.runtime.getURL(`${popupHtml}${search}`),1139            type: "popup",1140            width: 320,1141            height: 550,1142          });1143          return { ok: true, data: { detached: true } };1144        } catch {1145          return { ok: false };1146        }1147      }1148      case "GET_IDENTITIES": {1149        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1150        return { ok: true, data: vault.getIdentities() };1151      }1152      case "TOUCH_AUTO_LOCK": {1153        // touchAutoLock() is already called by shouldRefreshAutoLock above;1154        // this case just gives the popup a typed message to keep the session alive.1155        return { ok: true };1156      }1157      case "GET_ADVANCED_HEALTH_REPORT": {1158        const gate = await requirePro("advanced_health");1159        if (!gate.allowed) return { ok: false, error: "pro_required" };1160        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1161        const report = await buildAdvancedHealthReport(vault.getEntries());1162        return { ok: true, data: report };1163      }1164      case "IS_DURESS_ENABLED": {1165        const enabled = await vault.isDuressEnabled();1166        return { ok: true, data: enabled };1167      }1168      case "SETUP_DURESS": {1169        // Single enforcement point for the Duress Vault Pro gate. Free users1170        // who somehow reach this handler are rejected here; the popup also1171        // pre-checks isPro() to avoid showing the setup form to free users,1172        // but server-side is the actual security boundary.1173        const gate = await requirePro("duress_vault");1174        if (!gate.allowed) return { ok: false, error: "pro_required" };1175        // MV3 service workers restart after inactivity, losing the in-memory1176        // derived key. Detect this before calling setupDuress so the popup1177        // can show a meaningful prompt to re-lock and re-unlock.1178        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1179        const { duressPassword } = msg.payload as { duressPassword: string };1180        await vault.setupDuress(duressPassword);1181        return { ok: true };1182      }1183      case "DISABLE_DURESS": {1184        await vault.disableDuress();1185        return { ok: true };1186      }1187      case "VERIFY_MAIN_PASSWORD": {1188        const { password } = msg.payload as { password: string };1189        const ok = await vault.verifyMainPassword(password);1190        return { ok: true, data: ok };1191      }1192      case "CHANGE_PASSWORD": {1193        const { currentPassword, newPassword } = msg.payload as {1194          currentPassword: string;1195          newPassword: string;1196        };1197        const changed = await vault.changePassword(currentPassword, newPassword);1198        return changed1199          ? { ok: true }1200          : { ok: false, error: "incorrect_current_password" };1201      }1202      case "GET_SITE_PASSWORD_POLICY": {1203        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1204        if (!tab?.id) return { ok: true, data: null };1205        try {1206          const response = await chrome.tabs.sendMessage(tab.id, {1207            type: "GET_SITE_PASSWORD_POLICY",1208          });1209          return (response as MessageResponse) ?? { ok: true, data: null };1210        } catch {1211          return { ok: true, data: null };1212        }1213      }1214      case "RECORD_MANUAL_SUMMON": {1215        const { domain } = msg.payload as { domain: string };1216        const settings = vault.getSettings();1217        const existing = settings.manualSummonDomains?.[domain];1218        const now = Date.now();1219        await vault.updateSettings({1220          manualSummonDomains: {1221            ...settings.manualSummonDomains,1222            [domain]: {1223              firstSummonedAt: existing?.firstSummonedAt ?? now,1224              summonCount: (existing?.summonCount ?? 0) + 1,1225              lastSummonedAt: now,1226            },1227          },1228        });1229        return { ok: true };1230      }1231      case "DECLINE_CARD_SAVE": {1232        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1233        await vault.declineCardSaveOffer(last4, expMonth, expYear);1234        return { ok: true };1235      }1236      case "IS_CARD_DECLINED": {1237        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1238        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1239        return { ok: true, data: declined };1240      }1241      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1242        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1243          rpId?: string;1244          rpName?: string;1245          userName?: string;1246          userDisplayName?: string;1247        };1248        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1249        return await initiateFirefoxPasskeyCreate({1250          rpId,1251          rpName: rpName ?? rpId,1252          userName,1253          userDisplayName,1254        }, attestedSenderOrigin(sender));1255      }12561257      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1258        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1259        if (!payload) return { ok: false, error: "missing_payload" };1260        return await completeFirefoxPasskeyCreate(payload);1261      }12621263      case "PASSKEY_OFFER_DECLINE": {1264        const { domain } = (msg.payload ?? {}) as { domain?: string };1265        if (!domain) return { ok: false, error: "domain_required" };1266        await recordPasskeyOfferDecline(domain);1267        return { ok: true };1268      }12691270      case "GET_PASSKEY_OFFER_DECLINED": {1271        const { domain } = (msg.payload ?? {}) as { domain?: string };1272        if (!domain) return { ok: false, error: "domain_required" };1273        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1274      }12751276      case "PASSKEY_HAS_CREDENTIALS": {1277        const payload = msg.payload as {1278          rpId?: string;1279          allowCredentials?: Array<{ id: string; type?: string }>;1280        } | undefined;1281        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1282        return await handlePasskeyHasCredentials({1283          rpId: payload.rpId,1284          allowCredentials: payload.allowCredentials ?? [],1285        }, attestedSenderOrigin(sender));1286      }12871288      case "PASSKEY_CREATE": {1289        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1290        if (!payload?.rpId || !payload?.userName) {1291          return { ok: false, error: "rpid_and_username_required" };1292        }1293        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1294      }12951296      case "PASSKEY_GET": {1297        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1298        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1299        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1300      }13011302      case "PASSKEY_AUTH_RESPONSE": {1303        const { requestId, approved } = (msg.payload ?? {}) as {1304          requestId?: string | number;1305          approved?: boolean;1306        };1307        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1308          return { ok: false, error: 'requestId and approved required' };1309        }1310        await resolvePendingPasskeyRequest(Number(requestId), approved);1311        return { ok: true };1312      }13131314      case "GET_PASSKEY_FOR_DOMAIN": {1315        const { domain } = (msg.payload ?? {}) as { domain?: string };1316        if (!domain) return { ok: false, error: "domain_required" };1317        // Scope to the caller's own origin: a page may only ask about passkeys1318        // for a domain it actually owns, so an arbitrary page cannot enumerate1319        // which sites the user holds passkeys for or read the username (audit MEDIUM).1320        const origin = attestedSenderOrigin(sender);1321        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1322        if (!vault.isUnlocked()) return { ok: true, data: null };1323        const match = vault1324          .getEntries()1325          .find((entry) => entry.passkey?.rpId === domain);1326        if (!match || !match.passkey) return { ok: true, data: null };1327        // Slim shape — only the fields State 11 needs. Never expose private1328        // key material, even though this is locked behind isUnlocked.1329        return {1330          ok: true,1331          data: {1332            rpId: match.passkey.rpId,1333            userName: match.passkey.userName,1334            browser: match.passkey.browser,1335          },1336        };1337      }13381339      case "DESTROY_VAULT": {1340        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1341        // storage.local.clear() wipes every Peach key (slots, settings, license,1342        // onboarded flag, history, sync state, declined cards, recall, etc.);1343        // session.clear() wipes pending passkey requests + pro-notice queues.1344        // Caller (Panic.tsx) handles UI navigation back to onboarding.1345        //1346        // The Pro license is the one thing that must survive: the user paid for1347        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1348        // Capture it before the clear and restore it after. peach_pro_celebrated1349        // rides along so the Pro celebration doesn't replay on the next unlock.1350        const preserved = await chrome.storage.local.get([1351          "peach_license",1352          "peach_pro_celebrated",1353        ]);1354        vault.lock();1355        await storageClear();1356        await vault.clearVaultHistory();1357        const toRestore: Record<string, unknown> = {};1358        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1359        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1360        if (Object.keys(toRestore).length > 0) {1361          await chrome.storage.local.set(toRestore);1362        }1363        if (chrome.storage.session) {1364          await chrome.storage.session.clear();1365        }1366        return { ok: true };1367      }13681369      // Android-only: biometric unlock with pre-derived key.1370      case "UNLOCK_WITH_KEY": {1371        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1372        if (!isNativePlatform()) {1373          return { ok: false, error: "desktop_only_uses_password" };1374        }1375        try {1376          const result = await vault.unlockWithKey(masterKeyHex);1377          if (result.ok) {1378            onVaultUnlocked();1379            await publishInMemoryVault(result.entries);1380          }1381          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1382        } catch {1383          return { ok: false, error: "invalid_key" };1384        }1385      }1386      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1387      case "GET_DERIVED_KEY": {1388        if (!isNativePlatform()) {1389          return { ok: false, error: "android_only" };1390        }1391        if (!vault.isUnlocked()) {1392          return { ok: false, error: "vault_locked" };1393        }1394        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1395      }1396      case "GET_IDENTITY_SUGGESTIONS": {1397        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1398        const entries = vault.getEntries();1399        const suggestions = buildIdentitySuggestions(entries);1400        return { ok: true, data: { suggestions } };1401      }1402      case "POPULATE_INLINE_VAULT": {1403        if (!isNativePlatform()) return { ok: false };1404        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1405        const entries = vault.getEntries();1406        await publishInMemoryVault(entries);1407        return { ok: true };1408      }1409      case "ML_INIT":1410        return { ok: true };14111412      case "ML_PREDICT_BATCH": {1413        // AUD-002: shape-validate before forwarding to the ML helper.1414        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1415        if (!Array.isArray(featuresArray)) {1416          return { ok: false, error: "invalid_payload" };1417        }1418        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1419      }14201421      // ── Vault sync (v3) ───────────────────────────────────────────────1422      // Returns the public-facing local identity needed by the popup to1423      // drive Phase-1 audio pairing. The private long-term key never1424      // leaves the background.1425      case "GET_LOCAL_IDENTITY": {1426        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1427        // Pro license from an already-Pro peer (at least one device must be Pro).1428        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1429        // Identity derives from the stable root key, not the password-derived1430        // key, so pairing survives a master-password change (SEV-2-B).1431        const masterKeyHex = vault.getRootKeyHex();1432        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1433        const masterKey = unhexBytes(masterKeyHex);1434        try {1435          const identity = await buildLocalIdentity(masterKey);1436          // If this device is Pro, advertise the signed license so the peer can1437          // activate it after SAS confirmation — pairing carries Pro across.1438          if (await isProUser()) {1439            const license = await getLicenseKey();1440            if (license) (identity as { license?: string }).license = license;1441          }1442          return { ok: true, data: identity };1443        } finally {1444          masterKey.fill(0);1445        }1446      }14471448      case "LIST_PAIRED_DEVICES": {1449        const devices = await listPairedDevicesV3();1450        return { ok: true, data: { devices } };1451      }14521453      case "RENAME_PAIRED_DEVICE": {1454        const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string };1455        if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") {1456          return { ok: false, error: "invalid_payload" };1457        }1458        await renamePairedDeviceV3(deviceId, name);1459        return { ok: true };1460      }14611462      case "UNPAIR_DEVICE": {1463        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1464        if (typeof deviceId !== "string" || !deviceId) {1465          return { ok: false, error: "invalid_payload" };1466        }1467        // Removing a device REVOKES it rather than just dropping the local1468        // row: a plain removal is undone the moment any other peer vouches it1469        // back through a manifest, which is exactly what the relay makes easy.1470        await revokeDeviceByIdV3(deviceId, await getOrCreateDeviceId());1471        // Sync against the remaining hosts — the unpaired device no longer1472        // matters but the next alarm tick is up to ten minutes away.1473        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1474        return { ok: true };1475      }14761477      case "RENAME_LOCAL_DEVICE": {1478        const { name } = (msg.payload ?? {}) as { name?: string };1479        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1480        await setDeviceNameV3(name);1481        return { ok: true };1482      }14831484      // ── Relay pairing ─────────────────────────────────────────────────────1485      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1486      // session runs in the background; the SAS and the terminal result reach1487      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1488      case "START_ADOPTION_SOURCE": {1489        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1490        if (isRelayAdoptionSourceInFlight()) {1491          return { ok: false, error: "adoption_source_in_progress" };1492        }1493        try {1494          return { ok: true, data: await startRelayAdoptionSource() };1495        } catch (error) {1496          return {1497            ok: false,1498            error: error instanceof Error ? error.message : "adoption_source_failed",1499          };1500        }1501      }15021503      // Onboarding receiver — empty extension shows a QR, phone scans and1504      // sends the vault. The popup supplies the local-only password here so1505      // the background can wrap the adopted root key at rest without ever1506      // asking the user to retype it.1507      case "START_ADOPTION_RECEIVER": {1508        if (isRelayAdoptionSourceInFlight()) {1509          return { ok: false, error: "adoption_receiver_in_progress" };1510        }1511        const password = (msg.payload as { password?: unknown } | undefined)?.password;1512        if (typeof password !== "string" || password.length === 0) {1513          return { ok: false, error: "invalid_payload" };1514        }1515        try {1516          return { ok: true, data: await startRelayAdoptionReceiver(password) };1517        } catch (error) {1518          return {1519            ok: false,1520            error: error instanceof Error ? error.message : "adoption_receiver_failed",1521          };1522        }1523      }15241525      // Popup→bg counterpart to ADOPTION_SOURCE_SAS (receiver flow).1526      // The receiver now auto-accepts the SAS (both sides derive it from the1527      // same Noise handshake hash, so the codes match by construction) so1528      // the popup never has a SAS screen to tap on. The id round-trips the1529      // same way so a stale late response can't approve the wrong session.1530      // Popup→bg counterpart for the source flow: Confirm/Cancel on the1531      // source's SAS screen.15321533      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1534      // on the source's SAS screen. The id round-trips the same way so a stale1535      // late response can't approve the wrong session.1536      case "SOURCE_SAS_DECISION": {1537        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1538        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1539          return { ok: false, error: "invalid_payload" };1540        }1541        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1542      }15431544      case "CANCEL_ADOPTION_SOURCE": {1545        cancelRelayAdoptionSource();1546        return { ok: true };1547      }15481549      case "TRIGGER_SYNC": {1550        const payload = (msg.payload ?? {}) as {1551          reason?: "vault_change" | "foreground" | "manual";1552          force?: boolean;1553        };1554        const reason = payload.reason ?? "foreground";15551556        void triggerSyncIfReachable({ reason, force: payload.force === true });1557        return { ok: true };1558      }15591560      case "GET_SYNC_STATE": {1561        return { ok: true, data: getSyncState() };1562      }15631564      case "GET_SYNC_SETTINGS": {1565        return { ok: true, data: await getSyncSettings() };1566      }15671568      case "SET_SYNC_SETTINGS": {1569        const payload = (msg.payload ?? {}) as {1570          mode?: unknown;1571          relayUrl?: unknown;1572        };1573        try {1574          // A custom relay URL implies private mode; Peach's own relay stays1575          // public. See setRelayUrl.1576          if (payload.relayUrl !== undefined) {1577            if (typeof payload.relayUrl !== "string") {1578              return { ok: false, error: "invalid_relay_url" };1579            }1580            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1581          }1582          if (payload.mode !== undefined) {1583            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1584              return { ok: false, error: "invalid_sync_mode" };1585            }1586            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1587          }1588          return { ok: true, data: await getSyncSettings() };1589        } catch (error) {1590          return {1591            ok: false,1592            error: error instanceof Error ? error.message : "invalid_relay_url",1593          };1594        }1595      }15961597      case "GET_SYNC_ALERTS": {1598        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1599        const alerts = await getPendingSyncAlerts();1600        // The popup reads on open and acknowledges with consume:true after1601        // rendering, so a popup crash between read and render doesn't lose1602        // the alerts.1603        if (consume) await clearPendingSyncAlerts();1604        return { ok: true, data: alerts };1605      }16061607      case "GET_PENDING_VOUCHED_DEVICES": {1608        return { ok: true, data: await listPendingVouchedDevices() };1609      }1610      case "CONFIRM_VOUCHED_DEVICE": {1611        const { deviceId } = msg.payload as { deviceId: string };1612        const pending = await getPendingVouchedDevice(deviceId);1613        if (!pending) return { ok: false, error: "not_pending" };1614        // Last gate before a vouched device becomes a sync peer. A queue entry1615        // can predate the revocation that names it, so revocation is re-checked1616        // here rather than trusted to have swept the queue.1617        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {1618          await removePendingVouchedDevice(deviceId);1619          return { ok: false, error: "device_revoked" };1620        }1621        await upsertPairedDeviceV3({1622          deviceId: pending.deviceId,1623          deviceName: pending.deviceName,1624          deviceType:1625            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1626          longTermPublicKeyHex: pending.longTermPublicKeyHex,1627          signingPublicKeyHex: pending.signingPublicKeyHex,1628          wsPort: pending.wsPort,1629          pairedAt: pending.pairedAt,1630          trustSource: "vouched",1631        });1632        await removePendingVouchedDevice(deviceId);1633        // Newly confirmed vouched device is now a sync target — kick a round1634        // so the mesh introduction pays off without a 10-minute wait.1635        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1636        return { ok: true };1637      }1638      case "REJECT_VOUCHED_DEVICE": {1639        const { deviceId } = msg.payload as { deviceId: string };1640        await removePendingVouchedDevice(deviceId);1641        return { ok: true };1642      }1643      case "ROTATE_SYNC_IDENTITY": {1644        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1645        const result = await vault.rotateSyncIdentity();1646        return result.ok ? { ok: true } : { ok: false, error: result.error };1647      }16481649      default:1650        return { ok: false, error: "unknown_message_type" };1651    }1652  } catch (err) {1653    return {1654      ok: false,1655      error: err instanceof Error ? err.message : "operation_failed",1656    };1657  }1658}16591660// --- Mobile platform helpers ---16611662// Android: populates the in-memory vault used by PeachAutofillService.1663async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1664  const plugin = nativePlugin<{1665    setEntries?: (args: {1666      entries: Array<{1667        id: string;1668        title: string;1669        username: string;1670        email: string;1671        password: string;1672        url: string;1673        totp: string;1674        additionalUrls: string[];1675      }>;1676    }) => Promise<void>;1677  }>("InMemoryVaultPlugin");1678  if (!plugin?.setEntries) return;1679  await plugin.setEntries({1680    entries: entries.map((e) => ({1681      id: e.id,1682      title: e.title ?? "",1683      username: e.username ?? "",1684      email: (e as VaultEntry & { email?: string }).email ?? "",1685      password: e.password ?? "",1686      url: e.url ?? "",1687      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1688      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1689    })),1690  });1691}16921693// Android: clear the autofill in-memory store on lock.1694async function clearInMemoryVault(): Promise<void> {1695  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1696  if (!plugin?.clearEntries) return;1697  await plugin.clearEntries();1698}16991700// Returns username use-counts from the vault, sorted by frequency. Each row1701// also carries the entry's email so the popup can suggest the email/username1702// pair the user has actually used together.1703function buildIdentitySuggestions(1704  entries: VaultEntry[],1705): Array<{ email: string; username: string; count: number }> {1706  const usernameCounts = new Map<string, number>();1707  const usernameEmail = new Map<string, string>();1708  for (const entry of entries) {1709    const username = entry.username ?? "";1710    const email = (entry as VaultEntry & { email?: string }).email ?? "";1711    if (!username && !email) continue;1712    const key = username || email;1713    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1714    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1715  }1716  return Array.from(usernameCounts.entries())1717    .sort((a, b) => b[1] - a[1])1718    .map(([username, count]) => ({1719      email: usernameEmail.get(username) ?? "",1720      username,1721      count,1722    }));1723}17241725/** Notify all content scripts that the vault just became available. */1726function broadcastToContentScripts(message: { type: string }): void {1727  if (!chrome.tabs?.query) return;1728  chrome.tabs.query({}, (tabs) => {1729    for (const tab of tabs) {1730      if (tab.id !== undefined) {1731        chrome.tabs.sendMessage(tab.id, message).catch(() => {1732          // Tab may not have a content script — silently ignore1733        });1734      }1735    }1736  });1737}17381739function shouldRefreshAutoLock(type: MessageType): boolean {1740  return (1741    type !== "HAS_VAULT" &&1742    type !== "IS_UNLOCKED" &&1743    type !== "GET_VAULT_STATUS" &&1744    type !== "LOCK" &&1745    type !== "UPDATE_SETTINGS" &&1746    type !== "GET_PENDING_PASSKEY" &&1747    type !== "GET_PASSKEY_PROVIDER_STATE" &&1748    type !== "DECLINE_CARD_SAVE" &&1749    type !== "IS_CARD_DECLINED"1750  );1751}17521753function isAllowedCanaryWebhookUrl(value: string): boolean {1754  try {1755    const url = new URL(value);1756    if (url.protocol !== "https:") return false;17571758    const hostname = url.hostname.toLowerCase();1759    if (1760      hostname === "localhost" ||1761      hostname.endsWith(".localhost") ||1762      isPrivateIpv4(hostname) ||1763      isPrivateIpv6(hostname)1764    ) {1765      return false;1766    }17671768    return true;1769  } catch {1770    return false;1771  }1772}17731774function isPrivateIpv4(hostname: string): boolean {1775  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1776    return true;1777  }17781779  const octets = hostname.split(".").map((part) => Number(part));1780  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1781    return false;1782  }17831784  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1785}17861787function isPrivateIpv6(hostname: string): boolean {1788  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1789  // IPv4-mapped IPv6 literals embed a plain IPv4 address that the prefix1790  // list below can never match (WHATWG URL serializes [::ffff:192.168.0.1]1791  // as ::ffff:c0a8:1). Unwrap and test the embedded IPv4; unparseable mapped1792  // tails fail closed. (Codex Security 2026-08-04 LOW,1793  // ssrf.webhook-url-private-ip-filter.) DNS rebinding is out of scope for a1794  // one-shot host check.1795  const mapped = /^::ffff:(.+)$/.exec(normalized);1796  if (mapped) {1797    const tail = mapped[1] ?? "";1798    if (tail.includes(".")) return isPrivateIpv4(tail);1799    const parts = tail.split(":");1800    const [hi, lo] = parts;1801    if (1802      parts.length !== 2 ||1803      !hi ||1804      !lo ||1805      !/^[0-9a-f]{1,4}$/.test(hi) ||1806      !/^[0-9a-f]{1,4}$/.test(lo)1807    ) {1808      return true;1809    }1810    const octets = [1811      (Number.parseInt(hi, 16) >>> 8) & 0xff,1812      Number.parseInt(hi, 16) & 0xff,1813      (Number.parseInt(lo, 16) >>> 8) & 0xff,1814      Number.parseInt(lo, 16) & 0xff,1815    ];1816    return isPrivateIpv4(octets.join("."));1817  }1818  return (1819    normalized === "::1" ||1820    normalized.startsWith("fc") ||1821    normalized.startsWith("fd") ||1822    normalized.startsWith("fe80:")1823  );1824}