messages.ts

71.2 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) {331          const status = await vault.getPinUnlockStatus();332          if (status.configured && !status.available) {333            return {334              ok: false,335              error: status.attemptsRemaining === 0336                ? "pin_attempts_exceeded"337                : "pin_session_expired",338            };339          }340          return { ok: false };341        }342        const kat = await runSelfTest();343        if (!kat.ok) {344          await vault.lock();345          return { ok: false, error: "self_test_failed" };346        }347        await vault.updateSettings({ pinPreferred: true });348        await setupAutoLock();349        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });350        onVaultUnlocked();351        return { ok: true };352      }353      case "GET_PIN_STATUS":354        return { ok: true, data: await vault.getPinUnlockStatus() };355      case "VALIDATE_RECOVERY_WORDS": {356        const { words } = msg.payload as { words: string[] };357        const invalid = findInvalidWords(words);358        return { ok: true, data: { valid: invalid.length === 0, invalid } };359      }360      case "GET_RECOVERY_WORDS": {361        // Must be unlocked and have recovery set up (vault must be v2.12+).362        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };363        // LV-4: the recovery words re-derive the ROOT KEY — the highest-364        // value secret in the vault. A session unlock (which may be hours365        // old on a shared machine) is not enough; require a fresh password366        // proof, matching the 1Password/Bitwarden pattern for revealing367        // escrow material. EXEMPTION: the create-vault / rotation confirmation368        // window (peach_recovery_pending) shows the words immediately after369        // the user authenticated, and that confirmation UI has no password to370        // resend — skip the re-auth there only.371        if (!(await isRecoveryConfirmPending())) {372          const { password } = (msg.payload ?? {}) as { password?: string };373          if (typeof password !== "string" || !password) {374            return { ok: false, error: "password_required" };375          }376          if (!(await vault.verifyMainPassword(password))) {377            return { ok: false, error: "wrong_password" };378          }379        }380        try {381          const words = await vault.getRecoveryWords();382          return { ok: true, data: words };383        } catch {384          return { ok: false, error: "recovery_not_setup" };385        }386      }387      case "GET_RECOVERY_CONFIRM_PENDING":388        return { ok: true, data: await isRecoveryConfirmPending() };389      case "SET_RECOVERY_CONFIRM_PENDING":390        await setRecoveryConfirmPending();391        return { ok: true };392      case "CLEAR_RECOVERY_CONFIRM_PENDING":393        await clearRecoveryConfirmPending();394        return { ok: true };395      case "RECOVER_WITH_WORDS": {396        // User has lost their password but has their 12 recovery words.397        // We: (1) validate the words, (2) re-encrypt vault with new password.398        const { words, newPassword } = msg.payload as {399          words: string[];400          newPassword: string;401        };402        const stored = await vault.loadSlotA();403        if (!stored) return { ok: false, error: "no_vault" };404        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {405          return { ok: false, error: "recovery_not_setup" };406        }407        // Unwrap the root key from the recovery escrow.408        try {409          await vault.unwrapRootKeyForRecovery(410            stored.recovery_wrapped_root_key,411            stored.recovery_nonce ?? "",412            stored.recovery_tag ?? "",413            stored.recovery_salt,414            words415          );416        } catch {417          return { ok: false, error: "invalid_recovery_words" };418        }419        // Re-key: derive fresh salt + key from new password.420        const newSalt = vault.generateSalt();421        const newKey = await vault.deriveKey(newPassword, newSalt);422        // Re-wrap root key under the new password's derived key so the same423        // recovery words continue to work after the password change.424        await vault.rewrapRootKeyForPassword(newKey, newSalt);425        // Re-encrypt vault entries with the new key.426        await vault.changePasswordWithNewKey(newSalt, newKey);427        await setupAutoLock();428        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });429        return { ok: true };430      }431      case "LOCK":432        vault.lock();433        return { ok: true };434      case "IS_UNLOCKED":435        return { ok: true, data: vault.isUnlocked() };436      case "GET_VAULT_STATUS":437        return { ok: true, unlocked: vault.isUnlocked() };438      case "HAS_VAULT":439        return { ok: true, data: await vault.hasVault() };440      case "GET_ENTRIES":441        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };442        return { ok: true, data: vault.getEntries() };443      case "ADD_ENTRY": {444        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };445        const payload = msg.payload;446        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {447          return { ok: false, error: "invalid_payload" };448        }449        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);450        return { ok: true, data: entry };451      }452      case "BATCH_ADD_ENTRIES": {453        const payload = msg.payload as { entries?: unknown } | null | undefined;454        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {455          return { ok: false, error: "invalid_payload" };456        }457        if (!Array.isArray(payload.entries)) {458          return { ok: false, error: "invalid_payload" };459        }460        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);461        return { ok: true, data: added };462      }463      case "RESTORE_ENTRIES": {464        const payload = msg.payload as465          | { entries?: unknown; mode?: unknown; settings?: unknown }466          | null467          | undefined;468        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {469          return { ok: false, error: "invalid_payload" };470        }471        if (!Array.isArray(payload.entries)) {472          return { ok: false, error: "invalid_payload" };473        }474        if (payload.mode !== "replace" && payload.mode !== "merge") {475          return { ok: false, error: "invalid_payload" };476        }477        const summary = await vault.restoreEntries(478          payload.entries as Parameters<typeof vault.restoreEntries>[0],479          payload.mode480        );481        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {482          await vault.updateSettings(payload.settings as vault.VaultSettings);483        }484        return { ok: true, data: summary };485      }486      case "CLEAR_VAULT_ENTRIES": {487        await vault.clearVaultEntries("REPLACE_ALL");488        return { ok: true };489      }490      case "GET_VAULT_HISTORY": {491        const snapshots = await vault.getVaultHistory();492        return { ok: true, data: snapshots };493      }494      case "RESTORE_VAULT_SNAPSHOT": {495        const { snapshotId } = msg.payload as { snapshotId: string };496        const result = await vault.restoreVaultSnapshot(snapshotId);497        if (!result.ok) return { ok: false, error: result.error };498        broadcastToContentScripts({ type: "VAULT_LOCKED" });499        return { ok: true };500      }501      case "COUNT_DUPLICATES": {502        return { ok: true, data: vault.countDuplicates() };503      }504      case "DEDUPLICATE_ENTRIES": {505        const removed = await vault.deduplicateEntries();506        return { ok: true, data: removed };507      }508      case "UPDATE_ENTRY": {509        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;510        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {511          return { ok: false, error: "invalid_payload" };512        }513        const { id, patch } = payload;514        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {515          return { ok: false, error: "invalid_payload" };516        }517        // Single enforcement point for the Canary Entries Pro gate. Only518        // gates the transition into a canary entry — clearing/disabling a519        // canary (`canary: undefined`) is always allowed, so existing520        // canary entries remain manageable.521        const incomingCanary = (patch as { canary?: unknown }).canary;522        if (incomingCanary && typeof incomingCanary === "object") {523          const existing = vault.getEntryById(id);524          if (!existing?.canary) {525            const gate = await requirePro("canary_entry");526            if (!gate.allowed) return { ok: false, error: "pro_required" };527          }528        }529        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);530        return { ok: true };531      }532      case "ADD_ADDITIONAL_URL": {533        const { id, url } = msg.payload as { id: string; url: string };534        const trimmed = typeof url === "string" ? url.trim() : "";535        if (!trimmed) return { ok: false, error: "url_required" };536        const existing = vault.getEntryById(id);537        if (!existing) return { ok: false, error: "entry_not_found" };538        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };539        const merged = [...(existing.additionalUrls ?? []), trimmed];540        await vault.updateEntry(id, { additionalUrls: merged });541        return { ok: true };542      }543      case "DELETE_ENTRY": {544        const { id } = msg.payload as { id: string };545        await vault.deleteEntry(id);546        return { ok: true };547      }548      case "GET_DELETED_ENTRIES":549        return { ok: true, data: vault.getDeletedEntries() };550      case "RESTORE_ENTRY": {551        const { id } = msg.payload as { id: string };552        await vault.restoreEntry(id);553        return { ok: true };554      }555      case "PURGE_ENTRY": {556        const { id } = msg.payload as { id: string };557        await vault.purgeEntry(id);558        return { ok: true };559      }560      case "PURGE_EXPIRED_TRASH": {561        const { retentionMs } = msg.payload as { retentionMs: number };562        const purged = await vault.purgeExpiredTrash(retentionMs);563        return { ok: true, data: purged };564      }565      case "SAVE_NOTE": {566        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };567        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };568        const now = Date.now();569        if (id) {570          const existing = vault.getEntryById(id);571          if (!existing) return { ok: false, error: "not_found" };572          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });573          return { ok: true, data: vault.getEntryById(id) };574        } else {575          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt576          // (EntryDraft omits both), so passing them was the only reason the577          // `as any` cast existed. Dropping them makes the call type-check.578          const entry = await vault.addEntry({579            type: "note",580            title: title || "Untitled",581            notes: body,582          });583          return { ok: true, data: entry };584        }585      }586      case "DELETE_NOTE": {587        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };588        const { id } = msg.payload as { id: string };589        await vault.deleteEntry(id);590        return { ok: true };591      }592      case "GET_NOTES": {593        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };594        const notes = vault.getEntries().filter(595          (e) => e.type === "note" && !e.deletedAt596        );597        return { ok: true, data: notes } as MessageResponse;598      }599      case "SEARCH_VAULT": {600        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };601        // AUD-002: shape-validate the payload before calling string methods.602        // A raw cast lets a malformed message crash the handler with TypeError.603        const { query } = (msg.payload ?? {}) as { query?: unknown };604        if (typeof query !== "string") {605          return { ok: false, error: "invalid_payload" };606        }607        const q = query.toLowerCase();608        const searchResults = vault.getEntries().filter(609          (e) =>610            !e.deletedAt &&611            (e.title.toLowerCase().includes(q) ||612              e.notes?.toLowerCase().includes(q) ||613              e.username?.toLowerCase().includes(q))614        );615        return { ok: true, data: searchResults } as MessageResponse;616      }617      case "AUTOFILL_QUERY": {618        if (!vault.isUnlocked()) {619          return { ok: false, error: "vault_locked" };620        }621        let { includeAll } = msg.payload as { includeAll?: boolean };622        const { domain, kind, userGesture } = msg.payload as {623          domain: string;624          kind?: "login" | "card" | "totp";625          userGesture?: boolean;626        };627        // MV-2: the vault-wide inventory (every title/username/email/url)628        // may only leave the background on an explicit user gesture — the629        // user opening the search affordance — never on passive form focus.630        // userGesture is self-declared by our own content script; the value631        // of this gate is that PASSIVE code paths (which never set it)632        // cannot ship the inventory, shrinking what a compromised page that633        // merely triggers focus events can observe.634        if (includeAll && userGesture !== true) {635          includeAll = false;636        }637        // kind="card": return saved cards as compact summaries for the638        // inline card silver platter. Cards are not domain-scoped — every639        // saved card is a candidate on every checkout page — so domain is640        // ignored when kind === "card".641        if (kind === "card") {642          const cards = vault.getEntries().filter((e) => e.type === "card");643          return {644            ok: true,645            data: cards.map((e) => ({646              id: e.id,647              title: e.cardNickname || e.title,648              cardholderName: e.cardholderName,649              last4: e.last4,650              expMonth: e.expMonth,651              expYear: e.expYear,652              network: e.network,653            })),654          };655        }656        if (kind === "totp") {657          const matches = (658            includeAll659              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")660              : vault.queryDomain(domain)661          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));662          return {663            ok: true,664            data: matches.map((e) => ({665              id: e.id,666              title: e.title,667              username: e.username,668              email: e.email,669              url: e.url,670              hasTotp: true,671            })),672          };673        }674        // The inline selector fills username+password into a form. Passkey-675        // only entries have no password to fill; sign-in for those goes676        // through the WebAuthn path instead. Filter them out everywhere so677        // the user doesn't see four "GitHub" rows that mostly do nothing.678        // Notes and cards never belonged here either.679        const matches = (680          includeAll681            ? vault682                .getEntries()683                .filter((entry) => entry.type !== "note" && entry.type !== "card")684            : vault.queryDomain(domain)685        ).filter((entry) => !isPasskeyOnly(entry));686        return {687          ok: true,688          data: matches.map((e) =>689            includeAll690              ? {691                  id: e.id,692                  title: e.title,693                  // username/email/url shipped so the inline popup's search694                  // affordance can match on them, not just titles. No secrets695                  // cross the boundary — same shape as the domain-matched696                  // response below minus hasTotp (which the search list697                  // doesn't surface).698                  username: e.username,699                  email: e.email,700                  url: e.url,701                  hasPasskey: e.passkey !== undefined,702                }703              : {704                  id: e.id,705                  title: e.title,706                  username: e.username,707                  email: e.email,708                  url: e.url,709                  hasTotp: Boolean(e.totp),710                  hasPasskey: e.passkey !== undefined,711                }712          ),713        };714      }715      case "GET_ENTRY_FOR_FILL": {716        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };717        const { id, explicitSummon } = msg.payload as {718          id: string;719          explicitSummon?: boolean;720        };721        const entry = vault.getEntryById(id);722        if (!entry) return { ok: false, error: "entry_not_found" };723        // Passkey-only entries (passkey credential, no password) cannot be724        // filled into a form — sign-in goes through the WebAuthn path. A725        // login that ALSO has a passkey is still fillable for its password.726        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };727728        // MV-1: re-validate the entry against the requesting frame's origin.729        // sender.url / sender.tab.url are browser-attested — a page cannot730        // forge them. PB-26-005: the FRAME url (sender.url) is authoritative731        // for an all_frames content script; the top-frame tab.url would732        // misattribute a cross-origin iframe's request to the top page. When733        // the request does not come from a tab at all (popup surfaces use734        // GET_ENTRY_FOR_EDIT, not this), refuse.735        if (sender.tab !== undefined || sender.url !== undefined) {736          let senderDomain: string | null = null;737          try {738            const rawUrl = sender.url ?? sender.tab?.url ?? "";739            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;740          } catch {741            senderDomain = null;742          }743          if (!senderDomain) return { ok: false, error: "origin_unverified" };744745          const entryDomains = new Set<string>();746          const primary = extractDomain(entry.url ?? "");747          if (primary) entryDomains.add(primary);748          for (const extra of entry.additionalUrls ?? []) {749            const d = extractDomain(extra);750            if (d) entryDomains.add(d);751          }752753          // explicitSummon=true means the user actively picked this entry754          // from the cross-domain search affordance — an intentional755          // off-domain fill. Passive fill paths must stay domain-bound.756          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {757            // Domain mismatch — refuse silently (no oracle about which ids exist).758            return { ok: false, error: "entry_not_found" };759          }760        }761        // Strip the passkey credential AND the raw base32 TOTP seed from the762        // response. Content scripts never need either: the private key is the763        // authenticator's, and handing over the TOTP seed would let a764        // compromised content script mint valid codes indefinitely (SEV-3-C).765        // Generate the *current* 6-digit code here in the background and send766        // only that, plus the seconds left so the UI can render a countdown.767        // Also drop passwordHistory: filling needs only the *current* password.768        // Handing every past password to a content script during passive769        // autofill on an arbitrary page would widen the blast radius of a770        // compromised page far beyond the one credential being filled.771        const {772          passkey: _strippedPasskey,773          totp: seed,774          totpAlgorithm,775          totpDigits,776          totpPeriod,777          passwordHistory: _ph,778          ...safeEntry779        } = entry;780        let totpCode: string | undefined;781        let totpRemaining: number | undefined;782        if (seed) {783          try {784            // PCH-01-019: honour stored algorithm/digits/period (defaults apply785            // when these are undefined, i.e. RFC-default bare-seed entries).786            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);787            totpCode = generated.code;788            totpRemaining = generated.remaining;789          } catch {790            totpCode = undefined;791          }792        }793        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };794      }795      // Trusted full-entry fetch for Peach's own inline-popup surfaces that796      // genuinely need the raw TOTP seed: the edit form (which re-saves the797      // seed and would otherwise wipe it) and nothing else. Unlike798      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside799      // the inline popup, never during passive autofill on an arbitrary page.800      // The passkey credential is still stripped — the edit form never touches it.801      case "GET_ENTRY_FOR_EDIT": {802        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };803        const { id, explicitSummon } = msg.payload as {804          id: string;805          explicitSummon?: boolean;806        };807        const entry = vault.getEntryById(id);808        if (!entry) return { ok: false, error: "entry_not_found" };809810        // PCH-01-006: re-validate the browser-attested sender origin, mirroring811        // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and812        // full password history — at least as sensitive as the fill response — so813        // the boundary must be enforced here, not only by UI reachability. Today814        // the sole caller is the popup (no sender.tab, so this is a structural815        // no-op), but a future tab-context caller or an id leak would otherwise816        // inherit a full-credential oracle. Unlike the fill path we SKIP (not817        // refuse) when no sender domain resolves, to keep the popup caller working.818        // PB-26-005: the frame url (sender.url) is authoritative over the819        // top-frame sender.tab.url — mirrors the fill path.820        if (sender.tab !== undefined || sender.url !== undefined) {821          let senderDomain: string | null = null;822          try {823            const rawUrl = sender.url ?? sender.tab?.url ?? "";824            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;825          } catch {826            senderDomain = null;827          }828          if (senderDomain) {829            const entryDomains = new Set<string>();830            const primary = extractDomain(entry.url ?? "");831            if (primary) entryDomains.add(primary);832            for (const extra of entry.additionalUrls ?? []) {833              const d = extractDomain(extra);834              if (d) entryDomains.add(d);835            }836            if (explicitSummon !== true && !entryDomains.has(senderDomain)) {837              return { ok: false, error: "entry_not_found" }; // no id oracle838            }839          }840        }841842        const { passkey: _passkey, ...safeEntry } = entry;843        return { ok: true, data: safeEntry };844      }845      case "COPY": {846        // AUD-002: shape-validate the payload before passing to the clipboard847        // helper. A raw cast lets a malformed message reach the clipboard API848        // with a non-string and throw.849        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {850          text?: unknown;851          label?: unknown;852          alreadyWritten?: unknown;853        };854        if (typeof text !== "string" || typeof label !== "string") {855          return { ok: false, error: "invalid_payload" };856        }857        await copyToClipboard(text, label, Boolean(alreadyWritten));858        return { ok: true, clearSeconds: getEffectiveClearSeconds() };859      }860      case "CHECK_ALL_BREACHES": {861        const allEntries = vault.getEntries();862        const results: Record<string, number> = {};863        for (const entry of allEntries) {864          if (entry.type === "note") continue;865          if (!entry.password) continue;866          results[entry.id] = await vault.checkBreach(entry.password);867          // Small delay — be a good citizen to the HIBP API868          await new Promise((r) => setTimeout(r, 200));869        }870        // Persist any non-zero counts back to entries871        for (const [id, count] of Object.entries(results)) {872          const entry = vault.getEntryById(id);873          if (entry && (entry.breach ?? 0) !== count) {874            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });875          }876        }877        return { ok: true, data: results };878      }879      case "GET_SETTINGS":880        return { ok: true, data: await vault.ensureSettingsLoaded() };881      case "UPDATE_SETTINGS": {882        const patch = msg.payload;883        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {884          return { ok: false, error: "invalid_payload" };885        }886        await vault.updateSettings(patch as vault.VaultSettings);887        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {888          await setupAutoLock();889          if (vault.isUnlocked()) touchAutoLock();890        }891        return { ok: true };892      }893      case "SETUP_PIN": {894        const { currentPassword, pin } = (msg.payload ?? {}) as {895          currentPassword?: unknown;896          pin?: unknown;897        };898        if (typeof currentPassword !== "string" || typeof pin !== "string") {899          return { ok: false, error: "invalid_payload" };900        }901        return (await vault.setupPinUnlock(currentPassword, pin))902          ? { ok: true }903          : { ok: false, error: "incorrect_current_password" };904      }905      case "DISABLE_PIN": {906        const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown };907        if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" };908        return (await vault.disablePinUnlock(currentPassword))909          ? { ok: true }910          : { ok: false, error: "incorrect_current_password" };911      }912      case "GET_PENDING_PASSKEY":913        return { ok: true, data: await getPendingPasskeyRequest() };914      case "APPROVE_PASSKEY": {915        const { requestId } = msg.payload as { requestId: number };916        await resolvePendingPasskeyRequest(requestId, true);917        return { ok: true };918      }919      case "DENY_PASSKEY": {920        const { requestId } = msg.payload as { requestId: number };921        await resolvePendingPasskeyRequest(requestId, false);922        return { ok: true };923      }924      case "GET_PASSKEY_PROVIDER_STATE":925        return { ok: true, data: await getPasskeyProviderState() };926      case "SET_PASSKEY_PROVIDER_ENABLED": {927        const { enabled } = msg.payload as { enabled: boolean };928        // Disabling is always free; gating fires only when a free user is929        // trying to turn passkey interception on.930        if (enabled) {931          const gate = await requirePro("passkeys");932          if (!gate.allowed) return { ok: false, error: "pro_required" };933        }934        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };935      }936      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS937      // endpoint. Intentional product behavior — users configure their own938      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private939      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-940      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to941      // users that the entry title leaves the device when the canary fires.942      case "FIRE_CANARY_PING": {943        // Canary alert fires unconditionally for any entry with canary: true.944        // The Pro gate only governs creation/flagging of canary entries; once945        // an entry is flagged, the alert path is a security property and must946        // never be license-gated.947        const { webhookUrl, entryTitle, trigger } = msg.payload as {948          webhookUrl: string;949          entryTitle: string;950          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";951        };952        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {953          return { ok: false, error: "invalid_webhook_url" };954        }955        // LV-3: debounce non-test pings per (webhook, entry) so a page that956        // strobes focus/fill events can't turn the canary into a request957        // firehose at the user's endpoint. Test pings are exempt — they are958        // explicit user clicks in the settings UI and are awaited for959        // feedback. The FIRST ping in a window always goes out, so the960        // dead-man's-switch property (canary fires on access) is preserved;961        // only repeats within the window are coalesced.962        if (trigger !== "test") {963          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;964          const stored = await chrome.storage.local.get(rlKey);965          const last = (stored as Record<string, unknown>)[rlKey];966          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {967            return { ok: true, data: { rateLimited: true } };968          }969          await chrome.storage.local.set({ [rlKey]: Date.now() });970        }971        const body = JSON.stringify({972          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",973          entry: entryTitle,974          trigger,975          timestamp: new Date().toISOString(),976          source: "peach-extension",977        });978        if (trigger === "test") {979          // Permitted outbound fetch: user-configured canary alert endpoint980          // (validated by isAllowedCanaryWebhookUrl above). This is the981          // only non-HIBP outbound call in the extension — see982          // Projects.md §3.7. Test pings are awaited so the UI can show983          // success/failure.984          try {985            const res = await fetch(webhookUrl, {986              method: "POST",987              headers: { "Content-Type": "application/json" },988              body,989            });990            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };991          } catch (err) {992            return { ok: false, error: err instanceof Error ? err.message : "network_error" };993          }994        }995        // Non-test triggers are fire-and-forget996        fetch(webhookUrl, {997          method: "POST",998          headers: { "Content-Type": "application/json" },999          body,1000        }).catch(() => {});1001        return { ok: true };1002      }1003      case "ACTIVATE_LICENSE": {1004        const { key } = msg.payload as { key: string };1005        const licenseInfo = await activateLicense(key);1006        return { ok: true, data: licenseInfo };1007      }1008      case "GET_LICENSE": {1009        const licenseInfo = await getLicenseInfo();1010        return { ok: true, data: licenseInfo };1011      }1012      case "GET_LICENSE_KEY": {1013        const key = await getLicenseKey();1014        return { ok: true, data: key };1015      }1016      case "DEACTIVATE_LICENSE": {1017        await deactivateLicense();1018        return { ok: true };1019      }1020      case "SHOULD_PLAY_CELEBRATION": {1021        const should = await shouldPlayCelebration();1022        return { ok: true, data: should };1023      }1024      case "MARK_CELEBRATION_PLAYED": {1025        await markCelebrationPlayed();1026        return { ok: true };1027      }1028      case "GET_CODEX_VAULT_DATA": {1029        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1030        // popup navigates to the License section without further coordination.1031        // Also privileged-page-gated (PB-26-001), and recoveryWords inside the1032        // snapshot additionally require a fresh master-password proof.1033        const gate = await requirePro("codex");1034        if (!gate.allowed) return { ok: false, error: "pro_required" };1035        const { password } = (msg.payload ?? {}) as { password?: string };1036        return await handleGetCodexVaultData(password);1037      }1038      case "ESTIMATE_CODEX_PAGES": {1039        const gate = await requirePro("codex");1040        if (!gate.allowed) return { ok: false, error: "pro_required" };1041        return await handleEstimateCodexPages();1042      }1043      case "RESTORE_FROM_CODEX": {1044        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1045        // be able to restore a vault that was printed by a Pro user.1046        // DO NOT add a Pro gate here.1047        const payload = msg.payload as CodexRestorePayload;1048        return await handleRestoreFromCodex(payload);1049      }1050      case "OPEN_PRO_GATE": {1051        // Content script requests: open popup and navigate to License section.1052        const { feature } = (msg.payload ?? {}) as { feature?: string };1053        if (chrome.storage.session) {1054          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1055        }1056        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1057        return { ok: true };1058      }1059      case "OPEN_POPUP": {1060        // Content script asks to open the trusted extension popup — used by the1061        // inline locked bubble so the master password is entered in the popup,1062        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1063        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1064        // toolbar icon. The badge already signals Peach needs attention.1065        //1066        // Set a session flag so the popup knows it was opened for inline unlock1067        // and should close itself once the vault is unlocked (returning the user1068        // to the inline autofill selector on the page).1069        if (chrome.storage.session) {1070          await chrome.storage.session.set({ peach_inline_unlock: true });1071        }1072        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1073        return { ok: true };1074      }1075      case "OPEN_DETACHED_POPUP": {1076        // A window created by the action popup and then orphaned with1077        // window.close() is cascaded shut by Chrome, so the file-picker1078        // flows (OS dialogs that dismiss the popup on focus loss) ask the SW1079        // to open the standalone window instead — the SW has no window to be1080        // associated with. The query string is allowlisted so this can never1081        // open an arbitrary URL.1082        const { route } = (msg.payload ?? {}) as { route?: string };1083        const search = route === "peachscript"1084          ? "?restore=peachscript"1085          : route === "csv"1086            ? "?restore=csv"1087            : route === "codex-pdf"1088              ? "?codex=pdf"1089              : null;1090        if (!search) return { ok: false, error: "bad_route" };1091        try {1092          const popupHtml =1093            chrome.runtime.getManifest().action?.default_popup ?? "src/popup/index.html";1094          await chrome.windows.create({1095            url: chrome.runtime.getURL(`${popupHtml}${search}`),1096            type: "popup",1097            width: 320,1098            height: 550,1099          });1100          return { ok: true, data: { detached: true } };1101        } catch {1102          return { ok: false };1103        }1104      }1105      case "GET_IDENTITIES": {1106        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1107        return { ok: true, data: vault.getIdentities() };1108      }1109      case "TOUCH_AUTO_LOCK": {1110        // touchAutoLock() is already called by shouldRefreshAutoLock above;1111        // this case just gives the popup a typed message to keep the session alive.1112        return { ok: true };1113      }1114      case "GET_ADVANCED_HEALTH_REPORT": {1115        const gate = await requirePro("advanced_health");1116        if (!gate.allowed) return { ok: false, error: "pro_required" };1117        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1118        const report = await buildAdvancedHealthReport(vault.getEntries());1119        return { ok: true, data: report };1120      }1121      case "IS_DURESS_ENABLED": {1122        const enabled = await vault.isDuressEnabled();1123        return { ok: true, data: enabled };1124      }1125      case "SETUP_DURESS": {1126        // Single enforcement point for the Duress Vault Pro gate. Free users1127        // who somehow reach this handler are rejected here; the popup also1128        // pre-checks isPro() to avoid showing the setup form to free users,1129        // but server-side is the actual security boundary.1130        const gate = await requirePro("duress_vault");1131        if (!gate.allowed) return { ok: false, error: "pro_required" };1132        // MV3 service workers restart after inactivity, losing the in-memory1133        // derived key. Detect this before calling setupDuress so the popup1134        // can show a meaningful prompt to re-lock and re-unlock.1135        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1136        const { duressPassword } = msg.payload as { duressPassword: string };1137        await vault.setupDuress(duressPassword);1138        return { ok: true };1139      }1140      case "DISABLE_DURESS": {1141        await vault.disableDuress();1142        return { ok: true };1143      }1144      case "VERIFY_MAIN_PASSWORD": {1145        const { password } = msg.payload as { password: string };1146        const ok = await vault.verifyMainPassword(password);1147        return { ok: true, data: ok };1148      }1149      case "CHANGE_PASSWORD": {1150        const { currentPassword, newPassword } = msg.payload as {1151          currentPassword: string;1152          newPassword: string;1153        };1154        const changed = await vault.changePassword(currentPassword, newPassword);1155        return changed1156          ? { ok: true }1157          : { ok: false, error: "incorrect_current_password" };1158      }1159      case "GET_SITE_PASSWORD_POLICY": {1160        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1161        if (!tab?.id) return { ok: true, data: null };1162        try {1163          const response = await chrome.tabs.sendMessage(tab.id, {1164            type: "GET_SITE_PASSWORD_POLICY",1165          });1166          return (response as MessageResponse) ?? { ok: true, data: null };1167        } catch {1168          return { ok: true, data: null };1169        }1170      }1171      case "RECORD_MANUAL_SUMMON": {1172        const { domain } = msg.payload as { domain: string };1173        const settings = vault.getSettings();1174        const existing = settings.manualSummonDomains?.[domain];1175        const now = Date.now();1176        await vault.updateSettings({1177          manualSummonDomains: {1178            ...settings.manualSummonDomains,1179            [domain]: {1180              firstSummonedAt: existing?.firstSummonedAt ?? now,1181              summonCount: (existing?.summonCount ?? 0) + 1,1182              lastSummonedAt: now,1183            },1184          },1185        });1186        return { ok: true };1187      }1188      case "DECLINE_CARD_SAVE": {1189        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1190        await vault.declineCardSaveOffer(last4, expMonth, expYear);1191        return { ok: true };1192      }1193      case "IS_CARD_DECLINED": {1194        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1195        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1196        return { ok: true, data: declined };1197      }1198      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1199        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1200          rpId?: string;1201          rpName?: string;1202          userName?: string;1203          userDisplayName?: string;1204        };1205        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1206        return await initiateFirefoxPasskeyCreate({1207          rpId,1208          rpName: rpName ?? rpId,1209          userName,1210          userDisplayName,1211        }, attestedSenderOrigin(sender));1212      }12131214      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1215        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1216        if (!payload) return { ok: false, error: "missing_payload" };1217        return await completeFirefoxPasskeyCreate(payload);1218      }12191220      case "PASSKEY_OFFER_DECLINE": {1221        const { domain } = (msg.payload ?? {}) as { domain?: string };1222        if (!domain) return { ok: false, error: "domain_required" };1223        await recordPasskeyOfferDecline(domain);1224        return { ok: true };1225      }12261227      case "GET_PASSKEY_OFFER_DECLINED": {1228        const { domain } = (msg.payload ?? {}) as { domain?: string };1229        if (!domain) return { ok: false, error: "domain_required" };1230        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1231      }12321233      case "PASSKEY_HAS_CREDENTIALS": {1234        const payload = msg.payload as {1235          rpId?: string;1236          allowCredentials?: Array<{ id: string; type?: string }>;1237        } | undefined;1238        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1239        return await handlePasskeyHasCredentials({1240          rpId: payload.rpId,1241          allowCredentials: payload.allowCredentials ?? [],1242        }, attestedSenderOrigin(sender));1243      }12441245      case "PASSKEY_CREATE": {1246        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1247        if (!payload?.rpId || !payload?.userName) {1248          return { ok: false, error: "rpid_and_username_required" };1249        }1250        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1251      }12521253      case "PASSKEY_GET": {1254        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1255        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1256        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1257      }12581259      case "PASSKEY_AUTH_RESPONSE": {1260        const { requestId, approved } = (msg.payload ?? {}) as {1261          requestId?: string | number;1262          approved?: boolean;1263        };1264        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1265          return { ok: false, error: 'requestId and approved required' };1266        }1267        await resolvePendingPasskeyRequest(Number(requestId), approved);1268        return { ok: true };1269      }12701271      case "GET_PASSKEY_FOR_DOMAIN": {1272        const { domain } = (msg.payload ?? {}) as { domain?: string };1273        if (!domain) return { ok: false, error: "domain_required" };1274        // Scope to the caller's own origin: a page may only ask about passkeys1275        // for a domain it actually owns, so an arbitrary page cannot enumerate1276        // which sites the user holds passkeys for or read the username (audit MEDIUM).1277        const origin = attestedSenderOrigin(sender);1278        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1279        if (!vault.isUnlocked()) return { ok: true, data: null };1280        const match = vault1281          .getEntries()1282          .find((entry) => entry.passkey?.rpId === domain);1283        if (!match || !match.passkey) return { ok: true, data: null };1284        // Slim shape — only the fields State 11 needs. Never expose private1285        // key material, even though this is locked behind isUnlocked.1286        return {1287          ok: true,1288          data: {1289            rpId: match.passkey.rpId,1290            userName: match.passkey.userName,1291            browser: match.passkey.browser,1292          },1293        };1294      }12951296      case "DESTROY_VAULT": {1297        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1298        // storage.local.clear() wipes every Peach key (slots, settings, license,1299        // onboarded flag, history, sync state, declined cards, recall, etc.);1300        // session.clear() wipes pending passkey requests + pro-notice queues.1301        // Caller (Panic.tsx) handles UI navigation back to onboarding.1302        //1303        // The Pro license is the one thing that must survive: the user paid for1304        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1305        // Capture it before the clear and restore it after. peach_pro_celebrated1306        // rides along so the Pro celebration doesn't replay on the next unlock.1307        const preserved = await chrome.storage.local.get([1308          "peach_license",1309          "peach_pro_celebrated",1310        ]);1311        vault.lock();1312        await storageClear();1313        await vault.clearVaultHistory();1314        const toRestore: Record<string, unknown> = {};1315        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1316        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1317        if (Object.keys(toRestore).length > 0) {1318          await chrome.storage.local.set(toRestore);1319        }1320        if (chrome.storage.session) {1321          await chrome.storage.session.clear();1322        }1323        await clearRecoveryConfirmPending();1324        return { ok: true };1325      }13261327      case "GET_IDENTITY_SUGGESTIONS": {1328        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1329        const entries = vault.getEntries();1330        const suggestions = buildIdentitySuggestions(entries);1331        return { ok: true, data: { suggestions } };1332      }1333      case "ML_INIT":1334        return { ok: true };13351336      case "ML_PREDICT_BATCH": {1337        // AUD-002: shape-validate before forwarding to the ML helper.1338        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1339        if (!Array.isArray(featuresArray)) {1340          return { ok: false, error: "invalid_payload" };1341        }1342        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1343      }13441345      // ── Vault sync (v3) ───────────────────────────────────────────────1346      // Returns the public-facing local identity needed by the popup to1347      // drive Phase-1 audio pairing. The private long-term key never1348      // leaves the background.1349      case "GET_LOCAL_IDENTITY": {1350        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1351        // Pro license from an already-Pro peer (at least one device must be Pro).1352        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1353        // Identity derives from the stable root key, not the password-derived1354        // key, so pairing survives a master-password change (SEV-2-B).1355        const masterKeyHex = vault.getRootKeyHex();1356        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1357        const masterKey = unhexBytes(masterKeyHex);1358        try {1359          const identity = await buildLocalIdentity(masterKey);1360          // If this device is Pro, advertise the signed license so the peer can1361          // activate it after SAS confirmation — pairing carries Pro across.1362          if (await isProUser()) {1363            const license = await getLicenseKey();1364            if (license) (identity as { license?: string }).license = license;1365          }1366          return { ok: true, data: identity };1367        } finally {1368          masterKey.fill(0);1369        }1370      }13711372      case "LIST_PAIRED_DEVICES": {1373        const devices = await listPairedDevicesV3();1374        return { ok: true, data: { devices } };1375      }13761377      case "RENAME_PAIRED_DEVICE": {1378        const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string };1379        if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") {1380          return { ok: false, error: "invalid_payload" };1381        }1382        await renamePairedDeviceV3(deviceId, name);1383        return { ok: true };1384      }13851386      case "UNPAIR_DEVICE": {1387        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1388        if (typeof deviceId !== "string" || !deviceId) {1389          return { ok: false, error: "invalid_payload" };1390        }1391        // Removing a device REVOKES it rather than just dropping the local1392        // row: a plain removal is undone the moment any other peer vouches it1393        // back through a manifest, which is exactly what the relay makes easy.1394        await revokeDeviceByIdV3(deviceId, await getOrCreateDeviceId());1395        // Sync against the remaining hosts — the unpaired device no longer1396        // matters but the next alarm tick is up to ten minutes away.1397        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1398        return { ok: true };1399      }14001401      case "RENAME_LOCAL_DEVICE": {1402        const { name } = (msg.payload ?? {}) as { name?: string };1403        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1404        await setDeviceNameV3(name);1405        return { ok: true };1406      }14071408      // ── Relay pairing ─────────────────────────────────────────────────────1409      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1410      // session runs in the background; the SAS and the terminal result reach1411      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1412      case "START_ADOPTION_SOURCE": {1413        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1414        if (isRelayAdoptionSourceInFlight()) {1415          return { ok: false, error: "adoption_source_in_progress" };1416        }1417        try {1418          return { ok: true, data: await startRelayAdoptionSource() };1419        } catch (error) {1420          return {1421            ok: false,1422            error: error instanceof Error ? error.message : "adoption_source_failed",1423          };1424        }1425      }14261427      // Onboarding receiver — empty extension shows a QR, phone scans and1428      // sends the vault. The popup supplies the local-only password here so1429      // the background can wrap the adopted root key at rest without ever1430      // asking the user to retype it.1431      case "START_ADOPTION_RECEIVER": {1432        if (isRelayAdoptionSourceInFlight()) {1433          return { ok: false, error: "adoption_receiver_in_progress" };1434        }1435        const password = (msg.payload as { password?: unknown } | undefined)?.password;1436        if (typeof password !== "string" || password.length === 0) {1437          return { ok: false, error: "invalid_payload" };1438        }1439        try {1440          return { ok: true, data: await startRelayAdoptionReceiver(password) };1441        } catch (error) {1442          return {1443            ok: false,1444            error: error instanceof Error ? error.message : "adoption_receiver_failed",1445          };1446        }1447      }14481449      // Popup→bg counterpart to ADOPTION_SOURCE_SAS (receiver flow).1450      // The receiver now auto-accepts the SAS (both sides derive it from the1451      // same Noise handshake hash, so the codes match by construction) so1452      // the popup never has a SAS screen to tap on. The id round-trips the1453      // same way so a stale late response can't approve the wrong session.1454      // Popup→bg counterpart for the source flow: Confirm/Cancel on the1455      // source's SAS screen.14561457      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1458      // on the source's SAS screen. The id round-trips the same way so a stale1459      // late response can't approve the wrong session.1460      case "SOURCE_SAS_DECISION": {1461        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1462        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1463          return { ok: false, error: "invalid_payload" };1464        }1465        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1466      }14671468      case "CANCEL_ADOPTION_SOURCE": {1469        cancelRelayAdoptionSource();1470        return { ok: true };1471      }14721473      case "TRIGGER_SYNC": {1474        const payload = (msg.payload ?? {}) as {1475          reason?: "vault_change" | "foreground" | "manual";1476          force?: boolean;1477        };1478        const reason = payload.reason ?? "foreground";14791480        void triggerSyncIfReachable({ reason, force: payload.force === true });1481        return { ok: true };1482      }14831484      case "GET_SYNC_STATE": {1485        return { ok: true, data: getSyncState() };1486      }14871488      case "GET_SYNC_SETTINGS": {1489        return { ok: true, data: await getSyncSettings() };1490      }14911492      case "SET_SYNC_SETTINGS": {1493        const payload = (msg.payload ?? {}) as {1494          mode?: unknown;1495          relayUrl?: unknown;1496        };1497        try {1498          // A custom relay URL implies private mode; Peach's own relay stays1499          // public. See setRelayUrl.1500          if (payload.relayUrl !== undefined) {1501            if (typeof payload.relayUrl !== "string") {1502              return { ok: false, error: "invalid_relay_url" };1503            }1504            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1505          }1506          if (payload.mode !== undefined) {1507            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1508              return { ok: false, error: "invalid_sync_mode" };1509            }1510            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1511          }1512          return { ok: true, data: await getSyncSettings() };1513        } catch (error) {1514          return {1515            ok: false,1516            error: error instanceof Error ? error.message : "invalid_relay_url",1517          };1518        }1519      }15201521      case "GET_SYNC_ALERTS": {1522        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1523        const alerts = await getPendingSyncAlerts();1524        // The popup reads on open and acknowledges with consume:true after1525        // rendering, so a popup crash between read and render doesn't lose1526        // the alerts.1527        if (consume) await clearPendingSyncAlerts();1528        return { ok: true, data: alerts };1529      }15301531      case "GET_PENDING_VOUCHED_DEVICES": {1532        return { ok: true, data: await listPendingVouchedDevices() };1533      }1534      case "CONFIRM_VOUCHED_DEVICE": {1535        const { deviceId } = msg.payload as { deviceId: string };1536        const pending = await getPendingVouchedDevice(deviceId);1537        if (!pending) return { ok: false, error: "not_pending" };1538        // Last gate before a vouched device becomes a sync peer. A queue entry1539        // can predate the revocation that names it, so revocation is re-checked1540        // here rather than trusted to have swept the queue.1541        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {1542          await removePendingVouchedDevice(deviceId);1543          return { ok: false, error: "device_revoked" };1544        }1545        await upsertPairedDeviceV3({1546          deviceId: pending.deviceId,1547          deviceName: pending.deviceName,1548          deviceType:1549            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1550          longTermPublicKeyHex: pending.longTermPublicKeyHex,1551          signingPublicKeyHex: pending.signingPublicKeyHex,1552          wsPort: pending.wsPort,1553          pairedAt: pending.pairedAt,1554          trustSource: "vouched",1555        });1556        await removePendingVouchedDevice(deviceId);1557        // Newly confirmed vouched device is now a sync target — kick a round1558        // so the mesh introduction pays off without a 10-minute wait.1559        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1560        return { ok: true };1561      }1562      case "REJECT_VOUCHED_DEVICE": {1563        const { deviceId } = msg.payload as { deviceId: string };1564        await removePendingVouchedDevice(deviceId);1565        return { ok: true };1566      }1567      case "ROTATE_SYNC_IDENTITY": {1568        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1569        const result = await vault.rotateSyncIdentity();1570        return result.ok ? { ok: true } : { ok: false, error: result.error };1571      }15721573      default:1574        return { ok: false, error: "unknown_message_type" };1575    }1576  } catch (err) {1577    return {1578      ok: false,1579      error: err instanceof Error ? err.message : "operation_failed",1580    };1581  }1582}15831584// Returns username use-counts from the vault, sorted by frequency. Each row1585// also carries the entry's email so the popup can suggest the email/username1586// pair the user has actually used together.1587function buildIdentitySuggestions(1588  entries: VaultEntry[],1589): Array<{ email: string; username: string; count: number }> {1590  const usernameCounts = new Map<string, number>();1591  const usernameEmail = new Map<string, string>();1592  for (const entry of entries) {1593    const username = entry.username ?? "";1594    const email = (entry as VaultEntry & { email?: string }).email ?? "";1595    if (!username && !email) continue;1596    const key = username || email;1597    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1598    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1599  }1600  return Array.from(usernameCounts.entries())1601    .sort((a, b) => b[1] - a[1])1602    .map(([username, count]) => ({1603      email: usernameEmail.get(username) ?? "",1604      username,1605      count,1606    }));1607}16081609/** Notify all content scripts that the vault just became available. */1610function broadcastToContentScripts(message: { type: string }): void {1611  if (!chrome.tabs?.query) return;1612  chrome.tabs.query({}, (tabs) => {1613    for (const tab of tabs) {1614      if (tab.id !== undefined) {1615        chrome.tabs.sendMessage(tab.id, message).catch(() => {1616          // Tab may not have a content script — silently ignore1617        });1618      }1619    }1620  });1621}16221623function shouldRefreshAutoLock(type: MessageType): boolean {1624  return (1625    type !== "HAS_VAULT" &&1626    type !== "IS_UNLOCKED" &&1627    type !== "GET_VAULT_STATUS" &&1628    type !== "LOCK" &&1629    type !== "UPDATE_SETTINGS" &&1630    type !== "GET_PENDING_PASSKEY" &&1631    type !== "GET_PASSKEY_PROVIDER_STATE" &&1632    type !== "DECLINE_CARD_SAVE" &&1633    type !== "IS_CARD_DECLINED"1634  );1635}16361637function isAllowedCanaryWebhookUrl(value: string): boolean {1638  try {1639    const url = new URL(value);1640    if (url.protocol !== "https:") return false;16411642    const hostname = url.hostname.toLowerCase();1643    if (1644      hostname === "localhost" ||1645      hostname.endsWith(".localhost") ||1646      isPrivateIpv4(hostname) ||1647      isPrivateIpv6(hostname)1648    ) {1649      return false;1650    }16511652    return true;1653  } catch {1654    return false;1655  }1656}16571658function isPrivateIpv4(hostname: string): boolean {1659  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1660    return true;1661  }16621663  const octets = hostname.split(".").map((part) => Number(part));1664  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1665    return false;1666  }16671668  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1669}16701671function isPrivateIpv6(hostname: string): boolean {1672  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1673  // IPv4-mapped IPv6 literals embed a plain IPv4 address that the prefix1674  // list below can never match (WHATWG URL serializes [::ffff:192.168.0.1]1675  // as ::ffff:c0a8:1). Unwrap and test the embedded IPv4; unparseable mapped1676  // tails fail closed. (Codex Security 2026-08-04 LOW,1677  // ssrf.webhook-url-private-ip-filter.) DNS rebinding is out of scope for a1678  // one-shot host check.1679  const mapped = /^::ffff:(.+)$/.exec(normalized);1680  if (mapped) {1681    const tail = mapped[1] ?? "";1682    if (tail.includes(".")) return isPrivateIpv4(tail);1683    const parts = tail.split(":");1684    const [hi, lo] = parts;1685    if (1686      parts.length !== 2 ||1687      !hi ||1688      !lo ||1689      !/^[0-9a-f]{1,4}$/.test(hi) ||1690      !/^[0-9a-f]{1,4}$/.test(lo)1691    ) {1692      return true;1693    }1694    const octets = [1695      (Number.parseInt(hi, 16) >>> 8) & 0xff,1696      Number.parseInt(hi, 16) & 0xff,1697      (Number.parseInt(lo, 16) >>> 8) & 0xff,1698      Number.parseInt(lo, 16) & 0xff,1699    ];1700    return isPrivateIpv4(octets.join("."));1701  }1702  return (1703    normalized === "::1" ||1704    normalized.startsWith("fc") ||1705    normalized.startsWith("fd") ||1706    normalized.startsWith("fe80:")1707  );1708}