messages.ts

71.3 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 { computeVaultId } from "../shared/sync-identity";16import {17  getPendingVouchedDevice,18  listPendingVouchedDevices,19  removePendingVouchedDevice,20} from "./pending-vouched-devices";21import { isRecoveryConfirmPending } from "./recovery-pending";22import { setupAutoLock, touchAutoLock } from "./alarms";23import { runSelfTest } from "./self-test";24import * as vault from "./vault";25import {26  handleEstimateCodexPages,27  handleGetCodexVaultData,28  handleRestoreFromCodex,29} from "./codex-handlers";30import type { CodexRestorePayload } from "../shared/codex-types";31import {32  activateLicense,33  deactivateLicense,34  getLicenseInfo,35  getLicenseKey,36  isProUser,37  markCelebrationPlayed,38  shouldPlayCelebration,39} from "./license";40import {41  completeFirefoxPasskeyCreate,42  getPasskeyProviderState,43  getPendingPasskeyRequest,44  handleFirefoxPasskeyCreate,45  handleFirefoxPasskeyGet,46  handlePasskeyHasCredentials,47  initiateFirefoxPasskeyCreate,48  isPasskeyOfferDeclined,49  onVaultUnlocked,50  recordPasskeyOfferDecline,51  resolvePendingPasskeyRequest,52  setPasskeyProviderEnabled,53} from "./passkey";54import { buildAdvancedHealthReport } from "./health";55import { storageClear } from "../shared/storage";56import { findInvalidWords } from "../shared/recovery-words";57import type {58  Message,59  MessageResponse,60  MessageType,61  ProFeature,62  VaultEntry,63} from "../shared/types";64import { isPasskeyOnly } from "../shared/types";65import { generateTOTP } from "../crypto/totp";66import { isValidRpId } from "../shared/passkey-utils";67import { isNativePlatform, nativePlugin } from "../shared/native";68import { predictBatch as mlPredictBatch } from "./ml";69import type { MLFieldFeatures } from "../shared/ml";70import {71  buildLocalIdentity,72  getOrCreateDeviceId,73  setDeviceName as setDeviceNameV3,74} from "./device-identity";75import {76  isDeviceRevoked,77  listPairedDevices as listPairedDevicesV3,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  confirmRelayAdoptionSource,91  isRelayAdoptionSourceInFlight,92  startRelayAdoptionSource,93} from "./relay-adoption-source-bg";94import {95  getSyncSettings,96  setRelayUrl,97  setSyncMode,98  type SyncMode,99} from "./sync-settings";100import {101  getSyncState,102  hydratePersistedSyncState,103  setSyncRunner,104  triggerSyncIfReachable,105} from "./sync-trigger";106import { productionSyncRunner } from "./sync-runner";107108// Compile-time E2E flag, folded to a literal by Vite's `define` (false in109// every production build — verified in the bundled output). Mirrors the110// create-path bypass in passkey.ts so the Playwright passkey smoke can enable111// the provider without a real Pro licence; the gate is fully intact for users.112declare const __PEACH_E2E_PASSKEYS__: boolean;113const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true;114115let nativeSyncRunnerBootstrapped = false;116117function unhexBytes(hex: string): Uint8Array {118  if (hex.length % 2 !== 0) throw new Error("invalid hex");119  const out = new Uint8Array(hex.length / 2);120  for (let i = 0; i < out.length; i++) {121    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);122  }123  return out;124}125126/**127 * The single Pro gate. Every gated handler calls this first; the broadcast128 * lets the popup react (navigate to the License section, highlight the129 * relevant feature). Background never touches the popup view directly —130 * the popup owns navigation. See Projects.md "Pro gate rule".131 */132async function requirePro(133  feature: ProFeature,134  trigger: "user" | "background" = "user"135): Promise<{ allowed: boolean }> {136  if (PASSKEY_E2E_PRO_BYPASS && feature === "passkeys") return { allowed: true };137  if (await isProUser()) return { allowed: true };138139  if (trigger === "user") {140    // User deliberately triggered this feature — redirect the popup immediately.141    chrome.runtime142      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })143      .catch(() => {144        // Popup may be closed — the gate signal is best-effort.145      });146  } else {147    // Background trigger (e.g. passive sync initiation) — no popup is open.148    // Queue a notice so the next popup open shows a soft banner instead of149    // silently failing.150    if (chrome.storage.session) {151      chrome.storage.session152        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })153        .catch(() => {});154    }155  }156157  return { allowed: false };158}159160// ---------------------------------------------------------------------------161// PCH-01-018: operations that irreversibly destroy or replace vault contents.162// These are gated to trusted extension-page senders in handleMessage; the163// confirmation UX otherwise lives only in the popup. Keep this in sync when164// adding new destructive handlers.165const DESTRUCTIVE_MESSAGE_TYPES: ReadonlySet<string> = new Set([166  "DESTROY_VAULT",167  "CLEAR_VAULT_ENTRIES",168  "RESTORE_VAULT_SNAPSHOT",169  "RESTORE_FROM_CODEX",170]);171172// LV-3: minimum interval between non-test canary pings per webhook+entry.173const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour174175const PRIVATE_IPV4_RANGES = [176  { prefix: "10." },177  { prefix: "127." },178  { prefix: "169.254." },179  { prefix: "192.168." },180];181182export function setupMessageHandler(): void {183  chrome.runtime.onMessage.addListener(184    (msg: unknown, sender, sendResponse) => {185      if (!isMessage(msg)) {186        sendResponse({ ok: false, error: "invalid_message" });187        return true;188      }189      handleMessage(msg, sender)190        .then(sendResponse)191        .catch((err) =>192          sendResponse({193            ok: false,194            error: err instanceof Error ? err.message : String(err),195          })196        );197      return true;198    }199  );200201  // Android: the chrome shim queues sendMessage calls until this handler is202  // registered. Without this hookup, every message hangs on Capacitor builds.203  // eslint-disable-next-line @typescript-eslint/no-explicit-any204  const reg = (globalThis as any).__peachRegisterMessageHandler;205  if (typeof reg === "function") {206    reg(async (m: unknown) => {207      if (!isMessage(m)) return { ok: false, error: "invalid_message" };208      try {209        return await handleMessage(m);210      } catch (err) {211        return {212          ok: false,213          error: err instanceof Error ? err.message : String(err),214        };215      }216    });217  }218  if (isNativePlatform()) {219    void bootstrapNativeSyncRunner();220  }221}222223async function bootstrapNativeSyncRunner(): Promise<void> {224  if (nativeSyncRunnerBootstrapped) return;225  nativeSyncRunnerBootstrapped = true;226  try {227    setSyncRunner(productionSyncRunner);228    await hydratePersistedSyncState();229  } catch (err) {230    nativeSyncRunnerBootstrapped = false;231    console.warn("[Peach] failed to bootstrap native sync runner:", err);232  }233}234235function isMessage(m: unknown): m is Message {236  return typeof m === "object" && m !== null && "type" in m;237}238239/**240 * The browser-attested origin of the page that originated this message. A web241 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),242 * so every page-driven message arrives via the content-script relay and the243 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a244 * value the page cannot forge. This is the ONLY trustworthy origin for passkey245 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.246 */247function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {248  if (sender.origin) return sender.origin;249  if (sender.url) {250    try { return new URL(sender.url).origin; } catch { return undefined; }251  }252  return undefined;253}254255// Resolves once restoreFromSession() has run, so handlers see the correct256// post-restore unlock state. entry.ts registers this BEFORE the message257// handler so the onMessage listener is added synchronously at SW startup258// (MV3 requirement) while unlock-dependent handlers still wait for restore.259let restoreReady: Promise<void> = Promise.resolve();260261/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */262export function setRestoreReady(p: Promise<unknown>): void {263  restoreReady = p.then(() => undefined, () => undefined);264}265266export async function handleMessage(267  msg: Message,268  sender: Partial<chrome.runtime.MessageSender> = {}269): Promise<MessageResponse> {270  try {271    // Wait for session-restore to finish before reading any unlock/vault state.272    // On a cold SW start the popup's first message arrives while restore is273    // still in flight; without this gate IS_UNLOCKED would report locked (a274    // spurious lock screen) and the storage reads could race. The onMessage275    // listener itself is registered synchronously (entry.ts) so this gate, not276    // listener registration, is what absorbs the cold-start window.277    await restoreReady;278    // Validate sender — only allow messages from our extension pages/scripts.279    // `sender.id` is undefined for messages originating from extension UI280    // (popup/options), which is legitimate; reject only when it is defined281    // and does not match our extension id.282    if (283      sender.id !== undefined &&284      sender.id !== chrome.runtime.id285    ) {286      return { ok: false, error: "invalid_sender" };287    }288289    // PCH-01-018: irreversible operations must originate from a trusted extension290    // page (popup/options), never from a content script. The sender.id check above291    // only proves the message came from *our* extension — a content script injected292    // into an attacker page passes it. A single XSS-class bug in the injected UI293    // would otherwise escalate to vault destruction. Extension pages carry an294    // extension-origin sender.url; content scripts carry a page URL.295    if (DESTRUCTIVE_MESSAGE_TYPES.has(msg.type)) {296      const extensionOrigin = chrome.runtime.getURL("");297      if (!sender.url?.startsWith(extensionOrigin)) {298        return { ok: false, error: "invalid_sender" };299      }300    }301302    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {303      touchAutoLock();304    }305306    switch (msg.type) {307      case "CREATE_VAULT": {308        const { password } = msg.payload as { password: string };309        // Refuse to create a vault under an empty master password — the derived310        // key would be publicly known and the at-rest AES-GCM protection void311        // (audit HIGH; the CSV-import path previously passed ""). Length/strength312        // policy lives in the onboarding UI; this is the non-negotiable floor.313        if (typeof password !== "string" || password.length === 0) {314          return { ok: false, error: "invalid_payload" };315        }316        await vault.createVault(password);317        await setupAutoLock();318        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });319        onVaultUnlocked();320        return { ok: true };321      }322      case "CREATE_VAULT_FROM_ROOT_KEY": {323        const { password, rootKeyHex } = (msg.payload ?? {}) as {324          password?: unknown;325          rootKeyHex?: unknown;326        };327        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {328          return { ok: false, error: "invalid_payload" };329        }330331        try {332          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);333          await setupAutoLock();334          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });335          onVaultUnlocked();336          return { ok: true, vaultId };337        } catch (err) {338          return { ok: false, error: err instanceof Error ? err.message : String(err) };339        }340      }341      case "UNLOCK": {342        const { password } = msg.payload as { password: string };343        const ok = await vault.unlock(password);344        if (ok) {345          // KAT: verify the WebCrypto stack is healthy before the user relies on it.346          // Runs after unlock so latency is hidden behind the vault-load time.347          const kat = await runSelfTest();348          if (!kat.ok) {349            console.error("[Peach] Crypto self-test FAILED:", kat.error);350            await vault.lock();351            return { ok: false, error: "self_test_failed" };352          }353          await setupAutoLock();354          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });355          onVaultUnlocked();356          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());357          return { ok: true };358        }359        // Distinguish corruption from wrong password so the popup can offer360        // a history-restore path instead of falsely accusing the user of361        // mistyping (M7/COR-007).362        const failure = vault.consumeLastUnlockFailureReason();363        if (failure) {364          return {365            ok: false,366            error: "vault_corrupted",367            canRestoreFromHistory: true,368          } as MessageResponse;369        }370        return { ok: false };371      }372      case "VALIDATE_RECOVERY_WORDS": {373        const { words } = msg.payload as { words: string[] };374        const invalid = findInvalidWords(words);375        return { ok: true, data: { valid: invalid.length === 0, invalid } };376      }377      case "GET_RECOVERY_WORDS": {378        // Must be unlocked and have recovery set up (vault must be v2.12+).379        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };380        // LV-4: the recovery words re-derive the ROOT KEY — the highest-381        // value secret in the vault. A session unlock (which may be hours382        // old on a shared machine) is not enough; require a fresh password383        // proof, matching the 1Password/Bitwarden pattern for revealing384        // escrow material. EXEMPTION: the create-vault / rotation confirmation385        // window (peach_recovery_pending) shows the words immediately after386        // the user authenticated, and that confirmation UI has no password to387        // resend — skip the re-auth there only.388        if (!(await isRecoveryConfirmPending())) {389          const { password } = (msg.payload ?? {}) as { password?: string };390          if (typeof password !== "string" || !password) {391            return { ok: false, error: "password_required" };392          }393          if (!(await vault.verifyMainPassword(password))) {394            return { ok: false, error: "wrong_password" };395          }396        }397        try {398          const words = await vault.getRecoveryWords();399          return { ok: true, data: words };400        } catch (e) {401          // pre-v2.12 vault that hasn't migrated402          return { ok: false, error: "recovery_not_setup" };403        }404      }405      case "RECOVER_WITH_WORDS": {406        // User has lost their password but has their 12 recovery words.407        // We: (1) validate the words, (2) re-encrypt vault with new password.408        const { words, newPassword } = msg.payload as {409          words: string[];410          newPassword: string;411        };412        const stored = await vault.loadSlotA();413        if (!stored) return { ok: false, error: "no_vault" };414        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {415          return { ok: false, error: "recovery_not_setup" };416        }417        // Unwrap the root key from the recovery escrow.418        try {419          await vault.unwrapRootKeyForRecovery(420            stored.recovery_wrapped_root_key,421            stored.recovery_nonce ?? "",422            stored.recovery_tag ?? "",423            stored.recovery_salt,424            words425          );426        } catch {427          return { ok: false, error: "invalid_recovery_words" };428        }429        // Re-key: derive fresh salt + key from new password.430        const newSalt = vault.generateSalt();431        const newKey = await vault.deriveKey(newPassword, newSalt);432        // Re-wrap root key under the new password's derived key so the same433        // recovery words continue to work after the password change.434        await vault.rewrapRootKeyForPassword(newKey, newSalt);435        // Re-encrypt vault entries with the new key.436        await vault.changePasswordWithNewKey(newSalt, newKey);437        await setupAutoLock();438        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });439        return { ok: true };440      }441      case "LOCK":442        vault.lock();443        if (isNativePlatform()) await clearInMemoryVault();444        return { ok: true };445      case "IS_UNLOCKED":446        return { ok: true, data: vault.isUnlocked() };447      case "GET_VAULT_STATUS":448        return { ok: true, unlocked: vault.isUnlocked() };449      case "HAS_VAULT":450        return { ok: true, data: await vault.hasVault() };451      case "GET_ENTRIES":452        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };453        return { ok: true, data: vault.getEntries() };454      case "ADD_ENTRY": {455        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };456        const payload = msg.payload;457        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {458          return { ok: false, error: "invalid_payload" };459        }460        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);461        return { ok: true, data: entry };462      }463      case "BATCH_ADD_ENTRIES": {464        const payload = msg.payload as { entries?: unknown } | null | undefined;465        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {466          return { ok: false, error: "invalid_payload" };467        }468        if (!Array.isArray(payload.entries)) {469          return { ok: false, error: "invalid_payload" };470        }471        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);472        return { ok: true, data: added };473      }474      case "RESTORE_ENTRIES": {475        const payload = msg.payload as476          | { entries?: unknown; mode?: unknown; settings?: unknown }477          | null478          | undefined;479        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {480          return { ok: false, error: "invalid_payload" };481        }482        if (!Array.isArray(payload.entries)) {483          return { ok: false, error: "invalid_payload" };484        }485        if (payload.mode !== "replace" && payload.mode !== "merge") {486          return { ok: false, error: "invalid_payload" };487        }488        const summary = await vault.restoreEntries(489          payload.entries as Parameters<typeof vault.restoreEntries>[0],490          payload.mode491        );492        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {493          await vault.updateSettings(payload.settings as vault.VaultSettings);494        }495        return { ok: true, data: summary };496      }497      case "CLEAR_VAULT_ENTRIES": {498        await vault.clearVaultEntries("REPLACE_ALL");499        return { ok: true };500      }501      case "GET_VAULT_HISTORY": {502        const snapshots = await vault.getVaultHistory();503        return { ok: true, data: snapshots };504      }505      case "RESTORE_VAULT_SNAPSHOT": {506        const { snapshotId } = msg.payload as { snapshotId: string };507        const result = await vault.restoreVaultSnapshot(snapshotId);508        if (!result.ok) return { ok: false, error: result.error };509        broadcastToContentScripts({ type: "VAULT_LOCKED" });510        return { ok: true };511      }512      case "COUNT_DUPLICATES": {513        return { ok: true, data: vault.countDuplicates() };514      }515      case "DEDUPLICATE_ENTRIES": {516        const removed = await vault.deduplicateEntries();517        return { ok: true, data: removed };518      }519      case "UPDATE_ENTRY": {520        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;521        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {522          return { ok: false, error: "invalid_payload" };523        }524        const { id, patch } = payload;525        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {526          return { ok: false, error: "invalid_payload" };527        }528        // Single enforcement point for the Canary Entries Pro gate. Only529        // gates the transition into a canary entry — clearing/disabling a530        // canary (`canary: undefined`) is always allowed, so existing531        // canary entries remain manageable.532        const incomingCanary = (patch as { canary?: unknown }).canary;533        if (incomingCanary && typeof incomingCanary === "object") {534          const existing = vault.getEntryById(id);535          if (!existing?.canary) {536            const gate = await requirePro("canary_entry");537            if (!gate.allowed) return { ok: false, error: "pro_required" };538          }539        }540        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);541        return { ok: true };542      }543      case "ADD_ADDITIONAL_URL": {544        const { id, url } = msg.payload as { id: string; url: string };545        const trimmed = typeof url === "string" ? url.trim() : "";546        if (!trimmed) return { ok: false, error: "url_required" };547        const existing = vault.getEntryById(id);548        if (!existing) return { ok: false, error: "entry_not_found" };549        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };550        const merged = [...(existing.additionalUrls ?? []), trimmed];551        await vault.updateEntry(id, { additionalUrls: merged });552        return { ok: true };553      }554      case "DELETE_ENTRY": {555        const { id } = msg.payload as { id: string };556        await vault.deleteEntry(id);557        return { ok: true };558      }559      case "GET_DELETED_ENTRIES":560        return { ok: true, data: vault.getDeletedEntries() };561      case "RESTORE_ENTRY": {562        const { id } = msg.payload as { id: string };563        await vault.restoreEntry(id);564        return { ok: true };565      }566      case "PURGE_ENTRY": {567        const { id } = msg.payload as { id: string };568        await vault.purgeEntry(id);569        return { ok: true };570      }571      case "PURGE_EXPIRED_TRASH": {572        const { retentionMs } = msg.payload as { retentionMs: number };573        const purged = await vault.purgeExpiredTrash(retentionMs);574        return { ok: true, data: purged };575      }576      case "SAVE_NOTE": {577        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };578        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };579        const now = Date.now();580        if (id) {581          const existing = vault.getEntryById(id);582          if (!existing) return { ok: false, error: "not_found" };583          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });584          return { ok: true, data: vault.getEntryById(id) };585        } else {586          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt587          // (EntryDraft omits both), so passing them was the only reason the588          // `as any` cast existed. Dropping them makes the call type-check.589          const entry = await vault.addEntry({590            type: "note",591            title: title || "Untitled",592            notes: body,593          });594          return { ok: true, data: entry };595        }596      }597      case "DELETE_NOTE": {598        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };599        const { id } = msg.payload as { id: string };600        await vault.deleteEntry(id);601        return { ok: true };602      }603      case "GET_NOTES": {604        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };605        const notes = vault.getEntries().filter(606          (e) => e.type === "note" && !e.deletedAt607        );608        return { ok: true, data: notes } as MessageResponse;609      }610      case "SEARCH_VAULT": {611        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };612        // AUD-002: shape-validate the payload before calling string methods.613        // A raw cast lets a malformed message crash the handler with TypeError.614        const { query } = (msg.payload ?? {}) as { query?: unknown };615        if (typeof query !== "string") {616          return { ok: false, error: "invalid_payload" };617        }618        const q = query.toLowerCase();619        const searchResults = vault.getEntries().filter(620          (e) =>621            !e.deletedAt &&622            (e.title.toLowerCase().includes(q) ||623              e.notes?.toLowerCase().includes(q) ||624              e.username?.toLowerCase().includes(q))625        );626        return { ok: true, data: searchResults } as MessageResponse;627      }628      case "AUTOFILL_QUERY": {629        if (!vault.isUnlocked()) {630          return { ok: false, error: "vault_locked" };631        }632        let { includeAll } = msg.payload as { includeAll?: boolean };633        const { domain, kind, userGesture } = msg.payload as {634          domain: string;635          kind?: "login" | "card" | "totp";636          userGesture?: boolean;637        };638        // MV-2: the vault-wide inventory (every title/username/email/url)639        // may only leave the background on an explicit user gesture — the640        // user opening the search affordance — never on passive form focus.641        // userGesture is self-declared by our own content script; the value642        // of this gate is that PASSIVE code paths (which never set it)643        // cannot ship the inventory, shrinking what a compromised page that644        // merely triggers focus events can observe.645        if (includeAll && userGesture !== true) {646          includeAll = false;647        }648        // kind="card": return saved cards as compact summaries for the649        // inline card silver platter. Cards are not domain-scoped — every650        // saved card is a candidate on every checkout page — so domain is651        // ignored when kind === "card".652        if (kind === "card") {653          const cards = vault.getEntries().filter((e) => e.type === "card");654          return {655            ok: true,656            data: cards.map((e) => ({657              id: e.id,658              title: e.cardNickname || e.title,659              cardholderName: e.cardholderName,660              last4: e.last4,661              expMonth: e.expMonth,662              expYear: e.expYear,663              network: e.network,664            })),665          };666        }667        if (kind === "totp") {668          const matches = (669            includeAll670              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")671              : vault.queryDomain(domain)672          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));673          return {674            ok: true,675            data: matches.map((e) => ({676              id: e.id,677              title: e.title,678              username: e.username,679              email: e.email,680              url: e.url,681              hasTotp: true,682            })),683          };684        }685        // The inline selector fills username+password into a form. Passkey-686        // only entries have no password to fill; sign-in for those goes687        // through the WebAuthn path instead. Filter them out everywhere so688        // the user doesn't see four "GitHub" rows that mostly do nothing.689        // Notes and cards never belonged here either.690        const matches = (691          includeAll692            ? vault693                .getEntries()694                .filter((entry) => entry.type !== "note" && entry.type !== "card")695            : vault.queryDomain(domain)696        ).filter((entry) => !isPasskeyOnly(entry));697        return {698          ok: true,699          data: matches.map((e) =>700            includeAll701              ? {702                  id: e.id,703                  title: e.title,704                  // username/email/url shipped so the inline popup's search705                  // affordance can match on them, not just titles. No secrets706                  // cross the boundary — same shape as the domain-matched707                  // response below minus hasTotp (which the search list708                  // doesn't surface).709                  username: e.username,710                  email: e.email,711                  url: e.url,712                  hasPasskey: e.passkey !== undefined,713                }714              : {715                  id: e.id,716                  title: e.title,717                  username: e.username,718                  email: e.email,719                  url: e.url,720                  hasTotp: Boolean(e.totp),721                  hasPasskey: e.passkey !== undefined,722                }723          ),724        };725      }726      case "GET_ENTRY_FOR_FILL": {727        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };728        const { id, explicitSummon } = msg.payload as {729          id: string;730          explicitSummon?: boolean;731        };732        const entry = vault.getEntryById(id);733        if (!entry) return { ok: false, error: "entry_not_found" };734        // Passkey-only entries (passkey credential, no password) cannot be735        // filled into a form — sign-in goes through the WebAuthn path. A736        // login that ALSO has a passkey is still fillable for its password.737        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };738739        // MV-1: re-validate the entry against the requesting tab's origin.740        // sender.tab.url is browser-attested — a page cannot forge it. When741        // the request does not come from a tab at all (popup surfaces use742        // GET_ENTRY_FOR_EDIT, not this), refuse.743        if (sender.tab !== undefined || sender.url !== undefined) {744          let senderDomain: string | null = null;745          try {746            const rawUrl = sender.tab?.url ?? sender.url ?? "";747            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;748          } catch {749            senderDomain = null;750          }751          if (!senderDomain) return { ok: false, error: "origin_unverified" };752753          const entryDomains = new Set<string>();754          const primary = extractDomain(entry.url ?? "");755          if (primary) entryDomains.add(primary);756          for (const extra of entry.additionalUrls ?? []) {757            const d = extractDomain(extra);758            if (d) entryDomains.add(d);759          }760761          // explicitSummon=true means the user actively picked this entry762          // from the cross-domain search affordance — an intentional763          // off-domain fill. Passive fill paths must stay domain-bound.764          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {765            // Domain mismatch — refuse silently (no oracle about which ids exist).766            return { ok: false, error: "entry_not_found" };767          }768        }769        // Strip the passkey credential AND the raw base32 TOTP seed from the770        // response. Content scripts never need either: the private key is the771        // authenticator's, and handing over the TOTP seed would let a772        // compromised content script mint valid codes indefinitely (SEV-3-C).773        // Generate the *current* 6-digit code here in the background and send774        // only that, plus the seconds left so the UI can render a countdown.775        // Also drop passwordHistory: filling needs only the *current* password.776        // Handing every past password to a content script during passive777        // autofill on an arbitrary page would widen the blast radius of a778        // compromised page far beyond the one credential being filled.779        const {780          passkey: _strippedPasskey,781          totp: seed,782          totpAlgorithm,783          totpDigits,784          totpPeriod,785          passwordHistory: _ph,786          ...safeEntry787        } = entry;788        let totpCode: string | undefined;789        let totpRemaining: number | undefined;790        if (seed) {791          try {792            // PCH-01-019: honour stored algorithm/digits/period (defaults apply793            // when these are undefined, i.e. legacy bare-seed entries).794            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);795            totpCode = generated.code;796            totpRemaining = generated.remaining;797          } catch {798            totpCode = undefined;799          }800        }801        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };802      }803      // Trusted full-entry fetch for Peach's own inline-popup surfaces that804      // genuinely need the raw TOTP seed: the edit form (which re-saves the805      // seed and would otherwise wipe it) and nothing else. Unlike806      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside807      // the inline popup, never during passive autofill on an arbitrary page.808      // The passkey credential is still stripped — the edit form never touches it.809      case "GET_ENTRY_FOR_EDIT": {810        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };811        const { id, explicitSummon } = msg.payload as {812          id: string;813          explicitSummon?: boolean;814        };815        const entry = vault.getEntryById(id);816        if (!entry) return { ok: false, error: "entry_not_found" };817818        // PCH-01-006: re-validate the browser-attested sender origin, mirroring819        // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and820        // full password history — at least as sensitive as the fill response — so821        // the boundary must be enforced here, not only by UI reachability. Today822        // the sole caller is the popup (no sender.tab, so this is a structural823        // no-op), but a future tab-context caller or an id leak would otherwise824        // inherit a full-credential oracle. Unlike the fill path we SKIP (not825        // refuse) when no sender domain resolves, to keep the popup caller working.826        if (sender.tab !== undefined || sender.url !== undefined) {827          let senderDomain: string | null = null;828          try {829            const rawUrl = sender.tab?.url ?? sender.url ?? "";830            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;831          } catch {832            senderDomain = null;833          }834          if (senderDomain) {835            const entryDomains = new Set<string>();836            const primary = extractDomain(entry.url ?? "");837            if (primary) entryDomains.add(primary);838            for (const extra of entry.additionalUrls ?? []) {839              const d = extractDomain(extra);840              if (d) entryDomains.add(d);841            }842            if (explicitSummon !== true && !entryDomains.has(senderDomain)) {843              return { ok: false, error: "entry_not_found" }; // no id oracle844            }845          }846        }847848        const { passkey: _passkey, ...safeEntry } = entry;849        return { ok: true, data: safeEntry };850      }851      case "COPY": {852        // AUD-002: shape-validate the payload before passing to the clipboard853        // helper. A raw cast lets a malformed message reach the clipboard API854        // with a non-string and throw.855        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {856          text?: unknown;857          label?: unknown;858          alreadyWritten?: unknown;859        };860        if (typeof text !== "string" || typeof label !== "string") {861          return { ok: false, error: "invalid_payload" };862        }863        await copyToClipboard(text, label, Boolean(alreadyWritten));864        return { ok: true, clearSeconds: getEffectiveClearSeconds() };865      }866      case "CHECK_ALL_BREACHES": {867        const allEntries = vault.getEntries();868        const results: Record<string, number> = {};869        for (const entry of allEntries) {870          if (entry.type === "note") continue;871          if (!entry.password) continue;872          results[entry.id] = await vault.checkBreach(entry.password);873          // Small delay — be a good citizen to the HIBP API874          await new Promise((r) => setTimeout(r, 200));875        }876        // Persist any non-zero counts back to entries877        for (const [id, count] of Object.entries(results)) {878          const entry = vault.getEntryById(id);879          if (entry && (entry.breach ?? 0) !== count) {880            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });881          }882        }883        return { ok: true, data: results };884      }885      case "GET_SETTINGS":886        return { ok: true, data: await vault.ensureSettingsLoaded() };887      case "UPDATE_SETTINGS": {888        const patch = msg.payload;889        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {890          return { ok: false, error: "invalid_payload" };891        }892        await vault.updateSettings(patch as vault.VaultSettings);893        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {894          await setupAutoLock();895          if (vault.isUnlocked()) touchAutoLock();896        }897        return { ok: true };898      }899      case "GET_PENDING_PASSKEY":900        return { ok: true, data: await getPendingPasskeyRequest() };901      case "APPROVE_PASSKEY": {902        const { requestId } = msg.payload as { requestId: number };903        await resolvePendingPasskeyRequest(requestId, true);904        return { ok: true };905      }906      case "DENY_PASSKEY": {907        const { requestId } = msg.payload as { requestId: number };908        await resolvePendingPasskeyRequest(requestId, false);909        return { ok: true };910      }911      case "GET_PASSKEY_PROVIDER_STATE":912        return { ok: true, data: await getPasskeyProviderState() };913      case "SET_PASSKEY_PROVIDER_ENABLED": {914        const { enabled } = msg.payload as { enabled: boolean };915        // Disabling is always free; gating fires only when a free user is916        // trying to turn passkey interception on.917        if (enabled) {918          const gate = await requirePro("passkeys");919          if (!gate.allowed) return { ok: false, error: "pro_required" };920        }921        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };922      }923      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS924      // endpoint. Intentional product behavior — users configure their own925      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private926      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-927      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to928      // users that the entry title leaves the device when the canary fires.929      case "FIRE_CANARY_PING": {930        // Canary alert fires unconditionally for any entry with canary: true.931        // The Pro gate only governs creation/flagging of canary entries; once932        // an entry is flagged, the alert path is a security property and must933        // never be license-gated.934        const { webhookUrl, entryTitle, trigger } = msg.payload as {935          webhookUrl: string;936          entryTitle: string;937          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";938        };939        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {940          return { ok: false, error: "invalid_webhook_url" };941        }942        // LV-3: debounce non-test pings per (webhook, entry) so a page that943        // strobes focus/fill events can't turn the canary into a request944        // firehose at the user's endpoint. Test pings are exempt — they are945        // explicit user clicks in the settings UI and are awaited for946        // feedback. The FIRST ping in a window always goes out, so the947        // dead-man's-switch property (canary fires on access) is preserved;948        // only repeats within the window are coalesced.949        if (trigger !== "test") {950          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;951          const stored = await chrome.storage.local.get(rlKey);952          const last = (stored as Record<string, unknown>)[rlKey];953          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {954            return { ok: true, data: { rateLimited: true } };955          }956          await chrome.storage.local.set({ [rlKey]: Date.now() });957        }958        const body = JSON.stringify({959          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",960          entry: entryTitle,961          trigger,962          timestamp: new Date().toISOString(),963          source: "peach-extension",964        });965        if (trigger === "test") {966          // Permitted outbound fetch: user-configured canary alert endpoint967          // (validated by isAllowedCanaryWebhookUrl above). This is the968          // only non-HIBP outbound call in the extension — see969          // Projects.md §3.7. Test pings are awaited so the UI can show970          // success/failure.971          try {972            const res = await fetch(webhookUrl, {973              method: "POST",974              headers: { "Content-Type": "application/json" },975              body,976            });977            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };978          } catch (err) {979            return { ok: false, error: err instanceof Error ? err.message : "network_error" };980          }981        }982        // Non-test triggers are fire-and-forget983        fetch(webhookUrl, {984          method: "POST",985          headers: { "Content-Type": "application/json" },986          body,987        }).catch(() => {});988        return { ok: true };989      }990      case "ACTIVATE_LICENSE": {991        const { key } = msg.payload as { key: string };992        const licenseInfo = await activateLicense(key);993        return { ok: true, data: licenseInfo };994      }995      case "GET_LICENSE": {996        const licenseInfo = await getLicenseInfo();997        return { ok: true, data: licenseInfo };998      }999      case "GET_LICENSE_KEY": {1000        const key = await getLicenseKey();1001        return { ok: true, data: key };1002      }1003      case "DEACTIVATE_LICENSE": {1004        await deactivateLicense();1005        return { ok: true };1006      }1007      case "SHOULD_PLAY_CELEBRATION": {1008        const should = await shouldPlayCelebration();1009        return { ok: true, data: should };1010      }1011      case "MARK_CELEBRATION_PLAYED": {1012        await markCelebrationPlayed();1013        return { ok: true };1014      }1015      case "GET_CODEX_VAULT_DATA": {1016        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1017        // popup navigates to the License section without further coordination.1018        const gate = await requirePro("codex");1019        if (!gate.allowed) return { ok: false, error: "pro_required" };1020        return await handleGetCodexVaultData();1021      }1022      case "ESTIMATE_CODEX_PAGES": {1023        const gate = await requirePro("codex");1024        if (!gate.allowed) return { ok: false, error: "pro_required" };1025        return await handleEstimateCodexPages();1026      }1027      case "RESTORE_FROM_CODEX": {1028        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1029        // be able to restore a vault that was printed by a Pro user.1030        // DO NOT add a Pro gate here.1031        const payload = msg.payload as CodexRestorePayload;1032        return await handleRestoreFromCodex(payload);1033      }1034      case "OPEN_PRO_GATE": {1035        // Content script requests: open popup and navigate to License section.1036        const { feature } = (msg.payload ?? {}) as { feature?: string };1037        if (chrome.storage.session) {1038          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1039        }1040        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1041        return { ok: true };1042      }1043      case "OPEN_POPUP": {1044        // Content script asks to open the trusted extension popup — used by the1045        // inline locked bubble so the master password is entered in the popup,1046        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1047        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1048        // toolbar icon. The badge already signals Peach needs attention.1049        //1050        // Set a session flag so the popup knows it was opened for inline unlock1051        // and should close itself once the vault is unlocked (returning the user1052        // to the inline autofill selector on the page).1053        if (chrome.storage.session) {1054          await chrome.storage.session.set({ peach_inline_unlock: true });1055        }1056        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1057        return { ok: true };1058      }1059      case "GET_IDENTITIES": {1060        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1061        return { ok: true, data: vault.getIdentities() };1062      }1063      case "TOUCH_AUTO_LOCK": {1064        // touchAutoLock() is already called by shouldRefreshAutoLock above;1065        // this case just gives the popup a typed message to keep the session alive.1066        return { ok: true };1067      }1068      case "GET_ADVANCED_HEALTH_REPORT": {1069        const gate = await requirePro("advanced_health");1070        if (!gate.allowed) return { ok: false, error: "pro_required" };1071        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1072        const report = await buildAdvancedHealthReport(vault.getEntries());1073        return { ok: true, data: report };1074      }1075      case "IS_DURESS_ENABLED": {1076        const enabled = await vault.isDuressEnabled();1077        return { ok: true, data: enabled };1078      }1079      case "SETUP_DURESS": {1080        // Single enforcement point for the Duress Vault Pro gate. Free users1081        // who somehow reach this handler are rejected here; the popup also1082        // pre-checks isPro() to avoid showing the setup form to free users,1083        // but server-side is the actual security boundary.1084        const gate = await requirePro("duress_vault");1085        if (!gate.allowed) return { ok: false, error: "pro_required" };1086        // MV3 service workers restart after inactivity, losing the in-memory1087        // derived key. Detect this before calling setupDuress so the popup1088        // can show a meaningful prompt to re-lock and re-unlock.1089        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1090        const { duressPassword } = msg.payload as { duressPassword: string };1091        await vault.setupDuress(duressPassword);1092        return { ok: true };1093      }1094      case "DISABLE_DURESS": {1095        await vault.disableDuress();1096        return { ok: true };1097      }1098      case "VERIFY_MAIN_PASSWORD": {1099        const { password } = msg.payload as { password: string };1100        const ok = await vault.verifyMainPassword(password);1101        return { ok: true, data: ok };1102      }1103      case "CHANGE_PASSWORD": {1104        const { currentPassword, newPassword } = msg.payload as {1105          currentPassword: string;1106          newPassword: string;1107        };1108        const changed = await vault.changePassword(currentPassword, newPassword);1109        return changed1110          ? { ok: true }1111          : { ok: false, error: "incorrect_current_password" };1112      }1113      case "GET_SITE_PASSWORD_POLICY": {1114        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1115        if (!tab?.id) return { ok: true, data: null };1116        try {1117          const response = await chrome.tabs.sendMessage(tab.id, {1118            type: "GET_SITE_PASSWORD_POLICY",1119          });1120          return (response as MessageResponse) ?? { ok: true, data: null };1121        } catch {1122          return { ok: true, data: null };1123        }1124      }1125      case "RECORD_MANUAL_SUMMON": {1126        const { domain } = msg.payload as { domain: string };1127        const settings = vault.getSettings();1128        const existing = settings.manualSummonDomains?.[domain];1129        const now = Date.now();1130        await vault.updateSettings({1131          manualSummonDomains: {1132            ...settings.manualSummonDomains,1133            [domain]: {1134              firstSummonedAt: existing?.firstSummonedAt ?? now,1135              summonCount: (existing?.summonCount ?? 0) + 1,1136              lastSummonedAt: now,1137            },1138          },1139        });1140        return { ok: true };1141      }1142      case "DECLINE_CARD_SAVE": {1143        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1144        await vault.declineCardSaveOffer(last4, expMonth, expYear);1145        return { ok: true };1146      }1147      case "IS_CARD_DECLINED": {1148        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1149        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1150        return { ok: true, data: declined };1151      }1152      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1153        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1154          rpId?: string;1155          rpName?: string;1156          userName?: string;1157          userDisplayName?: string;1158        };1159        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1160        return await initiateFirefoxPasskeyCreate({1161          rpId,1162          rpName: rpName ?? rpId,1163          userName,1164          userDisplayName,1165        });1166      }11671168      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1169        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1170        if (!payload) return { ok: false, error: "missing_payload" };1171        return await completeFirefoxPasskeyCreate(payload);1172      }11731174      case "PASSKEY_OFFER_DECLINE": {1175        const { domain } = (msg.payload ?? {}) as { domain?: string };1176        if (!domain) return { ok: false, error: "domain_required" };1177        await recordPasskeyOfferDecline(domain);1178        return { ok: true };1179      }11801181      case "GET_PASSKEY_OFFER_DECLINED": {1182        const { domain } = (msg.payload ?? {}) as { domain?: string };1183        if (!domain) return { ok: false, error: "domain_required" };1184        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1185      }11861187      case "PASSKEY_HAS_CREDENTIALS": {1188        const payload = msg.payload as {1189          rpId?: string;1190          allowCredentials?: Array<{ id: string; type?: string }>;1191        } | undefined;1192        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1193        return await handlePasskeyHasCredentials({1194          rpId: payload.rpId,1195          allowCredentials: payload.allowCredentials ?? [],1196        }, attestedSenderOrigin(sender));1197      }11981199      case "PASSKEY_CREATE": {1200        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1201        if (!payload?.rpId || !payload?.userName) {1202          return { ok: false, error: "rpid_and_username_required" };1203        }1204        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1205      }12061207      case "PASSKEY_GET": {1208        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1209        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1210        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1211      }12121213      case "PASSKEY_AUTH_RESPONSE": {1214        const { requestId, approved } = (msg.payload ?? {}) as {1215          requestId?: string | number;1216          approved?: boolean;1217        };1218        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1219          return { ok: false, error: 'requestId and approved required' };1220        }1221        await resolvePendingPasskeyRequest(Number(requestId), approved);1222        return { ok: true };1223      }12241225      case "GET_PASSKEY_FOR_DOMAIN": {1226        const { domain } = (msg.payload ?? {}) as { domain?: string };1227        if (!domain) return { ok: false, error: "domain_required" };1228        // Scope to the caller's own origin: a page may only ask about passkeys1229        // for a domain it actually owns, so an arbitrary page cannot enumerate1230        // which sites the user holds passkeys for or read the username (audit MEDIUM).1231        const origin = attestedSenderOrigin(sender);1232        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1233        if (!vault.isUnlocked()) return { ok: true, data: null };1234        const match = vault1235          .getEntries()1236          .find((entry) => entry.passkey?.rpId === domain);1237        if (!match || !match.passkey) return { ok: true, data: null };1238        // Slim shape — only the fields State 11 needs. Never expose private1239        // key material, even though this is locked behind isUnlocked.1240        return {1241          ok: true,1242          data: {1243            rpId: match.passkey.rpId,1244            userName: match.passkey.userName,1245            browser: match.passkey.browser,1246          },1247        };1248      }12491250      case "DESTROY_VAULT": {1251        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1252        // storage.local.clear() wipes every Peach key (slots, settings, license,1253        // onboarded flag, history, sync state, declined cards, recall, etc.);1254        // session.clear() wipes pending passkey requests + pro-notice queues.1255        // Caller (Panic.tsx) handles UI navigation back to onboarding.1256        //1257        // The Pro license is the one thing that must survive: the user paid for1258        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1259        // Capture it before the clear and restore it after. peach_pro_celebrated1260        // rides along so the Pro celebration doesn't replay on the next unlock.1261        const preserved = await chrome.storage.local.get([1262          "peach_license",1263          "peach_pro_celebrated",1264        ]);1265        vault.lock();1266        await storageClear();1267        await vault.clearVaultHistory();1268        const toRestore: Record<string, unknown> = {};1269        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1270        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1271        if (Object.keys(toRestore).length > 0) {1272          await chrome.storage.local.set(toRestore);1273        }1274        if (chrome.storage.session) {1275          await chrome.storage.session.clear();1276        }1277        return { ok: true };1278      }12791280      // Android-only: biometric unlock with pre-derived key.1281      case "UNLOCK_WITH_KEY": {1282        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1283        if (!isNativePlatform()) {1284          return { ok: false, error: "desktop_only_uses_password" };1285        }1286        try {1287          const result = await vault.unlockWithKey(masterKeyHex);1288          if (result.ok) {1289            onVaultUnlocked();1290            await publishInMemoryVault(result.entries);1291          }1292          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1293        } catch {1294          return { ok: false, error: "invalid_key" };1295        }1296      }1297      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1298      case "GET_DERIVED_KEY": {1299        if (!isNativePlatform()) {1300          return { ok: false, error: "android_only" };1301        }1302        if (!vault.isUnlocked()) {1303          return { ok: false, error: "vault_locked" };1304        }1305        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1306      }1307      case "GET_IDENTITY_SUGGESTIONS": {1308        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1309        const entries = vault.getEntries();1310        const suggestions = buildIdentitySuggestions(entries);1311        return { ok: true, data: { suggestions } };1312      }1313      case "POPULATE_INLINE_VAULT": {1314        if (!isNativePlatform()) return { ok: false };1315        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1316        const entries = vault.getEntries();1317        await publishInMemoryVault(entries);1318        return { ok: true };1319      }1320      case "ML_INIT":1321        return { ok: true };13221323      case "ML_PREDICT_BATCH": {1324        // AUD-002: shape-validate before forwarding to the ML helper.1325        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1326        if (!Array.isArray(featuresArray)) {1327          return { ok: false, error: "invalid_payload" };1328        }1329        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1330      }13311332      // ── Vault sync (v3) ───────────────────────────────────────────────1333      // Returns the public-facing local identity needed by the popup to1334      // drive Phase-1 audio pairing. The private long-term key never1335      // leaves the background.1336      case "GET_LOCAL_IDENTITY": {1337        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1338        // Pro license from an already-Pro peer (at least one device must be Pro).1339        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1340        // Identity derives from the stable root key, not the password-derived1341        // key, so pairing survives a master-password change (SEV-2-B).1342        const masterKeyHex = vault.getRootKeyHex();1343        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1344        const masterKey = unhexBytes(masterKeyHex);1345        try {1346          const identity = await buildLocalIdentity(masterKey);1347          // If this device is Pro, advertise the signed license so the peer can1348          // activate it after SAS confirmation — pairing carries Pro across.1349          if (await isProUser()) {1350            const license = await getLicenseKey();1351            if (license) (identity as { license?: string }).license = license;1352          }1353          return { ok: true, data: identity };1354        } finally {1355          masterKey.fill(0);1356        }1357      }13581359      case "GET_ADOPTION_MATERIAL": {1360        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1361        const rootKeyHex = vault.getRootKeyHex();1362        if (!rootKeyHex) return { ok: false, error: "vault_locked" };1363        const rootKeyBytes = unhexBytes(rootKeyHex);1364        try {1365          const data: { rootKeyHex: string; vaultId: string; license?: string } = {1366            rootKeyHex,1367            vaultId: await computeVaultId(rootKeyBytes),1368          };1369          if (await isProUser()) {1370            const license = await getLicenseKey();1371            if (license) data.license = license;1372          }1373          return { ok: true, data };1374        } finally {1375          rootKeyBytes.fill(0);1376        }1377      }13781379      case "COMPLETE_PAIRING": {1380        // Not Pro-gated — see GET_LOCAL_IDENTITY.1381        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1382        const paired = (msg.payload as { paired?: unknown })?.paired;1383        if (typeof paired !== "object" || paired === null) {1384          return { ok: false, error: "invalid_payload" };1385        }1386        const candidate = paired as Record<string, unknown>;1387        if (1388          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1389          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1390          typeof candidate.deviceType !== "string" ||1391          typeof candidate.longTermPublicKeyHex !== "string" ||1392          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1393          (1394            candidate.signingPublicKeyHex !== undefined &&1395            (1396              typeof candidate.signingPublicKeyHex !== "string" ||1397              !/^[0-9a-f]{64}$/.test(candidate.signingPublicKeyHex)1398            )1399          ) ||1400          typeof candidate.pairedAt !== "number"1401        ) {1402          return { ok: false, error: "invalid_paired_device" };1403        }1404        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1405        // Newly paired device → kick a sync so it gets its first round1406        // without waiting for the next 10-minute alarm tick. Fire-and-forget;1407        // the in-flight guard handles overlap with any other trigger.1408        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1409        return { ok: true };1410      }14111412      case "LIST_PAIRED_DEVICES": {1413        const devices = await listPairedDevicesV3();1414        return { ok: true, data: { devices } };1415      }14161417      case "UNPAIR_DEVICE": {1418        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1419        if (typeof deviceId !== "string" || !deviceId) {1420          return { ok: false, error: "invalid_payload" };1421        }1422        // Removing a device REVOKES it rather than just dropping the local1423        // row: a plain removal is undone the moment any other peer vouches it1424        // back through a manifest, which is exactly what the relay makes easy.1425        await revokeDeviceByIdV3(deviceId, await getOrCreateDeviceId());1426        // Sync against the remaining hosts — the unpaired device no longer1427        // matters but the next alarm tick is up to ten minutes away.1428        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1429        return { ok: true };1430      }14311432      case "RENAME_LOCAL_DEVICE": {1433        const { name } = (msg.payload ?? {}) as { name?: string };1434        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1435        await setDeviceNameV3(name);1436        return { ok: true };1437      }14381439      // ── Relay pairing ─────────────────────────────────────────────────────1440      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1441      // session runs in the background; the SAS and the terminal result reach1442      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1443      case "START_ADOPTION_SOURCE": {1444        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1445        if (isRelayAdoptionSourceInFlight()) {1446          return { ok: false, error: "adoption_source_in_progress" };1447        }1448        try {1449          return { ok: true, data: await startRelayAdoptionSource() };1450        } catch (error) {1451          return {1452            ok: false,1453            error: error instanceof Error ? error.message : "adoption_source_failed",1454          };1455        }1456      }14571458      case "ADOPTION_SOURCE_CONFIRM": {1459        const { password, cancel } = (msg.payload ?? {}) as {1460          password?: unknown;1461          cancel?: unknown;1462        };1463        if (cancel === true) {1464          return {1465            ok: true,1466            data: await confirmRelayAdoptionSource(null),1467          };1468        }1469        if (typeof password !== "string" || password.length === 0) {1470          return { ok: false, error: "invalid_payload" };1471        }1472        return {1473          ok: true,1474          data: await confirmRelayAdoptionSource(password),1475        };1476      }14771478      case "CANCEL_ADOPTION_SOURCE": {1479        cancelRelayAdoptionSource();1480        return { ok: true };1481      }14821483      case "TRIGGER_SYNC": {1484        const payload = (msg.payload ?? {}) as {1485          reason?: "vault_change" | "foreground" | "manual";1486          force?: boolean;1487        };1488        const reason = payload.reason ?? "foreground";14891490        void triggerSyncIfReachable({ reason, force: payload.force === true });1491        return { ok: true };1492      }14931494      case "GET_SYNC_STATE": {1495        return { ok: true, data: getSyncState() };1496      }14971498      case "GET_SYNC_SETTINGS": {1499        return { ok: true, data: await getSyncSettings() };1500      }15011502      case "SET_SYNC_SETTINGS": {1503        const payload = (msg.payload ?? {}) as {1504          mode?: unknown;1505          relayUrl?: unknown;1506        };1507        try {1508          // A custom relay URL implies private mode; Peach's own relay stays1509          // public. See setRelayUrl.1510          if (payload.relayUrl !== undefined) {1511            if (typeof payload.relayUrl !== "string") {1512              return { ok: false, error: "invalid_relay_url" };1513            }1514            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1515          }1516          if (payload.mode !== undefined) {1517            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1518              return { ok: false, error: "invalid_sync_mode" };1519            }1520            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1521          }1522          return { ok: true, data: await getSyncSettings() };1523        } catch (error) {1524          return {1525            ok: false,1526            error: error instanceof Error ? error.message : "invalid_relay_url",1527          };1528        }1529      }15301531      case "GET_SYNC_ALERTS": {1532        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1533        const alerts = await getPendingSyncAlerts();1534        // The popup reads on open and acknowledges with consume:true after1535        // rendering, so a popup crash between read and render doesn't lose1536        // the alerts.1537        if (consume) await clearPendingSyncAlerts();1538        return { ok: true, data: alerts };1539      }15401541      case "GET_PENDING_VOUCHED_DEVICES": {1542        return { ok: true, data: await listPendingVouchedDevices() };1543      }1544      case "CONFIRM_VOUCHED_DEVICE": {1545        const { deviceId } = msg.payload as { deviceId: string };1546        const pending = await getPendingVouchedDevice(deviceId);1547        if (!pending) return { ok: false, error: "not_pending" };1548        // Last gate before a vouched device becomes a sync peer. A queue entry1549        // can predate the revocation that names it, so revocation is re-checked1550        // here rather than trusted to have swept the queue.1551        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {1552          await removePendingVouchedDevice(deviceId);1553          return { ok: false, error: "device_revoked" };1554        }1555        await upsertPairedDeviceV3({1556          deviceId: pending.deviceId,1557          deviceName: pending.deviceName,1558          deviceType:1559            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1560          longTermPublicKeyHex: pending.longTermPublicKeyHex,1561          signingPublicKeyHex: pending.signingPublicKeyHex,1562          wsPort: pending.wsPort,1563          pairedAt: pending.pairedAt,1564          trustSource: "vouched",1565        });1566        await removePendingVouchedDevice(deviceId);1567        // Newly confirmed vouched device is now a sync target — kick a round1568        // so the mesh introduction pays off without a 10-minute wait.1569        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1570        return { ok: true };1571      }1572      case "REJECT_VOUCHED_DEVICE": {1573        const { deviceId } = msg.payload as { deviceId: string };1574        await removePendingVouchedDevice(deviceId);1575        return { ok: true };1576      }1577      case "ROTATE_SYNC_IDENTITY": {1578        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1579        const result = await vault.rotateSyncIdentity();1580        return result.ok ? { ok: true } : { ok: false, error: result.error };1581      }15821583      default:1584        return { ok: false, error: "unknown_message_type" };1585    }1586  } catch (err) {1587    return {1588      ok: false,1589      error: err instanceof Error ? err.message : "operation_failed",1590    };1591  }1592}15931594// --- Mobile platform helpers ---15951596// Android: populates the in-memory vault used by PeachAutofillService.1597async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1598  const plugin = nativePlugin<{1599    setEntries?: (args: {1600      entries: Array<{1601        id: string;1602        title: string;1603        username: string;1604        email: string;1605        password: string;1606        url: string;1607        totp: string;1608        additionalUrls: string[];1609      }>;1610    }) => Promise<void>;1611  }>("InMemoryVaultPlugin");1612  if (!plugin?.setEntries) return;1613  await plugin.setEntries({1614    entries: entries.map((e) => ({1615      id: e.id,1616      title: e.title ?? "",1617      username: e.username ?? "",1618      email: (e as VaultEntry & { email?: string }).email ?? "",1619      password: e.password ?? "",1620      url: e.url ?? "",1621      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1622      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1623    })),1624  });1625}16261627// Android: clear the autofill in-memory store on lock.1628async function clearInMemoryVault(): Promise<void> {1629  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1630  if (!plugin?.clearEntries) return;1631  await plugin.clearEntries();1632}16331634// Returns username use-counts from the vault, sorted by frequency. Each row1635// also carries the entry's email so the popup can suggest the email/username1636// pair the user has actually used together.1637function buildIdentitySuggestions(1638  entries: VaultEntry[],1639): Array<{ email: string; username: string; count: number }> {1640  const usernameCounts = new Map<string, number>();1641  const usernameEmail = new Map<string, string>();1642  for (const entry of entries) {1643    const username = entry.username ?? "";1644    const email = (entry as VaultEntry & { email?: string }).email ?? "";1645    if (!username && !email) continue;1646    const key = username || email;1647    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1648    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1649  }1650  return Array.from(usernameCounts.entries())1651    .sort((a, b) => b[1] - a[1])1652    .map(([username, count]) => ({1653      email: usernameEmail.get(username) ?? "",1654      username,1655      count,1656    }));1657}16581659/** Notify all content scripts that the vault just became available. */1660function broadcastToContentScripts(message: { type: string }): void {1661  if (!chrome.tabs?.query) return;1662  chrome.tabs.query({}, (tabs) => {1663    for (const tab of tabs) {1664      if (tab.id !== undefined) {1665        chrome.tabs.sendMessage(tab.id, message).catch(() => {1666          // Tab may not have a content script — silently ignore1667        });1668      }1669    }1670  });1671}16721673function shouldRefreshAutoLock(type: MessageType): boolean {1674  return (1675    type !== "HAS_VAULT" &&1676    type !== "IS_UNLOCKED" &&1677    type !== "GET_VAULT_STATUS" &&1678    type !== "LOCK" &&1679    type !== "UPDATE_SETTINGS" &&1680    type !== "GET_PENDING_PASSKEY" &&1681    type !== "GET_PASSKEY_PROVIDER_STATE" &&1682    type !== "DECLINE_CARD_SAVE" &&1683    type !== "IS_CARD_DECLINED"1684  );1685}16861687function isAllowedCanaryWebhookUrl(value: string): boolean {1688  try {1689    const url = new URL(value);1690    if (url.protocol !== "https:") return false;16911692    const hostname = url.hostname.toLowerCase();1693    if (1694      hostname === "localhost" ||1695      hostname.endsWith(".localhost") ||1696      isPrivateIpv4(hostname) ||1697      isPrivateIpv6(hostname)1698    ) {1699      return false;1700    }17011702    return true;1703  } catch {1704    return false;1705  }1706}17071708function isPrivateIpv4(hostname: string): boolean {1709  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1710    return true;1711  }17121713  const octets = hostname.split(".").map((part) => Number(part));1714  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1715    return false;1716  }17171718  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1719}17201721function isPrivateIpv6(hostname: string): boolean {1722  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1723  return (1724    normalized === "::1" ||1725    normalized.startsWith("fc") ||1726    normalized.startsWith("fd") ||1727    normalized.startsWith("fe80:")1728  );1729}