messages.ts

70.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 { 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}209210// Resolves once restoreFromSession() has run, so handlers see the correct211// post-restore unlock state. entry.ts registers this BEFORE the message212// handler so the onMessage listener is added synchronously at SW startup213// (MV3 requirement) while unlock-dependent handlers still wait for restore.214let restoreReady: Promise<void> = Promise.resolve();215216/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */217export function setRestoreReady(p: Promise<unknown>): void {218  restoreReady = p.then(() => undefined, () => undefined);219}220221export async function handleMessage(222  msg: Message,223  sender: Partial<chrome.runtime.MessageSender> = {}224): Promise<MessageResponse> {225  try {226    // Wait for session-restore to finish before reading any unlock/vault state.227    // On a cold SW start the popup's first message arrives while restore is228    // still in flight; without this gate IS_UNLOCKED would report locked (a229    // spurious lock screen) and the storage reads could race. The onMessage230    // listener itself is registered synchronously (entry.ts) so this gate, not231    // listener registration, is what absorbs the cold-start window.232    await restoreReady;233    // Validate sender — only allow messages from our extension pages/scripts.234    // `sender.id` is undefined for messages originating from extension UI235    // (popup/options), which is legitimate; reject only when it is defined236    // and does not match our extension id.237    if (238      sender.id !== undefined &&239      sender.id !== chrome.runtime.id240    ) {241      return { ok: false, error: "invalid_sender" };242    }243244    // PB-26-016: sender authorization is an exhaustive policy, not a245    // hand-maintained privileged denylist. A missing/unknown policy entry or a246    // background-only message fails closed before any handler runs.247    if (!isMessageSenderAllowed(248      msg.type,249      sender,250      chrome.runtime.id,251      chrome.runtime.getURL(""),252    )) {253      return { ok: false, error: "invalid_sender" };254    }255256    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {257      touchAutoLock();258    }259260    switch (msg.type) {261      case "CREATE_VAULT": {262        const { password } = msg.payload as { password: string };263        // Refuse to create a vault under an empty master password — the derived264        // key would be publicly known and the at-rest AES-GCM protection void265        // (audit HIGH; the CSV-import path previously passed ""). Length/strength266        // policy lives in the onboarding UI; this is the non-negotiable floor.267        if (typeof password !== "string" || password.length === 0) {268          return { ok: false, error: "invalid_payload" };269        }270        await vault.createVault(password);271        await setupAutoLock();272        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });273        onVaultUnlocked();274        return { ok: true };275      }276      case "CREATE_VAULT_FROM_ROOT_KEY": {277        const { password, rootKeyHex } = (msg.payload ?? {}) as {278          password?: unknown;279          rootKeyHex?: unknown;280        };281        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {282          return { ok: false, error: "invalid_payload" };283        }284285        try {286          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);287          await setupAutoLock();288          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });289          onVaultUnlocked();290          return { ok: true, vaultId };291        } catch (err) {292          return { ok: false, error: err instanceof Error ? err.message : String(err) };293        }294      }295      case "UNLOCK": {296        const { password } = msg.payload as { password: string };297        const ok = await vault.unlock(password);298        if (ok) {299          // KAT: verify the WebCrypto stack is healthy before the user relies on it.300          // Runs after unlock so latency is hidden behind the vault-load time.301          const kat = await runSelfTest();302          if (!kat.ok) {303            console.error("[Peach] Crypto self-test FAILED:", kat.error);304            await vault.lock();305            return { ok: false, error: "self_test_failed" };306          }307          await vault.updateSettings({ pinPreferred: false });308          await setupAutoLock();309          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });310          onVaultUnlocked();311          return { ok: true };312        }313        // Distinguish corruption from wrong password so the popup can offer314        // a history-restore path instead of falsely accusing the user of315        // mistyping (M7/COR-007).316        const failure = vault.consumeLastUnlockFailureReason();317        if (failure) {318          return {319            ok: false,320            error: "vault_corrupted",321            canRestoreFromHistory: true,322          } as MessageResponse;323        }324        return { ok: false };325      }326      case "UNLOCK_WITH_PIN": {327        const { pin } = (msg.payload ?? {}) as { pin?: unknown };328        if (typeof pin !== "string") return { ok: false, error: "invalid_payload" };329        const ok = await vault.unlockWithPin(pin);330        if (!ok) return { ok: false };331        const kat = await runSelfTest();332        if (!kat.ok) {333          await vault.lock();334          return { ok: false, error: "self_test_failed" };335        }336        await vault.updateSettings({ pinPreferred: true });337        await setupAutoLock();338        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });339        onVaultUnlocked();340        return { ok: true };341      }342      case "VALIDATE_RECOVERY_WORDS": {343        const { words } = msg.payload as { words: string[] };344        const invalid = findInvalidWords(words);345        return { ok: true, data: { valid: invalid.length === 0, invalid } };346      }347      case "GET_RECOVERY_WORDS": {348        // Must be unlocked and have recovery set up (vault must be v2.12+).349        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };350        // LV-4: the recovery words re-derive the ROOT KEY — the highest-351        // value secret in the vault. A session unlock (which may be hours352        // old on a shared machine) is not enough; require a fresh password353        // proof, matching the 1Password/Bitwarden pattern for revealing354        // escrow material. EXEMPTION: the create-vault / rotation confirmation355        // window (peach_recovery_pending) shows the words immediately after356        // the user authenticated, and that confirmation UI has no password to357        // resend — skip the re-auth there only.358        if (!(await isRecoveryConfirmPending())) {359          const { password } = (msg.payload ?? {}) as { password?: string };360          if (typeof password !== "string" || !password) {361            return { ok: false, error: "password_required" };362          }363          if (!(await vault.verifyMainPassword(password))) {364            return { ok: false, error: "wrong_password" };365          }366        }367        try {368          const words = await vault.getRecoveryWords();369          return { ok: true, data: words };370        } catch {371          return { ok: false, error: "recovery_not_setup" };372        }373      }374      case "GET_RECOVERY_CONFIRM_PENDING":375        return { ok: true, data: await isRecoveryConfirmPending() };376      case "SET_RECOVERY_CONFIRM_PENDING":377        await setRecoveryConfirmPending();378        return { ok: true };379      case "CLEAR_RECOVERY_CONFIRM_PENDING":380        await clearRecoveryConfirmPending();381        return { ok: true };382      case "RECOVER_WITH_WORDS": {383        // User has lost their password but has their 12 recovery words.384        // We: (1) validate the words, (2) re-encrypt vault with new password.385        const { words, newPassword } = msg.payload as {386          words: string[];387          newPassword: string;388        };389        const stored = await vault.loadSlotA();390        if (!stored) return { ok: false, error: "no_vault" };391        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {392          return { ok: false, error: "recovery_not_setup" };393        }394        // Unwrap the root key from the recovery escrow.395        try {396          await vault.unwrapRootKeyForRecovery(397            stored.recovery_wrapped_root_key,398            stored.recovery_nonce ?? "",399            stored.recovery_tag ?? "",400            stored.recovery_salt,401            words402          );403        } catch {404          return { ok: false, error: "invalid_recovery_words" };405        }406        // Re-key: derive fresh salt + key from new password.407        const newSalt = vault.generateSalt();408        const newKey = await vault.deriveKey(newPassword, newSalt);409        // Re-wrap root key under the new password's derived key so the same410        // recovery words continue to work after the password change.411        await vault.rewrapRootKeyForPassword(newKey, newSalt);412        // Re-encrypt vault entries with the new key.413        await vault.changePasswordWithNewKey(newSalt, newKey);414        await setupAutoLock();415        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });416        return { ok: true };417      }418      case "LOCK":419        vault.lock();420        return { ok: true };421      case "IS_UNLOCKED":422        return { ok: true, data: vault.isUnlocked() };423      case "GET_VAULT_STATUS":424        return { ok: true, unlocked: vault.isUnlocked() };425      case "HAS_VAULT":426        return { ok: true, data: await vault.hasVault() };427      case "GET_ENTRIES":428        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };429        return { ok: true, data: vault.getEntries() };430      case "ADD_ENTRY": {431        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };432        const payload = msg.payload;433        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {434          return { ok: false, error: "invalid_payload" };435        }436        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);437        return { ok: true, data: entry };438      }439      case "BATCH_ADD_ENTRIES": {440        const payload = msg.payload as { entries?: unknown } | null | undefined;441        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {442          return { ok: false, error: "invalid_payload" };443        }444        if (!Array.isArray(payload.entries)) {445          return { ok: false, error: "invalid_payload" };446        }447        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);448        return { ok: true, data: added };449      }450      case "RESTORE_ENTRIES": {451        const payload = msg.payload as452          | { entries?: unknown; mode?: unknown; settings?: unknown }453          | null454          | undefined;455        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {456          return { ok: false, error: "invalid_payload" };457        }458        if (!Array.isArray(payload.entries)) {459          return { ok: false, error: "invalid_payload" };460        }461        if (payload.mode !== "replace" && payload.mode !== "merge") {462          return { ok: false, error: "invalid_payload" };463        }464        const summary = await vault.restoreEntries(465          payload.entries as Parameters<typeof vault.restoreEntries>[0],466          payload.mode467        );468        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {469          await vault.updateSettings(payload.settings as vault.VaultSettings);470        }471        return { ok: true, data: summary };472      }473      case "CLEAR_VAULT_ENTRIES": {474        await vault.clearVaultEntries("REPLACE_ALL");475        return { ok: true };476      }477      case "GET_VAULT_HISTORY": {478        const snapshots = await vault.getVaultHistory();479        return { ok: true, data: snapshots };480      }481      case "RESTORE_VAULT_SNAPSHOT": {482        const { snapshotId } = msg.payload as { snapshotId: string };483        const result = await vault.restoreVaultSnapshot(snapshotId);484        if (!result.ok) return { ok: false, error: result.error };485        broadcastToContentScripts({ type: "VAULT_LOCKED" });486        return { ok: true };487      }488      case "COUNT_DUPLICATES": {489        return { ok: true, data: vault.countDuplicates() };490      }491      case "DEDUPLICATE_ENTRIES": {492        const removed = await vault.deduplicateEntries();493        return { ok: true, data: removed };494      }495      case "UPDATE_ENTRY": {496        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;497        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {498          return { ok: false, error: "invalid_payload" };499        }500        const { id, patch } = payload;501        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {502          return { ok: false, error: "invalid_payload" };503        }504        // Single enforcement point for the Canary Entries Pro gate. Only505        // gates the transition into a canary entry — clearing/disabling a506        // canary (`canary: undefined`) is always allowed, so existing507        // canary entries remain manageable.508        const incomingCanary = (patch as { canary?: unknown }).canary;509        if (incomingCanary && typeof incomingCanary === "object") {510          const existing = vault.getEntryById(id);511          if (!existing?.canary) {512            const gate = await requirePro("canary_entry");513            if (!gate.allowed) return { ok: false, error: "pro_required" };514          }515        }516        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);517        return { ok: true };518      }519      case "ADD_ADDITIONAL_URL": {520        const { id, url } = msg.payload as { id: string; url: string };521        const trimmed = typeof url === "string" ? url.trim() : "";522        if (!trimmed) return { ok: false, error: "url_required" };523        const existing = vault.getEntryById(id);524        if (!existing) return { ok: false, error: "entry_not_found" };525        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };526        const merged = [...(existing.additionalUrls ?? []), trimmed];527        await vault.updateEntry(id, { additionalUrls: merged });528        return { ok: true };529      }530      case "DELETE_ENTRY": {531        const { id } = msg.payload as { id: string };532        await vault.deleteEntry(id);533        return { ok: true };534      }535      case "GET_DELETED_ENTRIES":536        return { ok: true, data: vault.getDeletedEntries() };537      case "RESTORE_ENTRY": {538        const { id } = msg.payload as { id: string };539        await vault.restoreEntry(id);540        return { ok: true };541      }542      case "PURGE_ENTRY": {543        const { id } = msg.payload as { id: string };544        await vault.purgeEntry(id);545        return { ok: true };546      }547      case "PURGE_EXPIRED_TRASH": {548        const { retentionMs } = msg.payload as { retentionMs: number };549        const purged = await vault.purgeExpiredTrash(retentionMs);550        return { ok: true, data: purged };551      }552      case "SAVE_NOTE": {553        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };554        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };555        const now = Date.now();556        if (id) {557          const existing = vault.getEntryById(id);558          if (!existing) return { ok: false, error: "not_found" };559          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });560          return { ok: true, data: vault.getEntryById(id) };561        } else {562          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt563          // (EntryDraft omits both), so passing them was the only reason the564          // `as any` cast existed. Dropping them makes the call type-check.565          const entry = await vault.addEntry({566            type: "note",567            title: title || "Untitled",568            notes: body,569          });570          return { ok: true, data: entry };571        }572      }573      case "DELETE_NOTE": {574        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };575        const { id } = msg.payload as { id: string };576        await vault.deleteEntry(id);577        return { ok: true };578      }579      case "GET_NOTES": {580        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };581        const notes = vault.getEntries().filter(582          (e) => e.type === "note" && !e.deletedAt583        );584        return { ok: true, data: notes } as MessageResponse;585      }586      case "SEARCH_VAULT": {587        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };588        // AUD-002: shape-validate the payload before calling string methods.589        // A raw cast lets a malformed message crash the handler with TypeError.590        const { query } = (msg.payload ?? {}) as { query?: unknown };591        if (typeof query !== "string") {592          return { ok: false, error: "invalid_payload" };593        }594        const q = query.toLowerCase();595        const searchResults = vault.getEntries().filter(596          (e) =>597            !e.deletedAt &&598            (e.title.toLowerCase().includes(q) ||599              e.notes?.toLowerCase().includes(q) ||600              e.username?.toLowerCase().includes(q))601        );602        return { ok: true, data: searchResults } as MessageResponse;603      }604      case "AUTOFILL_QUERY": {605        if (!vault.isUnlocked()) {606          return { ok: false, error: "vault_locked" };607        }608        let { includeAll } = msg.payload as { includeAll?: boolean };609        const { domain, kind, userGesture } = msg.payload as {610          domain: string;611          kind?: "login" | "card" | "totp";612          userGesture?: boolean;613        };614        // MV-2: the vault-wide inventory (every title/username/email/url)615        // may only leave the background on an explicit user gesture — the616        // user opening the search affordance — never on passive form focus.617        // userGesture is self-declared by our own content script; the value618        // of this gate is that PASSIVE code paths (which never set it)619        // cannot ship the inventory, shrinking what a compromised page that620        // merely triggers focus events can observe.621        if (includeAll && userGesture !== true) {622          includeAll = false;623        }624        // kind="card": return saved cards as compact summaries for the625        // inline card silver platter. Cards are not domain-scoped — every626        // saved card is a candidate on every checkout page — so domain is627        // ignored when kind === "card".628        if (kind === "card") {629          const cards = vault.getEntries().filter((e) => e.type === "card");630          return {631            ok: true,632            data: cards.map((e) => ({633              id: e.id,634              title: e.cardNickname || e.title,635              cardholderName: e.cardholderName,636              last4: e.last4,637              expMonth: e.expMonth,638              expYear: e.expYear,639              network: e.network,640            })),641          };642        }643        if (kind === "totp") {644          const matches = (645            includeAll646              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")647              : vault.queryDomain(domain)648          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));649          return {650            ok: true,651            data: matches.map((e) => ({652              id: e.id,653              title: e.title,654              username: e.username,655              email: e.email,656              url: e.url,657              hasTotp: true,658            })),659          };660        }661        // The inline selector fills username+password into a form. Passkey-662        // only entries have no password to fill; sign-in for those goes663        // through the WebAuthn path instead. Filter them out everywhere so664        // the user doesn't see four "GitHub" rows that mostly do nothing.665        // Notes and cards never belonged here either.666        const matches = (667          includeAll668            ? vault669                .getEntries()670                .filter((entry) => entry.type !== "note" && entry.type !== "card")671            : vault.queryDomain(domain)672        ).filter((entry) => !isPasskeyOnly(entry));673        return {674          ok: true,675          data: matches.map((e) =>676            includeAll677              ? {678                  id: e.id,679                  title: e.title,680                  // username/email/url shipped so the inline popup's search681                  // affordance can match on them, not just titles. No secrets682                  // cross the boundary — same shape as the domain-matched683                  // response below minus hasTotp (which the search list684                  // doesn't surface).685                  username: e.username,686                  email: e.email,687                  url: e.url,688                  hasPasskey: e.passkey !== undefined,689                }690              : {691                  id: e.id,692                  title: e.title,693                  username: e.username,694                  email: e.email,695                  url: e.url,696                  hasTotp: Boolean(e.totp),697                  hasPasskey: e.passkey !== undefined,698                }699          ),700        };701      }702      case "GET_ENTRY_FOR_FILL": {703        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };704        const { id, explicitSummon } = msg.payload as {705          id: string;706          explicitSummon?: boolean;707        };708        const entry = vault.getEntryById(id);709        if (!entry) return { ok: false, error: "entry_not_found" };710        // Passkey-only entries (passkey credential, no password) cannot be711        // filled into a form — sign-in goes through the WebAuthn path. A712        // login that ALSO has a passkey is still fillable for its password.713        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };714715        // MV-1: re-validate the entry against the requesting frame's origin.716        // sender.url / sender.tab.url are browser-attested — a page cannot717        // forge them. PB-26-005: the FRAME url (sender.url) is authoritative718        // for an all_frames content script; the top-frame tab.url would719        // misattribute a cross-origin iframe's request to the top page. When720        // the request does not come from a tab at all (popup surfaces use721        // GET_ENTRY_FOR_EDIT, not this), refuse.722        if (sender.tab !== undefined || sender.url !== undefined) {723          let senderDomain: string | null = null;724          try {725            const rawUrl = sender.url ?? sender.tab?.url ?? "";726            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;727          } catch {728            senderDomain = null;729          }730          if (!senderDomain) return { ok: false, error: "origin_unverified" };731732          const entryDomains = new Set<string>();733          const primary = extractDomain(entry.url ?? "");734          if (primary) entryDomains.add(primary);735          for (const extra of entry.additionalUrls ?? []) {736            const d = extractDomain(extra);737            if (d) entryDomains.add(d);738          }739740          // explicitSummon=true means the user actively picked this entry741          // from the cross-domain search affordance — an intentional742          // off-domain fill. Passive fill paths must stay domain-bound.743          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {744            // Domain mismatch — refuse silently (no oracle about which ids exist).745            return { ok: false, error: "entry_not_found" };746          }747        }748        // Strip the passkey credential AND the raw base32 TOTP seed from the749        // response. Content scripts never need either: the private key is the750        // authenticator's, and handing over the TOTP seed would let a751        // compromised content script mint valid codes indefinitely (SEV-3-C).752        // Generate the *current* 6-digit code here in the background and send753        // only that, plus the seconds left so the UI can render a countdown.754        // Also drop passwordHistory: filling needs only the *current* password.755        // Handing every past password to a content script during passive756        // autofill on an arbitrary page would widen the blast radius of a757        // compromised page far beyond the one credential being filled.758        const {759          passkey: _strippedPasskey,760          totp: seed,761          totpAlgorithm,762          totpDigits,763          totpPeriod,764          passwordHistory: _ph,765          ...safeEntry766        } = entry;767        let totpCode: string | undefined;768        let totpRemaining: number | undefined;769        if (seed) {770          try {771            // PCH-01-019: honour stored algorithm/digits/period (defaults apply772            // when these are undefined, i.e. RFC-default bare-seed entries).773            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);774            totpCode = generated.code;775            totpRemaining = generated.remaining;776          } catch {777            totpCode = undefined;778          }779        }780        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };781      }782      // Trusted full-entry fetch for Peach's own inline-popup surfaces that783      // genuinely need the raw TOTP seed: the edit form (which re-saves the784      // seed and would otherwise wipe it) and nothing else. Unlike785      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside786      // the inline popup, never during passive autofill on an arbitrary page.787      // The passkey credential is still stripped — the edit form never touches it.788      case "GET_ENTRY_FOR_EDIT": {789        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };790        const { id, explicitSummon } = msg.payload as {791          id: string;792          explicitSummon?: boolean;793        };794        const entry = vault.getEntryById(id);795        if (!entry) return { ok: false, error: "entry_not_found" };796797        // PCH-01-006: re-validate the browser-attested sender origin, mirroring798        // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and799        // full password history — at least as sensitive as the fill response — so800        // the boundary must be enforced here, not only by UI reachability. Today801        // the sole caller is the popup (no sender.tab, so this is a structural802        // no-op), but a future tab-context caller or an id leak would otherwise803        // inherit a full-credential oracle. Unlike the fill path we SKIP (not804        // refuse) when no sender domain resolves, to keep the popup caller working.805        // PB-26-005: the frame url (sender.url) is authoritative over the806        // top-frame sender.tab.url — mirrors the fill path.807        if (sender.tab !== undefined || sender.url !== undefined) {808          let senderDomain: string | null = null;809          try {810            const rawUrl = sender.url ?? sender.tab?.url ?? "";811            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;812          } catch {813            senderDomain = null;814          }815          if (senderDomain) {816            const entryDomains = new Set<string>();817            const primary = extractDomain(entry.url ?? "");818            if (primary) entryDomains.add(primary);819            for (const extra of entry.additionalUrls ?? []) {820              const d = extractDomain(extra);821              if (d) entryDomains.add(d);822            }823            if (explicitSummon !== true && !entryDomains.has(senderDomain)) {824              return { ok: false, error: "entry_not_found" }; // no id oracle825            }826          }827        }828829        const { passkey: _passkey, ...safeEntry } = entry;830        return { ok: true, data: safeEntry };831      }832      case "COPY": {833        // AUD-002: shape-validate the payload before passing to the clipboard834        // helper. A raw cast lets a malformed message reach the clipboard API835        // with a non-string and throw.836        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {837          text?: unknown;838          label?: unknown;839          alreadyWritten?: unknown;840        };841        if (typeof text !== "string" || typeof label !== "string") {842          return { ok: false, error: "invalid_payload" };843        }844        await copyToClipboard(text, label, Boolean(alreadyWritten));845        return { ok: true, clearSeconds: getEffectiveClearSeconds() };846      }847      case "CHECK_ALL_BREACHES": {848        const allEntries = vault.getEntries();849        const results: Record<string, number> = {};850        for (const entry of allEntries) {851          if (entry.type === "note") continue;852          if (!entry.password) continue;853          results[entry.id] = await vault.checkBreach(entry.password);854          // Small delay — be a good citizen to the HIBP API855          await new Promise((r) => setTimeout(r, 200));856        }857        // Persist any non-zero counts back to entries858        for (const [id, count] of Object.entries(results)) {859          const entry = vault.getEntryById(id);860          if (entry && (entry.breach ?? 0) !== count) {861            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });862          }863        }864        return { ok: true, data: results };865      }866      case "GET_SETTINGS":867        return { ok: true, data: await vault.ensureSettingsLoaded() };868      case "UPDATE_SETTINGS": {869        const patch = msg.payload;870        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {871          return { ok: false, error: "invalid_payload" };872        }873        await vault.updateSettings(patch as vault.VaultSettings);874        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {875          await setupAutoLock();876          if (vault.isUnlocked()) touchAutoLock();877        }878        return { ok: true };879      }880      case "SETUP_PIN": {881        const { currentPassword, pin } = (msg.payload ?? {}) as {882          currentPassword?: unknown;883          pin?: unknown;884        };885        if (typeof currentPassword !== "string" || typeof pin !== "string") {886          return { ok: false, error: "invalid_payload" };887        }888        return (await vault.setupPinUnlock(currentPassword, pin))889          ? { ok: true }890          : { ok: false, error: "incorrect_current_password" };891      }892      case "DISABLE_PIN": {893        const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown };894        if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" };895        return (await vault.disablePinUnlock(currentPassword))896          ? { ok: true }897          : { ok: false, error: "incorrect_current_password" };898      }899      case "GET_PENDING_PASSKEY":900        return { ok: true, data: await getPendingPasskeyRequest() };901      case "APPROVE_PASSKEY": {902        const { requestId } = msg.payload as { requestId: number };903        await resolvePendingPasskeyRequest(requestId, true);904        return { ok: true };905      }906      case "DENY_PASSKEY": {907        const { requestId } = msg.payload as { requestId: number };908        await resolvePendingPasskeyRequest(requestId, false);909        return { ok: true };910      }911      case "GET_PASSKEY_PROVIDER_STATE":912        return { ok: true, data: await getPasskeyProviderState() };913      case "SET_PASSKEY_PROVIDER_ENABLED": {914        const { enabled } = msg.payload as { enabled: boolean };915        // Disabling is always free; gating fires only when a free user is916        // trying to turn passkey interception on.917        if (enabled) {918          const gate = await requirePro("passkeys");919          if (!gate.allowed) return { ok: false, error: "pro_required" };920        }921        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };922      }923      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS924      // endpoint. Intentional product behavior — users configure their own925      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private926      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-927      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to928      // users that the entry title leaves the device when the canary fires.929      case "FIRE_CANARY_PING": {930        // Canary alert fires unconditionally for any entry with canary: true.931        // The Pro gate only governs creation/flagging of canary entries; once932        // an entry is flagged, the alert path is a security property and must933        // never be license-gated.934        const { webhookUrl, entryTitle, trigger } = msg.payload as {935          webhookUrl: string;936          entryTitle: string;937          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";938        };939        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {940          return { ok: false, error: "invalid_webhook_url" };941        }942        // LV-3: debounce non-test pings per (webhook, entry) so a page that943        // strobes focus/fill events can't turn the canary into a request944        // firehose at the user's endpoint. Test pings are exempt — they are945        // explicit user clicks in the settings UI and are awaited for946        // feedback. The FIRST ping in a window always goes out, so the947        // dead-man's-switch property (canary fires on access) is preserved;948        // only repeats within the window are coalesced.949        if (trigger !== "test") {950          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;951          const stored = await chrome.storage.local.get(rlKey);952          const last = (stored as Record<string, unknown>)[rlKey];953          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {954            return { ok: true, data: { rateLimited: true } };955          }956          await chrome.storage.local.set({ [rlKey]: Date.now() });957        }958        const body = JSON.stringify({959          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",960          entry: entryTitle,961          trigger,962          timestamp: new Date().toISOString(),963          source: "peach-extension",964        });965        if (trigger === "test") {966          // Permitted outbound fetch: user-configured canary alert endpoint967          // (validated by isAllowedCanaryWebhookUrl above). This is the968          // only non-HIBP outbound call in the extension — see969          // Projects.md §3.7. Test pings are awaited so the UI can show970          // success/failure.971          try {972            const res = await fetch(webhookUrl, {973              method: "POST",974              headers: { "Content-Type": "application/json" },975              body,976            });977            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };978          } catch (err) {979            return { ok: false, error: err instanceof Error ? err.message : "network_error" };980          }981        }982        // Non-test triggers are fire-and-forget983        fetch(webhookUrl, {984          method: "POST",985          headers: { "Content-Type": "application/json" },986          body,987        }).catch(() => {});988        return { ok: true };989      }990      case "ACTIVATE_LICENSE": {991        const { key } = msg.payload as { key: string };992        const licenseInfo = await activateLicense(key);993        return { ok: true, data: licenseInfo };994      }995      case "GET_LICENSE": {996        const licenseInfo = await getLicenseInfo();997        return { ok: true, data: licenseInfo };998      }999      case "GET_LICENSE_KEY": {1000        const key = await getLicenseKey();1001        return { ok: true, data: key };1002      }1003      case "DEACTIVATE_LICENSE": {1004        await deactivateLicense();1005        return { ok: true };1006      }1007      case "SHOULD_PLAY_CELEBRATION": {1008        const should = await shouldPlayCelebration();1009        return { ok: true, data: should };1010      }1011      case "MARK_CELEBRATION_PLAYED": {1012        await markCelebrationPlayed();1013        return { ok: true };1014      }1015      case "GET_CODEX_VAULT_DATA": {1016        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1017        // popup navigates to the License section without further coordination.1018        // Also privileged-page-gated (PB-26-001), and recoveryWords inside the1019        // snapshot additionally require a fresh master-password proof.1020        const gate = await requirePro("codex");1021        if (!gate.allowed) return { ok: false, error: "pro_required" };1022        const { password } = (msg.payload ?? {}) as { password?: string };1023        return await handleGetCodexVaultData(password);1024      }1025      case "ESTIMATE_CODEX_PAGES": {1026        const gate = await requirePro("codex");1027        if (!gate.allowed) return { ok: false, error: "pro_required" };1028        return await handleEstimateCodexPages();1029      }1030      case "RESTORE_FROM_CODEX": {1031        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1032        // be able to restore a vault that was printed by a Pro user.1033        // DO NOT add a Pro gate here.1034        const payload = msg.payload as CodexRestorePayload;1035        return await handleRestoreFromCodex(payload);1036      }1037      case "OPEN_PRO_GATE": {1038        // Content script requests: open popup and navigate to License section.1039        const { feature } = (msg.payload ?? {}) as { feature?: string };1040        if (chrome.storage.session) {1041          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1042        }1043        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1044        return { ok: true };1045      }1046      case "OPEN_POPUP": {1047        // Content script asks to open the trusted extension popup — used by the1048        // inline locked bubble so the master password is entered in the popup,1049        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1050        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1051        // toolbar icon. The badge already signals Peach needs attention.1052        //1053        // Set a session flag so the popup knows it was opened for inline unlock1054        // and should close itself once the vault is unlocked (returning the user1055        // to the inline autofill selector on the page).1056        if (chrome.storage.session) {1057          await chrome.storage.session.set({ peach_inline_unlock: true });1058        }1059        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1060        return { ok: true };1061      }1062      case "OPEN_DETACHED_POPUP": {1063        // A window created by the action popup and then orphaned with1064        // window.close() is cascaded shut by Chrome, so the file-picker1065        // flows (OS dialogs that dismiss the popup on focus loss) ask the SW1066        // to open the standalone window instead — the SW has no window to be1067        // associated with. The query string is allowlisted so this can never1068        // open an arbitrary URL.1069        const { route } = (msg.payload ?? {}) as { route?: string };1070        const search = route === "peachscript"1071          ? "?restore=peachscript"1072          : route === "csv"1073            ? "?restore=csv"1074            : route === "codex-pdf"1075              ? "?codex=pdf"1076              : null;1077        if (!search) return { ok: false, error: "bad_route" };1078        try {1079          const popupHtml =1080            chrome.runtime.getManifest().action?.default_popup ?? "src/popup/index.html";1081          await chrome.windows.create({1082            url: chrome.runtime.getURL(`${popupHtml}${search}`),1083            type: "popup",1084            width: 320,1085            height: 550,1086          });1087          return { ok: true, data: { detached: true } };1088        } catch {1089          return { ok: false };1090        }1091      }1092      case "GET_IDENTITIES": {1093        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1094        return { ok: true, data: vault.getIdentities() };1095      }1096      case "TOUCH_AUTO_LOCK": {1097        // touchAutoLock() is already called by shouldRefreshAutoLock above;1098        // this case just gives the popup a typed message to keep the session alive.1099        return { ok: true };1100      }1101      case "GET_ADVANCED_HEALTH_REPORT": {1102        const gate = await requirePro("advanced_health");1103        if (!gate.allowed) return { ok: false, error: "pro_required" };1104        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1105        const report = await buildAdvancedHealthReport(vault.getEntries());1106        return { ok: true, data: report };1107      }1108      case "IS_DURESS_ENABLED": {1109        const enabled = await vault.isDuressEnabled();1110        return { ok: true, data: enabled };1111      }1112      case "SETUP_DURESS": {1113        // Single enforcement point for the Duress Vault Pro gate. Free users1114        // who somehow reach this handler are rejected here; the popup also1115        // pre-checks isPro() to avoid showing the setup form to free users,1116        // but server-side is the actual security boundary.1117        const gate = await requirePro("duress_vault");1118        if (!gate.allowed) return { ok: false, error: "pro_required" };1119        // MV3 service workers restart after inactivity, losing the in-memory1120        // derived key. Detect this before calling setupDuress so the popup1121        // can show a meaningful prompt to re-lock and re-unlock.1122        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1123        const { duressPassword } = msg.payload as { duressPassword: string };1124        await vault.setupDuress(duressPassword);1125        return { ok: true };1126      }1127      case "DISABLE_DURESS": {1128        await vault.disableDuress();1129        return { ok: true };1130      }1131      case "VERIFY_MAIN_PASSWORD": {1132        const { password } = msg.payload as { password: string };1133        const ok = await vault.verifyMainPassword(password);1134        return { ok: true, data: ok };1135      }1136      case "CHANGE_PASSWORD": {1137        const { currentPassword, newPassword } = msg.payload as {1138          currentPassword: string;1139          newPassword: string;1140        };1141        const changed = await vault.changePassword(currentPassword, newPassword);1142        return changed1143          ? { ok: true }1144          : { ok: false, error: "incorrect_current_password" };1145      }1146      case "GET_SITE_PASSWORD_POLICY": {1147        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1148        if (!tab?.id) return { ok: true, data: null };1149        try {1150          const response = await chrome.tabs.sendMessage(tab.id, {1151            type: "GET_SITE_PASSWORD_POLICY",1152          });1153          return (response as MessageResponse) ?? { ok: true, data: null };1154        } catch {1155          return { ok: true, data: null };1156        }1157      }1158      case "RECORD_MANUAL_SUMMON": {1159        const { domain } = msg.payload as { domain: string };1160        const settings = vault.getSettings();1161        const existing = settings.manualSummonDomains?.[domain];1162        const now = Date.now();1163        await vault.updateSettings({1164          manualSummonDomains: {1165            ...settings.manualSummonDomains,1166            [domain]: {1167              firstSummonedAt: existing?.firstSummonedAt ?? now,1168              summonCount: (existing?.summonCount ?? 0) + 1,1169              lastSummonedAt: now,1170            },1171          },1172        });1173        return { ok: true };1174      }1175      case "DECLINE_CARD_SAVE": {1176        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1177        await vault.declineCardSaveOffer(last4, expMonth, expYear);1178        return { ok: true };1179      }1180      case "IS_CARD_DECLINED": {1181        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1182        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1183        return { ok: true, data: declined };1184      }1185      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1186        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1187          rpId?: string;1188          rpName?: string;1189          userName?: string;1190          userDisplayName?: string;1191        };1192        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1193        return await initiateFirefoxPasskeyCreate({1194          rpId,1195          rpName: rpName ?? rpId,1196          userName,1197          userDisplayName,1198        }, attestedSenderOrigin(sender));1199      }12001201      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1202        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1203        if (!payload) return { ok: false, error: "missing_payload" };1204        return await completeFirefoxPasskeyCreate(payload);1205      }12061207      case "PASSKEY_OFFER_DECLINE": {1208        const { domain } = (msg.payload ?? {}) as { domain?: string };1209        if (!domain) return { ok: false, error: "domain_required" };1210        await recordPasskeyOfferDecline(domain);1211        return { ok: true };1212      }12131214      case "GET_PASSKEY_OFFER_DECLINED": {1215        const { domain } = (msg.payload ?? {}) as { domain?: string };1216        if (!domain) return { ok: false, error: "domain_required" };1217        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1218      }12191220      case "PASSKEY_HAS_CREDENTIALS": {1221        const payload = msg.payload as {1222          rpId?: string;1223          allowCredentials?: Array<{ id: string; type?: string }>;1224        } | undefined;1225        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1226        return await handlePasskeyHasCredentials({1227          rpId: payload.rpId,1228          allowCredentials: payload.allowCredentials ?? [],1229        }, attestedSenderOrigin(sender));1230      }12311232      case "PASSKEY_CREATE": {1233        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1234        if (!payload?.rpId || !payload?.userName) {1235          return { ok: false, error: "rpid_and_username_required" };1236        }1237        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1238      }12391240      case "PASSKEY_GET": {1241        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1242        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1243        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1244      }12451246      case "PASSKEY_AUTH_RESPONSE": {1247        const { requestId, approved } = (msg.payload ?? {}) as {1248          requestId?: string | number;1249          approved?: boolean;1250        };1251        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1252          return { ok: false, error: 'requestId and approved required' };1253        }1254        await resolvePendingPasskeyRequest(Number(requestId), approved);1255        return { ok: true };1256      }12571258      case "GET_PASSKEY_FOR_DOMAIN": {1259        const { domain } = (msg.payload ?? {}) as { domain?: string };1260        if (!domain) return { ok: false, error: "domain_required" };1261        // Scope to the caller's own origin: a page may only ask about passkeys1262        // for a domain it actually owns, so an arbitrary page cannot enumerate1263        // which sites the user holds passkeys for or read the username (audit MEDIUM).1264        const origin = attestedSenderOrigin(sender);1265        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1266        if (!vault.isUnlocked()) return { ok: true, data: null };1267        const match = vault1268          .getEntries()1269          .find((entry) => entry.passkey?.rpId === domain);1270        if (!match || !match.passkey) return { ok: true, data: null };1271        // Slim shape — only the fields State 11 needs. Never expose private1272        // key material, even though this is locked behind isUnlocked.1273        return {1274          ok: true,1275          data: {1276            rpId: match.passkey.rpId,1277            userName: match.passkey.userName,1278            browser: match.passkey.browser,1279          },1280        };1281      }12821283      case "DESTROY_VAULT": {1284        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1285        // storage.local.clear() wipes every Peach key (slots, settings, license,1286        // onboarded flag, history, sync state, declined cards, recall, etc.);1287        // session.clear() wipes pending passkey requests + pro-notice queues.1288        // Caller (Panic.tsx) handles UI navigation back to onboarding.1289        //1290        // The Pro license is the one thing that must survive: the user paid for1291        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1292        // Capture it before the clear and restore it after. peach_pro_celebrated1293        // rides along so the Pro celebration doesn't replay on the next unlock.1294        const preserved = await chrome.storage.local.get([1295          "peach_license",1296          "peach_pro_celebrated",1297        ]);1298        vault.lock();1299        await storageClear();1300        await vault.clearVaultHistory();1301        const toRestore: Record<string, unknown> = {};1302        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1303        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1304        if (Object.keys(toRestore).length > 0) {1305          await chrome.storage.local.set(toRestore);1306        }1307        if (chrome.storage.session) {1308          await chrome.storage.session.clear();1309        }1310        await clearRecoveryConfirmPending();1311        return { ok: true };1312      }13131314      case "GET_IDENTITY_SUGGESTIONS": {1315        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1316        const entries = vault.getEntries();1317        const suggestions = buildIdentitySuggestions(entries);1318        return { ok: true, data: { suggestions } };1319      }1320      case "ML_INIT":1321        return { ok: true };13221323      case "ML_PREDICT_BATCH": {1324        // AUD-002: shape-validate before forwarding to the ML helper.1325        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1326        if (!Array.isArray(featuresArray)) {1327          return { ok: false, error: "invalid_payload" };1328        }1329        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1330      }13311332      // ── Vault sync (v3) ───────────────────────────────────────────────1333      // Returns the public-facing local identity needed by the popup to1334      // drive Phase-1 audio pairing. The private long-term key never1335      // leaves the background.1336      case "GET_LOCAL_IDENTITY": {1337        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1338        // Pro license from an already-Pro peer (at least one device must be Pro).1339        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1340        // Identity derives from the stable root key, not the password-derived1341        // key, so pairing survives a master-password change (SEV-2-B).1342        const masterKeyHex = vault.getRootKeyHex();1343        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1344        const masterKey = unhexBytes(masterKeyHex);1345        try {1346          const identity = await buildLocalIdentity(masterKey);1347          // If this device is Pro, advertise the signed license so the peer can1348          // activate it after SAS confirmation — pairing carries Pro across.1349          if (await isProUser()) {1350            const license = await getLicenseKey();1351            if (license) (identity as { license?: string }).license = license;1352          }1353          return { ok: true, data: identity };1354        } finally {1355          masterKey.fill(0);1356        }1357      }13581359      case "LIST_PAIRED_DEVICES": {1360        const devices = await listPairedDevicesV3();1361        return { ok: true, data: { devices } };1362      }13631364      case "RENAME_PAIRED_DEVICE": {1365        const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string };1366        if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") {1367          return { ok: false, error: "invalid_payload" };1368        }1369        await renamePairedDeviceV3(deviceId, name);1370        return { ok: true };1371      }13721373      case "UNPAIR_DEVICE": {1374        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1375        if (typeof deviceId !== "string" || !deviceId) {1376          return { ok: false, error: "invalid_payload" };1377        }1378        // Removing a device REVOKES it rather than just dropping the local1379        // row: a plain removal is undone the moment any other peer vouches it1380        // back through a manifest, which is exactly what the relay makes easy.1381        await revokeDeviceByIdV3(deviceId, await getOrCreateDeviceId());1382        // Sync against the remaining hosts — the unpaired device no longer1383        // matters but the next alarm tick is up to ten minutes away.1384        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1385        return { ok: true };1386      }13871388      case "RENAME_LOCAL_DEVICE": {1389        const { name } = (msg.payload ?? {}) as { name?: string };1390        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1391        await setDeviceNameV3(name);1392        return { ok: true };1393      }13941395      // ── Relay pairing ─────────────────────────────────────────────────────1396      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1397      // session runs in the background; the SAS and the terminal result reach1398      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1399      case "START_ADOPTION_SOURCE": {1400        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1401        if (isRelayAdoptionSourceInFlight()) {1402          return { ok: false, error: "adoption_source_in_progress" };1403        }1404        try {1405          return { ok: true, data: await startRelayAdoptionSource() };1406        } catch (error) {1407          return {1408            ok: false,1409            error: error instanceof Error ? error.message : "adoption_source_failed",1410          };1411        }1412      }14131414      // Onboarding receiver — empty extension shows a QR, phone scans and1415      // sends the vault. The popup supplies the local-only password here so1416      // the background can wrap the adopted root key at rest without ever1417      // asking the user to retype it.1418      case "START_ADOPTION_RECEIVER": {1419        if (isRelayAdoptionSourceInFlight()) {1420          return { ok: false, error: "adoption_receiver_in_progress" };1421        }1422        const password = (msg.payload as { password?: unknown } | undefined)?.password;1423        if (typeof password !== "string" || password.length === 0) {1424          return { ok: false, error: "invalid_payload" };1425        }1426        try {1427          return { ok: true, data: await startRelayAdoptionReceiver(password) };1428        } catch (error) {1429          return {1430            ok: false,1431            error: error instanceof Error ? error.message : "adoption_receiver_failed",1432          };1433        }1434      }14351436      // Popup→bg counterpart to ADOPTION_SOURCE_SAS (receiver flow).1437      // The receiver now auto-accepts the SAS (both sides derive it from the1438      // same Noise handshake hash, so the codes match by construction) so1439      // the popup never has a SAS screen to tap on. The id round-trips the1440      // same way so a stale late response can't approve the wrong session.1441      // Popup→bg counterpart for the source flow: Confirm/Cancel on the1442      // source's SAS screen.14431444      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1445      // on the source's SAS screen. The id round-trips the same way so a stale1446      // late response can't approve the wrong session.1447      case "SOURCE_SAS_DECISION": {1448        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1449        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1450          return { ok: false, error: "invalid_payload" };1451        }1452        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1453      }14541455      case "CANCEL_ADOPTION_SOURCE": {1456        cancelRelayAdoptionSource();1457        return { ok: true };1458      }14591460      case "TRIGGER_SYNC": {1461        const payload = (msg.payload ?? {}) as {1462          reason?: "vault_change" | "foreground" | "manual";1463          force?: boolean;1464        };1465        const reason = payload.reason ?? "foreground";14661467        void triggerSyncIfReachable({ reason, force: payload.force === true });1468        return { ok: true };1469      }14701471      case "GET_SYNC_STATE": {1472        return { ok: true, data: getSyncState() };1473      }14741475      case "GET_SYNC_SETTINGS": {1476        return { ok: true, data: await getSyncSettings() };1477      }14781479      case "SET_SYNC_SETTINGS": {1480        const payload = (msg.payload ?? {}) as {1481          mode?: unknown;1482          relayUrl?: unknown;1483        };1484        try {1485          // A custom relay URL implies private mode; Peach's own relay stays1486          // public. See setRelayUrl.1487          if (payload.relayUrl !== undefined) {1488            if (typeof payload.relayUrl !== "string") {1489              return { ok: false, error: "invalid_relay_url" };1490            }1491            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1492          }1493          if (payload.mode !== undefined) {1494            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1495              return { ok: false, error: "invalid_sync_mode" };1496            }1497            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1498          }1499          return { ok: true, data: await getSyncSettings() };1500        } catch (error) {1501          return {1502            ok: false,1503            error: error instanceof Error ? error.message : "invalid_relay_url",1504          };1505        }1506      }15071508      case "GET_SYNC_ALERTS": {1509        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1510        const alerts = await getPendingSyncAlerts();1511        // The popup reads on open and acknowledges with consume:true after1512        // rendering, so a popup crash between read and render doesn't lose1513        // the alerts.1514        if (consume) await clearPendingSyncAlerts();1515        return { ok: true, data: alerts };1516      }15171518      case "GET_PENDING_VOUCHED_DEVICES": {1519        return { ok: true, data: await listPendingVouchedDevices() };1520      }1521      case "CONFIRM_VOUCHED_DEVICE": {1522        const { deviceId } = msg.payload as { deviceId: string };1523        const pending = await getPendingVouchedDevice(deviceId);1524        if (!pending) return { ok: false, error: "not_pending" };1525        // Last gate before a vouched device becomes a sync peer. A queue entry1526        // can predate the revocation that names it, so revocation is re-checked1527        // here rather than trusted to have swept the queue.1528        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {1529          await removePendingVouchedDevice(deviceId);1530          return { ok: false, error: "device_revoked" };1531        }1532        await upsertPairedDeviceV3({1533          deviceId: pending.deviceId,1534          deviceName: pending.deviceName,1535          deviceType:1536            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1537          longTermPublicKeyHex: pending.longTermPublicKeyHex,1538          signingPublicKeyHex: pending.signingPublicKeyHex,1539          wsPort: pending.wsPort,1540          pairedAt: pending.pairedAt,1541          trustSource: "vouched",1542        });1543        await removePendingVouchedDevice(deviceId);1544        // Newly confirmed vouched device is now a sync target — kick a round1545        // so the mesh introduction pays off without a 10-minute wait.1546        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1547        return { ok: true };1548      }1549      case "REJECT_VOUCHED_DEVICE": {1550        const { deviceId } = msg.payload as { deviceId: string };1551        await removePendingVouchedDevice(deviceId);1552        return { ok: true };1553      }1554      case "ROTATE_SYNC_IDENTITY": {1555        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1556        const result = await vault.rotateSyncIdentity();1557        return result.ok ? { ok: true } : { ok: false, error: result.error };1558      }15591560      default:1561        return { ok: false, error: "unknown_message_type" };1562    }1563  } catch (err) {1564    return {1565      ok: false,1566      error: err instanceof Error ? err.message : "operation_failed",1567    };1568  }1569}15701571// Returns username use-counts from the vault, sorted by frequency. Each row1572// also carries the entry's email so the popup can suggest the email/username1573// pair the user has actually used together.1574function buildIdentitySuggestions(1575  entries: VaultEntry[],1576): Array<{ email: string; username: string; count: number }> {1577  const usernameCounts = new Map<string, number>();1578  const usernameEmail = new Map<string, string>();1579  for (const entry of entries) {1580    const username = entry.username ?? "";1581    const email = (entry as VaultEntry & { email?: string }).email ?? "";1582    if (!username && !email) continue;1583    const key = username || email;1584    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1585    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1586  }1587  return Array.from(usernameCounts.entries())1588    .sort((a, b) => b[1] - a[1])1589    .map(([username, count]) => ({1590      email: usernameEmail.get(username) ?? "",1591      username,1592      count,1593    }));1594}15951596/** Notify all content scripts that the vault just became available. */1597function broadcastToContentScripts(message: { type: string }): void {1598  if (!chrome.tabs?.query) return;1599  chrome.tabs.query({}, (tabs) => {1600    for (const tab of tabs) {1601      if (tab.id !== undefined) {1602        chrome.tabs.sendMessage(tab.id, message).catch(() => {1603          // Tab may not have a content script — silently ignore1604        });1605      }1606    }1607  });1608}16091610function shouldRefreshAutoLock(type: MessageType): boolean {1611  return (1612    type !== "HAS_VAULT" &&1613    type !== "IS_UNLOCKED" &&1614    type !== "GET_VAULT_STATUS" &&1615    type !== "LOCK" &&1616    type !== "UPDATE_SETTINGS" &&1617    type !== "GET_PENDING_PASSKEY" &&1618    type !== "GET_PASSKEY_PROVIDER_STATE" &&1619    type !== "DECLINE_CARD_SAVE" &&1620    type !== "IS_CARD_DECLINED"1621  );1622}16231624function isAllowedCanaryWebhookUrl(value: string): boolean {1625  try {1626    const url = new URL(value);1627    if (url.protocol !== "https:") return false;16281629    const hostname = url.hostname.toLowerCase();1630    if (1631      hostname === "localhost" ||1632      hostname.endsWith(".localhost") ||1633      isPrivateIpv4(hostname) ||1634      isPrivateIpv6(hostname)1635    ) {1636      return false;1637    }16381639    return true;1640  } catch {1641    return false;1642  }1643}16441645function isPrivateIpv4(hostname: string): boolean {1646  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1647    return true;1648  }16491650  const octets = hostname.split(".").map((part) => Number(part));1651  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1652    return false;1653  }16541655  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1656}16571658function isPrivateIpv6(hostname: string): boolean {1659  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1660  // IPv4-mapped IPv6 literals embed a plain IPv4 address that the prefix1661  // list below can never match (WHATWG URL serializes [::ffff:192.168.0.1]1662  // as ::ffff:c0a8:1). Unwrap and test the embedded IPv4; unparseable mapped1663  // tails fail closed. (Codex Security 2026-08-04 LOW,1664  // ssrf.webhook-url-private-ip-filter.) DNS rebinding is out of scope for a1665  // one-shot host check.1666  const mapped = /^::ffff:(.+)$/.exec(normalized);1667  if (mapped) {1668    const tail = mapped[1] ?? "";1669    if (tail.includes(".")) return isPrivateIpv4(tail);1670    const parts = tail.split(":");1671    const [hi, lo] = parts;1672    if (1673      parts.length !== 2 ||1674      !hi ||1675      !lo ||1676      !/^[0-9a-f]{1,4}$/.test(hi) ||1677      !/^[0-9a-f]{1,4}$/.test(lo)1678    ) {1679      return true;1680    }1681    const octets = [1682      (Number.parseInt(hi, 16) >>> 8) & 0xff,1683      Number.parseInt(hi, 16) & 0xff,1684      (Number.parseInt(lo, 16) >>> 8) & 0xff,1685      Number.parseInt(lo, 16) & 0xff,1686    ];1687    return isPrivateIpv4(octets.join("."));1688  }1689  return (1690    normalized === "::1" ||1691    normalized.startsWith("fc") ||1692    normalized.startsWith("fd") ||1693    normalized.startsWith("fe80:")1694  );1695}