messages.ts

57.2 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard } 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        return { ok: true, data: entry };369      }370      case "BATCH_ADD_ENTRIES": {371        const payload = msg.payload as { entries?: unknown } | null | undefined;372        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {373          return { ok: false, error: "invalid_payload" };374        }375        if (!Array.isArray(payload.entries)) {376          return { ok: false, error: "invalid_payload" };377        }378        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);379        return { ok: true, data: added };380      }381      case "RESTORE_ENTRIES": {382        const payload = msg.payload as383          | { entries?: unknown; mode?: unknown; settings?: unknown }384          | null385          | undefined;386        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {387          return { ok: false, error: "invalid_payload" };388        }389        if (!Array.isArray(payload.entries)) {390          return { ok: false, error: "invalid_payload" };391        }392        if (payload.mode !== "replace" && payload.mode !== "merge") {393          return { ok: false, error: "invalid_payload" };394        }395        const summary = await vault.restoreEntries(396          payload.entries as Parameters<typeof vault.restoreEntries>[0],397          payload.mode398        );399        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {400          await vault.updateSettings(payload.settings as vault.VaultSettings);401        }402        return { ok: true, data: summary };403      }404      case "CLEAR_VAULT_ENTRIES": {405        await vault.clearVaultEntries("REPLACE_ALL");406        return { ok: true };407      }408      case "GET_VAULT_HISTORY": {409        const snapshots = await vault.getVaultHistory();410        return { ok: true, data: snapshots };411      }412      case "RESTORE_VAULT_SNAPSHOT": {413        const { snapshotId } = msg.payload as { snapshotId: string };414        const result = await vault.restoreVaultSnapshot(snapshotId);415        if (!result.ok) return { ok: false, error: result.error };416        broadcastToContentScripts({ type: "VAULT_LOCKED" });417        return { ok: true };418      }419      case "COUNT_DUPLICATES": {420        return { ok: true, data: vault.countDuplicates() };421      }422      case "DEDUPLICATE_ENTRIES": {423        const removed = await vault.deduplicateEntries();424        return { ok: true, data: removed };425      }426      case "UPDATE_ENTRY": {427        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;428        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {429          return { ok: false, error: "invalid_payload" };430        }431        const { id, patch } = payload;432        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {433          return { ok: false, error: "invalid_payload" };434        }435        // Single enforcement point for the Canary Entries Pro gate. Only436        // gates the transition into a canary entry — clearing/disabling a437        // canary (`canary: undefined`) is always allowed, so existing438        // canary entries remain manageable.439        const incomingCanary = (patch as { canary?: unknown }).canary;440        if (incomingCanary && typeof incomingCanary === "object") {441          const existing = vault.getEntryById(id);442          if (!existing?.canary) {443            const gate = await requirePro("canary_entry");444            if (!gate.allowed) return { ok: false, error: "pro_required" };445          }446        }447        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);448        return { ok: true };449      }450      case "ADD_ADDITIONAL_URL": {451        const { id, url } = msg.payload as { id: string; url: string };452        const trimmed = typeof url === "string" ? url.trim() : "";453        if (!trimmed) return { ok: false, error: "url_required" };454        const existing = vault.getEntryById(id);455        if (!existing) return { ok: false, error: "entry_not_found" };456        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };457        const merged = [...(existing.additionalUrls ?? []), trimmed];458        await vault.updateEntry(id, { additionalUrls: merged });459        return { ok: true };460      }461      case "DELETE_ENTRY": {462        const { id } = msg.payload as { id: string };463        await vault.deleteEntry(id);464        return { ok: true };465      }466      case "GET_DELETED_ENTRIES":467        return { ok: true, data: vault.getDeletedEntries() };468      case "RESTORE_ENTRY": {469        const { id } = msg.payload as { id: string };470        await vault.restoreEntry(id);471        return { ok: true };472      }473      case "PURGE_ENTRY": {474        const { id } = msg.payload as { id: string };475        await vault.purgeEntry(id);476        return { ok: true };477      }478      case "PURGE_EXPIRED_TRASH": {479        const { retentionMs } = msg.payload as { retentionMs: number };480        const purged = await vault.purgeExpiredTrash(retentionMs);481        return { ok: true, data: purged };482      }483      case "SAVE_NOTE": {484        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };485        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };486        const now = Date.now();487        if (id) {488          const existing = vault.getEntryById(id);489          if (!existing) return { ok: false, error: "not_found" };490          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });491          return { ok: true, data: vault.getEntryById(id) };492        } else {493          const entry = await vault.addEntry({494            type: "note",495            title: title || "Untitled",496            notes: body,497            createdAt: now,498            modifiedAt: now,499          } as any);500          return { ok: true, data: entry };501        }502      }503      case "DELETE_NOTE": {504        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };505        const { id } = msg.payload as { id: string };506        await vault.deleteEntry(id);507        return { ok: true };508      }509      case "GET_NOTES": {510        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };511        const notes = vault.getEntries().filter(512          (e) => e.type === "note" && !e.deletedAt513        );514        return { ok: true, data: notes } as MessageResponse;515      }516      case "SEARCH_VAULT": {517        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };518        // AUD-002: shape-validate the payload before calling string methods.519        // A raw cast lets a malformed message crash the handler with TypeError.520        const { query } = (msg.payload ?? {}) as { query?: unknown };521        if (typeof query !== "string") {522          return { ok: false, error: "invalid_payload" };523        }524        const q = query.toLowerCase();525        const searchResults = vault.getEntries().filter(526          (e) =>527            !e.deletedAt &&528            (e.title.toLowerCase().includes(q) ||529              e.notes?.toLowerCase().includes(q) ||530              e.username?.toLowerCase().includes(q))531        );532        return { ok: true, data: searchResults } as MessageResponse;533      }534      case "AUTOFILL_QUERY": {535        if (!vault.isUnlocked()) {536          return { ok: false, error: "vault_locked" };537        }538        const { domain, includeAll, kind } = msg.payload as {539          domain: string;540          includeAll?: boolean;541          kind?: "login" | "card" | "totp";542        };543        // kind="card": return saved cards as compact summaries for the544        // inline card silver platter. Cards are not domain-scoped — every545        // saved card is a candidate on every checkout page — so domain is546        // ignored when kind === "card".547        if (kind === "card") {548          const cards = vault.getEntries().filter((e) => e.type === "card");549          return {550            ok: true,551            data: cards.map((e) => ({552              id: e.id,553              title: e.cardNickname || e.title,554              cardholderName: e.cardholderName,555              last4: e.last4,556              expMonth: e.expMonth,557              expYear: e.expYear,558              network: e.network,559            })),560          };561        }562        if (kind === "totp") {563          const matches = (564            includeAll565              ? vault.getEntries().filter((entry) => entry.type !== "note" && entry.type !== "card")566              : vault.queryDomain(domain)567          ).filter((entry) => !isPasskeyOnly(entry) && Boolean(entry.totp));568          return {569            ok: true,570            data: matches.map((e) => ({571              id: e.id,572              title: e.title,573              username: e.username,574              email: e.email,575              url: e.url,576              hasTotp: true,577            })),578          };579        }580        // The inline selector fills username+password into a form. Passkey-581        // only entries have no password to fill; sign-in for those goes582        // through the WebAuthn path instead. Filter them out everywhere so583        // the user doesn't see four "GitHub" rows that mostly do nothing.584        // Notes and cards never belonged here either.585        const matches = (586          includeAll587            ? vault588                .getEntries()589                .filter((entry) => entry.type !== "note" && entry.type !== "card")590            : vault.queryDomain(domain)591        ).filter((entry) => !isPasskeyOnly(entry));592        return {593          ok: true,594          data: matches.map((e) =>595            includeAll596              ? {597                  id: e.id,598                  title: e.title,599                  // username/email/url shipped so the inline popup's search600                  // affordance can match on them, not just titles. No secrets601                  // cross the boundary — same shape as the domain-matched602                  // response below minus hasTotp (which the search list603                  // doesn't surface).604                  username: e.username,605                  email: e.email,606                  url: e.url,607                  hasPasskey: e.passkey !== undefined,608                }609              : {610                  id: e.id,611                  title: e.title,612                  username: e.username,613                  email: e.email,614                  url: e.url,615                  hasTotp: Boolean(e.totp),616                  hasPasskey: e.passkey !== undefined,617                }618          ),619        };620      }621      case "GET_ENTRY_FOR_FILL": {622        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };623        const { id } = msg.payload as { id: string };624        const entry = vault.getEntryById(id);625        if (!entry) return { ok: false, error: "entry_not_found" };626        // Passkey-only entries (passkey credential, no password) cannot be627        // filled into a form — sign-in goes through the WebAuthn path. A628        // login that ALSO has a passkey is still fillable for its password.629        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };630        // Strip the passkey credential AND the raw base32 TOTP seed from the631        // response. Content scripts never need either: the private key is the632        // authenticator's, and handing over the TOTP seed would let a633        // compromised content script mint valid codes indefinitely (SEV-3-C).634        // Generate the *current* 6-digit code here in the background and send635        // only that, plus the seconds left so the UI can render a countdown.636        // Also drop passwordHistory: filling needs only the *current* password.637        // Handing every past password to a content script during passive638        // autofill on an arbitrary page would widen the blast radius of a639        // compromised page far beyond the one credential being filled.640        const { passkey: _strippedPasskey, totp: seed, passwordHistory: _ph, ...safeEntry } = entry;641        let totpCode: string | undefined;642        let totpRemaining: number | undefined;643        if (seed) {644          try {645            const generated = generateTOTP(seed);646            totpCode = generated.code;647            totpRemaining = generated.remaining;648          } catch {649            totpCode = undefined;650          }651        }652        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };653      }654      // Trusted full-entry fetch for Peach's own inline-popup surfaces that655      // genuinely need the raw TOTP seed: the edit form (which re-saves the656      // seed and would otherwise wipe it) and nothing else. Unlike657      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside658      // the inline popup, never during passive autofill on an arbitrary page.659      // The passkey credential is still stripped — the edit form never touches it.660      case "GET_ENTRY_FOR_EDIT": {661        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };662        const { id } = msg.payload as { id: string };663        const entry = vault.getEntryById(id);664        if (!entry) return { ok: false, error: "entry_not_found" };665        const { passkey: _passkey, ...safeEntry } = entry;666        return { ok: true, data: safeEntry };667      }668      case "COPY": {669        // AUD-002: shape-validate the payload before passing to the clipboard670        // helper. A raw cast lets a malformed message reach the clipboard API671        // with a non-string and throw.672        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {673          text?: unknown;674          label?: unknown;675          alreadyWritten?: unknown;676        };677        if (typeof text !== "string" || typeof label !== "string") {678          return { ok: false, error: "invalid_payload" };679        }680        await copyToClipboard(text, label, Boolean(alreadyWritten));681        return { ok: true };682      }683      case "CHECK_ALL_BREACHES": {684        const allEntries = vault.getEntries();685        const results: Record<string, number> = {};686        for (const entry of allEntries) {687          if (entry.type === "note") continue;688          if (!entry.password) continue;689          results[entry.id] = await vault.checkBreach(entry.password);690          // Small delay — be a good citizen to the HIBP API691          await new Promise((r) => setTimeout(r, 200));692        }693        // Persist any non-zero counts back to entries694        for (const [id, count] of Object.entries(results)) {695          const entry = vault.getEntryById(id);696          if (entry && (entry.breach ?? 0) !== count) {697            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });698          }699        }700        return { ok: true, data: results };701      }702      case "GET_SETTINGS":703        return { ok: true, data: await vault.ensureSettingsLoaded() };704      case "UPDATE_SETTINGS": {705        const patch = msg.payload;706        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {707          return { ok: false, error: "invalid_payload" };708        }709        await vault.updateSettings(patch as vault.VaultSettings);710        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {711          await setupAutoLock();712          if (vault.isUnlocked()) touchAutoLock();713        }714        return { ok: true };715      }716      case "GET_PENDING_PASSKEY":717        return { ok: true, data: await getPendingPasskeyRequest() };718      case "APPROVE_PASSKEY": {719        const { requestId } = msg.payload as { requestId: number };720        await resolvePendingPasskeyRequest(requestId, true);721        return { ok: true };722      }723      case "DENY_PASSKEY": {724        const { requestId } = msg.payload as { requestId: number };725        await resolvePendingPasskeyRequest(requestId, false);726        return { ok: true };727      }728      case "GET_PASSKEY_PROVIDER_STATE":729        return { ok: true, data: await getPasskeyProviderState() };730      case "SET_PASSKEY_PROVIDER_ENABLED": {731        const { enabled } = msg.payload as { enabled: boolean };732        // Disabling is always free; gating fires only when a free user is733        // trying to turn passkey interception on.734        if (enabled) {735          const gate = await requirePro("passkeys");736          if (!gate.allowed) return { ok: false, error: "pro_required" };737        }738        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };739      }740      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS741      // endpoint. Intentional product behavior — users configure their own742      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private743      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-744      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to745      // users that the entry title leaves the device when the canary fires.746      case "FIRE_CANARY_PING": {747        // Canary alert fires unconditionally for any entry with canary: true.748        // The Pro gate only governs creation/flagging of canary entries; once749        // an entry is flagged, the alert path is a security property and must750        // never be license-gated.751        const { webhookUrl, entryTitle, trigger } = msg.payload as {752          webhookUrl: string;753          entryTitle: string;754          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";755        };756        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {757          return { ok: false, error: "invalid_webhook_url" };758        }759        const body = JSON.stringify({760          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",761          entry: entryTitle,762          trigger,763          timestamp: new Date().toISOString(),764          source: "peach-extension",765        });766        if (trigger === "test") {767          // Permitted outbound fetch: user-configured canary alert endpoint768          // (validated by isAllowedCanaryWebhookUrl above). This is the769          // only non-HIBP outbound call in the extension — see770          // Projects.md §3.7. Test pings are awaited so the UI can show771          // success/failure.772          try {773            const res = await fetch(webhookUrl, {774              method: "POST",775              headers: { "Content-Type": "application/json" },776              body,777            });778            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };779          } catch (err) {780            return { ok: false, error: err instanceof Error ? err.message : "network_error" };781          }782        }783        // Non-test triggers are fire-and-forget784        fetch(webhookUrl, {785          method: "POST",786          headers: { "Content-Type": "application/json" },787          body,788        }).catch(() => {});789        return { ok: true };790      }791      case "ACTIVATE_LICENSE": {792        const { key } = msg.payload as { key: string };793        const licenseInfo = await activateLicense(key);794        return { ok: true, data: licenseInfo };795      }796      case "GET_LICENSE": {797        const licenseInfo = await getLicenseInfo();798        return { ok: true, data: licenseInfo };799      }800      case "GET_LICENSE_KEY": {801        const key = await getLicenseKey();802        return { ok: true, data: key };803      }804      case "DEACTIVATE_LICENSE": {805        await deactivateLicense();806        return { ok: true };807      }808      case "SHOULD_PLAY_CELEBRATION": {809        const should = await shouldPlayCelebration();810        return { ok: true, data: should };811      }812      case "MARK_CELEBRATION_PLAYED": {813        await markCelebrationPlayed();814        return { ok: true };815      }816      case "GET_CODEX_VAULT_DATA": {817        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the818        // popup navigates to the License section without further coordination.819        const gate = await requirePro("codex");820        if (!gate.allowed) return { ok: false, error: "pro_required" };821        return await handleGetCodexVaultData();822      }823      case "ESTIMATE_CODEX_PAGES": {824        const gate = await requirePro("codex");825        if (!gate.allowed) return { ok: false, error: "pro_required" };826        return await handleEstimateCodexPages();827      }828      case "RESTORE_FROM_CODEX": {829        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still830        // be able to restore a vault that was printed by a Pro user.831        // DO NOT add a Pro gate here.832        const payload = msg.payload as CodexRestorePayload;833        return await handleRestoreFromCodex(payload);834      }835      case "OPEN_PRO_GATE": {836        // Content script requests: open popup and navigate to License section.837        const { feature } = (msg.payload ?? {}) as { feature?: string };838        if (chrome.storage.session) {839          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });840        }841        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }842        return { ok: true };843      }844      case "OPEN_POPUP": {845        // Content script asks to open the trusted extension popup — used by the846        // inline locked bubble so the master password is entered in the popup,847        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a848        // user gesture + Chrome 127+/Firefox; on failure the user clicks the849        // toolbar icon. The badge already signals Peach needs attention.850        //851        // Set a session flag so the popup knows it was opened for inline unlock852        // and should close itself once the vault is unlocked (returning the user853        // to the inline autofill selector on the page).854        if (chrome.storage.session) {855          await chrome.storage.session.set({ peach_inline_unlock: true });856        }857        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }858        return { ok: true };859      }860      case "GET_IDENTITIES": {861        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };862        return { ok: true, data: vault.getIdentities() };863      }864      case "TOUCH_AUTO_LOCK": {865        // touchAutoLock() is already called by shouldRefreshAutoLock above;866        // this case just gives the popup a typed message to keep the session alive.867        return { ok: true };868      }869      case "GET_ADVANCED_HEALTH_REPORT": {870        const gate = await requirePro("advanced_health");871        if (!gate.allowed) return { ok: false, error: "pro_required" };872        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };873        const report = await buildAdvancedHealthReport(vault.getEntries());874        return { ok: true, data: report };875      }876      case "IS_DURESS_ENABLED": {877        const enabled = await vault.isDuressEnabled();878        return { ok: true, data: enabled };879      }880      case "SETUP_DURESS": {881        // Single enforcement point for the Duress Vault Pro gate. Free users882        // who somehow reach this handler are rejected here; the popup also883        // pre-checks isPro() to avoid showing the setup form to free users,884        // but server-side is the actual security boundary.885        const gate = await requirePro("duress_vault");886        if (!gate.allowed) return { ok: false, error: "pro_required" };887        // MV3 service workers restart after inactivity, losing the in-memory888        // derived key. Detect this before calling setupDuress so the popup889        // can show a meaningful prompt to re-lock and re-unlock.890        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };891        const { duressPassword } = msg.payload as { duressPassword: string };892        await vault.setupDuress(duressPassword);893        return { ok: true };894      }895      case "DISABLE_DURESS": {896        await vault.disableDuress();897        return { ok: true };898      }899      case "VERIFY_MAIN_PASSWORD": {900        const { password } = msg.payload as { password: string };901        const ok = await vault.verifyMainPassword(password);902        return { ok: true, data: ok };903      }904      case "CHANGE_PASSWORD": {905        const { currentPassword, newPassword } = msg.payload as {906          currentPassword: string;907          newPassword: string;908        };909        const changed = await vault.changePassword(currentPassword, newPassword);910        return changed911          ? { ok: true }912          : { ok: false, error: "incorrect_current_password" };913      }914      case "GET_SITE_PASSWORD_POLICY": {915        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });916        if (!tab?.id) return { ok: true, data: null };917        try {918          const response = await chrome.tabs.sendMessage(tab.id, {919            type: "GET_SITE_PASSWORD_POLICY",920          });921          return (response as MessageResponse) ?? { ok: true, data: null };922        } catch {923          return { ok: true, data: null };924        }925      }926      case "RECORD_MANUAL_SUMMON": {927        const { domain } = msg.payload as { domain: string };928        const settings = vault.getSettings();929        const existing = settings.manualSummonDomains?.[domain];930        const now = Date.now();931        await vault.updateSettings({932          manualSummonDomains: {933            ...settings.manualSummonDomains,934            [domain]: {935              firstSummonedAt: existing?.firstSummonedAt ?? now,936              summonCount: (existing?.summonCount ?? 0) + 1,937              lastSummonedAt: now,938            },939          },940        });941        return { ok: true };942      }943      case "DECLINE_CARD_SAVE": {944        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };945        await vault.declineCardSaveOffer(last4, expMonth, expYear);946        return { ok: true };947      }948      case "IS_CARD_DECLINED": {949        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };950        const declined = await vault.isCardDeclined(last4, expMonth, expYear);951        return { ok: true, data: declined };952      }953      case "INITIATE_FIREFOX_PASSKEY_CREATE": {954        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {955          rpId?: string;956          rpName?: string;957          userName?: string;958          userDisplayName?: string;959        };960        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };961        return await initiateFirefoxPasskeyCreate({962          rpId,963          rpName: rpName ?? rpId,964          userName,965          userDisplayName,966        });967      }968969      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {970        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;971        if (!payload) return { ok: false, error: "missing_payload" };972        return await completeFirefoxPasskeyCreate(payload);973      }974975      case "PASSKEY_OFFER_DECLINE": {976        const { domain } = (msg.payload ?? {}) as { domain?: string };977        if (!domain) return { ok: false, error: "domain_required" };978        await recordPasskeyOfferDecline(domain);979        return { ok: true };980      }981982      case "GET_PASSKEY_OFFER_DECLINED": {983        const { domain } = (msg.payload ?? {}) as { domain?: string };984        if (!domain) return { ok: false, error: "domain_required" };985        return { ok: true, data: await isPasskeyOfferDeclined(domain) };986      }987988      case "PASSKEY_HAS_CREDENTIALS": {989        const payload = msg.payload as {990          rpId?: string;991          allowCredentials?: Array<{ id: string; type?: string }>;992        } | undefined;993        if (!payload?.rpId) return { ok: false, error: "rpid_required" };994        return await handlePasskeyHasCredentials({995          rpId: payload.rpId,996          allowCredentials: payload.allowCredentials ?? [],997        }, attestedSenderOrigin(sender));998      }9991000      case "PASSKEY_CREATE": {1001        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1002        if (!payload?.rpId || !payload?.userName) {1003          return { ok: false, error: "rpid_and_username_required" };1004        }1005        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1006      }10071008      case "PASSKEY_GET": {1009        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1010        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1011        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1012      }10131014      case "PASSKEY_AUTH_RESPONSE": {1015        const { requestId, approved } = (msg.payload ?? {}) as {1016          requestId?: string | number;1017          approved?: boolean;1018        };1019        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1020          return { ok: false, error: 'requestId and approved required' };1021        }1022        await resolvePendingPasskeyRequest(Number(requestId), approved);1023        return { ok: true };1024      }10251026      case "GET_PASSKEY_FOR_DOMAIN": {1027        const { domain } = (msg.payload ?? {}) as { domain?: string };1028        if (!domain) return { ok: false, error: "domain_required" };1029        // Scope to the caller's own origin: a page may only ask about passkeys1030        // for a domain it actually owns, so an arbitrary page cannot enumerate1031        // which sites the user holds passkeys for or read the username (audit MEDIUM).1032        const origin = attestedSenderOrigin(sender);1033        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1034        if (!vault.isUnlocked()) return { ok: true, data: null };1035        const match = vault1036          .getEntries()1037          .find((entry) => entry.passkey?.rpId === domain);1038        if (!match || !match.passkey) return { ok: true, data: null };1039        // Slim shape — only the fields State 11 needs. Never expose private1040        // key material, even though this is locked behind isUnlocked.1041        return {1042          ok: true,1043          data: {1044            rpId: match.passkey.rpId,1045            userName: match.passkey.userName,1046            browser: match.passkey.browser,1047          },1048        };1049      }10501051      case "DESTROY_VAULT": {1052        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1053        // storage.local.clear() wipes every Peach key (slots, settings, license,1054        // onboarded flag, history, sync state, declined cards, recall, etc.);1055        // session.clear() wipes pending passkey requests + pro-notice queues.1056        // Caller (Panic.tsx) handles UI navigation back to onboarding.1057        //1058        // The Pro license is the one thing that must survive: the user paid for1059        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1060        // Capture it before the clear and restore it after. peach_pro_celebrated1061        // rides along so the Pro celebration doesn't replay on the next unlock.1062        const preserved = await chrome.storage.local.get([1063          "peach_license",1064          "peach_pro_celebrated",1065        ]);1066        vault.lock();1067        await storageClear();1068        await vault.clearVaultHistory();1069        const toRestore: Record<string, unknown> = {};1070        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1071        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1072        if (Object.keys(toRestore).length > 0) {1073          await chrome.storage.local.set(toRestore);1074        }1075        if (chrome.storage.session) {1076          await chrome.storage.session.clear();1077        }1078        return { ok: true };1079      }10801081      case "SUBMIT_FEEDBACK": {1082        const { category, message, version, browser } = msg.payload as {1083          category: string;1084          message: string;1085          version: string;1086          browser: string;1087        };1088        if (!message.trim()) return { ok: false, error: "message_empty" };1089        if (!FEEDBACK_ENDPOINT) return { ok: true };1090        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1091          return { ok: false, error: "invalid_feedback_endpoint" };1092        }1093        try {1094          const res = await fetch(FEEDBACK_ENDPOINT, {1095            method: "POST",1096            headers: { "Content-Type": "application/json" },1097            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1098          });1099          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1100        } catch (err) {1101          return { ok: false, error: err instanceof Error ? err.message : "network_error" };1102        }1103      }1104      // Android-only: biometric unlock with pre-derived key.1105      case "UNLOCK_WITH_KEY": {1106        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1107        if (!isNativePlatform()) {1108          return { ok: false, error: "desktop_only_uses_password" };1109        }1110        try {1111          const result = await vault.unlockWithKey(masterKeyHex);1112          if (result.ok) {1113            onVaultUnlocked();1114            await publishInMemoryVault(result.entries);1115          }1116          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1117        } catch {1118          return { ok: false, error: "invalid_key" };1119        }1120      }1121      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1122      case "GET_DERIVED_KEY": {1123        if (!isNativePlatform()) {1124          return { ok: false, error: "android_only" };1125        }1126        if (!vault.isUnlocked()) {1127          return { ok: false, error: "vault_locked" };1128        }1129        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1130      }1131      case "GET_IDENTITY_SUGGESTIONS": {1132        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1133        const entries = vault.getEntries();1134        const suggestions = buildIdentitySuggestions(entries);1135        return { ok: true, data: { suggestions } };1136      }1137      case "POPULATE_INLINE_VAULT": {1138        if (!isNativePlatform()) return { ok: false };1139        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1140        const entries = vault.getEntries();1141        await publishInMemoryVault(entries);1142        return { ok: true };1143      }1144      case "ML_INIT":1145        return { ok: true };11461147      case "ML_PREDICT_BATCH": {1148        // AUD-002: shape-validate before forwarding to the ML helper.1149        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1150        if (!Array.isArray(featuresArray)) {1151          return { ok: false, error: "invalid_payload" };1152        }1153        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1154      }11551156      // ── Chirp Sync (v3) ───────────────────────────────────────────────1157      // Returns the public-facing local identity needed by the popup to1158      // drive Phase-1 audio pairing. The private long-term key never1159      // leaves the background.1160      case "CHIRP_GET_LOCAL_IDENTITY": {1161        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1162        const proCheck = await requirePro("sync");1163        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1164        // Identity derives from the stable root key, not the password-derived1165        // key, so pairing survives a master-password change (SEV-2-B).1166        const masterKeyHex = vault.getRootKeyHex();1167        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1168        const masterKey = unhexBytes(masterKeyHex);1169        try {1170          const identity = await buildLocalIdentity(masterKey);1171          return { ok: true, data: identity };1172        } finally {1173          masterKey.fill(0);1174        }1175      }11761177      case "CHIRP_COMPLETE_PAIRING": {1178        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1179        const proCheck = await requirePro("sync");1180        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1181        const paired = (msg.payload as { paired?: unknown })?.paired;1182        if (typeof paired !== "object" || paired === null) {1183          return { ok: false, error: "invalid_payload" };1184        }1185        const candidate = paired as Record<string, unknown>;1186        if (1187          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1188          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1189          typeof candidate.deviceType !== "string" ||1190          typeof candidate.longTermPublicKeyHex !== "string" ||1191          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1192          (1193            candidate.signingPublicKeyHex !== undefined &&1194            (1195              typeof candidate.signingPublicKeyHex !== "string" ||1196              !/^[0-9a-f]{64}$/.test(candidate.signingPublicKeyHex)1197            )1198          ) ||1199          typeof candidate.pairedAt !== "number"1200        ) {1201          return { ok: false, error: "invalid_paired_device" };1202        }1203        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1204        return { ok: true };1205      }12061207      case "CHIRP_LIST_PAIRED_DEVICES": {1208        const devices = await listPairedDevicesV3();1209        return { ok: true, data: { devices } };1210      }12111212      case "CHIRP_UNPAIR_DEVICE": {1213        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1214        if (typeof deviceId !== "string" || !deviceId) {1215          return { ok: false, error: "invalid_payload" };1216        }1217        await removePairedDeviceByIdV3(deviceId);1218        return { ok: true };1219      }12201221      case "CHIRP_RENAME_LOCAL_DEVICE": {1222        const { name } = (msg.payload ?? {}) as { name?: string };1223        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1224        await setDeviceNameV3(name);1225        return { ok: true };1226      }12271228      case "TRIGGER_SYNC": {1229        const payload = (msg.payload ?? {}) as {1230          reason?: "vault_change" | "foreground" | "manual" | "mdns";1231          force?: boolean;1232          deviceId?: string;1233          discoveredIp?: string;1234          discoveredPort?: number;1235        };1236        const reason = payload.reason ?? "foreground";12371238        // mDNS discovery delivers a fresh (ip, port) resolved by the native1239        // side. Update the cached address before the sync runner tries to1240        // connect — avoids a subnet probe on the very next round.1241        if (1242          reason === "mdns" &&1243          typeof payload.deviceId === "string" &&1244          typeof payload.discoveredIp === "string"1245        ) {1246          const { findPairedDeviceById, setLastKnownIp } = await import("./paired-devices");1247          const device = await findPairedDeviceById(payload.deviceId);1248          if (device?.longTermPublicKeyHex) {1249            await setLastKnownIp(device.longTermPublicKeyHex, payload.discoveredIp).catch(() => undefined);1250          }1251        }12521253        const { triggerSyncIfReachable } = await import("./sync-trigger");1254        void triggerSyncIfReachable({ reason, force: payload.force === true });1255        return { ok: true };1256      }12571258      case "GET_SYNC_STATE": {1259        const { getSyncState } = await import("./sync-trigger");1260        return { ok: true, data: getSyncState() };1261      }12621263      default:1264        return { ok: false, error: "unknown_message_type" };1265    }1266  } catch (err) {1267    return {1268      ok: false,1269      error: err instanceof Error ? err.message : "operation_failed",1270    };1271  }1272}12731274// --- Mobile platform helpers ---12751276// Android: populates the in-memory vault used by PeachAutofillService.1277async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1278  const plugin = nativePlugin<{1279    setEntries?: (args: {1280      entries: Array<{1281        id: string;1282        title: string;1283        username: string;1284        email: string;1285        password: string;1286        url: string;1287        totp: string;1288        additionalUrls: string[];1289      }>;1290    }) => Promise<void>;1291  }>("InMemoryVaultPlugin");1292  if (!plugin?.setEntries) return;1293  await plugin.setEntries({1294    entries: entries.map((e) => ({1295      id: e.id,1296      title: e.title ?? "",1297      username: e.username ?? "",1298      email: (e as VaultEntry & { email?: string }).email ?? "",1299      password: e.password ?? "",1300      url: e.url ?? "",1301      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1302      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1303    })),1304  });1305}13061307// Android: clear the autofill in-memory store on lock.1308async function clearInMemoryVault(): Promise<void> {1309  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1310  if (!plugin?.clearEntries) return;1311  await plugin.clearEntries();1312}13131314// Returns username use-counts from the vault, sorted by frequency. Each row1315// also carries the entry's email so the popup can suggest the email/username1316// pair the user has actually used together.1317function buildIdentitySuggestions(1318  entries: VaultEntry[],1319): Array<{ email: string; username: string; count: number }> {1320  const usernameCounts = new Map<string, number>();1321  const usernameEmail = new Map<string, string>();1322  for (const entry of entries) {1323    const username = entry.username ?? "";1324    const email = (entry as VaultEntry & { email?: string }).email ?? "";1325    if (!username && !email) continue;1326    const key = username || email;1327    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1328    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1329  }1330  return Array.from(usernameCounts.entries())1331    .sort((a, b) => b[1] - a[1])1332    .map(([username, count]) => ({1333      email: usernameEmail.get(username) ?? "",1334      username,1335      count,1336    }));1337}13381339/** Notify all content scripts that the vault just became available. */1340function broadcastToContentScripts(message: { type: string }): void {1341  if (!chrome.tabs?.query) return;1342  chrome.tabs.query({}, (tabs) => {1343    for (const tab of tabs) {1344      if (tab.id !== undefined) {1345        chrome.tabs.sendMessage(tab.id, message).catch(() => {1346          // Tab may not have a content script — silently ignore1347        });1348      }1349    }1350  });1351}13521353function shouldRefreshAutoLock(type: MessageType): boolean {1354  return (1355    type !== "HAS_VAULT" &&1356    type !== "IS_UNLOCKED" &&1357    type !== "GET_VAULT_STATUS" &&1358    type !== "LOCK" &&1359    type !== "UPDATE_SETTINGS" &&1360    type !== "GET_PENDING_PASSKEY" &&1361    type !== "GET_PASSKEY_PROVIDER_STATE" &&1362    type !== "DECLINE_CARD_SAVE" &&1363    type !== "IS_CARD_DECLINED" &&1364    type !== "SUBMIT_FEEDBACK"1365  );1366}13671368function isAllowedCanaryWebhookUrl(value: string): boolean {1369  try {1370    const url = new URL(value);1371    if (url.protocol !== "https:") return false;13721373    const hostname = url.hostname.toLowerCase();1374    if (1375      hostname === "localhost" ||1376      hostname.endsWith(".localhost") ||1377      isPrivateIpv4(hostname) ||1378      isPrivateIpv6(hostname)1379    ) {1380      return false;1381    }13821383    return true;1384  } catch {1385    return false;1386  }1387}13881389function isPrivateIpv4(hostname: string): boolean {1390  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1391    return true;1392  }13931394  const octets = hostname.split(".").map((part) => Number(part));1395  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1396    return false;1397  }13981399  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1400}14011402function isPrivateIpv6(hostname: string): boolean {1403  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1404  return (1405    normalized === "::1" ||1406    normalized.startsWith("fc") ||1407    normalized.startsWith("fd") ||1408    normalized.startsWith("fe80:")1409  );1410}