messages.ts

73.0 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 { isMessageSenderAllowed } 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 entryAllowsSender(entry: VaultEntry, sender: Partial<chrome.runtime.MessageSender>): boolean {211  if (sender.url?.startsWith("chrome-extension://") || sender.url?.startsWith("moz-extension://")) return true;212  if (sender.tab === undefined && sender.url === undefined) return false;213  const origin = attestedSenderOrigin(sender);214  if (!origin) return false;215  let hostname: string;216  try { hostname = new URL(origin).hostname; } catch { return false; }217  const domains = [entry.url, ...(entry.additionalUrls ?? [])]218    .map((url) => extractDomain(url ?? ""))219    .filter((domain): domain is string => Boolean(domain));220  return domains.includes(extractDomain(hostname) ?? "");221}222223function patchChangesEntryOrigin(patch: object): boolean {224  return Object.hasOwn(patch, "url") || Object.hasOwn(patch, "additionalUrls");225}226// Resolves once restoreFromSession() has run, so handlers see the correct227// post-restore unlock state. entry.ts registers this BEFORE the message228// handler so the onMessage listener is added synchronously at SW startup229// (MV3 requirement) while unlock-dependent handlers still wait for restore.230let restoreReady: Promise<void> = Promise.resolve();231232/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */233export function setRestoreReady(p: Promise<unknown>): void {234  restoreReady = p.then(() => undefined, () => undefined);235}236237export async function handleMessage(238  msg: Message,239  sender: Partial<chrome.runtime.MessageSender> = {}240): Promise<MessageResponse> {241  try {242    // Wait for session-restore to finish before reading any unlock/vault state.243    // On a cold SW start the popup's first message arrives while restore is244    // still in flight; without this gate IS_UNLOCKED would report locked (a245    // spurious lock screen) and the storage reads could race. The onMessage246    // listener itself is registered synchronously (entry.ts) so this gate, not247    // listener registration, is what absorbs the cold-start window.248    await restoreReady;249    // Validate sender — only allow messages from our extension pages/scripts.250    // `sender.id` is undefined for messages originating from extension UI251    // (popup/options), which is legitimate; reject only when it is defined252    // and does not match our extension id.253    if (254      sender.id !== undefined &&255      sender.id !== chrome.runtime.id256    ) {257      return { ok: false, error: "invalid_sender" };258    }259260    // PB-26-016: sender authorization is an exhaustive policy, not a261    // hand-maintained privileged denylist. A missing/unknown policy entry or a262    // background-only message fails closed before any handler runs.263    // Extension UI messages may legitimately omit sender.url. Resolve the264    // browser-attested extension origin only when a URL is present; this also265    // keeps test/runtime shims without getURL fail-closed for URL-bearing266    // senders instead of throwing before policy evaluation.267    const extensionOrigin = sender.url && typeof chrome.runtime.getURL === "function"268      ? chrome.runtime.getURL("")269      : "";270    if (!isMessageSenderAllowed(msg.type, sender, chrome.runtime.id, extensionOrigin)) {271      return { ok: false, error: "invalid_sender" };272    }273274    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {275      touchAutoLock();276    }277278    switch (msg.type) {279      case "CREATE_VAULT": {280        const { password } = msg.payload as { password: string };281        // Refuse to create a vault under an empty master password — the derived282        // key would be publicly known and the at-rest AES-GCM protection void283        // (audit HIGH; the CSV-import path previously passed ""). Length/strength284        // policy lives in the onboarding UI; this is the non-negotiable floor.285        if (typeof password !== "string" || password.length === 0) {286          return { ok: false, error: "invalid_payload" };287        }288        await vault.createVault(password);289        await setupAutoLock();290        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });291        onVaultUnlocked();292        return { ok: true };293      }294      case "CREATE_VAULT_FROM_ROOT_KEY": {295        const { password, rootKeyHex } = (msg.payload ?? {}) as {296          password?: unknown;297          rootKeyHex?: unknown;298        };299        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {300          return { ok: false, error: "invalid_payload" };301        }302303        try {304          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);305          await setupAutoLock();306          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });307          onVaultUnlocked();308          return { ok: true, vaultId };309        } catch (err) {310          return { ok: false, error: err instanceof Error ? err.message : String(err) };311        }312      }313      case "UNLOCK": {314        const { password } = msg.payload as { password: string };315        const ok = await vault.unlock(password);316        if (ok) {317          // KAT: verify the WebCrypto stack is healthy before the user relies on it.318          // Runs after unlock so latency is hidden behind the vault-load time.319          const kat = await runSelfTest();320          if (!kat.ok) {321            console.error("[Peach] Crypto self-test FAILED:", kat.error);322            await vault.lock();323            return { ok: false, error: "self_test_failed" };324          }325          await vault.updateSettings({ pinPreferred: false });326          await setupAutoLock();327          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });328          onVaultUnlocked();329          return { ok: true };330        }331        // Distinguish corruption from wrong password so the popup can offer332        // a history-restore path instead of falsely accusing the user of333        // mistyping (M7/COR-007).334        const failure = vault.consumeLastUnlockFailureReason();335        if (failure) {336          return {337            ok: false,338            error: "vault_corrupted",339            canRestoreFromHistory: true,340          } as MessageResponse;341        }342        return { ok: false };343      }344      case "UNLOCK_WITH_PIN": {345        const { pin } = (msg.payload ?? {}) as { pin?: unknown };346        if (typeof pin !== "string") return { ok: false, error: "invalid_payload" };347        const ok = await vault.unlockWithPin(pin);348        if (!ok) {349          const status = await vault.getPinUnlockStatus();350          if (status.configured && !status.available) {351            return {352              ok: false,353              error: status.attemptsRemaining === 0354                ? "pin_attempts_exceeded"355                : "pin_session_expired",356            };357          }358          return { ok: false };359        }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 "GET_PIN_STATUS":372        return { ok: true, data: await vault.getPinUnlockStatus() };373      case "VALIDATE_RECOVERY_WORDS": {374        const { words } = msg.payload as { words: string[] };375        const invalid = findInvalidWords(words);376        return { ok: true, data: { valid: invalid.length === 0, invalid } };377      }378      case "GET_RECOVERY_WORDS": {379        // Must be unlocked and have recovery set up (vault must be v2.12+).380        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };381        // LV-4: the recovery words re-derive the ROOT KEY — the highest-382        // value secret in the vault. A session unlock (which may be hours383        // old on a shared machine) is not enough; require a fresh password384        // proof, matching the 1Password/Bitwarden pattern for revealing385        // escrow material. EXEMPTION: the create-vault / rotation confirmation386        // window (peach_recovery_pending) shows the words immediately after387        // the user authenticated, and that confirmation UI has no password to388        // resend — skip the re-auth there only.389        if (!(await isRecoveryConfirmPending())) {390          const { password } = (msg.payload ?? {}) as { password?: string };391          if (typeof password !== "string" || !password) {392            return { ok: false, error: "password_required" };393          }394          if (!(await vault.verifyMainPassword(password))) {395            return { ok: false, error: "wrong_password" };396          }397        }398        try {399          const words = await vault.getRecoveryWords();400          return { ok: true, data: words };401        } catch {402          return { ok: false, error: "recovery_not_setup" };403        }404      }405      case "GET_RECOVERY_CONFIRM_PENDING":406        return { ok: true, data: await isRecoveryConfirmPending() };407      case "SET_RECOVERY_CONFIRM_PENDING":408        await setRecoveryConfirmPending();409        return { ok: true };410      case "CLEAR_RECOVERY_CONFIRM_PENDING":411        await clearRecoveryConfirmPending();412        return { ok: true };413      case "RECOVER_WITH_WORDS": {414        // User has lost their password but has their 12 recovery words.415        // We: (1) validate the words, (2) re-encrypt vault with new password.416        const { words, newPassword } = msg.payload as {417          words: string[];418          newPassword: string;419        };420        const stored = await vault.loadSlotA();421        if (!stored) return { ok: false, error: "no_vault" };422        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {423          return { ok: false, error: "recovery_not_setup" };424        }425        // Unwrap the root key from the recovery escrow.426        try {427          await vault.unwrapRootKeyForRecovery(428            stored.recovery_wrapped_root_key,429            stored.recovery_nonce ?? "",430            stored.recovery_tag ?? "",431            stored.recovery_salt,432            words433          );434        } catch {435          return { ok: false, error: "invalid_recovery_words" };436        }437        // Re-key: derive fresh salt + key from new password.438        const newSalt = vault.generateSalt();439        const newKey = await vault.deriveKey(newPassword, newSalt);440        // Re-wrap root key under the new password's derived key so the same441        // recovery words continue to work after the password change.442        await vault.rewrapRootKeyForPassword(newKey, newSalt);443        // Re-encrypt vault entries with the new key.444        await vault.changePasswordWithNewKey(newSalt, newKey);445        await setupAutoLock();446        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });447        return { ok: true };448      }449      case "LOCK":450        vault.lock();451        return { ok: true };452      case "IS_UNLOCKED":453        return { ok: true, data: vault.isUnlocked() };454      case "GET_VAULT_STATUS":455        return { ok: true, unlocked: vault.isUnlocked() };456      case "HAS_VAULT":457        return { ok: true, data: await vault.hasVault() };458      case "GET_ENTRIES":459        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };460        return { ok: true, data: vault.getEntries() };461      case "ADD_ENTRY": {462        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };463        const payload = msg.payload;464        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {465          return { ok: false, error: "invalid_payload" };466        }467        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);468        return { ok: true, data: entry };469      }470      case "BATCH_ADD_ENTRIES": {471        const payload = msg.payload as { entries?: unknown } | null | undefined;472        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {473          return { ok: false, error: "invalid_payload" };474        }475        if (!Array.isArray(payload.entries)) {476          return { ok: false, error: "invalid_payload" };477        }478        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);479        return { ok: true, data: added };480      }481      case "RESTORE_ENTRIES": {482        const payload = msg.payload as483          | { entries?: unknown; mode?: unknown; settings?: unknown }484          | null485          | undefined;486        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {487          return { ok: false, error: "invalid_payload" };488        }489        if (!Array.isArray(payload.entries)) {490          return { ok: false, error: "invalid_payload" };491        }492        if (payload.mode !== "replace" && payload.mode !== "merge") {493          return { ok: false, error: "invalid_payload" };494        }495        const summary = await vault.restoreEntries(496          payload.entries as Parameters<typeof vault.restoreEntries>[0],497          payload.mode498        );499        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {500          await vault.updateSettings(payload.settings as vault.VaultSettings);501        }502        return { ok: true, data: summary };503      }504      case "CLEAR_VAULT_ENTRIES": {505        await vault.clearVaultEntries("REPLACE_ALL");506        return { ok: true };507      }508      case "GET_VAULT_HISTORY": {509        const snapshots = await vault.getVaultHistory();510        return { ok: true, data: snapshots };511      }512      case "RESTORE_VAULT_SNAPSHOT": {513        const { snapshotId } = msg.payload as { snapshotId: string };514        const result = await vault.restoreVaultSnapshot(snapshotId);515        if (!result.ok) return { ok: false, error: result.error };516        broadcastToContentScripts({ type: "VAULT_LOCKED" });517        return { ok: true };518      }519      case "COUNT_DUPLICATES": {520        return { ok: true, data: vault.countDuplicates() };521      }522      case "DEDUPLICATE_ENTRIES": {523        const removed = await vault.deduplicateEntries();524        return { ok: true, data: removed };525      }526      case "UPDATE_ENTRY": {527        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;528        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {529          return { ok: false, error: "invalid_payload" };530        }531        const { id, patch } = payload;532        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {533          return { ok: false, error: "invalid_payload" };534        }535        const existingEntry = vault.getEntryById(id);536        if (!existingEntry) return { ok: false, error: "entry_not_found" };537        if ((patchChangesEntryOrigin(patch) || sender.tab !== undefined || sender.url !== undefined) && !entryAllowsSender(existingEntry, sender)) {538          return { ok: false, error: "origin_binding_required" };539        }540        // Single enforcement point for the Canary Entries Pro gate. Only541        // gates the transition into a canary entry — clearing/disabling a542        // canary (`canary: undefined`) is always allowed, so existing543        // canary entries remain manageable.544        const incomingCanary = (patch as { canary?: unknown }).canary;545        if (incomingCanary && typeof incomingCanary === "object") {546          const existing = vault.getEntryById(id);547          if (!existing?.canary) {548            const gate = await requirePro("canary_entry");549            if (!gate.allowed) return { ok: false, error: "pro_required" };550          }551        }552        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);553        return { ok: true };554      }555      case "ADD_ADDITIONAL_URL": {556        const { id, url } = msg.payload as { id: string; url: string };557        const trimmed = typeof url === "string" ? url.trim() : "";558        if (!trimmed) return { ok: false, error: "url_required" };559        const existing = vault.getEntryById(id);560        if (!existing) return { ok: false, error: "entry_not_found" };561        if (!entryAllowsSender(existing, sender)) return { ok: false, error: "origin_binding_required" };562        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };563        const merged = [...(existing.additionalUrls ?? []), trimmed];564        await vault.updateEntry(id, { additionalUrls: merged });565        return { ok: true };566      }567      case "DELETE_ENTRY": {568        const { id } = msg.payload as { id: string };569        await vault.deleteEntry(id);570        return { ok: true };571      }572      case "GET_DELETED_ENTRIES":573        return { ok: true, data: vault.getDeletedEntries() };574      case "RESTORE_ENTRY": {575        const { id } = msg.payload as { id: string };576        await vault.restoreEntry(id);577        return { ok: true };578      }579      case "PURGE_ENTRY": {580        const { id } = msg.payload as { id: string };581        await vault.purgeEntry(id);582        return { ok: true };583      }584      case "PURGE_EXPIRED_TRASH": {585        const { retentionMs } = msg.payload as { retentionMs: number };586        const purged = await vault.purgeExpiredTrash(retentionMs);587        return { ok: true, data: purged };588      }589      case "SAVE_NOTE": {590        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };591        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };592        const now = Date.now();593        if (id) {594          const existing = vault.getEntryById(id);595          if (!existing) return { ok: false, error: "not_found" };596          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });597          return { ok: true, data: vault.getEntryById(id) };598        } else {599          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt600          // (EntryDraft omits both), so passing them was the only reason the601          // `as any` cast existed. Dropping them makes the call type-check.602          const entry = await vault.addEntry({603            type: "note",604            title: title || "Untitled",605            notes: body,606          });607          return { ok: true, data: entry };608        }609      }610      case "DELETE_NOTE": {611        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };612        const { id } = msg.payload as { id: string };613        await vault.deleteEntry(id);614        return { ok: true };615      }616      case "GET_NOTES": {617        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };618        const notes = vault.getEntries().filter(619          (e) => e.type === "note" && !e.deletedAt620        );621        return { ok: true, data: notes } as MessageResponse;622      }623      case "SEARCH_VAULT": {624        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };625        // AUD-002: shape-validate the payload before calling string methods.626        // A raw cast lets a malformed message crash the handler with TypeError.627        const { query } = (msg.payload ?? {}) as { query?: unknown };628        if (typeof query !== "string") {629          return { ok: false, error: "invalid_payload" };630        }631        const q = query.toLowerCase();632        const searchResults = vault.getEntries().filter(633          (e) =>634            !e.deletedAt &&635            (e.title.toLowerCase().includes(q) ||636              e.notes?.toLowerCase().includes(q) ||637              e.username?.toLowerCase().includes(q))638        );639        return { ok: true, data: searchResults } as MessageResponse;640      }641      case "AUTOFILL_QUERY": {642        if (!vault.isUnlocked()) {643          return { ok: false, error: "vault_locked" };644        }645        let { includeAll } = msg.payload as { includeAll?: boolean };646        const { domain, kind, userGesture } = msg.payload as {647          domain: string;648          kind?: "login" | "card" | "totp";649          userGesture?: boolean;650        };651        // MV-2: the vault-wide inventory (every title/username/email/url)652        // may only leave the background on an explicit user gesture — the653        // user opening the search affordance — never on passive form focus.654        // userGesture is self-declared by our own content script; the value655        // of this gate is that PASSIVE code paths (which never set it)656        // cannot ship the inventory, shrinking what a compromised page that657        // merely triggers focus events can observe.658        if (includeAll && userGesture !== true) {659          includeAll = false;660        }661        // kind="card": return saved cards as compact summaries for the662        // inline card silver platter. Cards are not domain-scoped — every663        // saved card is a candidate on every checkout page — so domain is664        // ignored when kind === "card".665        if (kind === "card") {666          const cards = vault.getEntries().filter((e) => e.type === "card");667          return {668            ok: true,669            data: cards.map((e) => ({670              id: e.id,671              title: e.cardNickname || e.title,672              cardholderName: e.cardholderName,673              last4: e.last4,674              expMonth: e.expMonth,675              expYear: e.expYear,676              network: e.network,677            })),678          };679        }680        if (kind === "totp") {681          const matches = (682            includeAll683              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")684              : vault.queryDomain(domain)685          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));686          return {687            ok: true,688            data: matches.map((e) => ({689              id: e.id,690              title: e.title,691              username: e.username,692              email: e.email,693              url: e.url,694              hasTotp: true,695            })),696          };697        }698        // The inline selector fills username+password into a form. Passkey-699        // only entries have no password to fill; sign-in for those goes700        // through the WebAuthn path instead. Filter them out everywhere so701        // the user doesn't see four "GitHub" rows that mostly do nothing.702        // Notes and cards never belonged here either.703        const matches = (704          includeAll705            ? vault706                .getEntries()707                .filter((entry) => entry.type !== "note" && entry.type !== "card")708            : vault.queryDomain(domain)709        ).filter((entry) => !isPasskeyOnly(entry));710        return {711          ok: true,712          data: matches.map((e) =>713            includeAll714              ? {715                  id: e.id,716                  title: e.title,717                  // username/email/url shipped so the inline popup's search718                  // affordance can match on them, not just titles. No secrets719                  // cross the boundary — same shape as the domain-matched720                  // response below minus hasTotp (which the search list721                  // doesn't surface).722                  username: e.username,723                  email: e.email,724                  url: e.url,725                  hasPasskey: e.passkey !== undefined,726                }727              : {728                  id: e.id,729                  title: e.title,730                  username: e.username,731                  email: e.email,732                  url: e.url,733                  hasTotp: Boolean(e.totp),734                  hasPasskey: e.passkey !== undefined,735                }736          ),737        };738      }739      case "GET_ENTRY_FOR_FILL": {740        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };741        const { id, explicitSummon } = msg.payload as {742          id: string;743          explicitSummon?: boolean;744        };745        const entry = vault.getEntryById(id);746        if (!entry) return { ok: false, error: "entry_not_found" };747        // Passkey-only entries (passkey credential, no password) cannot be748        // filled into a form — sign-in goes through the WebAuthn path. A749        // login that ALSO has a passkey is still fillable for its password.750        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };751752        // MV-1: re-validate the entry against the requesting frame's origin.753        // sender.url / sender.tab.url are browser-attested — a page cannot754        // forge them. PB-26-005: the FRAME url (sender.url) is authoritative755        // for an all_frames content script; the top-frame tab.url would756        // misattribute a cross-origin iframe's request to the top page. When757        // the request does not come from a tab at all (popup surfaces use758        // GET_ENTRY_FOR_EDIT, not this), refuse.759        if (sender.tab !== undefined || sender.url !== undefined) {760          let senderDomain: string | null = null;761          try {762            const rawUrl = sender.url ?? sender.tab?.url ?? "";763            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;764          } catch {765            senderDomain = null;766          }767          if (!senderDomain) return { ok: false, error: "origin_unverified" };768769          const entryDomains = new Set<string>();770          const primary = extractDomain(entry.url ?? "");771          if (primary) entryDomains.add(primary);772          for (const extra of entry.additionalUrls ?? []) {773            const d = extractDomain(extra);774            if (d) entryDomains.add(d);775          }776777          // explicitSummon=true means the user actively picked this entry778          // from the cross-domain search affordance — an intentional779          // off-domain fill. Passive fill paths must stay domain-bound.780          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {781            // Domain mismatch — refuse silently (no oracle about which ids exist).782            return { ok: false, error: "entry_not_found" };783          }784        }785        // Strip the passkey credential AND the raw base32 TOTP seed from the786        // response. Content scripts never need either: the private key is the787        // authenticator's, and handing over the TOTP seed would let a788        // compromised content script mint valid codes indefinitely (SEV-3-C).789        // Generate the *current* 6-digit code here in the background and send790        // only that, plus the seconds left so the UI can render a countdown.791        // Also drop passwordHistory: filling needs only the *current* password.792        // Handing every past password to a content script during passive793        // autofill on an arbitrary page would widen the blast radius of a794        // compromised page far beyond the one credential being filled.795        const {796          passkey: _strippedPasskey,797          totp: seed,798          totpAlgorithm,799          totpDigits,800          totpPeriod,801          passwordHistory: _ph,802          ...safeEntry803        } = entry;804        let totpCode: string | undefined;805        let totpRemaining: number | undefined;806        if (seed) {807          try {808            // PCH-01-019: honour stored algorithm/digits/period (defaults apply809            // when these are undefined, i.e. RFC-default bare-seed entries).810            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);811            totpCode = generated.code;812            totpRemaining = generated.remaining;813          } catch {814            totpCode = undefined;815          }816        }817        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };818      }819      // Trusted full-entry fetch for Peach's own inline-popup surfaces that820      // genuinely need the raw TOTP seed: the edit form (which re-saves the821      // seed and would otherwise wipe it) and nothing else. Unlike822      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside823      // the inline popup, never during passive autofill on an arbitrary page.824      // The passkey credential is still stripped — the edit form never touches it.825      case "GET_ENTRY_FOR_EDIT": {826        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };827        const { id, explicitSummon } = msg.payload as {828          id: string;829          explicitSummon?: boolean;830        };831        const entry = vault.getEntryById(id);832        if (!entry) return { ok: false, error: "entry_not_found" };833834        // PCH-01-006: re-validate the browser-attested sender origin, mirroring835        // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and836        // full password history — at least as sensitive as the fill response — so837        // the boundary must be enforced here, not only by UI reachability. Today838        // the sole caller is the popup (no sender.tab, so this is a structural839        // no-op), but a future tab-context caller or an id leak would otherwise840        // inherit a full-credential oracle. Unlike the fill path we SKIP (not841        // refuse) when no sender domain resolves, to keep the popup caller working.842        // PB-26-005: the frame url (sender.url) is authoritative over the843        // top-frame sender.tab.url — mirrors the fill path.844        if (sender.tab !== undefined || sender.url !== undefined) {845          let senderDomain: string | null = null;846          try {847            const rawUrl = sender.url ?? sender.tab?.url ?? "";848            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;849          } catch {850            senderDomain = null;851          }852          if (senderDomain) {853            const entryDomains = new Set<string>();854            const primary = extractDomain(entry.url ?? "");855            if (primary) entryDomains.add(primary);856            for (const extra of entry.additionalUrls ?? []) {857              const d = extractDomain(extra);858              if (d) entryDomains.add(d);859            }860            if (explicitSummon !== true && !entryDomains.has(senderDomain)) {861              return { ok: false, error: "entry_not_found" }; // no id oracle862            }863          }864        }865866        const { passkey: _passkey, ...safeEntry } = entry;867        return { ok: true, data: safeEntry };868      }869      case "COPY": {870        // AUD-002: shape-validate the payload before passing to the clipboard871        // helper. A raw cast lets a malformed message reach the clipboard API872        // with a non-string and throw.873        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {874          text?: unknown;875          label?: unknown;876          alreadyWritten?: unknown;877        };878        if (typeof text !== "string" || typeof label !== "string") {879          return { ok: false, error: "invalid_payload" };880        }881        await copyToClipboard(text, label, Boolean(alreadyWritten));882        return { ok: true, clearSeconds: getEffectiveClearSeconds() };883      }884      case "CHECK_ALL_BREACHES": {885        const allEntries = vault.getEntries();886        const results: Record<string, number> = {};887        for (const entry of allEntries) {888          if (entry.type === "note") continue;889          if (!entry.password) continue;890          results[entry.id] = await vault.checkBreach(entry.password);891          // Small delay — be a good citizen to the HIBP API892          await new Promise((r) => setTimeout(r, 200));893        }894        // Persist any non-zero counts back to entries895        for (const [id, count] of Object.entries(results)) {896          const entry = vault.getEntryById(id);897          if (entry && (entry.breach ?? 0) !== count) {898            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });899          }900        }901        return { ok: true, data: results };902      }903      case "GET_SETTINGS":904        return { ok: true, data: await vault.ensureSettingsLoaded() };905      case "UPDATE_SETTINGS": {906        const patch = msg.payload;907        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {908          return { ok: false, error: "invalid_payload" };909        }910        await vault.updateSettings(patch as vault.VaultSettings);911        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {912          await setupAutoLock();913          if (vault.isUnlocked()) touchAutoLock();914        }915        return { ok: true };916      }917      case "SETUP_PIN": {918        const { currentPassword, pin } = (msg.payload ?? {}) as {919          currentPassword?: unknown;920          pin?: unknown;921        };922        if (typeof currentPassword !== "string" || typeof pin !== "string") {923          return { ok: false, error: "invalid_payload" };924        }925        return (await vault.setupPinUnlock(currentPassword, pin))926          ? { ok: true }927          : { ok: false, error: "incorrect_current_password" };928      }929      case "DISABLE_PIN": {930        const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown };931        if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" };932        return (await vault.disablePinUnlock(currentPassword))933          ? { ok: true }934          : { ok: false, error: "incorrect_current_password" };935      }936      case "GET_PENDING_PASSKEY":937        return { ok: true, data: await getPendingPasskeyRequest() };938      case "APPROVE_PASSKEY": {939        const { requestId } = msg.payload as { requestId: number };940        await resolvePendingPasskeyRequest(requestId, true);941        return { ok: true };942      }943      case "DENY_PASSKEY": {944        const { requestId } = msg.payload as { requestId: number };945        await resolvePendingPasskeyRequest(requestId, false);946        return { ok: true };947      }948      case "GET_PASSKEY_PROVIDER_STATE":949        return { ok: true, data: await getPasskeyProviderState() };950      case "SET_PASSKEY_PROVIDER_ENABLED": {951        const { enabled } = msg.payload as { enabled: boolean };952        // Disabling is always free; gating fires only when a free user is953        // trying to turn passkey interception on.954        if (enabled) {955          const gate = await requirePro("passkeys");956          if (!gate.allowed) return { ok: false, error: "pro_required" };957        }958        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };959      }960      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS961      // endpoint. Intentional product behavior — users configure their own962      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private963      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-964      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to965      // users that the entry title leaves the device when the canary fires.966      case "FIRE_CANARY_PING": {967        // Canary alert fires unconditionally for any entry with canary: true.968        // The Pro gate only governs creation/flagging of canary entries; once969        // an entry is flagged, the alert path is a security property and must970        // never be license-gated.971        const { webhookUrl, entryTitle, trigger } = msg.payload as {972          webhookUrl: string;973          entryTitle: string;974          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";975        };976        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {977          return { ok: false, error: "invalid_webhook_url" };978        }979        // LV-3: debounce non-test pings per (webhook, entry) so a page that980        // strobes focus/fill events can't turn the canary into a request981        // firehose at the user's endpoint. Test pings are exempt — they are982        // explicit user clicks in the settings UI and are awaited for983        // feedback. The FIRST ping in a window always goes out, so the984        // dead-man's-switch property (canary fires on access) is preserved;985        // only repeats within the window are coalesced.986        if (trigger !== "test") {987          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;988          const stored = await chrome.storage.local.get(rlKey);989          const last = (stored as Record<string, unknown>)[rlKey];990          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {991            return { ok: true, data: { rateLimited: true } };992          }993          await chrome.storage.local.set({ [rlKey]: Date.now() });994        }995        const body = JSON.stringify({996          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",997          entry: entryTitle,998          trigger,999          timestamp: new Date().toISOString(),1000          source: "peach-extension",1001        });1002        if (trigger === "test") {1003          // Permitted outbound fetch: user-configured canary alert endpoint1004          // (validated by isAllowedCanaryWebhookUrl above). This is the1005          // only non-HIBP outbound call in the extension — see1006          // Projects.md §3.7. Test pings are awaited so the UI can show1007          // success/failure.1008          try {1009            const res = await fetch(webhookUrl, {1010              method: "POST",1011              headers: { "Content-Type": "application/json" },1012              body,1013            });1014            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1015          } catch (err) {1016            return { ok: false, error: err instanceof Error ? err.message : "network_error" };1017          }1018        }1019        // Non-test triggers are fire-and-forget1020        fetch(webhookUrl, {1021          method: "POST",1022          headers: { "Content-Type": "application/json" },1023          body,1024        }).catch(() => {});1025        return { ok: true };1026      }1027      case "ACTIVATE_LICENSE": {1028        const { key } = msg.payload as { key: string };1029        const licenseInfo = await activateLicense(key);1030        return { ok: true, data: licenseInfo };1031      }1032      case "GET_LICENSE": {1033        const licenseInfo = await getLicenseInfo();1034        return { ok: true, data: licenseInfo };1035      }1036      case "GET_LICENSE_KEY": {1037        const key = await getLicenseKey();1038        return { ok: true, data: key };1039      }1040      case "DEACTIVATE_LICENSE": {1041        await deactivateLicense();1042        return { ok: true };1043      }1044      case "SHOULD_PLAY_CELEBRATION": {1045        const should = await shouldPlayCelebration();1046        return { ok: true, data: should };1047      }1048      case "MARK_CELEBRATION_PLAYED": {1049        await markCelebrationPlayed();1050        return { ok: true };1051      }1052      case "GET_CODEX_VAULT_DATA": {1053        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1054        // popup navigates to the License section without further coordination.1055        // Also privileged-page-gated (PB-26-001), and recoveryWords inside the1056        // snapshot additionally require a fresh master-password proof.1057        const gate = await requirePro("codex");1058        if (!gate.allowed) return { ok: false, error: "pro_required" };1059        const { password } = (msg.payload ?? {}) as { password?: string };1060        return await handleGetCodexVaultData(password);1061      }1062      case "ESTIMATE_CODEX_PAGES": {1063        const gate = await requirePro("codex");1064        if (!gate.allowed) return { ok: false, error: "pro_required" };1065        return await handleEstimateCodexPages();1066      }1067      case "RESTORE_FROM_CODEX": {1068        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1069        // be able to restore a vault that was printed by a Pro user.1070        // DO NOT add a Pro gate here.1071        const payload = msg.payload as CodexRestorePayload;1072        return await handleRestoreFromCodex(payload);1073      }1074      case "OPEN_PRO_GATE": {1075        // Content script requests: open popup and navigate to License section.1076        const { feature } = (msg.payload ?? {}) as { feature?: string };1077        if (chrome.storage.session) {1078          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1079        }1080        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1081        return { ok: true };1082      }1083      case "OPEN_POPUP": {1084        // Content script asks to open the trusted extension popup — used by the1085        // inline locked bubble so the master password is entered in the popup,1086        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1087        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1088        // toolbar icon. The badge already signals Peach needs attention.1089        //1090        // Set a session flag so the popup knows it was opened for inline unlock1091        // and should close itself once the vault is unlocked (returning the user1092        // to the inline autofill selector on the page).1093        if (chrome.storage.session) {1094          await chrome.storage.session.set({ peach_inline_unlock: true });1095        }1096        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1097        return { ok: true };1098      }1099      case "OPEN_DETACHED_POPUP": {1100        // A window created by the action popup and then orphaned with1101        // window.close() is cascaded shut by Chrome, so the file-picker1102        // flows (OS dialogs that dismiss the popup on focus loss) ask the SW1103        // to open the standalone window instead — the SW has no window to be1104        // associated with. The query string is allowlisted so this can never1105        // open an arbitrary URL.1106        const { route } = (msg.payload ?? {}) as { route?: string };1107        const search = route === "peachscript"1108          ? "?restore=peachscript"1109          : route === "csv"1110            ? "?restore=csv"1111            : route === "codex-pdf"1112              ? "?codex=pdf"1113              : null;1114        if (!search) return { ok: false, error: "bad_route" };1115        try {1116          const popupHtml =1117            chrome.runtime.getManifest().action?.default_popup ?? "src/popup/index.html";1118          await chrome.windows.create({1119            url: chrome.runtime.getURL(`${popupHtml}${search}`),1120            type: "popup",1121            width: 320,1122            height: 550,1123          });1124          return { ok: true, data: { detached: true } };1125        } catch {1126          return { ok: false };1127        }1128      }1129      case "GET_IDENTITIES": {1130        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1131        return { ok: true, data: vault.getIdentities() };1132      }1133      case "TOUCH_AUTO_LOCK": {1134        // touchAutoLock() is already called by shouldRefreshAutoLock above;1135        // this case just gives the popup a typed message to keep the session alive.1136        return { ok: true };1137      }1138      case "GET_ADVANCED_HEALTH_REPORT": {1139        const gate = await requirePro("advanced_health");1140        if (!gate.allowed) return { ok: false, error: "pro_required" };1141        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1142        const report = await buildAdvancedHealthReport(vault.getEntries());1143        return { ok: true, data: report };1144      }1145      case "IS_DURESS_ENABLED": {1146        const enabled = await vault.isDuressEnabled();1147        return { ok: true, data: enabled };1148      }1149      case "SETUP_DURESS": {1150        // Single enforcement point for the Duress Vault Pro gate. Free users1151        // who somehow reach this handler are rejected here; the popup also1152        // pre-checks isPro() to avoid showing the setup form to free users,1153        // but server-side is the actual security boundary.1154        const gate = await requirePro("duress_vault");1155        if (!gate.allowed) return { ok: false, error: "pro_required" };1156        // MV3 service workers restart after inactivity, losing the in-memory1157        // derived key. Detect this before calling setupDuress so the popup1158        // can show a meaningful prompt to re-lock and re-unlock.1159        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1160        const { duressPassword } = msg.payload as { duressPassword: string };1161        await vault.setupDuress(duressPassword);1162        return { ok: true };1163      }1164      case "DISABLE_DURESS": {1165        await vault.disableDuress();1166        return { ok: true };1167      }1168      case "VERIFY_MAIN_PASSWORD": {1169        const { password } = msg.payload as { password: string };1170        const ok = await vault.verifyMainPassword(password);1171        return { ok: true, data: ok };1172      }1173      case "CHANGE_PASSWORD": {1174        const { currentPassword, newPassword } = msg.payload as {1175          currentPassword: string;1176          newPassword: string;1177        };1178        const changed = await vault.changePassword(currentPassword, newPassword);1179        return changed1180          ? { ok: true }1181          : { ok: false, error: "incorrect_current_password" };1182      }1183      case "GET_SITE_PASSWORD_POLICY": {1184        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1185        if (!tab?.id) return { ok: true, data: null };1186        try {1187          const response = await chrome.tabs.sendMessage(tab.id, {1188            type: "GET_SITE_PASSWORD_POLICY",1189          });1190          return (response as MessageResponse) ?? { ok: true, data: null };1191        } catch {1192          return { ok: true, data: null };1193        }1194      }1195      case "RECORD_MANUAL_SUMMON": {1196        const { domain } = msg.payload as { domain: string };1197        const settings = vault.getSettings();1198        const existing = settings.manualSummonDomains?.[domain];1199        const now = Date.now();1200        await vault.updateSettings({1201          manualSummonDomains: {1202            ...settings.manualSummonDomains,1203            [domain]: {1204              firstSummonedAt: existing?.firstSummonedAt ?? now,1205              summonCount: (existing?.summonCount ?? 0) + 1,1206              lastSummonedAt: now,1207            },1208          },1209        });1210        return { ok: true };1211      }1212      case "DECLINE_CARD_SAVE": {1213        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1214        await vault.declineCardSaveOffer(last4, expMonth, expYear);1215        return { ok: true };1216      }1217      case "IS_CARD_DECLINED": {1218        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1219        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1220        return { ok: true, data: declined };1221      }1222      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1223        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1224          rpId?: string;1225          rpName?: string;1226          userName?: string;1227          userDisplayName?: string;1228        };1229        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1230        return await initiateFirefoxPasskeyCreate({1231          rpId,1232          rpName: rpName ?? rpId,1233          userName,1234          userDisplayName,1235        }, attestedSenderOrigin(sender));1236      }12371238      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1239        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1240        if (!payload) return { ok: false, error: "missing_payload" };1241        return await completeFirefoxPasskeyCreate(payload);1242      }12431244      case "PASSKEY_OFFER_DECLINE": {1245        const { domain } = (msg.payload ?? {}) as { domain?: string };1246        const origin = attestedSenderOrigin(sender);1247        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1248        await recordPasskeyOfferDecline(domain);1249        return { ok: true };1250      }12511252      case "GET_PASSKEY_OFFER_DECLINED": {1253        const { domain } = (msg.payload ?? {}) as { domain?: string };1254        const origin = attestedSenderOrigin(sender);1255        if (!domain || !origin || !isValidRpId(domain, origin)) return { ok: false, error: "invalid_domain" };1256        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1257      }12581259      case "PASSKEY_HAS_CREDENTIALS": {1260        const payload = msg.payload as {1261          rpId?: string;1262          allowCredentials?: Array<{ id: string; type?: string }>;1263        } | undefined;1264        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1265        return await handlePasskeyHasCredentials({1266          rpId: payload.rpId,1267          allowCredentials: payload.allowCredentials ?? [],1268        }, attestedSenderOrigin(sender));1269      }12701271      case "PASSKEY_CREATE": {1272        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1273        if (!payload?.rpId || !payload?.userName) {1274          return { ok: false, error: "rpid_and_username_required" };1275        }1276        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1277      }12781279      case "PASSKEY_GET": {1280        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1281        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1282        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1283      }12841285      case "PASSKEY_AUTH_RESPONSE": {1286        const { requestId, approved } = (msg.payload ?? {}) as {1287          requestId?: string | number;1288          approved?: boolean;1289        };1290        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1291          return { ok: false, error: 'requestId and approved required' };1292        }1293        await resolvePendingPasskeyRequest(Number(requestId), approved);1294        return { ok: true };1295      }12961297      case "GET_PASSKEY_FOR_DOMAIN": {1298        const { domain } = (msg.payload ?? {}) as { domain?: string };1299        if (!domain) return { ok: false, error: "domain_required" };1300        // Scope to the caller's own origin: a page may only ask about passkeys1301        // for a domain it actually owns, so an arbitrary page cannot enumerate1302        // which sites the user holds passkeys for or read the username (audit MEDIUM).1303        const origin = attestedSenderOrigin(sender);1304        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1305        if (!vault.isUnlocked()) return { ok: true, data: null };1306        const match = vault1307          .getEntries()1308          .find((entry) => entry.passkey?.rpId === domain);1309        if (!match || !match.passkey) return { ok: true, data: null };1310        // Slim shape — only the fields State 11 needs. Never expose private1311        // key material, even though this is locked behind isUnlocked.1312        return {1313          ok: true,1314          data: {1315            rpId: match.passkey.rpId,1316            userName: match.passkey.userName,1317            browser: match.passkey.browser,1318          },1319        };1320      }13211322      case "DESTROY_VAULT": {1323        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1324        // storage.local.clear() wipes every Peach key (slots, settings, license,1325        // onboarded flag, history, sync state, declined cards, recall, etc.);1326        // session.clear() wipes pending passkey requests + pro-notice queues.1327        // Caller (Panic.tsx) handles UI navigation back to onboarding.1328        //1329        // The Pro license is the one thing that must survive: the user paid for1330        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1331        // Capture it before the clear and restore it after. peach_pro_celebrated1332        // rides along so the Pro celebration doesn't replay on the next unlock.1333        const preserved = await chrome.storage.local.get([1334          "peach_license",1335          "peach_pro_celebrated",1336        ]);1337        vault.lock();1338        await storageClear();1339        await vault.clearVaultHistory();1340        const toRestore: Record<string, unknown> = {};1341        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1342        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1343        if (Object.keys(toRestore).length > 0) {1344          await chrome.storage.local.set(toRestore);1345        }1346        if (chrome.storage.session) {1347          await chrome.storage.session.clear();1348        }1349        await clearRecoveryConfirmPending();1350        return { ok: true };1351      }13521353      case "GET_IDENTITY_SUGGESTIONS": {1354        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1355        const entries = vault.getEntries();1356        const suggestions = buildIdentitySuggestions(entries);1357        return { ok: true, data: { suggestions } };1358      }1359      case "ML_INIT":1360        return { ok: true };13611362      case "ML_PREDICT_BATCH": {1363        // AUD-002: shape-validate before forwarding to the ML helper.1364        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1365        if (!Array.isArray(featuresArray)) {1366          return { ok: false, error: "invalid_payload" };1367        }1368        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1369      }13701371      // ── Vault sync (v3) ───────────────────────────────────────────────1372      // Returns the public-facing local identity needed by the popup to1373      // drive Phase-1 audio pairing. The private long-term key never1374      // leaves the background.1375      case "GET_LOCAL_IDENTITY": {1376        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1377        // Pro license from an already-Pro peer (at least one device must be Pro).1378        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1379        // Identity derives from the stable root key, not the password-derived1380        // key, so pairing survives a master-password change (SEV-2-B).1381        const masterKeyHex = vault.getRootKeyHex();1382        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1383        const masterKey = unhexBytes(masterKeyHex);1384        try {1385          const identity = await buildLocalIdentity(masterKey);1386          // If this device is Pro, advertise the signed license so the peer can1387          // activate it after SAS confirmation — pairing carries Pro across.1388          if (await isProUser()) {1389            const license = await getLicenseKey();1390            if (license) (identity as { license?: string }).license = license;1391          }1392          return { ok: true, data: identity };1393        } finally {1394          masterKey.fill(0);1395        }1396      }13971398      case "LIST_PAIRED_DEVICES": {1399        const devices = await listPairedDevicesV3();1400        return { ok: true, data: { devices } };1401      }14021403      case "RENAME_PAIRED_DEVICE": {1404        const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string };1405        if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") {1406          return { ok: false, error: "invalid_payload" };1407        }1408        await renamePairedDeviceV3(deviceId, name);1409        return { ok: true };1410      }14111412      case "UNPAIR_DEVICE": {1413        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1414        if (typeof deviceId !== "string" || !deviceId) {1415          return { ok: false, error: "invalid_payload" };1416        }1417        // Removing a device REVOKES it rather than just dropping the local1418        // row: a plain removal is undone the moment any other peer vouches it1419        // back through a manifest, which is exactly what the relay makes easy.1420        await revokeDeviceByIdV3(deviceId, await getOrCreateDeviceId());1421        // Sync against the remaining hosts — the unpaired device no longer1422        // matters but the next alarm tick is up to ten minutes away.1423        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1424        return { ok: true };1425      }14261427      case "RENAME_LOCAL_DEVICE": {1428        const { name } = (msg.payload ?? {}) as { name?: string };1429        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1430        await setDeviceNameV3(name);1431        return { ok: true };1432      }14331434      // ── Relay pairing ─────────────────────────────────────────────────────1435      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1436      // session runs in the background; the SAS and the terminal result reach1437      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1438      case "START_ADOPTION_SOURCE": {1439        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1440        if (isRelayAdoptionSourceInFlight()) {1441          return { ok: false, error: "adoption_source_in_progress" };1442        }1443        try {1444          return { ok: true, data: await startRelayAdoptionSource() };1445        } catch (error) {1446          return {1447            ok: false,1448            error: error instanceof Error ? error.message : "adoption_source_failed",1449          };1450        }1451      }14521453      // Onboarding receiver — empty extension shows a QR, phone scans and1454      // sends the vault. The popup supplies the local-only password here so1455      // the background can wrap the adopted root key at rest without ever1456      // asking the user to retype it.1457      case "START_ADOPTION_RECEIVER": {1458        if (isRelayAdoptionSourceInFlight()) {1459          return { ok: false, error: "adoption_receiver_in_progress" };1460        }1461        const password = (msg.payload as { password?: unknown } | undefined)?.password;1462        if (typeof password !== "string" || password.length === 0) {1463          return { ok: false, error: "invalid_payload" };1464        }1465        try {1466          return { ok: true, data: await startRelayAdoptionReceiver(password) };1467        } catch (error) {1468          return {1469            ok: false,1470            error: error instanceof Error ? error.message : "adoption_receiver_failed",1471          };1472        }1473      }14741475      // Popup→bg counterpart to ADOPTION_SOURCE_SAS (receiver flow).1476      // The receiver now auto-accepts the SAS (both sides derive it from the1477      // same Noise handshake hash, so the codes match by construction) so1478      // the popup never has a SAS screen to tap on. The id round-trips the1479      // same way so a stale late response can't approve the wrong session.1480      // Popup→bg counterpart for the source flow: Confirm/Cancel on the1481      // source's SAS screen.14821483      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1484      // on the source's SAS screen. The id round-trips the same way so a stale1485      // late response can't approve the wrong session.1486      case "SOURCE_SAS_DECISION": {1487        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1488        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1489          return { ok: false, error: "invalid_payload" };1490        }1491        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1492      }14931494      case "CANCEL_ADOPTION_SOURCE": {1495        cancelRelayAdoptionSource();1496        return { ok: true };1497      }14981499      case "TRIGGER_SYNC": {1500        const payload = (msg.payload ?? {}) as {1501          reason?: "vault_change" | "foreground" | "manual";1502          force?: boolean;1503        };1504        const reason = payload.reason ?? "foreground";15051506        void triggerSyncIfReachable({ reason, force: payload.force === true });1507        return { ok: true };1508      }15091510      case "GET_SYNC_STATE": {1511        return { ok: true, data: getSyncState() };1512      }15131514      case "GET_SYNC_SETTINGS": {1515        return { ok: true, data: await getSyncSettings() };1516      }15171518      case "SET_SYNC_SETTINGS": {1519        const payload = (msg.payload ?? {}) as {1520          mode?: unknown;1521          relayUrl?: unknown;1522        };1523        try {1524          // A custom relay URL implies private mode; Peach's own relay stays1525          // public. See setRelayUrl.1526          if (payload.relayUrl !== undefined) {1527            if (typeof payload.relayUrl !== "string") {1528              return { ok: false, error: "invalid_relay_url" };1529            }1530            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1531          }1532          if (payload.mode !== undefined) {1533            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1534              return { ok: false, error: "invalid_sync_mode" };1535            }1536            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1537          }1538          return { ok: true, data: await getSyncSettings() };1539        } catch (error) {1540          return {1541            ok: false,1542            error: error instanceof Error ? error.message : "invalid_relay_url",1543          };1544        }1545      }15461547      case "GET_SYNC_ALERTS": {1548        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1549        const alerts = await getPendingSyncAlerts();1550        // The popup reads on open and acknowledges with consume:true after1551        // rendering, so a popup crash between read and render doesn't lose1552        // the alerts.1553        if (consume) await clearPendingSyncAlerts();1554        return { ok: true, data: alerts };1555      }15561557      case "GET_PENDING_VOUCHED_DEVICES": {1558        return { ok: true, data: await listPendingVouchedDevices() };1559      }1560      case "CONFIRM_VOUCHED_DEVICE": {1561        const { deviceId } = msg.payload as { deviceId: string };1562        const pending = await getPendingVouchedDevice(deviceId);1563        if (!pending) return { ok: false, error: "not_pending" };1564        // Last gate before a vouched device becomes a sync peer. A queue entry1565        // can predate the revocation that names it, so revocation is re-checked1566        // here rather than trusted to have swept the queue.1567        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {1568          await removePendingVouchedDevice(deviceId);1569          return { ok: false, error: "device_revoked" };1570        }1571        await upsertPairedDeviceV3({1572          deviceId: pending.deviceId,1573          deviceName: pending.deviceName,1574          deviceType:1575            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1576          longTermPublicKeyHex: pending.longTermPublicKeyHex,1577          signingPublicKeyHex: pending.signingPublicKeyHex,1578          wsPort: pending.wsPort,1579          pairedAt: pending.pairedAt,1580          trustSource: "vouched",1581        });1582        await removePendingVouchedDevice(deviceId);1583        // Newly confirmed vouched device is now a sync target — kick a round1584        // so the mesh introduction pays off without a 10-minute wait.1585        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1586        return { ok: true };1587      }1588      case "REJECT_VOUCHED_DEVICE": {1589        const { deviceId } = msg.payload as { deviceId: string };1590        await removePendingVouchedDevice(deviceId);1591        return { ok: true };1592      }1593      case "ROTATE_SYNC_IDENTITY": {1594        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1595        const result = await vault.rotateSyncIdentity();1596        return result.ok ? { ok: true } : { ok: false, error: result.error };1597      }15981599      default:1600        return { ok: false, error: "unknown_message_type" };1601    }1602  } catch (err) {1603    return {1604      ok: false,1605      error: err instanceof Error ? err.message : "operation_failed",1606    };1607  }1608}16091610// Returns username use-counts from the vault, sorted by frequency. Each row1611// also carries the entry's email so the popup can suggest the email/username1612// pair the user has actually used together.1613function buildIdentitySuggestions(1614  entries: VaultEntry[],1615): Array<{ email: string; username: string; count: number }> {1616  const usernameCounts = new Map<string, number>();1617  const usernameEmail = new Map<string, string>();1618  for (const entry of entries) {1619    const username = entry.username ?? "";1620    const email = (entry as VaultEntry & { email?: string }).email ?? "";1621    if (!username && !email) continue;1622    const key = username || email;1623    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1624    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1625  }1626  return Array.from(usernameCounts.entries())1627    .sort((a, b) => b[1] - a[1])1628    .map(([username, count]) => ({1629      email: usernameEmail.get(username) ?? "",1630      username,1631      count,1632    }));1633}16341635/** Notify all content scripts that the vault just became available. */1636function broadcastToContentScripts(message: { type: string }): void {1637  if (!chrome.tabs?.query) return;1638  chrome.tabs.query({}, (tabs) => {1639    for (const tab of tabs) {1640      if (tab.id !== undefined) {1641        chrome.tabs.sendMessage(tab.id, message).catch(() => {1642          // Tab may not have a content script — silently ignore1643        });1644      }1645    }1646  });1647}16481649function shouldRefreshAutoLock(type: MessageType): boolean {1650  return (1651    type !== "HAS_VAULT" &&1652    type !== "IS_UNLOCKED" &&1653    type !== "GET_VAULT_STATUS" &&1654    type !== "LOCK" &&1655    type !== "UPDATE_SETTINGS" &&1656    type !== "GET_PENDING_PASSKEY" &&1657    type !== "GET_PASSKEY_PROVIDER_STATE" &&1658    type !== "DECLINE_CARD_SAVE" &&1659    type !== "IS_CARD_DECLINED" &&1660    type !== "AUTOFILL_QUERY" &&1661    type !== "ML_PREDICT_BATCH"1662  );1663}16641665function isAllowedCanaryWebhookUrl(value: string): boolean {1666  try {1667    const url = new URL(value);1668    if (url.protocol !== "https:") return false;16691670    const hostname = url.hostname.toLowerCase();1671    if (1672      hostname === "localhost" ||1673      hostname.endsWith(".localhost") ||1674      isPrivateIpv4(hostname) ||1675      isPrivateIpv6(hostname)1676    ) {1677      return false;1678    }16791680    return true;1681  } catch {1682    return false;1683  }1684}16851686function isPrivateIpv4(hostname: string): boolean {1687  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1688    return true;1689  }16901691  const octets = hostname.split(".").map((part) => Number(part));1692  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1693    return false;1694  }16951696  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1697}16981699function isPrivateIpv6(hostname: string): boolean {1700  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1701  // IPv4-mapped IPv6 literals embed a plain IPv4 address that the prefix1702  // list below can never match (WHATWG URL serializes [::ffff:192.168.0.1]1703  // as ::ffff:c0a8:1). Unwrap and test the embedded IPv4; unparseable mapped1704  // tails fail closed. (Codex Security 2026-08-04 LOW,1705  // ssrf.webhook-url-private-ip-filter.) DNS rebinding is out of scope for a1706  // one-shot host check.1707  const mapped = /^::ffff:(.+)$/.exec(normalized);1708  if (mapped) {1709    const tail = mapped[1] ?? "";1710    if (tail.includes(".")) return isPrivateIpv4(tail);1711    const parts = tail.split(":");1712    const [hi, lo] = parts;1713    if (1714      parts.length !== 2 ||1715      !hi ||1716      !lo ||1717      !/^[0-9a-f]{1,4}$/.test(hi) ||1718      !/^[0-9a-f]{1,4}$/.test(lo)1719    ) {1720      return true;1721    }1722    const octets = [1723      (Number.parseInt(hi, 16) >>> 8) & 0xff,1724      Number.parseInt(hi, 16) & 0xff,1725      (Number.parseInt(lo, 16) >>> 8) & 0xff,1726      Number.parseInt(lo, 16) & 0xff,1727    ];1728    return isPrivateIpv4(octets.join("."));1729  }1730  return (1731    normalized === "::1" ||1732    normalized.startsWith("fc") ||1733    normalized.startsWith("fd") ||1734    normalized.startsWith("fe80:")1735  );1736}