messages.ts

63.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 } 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 { isRecoveryConfirmPending } from "./recovery-pending";21import { setupAutoLock, touchAutoLock } from "./alarms";22import { runSelfTest } from "./self-test";23import * as vault from "./vault";24import {25  handleEstimateCodexPages,26  handleGetCodexVaultData,27  handleRestoreFromCodex,28} from "./codex-handlers";29import type { CodexRestorePayload } from "../shared/codex-types";30import {31  activateLicense,32  deactivateLicense,33  getLicenseInfo,34  getLicenseKey,35  isProUser,36  markCelebrationPlayed,37  shouldPlayCelebration,38} from "./license";39import {40  completeFirefoxPasskeyCreate,41  getPasskeyProviderState,42  getPendingPasskeyRequest,43  handleFirefoxPasskeyCreate,44  handleFirefoxPasskeyGet,45  handlePasskeyHasCredentials,46  initiateFirefoxPasskeyCreate,47  isPasskeyOfferDeclined,48  onVaultUnlocked,49  recordPasskeyOfferDecline,50  resolvePendingPasskeyRequest,51  setPasskeyProviderEnabled,52} from "./passkey";53import { buildAdvancedHealthReport } from "./health";54import { storageClear } from "../shared/storage";55import { findInvalidWords } from "../shared/recovery-words";56import type {57  Message,58  MessageResponse,59  MessageType,60  ProFeature,61  VaultEntry,62} from "../shared/types";63import { isPasskeyOnly } from "../shared/types";64import { generateTOTP } from "../crypto/totp";65import { isValidRpId } from "../shared/passkey-utils";66import { isNativePlatform, nativePlugin } from "../shared/native";67import { predictBatch as mlPredictBatch } from "./ml";68import type { MLFieldFeatures } from "../shared/ml";69import { buildLocalIdentity, setDeviceName as setDeviceNameV3 } from "./chirp-identity";70import {71  listPairedDevices as listPairedDevicesV3,72  removePairedDeviceById as removePairedDeviceByIdV3,73  upsertPairedDevice as upsertPairedDeviceV3,74} from "./paired-devices";7576// Compile-time E2E flag, folded to a literal by Vite's `define` (false in77// every production build — verified in the bundled output). Mirrors the78// create-path bypass in passkey.ts so the Playwright passkey smoke can enable79// the provider without a real Pro licence; the gate is fully intact for users.80declare const __PEACH_E2E_PASSKEYS__: boolean;81const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true;8283let nativeSyncRunnerBootstrapped = false;8485function unhexBytes(hex: string): Uint8Array {86  if (hex.length % 2 !== 0) throw new Error("invalid hex");87  const out = new Uint8Array(hex.length / 2);88  for (let i = 0; i < out.length; i++) {89    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);90  }91  return out;92}9394/**95 * The single Pro gate. Every gated handler calls this first; the broadcast96 * lets the popup react (navigate to the License section, highlight the97 * relevant feature). Background never touches the popup view directly —98 * the popup owns navigation. See Projects.md "Pro gate rule".99 */100async function requirePro(101  feature: ProFeature,102  trigger: "user" | "background" = "user"103): Promise<{ allowed: boolean }> {104  if (PASSKEY_E2E_PRO_BYPASS && feature === "passkeys") return { allowed: true };105  if (await isProUser()) return { allowed: true };106107  if (trigger === "user") {108    // User deliberately triggered this feature — redirect the popup immediately.109    chrome.runtime110      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })111      .catch(() => {112        // Popup may be closed — the gate signal is best-effort.113      });114  } else {115    // Background trigger (e.g. passive sync initiation) — no popup is open.116    // Queue a notice so the next popup open shows a soft banner instead of117    // silently failing.118    if (chrome.storage.session) {119      chrome.storage.session120        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })121        .catch(() => {});122    }123  }124125  return { allowed: false };126}127128// ---------------------------------------------------------------------------129// Feedback submission target. Empty disables network submission while the UI130// continues to function as a no-op (the handler returns ok:true without131// calling fetch). When set, the URL is validated by132// `isAllowedCanaryWebhookUrl` before any request.133// ---------------------------------------------------------------------------134135const FEEDBACK_ENDPOINT = "";136137// LV-3: minimum interval between non-test canary pings per webhook+entry.138const CANARY_MIN_INTERVAL_MS = 60 * 60 * 1000; // 1 hour139140const PRIVATE_IPV4_RANGES = [141  { prefix: "10." },142  { prefix: "127." },143  { prefix: "169.254." },144  { prefix: "192.168." },145];146147export function setupMessageHandler(): void {148  chrome.runtime.onMessage.addListener(149    (msg: unknown, sender, sendResponse) => {150      if (!isMessage(msg)) {151        sendResponse({ ok: false, error: "invalid_message" });152        return true;153      }154      handleMessage(msg, sender)155        .then(sendResponse)156        .catch((err) =>157          sendResponse({158            ok: false,159            error: err instanceof Error ? err.message : String(err),160          })161        );162      return true;163    }164  );165166  // Android: the chrome shim queues sendMessage calls until this handler is167  // registered. Without this hookup, every message hangs on Capacitor builds.168  // eslint-disable-next-line @typescript-eslint/no-explicit-any169  const reg = (globalThis as any).__peachRegisterMessageHandler;170  if (typeof reg === "function") {171    reg(async (m: unknown) => {172      if (!isMessage(m)) return { ok: false, error: "invalid_message" };173      try {174        return await handleMessage(m);175      } catch (err) {176        return {177          ok: false,178          error: err instanceof Error ? err.message : String(err),179        };180      }181    });182  }183  if (isNativePlatform()) {184    void bootstrapNativeSyncRunner();185  }186}187188async function bootstrapNativeSyncRunner(): Promise<void> {189  if (nativeSyncRunnerBootstrapped) return;190  nativeSyncRunnerBootstrapped = true;191  try {192    const { setSyncRunner, hydratePersistedSyncState } = await import("./sync-trigger");193    const { productionSyncRunner } = await import("./chirp-sync-runner");194    setSyncRunner(productionSyncRunner);195    await hydratePersistedSyncState();196  } catch (err) {197    nativeSyncRunnerBootstrapped = false;198    console.warn("[Peach] failed to bootstrap native sync runner:", err);199  }200}201202function isMessage(m: unknown): m is Message {203  return typeof m === "object" && m !== null && "type" in m;204}205206/**207 * The browser-attested origin of the page that originated this message. A web208 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),209 * so every page-driven message arrives via the content-script relay and the210 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a211 * value the page cannot forge. This is the ONLY trustworthy origin for passkey212 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.213 */214function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {215  if (sender.origin) return sender.origin;216  if (sender.url) {217    try { return new URL(sender.url).origin; } catch { return undefined; }218  }219  return undefined;220}221222// Resolves once restoreFromSession() has run, so handlers see the correct223// post-restore unlock state. entry.ts registers this BEFORE the message224// handler so the onMessage listener is added synchronously at SW startup225// (MV3 requirement) while unlock-dependent handlers still wait for restore.226let restoreReady: Promise<void> = Promise.resolve();227228/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */229export function setRestoreReady(p: Promise<unknown>): void {230  restoreReady = p.then(() => undefined, () => undefined);231}232233export async function handleMessage(234  msg: Message,235  sender: Partial<chrome.runtime.MessageSender> = {}236): Promise<MessageResponse> {237  try {238    // Wait for session-restore to finish before reading any unlock/vault state.239    // On a cold SW start the popup's first message arrives while restore is240    // still in flight; without this gate IS_UNLOCKED would report locked (a241    // spurious lock screen) and the storage reads could race. The onMessage242    // listener itself is registered synchronously (entry.ts) so this gate, not243    // listener registration, is what absorbs the cold-start window.244    await restoreReady;245    // Validate sender — only allow messages from our extension pages/scripts.246    // `sender.id` is undefined for messages originating from extension UI247    // (popup/options), which is legitimate; reject only when it is defined248    // and does not match our extension id.249    if (250      sender.id !== undefined &&251      sender.id !== chrome.runtime.id252    ) {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 "UNLOCK": {277        const { password } = msg.payload as { password: string };278        const ok = await vault.unlock(password);279        if (ok) {280          // KAT: verify the WebCrypto stack is healthy before the user relies on it.281          // Runs after unlock so latency is hidden behind the vault-load time.282          const kat = await runSelfTest();283          if (!kat.ok) {284            console.error("[Peach] Crypto self-test FAILED:", kat.error);285            await vault.lock();286            return { ok: false, error: "self_test_failed" };287          }288          await setupAutoLock();289          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });290          onVaultUnlocked();291          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());292          return { ok: true };293        }294        // Distinguish corruption from wrong password so the popup can offer295        // a history-restore path instead of falsely accusing the user of296        // mistyping (M7/COR-007).297        const failure = vault.consumeLastUnlockFailureReason();298        if (failure) {299          return {300            ok: false,301            error: "vault_corrupted",302            canRestoreFromHistory: true,303          } as MessageResponse;304        }305        return { ok: false };306      }307      case "VALIDATE_RECOVERY_WORDS": {308        const { words } = msg.payload as { words: string[] };309        const invalid = findInvalidWords(words);310        return { ok: true, data: { valid: invalid.length === 0, invalid } };311      }312      case "GET_RECOVERY_WORDS": {313        // Must be unlocked and have recovery set up (vault must be v2.12+).314        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };315        // LV-4: the recovery words re-derive the ROOT KEY — the highest-316        // value secret in the vault. A session unlock (which may be hours317        // old on a shared machine) is not enough; require a fresh password318        // proof, matching the 1Password/Bitwarden pattern for revealing319        // escrow material. EXEMPTION: the create-vault / rotation confirmation320        // window (peach_recovery_pending) shows the words immediately after321        // the user authenticated, and that confirmation UI has no password to322        // resend — skip the re-auth there only.323        if (!(await isRecoveryConfirmPending())) {324          const { password } = (msg.payload ?? {}) as { password?: string };325          if (typeof password !== "string" || !password) {326            return { ok: false, error: "password_required" };327          }328          if (!(await vault.verifyMainPassword(password))) {329            return { ok: false, error: "wrong_password" };330          }331        }332        try {333          const words = await vault.getRecoveryWords();334          return { ok: true, data: words };335        } catch (e) {336          // pre-v2.12 vault that hasn't migrated337          return { ok: false, error: "recovery_not_setup" };338        }339      }340      case "RECOVER_WITH_WORDS": {341        // User has lost their password but has their 12 recovery words.342        // We: (1) validate the words, (2) re-encrypt vault with new password.343        const { words, newPassword } = msg.payload as {344          words: string[];345          newPassword: string;346        };347        const stored = await vault.loadSlotA();348        if (!stored) return { ok: false, error: "no_vault" };349        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {350          return { ok: false, error: "recovery_not_setup" };351        }352        // Unwrap the root key from the recovery escrow.353        try {354          await vault.unwrapRootKeyForRecovery(355            stored.recovery_wrapped_root_key,356            stored.recovery_nonce ?? "",357            stored.recovery_tag ?? "",358            stored.recovery_salt,359            words360          );361        } catch {362          return { ok: false, error: "invalid_recovery_words" };363        }364        // Re-key: derive fresh salt + key from new password.365        const newSalt = vault.generateSalt();366        const newKey = await vault.deriveKey(newPassword, newSalt);367        // Re-wrap root key under the new password's derived key so the same368        // recovery words continue to work after the password change.369        await vault.rewrapRootKeyForPassword(newKey, newSalt);370        // Re-encrypt vault entries with the new key.371        await vault.changePasswordWithNewKey(newSalt, newKey);372        await setupAutoLock();373        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });374        return { ok: true };375      }376      case "LOCK":377        vault.lock();378        if (isNativePlatform()) await clearInMemoryVault();379        return { ok: true };380      case "IS_UNLOCKED":381        return { ok: true, data: vault.isUnlocked() };382      case "GET_VAULT_STATUS":383        return { ok: true, unlocked: vault.isUnlocked() };384      case "HAS_VAULT":385        return { ok: true, data: await vault.hasVault() };386      case "GET_ENTRIES":387        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };388        return { ok: true, data: vault.getEntries() };389      case "ADD_ENTRY": {390        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };391        const payload = msg.payload;392        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {393          return { ok: false, error: "invalid_payload" };394        }395        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);396        return { ok: true, data: entry };397      }398      case "BATCH_ADD_ENTRIES": {399        const payload = msg.payload as { entries?: unknown } | null | undefined;400        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {401          return { ok: false, error: "invalid_payload" };402        }403        if (!Array.isArray(payload.entries)) {404          return { ok: false, error: "invalid_payload" };405        }406        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);407        return { ok: true, data: added };408      }409      case "RESTORE_ENTRIES": {410        const payload = msg.payload as411          | { entries?: unknown; mode?: unknown; settings?: unknown }412          | null413          | undefined;414        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {415          return { ok: false, error: "invalid_payload" };416        }417        if (!Array.isArray(payload.entries)) {418          return { ok: false, error: "invalid_payload" };419        }420        if (payload.mode !== "replace" && payload.mode !== "merge") {421          return { ok: false, error: "invalid_payload" };422        }423        const summary = await vault.restoreEntries(424          payload.entries as Parameters<typeof vault.restoreEntries>[0],425          payload.mode426        );427        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {428          await vault.updateSettings(payload.settings as vault.VaultSettings);429        }430        return { ok: true, data: summary };431      }432      case "CLEAR_VAULT_ENTRIES": {433        await vault.clearVaultEntries("REPLACE_ALL");434        return { ok: true };435      }436      case "GET_VAULT_HISTORY": {437        const snapshots = await vault.getVaultHistory();438        return { ok: true, data: snapshots };439      }440      case "RESTORE_VAULT_SNAPSHOT": {441        const { snapshotId } = msg.payload as { snapshotId: string };442        const result = await vault.restoreVaultSnapshot(snapshotId);443        if (!result.ok) return { ok: false, error: result.error };444        broadcastToContentScripts({ type: "VAULT_LOCKED" });445        return { ok: true };446      }447      case "COUNT_DUPLICATES": {448        return { ok: true, data: vault.countDuplicates() };449      }450      case "DEDUPLICATE_ENTRIES": {451        const removed = await vault.deduplicateEntries();452        return { ok: true, data: removed };453      }454      case "UPDATE_ENTRY": {455        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;456        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {457          return { ok: false, error: "invalid_payload" };458        }459        const { id, patch } = payload;460        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {461          return { ok: false, error: "invalid_payload" };462        }463        // Single enforcement point for the Canary Entries Pro gate. Only464        // gates the transition into a canary entry — clearing/disabling a465        // canary (`canary: undefined`) is always allowed, so existing466        // canary entries remain manageable.467        const incomingCanary = (patch as { canary?: unknown }).canary;468        if (incomingCanary && typeof incomingCanary === "object") {469          const existing = vault.getEntryById(id);470          if (!existing?.canary) {471            const gate = await requirePro("canary_entry");472            if (!gate.allowed) return { ok: false, error: "pro_required" };473          }474        }475        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);476        return { ok: true };477      }478      case "ADD_ADDITIONAL_URL": {479        const { id, url } = msg.payload as { id: string; url: string };480        const trimmed = typeof url === "string" ? url.trim() : "";481        if (!trimmed) return { ok: false, error: "url_required" };482        const existing = vault.getEntryById(id);483        if (!existing) return { ok: false, error: "entry_not_found" };484        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };485        const merged = [...(existing.additionalUrls ?? []), trimmed];486        await vault.updateEntry(id, { additionalUrls: merged });487        return { ok: true };488      }489      case "DELETE_ENTRY": {490        const { id } = msg.payload as { id: string };491        await vault.deleteEntry(id);492        return { ok: true };493      }494      case "GET_DELETED_ENTRIES":495        return { ok: true, data: vault.getDeletedEntries() };496      case "RESTORE_ENTRY": {497        const { id } = msg.payload as { id: string };498        await vault.restoreEntry(id);499        return { ok: true };500      }501      case "PURGE_ENTRY": {502        const { id } = msg.payload as { id: string };503        await vault.purgeEntry(id);504        return { ok: true };505      }506      case "PURGE_EXPIRED_TRASH": {507        const { retentionMs } = msg.payload as { retentionMs: number };508        const purged = await vault.purgeExpiredTrash(retentionMs);509        return { ok: true, data: purged };510      }511      case "SAVE_NOTE": {512        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };513        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };514        const now = Date.now();515        if (id) {516          const existing = vault.getEntryById(id);517          if (!existing) return { ok: false, error: "not_found" };518          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });519          return { ok: true, data: vault.getEntryById(id) };520        } else {521          const entry = await vault.addEntry({522            type: "note",523            title: title || "Untitled",524            notes: body,525            createdAt: now,526            modifiedAt: now,527          } as any);528          return { ok: true, data: entry };529        }530      }531      case "DELETE_NOTE": {532        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };533        const { id } = msg.payload as { id: string };534        await vault.deleteEntry(id);535        return { ok: true };536      }537      case "GET_NOTES": {538        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };539        const notes = vault.getEntries().filter(540          (e) => e.type === "note" && !e.deletedAt541        );542        return { ok: true, data: notes } as MessageResponse;543      }544      case "SEARCH_VAULT": {545        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };546        // AUD-002: shape-validate the payload before calling string methods.547        // A raw cast lets a malformed message crash the handler with TypeError.548        const { query } = (msg.payload ?? {}) as { query?: unknown };549        if (typeof query !== "string") {550          return { ok: false, error: "invalid_payload" };551        }552        const q = query.toLowerCase();553        const searchResults = vault.getEntries().filter(554          (e) =>555            !e.deletedAt &&556            (e.title.toLowerCase().includes(q) ||557              e.notes?.toLowerCase().includes(q) ||558              e.username?.toLowerCase().includes(q))559        );560        return { ok: true, data: searchResults } as MessageResponse;561      }562      case "AUTOFILL_QUERY": {563        if (!vault.isUnlocked()) {564          return { ok: false, error: "vault_locked" };565        }566        let { includeAll } = msg.payload as { includeAll?: boolean };567        const { domain, kind, userGesture } = msg.payload as {568          domain: string;569          kind?: "login" | "card" | "totp";570          userGesture?: boolean;571        };572        // MV-2: the vault-wide inventory (every title/username/email/url)573        // may only leave the background on an explicit user gesture — the574        // user opening the search affordance — never on passive form focus.575        // userGesture is self-declared by our own content script; the value576        // of this gate is that PASSIVE code paths (which never set it)577        // cannot ship the inventory, shrinking what a compromised page that578        // merely triggers focus events can observe.579        if (includeAll && userGesture !== true) {580          includeAll = false;581        }582        // kind="card": return saved cards as compact summaries for the583        // inline card silver platter. Cards are not domain-scoped — every584        // saved card is a candidate on every checkout page — so domain is585        // ignored when kind === "card".586        if (kind === "card") {587          const cards = vault.getEntries().filter((e) => e.type === "card");588          return {589            ok: true,590            data: cards.map((e) => ({591              id: e.id,592              title: e.cardNickname || e.title,593              cardholderName: e.cardholderName,594              last4: e.last4,595              expMonth: e.expMonth,596              expYear: e.expYear,597              network: e.network,598            })),599          };600        }601        if (kind === "totp") {602          const matches = (603            includeAll604              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")605              : vault.queryDomain(domain)606          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));607          return {608            ok: true,609            data: matches.map((e) => ({610              id: e.id,611              title: e.title,612              username: e.username,613              email: e.email,614              url: e.url,615              hasTotp: true,616            })),617          };618        }619        // The inline selector fills username+password into a form. Passkey-620        // only entries have no password to fill; sign-in for those goes621        // through the WebAuthn path instead. Filter them out everywhere so622        // the user doesn't see four "GitHub" rows that mostly do nothing.623        // Notes and cards never belonged here either.624        const matches = (625          includeAll626            ? vault627                .getEntries()628                .filter((entry) => entry.type !== "note" && entry.type !== "card")629            : vault.queryDomain(domain)630        ).filter((entry) => !isPasskeyOnly(entry));631        return {632          ok: true,633          data: matches.map((e) =>634            includeAll635              ? {636                  id: e.id,637                  title: e.title,638                  // username/email/url shipped so the inline popup's search639                  // affordance can match on them, not just titles. No secrets640                  // cross the boundary — same shape as the domain-matched641                  // response below minus hasTotp (which the search list642                  // doesn't surface).643                  username: e.username,644                  email: e.email,645                  url: e.url,646                  hasPasskey: e.passkey !== undefined,647                }648              : {649                  id: e.id,650                  title: e.title,651                  username: e.username,652                  email: e.email,653                  url: e.url,654                  hasTotp: Boolean(e.totp),655                  hasPasskey: e.passkey !== undefined,656                }657          ),658        };659      }660      case "GET_ENTRY_FOR_FILL": {661        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };662        const { id, explicitSummon } = msg.payload as {663          id: string;664          explicitSummon?: boolean;665        };666        const entry = vault.getEntryById(id);667        if (!entry) return { ok: false, error: "entry_not_found" };668        // Passkey-only entries (passkey credential, no password) cannot be669        // filled into a form — sign-in goes through the WebAuthn path. A670        // login that ALSO has a passkey is still fillable for its password.671        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };672673        // MV-1: re-validate the entry against the requesting tab's origin.674        // sender.tab.url is browser-attested — a page cannot forge it. When675        // the request does not come from a tab at all (popup surfaces use676        // GET_ENTRY_FOR_EDIT, not this), refuse.677        if (sender.tab !== undefined || sender.url !== undefined) {678          let senderDomain: string | null = null;679          try {680            const rawUrl = sender.tab?.url ?? sender.url ?? "";681            senderDomain = rawUrl ? extractDomain(new URL(rawUrl).hostname) : null;682          } catch {683            senderDomain = null;684          }685          if (!senderDomain) return { ok: false, error: "origin_unverified" };686687          const entryDomains = new Set<string>();688          const primary = extractDomain(entry.url ?? "");689          if (primary) entryDomains.add(primary);690          for (const extra of entry.additionalUrls ?? []) {691            const d = extractDomain(extra);692            if (d) entryDomains.add(d);693          }694695          // explicitSummon=true means the user actively picked this entry696          // from the cross-domain search affordance — an intentional697          // off-domain fill. Passive fill paths must stay domain-bound.698          if (explicitSummon !== true && !entryDomains.has(senderDomain)) {699            // Domain mismatch — refuse silently (no oracle about which ids exist).700            return { ok: false, error: "entry_not_found" };701          }702        }703        // Strip the passkey credential AND the raw base32 TOTP seed from the704        // response. Content scripts never need either: the private key is the705        // authenticator's, and handing over the TOTP seed would let a706        // compromised content script mint valid codes indefinitely (SEV-3-C).707        // Generate the *current* 6-digit code here in the background and send708        // only that, plus the seconds left so the UI can render a countdown.709        // Also drop passwordHistory: filling needs only the *current* password.710        // Handing every past password to a content script during passive711        // autofill on an arbitrary page would widen the blast radius of a712        // compromised page far beyond the one credential being filled.713        const { passkey: _strippedPasskey, totp: seed, passwordHistory: _ph, ...safeEntry } = entry;714        let totpCode: string | undefined;715        let totpRemaining: number | undefined;716        if (seed) {717          try {718            const generated = generateTOTP(seed);719            totpCode = generated.code;720            totpRemaining = generated.remaining;721          } catch {722            totpCode = undefined;723          }724        }725        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };726      }727      // Trusted full-entry fetch for Peach's own inline-popup surfaces that728      // genuinely need the raw TOTP seed: the edit form (which re-saves the729      // seed and would otherwise wipe it) and nothing else. Unlike730      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside731      // the inline popup, never during passive autofill on an arbitrary page.732      // The passkey credential is still stripped — the edit form never touches it.733      case "GET_ENTRY_FOR_EDIT": {734        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };735        const { id } = msg.payload as { id: string };736        const entry = vault.getEntryById(id);737        if (!entry) return { ok: false, error: "entry_not_found" };738        const { passkey: _passkey, ...safeEntry } = entry;739        return { ok: true, data: safeEntry };740      }741      case "COPY": {742        // AUD-002: shape-validate the payload before passing to the clipboard743        // helper. A raw cast lets a malformed message reach the clipboard API744        // with a non-string and throw.745        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {746          text?: unknown;747          label?: unknown;748          alreadyWritten?: unknown;749        };750        if (typeof text !== "string" || typeof label !== "string") {751          return { ok: false, error: "invalid_payload" };752        }753        await copyToClipboard(text, label, Boolean(alreadyWritten));754        return { ok: true };755      }756      case "CHECK_ALL_BREACHES": {757        const allEntries = vault.getEntries();758        const results: Record<string, number> = {};759        for (const entry of allEntries) {760          if (entry.type === "note") continue;761          if (!entry.password) continue;762          results[entry.id] = await vault.checkBreach(entry.password);763          // Small delay — be a good citizen to the HIBP API764          await new Promise((r) => setTimeout(r, 200));765        }766        // Persist any non-zero counts back to entries767        for (const [id, count] of Object.entries(results)) {768          const entry = vault.getEntryById(id);769          if (entry && (entry.breach ?? 0) !== count) {770            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });771          }772        }773        return { ok: true, data: results };774      }775      case "GET_SETTINGS":776        return { ok: true, data: await vault.ensureSettingsLoaded() };777      case "UPDATE_SETTINGS": {778        const patch = msg.payload;779        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {780          return { ok: false, error: "invalid_payload" };781        }782        await vault.updateSettings(patch as vault.VaultSettings);783        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {784          await setupAutoLock();785          if (vault.isUnlocked()) touchAutoLock();786        }787        return { ok: true };788      }789      case "GET_PENDING_PASSKEY":790        return { ok: true, data: await getPendingPasskeyRequest() };791      case "APPROVE_PASSKEY": {792        const { requestId } = msg.payload as { requestId: number };793        await resolvePendingPasskeyRequest(requestId, true);794        return { ok: true };795      }796      case "DENY_PASSKEY": {797        const { requestId } = msg.payload as { requestId: number };798        await resolvePendingPasskeyRequest(requestId, false);799        return { ok: true };800      }801      case "GET_PASSKEY_PROVIDER_STATE":802        return { ok: true, data: await getPasskeyProviderState() };803      case "SET_PASSKEY_PROVIDER_ENABLED": {804        const { enabled } = msg.payload as { enabled: boolean };805        // Disabling is always free; gating fires only when a free user is806        // trying to turn passkey interception on.807        if (enabled) {808          const gate = await requirePro("passkeys");809          if (!gate.allowed) return { ok: false, error: "pro_required" };810        }811        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };812      }813      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS814      // endpoint. Intentional product behavior — users configure their own815      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private816      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-817      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to818      // users that the entry title leaves the device when the canary fires.819      case "FIRE_CANARY_PING": {820        // Canary alert fires unconditionally for any entry with canary: true.821        // The Pro gate only governs creation/flagging of canary entries; once822        // an entry is flagged, the alert path is a security property and must823        // never be license-gated.824        const { webhookUrl, entryTitle, trigger } = msg.payload as {825          webhookUrl: string;826          entryTitle: string;827          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";828        };829        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {830          return { ok: false, error: "invalid_webhook_url" };831        }832        // LV-3: debounce non-test pings per (webhook, entry) so a page that833        // strobes focus/fill events can't turn the canary into a request834        // firehose at the user's endpoint. Test pings are exempt — they are835        // explicit user clicks in the settings UI and are awaited for836        // feedback. The FIRST ping in a window always goes out, so the837        // dead-man's-switch property (canary fires on access) is preserved;838        // only repeats within the window are coalesced.839        if (trigger !== "test") {840          const rlKey = `canary-last-fetch:${webhookUrl}:${entryTitle}`;841          const stored = await chrome.storage.local.get(rlKey);842          const last = (stored as Record<string, unknown>)[rlKey];843          if (typeof last === "number" && Date.now() - last < CANARY_MIN_INTERVAL_MS) {844            return { ok: true, data: { rateLimited: true } };845          }846          await chrome.storage.local.set({ [rlKey]: Date.now() });847        }848        const body = JSON.stringify({849          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",850          entry: entryTitle,851          trigger,852          timestamp: new Date().toISOString(),853          source: "peach-extension",854        });855        if (trigger === "test") {856          // Permitted outbound fetch: user-configured canary alert endpoint857          // (validated by isAllowedCanaryWebhookUrl above). This is the858          // only non-HIBP outbound call in the extension — see859          // Projects.md §3.7. Test pings are awaited so the UI can show860          // success/failure.861          try {862            const res = await fetch(webhookUrl, {863              method: "POST",864              headers: { "Content-Type": "application/json" },865              body,866            });867            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };868          } catch (err) {869            return { ok: false, error: err instanceof Error ? err.message : "network_error" };870          }871        }872        // Non-test triggers are fire-and-forget873        fetch(webhookUrl, {874          method: "POST",875          headers: { "Content-Type": "application/json" },876          body,877        }).catch(() => {});878        return { ok: true };879      }880      case "ACTIVATE_LICENSE": {881        const { key } = msg.payload as { key: string };882        const licenseInfo = await activateLicense(key);883        return { ok: true, data: licenseInfo };884      }885      case "GET_LICENSE": {886        const licenseInfo = await getLicenseInfo();887        return { ok: true, data: licenseInfo };888      }889      case "GET_LICENSE_KEY": {890        const key = await getLicenseKey();891        return { ok: true, data: key };892      }893      case "DEACTIVATE_LICENSE": {894        await deactivateLicense();895        return { ok: true };896      }897      case "SHOULD_PLAY_CELEBRATION": {898        const should = await shouldPlayCelebration();899        return { ok: true, data: should };900      }901      case "MARK_CELEBRATION_PLAYED": {902        await markCelebrationPlayed();903        return { ok: true };904      }905      case "GET_CODEX_VAULT_DATA": {906        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the907        // popup navigates to the License section without further coordination.908        const gate = await requirePro("codex");909        if (!gate.allowed) return { ok: false, error: "pro_required" };910        return await handleGetCodexVaultData();911      }912      case "ESTIMATE_CODEX_PAGES": {913        const gate = await requirePro("codex");914        if (!gate.allowed) return { ok: false, error: "pro_required" };915        return await handleEstimateCodexPages();916      }917      case "RESTORE_FROM_CODEX": {918        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still919        // be able to restore a vault that was printed by a Pro user.920        // DO NOT add a Pro gate here.921        const payload = msg.payload as CodexRestorePayload;922        return await handleRestoreFromCodex(payload);923      }924      case "OPEN_PRO_GATE": {925        // Content script requests: open popup and navigate to License section.926        const { feature } = (msg.payload ?? {}) as { feature?: string };927        if (chrome.storage.session) {928          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });929        }930        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }931        return { ok: true };932      }933      case "OPEN_POPUP": {934        // Content script asks to open the trusted extension popup — used by the935        // inline locked bubble so the master password is entered in the popup,936        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a937        // user gesture + Chrome 127+/Firefox; on failure the user clicks the938        // toolbar icon. The badge already signals Peach needs attention.939        //940        // Set a session flag so the popup knows it was opened for inline unlock941        // and should close itself once the vault is unlocked (returning the user942        // to the inline autofill selector on the page).943        if (chrome.storage.session) {944          await chrome.storage.session.set({ peach_inline_unlock: true });945        }946        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }947        return { ok: true };948      }949      case "GET_IDENTITIES": {950        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };951        return { ok: true, data: vault.getIdentities() };952      }953      case "TOUCH_AUTO_LOCK": {954        // touchAutoLock() is already called by shouldRefreshAutoLock above;955        // this case just gives the popup a typed message to keep the session alive.956        return { ok: true };957      }958      case "GET_ADVANCED_HEALTH_REPORT": {959        const gate = await requirePro("advanced_health");960        if (!gate.allowed) return { ok: false, error: "pro_required" };961        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };962        const report = await buildAdvancedHealthReport(vault.getEntries());963        return { ok: true, data: report };964      }965      case "IS_DURESS_ENABLED": {966        const enabled = await vault.isDuressEnabled();967        return { ok: true, data: enabled };968      }969      case "SETUP_DURESS": {970        // Single enforcement point for the Duress Vault Pro gate. Free users971        // who somehow reach this handler are rejected here; the popup also972        // pre-checks isPro() to avoid showing the setup form to free users,973        // but server-side is the actual security boundary.974        const gate = await requirePro("duress_vault");975        if (!gate.allowed) return { ok: false, error: "pro_required" };976        // MV3 service workers restart after inactivity, losing the in-memory977        // derived key. Detect this before calling setupDuress so the popup978        // can show a meaningful prompt to re-lock and re-unlock.979        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };980        const { duressPassword } = msg.payload as { duressPassword: string };981        await vault.setupDuress(duressPassword);982        return { ok: true };983      }984      case "DISABLE_DURESS": {985        await vault.disableDuress();986        return { ok: true };987      }988      case "VERIFY_MAIN_PASSWORD": {989        const { password } = msg.payload as { password: string };990        const ok = await vault.verifyMainPassword(password);991        return { ok: true, data: ok };992      }993      case "CHANGE_PASSWORD": {994        const { currentPassword, newPassword } = msg.payload as {995          currentPassword: string;996          newPassword: string;997        };998        const changed = await vault.changePassword(currentPassword, newPassword);999        return changed1000          ? { ok: true }1001          : { ok: false, error: "incorrect_current_password" };1002      }1003      case "GET_SITE_PASSWORD_POLICY": {1004        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1005        if (!tab?.id) return { ok: true, data: null };1006        try {1007          const response = await chrome.tabs.sendMessage(tab.id, {1008            type: "GET_SITE_PASSWORD_POLICY",1009          });1010          return (response as MessageResponse) ?? { ok: true, data: null };1011        } catch {1012          return { ok: true, data: null };1013        }1014      }1015      case "RECORD_MANUAL_SUMMON": {1016        const { domain } = msg.payload as { domain: string };1017        const settings = vault.getSettings();1018        const existing = settings.manualSummonDomains?.[domain];1019        const now = Date.now();1020        await vault.updateSettings({1021          manualSummonDomains: {1022            ...settings.manualSummonDomains,1023            [domain]: {1024              firstSummonedAt: existing?.firstSummonedAt ?? now,1025              summonCount: (existing?.summonCount ?? 0) + 1,1026              lastSummonedAt: now,1027            },1028          },1029        });1030        return { ok: true };1031      }1032      case "DECLINE_CARD_SAVE": {1033        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1034        await vault.declineCardSaveOffer(last4, expMonth, expYear);1035        return { ok: true };1036      }1037      case "IS_CARD_DECLINED": {1038        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1039        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1040        return { ok: true, data: declined };1041      }1042      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1043        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1044          rpId?: string;1045          rpName?: string;1046          userName?: string;1047          userDisplayName?: string;1048        };1049        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1050        return await initiateFirefoxPasskeyCreate({1051          rpId,1052          rpName: rpName ?? rpId,1053          userName,1054          userDisplayName,1055        });1056      }10571058      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1059        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1060        if (!payload) return { ok: false, error: "missing_payload" };1061        return await completeFirefoxPasskeyCreate(payload);1062      }10631064      case "PASSKEY_OFFER_DECLINE": {1065        const { domain } = (msg.payload ?? {}) as { domain?: string };1066        if (!domain) return { ok: false, error: "domain_required" };1067        await recordPasskeyOfferDecline(domain);1068        return { ok: true };1069      }10701071      case "GET_PASSKEY_OFFER_DECLINED": {1072        const { domain } = (msg.payload ?? {}) as { domain?: string };1073        if (!domain) return { ok: false, error: "domain_required" };1074        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1075      }10761077      case "PASSKEY_HAS_CREDENTIALS": {1078        const payload = msg.payload as {1079          rpId?: string;1080          allowCredentials?: Array<{ id: string; type?: string }>;1081        } | undefined;1082        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1083        return await handlePasskeyHasCredentials({1084          rpId: payload.rpId,1085          allowCredentials: payload.allowCredentials ?? [],1086        }, attestedSenderOrigin(sender));1087      }10881089      case "PASSKEY_CREATE": {1090        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1091        if (!payload?.rpId || !payload?.userName) {1092          return { ok: false, error: "rpid_and_username_required" };1093        }1094        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1095      }10961097      case "PASSKEY_GET": {1098        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1099        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1100        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1101      }11021103      case "PASSKEY_AUTH_RESPONSE": {1104        const { requestId, approved } = (msg.payload ?? {}) as {1105          requestId?: string | number;1106          approved?: boolean;1107        };1108        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1109          return { ok: false, error: 'requestId and approved required' };1110        }1111        await resolvePendingPasskeyRequest(Number(requestId), approved);1112        return { ok: true };1113      }11141115      case "GET_PASSKEY_FOR_DOMAIN": {1116        const { domain } = (msg.payload ?? {}) as { domain?: string };1117        if (!domain) return { ok: false, error: "domain_required" };1118        // Scope to the caller's own origin: a page may only ask about passkeys1119        // for a domain it actually owns, so an arbitrary page cannot enumerate1120        // which sites the user holds passkeys for or read the username (audit MEDIUM).1121        const origin = attestedSenderOrigin(sender);1122        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1123        if (!vault.isUnlocked()) return { ok: true, data: null };1124        const match = vault1125          .getEntries()1126          .find((entry) => entry.passkey?.rpId === domain);1127        if (!match || !match.passkey) return { ok: true, data: null };1128        // Slim shape — only the fields State 11 needs. Never expose private1129        // key material, even though this is locked behind isUnlocked.1130        return {1131          ok: true,1132          data: {1133            rpId: match.passkey.rpId,1134            userName: match.passkey.userName,1135            browser: match.passkey.browser,1136          },1137        };1138      }11391140      case "DESTROY_VAULT": {1141        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1142        // storage.local.clear() wipes every Peach key (slots, settings, license,1143        // onboarded flag, history, sync state, declined cards, recall, etc.);1144        // session.clear() wipes pending passkey requests + pro-notice queues.1145        // Caller (Panic.tsx) handles UI navigation back to onboarding.1146        //1147        // The Pro license is the one thing that must survive: the user paid for1148        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1149        // Capture it before the clear and restore it after. peach_pro_celebrated1150        // rides along so the Pro celebration doesn't replay on the next unlock.1151        const preserved = await chrome.storage.local.get([1152          "peach_license",1153          "peach_pro_celebrated",1154        ]);1155        vault.lock();1156        await storageClear();1157        await vault.clearVaultHistory();1158        const toRestore: Record<string, unknown> = {};1159        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1160        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1161        if (Object.keys(toRestore).length > 0) {1162          await chrome.storage.local.set(toRestore);1163        }1164        if (chrome.storage.session) {1165          await chrome.storage.session.clear();1166        }1167        return { ok: true };1168      }11691170      case "SUBMIT_FEEDBACK": {1171        const { category, message, version, browser } = msg.payload as {1172          category: string;1173          message: string;1174          version: string;1175          browser: string;1176        };1177        if (!message.trim()) return { ok: false, error: "message_empty" };1178        if (!FEEDBACK_ENDPOINT) return { ok: true };1179        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1180          return { ok: false, error: "invalid_feedback_endpoint" };1181        }1182        try {1183          const res = await fetch(FEEDBACK_ENDPOINT, {1184            method: "POST",1185            headers: { "Content-Type": "application/json" },1186            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1187          });1188          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1189        } catch (err) {1190          return { ok: false, error: err instanceof Error ? err.message : "network_error" };1191        }1192      }1193      // Android-only: biometric unlock with pre-derived key.1194      case "UNLOCK_WITH_KEY": {1195        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1196        if (!isNativePlatform()) {1197          return { ok: false, error: "desktop_only_uses_password" };1198        }1199        try {1200          const result = await vault.unlockWithKey(masterKeyHex);1201          if (result.ok) {1202            onVaultUnlocked();1203            await publishInMemoryVault(result.entries);1204          }1205          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1206        } catch {1207          return { ok: false, error: "invalid_key" };1208        }1209      }1210      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1211      case "GET_DERIVED_KEY": {1212        if (!isNativePlatform()) {1213          return { ok: false, error: "android_only" };1214        }1215        if (!vault.isUnlocked()) {1216          return { ok: false, error: "vault_locked" };1217        }1218        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1219      }1220      case "GET_IDENTITY_SUGGESTIONS": {1221        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1222        const entries = vault.getEntries();1223        const suggestions = buildIdentitySuggestions(entries);1224        return { ok: true, data: { suggestions } };1225      }1226      case "POPULATE_INLINE_VAULT": {1227        if (!isNativePlatform()) return { ok: false };1228        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1229        const entries = vault.getEntries();1230        await publishInMemoryVault(entries);1231        return { ok: true };1232      }1233      case "ML_INIT":1234        return { ok: true };12351236      case "ML_PREDICT_BATCH": {1237        // AUD-002: shape-validate before forwarding to the ML helper.1238        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1239        if (!Array.isArray(featuresArray)) {1240          return { ok: false, error: "invalid_payload" };1241        }1242        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1243      }12441245      // ── Chirp Sync (v3) ───────────────────────────────────────────────1246      // Returns the public-facing local identity needed by the popup to1247      // drive Phase-1 audio pairing. The private long-term key never1248      // leaves the background.1249      case "CHIRP_GET_LOCAL_IDENTITY": {1250        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1251        const proCheck = await requirePro("sync");1252        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1253        // Identity derives from the stable root key, not the password-derived1254        // key, so pairing survives a master-password change (SEV-2-B).1255        const masterKeyHex = vault.getRootKeyHex();1256        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1257        const masterKey = unhexBytes(masterKeyHex);1258        try {1259          const identity = await buildLocalIdentity(masterKey);1260          return { ok: true, data: identity };1261        } finally {1262          masterKey.fill(0);1263        }1264      }12651266      case "CHIRP_COMPLETE_PAIRING": {1267        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1268        const proCheck = await requirePro("sync");1269        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1270        const paired = (msg.payload as { paired?: unknown })?.paired;1271        if (typeof paired !== "object" || paired === null) {1272          return { ok: false, error: "invalid_payload" };1273        }1274        const candidate = paired as Record<string, unknown>;1275        if (1276          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1277          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1278          typeof candidate.deviceType !== "string" ||1279          typeof candidate.longTermPublicKeyHex !== "string" ||1280          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1281          (1282            candidate.signingPublicKeyHex !== undefined &&1283            (1284              typeof candidate.signingPublicKeyHex !== "string" ||1285              !/^[0-9a-f]{64}$/.test(candidate.signingPublicKeyHex)1286            )1287          ) ||1288          typeof candidate.pairedAt !== "number"1289        ) {1290          return { ok: false, error: "invalid_paired_device" };1291        }1292        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1293        return { ok: true };1294      }12951296      case "CHIRP_LIST_PAIRED_DEVICES": {1297        const devices = await listPairedDevicesV3();1298        return { ok: true, data: { devices } };1299      }13001301      case "CHIRP_UNPAIR_DEVICE": {1302        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1303        if (typeof deviceId !== "string" || !deviceId) {1304          return { ok: false, error: "invalid_payload" };1305        }1306        await removePairedDeviceByIdV3(deviceId);1307        return { ok: true };1308      }13091310      case "CHIRP_RENAME_LOCAL_DEVICE": {1311        const { name } = (msg.payload ?? {}) as { name?: string };1312        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1313        await setDeviceNameV3(name);1314        return { ok: true };1315      }13161317      case "TRIGGER_SYNC": {1318        const payload = (msg.payload ?? {}) as {1319          reason?: "vault_change" | "foreground" | "manual" | "mdns";1320          force?: boolean;1321          deviceId?: string;1322          discoveredIp?: string;1323          discoveredPort?: number;1324        };1325        const reason = payload.reason ?? "foreground";13261327        // mDNS discovery delivers a fresh (ip, port) resolved by the native1328        // side. Update the cached address before the sync runner tries to1329        // connect — avoids a subnet probe on the very next round.1330        if (1331          reason === "mdns" &&1332          typeof payload.deviceId === "string" &&1333          typeof payload.discoveredIp === "string"1334        ) {1335          const { findPairedDeviceById, setLastKnownIp } = await import("./paired-devices");1336          const device = await findPairedDeviceById(payload.deviceId);1337          if (device?.longTermPublicKeyHex) {1338            await setLastKnownIp(device.longTermPublicKeyHex, payload.discoveredIp).catch(() => undefined);1339          }1340        }13411342        const { triggerSyncIfReachable } = await import("./sync-trigger");1343        void triggerSyncIfReachable({ reason, force: payload.force === true });1344        return { ok: true };1345      }13461347      case "GET_SYNC_STATE": {1348        const { getSyncState } = await import("./sync-trigger");1349        return { ok: true, data: getSyncState() };1350      }13511352      case "GET_SYNC_ALERTS": {1353        const { consume } = (msg.payload ?? {}) as { consume?: boolean };1354        const alerts = await getPendingSyncAlerts();1355        // The popup reads on open and acknowledges with consume:true after1356        // rendering, so a popup crash between read and render doesn't lose1357        // the alerts.1358        if (consume) await clearPendingSyncAlerts();1359        return { ok: true, data: alerts };1360      }13611362      case "GET_PENDING_VOUCHED_DEVICES": {1363        return { ok: true, data: await listPendingVouchedDevices() };1364      }1365      case "CONFIRM_VOUCHED_DEVICE": {1366        const { deviceId } = msg.payload as { deviceId: string };1367        const pending = await getPendingVouchedDevice(deviceId);1368        if (!pending) return { ok: false, error: "not_pending" };1369        await upsertPairedDeviceV3({1370          deviceId: pending.deviceId,1371          deviceName: pending.deviceName,1372          deviceType:1373            pending.deviceType as import("../shared/sync-types").PairedDevice["deviceType"],1374          longTermPublicKeyHex: pending.longTermPublicKeyHex,1375          signingPublicKeyHex: pending.signingPublicKeyHex,1376          wsPort: pending.wsPort,1377          pairedAt: pending.pairedAt,1378          trustSource: "vouched",1379        });1380        await removePendingVouchedDevice(deviceId);1381        return { ok: true };1382      }1383      case "REJECT_VOUCHED_DEVICE": {1384        const { deviceId } = msg.payload as { deviceId: string };1385        await removePendingVouchedDevice(deviceId);1386        return { ok: true };1387      }1388      case "ROTATE_SYNC_IDENTITY": {1389        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1390        const result = await vault.rotateSyncIdentity();1391        return result.ok ? { ok: true } : { ok: false, error: result.error };1392      }13931394      default:1395        return { ok: false, error: "unknown_message_type" };1396    }1397  } catch (err) {1398    return {1399      ok: false,1400      error: err instanceof Error ? err.message : "operation_failed",1401    };1402  }1403}14041405// --- Mobile platform helpers ---14061407// Android: populates the in-memory vault used by PeachAutofillService.1408async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1409  const plugin = nativePlugin<{1410    setEntries?: (args: {1411      entries: Array<{1412        id: string;1413        title: string;1414        username: string;1415        email: string;1416        password: string;1417        url: string;1418        totp: string;1419        additionalUrls: string[];1420      }>;1421    }) => Promise<void>;1422  }>("InMemoryVaultPlugin");1423  if (!plugin?.setEntries) return;1424  await plugin.setEntries({1425    entries: entries.map((e) => ({1426      id: e.id,1427      title: e.title ?? "",1428      username: e.username ?? "",1429      email: (e as VaultEntry & { email?: string }).email ?? "",1430      password: e.password ?? "",1431      url: e.url ?? "",1432      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1433      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1434    })),1435  });1436}14371438// Android: clear the autofill in-memory store on lock.1439async function clearInMemoryVault(): Promise<void> {1440  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1441  if (!plugin?.clearEntries) return;1442  await plugin.clearEntries();1443}14441445// Returns username use-counts from the vault, sorted by frequency. Each row1446// also carries the entry's email so the popup can suggest the email/username1447// pair the user has actually used together.1448function buildIdentitySuggestions(1449  entries: VaultEntry[],1450): Array<{ email: string; username: string; count: number }> {1451  const usernameCounts = new Map<string, number>();1452  const usernameEmail = new Map<string, string>();1453  for (const entry of entries) {1454    const username = entry.username ?? "";1455    const email = (entry as VaultEntry & { email?: string }).email ?? "";1456    if (!username && !email) continue;1457    const key = username || email;1458    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1459    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1460  }1461  return Array.from(usernameCounts.entries())1462    .sort((a, b) => b[1] - a[1])1463    .map(([username, count]) => ({1464      email: usernameEmail.get(username) ?? "",1465      username,1466      count,1467    }));1468}14691470/** Notify all content scripts that the vault just became available. */1471function broadcastToContentScripts(message: { type: string }): void {1472  if (!chrome.tabs?.query) return;1473  chrome.tabs.query({}, (tabs) => {1474    for (const tab of tabs) {1475      if (tab.id !== undefined) {1476        chrome.tabs.sendMessage(tab.id, message).catch(() => {1477          // Tab may not have a content script — silently ignore1478        });1479      }1480    }1481  });1482}14831484function shouldRefreshAutoLock(type: MessageType): boolean {1485  return (1486    type !== "HAS_VAULT" &&1487    type !== "IS_UNLOCKED" &&1488    type !== "GET_VAULT_STATUS" &&1489    type !== "LOCK" &&1490    type !== "UPDATE_SETTINGS" &&1491    type !== "GET_PENDING_PASSKEY" &&1492    type !== "GET_PASSKEY_PROVIDER_STATE" &&1493    type !== "DECLINE_CARD_SAVE" &&1494    type !== "IS_CARD_DECLINED" &&1495    type !== "SUBMIT_FEEDBACK"1496  );1497}14981499function isAllowedCanaryWebhookUrl(value: string): boolean {1500  try {1501    const url = new URL(value);1502    if (url.protocol !== "https:") return false;15031504    const hostname = url.hostname.toLowerCase();1505    if (1506      hostname === "localhost" ||1507      hostname.endsWith(".localhost") ||1508      isPrivateIpv4(hostname) ||1509      isPrivateIpv6(hostname)1510    ) {1511      return false;1512    }15131514    return true;1515  } catch {1516    return false;1517  }1518}15191520function isPrivateIpv4(hostname: string): boolean {1521  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1522    return true;1523  }15241525  const octets = hostname.split(".").map((part) => Number(part));1526  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1527    return false;1528  }15291530  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1531}15321533function isPrivateIpv6(hostname: string): boolean {1534  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1535  return (1536    normalized === "::1" ||1537    normalized.startsWith("fc") ||1538    normalized.startsWith("fd") ||1539    normalized.startsWith("fe80:")1540  );1541}