messages.ts

71.7 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard, getEffectiveClearSeconds } from "./clipboard";13import { getPendingSyncAlerts, clearPendingSyncAlerts } from "./sync-alerts";14import { extractDomain } from "../shared/domain";15import {16  getPendingVouchedDevice,17  listPendingVouchedDevices,18  removePendingVouchedDevice,19} from "./pending-vouched-devices";20import {21  clearRecoveryConfirmPending,22  isRecoveryConfirmPending,23  setRecoveryConfirmPending,24} from "./recovery-pending";25import { setupAutoLock, touchAutoLock } from "./alarms";26import { runSelfTest } from "./self-test";27import * as vault from "./vault";28import {29  handleEstimateCodexPages,30  handleGetCodexVaultData,31  handleRestoreFromCodex,32} from "./codex-handlers";33import type { CodexRestorePayload } from "../shared/codex-types";34import {35  activateLicense,36  deactivateLicense,37  getLicenseInfo,38  getLicenseKey,39  isProUser,40  markCelebrationPlayed,41  shouldPlayCelebration,42} from "./license";43import {44  completeFirefoxPasskeyCreate,45  getPasskeyProviderState,46  getPendingPasskeyRequest,47  handleFirefoxPasskeyCreate,48  handleFirefoxPasskeyGet,49  handlePasskeyHasCredentials,50  initiateFirefoxPasskeyCreate,51  isPasskeyOfferDeclined,52  onVaultUnlocked,53  recordPasskeyOfferDecline,54  resolvePendingPasskeyRequest,55  setPasskeyProviderEnabled,56} from "./passkey";57import { buildAdvancedHealthReport } from "./health";58import { storageClear } from "../shared/storage";59import { findInvalidWords } from "../shared/recovery-words";60import type {61  Message,62  MessageResponse,63  MessageType,64  ProFeature,65  VaultEntry,66} from "../shared/types";67import { isPasskeyOnly } from "../shared/types";68import { generateTOTP } from "../crypto/totp";69import { isValidRpId } from "../shared/passkey-utils";70import { predictBatch as mlPredictBatch } from "./ml";71import type { MLFieldFeatures } from "../shared/ml";72import {73  buildLocalIdentity,74  getOrCreateDeviceId,75  setDeviceName as setDeviceNameV3,76} from "./device-identity";77import {78  isDeviceRevoked,79  listPairedDevices as listPairedDevicesV3,80  renamePairedDevice as renamePairedDeviceV3,81  revokeDeviceById as revokeDeviceByIdV3,82  upsertPairedDevice as upsertPairedDeviceV3,83} from "./paired-devices";84// Sync and pairing are imported statically, never with `await import()`.85// `import()` throws `TypeError: import() is disallowed on86// ServiceWorkerGlobalScope` at runtime in MV3, and Vite's preload helper87// reports the failure through `window.dispatchEvent`, which does not exist in88// a worker either — so the real reason was replaced by "window is not defined"89// and the pairing UI just stopped. scripts/check-sw-static-imports.mjs fails90// the build if a runtime import() reappears anywhere in the worker's graph.91import {92  cancelRelayAdoptionSource,93  isRelayAdoptionSourceInFlight,94  resolveSourceSasConfirmation,95  startRelayAdoptionReceiver,96  startRelayAdoptionSource,97} from "./relay-adoption-bg";98import {99  getSyncSettings,100  setRelayUrl,101  setSyncMode,102  type SyncMode,103} from "./sync-settings";104import {105  getSyncState,106  triggerSyncIfReachable,107} from "./sync-trigger";108import { getMessageContext } from "./message-policy";109110// Compile-time E2E flag, folded to a literal by Vite's `define` (false in111// every production build — verified in the bundled output). Mirrors the112// create-path bypass in passkey.ts so the Playwright passkey smoke can enable113// the provider without a real Pro licence; the gate is fully intact for users.114declare const __PEACH_E2E_PASSKEYS__: boolean;115const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true;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// LV-3: minimum interval between non-test canary pings per webhook+entry.161const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour162163const PRIVATE_IPV4_RANGES = [164  { prefix: "10." },165  { prefix: "127." },166  { prefix: "169.254." },167  { prefix: "192.168." },168];169170export function setupMessageHandler(): void {171  chrome.runtime.onMessage.addListener(172    (msg: unknown, sender, sendResponse) => {173      if (!isMessage(msg)) {174        sendResponse({ ok: false, error: "invalid_message" });175        return true;176      }177      handleMessage(msg, sender)178        .then(sendResponse)179        .catch((err) =>180          sendResponse({181            ok: false,182            error: err instanceof Error ? err.message : String(err),183          })184        );185      return true;186    }187  );188}189190function isMessage(m: unknown): m is Message {191  return typeof m === "object" && m !== null && "type" in m;192}193194/**195 * The browser-attested origin of the page that originated this message. A web196 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),197 * so every page-driven message arrives via the content-script relay and the198 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a199 * value the page cannot forge. This is the ONLY trustworthy origin for passkey200 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.201 */202function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {203  if (sender.origin) return sender.origin;204  if (sender.url) {205    try { return new URL(sender.url).origin; } catch { return undefined; }206  }207  return undefined;208}209210function isExtensionPageSender(sender: Partial<chrome.runtime.MessageSender>): boolean {211  // A missing URL is the sender shape used by extension UI in unit tests and212  // by some browser APIs. A real content-script sender has a browser-attested213  // page URL, so it cannot use this compatibility path.214  if (!sender.url) return true;215  try {216    return new URL(sender.url).origin === new URL(chrome.runtime.getURL("")).origin;217  } catch {218    return false;219  }220}221222function isPageSender(sender: Partial<chrome.runtime.MessageSender>): boolean {223  return Boolean(sender.url) && !isExtensionPageSender(sender);224}225226function isSenderAllowedForContext(227  context: ReturnType<typeof getMessageContext>,228  sender: Partial<chrome.runtime.MessageSender>,229): boolean {230  switch (context) {231    case "extension-page-only":232      return isExtensionPageSender(sender);233    case "content-script-allowed":234      return true;235    case "page-relay":236      return isPageSender(sender);237    case "background-internal":238    case undefined:239      return false;240  }241}242243// Resolves once restoreFromSession() has run, so handlers see the correct244// post-restore unlock state. entry.ts registers this BEFORE the message245// handler so the onMessage listener is added synchronously at SW startup246// (MV3 requirement) while unlock-dependent handlers still wait for restore.247let restoreReady: Promise<void> = Promise.resolve();248249/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */250export function setRestoreReady(p: Promise<unknown>): void {251  restoreReady = p.then(() => undefined, () => undefined);252}253254export async function handleMessage(255  msg: Message,256  sender: Partial<chrome.runtime.MessageSender> = {}257): Promise<MessageResponse> {258  try {259    // Wait for session-restore to finish before reading any unlock/vault state.260    // On a cold SW start the popup's first message arrives while restore is261    // still in flight; without this gate IS_UNLOCKED would report locked (a262    // spurious lock screen) and the storage reads could race. The onMessage263    // listener itself is registered synchronously (entry.ts) so this gate, not264    // listener registration, is what absorbs the cold-start window.265    await restoreReady;266    // Validate sender — only allow messages from our extension pages/scripts.267    // `sender.id` is undefined for messages originating from extension UI268    // (popup/options), which is legitimate; reject only when it is defined269    // and does not match our extension id.270    if (271      sender.id !== undefined &&272      sender.id !== chrome.runtime.id273    ) {274      return { ok: false, error: "invalid_sender" };275    }276277    // PB-26-016: sender authorization is an exhaustive policy, not a278    // hand-maintained privileged denylist. A missing/unknown policy entry or a279    // background-only message fails closed before any handler runs.280    const messageContext = getMessageContext(msg.type);281    if (!isSenderAllowedForContext(messageContext, sender)) {282      return { ok: false, error: "invalid_sender" };283    }284285    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {286      touchAutoLock();287    }288289    switch (msg.type) {290      case "CREATE_VAULT": {291        const { password } = msg.payload as { password: string };292        // Refuse to create a vault under an empty master password — the derived293        // key would be publicly known and the at-rest AES-GCM protection void294        // (audit HIGH; the CSV-import path previously passed ""). Length/strength295        // policy lives in the onboarding UI; this is the non-negotiable floor.296        if (typeof password !== "string" || password.length === 0) {297          return { ok: false, error: "invalid_payload" };298        }299        await vault.createVault(password);300        await setupAutoLock();301        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });302        onVaultUnlocked();303        return { ok: true };304      }305      case "CREATE_VAULT_FROM_ROOT_KEY": {306        const { password, rootKeyHex } = (msg.payload ?? {}) as {307          password?: unknown;308          rootKeyHex?: unknown;309        };310        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {311          return { ok: false, error: "invalid_payload" };312        }313314        try {315          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);316          await setupAutoLock();317          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });318          onVaultUnlocked();319          return { ok: true, vaultId };320        } catch (err) {321          return { ok: false, error: err instanceof Error ? err.message : String(err) };322        }323      }324      case "UNLOCK": {325        const { password } = msg.payload as { password: string };326        const ok = await vault.unlock(password);327        if (ok) {328          // KAT: verify the WebCrypto stack is healthy before the user relies on it.329          // Runs after unlock so latency is hidden behind the vault-load time.330          const kat = await runSelfTest();331          if (!kat.ok) {332            console.error("[Peach] Crypto self-test FAILED:", kat.error);333            await vault.lock();334            return { ok: false, error: "self_test_failed" };335          }336          await vault.updateSettings({ pinPreferred: false });337          await setupAutoLock();338          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });339          onVaultUnlocked();340          return { ok: true };341        }342        // Distinguish corruption from wrong password so the popup can offer343        // a history-restore path instead of falsely accusing the user of344        // mistyping (M7/COR-007).345        const failure = vault.consumeLastUnlockFailureReason();346        if (failure) {347          return {348            ok: false,349            error: "vault_corrupted",350            canRestoreFromHistory: true,351          } as MessageResponse;352        }353        return { ok: false };354      }355      case "UNLOCK_WITH_PIN": {356        const { pin } = (msg.payload ?? {}) as { pin?: unknown };357        if (typeof pin !== "string") return { ok: false, error: "invalid_payload" };358        const ok = await vault.unlockWithPin(pin);359        if (!ok) return { ok: false };360        const kat = await runSelfTest();361        if (!kat.ok) {362          await vault.lock();363          return { ok: false, error: "self_test_failed" };364        }365        await vault.updateSettings({ pinPreferred: true });366        await setupAutoLock();367        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });368        onVaultUnlocked();369        return { ok: true };370      }371      case "VALIDATE_RECOVERY_WORDS": {372        const { words } = msg.payload as { words: string[] };373        const invalid = findInvalidWords(words);374        return { ok: true, data: { valid: invalid.length === 0, invalid } };375      }376      case "GET_RECOVERY_WORDS": {377        // Must be unlocked and have recovery set up (vault must be v2.12+).378        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };379        // LV-4: the recovery words re-derive the ROOT KEY — the highest-380        // value secret in the vault. A session unlock (which may be hours381        // old on a shared machine) is not enough; require a fresh password382        // proof, matching the 1Password/Bitwarden pattern for revealing383        // escrow material. EXEMPTION: the create-vault / rotation confirmation384        // window (peach_recovery_pending) shows the words immediately after385        // the user authenticated, and that confirmation UI has no password to386        // resend — skip the re-auth there only.387        if (!(await isRecoveryConfirmPending())) {388          const { password } = (msg.payload ?? {}) as { password?: string };389          if (typeof password !== "string" || !password) {390            return { ok: false, error: "password_required" };391          }392          if (!(await vault.verifyMainPassword(password))) {393            return { ok: false, error: "wrong_password" };394          }395        }396        try {397          const words = await vault.getRecoveryWords();398          return { ok: true, data: words };399        } catch {400          return { ok: false, error: "recovery_not_setup" };401        }402      }403      case "GET_RECOVERY_CONFIRM_PENDING":404        return { ok: true, data: await isRecoveryConfirmPending() };405      case "SET_RECOVERY_CONFIRM_PENDING":406        await setRecoveryConfirmPending();407        return { ok: true };408      case "CLEAR_RECOVERY_CONFIRM_PENDING":409        await clearRecoveryConfirmPending();410        return { ok: true };411      case "RECOVER_WITH_WORDS": {412        // User has lost their password but has their 12 recovery words.413        // We: (1) validate the words, (2) re-encrypt vault with new password.414        const { words, newPassword } = msg.payload as {415          words: string[];416          newPassword: string;417        };418        const stored = await vault.loadSlotA();419        if (!stored) return { ok: false, error: "no_vault" };420        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {421          return { ok: false, error: "recovery_not_setup" };422        }423        // Unwrap the root key from the recovery escrow.424        try {425          await vault.unwrapRootKeyForRecovery(426            stored.recovery_wrapped_root_key,427            stored.recovery_nonce ?? "",428            stored.recovery_tag ?? "",429            stored.recovery_salt,430            words431          );432        } catch {433          return { ok: false, error: "invalid_recovery_words" };434        }435        // Re-key: derive fresh salt + key from new password.436        const newSalt = vault.generateSalt();437        const newKey = await vault.deriveKey(newPassword, newSalt);438        // Re-wrap root key under the new password's derived key so the same439        // recovery words continue to work after the password change.440        await vault.rewrapRootKeyForPassword(newKey, newSalt);441        // Re-encrypt vault entries with the new key.442        await vault.changePasswordWithNewKey(newSalt, newKey);443        await setupAutoLock();444        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });445        return { ok: true };446      }447      case "LOCK":448        vault.lock();449        return { ok: true };450      case "IS_UNLOCKED":451        return { ok: true, data: vault.isUnlocked() };452      case "GET_VAULT_STATUS":453        return { ok: true, unlocked: vault.isUnlocked() };454      case "HAS_VAULT":455        return { ok: true, data: await vault.hasVault() };456      case "GET_ENTRIES":457        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };458        return { ok: true, data: vault.getEntries() };459      case "ADD_ENTRY": {460        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };461        const payload = msg.payload;462        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {463          return { ok: false, error: "invalid_payload" };464        }465        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);466        return { ok: true, data: entry };467      }468      case "BATCH_ADD_ENTRIES": {469        const payload = msg.payload as { entries?: unknown } | null | undefined;470        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {471          return { ok: false, error: "invalid_payload" };472        }473        if (!Array.isArray(payload.entries)) {474          return { ok: false, error: "invalid_payload" };475        }476        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);477        return { ok: true, data: added };478      }479      case "RESTORE_ENTRIES": {480        const payload = msg.payload as481          | { entries?: unknown; mode?: unknown; settings?: unknown }482          | null483          | undefined;484        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {485          return { ok: false, error: "invalid_payload" };486        }487        if (!Array.isArray(payload.entries)) {488          return { ok: false, error: "invalid_payload" };489        }490        if (payload.mode !== "replace" && payload.mode !== "merge") {491          return { ok: false, error: "invalid_payload" };492        }493        const summary = await vault.restoreEntries(494          payload.entries as Parameters<typeof vault.restoreEntries>[0],495          payload.mode496        );497        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {498          await vault.updateSettings(payload.settings as vault.VaultSettings);499        }500        return { ok: true, data: summary };501      }502      case "CLEAR_VAULT_ENTRIES": {503        await vault.clearVaultEntries("REPLACE_ALL");504        return { ok: true };505      }506      case "GET_VAULT_HISTORY": {507        const snapshots = await vault.getVaultHistory();508        return { ok: true, data: snapshots };509      }510      case "RESTORE_VAULT_SNAPSHOT": {511        const { snapshotId } = msg.payload as { snapshotId: string };512        const result = await vault.restoreVaultSnapshot(snapshotId);513        if (!result.ok) return { ok: false, error: result.error };514        broadcastToContentScripts({ type: "VAULT_LOCKED" });515        return { ok: true };516      }517      case "COUNT_DUPLICATES": {518        return { ok: true, data: vault.countDuplicates() };519      }520      case "DEDUPLICATE_ENTRIES": {521        const removed = await vault.deduplicateEntries();522        return { ok: true, data: removed };523      }524      case "UPDATE_ENTRY": {525        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;526        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {527          return { ok: false, error: "invalid_payload" };528        }529        const { id, patch } = payload;530        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {531          return { ok: false, error: "invalid_payload" };532        }533        // Single enforcement point for the Canary Entries Pro gate. Only534        // gates the transition into a canary entry — clearing/disabling a535        // canary (`canary: undefined`) is always allowed, so existing536        // canary entries remain manageable.537        const incomingCanary = (patch as { canary?: unknown }).canary;538        if (incomingCanary && typeof incomingCanary === "object") {539          const existing = vault.getEntryById(id);540          if (!existing?.canary) {541            const gate = await requirePro("canary_entry");542            if (!gate.allowed) return { ok: false, error: "pro_required" };543          }544        }545        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);546        return { ok: true };547      }548      case "ADD_ADDITIONAL_URL": {549        const { id, url } = msg.payload as { id: string; url: string };550        const trimmed = typeof url === "string" ? url.trim() : "";551        if (!trimmed) return { ok: false, error: "url_required" };552        const existing = vault.getEntryById(id);553        if (!existing) return { ok: false, error: "entry_not_found" };554        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };555        const merged = [...(existing.additionalUrls ?? []), trimmed];556        await vault.updateEntry(id, { additionalUrls: merged });557        return { ok: true };558      }559      case "DELETE_ENTRY": {560        const { id } = msg.payload as { id: string };561        await vault.deleteEntry(id);562        return { ok: true };563      }564      case "GET_DELETED_ENTRIES":565        return { ok: true, data: vault.getDeletedEntries() };566      case "RESTORE_ENTRY": {567        const { id } = msg.payload as { id: string };568        await vault.restoreEntry(id);569        return { ok: true };570      }571      case "PURGE_ENTRY": {572        const { id } = msg.payload as { id: string };573        await vault.purgeEntry(id);574        return { ok: true };575      }576      case "PURGE_EXPIRED_TRASH": {577        const { retentionMs } = msg.payload as { retentionMs: number };578        const purged = await vault.purgeExpiredTrash(retentionMs);579        return { ok: true, data: purged };580      }581      case "SAVE_NOTE": {582        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };583        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };584        const now = Date.now();585        if (id) {586          const existing = vault.getEntryById(id);587          if (!existing) return { ok: false, error: "not_found" };588          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });589          return { ok: true, data: vault.getEntryById(id) };590        } else {591          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt592          // (EntryDraft omits both), so passing them was the only reason the593          // `as any` cast existed. Dropping them makes the call type-check.594          const entry = await vault.addEntry({595            type: "note",596            title: title || "Untitled",597            notes: body,598          });599          return { ok: true, data: entry };600        }601      }602      case "DELETE_NOTE": {603        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };604        const { id } = msg.payload as { id: string };605        await vault.deleteEntry(id);606        return { ok: true };607      }608      case "GET_NOTES": {609        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };610        const notes = vault.getEntries().filter(611          (e) => e.type === "note" && !e.deletedAt612        );613        return { ok: true, data: notes } as MessageResponse;614      }615      case "SEARCH_VAULT": {616        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };617        // AUD-002: shape-validate the payload before calling string methods.618        // A raw cast lets a malformed message crash the handler with TypeError.619        const { query } = (msg.payload ?? {}) as { query?: unknown };620        if (typeof query !== "string") {621          return { ok: false, error: "invalid_payload" };622        }623        const q = query.toLowerCase();624        const searchResults = vault.getEntries().filter(625          (e) =>626            !e.deletedAt &&627            (e.title.toLowerCase().includes(q) ||628              e.notes?.toLowerCase().includes(q) ||629              e.username?.toLowerCase().includes(q))630        );631        return { ok: true, data: searchResults } as MessageResponse;632      }633      case "AUTOFILL_QUERY": {634        if (!vault.isUnlocked()) {635          return { ok: false, error: "vault_locked" };636        }637        let { includeAll } = msg.payload as { includeAll?: boolean };638        const { domain, kind, userGesture } = msg.payload as {639          domain: string;640          kind?: "login" | "card" | "totp";641          userGesture?: boolean;642        };643        // MV-2: the vault-wide inventory (every title/username/email/url)644        // may only leave the background on an explicit user gesture — the645        // user opening the search affordance — never on passive form focus.646        // userGesture is self-declared by our own content script; the value647        // of this gate is that PASSIVE code paths (which never set it)648        // cannot ship the inventory, shrinking what a compromised page that649        // merely triggers focus events can observe.650        if (includeAll && userGesture !== true) {651          includeAll = false;652        }653        // kind="card": return saved cards as compact summaries for the654        // inline card silver platter. Cards are not domain-scoped — every655        // saved card is a candidate on every checkout page — so domain is656        // ignored when kind === "card".657        if (kind === "card") {658          const cards = vault.getEntries().filter((e) => e.type === "card");659          return {660            ok: true,661            data: cards.map((e) => ({662              id: e.id,663              title: e.cardNickname || e.title,664              cardholderName: e.cardholderName,665              last4: e.last4,666              expMonth: e.expMonth,667              expYear: e.expYear,668              network: e.network,669            })),670          };671        }672        if (kind === "totp") {673          const matches = (674            includeAll675              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")676              : vault.queryDomain(domain)677          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));678          return {679            ok: true,680            data: matches.map((e) => ({681              id: e.id,682              title: e.title,683              username: e.username,684              email: e.email,685              url: e.url,686              hasTotp: true,687            })),688          };689        }690        // The inline selector fills username+password into a form. Passkey-691        // only entries have no password to fill; sign-in for those goes692        // through the WebAuthn path instead. Filter them out everywhere so693        // the user doesn't see four "GitHub" rows that mostly do nothing.694        // Notes and cards never belonged here either.695        const matches = (696          includeAll697            ? vault698                .getEntries()699                .filter((entry) => entry.type !== "note" && entry.type !== "card")700            : vault.queryDomain(domain)701        ).filter((entry) => !isPasskeyOnly(entry));702        return {703          ok: true,704          data: matches.map((e) =>705            includeAll706              ? {707                  id: e.id,708                  title: e.title,709                  // username/email/url shipped so the inline popup's search710                  // affordance can match on them, not just titles. No secrets711                  // cross the boundary — same shape as the domain-matched712                  // response below minus hasTotp (which the search list713                  // doesn't surface).714                  username: e.username,715                  email: e.email,716                  url: e.url,717                  hasPasskey: e.passkey !== undefined,718                }719              : {720                  id: e.id,721                  title: e.title,722                  username: e.username,723                  email: e.email,724                  url: e.url,725                  hasTotp: Boolean(e.totp),726                  hasPasskey: e.passkey !== undefined,727                }728          ),729        };730      }731      case "GET_ENTRY_FOR_FILL": {732        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };733        const { id, explicitSummon } = msg.payload as {734          id: string;735          explicitSummon?: boolean;736        };737        const entry = vault.getEntryById(id);738        if (!entry) return { ok: false, error: "entry_not_found" };739        // Passkey-only entries (passkey credential, no password) cannot be740        // filled into a form — sign-in goes through the WebAuthn path. A741        // login that ALSO has a passkey is still fillable for its password.742        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };743744        // MV-1: re-validate the entry against the requesting frame's origin.745        // sender.url / sender.tab.url are browser-attested — a page cannot746        // forge them. PB-26-005: the FRAME url (sender.url) is authoritative747        // for an all_frames content script; the top-frame tab.url would748        // misattribute a cross-origin iframe's request to the top page. When749        // the request does not come from a tab at all (popup surfaces use750        // GET_ENTRY_FOR_EDIT, not this), refuse.751        if (sender.tab !== undefined || sender.url !== undefined) {752          let senderDomain: string | null = null;753          try {754            const rawUrl = sender.url ?? sender.tab?.url ?? "";755            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;756          } catch {757            senderDomain = null;758          }759          if (!senderDomain) return { ok: false, error: "origin_unverified" };760761          const entryDomains = new Set<string>();762          const primary = extractDomain(entry.url ?? "");763          if (primary) entryDomains.add(primary);764          for (const extra of entry.additionalUrls ?? []) {765            const d = extractDomain(extra);766            if (d) entryDomains.add(d);767          }768769          // explicitSummon=true means the user actively picked this entry770          // from the cross-domain search affordance — an intentional771          // off-domain fill. Passive fill paths must stay domain-bound.772          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {773            // Domain mismatch — refuse silently (no oracle about which ids exist).774            return { ok: false, error: "entry_not_found" };775          }776        }777        // Strip the passkey credential AND the raw base32 TOTP seed from the778        // response. Content scripts never need either: the private key is the779        // authenticator's, and handing over the TOTP seed would let a780        // compromised content script mint valid codes indefinitely (SEV-3-C).781        // Generate the *current* 6-digit code here in the background and send782        // only that, plus the seconds left so the UI can render a countdown.783        // Also drop passwordHistory: filling needs only the *current* password.784        // Handing every past password to a content script during passive785        // autofill on an arbitrary page would widen the blast radius of a786        // compromised page far beyond the one credential being filled.787        const {788          passkey: _strippedPasskey,789          totp: seed,790          totpAlgorithm,791          totpDigits,792          totpPeriod,793          passwordHistory: _ph,794          ...safeEntry795        } = entry;796        let totpCode: string | undefined;797        let totpRemaining: number | undefined;798        if (seed) {799          try {800            // PCH-01-019: honour stored algorithm/digits/period (defaults apply801            // when these are undefined, i.e. RFC-default bare-seed entries).802            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);803            totpCode = generated.code;804            totpRemaining = generated.remaining;805          } catch {806            totpCode = undefined;807          }808        }809        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };810      }811      // Trusted full-entry fetch for Peach's own inline-popup surfaces that812      // genuinely need the raw TOTP seed: the edit form (which re-saves the813      // seed and would otherwise wipe it) and nothing else. Unlike814      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside815      // the inline popup, never during passive autofill on an arbitrary page.816      // The passkey credential is still stripped — the edit form never touches it.817      case "GET_ENTRY_FOR_EDIT": {818        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };819        const { id, explicitSummon } = msg.payload as {820          id: string;821          explicitSummon?: boolean;822        };823        const entry = vault.getEntryById(id);824        if (!entry) return { ok: false, error: "entry_not_found" };825826        // PCH-01-006: re-validate the browser-attested sender origin, mirroring827        // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and828        // full password history — at least as sensitive as the fill response — so829        // the boundary must be enforced here, not only by UI reachability. Today830        // the sole caller is the popup (no sender.tab, so this is a structural831        // no-op), but a future tab-context caller or an id leak would otherwise832        // inherit a full-credential oracle. Unlike the fill path we SKIP (not833        // refuse) when no sender domain resolves, to keep the popup caller working.834        // PB-26-005: the frame url (sender.url) is authoritative over the835        // top-frame sender.tab.url — mirrors the fill path.836        if (sender.tab !== undefined || sender.url !== undefined) {837          let senderDomain: string | null = null;838          try {839            const rawUrl = sender.url ?? sender.tab?.url ?? "";840            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;841          } catch {842            senderDomain = null;843          }844          if (senderDomain) {845            const entryDomains = new Set<string>();846            const primary = extractDomain(entry.url ?? "");847            if (primary) entryDomains.add(primary);848            for (const extra of entry.additionalUrls ?? []) {849              const d = extractDomain(extra);850              if (d) entryDomains.add(d);851            }852            if (explicitSummon !== true && !entryDomains.has(senderDomain)) {853              return { ok: false, error: "entry_not_found" }; // no id oracle854            }855          }856        }857858        const { passkey: _passkey, ...safeEntry } = entry;859        return { ok: true, data: safeEntry };860      }861      case "COPY": {862        // AUD-002: shape-validate the payload before passing to the clipboard863        // helper. A raw cast lets a malformed message reach the clipboard API864        // with a non-string and throw.865        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {866          text?: unknown;867          label?: unknown;868          alreadyWritten?: unknown;869        };870        if (typeof text !== "string" || typeof label !== "string") {871          return { ok: false, error: "invalid_payload" };872        }873        await copyToClipboard(text, label, Boolean(alreadyWritten));874        return { ok: true, clearSeconds: getEffectiveClearSeconds() };875      }876      case "CHECK_ALL_BREACHES": {877        const allEntries = vault.getEntries();878        const results: Record<string, number> = {};879        for (const entry of allEntries) {880          if (entry.type === "note") continue;881          if (!entry.password) continue;882          results[entry.id] = await vault.checkBreach(entry.password);883          // Small delay — be a good citizen to the HIBP API884          await new Promise((r) => setTimeout(r, 200));885        }886        // Persist any non-zero counts back to entries887        for (const [id, count] of Object.entries(results)) {888          const entry = vault.getEntryById(id);889          if (entry && (entry.breach ?? 0) !== count) {890            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });891          }892        }893        return { ok: true, data: results };894      }895      case "GET_SETTINGS":896        return { ok: true, data: await vault.ensureSettingsLoaded() };897      case "UPDATE_SETTINGS": {898        const patch = msg.payload;899        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {900          return { ok: false, error: "invalid_payload" };901        }902        await vault.updateSettings(patch as vault.VaultSettings);903        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {904          await setupAutoLock();905          if (vault.isUnlocked()) touchAutoLock();906        }907        return { ok: true };908      }909      case "SETUP_PIN": {910        const { currentPassword, pin } = (msg.payload ?? {}) as {911          currentPassword?: unknown;912          pin?: unknown;913        };914        if (typeof currentPassword !== "string" || typeof pin !== "string") {915          return { ok: false, error: "invalid_payload" };916        }917        return (await vault.setupPinUnlock(currentPassword, pin))918          ? { ok: true }919          : { ok: false, error: "incorrect_current_password" };920      }921      case "DISABLE_PIN": {922        const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown };923        if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" };924        return (await vault.disablePinUnlock(currentPassword))925          ? { ok: true }926          : { ok: false, error: "incorrect_current_password" };927      }928      case "GET_PENDING_PASSKEY":929        return { ok: true, data: await getPendingPasskeyRequest() };930      case "APPROVE_PASSKEY": {931        const { requestId } = msg.payload as { requestId: number };932        await resolvePendingPasskeyRequest(requestId, true);933        return { ok: true };934      }935      case "DENY_PASSKEY": {936        const { requestId } = msg.payload as { requestId: number };937        await resolvePendingPasskeyRequest(requestId, false);938        return { ok: true };939      }940      case "GET_PASSKEY_PROVIDER_STATE":941        return { ok: true, data: await getPasskeyProviderState() };942      case "SET_PASSKEY_PROVIDER_ENABLED": {943        const { enabled } = msg.payload as { enabled: boolean };944        // Disabling is always free; gating fires only when a free user is945        // trying to turn passkey interception on.946        if (enabled) {947          const gate = await requirePro("passkeys");948          if (!gate.allowed) return { ok: false, error: "pro_required" };949        }950        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };951      }952      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS953      // endpoint. Intentional product behavior — users configure their own954      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private955      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-956      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to957      // users that the entry title leaves the device when the canary fires.958      case "FIRE_CANARY_PING": {959        // Canary alert fires unconditionally for any entry with canary: true.960        // The Pro gate only governs creation/flagging of canary entries; once961        // an entry is flagged, the alert path is a security property and must962        // never be license-gated.963        const { webhookUrl, entryTitle, trigger } = msg.payload as {964          webhookUrl: string;965          entryTitle: string;966          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";967        };968        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {969          return { ok: false, error: "invalid_webhook_url" };970        }971        // LV-3: debounce non-test pings per (webhook, entry) so a page that972        // strobes focus/fill events can't turn the canary into a request973        // firehose at the user's endpoint. Test pings are exempt — they are974        // explicit user clicks in the settings UI and are awaited for975        // feedback. The FIRST ping in a window always goes out, so the976        // dead-man's-switch property (canary fires on access) is preserved;977        // only repeats within the window are coalesced.978        if (trigger !== "test") {979          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;980          const stored = await chrome.storage.local.get(rlKey);981          const last = (stored as Record<string, unknown>)[rlKey];982          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {983            return { ok: true, data: { rateLimited: true } };984          }985          await chrome.storage.local.set({ [rlKey]: Date.now() });986        }987        const body = JSON.stringify({988          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",989          entry: entryTitle,990          trigger,991          timestamp: new Date().toISOString(),992          source: "peach-extension",993        });994        if (trigger === "test") {995          // Permitted outbound fetch: user-configured canary alert endpoint996          // (validated by isAllowedCanaryWebhookUrl above). This is the997          // only non-HIBP outbound call in the extension — see998          // Projects.md §3.7. Test pings are awaited so the UI can show999          // success/failure.1000          try {1001            const res = await fetch(webhookUrl, {1002              method: "POST",1003              headers: { "Content-Type": "application/json" },1004              body,1005            });1006            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1007          } catch (err) {1008            return { ok: false, error: err instanceof Error ? err.message : "network_error" };1009          }1010        }1011        // Non-test triggers are fire-and-forget1012        fetch(webhookUrl, {1013          method: "POST",1014          headers: { "Content-Type": "application/json" },1015          body,1016        }).catch(() => {});1017        return { ok: true };1018      }1019      case "ACTIVATE_LICENSE": {1020        const { key } = msg.payload as { key: string };1021        const licenseInfo = await activateLicense(key);1022        return { ok: true, data: licenseInfo };1023      }1024      case "GET_LICENSE": {1025        const licenseInfo = await getLicenseInfo();1026        return { ok: true, data: licenseInfo };1027      }1028      case "GET_LICENSE_KEY": {1029        const key = await getLicenseKey();1030        return { ok: true, data: key };1031      }1032      case "DEACTIVATE_LICENSE": {1033        await deactivateLicense();1034        return { ok: true };1035      }1036      case "SHOULD_PLAY_CELEBRATION": {1037        const should = await shouldPlayCelebration();1038        return { ok: true, data: should };1039      }1040      case "MARK_CELEBRATION_PLAYED": {1041        await markCelebrationPlayed();1042        return { ok: true };1043      }1044      case "GET_CODEX_VAULT_DATA": {1045        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1046        // popup navigates to the License section without further coordination.1047        // Also privileged-page-gated (PB-26-001), and recoveryWords inside the1048        // snapshot additionally require a fresh master-password proof.1049        const gate = await requirePro("codex");1050        if (!gate.allowed) return { ok: false, error: "pro_required" };1051        const { password } = (msg.payload ?? {}) as { password?: string };1052        return await handleGetCodexVaultData(password);1053      }1054      case "ESTIMATE_CODEX_PAGES": {1055        const gate = await requirePro("codex");1056        if (!gate.allowed) return { ok: false, error: "pro_required" };1057        return await handleEstimateCodexPages();1058      }1059      case "RESTORE_FROM_CODEX": {1060        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1061        // be able to restore a vault that was printed by a Pro user.1062        // DO NOT add a Pro gate here.1063        const payload = msg.payload as CodexRestorePayload;1064        return await handleRestoreFromCodex(payload);1065      }1066      case "OPEN_PRO_GATE": {1067        // Content script requests: open popup and navigate to License section.1068        const { feature } = (msg.payload ?? {}) as { feature?: string };1069        if (chrome.storage.session) {1070          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1071        }1072        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1073        return { ok: true };1074      }1075      case "OPEN_POPUP": {1076        // Content script asks to open the trusted extension popup — used by the1077        // inline locked bubble so the master password is entered in the popup,1078        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1079        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1080        // toolbar icon. The badge already signals Peach needs attention.1081        //1082        // Set a session flag so the popup knows it was opened for inline unlock1083        // and should close itself once the vault is unlocked (returning the user1084        // to the inline autofill selector on the page).1085        if (chrome.storage.session) {1086          await chrome.storage.session.set({ peach_inline_unlock: true });1087        }1088        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1089        return { ok: true };1090      }1091      case "OPEN_DETACHED_POPUP": {1092        // A window created by the action popup and then orphaned with1093        // window.close() is cascaded shut by Chrome, so the file-picker1094        // flows (OS dialogs that dismiss the popup on focus loss) ask the SW1095        // to open the standalone window instead — the SW has no window to be1096        // associated with. The query string is allowlisted so this can never1097        // open an arbitrary URL.1098        const { route } = (msg.payload ?? {}) as { route?: string };1099        const search = route === "peachscript"1100          ? "?restore=peachscript"1101          : route === "csv"1102            ? "?restore=csv"1103            : route === "codex-pdf"1104              ? "?codex=pdf"1105              : null;1106        if (!search) return { ok: false, error: "bad_route" };1107        try {1108          const popupHtml =1109            chrome.runtime.getManifest().action?.default_popup ?? "src/popup/index.html";1110          await chrome.windows.create({1111            url: chrome.runtime.getURL(`${popupHtml}${search}`),1112            type: "popup",1113            width: 320,1114            height: 550,1115          });1116          return { ok: true, data: { detached: true } };1117        } catch {1118          return { ok: false };1119        }1120      }1121      case "GET_IDENTITIES": {1122        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1123        return { ok: true, data: vault.getIdentities() };1124      }1125      case "TOUCH_AUTO_LOCK": {1126        // touchAutoLock() is already called by shouldRefreshAutoLock above;1127        // this case just gives the popup a typed message to keep the session alive.1128        return { ok: true };1129      }1130      case "GET_ADVANCED_HEALTH_REPORT": {1131        const gate = await requirePro("advanced_health");1132        if (!gate.allowed) return { ok: false, error: "pro_required" };1133        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1134        const report = await buildAdvancedHealthReport(vault.getEntries());1135        return { ok: true, data: report };1136      }1137      case "IS_DURESS_ENABLED": {1138        const enabled = await vault.isDuressEnabled();1139        return { ok: true, data: enabled };1140      }1141      case "SETUP_DURESS": {1142        // Single enforcement point for the Duress Vault Pro gate. Free users1143        // who somehow reach this handler are rejected here; the popup also1144        // pre-checks isPro() to avoid showing the setup form to free users,1145        // but server-side is the actual security boundary.1146        const gate = await requirePro("duress_vault");1147        if (!gate.allowed) return { ok: false, error: "pro_required" };1148        // MV3 service workers restart after inactivity, losing the in-memory1149        // derived key. Detect this before calling setupDuress so the popup1150        // can show a meaningful prompt to re-lock and re-unlock.1151        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1152        const { duressPassword } = msg.payload as { duressPassword: string };1153        await vault.setupDuress(duressPassword);1154        return { ok: true };1155      }1156      case "DISABLE_DURESS": {1157        await vault.disableDuress();1158        return { ok: true };1159      }1160      case "VERIFY_MAIN_PASSWORD": {1161        const { password } = msg.payload as { password: string };1162        const ok = await vault.verifyMainPassword(password);1163        return { ok: true, data: ok };1164      }1165      case "CHANGE_PASSWORD": {1166        const { currentPassword, newPassword } = msg.payload as {1167          currentPassword: string;1168          newPassword: string;1169        };1170        const changed = await vault.changePassword(currentPassword, newPassword);1171        return changed1172          ? { ok: true }1173          : { ok: false, error: "incorrect_current_password" };1174      }1175      case "GET_SITE_PASSWORD_POLICY": {1176        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1177        if (!tab?.id) return { ok: true, data: null };1178        try {1179          const response = await chrome.tabs.sendMessage(tab.id, {1180            type: "GET_SITE_PASSWORD_POLICY",1181          });1182          return (response as MessageResponse) ?? { ok: true, data: null };1183        } catch {1184          return { ok: true, data: null };1185        }1186      }1187      case "RECORD_MANUAL_SUMMON": {1188        const { domain } = msg.payload as { domain: string };1189        const settings = vault.getSettings();1190        const existing = settings.manualSummonDomains?.[domain];1191        const now = Date.now();1192        await vault.updateSettings({1193          manualSummonDomains: {1194            ...settings.manualSummonDomains,1195            [domain]: {1196              firstSummonedAt: existing?.firstSummonedAt ?? now,1197              summonCount: (existing?.summonCount ?? 0) + 1,1198              lastSummonedAt: now,1199            },1200          },1201        });1202        return { ok: true };1203      }1204      case "DECLINE_CARD_SAVE": {1205        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1206        await vault.declineCardSaveOffer(last4, expMonth, expYear);1207        return { ok: true };1208      }1209      case "IS_CARD_DECLINED": {1210        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1211        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1212        return { ok: true, data: declined };1213      }1214      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1215        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1216          rpId?: string;1217          rpName?: string;1218          userName?: string;1219          userDisplayName?: string;1220        };1221        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1222        return await initiateFirefoxPasskeyCreate({1223          rpId,1224          rpName: rpName ?? rpId,1225          userName,1226          userDisplayName,1227        }, attestedSenderOrigin(sender));1228      }12291230      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1231        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1232        if (!payload) return { ok: false, error: "missing_payload" };1233        return await completeFirefoxPasskeyCreate(payload);1234      }12351236      case "PASSKEY_OFFER_DECLINE": {1237        const { domain } = (msg.payload ?? {}) as { domain?: string };1238        if (!domain) return { ok: false, error: "domain_required" };1239        await recordPasskeyOfferDecline(domain);1240        return { ok: true };1241      }12421243      case "GET_PASSKEY_OFFER_DECLINED": {1244        const { domain } = (msg.payload ?? {}) as { domain?: string };1245        if (!domain) return { ok: false, error: "domain_required" };1246        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1247      }12481249      case "PASSKEY_HAS_CREDENTIALS": {1250        const payload = msg.payload as {1251          rpId?: string;1252          allowCredentials?: Array<{ id: string; type?: string }>;1253        } | undefined;1254        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1255        return await handlePasskeyHasCredentials({1256          rpId: payload.rpId,1257          allowCredentials: payload.allowCredentials ?? [],1258        }, attestedSenderOrigin(sender));1259      }12601261      case "PASSKEY_CREATE": {1262        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1263        if (!payload?.rpId || !payload?.userName) {1264          return { ok: false, error: "rpid_and_username_required" };1265        }1266        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1267      }12681269      case "PASSKEY_GET": {1270        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1271        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1272        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1273      }12741275      case "PASSKEY_AUTH_RESPONSE": {1276        const { requestId, approved } = (msg.payload ?? {}) as {1277          requestId?: string | number;1278          approved?: boolean;1279        };1280        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1281          return { ok: false, error: 'requestId and approved required' };1282        }1283        await resolvePendingPasskeyRequest(Number(requestId), approved);1284        return { ok: true };1285      }12861287      case "GET_PASSKEY_FOR_DOMAIN": {1288        const { domain } = (msg.payload ?? {}) as { domain?: string };1289        if (!domain) return { ok: false, error: "domain_required" };1290        // Scope to the caller's own origin: a page may only ask about passkeys1291        // for a domain it actually owns, so an arbitrary page cannot enumerate1292        // which sites the user holds passkeys for or read the username (audit MEDIUM).1293        const origin = attestedSenderOrigin(sender);1294        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1295        if (!vault.isUnlocked()) return { ok: true, data: null };1296        const match = vault1297          .getEntries()1298          .find((entry) => entry.passkey?.rpId === domain);1299        if (!match || !match.passkey) return { ok: true, data: null };1300        // Slim shape — only the fields State 11 needs. Never expose private1301        // key material, even though this is locked behind isUnlocked.1302        return {1303          ok: true,1304          data: {1305            rpId: match.passkey.rpId,1306            userName: match.passkey.userName,1307            browser: match.passkey.browser,1308          },1309        };1310      }13111312      case "DESTROY_VAULT": {1313        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1314        // storage.local.clear() wipes every Peach key (slots, settings, license,1315        // onboarded flag, history, sync state, declined cards, recall, etc.);1316        // session.clear() wipes pending passkey requests + pro-notice queues.1317        // Caller (Panic.tsx) handles UI navigation back to onboarding.1318        //1319        // The Pro license is the one thing that must survive: the user paid for1320        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1321        // Capture it before the clear and restore it after. peach_pro_celebrated1322        // rides along so the Pro celebration doesn't replay on the next unlock.1323        const preserved = await chrome.storage.local.get([1324          "peach_license",1325          "peach_pro_celebrated",1326        ]);1327        vault.lock();1328        await storageClear();1329        await vault.clearVaultHistory();1330        const toRestore: Record<string, unknown> = {};1331        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1332        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1333        if (Object.keys(toRestore).length > 0) {1334          await chrome.storage.local.set(toRestore);1335        }1336        if (chrome.storage.session) {1337          await chrome.storage.session.clear();1338        }1339        await clearRecoveryConfirmPending();1340        return { ok: true };1341      }13421343      case "GET_IDENTITY_SUGGESTIONS": {1344        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1345        const entries = vault.getEntries();1346        const suggestions = buildIdentitySuggestions(entries);1347        return { ok: true, data: { suggestions } };1348      }1349      case "ML_INIT":1350        return { ok: true };13511352      case "ML_PREDICT_BATCH": {1353        // AUD-002: shape-validate before forwarding to the ML helper.1354        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1355        if (!Array.isArray(featuresArray)) {1356          return { ok: false, error: "invalid_payload" };1357        }1358        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1359      }13601361      // ── Vault sync (v3) ───────────────────────────────────────────────1362      // Returns the public-facing local identity needed by the popup to1363      // drive Phase-1 audio pairing. The private long-term key never1364      // leaves the background.1365      case "GET_LOCAL_IDENTITY": {1366        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1367        // Pro license from an already-Pro peer (at least one device must be Pro).1368        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1369        // Identity derives from the stable root key, not the password-derived1370        // key, so pairing survives a master-password change (SEV-2-B).1371        const masterKeyHex = vault.getRootKeyHex();1372        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1373        const masterKey = unhexBytes(masterKeyHex);1374        try {1375          const identity = await buildLocalIdentity(masterKey);1376          // If this device is Pro, advertise the signed license so the peer can1377          // activate it after SAS confirmation — pairing carries Pro across.1378          if (await isProUser()) {1379            const license = await getLicenseKey();1380            if (license) (identity as { license?: string }).license = license;1381          }1382          return { ok: true, data: identity };1383        } finally {1384          masterKey.fill(0);1385        }1386      }13871388      case "LIST_PAIRED_DEVICES": {1389        const devices = await listPairedDevicesV3();1390        return { ok: true, data: { devices } };1391      }13921393      case "RENAME_PAIRED_DEVICE": {1394        const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string };1395        if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") {1396          return { ok: false, error: "invalid_payload" };1397        }1398        await renamePairedDeviceV3(deviceId, name);1399        return { ok: true };1400      }14011402      case "UNPAIR_DEVICE": {1403        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1404        if (typeof deviceId !== "string" || !deviceId) {1405          return { ok: false, error: "invalid_payload" };1406        }1407        // Removing a device REVOKES it rather than just dropping the local1408        // row: a plain removal is undone the moment any other peer vouches it1409        // back through a manifest, which is exactly what the relay makes easy.1410        await revokeDeviceByIdV3(deviceId, await getOrCreateDeviceId());1411        // Sync against the remaining hosts — the unpaired device no longer1412        // matters but the next alarm tick is up to ten minutes away.1413        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1414        return { ok: true };1415      }14161417      case "RENAME_LOCAL_DEVICE": {1418        const { name } = (msg.payload ?? {}) as { name?: string };1419        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1420        await setDeviceNameV3(name);1421        return { ok: true };1422      }14231424      // ── Relay pairing ─────────────────────────────────────────────────────1425      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1426      // session runs in the background; the SAS and the terminal result reach1427      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1428      case "START_ADOPTION_SOURCE": {1429        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1430        if (isRelayAdoptionSourceInFlight()) {1431          return { ok: false, error: "adoption_source_in_progress" };1432        }1433        try {1434          return { ok: true, data: await startRelayAdoptionSource() };1435        } catch (error) {1436          return {1437            ok: false,1438            error: error instanceof Error ? error.message : "adoption_source_failed",1439          };1440        }1441      }14421443      // Onboarding receiver — empty extension shows a QR, phone scans and1444      // sends the vault. The popup supplies the local-only password here so1445      // the background can wrap the adopted root key at rest without ever1446      // asking the user to retype it.1447      case "START_ADOPTION_RECEIVER": {1448        if (isRelayAdoptionSourceInFlight()) {1449          return { ok: false, error: "adoption_receiver_in_progress" };1450        }1451        const password = (msg.payload as { password?: unknown } | undefined)?.password;1452        if (typeof password !== "string" || password.length === 0) {1453          return { ok: false, error: "invalid_payload" };1454        }1455        try {1456          return { ok: true, data: await startRelayAdoptionReceiver(password) };1457        } catch (error) {1458          return {1459            ok: false,1460            error: error instanceof Error ? error.message : "adoption_receiver_failed",1461          };1462        }1463      }14641465      // Popup→bg counterpart to ADOPTION_SOURCE_SAS (receiver flow).1466      // The receiver now auto-accepts the SAS (both sides derive it from the1467      // same Noise handshake hash, so the codes match by construction) so1468      // the popup never has a SAS screen to tap on. The id round-trips the1469      // same way so a stale late response can't approve the wrong session.1470      // Popup→bg counterpart for the source flow: Confirm/Cancel on the1471      // source's SAS screen.14721473      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1474      // on the source's SAS screen. The id round-trips the same way so a stale1475      // late response can't approve the wrong session.1476      case "SOURCE_SAS_DECISION": {1477        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1478        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1479          return { ok: false, error: "invalid_payload" };1480        }1481        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1482      }14831484      case "CANCEL_ADOPTION_SOURCE": {1485        cancelRelayAdoptionSource();1486        return { ok: true };1487      }14881489      case "TRIGGER_SYNC": {1490        const payload = (msg.payload ?? {}) as {1491          reason?: "vault_change" | "foreground" | "manual";1492          force?: boolean;1493        };1494        const reason = payload.reason ?? "foreground";14951496        void triggerSyncIfReachable({ reason, force: payload.force === true });1497        return { ok: true };1498      }14991500      case "GET_SYNC_STATE": {1501        return { ok: true, data: getSyncState() };1502      }15031504      case "GET_SYNC_SETTINGS": {1505        return { ok: true, data: await getSyncSettings() };1506      }15071508      case "SET_SYNC_SETTINGS": {1509        const payload = (msg.payload ?? {}) as {1510          mode?: unknown;1511          relayUrl?: unknown;1512        };1513        try {1514          // A custom relay URL implies private mode; Peach's own relay stays1515          // public. See setRelayUrl.1516          if (payload.relayUrl !== undefined) {1517            if (typeof payload.relayUrl !== "string") {1518              return { ok: false, error: "invalid_relay_url" };1519            }1520            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1521          }1522          if (payload.mode !== undefined) {1523            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1524              return { ok: false, error: "invalid_sync_mode" };1525            }1526            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1527          }1528          return { ok: true, data: await getSyncSettings() };1529        } catch (error) {1530          return {1531            ok: false,1532            error: error instanceof Error ? error.message : "invalid_relay_url",1533          };1534        }1535      }15361537      case "GET_SYNC_ALERTS": {1538        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1539        const alerts = await getPendingSyncAlerts();1540        // The popup reads on open and acknowledges with consume:true after1541        // rendering, so a popup crash between read and render doesn't lose1542        // the alerts.1543        if (consume) await clearPendingSyncAlerts();1544        return { ok: true, data: alerts };1545      }15461547      case "GET_PENDING_VOUCHED_DEVICES": {1548        return { ok: true, data: await listPendingVouchedDevices() };1549      }1550      case "CONFIRM_VOUCHED_DEVICE": {1551        const { deviceId } = msg.payload as { deviceId: string };1552        const pending = await getPendingVouchedDevice(deviceId);1553        if (!pending) return { ok: false, error: "not_pending" };1554        // Last gate before a vouched device becomes a sync peer. A queue entry1555        // can predate the revocation that names it, so revocation is re-checked1556        // here rather than trusted to have swept the queue.1557        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {1558          await removePendingVouchedDevice(deviceId);1559          return { ok: false, error: "device_revoked" };1560        }1561        await upsertPairedDeviceV3({1562          deviceId: pending.deviceId,1563          deviceName: pending.deviceName,1564          deviceType:1565            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1566          longTermPublicKeyHex: pending.longTermPublicKeyHex,1567          signingPublicKeyHex: pending.signingPublicKeyHex,1568          wsPort: pending.wsPort,1569          pairedAt: pending.pairedAt,1570          trustSource: "vouched",1571        });1572        await removePendingVouchedDevice(deviceId);1573        // Newly confirmed vouched device is now a sync target — kick a round1574        // so the mesh introduction pays off without a 10-minute wait.1575        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1576        return { ok: true };1577      }1578      case "REJECT_VOUCHED_DEVICE": {1579        const { deviceId } = msg.payload as { deviceId: string };1580        await removePendingVouchedDevice(deviceId);1581        return { ok: true };1582      }1583      case "ROTATE_SYNC_IDENTITY": {1584        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1585        const result = await vault.rotateSyncIdentity();1586        return result.ok ? { ok: true } : { ok: false, error: result.error };1587      }15881589      default:1590        return { ok: false, error: "unknown_message_type" };1591    }1592  } catch (err) {1593    return {1594      ok: false,1595      error: err instanceof Error ? err.message : "operation_failed",1596    };1597  }1598}15991600// Returns username use-counts from the vault, sorted by frequency. Each row1601// also carries the entry's email so the popup can suggest the email/username1602// pair the user has actually used together.1603function buildIdentitySuggestions(1604  entries: VaultEntry[],1605): Array<{ email: string; username: string; count: number }> {1606  const usernameCounts = new Map<string, number>();1607  const usernameEmail = new Map<string, string>();1608  for (const entry of entries) {1609    const username = entry.username ?? "";1610    const email = (entry as VaultEntry & { email?: string }).email ?? "";1611    if (!username && !email) continue;1612    const key = username || email;1613    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1614    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1615  }1616  return Array.from(usernameCounts.entries())1617    .sort((a, b) => b[1] - a[1])1618    .map(([username, count]) => ({1619      email: usernameEmail.get(username) ?? "",1620      username,1621      count,1622    }));1623}16241625/** Notify all content scripts that the vault just became available. */1626function broadcastToContentScripts(message: { type: string }): void {1627  if (!chrome.tabs?.query) return;1628  chrome.tabs.query({}, (tabs) => {1629    for (const tab of tabs) {1630      if (tab.id !== undefined) {1631        chrome.tabs.sendMessage(tab.id, message).catch(() => {1632          // Tab may not have a content script — silently ignore1633        });1634      }1635    }1636  });1637}16381639function shouldRefreshAutoLock(type: MessageType): boolean {1640  return (1641    type !== "HAS_VAULT" &&1642    type !== "IS_UNLOCKED" &&1643    type !== "GET_VAULT_STATUS" &&1644    type !== "LOCK" &&1645    type !== "UPDATE_SETTINGS" &&1646    type !== "GET_PENDING_PASSKEY" &&1647    type !== "GET_PASSKEY_PROVIDER_STATE" &&1648    type !== "DECLINE_CARD_SAVE" &&1649    type !== "IS_CARD_DECLINED"1650  );1651}16521653function isAllowedCanaryWebhookUrl(value: string): boolean {1654  try {1655    const url = new URL(value);1656    if (url.protocol !== "https:") return false;16571658    const hostname = url.hostname.toLowerCase();1659    if (1660      hostname === "localhost" ||1661      hostname.endsWith(".localhost") ||1662      isPrivateIpv4(hostname) ||1663      isPrivateIpv6(hostname)1664    ) {1665      return false;1666    }16671668    return true;1669  } catch {1670    return false;1671  }1672}16731674function isPrivateIpv4(hostname: string): boolean {1675  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1676    return true;1677  }16781679  const octets = hostname.split(".").map((part) => Number(part));1680  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1681    return false;1682  }16831684  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1685}16861687function isPrivateIpv6(hostname: string): boolean {1688  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1689  // IPv4-mapped IPv6 literals embed a plain IPv4 address that the prefix1690  // list below can never match (WHATWG URL serializes [::ffff:192.168.0.1]1691  // as ::ffff:c0a8:1). Unwrap and test the embedded IPv4; unparseable mapped1692  // tails fail closed. (Codex Security 2026-08-04 LOW,1693  // ssrf.webhook-url-private-ip-filter.) DNS rebinding is out of scope for a1694  // one-shot host check.1695  const mapped = /^::ffff:(.+)$/.exec(normalized);1696  if (mapped) {1697    const tail = mapped[1] ?? "";1698    if (tail.includes(".")) return isPrivateIpv4(tail);1699    const parts = tail.split(":");1700    const [hi, lo] = parts;1701    if (1702      parts.length !== 2 ||1703      !hi ||1704      !lo ||1705      !/^[0-9a-f]{1,4}$/.test(hi) ||1706      !/^[0-9a-f]{1,4}$/.test(lo)1707    ) {1708      return true;1709    }1710    const octets = [1711      (Number.parseInt(hi, 16) >>> 8) & 0xff,1712      Number.parseInt(hi, 16) & 0xff,1713      (Number.parseInt(lo, 16) >>> 8) & 0xff,1714      Number.parseInt(lo, 16) & 0xff,1715    ];1716    return isPrivateIpv4(octets.join("."));1717  }1718  return (1719    normalized === "::1" ||1720    normalized.startsWith("fc") ||1721    normalized.startsWith("fd") ||1722    normalized.startsWith("fe80:")1723  );1724}