messages.ts

57.1 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 { setupAutoLock, touchAutoLock } from "./alarms";14import { runSelfTest } from "./self-test";15import * as vault from "./vault";16import {17  handleEstimateCodexPages,18  handleGetCodexVaultData,19  handleRestoreFromCodex,20} from "./codex-handlers";21import type { CodexRestorePayload } from "../shared/codex-types";22import {23  activateLicense,24  deactivateLicense,25  getLicenseInfo,26  getLicenseKey,27  isProUser,28  markCelebrationPlayed,29  shouldPlayCelebration,30} from "./license";31import {32  completeFirefoxPasskeyCreate,33  getPasskeyProviderState,34  getPendingPasskeyRequest,35  handleFirefoxPasskeyCreate,36  handleFirefoxPasskeyGet,37  handlePasskeyHasCredentials,38  initiateFirefoxPasskeyCreate,39  isPasskeyOfferDeclined,40  onVaultUnlocked,41  recordPasskeyOfferDecline,42  resolvePendingPasskeyRequest,43  setPasskeyProviderEnabled,44} from "./passkey";45import { buildAdvancedHealthReport } from "./health";46import { storageClear } from "../shared/storage";47import { findInvalidWords } from "../shared/recovery-words";48import type {49  Message,50  MessageResponse,51  MessageType,52  ProFeature,53  VaultEntry,54} from "../shared/types";55import { isPasskeyOnly } from "../shared/types";56import { generateTOTP } from "../crypto/totp";57import { isValidRpId } from "../shared/passkey-utils";58import { isNativePlatform, nativePlugin } from "../shared/native";59import { predictBatch as mlPredictBatch } from "./ml";60import type { MLFieldFeatures } from "../shared/ml";61import { buildLocalIdentity, setDeviceName as setDeviceNameV3 } from "./chirp-identity";62import {63  listPairedDevices as listPairedDevicesV3,64  removePairedDeviceById as removePairedDeviceByIdV3,65  upsertPairedDevice as upsertPairedDeviceV3,66} from "./paired-devices";6768// Compile-time E2E flag, folded to a literal by Vite's `define` (false in69// every production build — verified in the bundled output). Mirrors the70// create-path bypass in passkey.ts so the Playwright passkey smoke can enable71// the provider without a real Pro licence; the gate is fully intact for users.72declare const __PEACH_E2E_PASSKEYS__: boolean;73const PASSKEY_E2E_PRO_BYPASS = __PEACH_E2E_PASSKEYS__ === true;7475let nativeSyncRunnerBootstrapped = false;7677function unhexBytes(hex: string): Uint8Array {78  if (hex.length % 2 !== 0) throw new Error("invalid hex");79  const out = new Uint8Array(hex.length / 2);80  for (let i = 0; i < out.length; i++) {81    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);82  }83  return out;84}8586/**87 * The single Pro gate. Every gated handler calls this first; the broadcast88 * lets the popup react (navigate to the License section, highlight the89 * relevant feature). Background never touches the popup view directly —90 * the popup owns navigation. See Projects.md "Pro gate rule".91 */92async function requirePro(93  feature: ProFeature,94  trigger: "user" | "background" = "user"95): Promise<{ allowed: boolean }> {96  if (PASSKEY_E2E_PRO_BYPASS && feature === "passkeys") return { allowed: true };97  if (await isProUser()) return { allowed: true };9899  if (trigger === "user") {100    // User deliberately triggered this feature — redirect the popup immediately.101    chrome.runtime102      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })103      .catch(() => {104        // Popup may be closed — the gate signal is best-effort.105      });106  } else {107    // Background trigger (e.g. passive sync initiation) — no popup is open.108    // Queue a notice so the next popup open shows a soft banner instead of109    // silently failing.110    if (chrome.storage.session) {111      chrome.storage.session112        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })113        .catch(() => {});114    }115  }116117  return { allowed: false };118}119120// ---------------------------------------------------------------------------121// Feedback submission target. Empty disables network submission while the UI122// continues to function as a no-op (the handler returns ok:true without123// calling fetch). When set, the URL is validated by124// `isAllowedCanaryWebhookUrl` before any request.125// ---------------------------------------------------------------------------126127const FEEDBACK_ENDPOINT = "";128129const PRIVATE_IPV4_RANGES = [130  { prefix: "10." },131  { prefix: "127." },132  { prefix: "169.254." },133  { prefix: "192.168." },134];135136export function setupMessageHandler(): void {137  chrome.runtime.onMessage.addListener(138    (msg: unknown, sender, sendResponse) => {139      if (!isMessage(msg)) {140        sendResponse({ ok: false, error: "invalid_message" });141        return true;142      }143      handleMessage(msg, sender)144        .then(sendResponse)145        .catch((err) =>146          sendResponse({147            ok: false,148            error: err instanceof Error ? err.message : String(err),149          })150        );151      return true;152    }153  );154155  // Android: the chrome shim queues sendMessage calls until this handler is156  // registered. Without this hookup, every message hangs on Capacitor builds.157  // eslint-disable-next-line @typescript-eslint/no-explicit-any158  const reg = (globalThis as any).__peachRegisterMessageHandler;159  if (typeof reg === "function") {160    reg(async (m: unknown) => {161      if (!isMessage(m)) return { ok: false, error: "invalid_message" };162      try {163        return await handleMessage(m);164      } catch (err) {165        return {166          ok: false,167          error: err instanceof Error ? err.message : String(err),168        };169      }170    });171  }172  if (isNativePlatform()) {173    void bootstrapNativeSyncRunner();174  }175}176177async function bootstrapNativeSyncRunner(): Promise<void> {178  if (nativeSyncRunnerBootstrapped) return;179  nativeSyncRunnerBootstrapped = true;180  try {181    const { setSyncRunner, hydratePersistedSyncState } = await import("./sync-trigger");182    const { productionSyncRunner } = await import("./chirp-sync-runner");183    setSyncRunner(productionSyncRunner);184    await hydratePersistedSyncState();185  } catch (err) {186    nativeSyncRunnerBootstrapped = false;187    console.warn("[Peach] failed to bootstrap native sync runner:", err);188  }189}190191function isMessage(m: unknown): m is Message {192  return typeof m === "object" && m !== null && "type" in m;193}194195/**196 * The browser-attested origin of the page that originated this message. A web197 * page cannot call chrome.runtime.sendMessage directly (no externally_connectable),198 * so every page-driven message arrives via the content-script relay and the199 * browser stamps `sender.origin`/`sender.url` with the real frame origin — a200 * value the page cannot forge. This is the ONLY trustworthy origin for passkey201 * rpId<->origin enforcement; payload-supplied origins are attacker-controlled.202 */203function attestedSenderOrigin(sender: Partial<chrome.runtime.MessageSender>): string | undefined {204  if (sender.origin) return sender.origin;205  if (sender.url) {206    try { return new URL(sender.url).origin; } catch { return undefined; }207  }208  return undefined;209}210211// Resolves once restoreFromSession() has run, so handlers see the correct212// post-restore unlock state. entry.ts registers this BEFORE the message213// handler so the onMessage listener is added synchronously at SW startup214// (MV3 requirement) while unlock-dependent handlers still wait for restore.215let restoreReady: Promise<void> = Promise.resolve();216217/** Called by entry.ts at startup with the in-flight restoreFromSession promise. */218export function setRestoreReady(p: Promise<unknown>): void {219  restoreReady = p.then(() => undefined, () => undefined);220}221222export async function handleMessage(223  msg: Message,224  sender: Partial<chrome.runtime.MessageSender> = {}225): Promise<MessageResponse> {226  try {227    // Wait for session-restore to finish before reading any unlock/vault state.228    // On a cold SW start the popup's first message arrives while restore is229    // still in flight; without this gate IS_UNLOCKED would report locked (a230    // spurious lock screen) and the storage reads could race. The onMessage231    // listener itself is registered synchronously (entry.ts) so this gate, not232    // listener registration, is what absorbs the cold-start window.233    await restoreReady;234    // Validate sender — only allow messages from our extension pages/scripts.235    // `sender.id` is undefined for messages originating from extension UI236    // (popup/options), which is legitimate; reject only when it is defined237    // and does not match our extension id.238    if (239      sender.id !== undefined &&240      sender.id !== chrome.runtime.id241    ) {242      return { ok: false, error: "invalid_sender" };243    }244245    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {246      touchAutoLock();247    }248249    switch (msg.type) {250      case "CREATE_VAULT": {251        const { password } = msg.payload as { password: string };252        // Refuse to create a vault under an empty master password — the derived253        // key would be publicly known and the at-rest AES-GCM protection void254        // (audit HIGH; the CSV-import path previously passed ""). Length/strength255        // policy lives in the onboarding UI; this is the non-negotiable floor.256        if (typeof password !== "string" || password.length === 0) {257          return { ok: false, error: "invalid_payload" };258        }259        await vault.createVault(password);260        await setupAutoLock();261        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });262        onVaultUnlocked();263        return { ok: true };264      }265      case "UNLOCK": {266        const { password } = msg.payload as { password: string };267        const ok = await vault.unlock(password);268        if (ok) {269          // KAT: verify the WebCrypto stack is healthy before the user relies on it.270          // Runs after unlock so latency is hidden behind the vault-load time.271          const kat = await runSelfTest();272          if (!kat.ok) {273            console.error("[Peach] Crypto self-test FAILED:", kat.error);274            await vault.lock();275            return { ok: false, error: "self_test_failed" };276          }277          await setupAutoLock();278          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });279          onVaultUnlocked();280          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());281          return { ok: true };282        }283        // Distinguish corruption from wrong password so the popup can offer284        // a history-restore path instead of falsely accusing the user of285        // mistyping (M7/COR-007).286        const failure = vault.consumeLastUnlockFailureReason();287        if (failure) {288          return {289            ok: false,290            error: "vault_corrupted",291            canRestoreFromHistory: true,292          } as MessageResponse;293        }294        return { ok: false };295      }296      case "VALIDATE_RECOVERY_WORDS": {297        const { words } = msg.payload as { words: string[] };298        const invalid = findInvalidWords(words);299        return { ok: true, data: { valid: invalid.length === 0, invalid } };300      }301      case "GET_RECOVERY_WORDS": {302        // Must be unlocked and have recovery set up (vault must be v2.12+).303        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };304        try {305          const words = await vault.getRecoveryWords();306          return { ok: true, data: words };307        } catch (e) {308          // pre-v2.12 vault that hasn't migrated309          return { ok: false, error: "recovery_not_setup" };310        }311      }312      case "RECOVER_WITH_WORDS": {313        // User has lost their password but has their 12 recovery words.314        // We: (1) validate the words, (2) re-encrypt vault with new password.315        const { words, newPassword } = msg.payload as {316          words: string[];317          newPassword: string;318        };319        const stored = await vault.loadSlotA();320        if (!stored) return { ok: false, error: "no_vault" };321        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {322          return { ok: false, error: "recovery_not_setup" };323        }324        // Unwrap the root key from the recovery escrow.325        try {326          await vault.unwrapRootKeyForRecovery(327            stored.recovery_wrapped_root_key,328            stored.recovery_nonce ?? "",329            stored.recovery_tag ?? "",330            stored.recovery_salt,331            words332          );333        } catch {334          return { ok: false, error: "invalid_recovery_words" };335        }336        // Re-key: derive fresh salt + key from new password.337        const newSalt = vault.generateSalt();338        const newKey = await vault.deriveKey(newPassword, newSalt);339        // Re-wrap root key under the new password's derived key so the same340        // recovery words continue to work after the password change.341        await vault.rewrapRootKeyForPassword(newKey, newSalt);342        // Re-encrypt vault entries with the new key.343        await vault.changePasswordWithNewKey(newSalt, newKey);344        await setupAutoLock();345        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });346        return { ok: true };347      }348      case "LOCK":349        vault.lock();350        if (isNativePlatform()) await clearInMemoryVault();351        return { ok: true };352      case "IS_UNLOCKED":353        return { ok: true, data: vault.isUnlocked() };354      case "GET_VAULT_STATUS":355        return { ok: true, unlocked: vault.isUnlocked() };356      case "HAS_VAULT":357        return { ok: true, data: await vault.hasVault() };358      case "GET_ENTRIES":359        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };360        return { ok: true, data: vault.getEntries() };361      case "ADD_ENTRY": {362        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };363        const payload = msg.payload;364        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {365          return { ok: false, error: "invalid_payload" };366        }367        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);368        // Merge any same-domain passkey entry with this new entry right away369        // (e.g. user adds a TOTP for a site that already has a passkey entry).370        void vault.consolidatePasskeyEntries();371        return { ok: true, data: entry };372      }373      case "BATCH_ADD_ENTRIES": {374        const payload = msg.payload as { entries?: unknown } | null | undefined;375        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {376          return { ok: false, error: "invalid_payload" };377        }378        if (!Array.isArray(payload.entries)) {379          return { ok: false, error: "invalid_payload" };380        }381        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);382        return { ok: true, data: added };383      }384      case "RESTORE_ENTRIES": {385        const payload = msg.payload as386          | { entries?: unknown; mode?: unknown; settings?: unknown }387          | null388          | undefined;389        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {390          return { ok: false, error: "invalid_payload" };391        }392        if (!Array.isArray(payload.entries)) {393          return { ok: false, error: "invalid_payload" };394        }395        if (payload.mode !== "replace" && payload.mode !== "merge") {396          return { ok: false, error: "invalid_payload" };397        }398        const summary = await vault.restoreEntries(399          payload.entries as Parameters<typeof vault.restoreEntries>[0],400          payload.mode401        );402        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {403          await vault.updateSettings(payload.settings as vault.VaultSettings);404        }405        return { ok: true, data: summary };406      }407      case "CLEAR_VAULT_ENTRIES": {408        await vault.clearVaultEntries("REPLACE_ALL");409        return { ok: true };410      }411      case "GET_VAULT_HISTORY": {412        const snapshots = await vault.getVaultHistory();413        return { ok: true, data: snapshots };414      }415      case "RESTORE_VAULT_SNAPSHOT": {416        const { snapshotId } = msg.payload as { snapshotId: string };417        const result = await vault.restoreVaultSnapshot(snapshotId);418        if (!result.ok) return { ok: false, error: result.error };419        broadcastToContentScripts({ type: "VAULT_LOCKED" });420        return { ok: true };421      }422      case "COUNT_DUPLICATES": {423        return { ok: true, data: vault.countDuplicates() };424      }425      case "DEDUPLICATE_ENTRIES": {426        const removed = await vault.deduplicateEntries();427        return { ok: true, data: removed };428      }429      case "UPDATE_ENTRY": {430        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;431        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {432          return { ok: false, error: "invalid_payload" };433        }434        const { id, patch } = payload;435        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {436          return { ok: false, error: "invalid_payload" };437        }438        // Single enforcement point for the Canary Entries Pro gate. Only439        // gates the transition into a canary entry — clearing/disabling a440        // canary (`canary: undefined`) is always allowed, so existing441        // canary entries remain manageable.442        const incomingCanary = (patch as { canary?: unknown }).canary;443        if (incomingCanary && typeof incomingCanary === "object") {444          const existing = vault.getEntryById(id);445          if (!existing?.canary) {446            const gate = await requirePro("canary_entry");447            if (!gate.allowed) return { ok: false, error: "pro_required" };448          }449        }450        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);451        return { ok: true };452      }453      case "ADD_ADDITIONAL_URL": {454        const { id, url } = msg.payload as { id: string; url: string };455        const trimmed = typeof url === "string" ? url.trim() : "";456        if (!trimmed) return { ok: false, error: "url_required" };457        const existing = vault.getEntryById(id);458        if (!existing) return { ok: false, error: "entry_not_found" };459        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };460        const merged = [...(existing.additionalUrls ?? []), trimmed];461        await vault.updateEntry(id, { additionalUrls: merged });462        return { ok: true };463      }464      case "DELETE_ENTRY": {465        const { id } = msg.payload as { id: string };466        await vault.deleteEntry(id);467        return { ok: true };468      }469      case "GET_DELETED_ENTRIES":470        return { ok: true, data: vault.getDeletedEntries() };471      case "RESTORE_ENTRY": {472        const { id } = msg.payload as { id: string };473        await vault.restoreEntry(id);474        return { ok: true };475      }476      case "PURGE_ENTRY": {477        const { id } = msg.payload as { id: string };478        await vault.purgeEntry(id);479        return { ok: true };480      }481      case "PURGE_EXPIRED_TRASH": {482        const { retentionMs } = msg.payload as { retentionMs: number };483        const purged = await vault.purgeExpiredTrash(retentionMs);484        return { ok: true, data: purged };485      }486      case "SAVE_NOTE": {487        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };488        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };489        const now = Date.now();490        if (id) {491          const existing = vault.getEntryById(id);492          if (!existing) return { ok: false, error: "not_found" };493          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });494          return { ok: true, data: vault.getEntryById(id) };495        } else {496          const entry = await vault.addEntry({497            type: "note",498            title: title || "Untitled",499            notes: body,500            createdAt: now,501            modifiedAt: now,502          } as any);503          return { ok: true, data: entry };504        }505      }506      case "DELETE_NOTE": {507        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };508        const { id } = msg.payload as { id: string };509        await vault.deleteEntry(id);510        return { ok: true };511      }512      case "GET_NOTES": {513        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };514        const notes = vault.getEntries().filter(515          (e) => e.type === "note" && !e.deletedAt516        );517        return { ok: true, data: notes } as MessageResponse;518      }519      case "SEARCH_VAULT": {520        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };521        // AUD-002: shape-validate the payload before calling string methods.522        // A raw cast lets a malformed message crash the handler with TypeError.523        const { query } = (msg.payload ?? {}) as { query?: unknown };524        if (typeof query !== "string") {525          return { ok: false, error: "invalid_payload" };526        }527        const q = query.toLowerCase();528        const searchResults = vault.getEntries().filter(529          (e) =>530            !e.deletedAt &&531            (e.title.toLowerCase().includes(q) ||532              e.notes?.toLowerCase().includes(q) ||533              e.username?.toLowerCase().includes(q))534        );535        return { ok: true, data: searchResults } as MessageResponse;536      }537      case "AUTOFILL_QUERY": {538        if (!vault.isUnlocked()) {539          return { ok: false, error: "vault_locked" };540        }541        const { domain, includeAll, kind } = msg.payload as {542          domain: string;543          includeAll?: boolean;544          kind?: "login" | "card" | "totp";545        };546        // kind="card": return saved cards as compact summaries for the547        // inline card silver platter. Cards are not domain-scoped — every548        // saved card is a candidate on every checkout page — so domain is549        // ignored when kind === "card".550        if (kind === "card") {551          const cards = vault.getEntries().filter((e) => e.type === "card");552          return {553            ok: true,554            data: cards.map((e) => ({555              id: e.id,556              title: e.cardNickname || e.title,557              cardholderName: e.cardholderName,558              last4: e.last4,559              expMonth: e.expMonth,560              expYear: e.expYear,561              network: e.network,562            })),563          };564        }565        if (kind === "totp") {566          const matches = (567            includeAll568              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")569              : vault.queryDomain(domain)570          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));571          return {572            ok: true,573            data: matches.map((e) => ({574              id: e.id,575              title: e.title,576              username: e.username,577              email: e.email,578              url: e.url,579              hasTotp: true,580            })),581          };582        }583        // The inline selector fills username+password into a form. Passkey-584        // only entries have no password to fill; sign-in for those goes585        // through the WebAuthn path instead. Filter them out everywhere so586        // the user doesn't see four "GitHub" rows that mostly do nothing.587        // Notes and cards never belonged here either.588        const matches = (589          includeAll590            ? vault591                .getEntries()592                .filter((entry) => entry.type !== "note" && entry.type !== "card")593            : vault.queryDomain(domain)594        ).filter((entry) => !isPasskeyOnly(entry));595        return {596          ok: true,597          data: matches.map((e) =>598            includeAll599              ? {600                  id: e.id,601                  title: e.title,602                  // username/email/url shipped so the inline popup's search603                  // affordance can match on them, not just titles. No secrets604                  // cross the boundary — same shape as the domain-matched605                  // response below minus hasTotp (which the search list606                  // doesn't surface).607                  username: e.username,608                  email: e.email,609                  url: e.url,610                  hasPasskey: e.passkey !== undefined,611                }612              : {613                  id: e.id,614                  title: e.title,615                  username: e.username,616                  email: e.email,617                  url: e.url,618                  hasTotp: Boolean(e.totp),619                  hasPasskey: e.passkey !== undefined,620                }621          ),622        };623      }624      case "GET_ENTRY_FOR_FILL": {625        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };626        const { id } = msg.payload as { id: string };627        const entry = vault.getEntryById(id);628        if (!entry) return { ok: false, error: "entry_not_found" };629        // Passkey-only entries (passkey credential, no password) cannot be630        // filled into a form — sign-in goes through the WebAuthn path. A631        // login that ALSO has a passkey is still fillable for its password.632        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };633        // Strip the passkey credential AND the raw base32 TOTP seed from the634        // response. Content scripts never need either: the private key is the635        // authenticator's, and handing over the TOTP seed would let a636        // compromised content script mint valid codes indefinitely (SEV-3-C).637        // Generate the *current* 6-digit code here in the background and send638        // only that, plus the seconds left so the UI can render a countdown.639        const { passkey: _strippedPasskey, totp: seed, ...safeEntry } = entry;640        let totpCode: string | undefined;641        let totpRemaining: number | undefined;642        if (seed) {643          try {644            const generated = generateTOTP(seed);645            totpCode = generated.code;646            totpRemaining = generated.remaining;647          } catch {648            totpCode = undefined;649          }650        }651        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };652      }653      // Trusted full-entry fetch for Peach's own inline-popup surfaces that654      // genuinely need the raw TOTP seed: the edit form (which re-saves the655      // seed and would otherwise wipe it) and nothing else. Unlike656      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside657      // the inline popup, never during passive autofill on an arbitrary page.658      // The passkey credential is still stripped — the edit form never touches it.659      case "GET_ENTRY_FOR_EDIT": {660        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };661        const { id } = msg.payload as { id: string };662        const entry = vault.getEntryById(id);663        if (!entry) return { ok: false, error: "entry_not_found" };664        const { passkey: _passkey, ...safeEntry } = entry;665        return { ok: true, data: safeEntry };666      }667      case "COPY": {668        // AUD-002: shape-validate the payload before passing to the clipboard669        // helper. A raw cast lets a malformed message reach the clipboard API670        // with a non-string and throw.671        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {672          text?: unknown;673          label?: unknown;674          alreadyWritten?: unknown;675        };676        if (typeof text !== "string" || typeof label !== "string") {677          return { ok: false, error: "invalid_payload" };678        }679        await copyToClipboard(text, label, Boolean(alreadyWritten));680        return { ok: true };681      }682      case "CHECK_ALL_BREACHES": {683        const allEntries = vault.getEntries();684        const results: Record<string, number> = {};685        for (const entry of allEntries) {686          if (entry.type === "note") continue;687          if (!entry.password) continue;688          results[entry.id] = await vault.checkBreach(entry.password);689          // Small delay — be a good citizen to the HIBP API690          await new Promise((r) => setTimeout(r, 200));691        }692        // Persist any non-zero counts back to entries693        for (const [id, count] of Object.entries(results)) {694          const entry = vault.getEntryById(id);695          if (entry && (entry.breach ?? 0) !== count) {696            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });697          }698        }699        return { ok: true, data: results };700      }701      case "GET_SETTINGS":702        return { ok: true, data: await vault.ensureSettingsLoaded() };703      case "UPDATE_SETTINGS": {704        const patch = msg.payload;705        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {706          return { ok: false, error: "invalid_payload" };707        }708        await vault.updateSettings(patch as vault.VaultSettings);709        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {710          await setupAutoLock();711          if (vault.isUnlocked()) touchAutoLock();712        }713        return { ok: true };714      }715      case "GET_PENDING_PASSKEY":716        return { ok: true, data: await getPendingPasskeyRequest() };717      case "APPROVE_PASSKEY": {718        const { requestId } = msg.payload as { requestId: number };719        await resolvePendingPasskeyRequest(requestId, true);720        return { ok: true };721      }722      case "DENY_PASSKEY": {723        const { requestId } = msg.payload as { requestId: number };724        await resolvePendingPasskeyRequest(requestId, false);725        return { ok: true };726      }727      case "GET_PASSKEY_PROVIDER_STATE":728        return { ok: true, data: await getPasskeyProviderState() };729      case "SET_PASSKEY_PROVIDER_ENABLED": {730        const { enabled } = msg.payload as { enabled: boolean };731        // Disabling is always free; gating fires only when a free user is732        // trying to turn passkey interception on.733        if (enabled) {734          const gate = await requirePro("passkeys");735          if (!gate.allowed) return { ok: false, error: "pro_required" };736        }737        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };738      }739      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS740      // endpoint. Intentional product behavior — users configure their own741      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private742      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-743      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to744      // users that the entry title leaves the device when the canary fires.745      case "FIRE_CANARY_PING": {746        // Canary alert fires unconditionally for any entry with canary: true.747        // The Pro gate only governs creation/flagging of canary entries; once748        // an entry is flagged, the alert path is a security property and must749        // never be license-gated.750        const { webhookUrl, entryTitle, trigger } = msg.payload as {751          webhookUrl: string;752          entryTitle: string;753          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";754        };755        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {756          return { ok: false, error: "invalid_webhook_url" };757        }758        const body = JSON.stringify({759          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",760          entry: entryTitle,761          trigger,762          timestamp: new Date().toISOString(),763          source: "peach-extension",764        });765        if (trigger === "test") {766          // Permitted outbound fetch: user-configured canary alert endpoint767          // (validated by isAllowedCanaryWebhookUrl above). This is the768          // only non-HIBP outbound call in the extension — see769          // Projects.md §3.7. Test pings are awaited so the UI can show770          // success/failure.771          try {772            const res = await fetch(webhookUrl, {773              method: "POST",774              headers: { "Content-Type": "application/json" },775              body,776            });777            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };778          } catch (err) {779            return { ok: false, error: err instanceof Error ? err.message : "network_error" };780          }781        }782        // Non-test triggers are fire-and-forget783        fetch(webhookUrl, {784          method: "POST",785          headers: { "Content-Type": "application/json" },786          body,787        }).catch(() => {});788        return { ok: true };789      }790      case "ACTIVATE_LICENSE": {791        const { key } = msg.payload as { key: string };792        const licenseInfo = await activateLicense(key);793        return { ok: true, data: licenseInfo };794      }795      case "GET_LICENSE": {796        const licenseInfo = await getLicenseInfo();797        return { ok: true, data: licenseInfo };798      }799      case "GET_LICENSE_KEY": {800        const key = await getLicenseKey();801        return { ok: true, data: key };802      }803      case "DEACTIVATE_LICENSE": {804        await deactivateLicense();805        return { ok: true };806      }807      case "SHOULD_PLAY_CELEBRATION": {808        const should = await shouldPlayCelebration();809        return { ok: true, data: should };810      }811      case "MARK_CELEBRATION_PLAYED": {812        await markCelebrationPlayed();813        return { ok: true };814      }815      case "GET_CODEX_VAULT_DATA": {816        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the817        // popup navigates to the License section without further coordination.818        const gate = await requirePro("codex");819        if (!gate.allowed) return { ok: false, error: "pro_required" };820        return await handleGetCodexVaultData();821      }822      case "ESTIMATE_CODEX_PAGES": {823        const gate = await requirePro("codex");824        if (!gate.allowed) return { ok: false, error: "pro_required" };825        return await handleEstimateCodexPages();826      }827      case "RESTORE_FROM_CODEX": {828        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still829        // be able to restore a vault that was printed by a Pro user.830        // DO NOT add a Pro gate here.831        const payload = msg.payload as CodexRestorePayload;832        return await handleRestoreFromCodex(payload);833      }834      case "OPEN_PRO_GATE": {835        // Content script requests: open popup and navigate to License section.836        const { feature } = (msg.payload ?? {}) as { feature?: string };837        if (chrome.storage.session) {838          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });839        }840        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }841        return { ok: true };842      }843      case "OPEN_POPUP": {844        // Content script asks to open the trusted extension popup — used by the845        // inline locked bubble so the master password is entered in the popup,846        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a847        // user gesture + Chrome 127+/Firefox; on failure the user clicks the848        // toolbar icon. The badge already signals Peach needs attention.849        //850        // Set a session flag so the popup knows it was opened for inline unlock851        // and should close itself once the vault is unlocked (returning the user852        // to the inline autofill selector on the page).853        if (chrome.storage.session) {854          await chrome.storage.session.set({ peach_inline_unlock: true });855        }856        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }857        return { ok: true };858      }859      case "GET_IDENTITIES": {860        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };861        return { ok: true, data: vault.getIdentities() };862      }863      case "TOUCH_AUTO_LOCK": {864        // touchAutoLock() is already called by shouldRefreshAutoLock above;865        // this case just gives the popup a typed message to keep the session alive.866        return { ok: true };867      }868      case "GET_ADVANCED_HEALTH_REPORT": {869        const gate = await requirePro("advanced_health");870        if (!gate.allowed) return { ok: false, error: "pro_required" };871        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };872        const report = await buildAdvancedHealthReport(vault.getEntries());873        return { ok: true, data: report };874      }875      case "IS_DURESS_ENABLED": {876        const enabled = await vault.isDuressEnabled();877        return { ok: true, data: enabled };878      }879      case "SETUP_DURESS": {880        // Single enforcement point for the Duress Vault Pro gate. Free users881        // who somehow reach this handler are rejected here; the popup also882        // pre-checks isPro() to avoid showing the setup form to free users,883        // but server-side is the actual security boundary.884        const gate = await requirePro("duress_vault");885        if (!gate.allowed) return { ok: false, error: "pro_required" };886        // MV3 service workers restart after inactivity, losing the in-memory887        // derived key. Detect this before calling setupDuress so the popup888        // can show a meaningful prompt to re-lock and re-unlock.889        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };890        const { duressPassword } = msg.payload as { duressPassword: string };891        await vault.setupDuress(duressPassword);892        return { ok: true };893      }894      case "DISABLE_DURESS": {895        await vault.disableDuress();896        return { ok: true };897      }898      case "VERIFY_MAIN_PASSWORD": {899        const { password } = msg.payload as { password: string };900        const ok = await vault.verifyMainPassword(password);901        return { ok: true, data: ok };902      }903      case "CHANGE_PASSWORD": {904        const { currentPassword, newPassword } = msg.payload as {905          currentPassword: string;906          newPassword: string;907        };908        const changed = await vault.changePassword(currentPassword, newPassword);909        return changed910          ? { ok: true }911          : { ok: false, error: "incorrect_current_password" };912      }913      case "GET_SITE_PASSWORD_POLICY": {914        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });915        if (!tab?.id) return { ok: true, data: null };916        try {917          const response = await chrome.tabs.sendMessage(tab.id, {918            type: "GET_SITE_PASSWORD_POLICY",919          });920          return (response as MessageResponse) ?? { ok: true, data: null };921        } catch {922          return { ok: true, data: null };923        }924      }925      case "RECORD_MANUAL_SUMMON": {926        const { domain } = msg.payload as { domain: string };927        const settings = vault.getSettings();928        const existing = settings.manualSummonDomains?.[domain];929        const now = Date.now();930        await vault.updateSettings({931          manualSummonDomains: {932            ...settings.manualSummonDomains,933            [domain]: {934              firstSummonedAt: existing?.firstSummonedAt ?? now,935              summonCount: (existing?.summonCount ?? 0) + 1,936              lastSummonedAt: now,937            },938          },939        });940        return { ok: true };941      }942      case "DECLINE_CARD_SAVE": {943        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };944        await vault.declineCardSaveOffer(last4, expMonth, expYear);945        return { ok: true };946      }947      case "IS_CARD_DECLINED": {948        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };949        const declined = await vault.isCardDeclined(last4, expMonth, expYear);950        return { ok: true, data: declined };951      }952      case "INITIATE_FIREFOX_PASSKEY_CREATE": {953        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {954          rpId?: string;955          rpName?: string;956          userName?: string;957          userDisplayName?: string;958        };959        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };960        return await initiateFirefoxPasskeyCreate({961          rpId,962          rpName: rpName ?? rpId,963          userName,964          userDisplayName,965        });966      }967968      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {969        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;970        if (!payload) return { ok: false, error: "missing_payload" };971        return await completeFirefoxPasskeyCreate(payload);972      }973974      case "PASSKEY_OFFER_DECLINE": {975        const { domain } = (msg.payload ?? {}) as { domain?: string };976        if (!domain) return { ok: false, error: "domain_required" };977        await recordPasskeyOfferDecline(domain);978        return { ok: true };979      }980981      case "GET_PASSKEY_OFFER_DECLINED": {982        const { domain } = (msg.payload ?? {}) as { domain?: string };983        if (!domain) return { ok: false, error: "domain_required" };984        return { ok: true, data: await isPasskeyOfferDeclined(domain) };985      }986987      case "PASSKEY_HAS_CREDENTIALS": {988        const payload = msg.payload as {989          rpId?: string;990          allowCredentials?: Array<{ id: string; type?: string }>;991        } | undefined;992        if (!payload?.rpId) return { ok: false, error: "rpid_required" };993        return await handlePasskeyHasCredentials({994          rpId: payload.rpId,995          allowCredentials: payload.allowCredentials ?? [],996        }, attestedSenderOrigin(sender));997      }998999      case "PASSKEY_CREATE": {1000        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1001        if (!payload?.rpId || !payload?.userName) {1002          return { ok: false, error: "rpid_and_username_required" };1003        }1004        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1005      }10061007      case "PASSKEY_GET": {1008        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1009        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1010        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1011      }10121013      case "PASSKEY_AUTH_RESPONSE": {1014        const { requestId, approved } = (msg.payload ?? {}) as {1015          requestId?: string | number;1016          approved?: boolean;1017        };1018        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1019          return { ok: false, error: 'requestId and approved required' };1020        }1021        await resolvePendingPasskeyRequest(Number(requestId), approved);1022        return { ok: true };1023      }10241025      case "GET_PASSKEY_FOR_DOMAIN": {1026        const { domain } = (msg.payload ?? {}) as { domain?: string };1027        if (!domain) return { ok: false, error: "domain_required" };1028        // Scope to the caller's own origin: a page may only ask about passkeys1029        // for a domain it actually owns, so an arbitrary page cannot enumerate1030        // which sites the user holds passkeys for or read the username (audit MEDIUM).1031        const origin = attestedSenderOrigin(sender);1032        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1033        if (!vault.isUnlocked()) return { ok: true, data: null };1034        const match = vault1035          .getEntries()1036          .find((entry) => entry.passkey?.rpId === domain);1037        if (!match || !match.passkey) return { ok: true, data: null };1038        // Slim shape — only the fields State 11 needs. Never expose private1039        // key material, even though this is locked behind isUnlocked.1040        return {1041          ok: true,1042          data: {1043            rpId: match.passkey.rpId,1044            userName: match.passkey.userName,1045            browser: match.passkey.browser,1046          },1047        };1048      }10491050      case "DESTROY_VAULT": {1051        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1052        // storage.local.clear() wipes every Peach key (slots, settings, license,1053        // onboarded flag, history, sync state, declined cards, recall, etc.);1054        // session.clear() wipes pending passkey requests + pro-notice queues.1055        // Caller (Panic.tsx) handles UI navigation back to onboarding.1056        //1057        // The Pro license is the one thing that must survive: the user paid for1058        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1059        // Capture it before the clear and restore it after. peach_pro_celebrated1060        // rides along so the Pro celebration doesn't replay on the next unlock.1061        const preserved = await chrome.storage.local.get([1062          "peach_license",1063          "peach_pro_celebrated",1064        ]);1065        vault.lock();1066        await storageClear();1067        await vault.clearVaultHistory();1068        const toRestore: Record<string, unknown> = {};1069        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1070        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1071        if (Object.keys(toRestore).length > 0) {1072          await chrome.storage.local.set(toRestore);1073        }1074        if (chrome.storage.session) {1075          await chrome.storage.session.clear();1076        }1077        return { ok: true };1078      }10791080      case "SUBMIT_FEEDBACK": {1081        const { category, message, version, browser } = msg.payload as {1082          category: string;1083          message: string;1084          version: string;1085          browser: string;1086        };1087        if (!message.trim()) return { ok: false, error: "message_empty" };1088        if (!FEEDBACK_ENDPOINT) return { ok: true };1089        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1090          return { ok: false, error: "invalid_feedback_endpoint" };1091        }1092        try {1093          const res = await fetch(FEEDBACK_ENDPOINT, {1094            method: "POST",1095            headers: { "Content-Type": "application/json" },1096            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1097          });1098          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1099        } catch (err) {1100          return { ok: false, error: err instanceof Error ? err.message : "network_error" };1101        }1102      }1103      // Android-only: biometric unlock with pre-derived key.1104      case "UNLOCK_WITH_KEY": {1105        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1106        if (!isNativePlatform()) {1107          return { ok: false, error: "desktop_only_uses_password" };1108        }1109        try {1110          const result = await vault.unlockWithKey(masterKeyHex);1111          if (result.ok) {1112            onVaultUnlocked();1113            await publishInMemoryVault(result.entries);1114          }1115          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1116        } catch {1117          return { ok: false, error: "invalid_key" };1118        }1119      }1120      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1121      case "GET_DERIVED_KEY": {1122        if (!isNativePlatform()) {1123          return { ok: false, error: "android_only" };1124        }1125        if (!vault.isUnlocked()) {1126          return { ok: false, error: "vault_locked" };1127        }1128        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1129      }1130      case "GET_IDENTITY_SUGGESTIONS": {1131        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1132        const entries = vault.getEntries();1133        const suggestions = buildIdentitySuggestions(entries);1134        return { ok: true, data: { suggestions } };1135      }1136      case "POPULATE_INLINE_VAULT": {1137        if (!isNativePlatform()) return { ok: false };1138        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1139        const entries = vault.getEntries();1140        await publishInMemoryVault(entries);1141        return { ok: true };1142      }1143      case "ML_INIT":1144        return { ok: true };11451146      case "ML_PREDICT_BATCH": {1147        // AUD-002: shape-validate before forwarding to the ML helper.1148        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1149        if (!Array.isArray(featuresArray)) {1150          return { ok: false, error: "invalid_payload" };1151        }1152        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1153      }11541155      // ── Chirp Sync (v3) ───────────────────────────────────────────────1156      // Returns the public-facing local identity needed by the popup to1157      // drive Phase-1 audio pairing. The private long-term key never1158      // leaves the background.1159      case "CHIRP_GET_LOCAL_IDENTITY": {1160        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1161        const proCheck = await requirePro("sync");1162        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1163        // Identity derives from the stable root key, not the password-derived1164        // key, so pairing survives a master-password change (SEV-2-B).1165        const masterKeyHex = vault.getRootKeyHex();1166        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1167        const masterKey = unhexBytes(masterKeyHex);1168        try {1169          const identity = await buildLocalIdentity(masterKey);1170          return { ok: true, data: identity };1171        } finally {1172          masterKey.fill(0);1173        }1174      }11751176      case "CHIRP_COMPLETE_PAIRING": {1177        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1178        const proCheck = await requirePro("sync");1179        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1180        const paired = (msg.payload as { paired?: unknown })?.paired;1181        if (typeof paired !== "object" || paired === null) {1182          return { ok: false, error: "invalid_payload" };1183        }1184        const candidate = paired as Record<string, unknown>;1185        if (1186          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1187          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1188          typeof candidate.deviceType !== "string" ||1189          typeof candidate.longTermPublicKeyHex !== "string" ||1190          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1191          (1192            candidate.signingPublicKeyHex !== undefined &&1193            (1194              typeof candidate.signingPublicKeyHex !== "string" ||1195              !/^[0-9a-f]{64}$/.test(candidate.signingPublicKeyHex)1196            )1197          ) ||1198          typeof candidate.pairedAt !== "number"1199        ) {1200          return { ok: false, error: "invalid_paired_device" };1201        }1202        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1203        return { ok: true };1204      }12051206      case "CHIRP_LIST_PAIRED_DEVICES": {1207        const devices = await listPairedDevicesV3();1208        return { ok: true, data: { devices } };1209      }12101211      case "CHIRP_UNPAIR_DEVICE": {1212        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1213        if (typeof deviceId !== "string" || !deviceId) {1214          return { ok: false, error: "invalid_payload" };1215        }1216        await removePairedDeviceByIdV3(deviceId);1217        return { ok: true };1218      }12191220      case "CHIRP_RENAME_LOCAL_DEVICE": {1221        const { name } = (msg.payload ?? {}) as { name?: string };1222        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1223        await setDeviceNameV3(name);1224        return { ok: true };1225      }12261227      case "TRIGGER_SYNC": {1228        const payload = (msg.payload ?? {}) as {1229          reason?: "vault_change" | "foreground" | "manual" | "mdns";1230          force?: boolean;1231          deviceId?: string;1232          discoveredIp?: string;1233          discoveredPort?: number;1234        };1235        const reason = payload.reason ?? "foreground";12361237        // mDNS discovery delivers a fresh (ip, port) resolved by the native1238        // side. Update the cached address before the sync runner tries to1239        // connect — avoids a subnet probe on the very next round.1240        if (1241          reason === "mdns" &&1242          typeof payload.deviceId === "string" &&1243          typeof payload.discoveredIp === "string"1244        ) {1245          const { findPairedDeviceById, setLastKnownIp } = await import("./paired-devices");1246          const device = await findPairedDeviceById(payload.deviceId);1247          if (device?.longTermPublicKeyHex) {1248            await setLastKnownIp(device.longTermPublicKeyHex, payload.discoveredIp).catch(() => undefined);1249          }1250        }12511252        const { triggerSyncIfReachable } = await import("./sync-trigger");1253        void triggerSyncIfReachable({ reason, force: payload.force === true });1254        return { ok: true };1255      }12561257      case "GET_SYNC_STATE": {1258        const { getSyncState } = await import("./sync-trigger");1259        return { ok: true, data: getSyncState() };1260      }12611262      default:1263        return { ok: false, error: "unknown_message_type" };1264    }1265  } catch (err) {1266    return {1267      ok: false,1268      error: err instanceof Error ? err.message : "operation_failed",1269    };1270  }1271}12721273// --- Mobile platform helpers ---12741275// Android: populates the in-memory vault used by PeachAutofillService.1276async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1277  const plugin = nativePlugin<{1278    setEntries?: (args: {1279      entries: Array<{1280        id: string;1281        title: string;1282        username: string;1283        email: string;1284        password: string;1285        url: string;1286        totp: string;1287        additionalUrls: string[];1288      }>;1289    }) => Promise<void>;1290  }>("InMemoryVaultPlugin");1291  if (!plugin?.setEntries) return;1292  await plugin.setEntries({1293    entries: entries.map((e) => ({1294      id: e.id,1295      title: e.title ?? "",1296      username: e.username ?? "",1297      email: (e as VaultEntry & { email?: string }).email ?? "",1298      password: e.password ?? "",1299      url: e.url ?? "",1300      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1301      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1302    })),1303  });1304}13051306// Android: clear the autofill in-memory store on lock.1307async function clearInMemoryVault(): Promise<void> {1308  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1309  if (!plugin?.clearEntries) return;1310  await plugin.clearEntries();1311}13121313// Returns username use-counts from the vault, sorted by frequency. Each row1314// also carries the entry's email so the popup can suggest the email/username1315// pair the user has actually used together.1316function buildIdentitySuggestions(1317  entries: VaultEntry[],1318): Array<{ email: string; username: string; count: number }> {1319  const usernameCounts = new Map<string, number>();1320  const usernameEmail = new Map<string, string>();1321  for (const entry of entries) {1322    const username = entry.username ?? "";1323    const email = (entry as VaultEntry & { email?: string }).email ?? "";1324    if (!username && !email) continue;1325    const key = username || email;1326    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1327    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1328  }1329  return Array.from(usernameCounts.entries())1330    .sort((a, b) => b[1] - a[1])1331    .map(([username, count]) => ({1332      email: usernameEmail.get(username) ?? "",1333      username,1334      count,1335    }));1336}13371338/** Notify all content scripts that the vault just became available. */1339function broadcastToContentScripts(message: { type: string }): void {1340  if (!chrome.tabs?.query) return;1341  chrome.tabs.query({}, (tabs) => {1342    for (const tab of tabs) {1343      if (tab.id !== undefined) {1344        chrome.tabs.sendMessage(tab.id, message).catch(() => {1345          // Tab may not have a content script — silently ignore1346        });1347      }1348    }1349  });1350}13511352function shouldRefreshAutoLock(type: MessageType): boolean {1353  return (1354    type !== "HAS_VAULT" &&1355    type !== "IS_UNLOCKED" &&1356    type !== "GET_VAULT_STATUS" &&1357    type !== "LOCK" &&1358    type !== "UPDATE_SETTINGS" &&1359    type !== "GET_PENDING_PASSKEY" &&1360    type !== "GET_PASSKEY_PROVIDER_STATE" &&1361    type !== "DECLINE_CARD_SAVE" &&1362    type !== "IS_CARD_DECLINED" &&1363    type !== "SUBMIT_FEEDBACK"1364  );1365}13661367function isAllowedCanaryWebhookUrl(value: string): boolean {1368  try {1369    const url = new URL(value);1370    if (url.protocol !== "https:") return false;13711372    const hostname = url.hostname.toLowerCase();1373    if (1374      hostname === "localhost" ||1375      hostname.endsWith(".localhost") ||1376      isPrivateIpv4(hostname) ||1377      isPrivateIpv6(hostname)1378    ) {1379      return false;1380    }13811382    return true;1383  } catch {1384    return false;1385  }1386}13871388function isPrivateIpv4(hostname: string): boolean {1389  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1390    return true;1391  }13921393  const octets = hostname.split(".").map((part) => Number(part));1394  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1395    return false;1396  }13971398  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1399}14001401function isPrivateIpv6(hostname: string): boolean {1402  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1403  return (1404    normalized === "::1" ||1405    normalized.startsWith("fc") ||1406    normalized.startsWith("fd") ||1407    normalized.startsWith("fe80:")1408  );1409}