messages.ts

71.5 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    // Extension UI messages may legitimately omit sender.url. Resolve the248    // browser-attested extension origin only when a URL is present; this also249    // keeps test/runtime shims without getURL fail-closed for URL-bearing250    // senders instead of throwing before policy evaluation.251    const extensionOrigin = sender.url && typeof chrome.runtime.getURL === "function"252      ? chrome.runtime.getURL("")253      : "";254    if (!isMessageSenderAllowed(msg.type, sender, chrome.runtime.id, extensionOrigin)) {255      return { ok: false, error: "invalid_sender" };256    }257258    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {259      touchAutoLock();260    }261262    switch (msg.type) {263      case "CREATE_VAULT": {264        const { password } = msg.payload as { password: string };265        // Refuse to create a vault under an empty master password — the derived266        // key would be publicly known and the at-rest AES-GCM protection void267        // (audit HIGH; the CSV-import path previously passed ""). Length/strength268        // policy lives in the onboarding UI; this is the non-negotiable floor.269        if (typeof password !== "string" || password.length === 0) {270          return { ok: false, error: "invalid_payload" };271        }272        await vault.createVault(password);273        await setupAutoLock();274        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });275        onVaultUnlocked();276        return { ok: true };277      }278      case "CREATE_VAULT_FROM_ROOT_KEY": {279        const { password, rootKeyHex } = (msg.payload ?? {}) as {280          password?: unknown;281          rootKeyHex?: unknown;282        };283        if (typeof password !== "string" || password.length === 0 || typeof rootKeyHex !== "string") {284          return { ok: false, error: "invalid_payload" };285        }286287        try {288          const { vaultId } = await vault.createVaultFromRootKey(password, rootKeyHex);289          await setupAutoLock();290          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });291          onVaultUnlocked();292          return { ok: true, vaultId };293        } catch (err) {294          return { ok: false, error: err instanceof Error ? err.message : String(err) };295        }296      }297      case "UNLOCK": {298        const { password } = msg.payload as { password: string };299        const ok = await vault.unlock(password);300        if (ok) {301          // KAT: verify the WebCrypto stack is healthy before the user relies on it.302          // Runs after unlock so latency is hidden behind the vault-load time.303          const kat = await runSelfTest();304          if (!kat.ok) {305            console.error("[Peach] Crypto self-test FAILED:", kat.error);306            await vault.lock();307            return { ok: false, error: "self_test_failed" };308          }309          await vault.updateSettings({ pinPreferred: false });310          await setupAutoLock();311          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });312          onVaultUnlocked();313          return { ok: true };314        }315        // Distinguish corruption from wrong password so the popup can offer316        // a history-restore path instead of falsely accusing the user of317        // mistyping (M7/COR-007).318        const failure = vault.consumeLastUnlockFailureReason();319        if (failure) {320          return {321            ok: false,322            error: "vault_corrupted",323            canRestoreFromHistory: true,324          } as MessageResponse;325        }326        return { ok: false };327      }328      case "UNLOCK_WITH_PIN": {329        const { pin } = (msg.payload ?? {}) as { pin?: unknown };330        if (typeof pin !== "string") return { ok: false, error: "invalid_payload" };331        const ok = await vault.unlockWithPin(pin);332        if (!ok) {333          const status = await vault.getPinUnlockStatus();334          if (status.configured && !status.available) {335            return {336              ok: false,337              error: status.attemptsRemaining === 0338                ? "pin_attempts_exceeded"339                : "pin_session_expired",340            };341          }342          return { ok: false };343        }344        const kat = await runSelfTest();345        if (!kat.ok) {346          await vault.lock();347          return { ok: false, error: "self_test_failed" };348        }349        await vault.updateSettings({ pinPreferred: true });350        await setupAutoLock();351        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });352        onVaultUnlocked();353        return { ok: true };354      }355      case "GET_PIN_STATUS":356        return { ok: true, data: await vault.getPinUnlockStatus() };357      case "VALIDATE_RECOVERY_WORDS": {358        const { words } = msg.payload as { words: string[] };359        const invalid = findInvalidWords(words);360        return { ok: true, data: { valid: invalid.length === 0, invalid } };361      }362      case "GET_RECOVERY_WORDS": {363        // Must be unlocked and have recovery set up (vault must be v2.12+).364        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };365        // LV-4: the recovery words re-derive the ROOT KEY — the highest-366        // value secret in the vault. A session unlock (which may be hours367        // old on a shared machine) is not enough; require a fresh password368        // proof, matching the 1Password/Bitwarden pattern for revealing369        // escrow material. EXEMPTION: the create-vault / rotation confirmation370        // window (peach_recovery_pending) shows the words immediately after371        // the user authenticated, and that confirmation UI has no password to372        // resend — skip the re-auth there only.373        if (!(await isRecoveryConfirmPending())) {374          const { password } = (msg.payload ?? {}) as { password?: string };375          if (typeof password !== "string" || !password) {376            return { ok: false, error: "password_required" };377          }378          if (!(await vault.verifyMainPassword(password))) {379            return { ok: false, error: "wrong_password" };380          }381        }382        try {383          const words = await vault.getRecoveryWords();384          return { ok: true, data: words };385        } catch {386          return { ok: false, error: "recovery_not_setup" };387        }388      }389      case "GET_RECOVERY_CONFIRM_PENDING":390        return { ok: true, data: await isRecoveryConfirmPending() };391      case "SET_RECOVERY_CONFIRM_PENDING":392        await setRecoveryConfirmPending();393        return { ok: true };394      case "CLEAR_RECOVERY_CONFIRM_PENDING":395        await clearRecoveryConfirmPending();396        return { ok: true };397      case "RECOVER_WITH_WORDS": {398        // User has lost their password but has their 12 recovery words.399        // We: (1) validate the words, (2) re-encrypt vault with new password.400        const { words, newPassword } = msg.payload as {401          words: string[];402          newPassword: string;403        };404        const stored = await vault.loadSlotA();405        if (!stored) return { ok: false, error: "no_vault" };406        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {407          return { ok: false, error: "recovery_not_setup" };408        }409        // Unwrap the root key from the recovery escrow.410        try {411          await vault.unwrapRootKeyForRecovery(412            stored.recovery_wrapped_root_key,413            stored.recovery_nonce ?? "",414            stored.recovery_tag ?? "",415            stored.recovery_salt,416            words417          );418        } catch {419          return { ok: false, error: "invalid_recovery_words" };420        }421        // Re-key: derive fresh salt + key from new password.422        const newSalt = vault.generateSalt();423        const newKey = await vault.deriveKey(newPassword, newSalt);424        // Re-wrap root key under the new password's derived key so the same425        // recovery words continue to work after the password change.426        await vault.rewrapRootKeyForPassword(newKey, newSalt);427        // Re-encrypt vault entries with the new key.428        await vault.changePasswordWithNewKey(newSalt, newKey);429        await setupAutoLock();430        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });431        return { ok: true };432      }433      case "LOCK":434        vault.lock();435        return { ok: true };436      case "IS_UNLOCKED":437        return { ok: true, data: vault.isUnlocked() };438      case "GET_VAULT_STATUS":439        return { ok: true, unlocked: vault.isUnlocked() };440      case "HAS_VAULT":441        return { ok: true, data: await vault.hasVault() };442      case "GET_ENTRIES":443        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };444        return { ok: true, data: vault.getEntries() };445      case "ADD_ENTRY": {446        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };447        const payload = msg.payload;448        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {449          return { ok: false, error: "invalid_payload" };450        }451        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);452        return { ok: true, data: entry };453      }454      case "BATCH_ADD_ENTRIES": {455        const payload = msg.payload as { entries?: unknown } | null | undefined;456        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {457          return { ok: false, error: "invalid_payload" };458        }459        if (!Array.isArray(payload.entries)) {460          return { ok: false, error: "invalid_payload" };461        }462        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);463        return { ok: true, data: added };464      }465      case "RESTORE_ENTRIES": {466        const payload = msg.payload as467          | { entries?: unknown; mode?: unknown; settings?: unknown }468          | null469          | undefined;470        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {471          return { ok: false, error: "invalid_payload" };472        }473        if (!Array.isArray(payload.entries)) {474          return { ok: false, error: "invalid_payload" };475        }476        if (payload.mode !== "replace" && payload.mode !== "merge") {477          return { ok: false, error: "invalid_payload" };478        }479        const summary = await vault.restoreEntries(480          payload.entries as Parameters<typeof vault.restoreEntries>[0],481          payload.mode482        );483        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {484          await vault.updateSettings(payload.settings as vault.VaultSettings);485        }486        return { ok: true, data: summary };487      }488      case "CLEAR_VAULT_ENTRIES": {489        await vault.clearVaultEntries("REPLACE_ALL");490        return { ok: true };491      }492      case "GET_VAULT_HISTORY": {493        const snapshots = await vault.getVaultHistory();494        return { ok: true, data: snapshots };495      }496      case "RESTORE_VAULT_SNAPSHOT": {497        const { snapshotId } = msg.payload as { snapshotId: string };498        const result = await vault.restoreVaultSnapshot(snapshotId);499        if (!result.ok) return { ok: false, error: result.error };500        broadcastToContentScripts({ type: "VAULT_LOCKED" });501        return { ok: true };502      }503      case "COUNT_DUPLICATES": {504        return { ok: true, data: vault.countDuplicates() };505      }506      case "DEDUPLICATE_ENTRIES": {507        const removed = await vault.deduplicateEntries();508        return { ok: true, data: removed };509      }510      case "UPDATE_ENTRY": {511        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;512        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {513          return { ok: false, error: "invalid_payload" };514        }515        const { id, patch } = payload;516        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {517          return { ok: false, error: "invalid_payload" };518        }519        // Single enforcement point for the Canary Entries Pro gate. Only520        // gates the transition into a canary entry — clearing/disabling a521        // canary (`canary: undefined`) is always allowed, so existing522        // canary entries remain manageable.523        const incomingCanary = (patch as { canary?: unknown }).canary;524        if (incomingCanary && typeof incomingCanary === "object") {525          const existing = vault.getEntryById(id);526          if (!existing?.canary) {527            const gate = await requirePro("canary_entry");528            if (!gate.allowed) return { ok: false, error: "pro_required" };529          }530        }531        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);532        return { ok: true };533      }534      case "ADD_ADDITIONAL_URL": {535        const { id, url } = msg.payload as { id: string; url: string };536        const trimmed = typeof url === "string" ? url.trim() : "";537        if (!trimmed) return { ok: false, error: "url_required" };538        const existing = vault.getEntryById(id);539        if (!existing) return { ok: false, error: "entry_not_found" };540        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };541        const merged = [...(existing.additionalUrls ?? []), trimmed];542        await vault.updateEntry(id, { additionalUrls: merged });543        return { ok: true };544      }545      case "DELETE_ENTRY": {546        const { id } = msg.payload as { id: string };547        await vault.deleteEntry(id);548        return { ok: true };549      }550      case "GET_DELETED_ENTRIES":551        return { ok: true, data: vault.getDeletedEntries() };552      case "RESTORE_ENTRY": {553        const { id } = msg.payload as { id: string };554        await vault.restoreEntry(id);555        return { ok: true };556      }557      case "PURGE_ENTRY": {558        const { id } = msg.payload as { id: string };559        await vault.purgeEntry(id);560        return { ok: true };561      }562      case "PURGE_EXPIRED_TRASH": {563        const { retentionMs } = msg.payload as { retentionMs: number };564        const purged = await vault.purgeExpiredTrash(retentionMs);565        return { ok: true, data: purged };566      }567      case "SAVE_NOTE": {568        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };569        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };570        const now = Date.now();571        if (id) {572          const existing = vault.getEntryById(id);573          if (!existing) return { ok: false, error: "not_found" };574          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });575          return { ok: true, data: vault.getEntryById(id) };576        } else {577          // PCH-01-026 #10: addEntry stamps its own createdAt/modifiedAt578          // (EntryDraft omits both), so passing them was the only reason the579          // `as any` cast existed. Dropping them makes the call type-check.580          const entry = await vault.addEntry({581            type: "note",582            title: title || "Untitled",583            notes: body,584          });585          return { ok: true, data: entry };586        }587      }588      case "DELETE_NOTE": {589        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };590        const { id } = msg.payload as { id: string };591        await vault.deleteEntry(id);592        return { ok: true };593      }594      case "GET_NOTES": {595        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };596        const notes = vault.getEntries().filter(597          (e) => e.type === "note" && !e.deletedAt598        );599        return { ok: true, data: notes } as MessageResponse;600      }601      case "SEARCH_VAULT": {602        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };603        // AUD-002: shape-validate the payload before calling string methods.604        // A raw cast lets a malformed message crash the handler with TypeError.605        const { query } = (msg.payload ?? {}) as { query?: unknown };606        if (typeof query !== "string") {607          return { ok: false, error: "invalid_payload" };608        }609        const q = query.toLowerCase();610        const searchResults = vault.getEntries().filter(611          (e) =>612            !e.deletedAt &&613            (e.title.toLowerCase().includes(q) ||614              e.notes?.toLowerCase().includes(q) ||615              e.username?.toLowerCase().includes(q))616        );617        return { ok: true, data: searchResults } as MessageResponse;618      }619      case "AUTOFILL_QUERY": {620        if (!vault.isUnlocked()) {621          return { ok: false, error: "vault_locked" };622        }623        let { includeAll } = msg.payload as { includeAll?: boolean };624        const { domain, kind, userGesture } = msg.payload as {625          domain: string;626          kind?: "login" | "card" | "totp";627          userGesture?: boolean;628        };629        // MV-2: the vault-wide inventory (every title/username/email/url)630        // may only leave the background on an explicit user gesture — the631        // user opening the search affordance — never on passive form focus.632        // userGesture is self-declared by our own content script; the value633        // of this gate is that PASSIVE code paths (which never set it)634        // cannot ship the inventory, shrinking what a compromised page that635        // merely triggers focus events can observe.636        if (includeAll && userGesture !== true) {637          includeAll = false;638        }639        // kind="card": return saved cards as compact summaries for the640        // inline card silver platter. Cards are not domain-scoped — every641        // saved card is a candidate on every checkout page — so domain is642        // ignored when kind === "card".643        if (kind === "card") {644          const cards = vault.getEntries().filter((e) => e.type === "card");645          return {646            ok: true,647            data: cards.map((e) => ({648              id: e.id,649              title: e.cardNickname || e.title,650              cardholderName: e.cardholderName,651              last4: e.last4,652              expMonth: e.expMonth,653              expYear: e.expYear,654              network: e.network,655            })),656          };657        }658        if (kind === "totp") {659          const matches = (660            includeAll661              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")662              : vault.queryDomain(domain)663          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));664          return {665            ok: true,666            data: matches.map((e) => ({667              id: e.id,668              title: e.title,669              username: e.username,670              email: e.email,671              url: e.url,672              hasTotp: true,673            })),674          };675        }676        // The inline selector fills username+password into a form. Passkey-677        // only entries have no password to fill; sign-in for those goes678        // through the WebAuthn path instead. Filter them out everywhere so679        // the user doesn't see four "GitHub" rows that mostly do nothing.680        // Notes and cards never belonged here either.681        const matches = (682          includeAll683            ? vault684                .getEntries()685                .filter((entry) => entry.type !== "note" && entry.type !== "card")686            : vault.queryDomain(domain)687        ).filter((entry) => !isPasskeyOnly(entry));688        return {689          ok: true,690          data: matches.map((e) =>691            includeAll692              ? {693                  id: e.id,694                  title: e.title,695                  // username/email/url shipped so the inline popup's search696                  // affordance can match on them, not just titles. No secrets697                  // cross the boundary — same shape as the domain-matched698                  // response below minus hasTotp (which the search list699                  // doesn't surface).700                  username: e.username,701                  email: e.email,702                  url: e.url,703                  hasPasskey: e.passkey !== undefined,704                }705              : {706                  id: e.id,707                  title: e.title,708                  username: e.username,709                  email: e.email,710                  url: e.url,711                  hasTotp: Boolean(e.totp),712                  hasPasskey: e.passkey !== undefined,713                }714          ),715        };716      }717      case "GET_ENTRY_FOR_FILL": {718        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };719        const { id, explicitSummon } = msg.payload as {720          id: string;721          explicitSummon?: boolean;722        };723        const entry = vault.getEntryById(id);724        if (!entry) return { ok: false, error: "entry_not_found" };725        // Passkey-only entries (passkey credential, no password) cannot be726        // filled into a form — sign-in goes through the WebAuthn path. A727        // login that ALSO has a passkey is still fillable for its password.728        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };729730        // MV-1: re-validate the entry against the requesting frame's origin.731        // sender.url / sender.tab.url are browser-attested — a page cannot732        // forge them. PB-26-005: the FRAME url (sender.url) is authoritative733        // for an all_frames content script; the top-frame tab.url would734        // misattribute a cross-origin iframe's request to the top page. When735        // the request does not come from a tab at all (popup surfaces use736        // GET_ENTRY_FOR_EDIT, not this), refuse.737        if (sender.tab !== undefined || sender.url !== undefined) {738          let senderDomain: string | null = null;739          try {740            const rawUrl = sender.url ?? sender.tab?.url ?? "";741            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;742          } catch {743            senderDomain = null;744          }745          if (!senderDomain) return { ok: false, error: "origin_unverified" };746747          const entryDomains = new Set<string>();748          const primary = extractDomain(entry.url ?? "");749          if (primary) entryDomains.add(primary);750          for (const extra of entry.additionalUrls ?? []) {751            const d = extractDomain(extra);752            if (d) entryDomains.add(d);753          }754755          // explicitSummon=true means the user actively picked this entry756          // from the cross-domain search affordance — an intentional757          // off-domain fill. Passive fill paths must stay domain-bound.758          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {759            // Domain mismatch — refuse silently (no oracle about which ids exist).760            return { ok: false, error: "entry_not_found" };761          }762        }763        // Strip the passkey credential AND the raw base32 TOTP seed from the764        // response. Content scripts never need either: the private key is the765        // authenticator's, and handing over the TOTP seed would let a766        // compromised content script mint valid codes indefinitely (SEV-3-C).767        // Generate the *current* 6-digit code here in the background and send768        // only that, plus the seconds left so the UI can render a countdown.769        // Also drop passwordHistory: filling needs only the *current* password.770        // Handing every past password to a content script during passive771        // autofill on an arbitrary page would widen the blast radius of a772        // compromised page far beyond the one credential being filled.773        const {774          passkey: _strippedPasskey,775          totp: seed,776          totpAlgorithm,777          totpDigits,778          totpPeriod,779          passwordHistory: _ph,780          ...safeEntry781        } = entry;782        let totpCode: string | undefined;783        let totpRemaining: number | undefined;784        if (seed) {785          try {786            // PCH-01-019: honour stored algorithm/digits/period (defaults apply787            // when these are undefined, i.e. RFC-default bare-seed entries).788            const generated = generateTOTP(seed, totpAlgorithm, totpDigits, totpPeriod);789            totpCode = generated.code;790            totpRemaining = generated.remaining;791          } catch {792            totpCode = undefined;793          }794        }795        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };796      }797      // Trusted full-entry fetch for Peach's own inline-popup surfaces that798      // genuinely need the raw TOTP seed: the edit form (which re-saves the799      // seed and would otherwise wipe it) and nothing else. Unlike800      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside801      // the inline popup, never during passive autofill on an arbitrary page.802      // The passkey credential is still stripped — the edit form never touches it.803      case "GET_ENTRY_FOR_EDIT": {804        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };805        const { id, explicitSummon } = msg.payload as {806          id: string;807          explicitSummon?: boolean;808        };809        const entry = vault.getEntryById(id);810        if (!entry) return { ok: false, error: "entry_not_found" };811812        // PCH-01-006: re-validate the browser-attested sender origin, mirroring813        // GET_ENTRY_FOR_FILL (MV-1). The edit channel ships the raw TOTP seed and814        // full password history — at least as sensitive as the fill response — so815        // the boundary must be enforced here, not only by UI reachability. Today816        // the sole caller is the popup (no sender.tab, so this is a structural817        // no-op), but a future tab-context caller or an id leak would otherwise818        // inherit a full-credential oracle. Unlike the fill path we SKIP (not819        // refuse) when no sender domain resolves, to keep the popup caller working.820        // PB-26-005: the frame url (sender.url) is authoritative over the821        // top-frame sender.tab.url — mirrors the fill path.822        if (sender.tab !== undefined || sender.url !== undefined) {823          let senderDomain: string | null = null;824          try {825            const rawUrl = sender.url ?? sender.tab?.url ?? "";826            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;827          } catch {828            senderDomain = null;829          }830          if (senderDomain) {831            const entryDomains = new Set<string>();832            const primary = extractDomain(entry.url ?? "");833            if (primary) entryDomains.add(primary);834            for (const extra of entry.additionalUrls ?? []) {835              const d = extractDomain(extra);836              if (d) entryDomains.add(d);837            }838            if (explicitSummon !== true && !entryDomains.has(senderDomain)) {839              return { ok: false, error: "entry_not_found" }; // no id oracle840            }841          }842        }843844        const { passkey: _passkey, ...safeEntry } = entry;845        return { ok: true, data: safeEntry };846      }847      case "COPY": {848        // AUD-002: shape-validate the payload before passing to the clipboard849        // helper. A raw cast lets a malformed message reach the clipboard API850        // with a non-string and throw.851        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {852          text?: unknown;853          label?: unknown;854          alreadyWritten?: unknown;855        };856        if (typeof text !== "string" || typeof label !== "string") {857          return { ok: false, error: "invalid_payload" };858        }859        await copyToClipboard(text, label, Boolean(alreadyWritten));860        return { ok: true, clearSeconds: getEffectiveClearSeconds() };861      }862      case "CHECK_ALL_BREACHES": {863        const allEntries = vault.getEntries();864        const results: Record<string, number> = {};865        for (const entry of allEntries) {866          if (entry.type === "note") continue;867          if (!entry.password) continue;868          results[entry.id] = await vault.checkBreach(entry.password);869          // Small delay — be a good citizen to the HIBP API870          await new Promise((r) => setTimeout(r, 200));871        }872        // Persist any non-zero counts back to entries873        for (const [id, count] of Object.entries(results)) {874          const entry = vault.getEntryById(id);875          if (entry && (entry.breach ?? 0) !== count) {876            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });877          }878        }879        return { ok: true, data: results };880      }881      case "GET_SETTINGS":882        return { ok: true, data: await vault.ensureSettingsLoaded() };883      case "UPDATE_SETTINGS": {884        const patch = msg.payload;885        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {886          return { ok: false, error: "invalid_payload" };887        }888        await vault.updateSettings(patch as vault.VaultSettings);889        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {890          await setupAutoLock();891          if (vault.isUnlocked()) touchAutoLock();892        }893        return { ok: true };894      }895      case "SETUP_PIN": {896        const { currentPassword, pin } = (msg.payload ?? {}) as {897          currentPassword?: unknown;898          pin?: unknown;899        };900        if (typeof currentPassword !== "string" || typeof pin !== "string") {901          return { ok: false, error: "invalid_payload" };902        }903        return (await vault.setupPinUnlock(currentPassword, pin))904          ? { ok: true }905          : { ok: false, error: "incorrect_current_password" };906      }907      case "DISABLE_PIN": {908        const { currentPassword } = (msg.payload ?? {}) as { currentPassword?: unknown };909        if (typeof currentPassword !== "string") return { ok: false, error: "invalid_payload" };910        return (await vault.disablePinUnlock(currentPassword))911          ? { ok: true }912          : { ok: false, error: "incorrect_current_password" };913      }914      case "GET_PENDING_PASSKEY":915        return { ok: true, data: await getPendingPasskeyRequest() };916      case "APPROVE_PASSKEY": {917        const { requestId } = msg.payload as { requestId: number };918        await resolvePendingPasskeyRequest(requestId, true);919        return { ok: true };920      }921      case "DENY_PASSKEY": {922        const { requestId } = msg.payload as { requestId: number };923        await resolvePendingPasskeyRequest(requestId, false);924        return { ok: true };925      }926      case "GET_PASSKEY_PROVIDER_STATE":927        return { ok: true, data: await getPasskeyProviderState() };928      case "SET_PASSKEY_PROVIDER_ENABLED": {929        const { enabled } = msg.payload as { enabled: boolean };930        // Disabling is always free; gating fires only when a free user is931        // trying to turn passkey interception on.932        if (enabled) {933          const gate = await requirePro("passkeys");934          if (!gate.allowed) return { ok: false, error: "pro_required" };935        }936        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };937      }938      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS939      // endpoint. Intentional product behavior — users configure their own940      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private941      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-942      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to943      // users that the entry title leaves the device when the canary fires.944      case "FIRE_CANARY_PING": {945        // Canary alert fires unconditionally for any entry with canary: true.946        // The Pro gate only governs creation/flagging of canary entries; once947        // an entry is flagged, the alert path is a security property and must948        // never be license-gated.949        const { webhookUrl, entryTitle, trigger } = msg.payload as {950          webhookUrl: string;951          entryTitle: string;952          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";953        };954        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {955          return { ok: false, error: "invalid_webhook_url" };956        }957        // LV-3: debounce non-test pings per (webhook, entry) so a page that958        // strobes focus/fill events can't turn the canary into a request959        // firehose at the user's endpoint. Test pings are exempt — they are960        // explicit user clicks in the settings UI and are awaited for961        // feedback. The FIRST ping in a window always goes out, so the962        // dead-man's-switch property (canary fires on access) is preserved;963        // only repeats within the window are coalesced.964        if (trigger !== "test") {965          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;966          const stored = await chrome.storage.local.get(rlKey);967          const last = (stored as Record<string, unknown>)[rlKey];968          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {969            return { ok: true, data: { rateLimited: true } };970          }971          await chrome.storage.local.set({ [rlKey]: Date.now() });972        }973        const body = JSON.stringify({974          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",975          entry: entryTitle,976          trigger,977          timestamp: new Date().toISOString(),978          source: "peach-extension",979        });980        if (trigger === "test") {981          // Permitted outbound fetch: user-configured canary alert endpoint982          // (validated by isAllowedCanaryWebhookUrl above). This is the983          // only non-HIBP outbound call in the extension — see984          // Projects.md §3.7. Test pings are awaited so the UI can show985          // success/failure.986          try {987            const res = await fetch(webhookUrl, {988              method: "POST",989              headers: { "Content-Type": "application/json" },990              body,991            });992            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };993          } catch (err) {994            return { ok: false, error: err instanceof Error ? err.message : "network_error" };995          }996        }997        // Non-test triggers are fire-and-forget998        fetch(webhookUrl, {999          method: "POST",1000          headers: { "Content-Type": "application/json" },1001          body,1002        }).catch(() => {});1003        return { ok: true };1004      }1005      case "ACTIVATE_LICENSE": {1006        const { key } = msg.payload as { key: string };1007        const licenseInfo = await activateLicense(key);1008        return { ok: true, data: licenseInfo };1009      }1010      case "GET_LICENSE": {1011        const licenseInfo = await getLicenseInfo();1012        return { ok: true, data: licenseInfo };1013      }1014      case "GET_LICENSE_KEY": {1015        const key = await getLicenseKey();1016        return { ok: true, data: key };1017      }1018      case "DEACTIVATE_LICENSE": {1019        await deactivateLicense();1020        return { ok: true };1021      }1022      case "SHOULD_PLAY_CELEBRATION": {1023        const should = await shouldPlayCelebration();1024        return { ok: true, data: should };1025      }1026      case "MARK_CELEBRATION_PLAYED": {1027        await markCelebrationPlayed();1028        return { ok: true };1029      }1030      case "GET_CODEX_VAULT_DATA": {1031        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the1032        // popup navigates to the License section without further coordination.1033        // Also privileged-page-gated (PB-26-001), and recoveryWords inside the1034        // snapshot additionally require a fresh master-password proof.1035        const gate = await requirePro("codex");1036        if (!gate.allowed) return { ok: false, error: "pro_required" };1037        const { password } = (msg.payload ?? {}) as { password?: string };1038        return await handleGetCodexVaultData(password);1039      }1040      case "ESTIMATE_CODEX_PAGES": {1041        const gate = await requirePro("codex");1042        if (!gate.allowed) return { ok: false, error: "pro_required" };1043        return await handleEstimateCodexPages();1044      }1045      case "RESTORE_FROM_CODEX": {1046        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still1047        // be able to restore a vault that was printed by a Pro user.1048        // DO NOT add a Pro gate here.1049        const payload = msg.payload as CodexRestorePayload;1050        return await handleRestoreFromCodex(payload);1051      }1052      case "OPEN_PRO_GATE": {1053        // Content script requests: open popup and navigate to License section.1054        const { feature } = (msg.payload ?? {}) as { feature?: string };1055        if (chrome.storage.session) {1056          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });1057        }1058        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }1059        return { ok: true };1060      }1061      case "OPEN_POPUP": {1062        // Content script asks to open the trusted extension popup — used by the1063        // inline locked bubble so the master password is entered in the popup,1064        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a1065        // user gesture + Chrome 127+/Firefox; on failure the user clicks the1066        // toolbar icon. The badge already signals Peach needs attention.1067        //1068        // Set a session flag so the popup knows it was opened for inline unlock1069        // and should close itself once the vault is unlocked (returning the user1070        // to the inline autofill selector on the page).1071        if (chrome.storage.session) {1072          await chrome.storage.session.set({ peach_inline_unlock: true });1073        }1074        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }1075        return { ok: true };1076      }1077      case "OPEN_DETACHED_POPUP": {1078        // A window created by the action popup and then orphaned with1079        // window.close() is cascaded shut by Chrome, so the file-picker1080        // flows (OS dialogs that dismiss the popup on focus loss) ask the SW1081        // to open the standalone window instead — the SW has no window to be1082        // associated with. The query string is allowlisted so this can never1083        // open an arbitrary URL.1084        const { route } = (msg.payload ?? {}) as { route?: string };1085        const search = route === "peachscript"1086          ? "?restore=peachscript"1087          : route === "csv"1088            ? "?restore=csv"1089            : route === "codex-pdf"1090              ? "?codex=pdf"1091              : null;1092        if (!search) return { ok: false, error: "bad_route" };1093        try {1094          const popupHtml =1095            chrome.runtime.getManifest().action?.default_popup ?? "src/popup/index.html";1096          await chrome.windows.create({1097            url: chrome.runtime.getURL(`${popupHtml}${search}`),1098            type: "popup",1099            width: 320,1100            height: 550,1101          });1102          return { ok: true, data: { detached: true } };1103        } catch {1104          return { ok: false };1105        }1106      }1107      case "GET_IDENTITIES": {1108        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1109        return { ok: true, data: vault.getIdentities() };1110      }1111      case "TOUCH_AUTO_LOCK": {1112        // touchAutoLock() is already called by shouldRefreshAutoLock above;1113        // this case just gives the popup a typed message to keep the session alive.1114        return { ok: true };1115      }1116      case "GET_ADVANCED_HEALTH_REPORT": {1117        const gate = await requirePro("advanced_health");1118        if (!gate.allowed) return { ok: false, error: "pro_required" };1119        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1120        const report = await buildAdvancedHealthReport(vault.getEntries());1121        return { ok: true, data: report };1122      }1123      case "IS_DURESS_ENABLED": {1124        const enabled = await vault.isDuressEnabled();1125        return { ok: true, data: enabled };1126      }1127      case "SETUP_DURESS": {1128        // Single enforcement point for the Duress Vault Pro gate. Free users1129        // who somehow reach this handler are rejected here; the popup also1130        // pre-checks isPro() to avoid showing the setup form to free users,1131        // but server-side is the actual security boundary.1132        const gate = await requirePro("duress_vault");1133        if (!gate.allowed) return { ok: false, error: "pro_required" };1134        // MV3 service workers restart after inactivity, losing the in-memory1135        // derived key. Detect this before calling setupDuress so the popup1136        // can show a meaningful prompt to re-lock and re-unlock.1137        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };1138        const { duressPassword } = msg.payload as { duressPassword: string };1139        await vault.setupDuress(duressPassword);1140        return { ok: true };1141      }1142      case "DISABLE_DURESS": {1143        await vault.disableDuress();1144        return { ok: true };1145      }1146      case "VERIFY_MAIN_PASSWORD": {1147        const { password } = msg.payload as { password: string };1148        const ok = await vault.verifyMainPassword(password);1149        return { ok: true, data: ok };1150      }1151      case "CHANGE_PASSWORD": {1152        const { currentPassword, newPassword } = msg.payload as {1153          currentPassword: string;1154          newPassword: string;1155        };1156        const changed = await vault.changePassword(currentPassword, newPassword);1157        return changed1158          ? { ok: true }1159          : { ok: false, error: "incorrect_current_password" };1160      }1161      case "GET_SITE_PASSWORD_POLICY": {1162        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1163        if (!tab?.id) return { ok: true, data: null };1164        try {1165          const response = await chrome.tabs.sendMessage(tab.id, {1166            type: "GET_SITE_PASSWORD_POLICY",1167          });1168          return (response as MessageResponse) ?? { ok: true, data: null };1169        } catch {1170          return { ok: true, data: null };1171        }1172      }1173      case "RECORD_MANUAL_SUMMON": {1174        const { domain } = msg.payload as { domain: string };1175        const settings = vault.getSettings();1176        const existing = settings.manualSummonDomains?.[domain];1177        const now = Date.now();1178        await vault.updateSettings({1179          manualSummonDomains: {1180            ...settings.manualSummonDomains,1181            [domain]: {1182              firstSummonedAt: existing?.firstSummonedAt ?? now,1183              summonCount: (existing?.summonCount ?? 0) + 1,1184              lastSummonedAt: now,1185            },1186          },1187        });1188        return { ok: true };1189      }1190      case "DECLINE_CARD_SAVE": {1191        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1192        await vault.declineCardSaveOffer(last4, expMonth, expYear);1193        return { ok: true };1194      }1195      case "IS_CARD_DECLINED": {1196        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1197        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1198        return { ok: true, data: declined };1199      }1200      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1201        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1202          rpId?: string;1203          rpName?: string;1204          userName?: string;1205          userDisplayName?: string;1206        };1207        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1208        return await initiateFirefoxPasskeyCreate({1209          rpId,1210          rpName: rpName ?? rpId,1211          userName,1212          userDisplayName,1213        }, attestedSenderOrigin(sender));1214      }12151216      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1217        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1218        if (!payload) return { ok: false, error: "missing_payload" };1219        return await completeFirefoxPasskeyCreate(payload);1220      }12211222      case "PASSKEY_OFFER_DECLINE": {1223        const { domain } = (msg.payload ?? {}) as { domain?: string };1224        if (!domain) return { ok: false, error: "domain_required" };1225        await recordPasskeyOfferDecline(domain);1226        return { ok: true };1227      }12281229      case "GET_PASSKEY_OFFER_DECLINED": {1230        const { domain } = (msg.payload ?? {}) as { domain?: string };1231        if (!domain) return { ok: false, error: "domain_required" };1232        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1233      }12341235      case "PASSKEY_HAS_CREDENTIALS": {1236        const payload = msg.payload as {1237          rpId?: string;1238          allowCredentials?: Array<{ id: string; type?: string }>;1239        } | undefined;1240        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1241        return await handlePasskeyHasCredentials({1242          rpId: payload.rpId,1243          allowCredentials: payload.allowCredentials ?? [],1244        }, attestedSenderOrigin(sender));1245      }12461247      case "PASSKEY_CREATE": {1248        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1249        if (!payload?.rpId || !payload?.userName) {1250          return { ok: false, error: "rpid_and_username_required" };1251        }1252        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1253      }12541255      case "PASSKEY_GET": {1256        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1257        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1258        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1259      }12601261      case "PASSKEY_AUTH_RESPONSE": {1262        const { requestId, approved } = (msg.payload ?? {}) as {1263          requestId?: string | number;1264          approved?: boolean;1265        };1266        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1267          return { ok: false, error: 'requestId and approved required' };1268        }1269        await resolvePendingPasskeyRequest(Number(requestId), approved);1270        return { ok: true };1271      }12721273      case "GET_PASSKEY_FOR_DOMAIN": {1274        const { domain } = (msg.payload ?? {}) as { domain?: string };1275        if (!domain) return { ok: false, error: "domain_required" };1276        // Scope to the caller's own origin: a page may only ask about passkeys1277        // for a domain it actually owns, so an arbitrary page cannot enumerate1278        // which sites the user holds passkeys for or read the username (audit MEDIUM).1279        const origin = attestedSenderOrigin(sender);1280        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1281        if (!vault.isUnlocked()) return { ok: true, data: null };1282        const match = vault1283          .getEntries()1284          .find((entry) => entry.passkey?.rpId === domain);1285        if (!match || !match.passkey) return { ok: true, data: null };1286        // Slim shape — only the fields State 11 needs. Never expose private1287        // key material, even though this is locked behind isUnlocked.1288        return {1289          ok: true,1290          data: {1291            rpId: match.passkey.rpId,1292            userName: match.passkey.userName,1293            browser: match.passkey.browser,1294          },1295        };1296      }12971298      case "DESTROY_VAULT": {1299        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1300        // storage.local.clear() wipes every Peach key (slots, settings, license,1301        // onboarded flag, history, sync state, declined cards, recall, etc.);1302        // session.clear() wipes pending passkey requests + pro-notice queues.1303        // Caller (Panic.tsx) handles UI navigation back to onboarding.1304        //1305        // The Pro license is the one thing that must survive: the user paid for1306        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1307        // Capture it before the clear and restore it after. peach_pro_celebrated1308        // rides along so the Pro celebration doesn't replay on the next unlock.1309        const preserved = await chrome.storage.local.get([1310          "peach_license",1311          "peach_pro_celebrated",1312        ]);1313        vault.lock();1314        await storageClear();1315        await vault.clearVaultHistory();1316        const toRestore: Record<string, unknown> = {};1317        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1318        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1319        if (Object.keys(toRestore).length > 0) {1320          await chrome.storage.local.set(toRestore);1321        }1322        if (chrome.storage.session) {1323          await chrome.storage.session.clear();1324        }1325        await clearRecoveryConfirmPending();1326        return { ok: true };1327      }13281329      case "GET_IDENTITY_SUGGESTIONS": {1330        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1331        const entries = vault.getEntries();1332        const suggestions = buildIdentitySuggestions(entries);1333        return { ok: true, data: { suggestions } };1334      }1335      case "ML_INIT":1336        return { ok: true };13371338      case "ML_PREDICT_BATCH": {1339        // AUD-002: shape-validate before forwarding to the ML helper.1340        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1341        if (!Array.isArray(featuresArray)) {1342          return { ok: false, error: "invalid_payload" };1343        }1344        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1345      }13461347      // ── Vault sync (v3) ───────────────────────────────────────────────1348      // Returns the public-facing local identity needed by the popup to1349      // drive Phase-1 audio pairing. The private long-term key never1350      // leaves the background.1351      case "GET_LOCAL_IDENTITY": {1352        // Not Pro-gated: a free device may attempt to pair so it can RECEIVE a1353        // Pro license from an already-Pro peer (at least one device must be Pro).1354        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1355        // Identity derives from the stable root key, not the password-derived1356        // key, so pairing survives a master-password change (SEV-2-B).1357        const masterKeyHex = vault.getRootKeyHex();1358        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1359        const masterKey = unhexBytes(masterKeyHex);1360        try {1361          const identity = await buildLocalIdentity(masterKey);1362          // If this device is Pro, advertise the signed license so the peer can1363          // activate it after SAS confirmation — pairing carries Pro across.1364          if (await isProUser()) {1365            const license = await getLicenseKey();1366            if (license) (identity as { license?: string }).license = license;1367          }1368          return { ok: true, data: identity };1369        } finally {1370          masterKey.fill(0);1371        }1372      }13731374      case "LIST_PAIRED_DEVICES": {1375        const devices = await listPairedDevicesV3();1376        return { ok: true, data: { devices } };1377      }13781379      case "RENAME_PAIRED_DEVICE": {1380        const { deviceId, name } = (msg.payload ?? {}) as { deviceId?: string; name?: string };1381        if (typeof deviceId !== "string" || !deviceId || typeof name !== "string") {1382          return { ok: false, error: "invalid_payload" };1383        }1384        await renamePairedDeviceV3(deviceId, name);1385        return { ok: true };1386      }13871388      case "UNPAIR_DEVICE": {1389        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1390        if (typeof deviceId !== "string" || !deviceId) {1391          return { ok: false, error: "invalid_payload" };1392        }1393        // Removing a device REVOKES it rather than just dropping the local1394        // row: a plain removal is undone the moment any other peer vouches it1395        // back through a manifest, which is exactly what the relay makes easy.1396        await revokeDeviceByIdV3(deviceId, await getOrCreateDeviceId());1397        // Sync against the remaining hosts — the unpaired device no longer1398        // matters but the next alarm tick is up to ten minutes away.1399        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1400        return { ok: true };1401      }14021403      case "RENAME_LOCAL_DEVICE": {1404        const { name } = (msg.payload ?? {}) as { name?: string };1405        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1406        await setDeviceNameV3(name);1407        return { ok: true };1408      }14091410      // ── Relay pairing ─────────────────────────────────────────────────────1411      // Not Pro-gated (a free device may pair to receive Pro/sync). The whole NK1412      // session runs in the background; the SAS and the terminal result reach1413      // the popup as ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT pushes.1414      case "START_ADOPTION_SOURCE": {1415        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1416        if (isRelayAdoptionSourceInFlight()) {1417          return { ok: false, error: "adoption_source_in_progress" };1418        }1419        try {1420          return { ok: true, data: await startRelayAdoptionSource() };1421        } catch (error) {1422          return {1423            ok: false,1424            error: error instanceof Error ? error.message : "adoption_source_failed",1425          };1426        }1427      }14281429      // Onboarding receiver — empty extension shows a QR, phone scans and1430      // sends the vault. The popup supplies the local-only password here so1431      // the background can wrap the adopted root key at rest without ever1432      // asking the user to retype it.1433      case "START_ADOPTION_RECEIVER": {1434        if (isRelayAdoptionSourceInFlight()) {1435          return { ok: false, error: "adoption_receiver_in_progress" };1436        }1437        const password = (msg.payload as { password?: unknown } | undefined)?.password;1438        if (typeof password !== "string" || password.length === 0) {1439          return { ok: false, error: "invalid_payload" };1440        }1441        try {1442          return { ok: true, data: await startRelayAdoptionReceiver(password) };1443        } catch (error) {1444          return {1445            ok: false,1446            error: error instanceof Error ? error.message : "adoption_receiver_failed",1447          };1448        }1449      }14501451      // Popup→bg counterpart to ADOPTION_SOURCE_SAS (receiver flow).1452      // The receiver now auto-accepts the SAS (both sides derive it from the1453      // same Noise handshake hash, so the codes match by construction) so1454      // the popup never has a SAS screen to tap on. The id round-trips the1455      // same way so a stale late response can't approve the wrong session.1456      // Popup→bg counterpart for the source flow: Confirm/Cancel on the1457      // source's SAS screen.14581459      // Source-side mirror of RECEIVER_SAS_DECISION: the popup's confirm/cancel1460      // on the source's SAS screen. The id round-trips the same way so a stale1461      // late response can't approve the wrong session.1462      case "SOURCE_SAS_DECISION": {1463        const payload = msg.payload as { id?: unknown; ok?: unknown } | undefined;1464        if (typeof payload?.id !== "string" || typeof payload?.ok !== "boolean") {1465          return { ok: false, error: "invalid_payload" };1466        }1467        return { ok: resolveSourceSasConfirmation(payload.id, payload.ok) };1468      }14691470      case "CANCEL_ADOPTION_SOURCE": {1471        cancelRelayAdoptionSource();1472        return { ok: true };1473      }14741475      case "TRIGGER_SYNC": {1476        const payload = (msg.payload ?? {}) as {1477          reason?: "vault_change" | "foreground" | "manual";1478          force?: boolean;1479        };1480        const reason = payload.reason ?? "foreground";14811482        void triggerSyncIfReachable({ reason, force: payload.force === true });1483        return { ok: true };1484      }14851486      case "GET_SYNC_STATE": {1487        return { ok: true, data: getSyncState() };1488      }14891490      case "GET_SYNC_SETTINGS": {1491        return { ok: true, data: await getSyncSettings() };1492      }14931494      case "SET_SYNC_SETTINGS": {1495        const payload = (msg.payload ?? {}) as {1496          mode?: unknown;1497          relayUrl?: unknown;1498        };1499        try {1500          // A custom relay URL implies private mode; Peach's own relay stays1501          // public. See setRelayUrl.1502          if (payload.relayUrl !== undefined) {1503            if (typeof payload.relayUrl !== "string") {1504              return { ok: false, error: "invalid_relay_url" };1505            }1506            return { ok: true, data: await setRelayUrl(payload.relayUrl) };1507          }1508          if (payload.mode !== undefined) {1509            if (payload.mode !== "public" && payload.mode !== "private" && payload.mode !== "off") {1510              return { ok: false, error: "invalid_sync_mode" };1511            }1512            return { ok: true, data: await setSyncMode(payload.mode as SyncMode) };1513          }1514          return { ok: true, data: await getSyncSettings() };1515        } catch (error) {1516          return {1517            ok: false,1518            error: error instanceof Error ? error.message : "invalid_relay_url",1519          };1520        }1521      }15221523      case "GET_SYNC_ALERTS": {1524        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1525        const alerts = await getPendingSyncAlerts();1526        // The popup reads on open and acknowledges with consume:true after1527        // rendering, so a popup crash between read and render doesn't lose1528        // the alerts.1529        if (consume) await clearPendingSyncAlerts();1530        return { ok: true, data: alerts };1531      }15321533      case "GET_PENDING_VOUCHED_DEVICES": {1534        return { ok: true, data: await listPendingVouchedDevices() };1535      }1536      case "CONFIRM_VOUCHED_DEVICE": {1537        const { deviceId } = msg.payload as { deviceId: string };1538        const pending = await getPendingVouchedDevice(deviceId);1539        if (!pending) return { ok: false, error: "not_pending" };1540        // Last gate before a vouched device becomes a sync peer. A queue entry1541        // can predate the revocation that names it, so revocation is re-checked1542        // here rather than trusted to have swept the queue.1543        if (await isDeviceRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {1544          await removePendingVouchedDevice(deviceId);1545          return { ok: false, error: "device_revoked" };1546        }1547        await upsertPairedDeviceV3({1548          deviceId: pending.deviceId,1549          deviceName: pending.deviceName,1550          deviceType:1551            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1552          longTermPublicKeyHex: pending.longTermPublicKeyHex,1553          signingPublicKeyHex: pending.signingPublicKeyHex,1554          wsPort: pending.wsPort,1555          pairedAt: pending.pairedAt,1556          trustSource: "vouched",1557        });1558        await removePendingVouchedDevice(deviceId);1559        // Newly confirmed vouched device is now a sync target — kick a round1560        // so the mesh introduction pays off without a 10-minute wait.1561        void triggerSyncIfReachable({ reason: "device_list_changed" }).catch(() => undefined);1562        return { ok: true };1563      }1564      case "REJECT_VOUCHED_DEVICE": {1565        const { deviceId } = msg.payload as { deviceId: string };1566        await removePendingVouchedDevice(deviceId);1567        return { ok: true };1568      }1569      case "ROTATE_SYNC_IDENTITY": {1570        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1571        const result = await vault.rotateSyncIdentity();1572        return result.ok ? { ok: true } : { ok: false, error: result.error };1573      }15741575      default:1576        return { ok: false, error: "unknown_message_type" };1577    }1578  } catch (err) {1579    return {1580      ok: false,1581      error: err instanceof Error ? err.message : "operation_failed",1582    };1583  }1584}15851586// Returns username use-counts from the vault, sorted by frequency. Each row1587// also carries the entry's email so the popup can suggest the email/username1588// pair the user has actually used together.1589function buildIdentitySuggestions(1590  entries: VaultEntry[],1591): Array<{ email: string; username: string; count: number }> {1592  const usernameCounts = new Map<string, number>();1593  const usernameEmail = new Map<string, string>();1594  for (const entry of entries) {1595    const username = entry.username ?? "";1596    const email = (entry as VaultEntry & { email?: string }).email ?? "";1597    if (!username && !email) continue;1598    const key = username || email;1599    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1600    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1601  }1602  return Array.from(usernameCounts.entries())1603    .sort((a, b) => b[1] - a[1])1604    .map(([username, count]) => ({1605      email: usernameEmail.get(username) ?? "",1606      username,1607      count,1608    }));1609}16101611/** Notify all content scripts that the vault just became available. */1612function broadcastToContentScripts(message: { type: string }): void {1613  if (!chrome.tabs?.query) return;1614  chrome.tabs.query({}, (tabs) => {1615    for (const tab of tabs) {1616      if (tab.id !== undefined) {1617        chrome.tabs.sendMessage(tab.id, message).catch(() => {1618          // Tab may not have a content script — silently ignore1619        });1620      }1621    }1622  });1623}16241625function shouldRefreshAutoLock(type: MessageType): boolean {1626  return (1627    type !== "HAS_VAULT" &&1628    type !== "IS_UNLOCKED" &&1629    type !== "GET_VAULT_STATUS" &&1630    type !== "LOCK" &&1631    type !== "UPDATE_SETTINGS" &&1632    type !== "GET_PENDING_PASSKEY" &&1633    type !== "GET_PASSKEY_PROVIDER_STATE" &&1634    type !== "DECLINE_CARD_SAVE" &&1635    type !== "IS_CARD_DECLINED"1636  );1637}16381639function isAllowedCanaryWebhookUrl(value: string): boolean {1640  try {1641    const url = new URL(value);1642    if (url.protocol !== "https:") return false;16431644    const hostname = url.hostname.toLowerCase();1645    if (1646      hostname === "localhost" ||1647      hostname.endsWith(".localhost") ||1648      isPrivateIpv4(hostname) ||1649      isPrivateIpv6(hostname)1650    ) {1651      return false;1652    }16531654    return true;1655  } catch {1656    return false;1657  }1658}16591660function isPrivateIpv4(hostname: string): boolean {1661  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1662    return true;1663  }16641665  const octets = hostname.split(".").map((part) => Number(part));1666  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1667    return false;1668  }16691670  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1671}16721673function isPrivateIpv6(hostname: string): boolean {1674  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1675  // IPv4-mapped IPv6 literals embed a plain IPv4 address that the prefix1676  // list below can never match (WHATWG URL serializes [::ffff:192.168.0.1]1677  // as ::ffff:c0a8:1). Unwrap and test the embedded IPv4; unparseable mapped1678  // tails fail closed. (Codex Security 2026-08-04 LOW,1679  // ssrf.webhook-url-private-ip-filter.) DNS rebinding is out of scope for a1680  // one-shot host check.1681  const mapped = /^::ffff:(.+)$/.exec(normalized);1682  if (mapped) {1683    const tail = mapped[1] ?? "";1684    if (tail.includes(".")) return isPrivateIpv4(tail);1685    const parts = tail.split(":");1686    const [hi, lo] = parts;1687    if (1688      parts.length !== 2 ||1689      !hi ||1690      !lo ||1691      !/^[0-9a-f]{1,4}$/.test(hi) ||1692      !/^[0-9a-f]{1,4}$/.test(lo)1693    ) {1694      return true;1695    }1696    const octets = [1697      (Number.parseInt(hi, 16) >>> 8) & 0xff,1698      Number.parseInt(hi, 16) & 0xff,1699      (Number.parseInt(lo, 16) >>> 8) & 0xff,1700      Number.parseInt(lo, 16) & 0xff,1701    ];1702    return isPrivateIpv4(octets.join("."));1703  }1704  return (1705    normalized === "::1" ||1706    normalized.startsWith("fc") ||1707    normalized.startsWith("fd") ||1708    normalized.startsWith("fe80:")1709  );1710}