messages.ts

56.9 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        const { passkey: _strippedPasskey, totp: seed, ...safeEntry } = entry;637        let totpCode: string | undefined;638        let totpRemaining: number | undefined;639        if (seed) {640          try {641            const generated = generateTOTP(seed);642            totpCode = generated.code;643            totpRemaining = generated.remaining;644          } catch {645            totpCode = undefined;646          }647        }648        return { ok: true, data: { ...safeEntry, totpCode, totpRemaining } };649      }650      // Trusted full-entry fetch for Peach's own inline-popup surfaces that651      // genuinely need the raw TOTP seed: the edit form (which re-saves the652      // seed and would otherwise wipe it) and nothing else. Unlike653      // GET_ENTRY_FOR_FILL this fires only on an explicit user action inside654      // the inline popup, never during passive autofill on an arbitrary page.655      // The passkey credential is still stripped — the edit form never touches it.656      case "GET_ENTRY_FOR_EDIT": {657        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };658        const { id } = msg.payload as { id: string };659        const entry = vault.getEntryById(id);660        if (!entry) return { ok: false, error: "entry_not_found" };661        const { passkey: _passkey, ...safeEntry } = entry;662        return { ok: true, data: safeEntry };663      }664      case "COPY": {665        // AUD-002: shape-validate the payload before passing to the clipboard666        // helper. A raw cast lets a malformed message reach the clipboard API667        // with a non-string and throw.668        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {669          text?: unknown;670          label?: unknown;671          alreadyWritten?: unknown;672        };673        if (typeof text !== "string" || typeof label !== "string") {674          return { ok: false, error: "invalid_payload" };675        }676        await copyToClipboard(text, label, Boolean(alreadyWritten));677        return { ok: true };678      }679      case "CHECK_ALL_BREACHES": {680        const allEntries = vault.getEntries();681        const results: Record<string, number> = {};682        for (const entry of allEntries) {683          if (entry.type === "note") continue;684          if (!entry.password) continue;685          results[entry.id] = await vault.checkBreach(entry.password);686          // Small delay — be a good citizen to the HIBP API687          await new Promise((r) => setTimeout(r, 200));688        }689        // Persist any non-zero counts back to entries690        for (const [id, count] of Object.entries(results)) {691          const entry = vault.getEntryById(id);692          if (entry && (entry.breach ?? 0) !== count) {693            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });694          }695        }696        return { ok: true, data: results };697      }698      case "GET_SETTINGS":699        return { ok: true, data: await vault.ensureSettingsLoaded() };700      case "UPDATE_SETTINGS": {701        const patch = msg.payload;702        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {703          return { ok: false, error: "invalid_payload" };704        }705        await vault.updateSettings(patch as vault.VaultSettings);706        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {707          await setupAutoLock();708          if (vault.isUnlocked()) touchAutoLock();709        }710        return { ok: true };711      }712      case "GET_PENDING_PASSKEY":713        return { ok: true, data: await getPendingPasskeyRequest() };714      case "APPROVE_PASSKEY": {715        const { requestId } = msg.payload as { requestId: number };716        await resolvePendingPasskeyRequest(requestId, true);717        return { ok: true };718      }719      case "DENY_PASSKEY": {720        const { requestId } = msg.payload as { requestId: number };721        await resolvePendingPasskeyRequest(requestId, false);722        return { ok: true };723      }724      case "GET_PASSKEY_PROVIDER_STATE":725        return { ok: true, data: await getPasskeyProviderState() };726      case "SET_PASSKEY_PROVIDER_ENABLED": {727        const { enabled } = msg.payload as { enabled: boolean };728        // Disabling is always free; gating fires only when a free user is729        // trying to turn passkey interception on.730        if (enabled) {731          const gate = await requirePro("passkeys");732          if (!gate.allowed) return { ok: false, error: "pro_required" };733        }734        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };735      }736      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS737      // endpoint. Intentional product behavior — users configure their own738      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private739      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-740      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to741      // users that the entry title leaves the device when the canary fires.742      case "FIRE_CANARY_PING": {743        // Canary alert fires unconditionally for any entry with canary: true.744        // The Pro gate only governs creation/flagging of canary entries; once745        // an entry is flagged, the alert path is a security property and must746        // never be license-gated.747        const { webhookUrl, entryTitle, trigger } = msg.payload as {748          webhookUrl: string;749          entryTitle: string;750          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";751        };752        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {753          return { ok: false, error: "invalid_webhook_url" };754        }755        const body = JSON.stringify({756          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",757          entry: entryTitle,758          trigger,759          timestamp: new Date().toISOString(),760          source: "peach-extension",761        });762        if (trigger === "test") {763          // Permitted outbound fetch: user-configured canary alert endpoint764          // (validated by isAllowedCanaryWebhookUrl above). This is the765          // only non-HIBP outbound call in the extension — see766          // Projects.md §3.7. Test pings are awaited so the UI can show767          // success/failure.768          try {769            const res = await fetch(webhookUrl, {770              method: "POST",771              headers: { "Content-Type": "application/json" },772              body,773            });774            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };775          } catch (err) {776            return { ok: false, error: err instanceof Error ? err.message : "network_error" };777          }778        }779        // Non-test triggers are fire-and-forget780        fetch(webhookUrl, {781          method: "POST",782          headers: { "Content-Type": "application/json" },783          body,784        }).catch(() => {});785        return { ok: true };786      }787      case "ACTIVATE_LICENSE": {788        const { key } = msg.payload as { key: string };789        const licenseInfo = await activateLicense(key);790        return { ok: true, data: licenseInfo };791      }792      case "GET_LICENSE": {793        const licenseInfo = await getLicenseInfo();794        return { ok: true, data: licenseInfo };795      }796      case "GET_LICENSE_KEY": {797        const key = await getLicenseKey();798        return { ok: true, data: key };799      }800      case "DEACTIVATE_LICENSE": {801        await deactivateLicense();802        return { ok: true };803      }804      case "SHOULD_PLAY_CELEBRATION": {805        const should = await shouldPlayCelebration();806        return { ok: true, data: should };807      }808      case "MARK_CELEBRATION_PLAYED": {809        await markCelebrationPlayed();810        return { ok: true };811      }812      case "GET_CODEX_VAULT_DATA": {813        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the814        // popup navigates to the License section without further coordination.815        const gate = await requirePro("codex");816        if (!gate.allowed) return { ok: false, error: "pro_required" };817        return await handleGetCodexVaultData();818      }819      case "ESTIMATE_CODEX_PAGES": {820        const gate = await requirePro("codex");821        if (!gate.allowed) return { ok: false, error: "pro_required" };822        return await handleEstimateCodexPages();823      }824      case "RESTORE_FROM_CODEX": {825        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still826        // be able to restore a vault that was printed by a Pro user.827        // DO NOT add a Pro gate here.828        const payload = msg.payload as CodexRestorePayload;829        return await handleRestoreFromCodex(payload);830      }831      case "OPEN_PRO_GATE": {832        // Content script requests: open popup and navigate to License section.833        const { feature } = (msg.payload ?? {}) as { feature?: string };834        if (chrome.storage.session) {835          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });836        }837        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }838        return { ok: true };839      }840      case "OPEN_POPUP": {841        // Content script asks to open the trusted extension popup — used by the842        // inline locked bubble so the master password is entered in the popup,843        // never in page-hosted DOM (audit HIGH). Best-effort: openPopup needs a844        // user gesture + Chrome 127+/Firefox; on failure the user clicks the845        // toolbar icon. The badge already signals Peach needs attention.846        //847        // Set a session flag so the popup knows it was opened for inline unlock848        // and should close itself once the vault is unlocked (returning the user849        // to the inline autofill selector on the page).850        if (chrome.storage.session) {851          await chrome.storage.session.set({ peach_inline_unlock: true });852        }853        try { await chrome.action.openPopup(); } catch { /* user opens via toolbar */ }854        return { ok: true };855      }856      case "GET_IDENTITIES": {857        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };858        return { ok: true, data: vault.getIdentities() };859      }860      case "TOUCH_AUTO_LOCK": {861        // touchAutoLock() is already called by shouldRefreshAutoLock above;862        // this case just gives the popup a typed message to keep the session alive.863        return { ok: true };864      }865      case "GET_ADVANCED_HEALTH_REPORT": {866        const gate = await requirePro("advanced_health");867        if (!gate.allowed) return { ok: false, error: "pro_required" };868        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };869        const report = await buildAdvancedHealthReport(vault.getEntries());870        return { ok: true, data: report };871      }872      case "IS_DURESS_ENABLED": {873        const enabled = await vault.isDuressEnabled();874        return { ok: true, data: enabled };875      }876      case "SETUP_DURESS": {877        // Single enforcement point for the Duress Vault Pro gate. Free users878        // who somehow reach this handler are rejected here; the popup also879        // pre-checks isPro() to avoid showing the setup form to free users,880        // but server-side is the actual security boundary.881        const gate = await requirePro("duress_vault");882        if (!gate.allowed) return { ok: false, error: "pro_required" };883        // MV3 service workers restart after inactivity, losing the in-memory884        // derived key. Detect this before calling setupDuress so the popup885        // can show a meaningful prompt to re-lock and re-unlock.886        if (!vault.isUnlocked()) return { ok: false, error: "session_expired" };887        const { duressPassword } = msg.payload as { duressPassword: string };888        await vault.setupDuress(duressPassword);889        return { ok: true };890      }891      case "DISABLE_DURESS": {892        await vault.disableDuress();893        return { ok: true };894      }895      case "VERIFY_MAIN_PASSWORD": {896        const { password } = msg.payload as { password: string };897        const ok = await vault.verifyMainPassword(password);898        return { ok: true, data: ok };899      }900      case "CHANGE_PASSWORD": {901        const { currentPassword, newPassword } = msg.payload as {902          currentPassword: string;903          newPassword: string;904        };905        const changed = await vault.changePassword(currentPassword, newPassword);906        return changed907          ? { ok: true }908          : { ok: false, error: "incorrect_current_password" };909      }910      case "GET_SITE_PASSWORD_POLICY": {911        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });912        if (!tab?.id) return { ok: true, data: null };913        try {914          const response = await chrome.tabs.sendMessage(tab.id, {915            type: "GET_SITE_PASSWORD_POLICY",916          });917          return (response as MessageResponse) ?? { ok: true, data: null };918        } catch {919          return { ok: true, data: null };920        }921      }922      case "RECORD_MANUAL_SUMMON": {923        const { domain } = msg.payload as { domain: string };924        const settings = vault.getSettings();925        const existing = settings.manualSummonDomains?.[domain];926        const now = Date.now();927        await vault.updateSettings({928          manualSummonDomains: {929            ...settings.manualSummonDomains,930            [domain]: {931              firstSummonedAt: existing?.firstSummonedAt ?? now,932              summonCount: (existing?.summonCount ?? 0) + 1,933              lastSummonedAt: now,934            },935          },936        });937        return { ok: true };938      }939      case "DECLINE_CARD_SAVE": {940        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };941        await vault.declineCardSaveOffer(last4, expMonth, expYear);942        return { ok: true };943      }944      case "IS_CARD_DECLINED": {945        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };946        const declined = await vault.isCardDeclined(last4, expMonth, expYear);947        return { ok: true, data: declined };948      }949      case "INITIATE_FIREFOX_PASSKEY_CREATE": {950        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {951          rpId?: string;952          rpName?: string;953          userName?: string;954          userDisplayName?: string;955        };956        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };957        return await initiateFirefoxPasskeyCreate({958          rpId,959          rpName: rpName ?? rpId,960          userName,961          userDisplayName,962        });963      }964965      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {966        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;967        if (!payload) return { ok: false, error: "missing_payload" };968        return await completeFirefoxPasskeyCreate(payload);969      }970971      case "PASSKEY_OFFER_DECLINE": {972        const { domain } = (msg.payload ?? {}) as { domain?: string };973        if (!domain) return { ok: false, error: "domain_required" };974        await recordPasskeyOfferDecline(domain);975        return { ok: true };976      }977978      case "GET_PASSKEY_OFFER_DECLINED": {979        const { domain } = (msg.payload ?? {}) as { domain?: string };980        if (!domain) return { ok: false, error: "domain_required" };981        return { ok: true, data: await isPasskeyOfferDeclined(domain) };982      }983984      case "PASSKEY_HAS_CREDENTIALS": {985        const payload = msg.payload as {986          rpId?: string;987          allowCredentials?: Array<{ id: string; type?: string }>;988        } | undefined;989        if (!payload?.rpId) return { ok: false, error: "rpid_required" };990        return await handlePasskeyHasCredentials({991          rpId: payload.rpId,992          allowCredentials: payload.allowCredentials ?? [],993        }, attestedSenderOrigin(sender));994      }995996      case "PASSKEY_CREATE": {997        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;998        if (!payload?.rpId || !payload?.userName) {999          return { ok: false, error: "rpid_and_username_required" };1000        }1001        return await handleFirefoxPasskeyCreate(payload, attestedSenderOrigin(sender));1002      }10031004      case "PASSKEY_GET": {1005        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1006        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1007        return await handleFirefoxPasskeyGet(payload, attestedSenderOrigin(sender));1008      }10091010      case "PASSKEY_AUTH_RESPONSE": {1011        const { requestId, approved } = (msg.payload ?? {}) as {1012          requestId?: string | number;1013          approved?: boolean;1014        };1015        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1016          return { ok: false, error: 'requestId and approved required' };1017        }1018        await resolvePendingPasskeyRequest(Number(requestId), approved);1019        return { ok: true };1020      }10211022      case "GET_PASSKEY_FOR_DOMAIN": {1023        const { domain } = (msg.payload ?? {}) as { domain?: string };1024        if (!domain) return { ok: false, error: "domain_required" };1025        // Scope to the caller's own origin: a page may only ask about passkeys1026        // for a domain it actually owns, so an arbitrary page cannot enumerate1027        // which sites the user holds passkeys for or read the username (audit MEDIUM).1028        const origin = attestedSenderOrigin(sender);1029        if (!origin || !isValidRpId(domain, origin)) return { ok: true, data: null };1030        if (!vault.isUnlocked()) return { ok: true, data: null };1031        const match = vault1032          .getEntries()1033          .find((entry) => entry.passkey?.rpId === domain);1034        if (!match || !match.passkey) return { ok: true, data: null };1035        // Slim shape — only the fields State 11 needs. Never expose private1036        // key material, even though this is locked behind isUnlocked.1037        return {1038          ok: true,1039          data: {1040            rpId: match.passkey.rpId,1041            userName: match.passkey.userName,1042            browser: match.passkey.browser,1043          },1044        };1045      }10461047      case "DESTROY_VAULT": {1048        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1049        // storage.local.clear() wipes every Peach key (slots, settings, license,1050        // onboarded flag, history, sync state, declined cards, recall, etc.);1051        // session.clear() wipes pending passkey requests + pro-notice queues.1052        // Caller (Panic.tsx) handles UI navigation back to onboarding.1053        //1054        // The Pro license is the one thing that must survive: the user paid for1055        // it, and destroying a vault (panic wipe, fresh start) is not a refund.1056        // Capture it before the clear and restore it after. peach_pro_celebrated1057        // rides along so the Pro celebration doesn't replay on the next unlock.1058        const preserved = await chrome.storage.local.get([1059          "peach_license",1060          "peach_pro_celebrated",1061        ]);1062        vault.lock();1063        await storageClear();1064        await vault.clearVaultHistory();1065        const toRestore: Record<string, unknown> = {};1066        if (preserved.peach_license !== undefined) toRestore.peach_license = preserved.peach_license;1067        if (preserved.peach_pro_celebrated !== undefined) toRestore.peach_pro_celebrated = preserved.peach_pro_celebrated;1068        if (Object.keys(toRestore).length > 0) {1069          await chrome.storage.local.set(toRestore);1070        }1071        if (chrome.storage.session) {1072          await chrome.storage.session.clear();1073        }1074        return { ok: true };1075      }10761077      case "SUBMIT_FEEDBACK": {1078        const { category, message, version, browser } = msg.payload as {1079          category: string;1080          message: string;1081          version: string;1082          browser: string;1083        };1084        if (!message.trim()) return { ok: false, error: "message_empty" };1085        if (!FEEDBACK_ENDPOINT) return { ok: true };1086        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1087          return { ok: false, error: "invalid_feedback_endpoint" };1088        }1089        try {1090          const res = await fetch(FEEDBACK_ENDPOINT, {1091            method: "POST",1092            headers: { "Content-Type": "application/json" },1093            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1094          });1095          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1096        } catch (err) {1097          return { ok: false, error: err instanceof Error ? err.message : "network_error" };1098        }1099      }1100      // Android-only: biometric unlock with pre-derived key.1101      case "UNLOCK_WITH_KEY": {1102        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1103        if (!isNativePlatform()) {1104          return { ok: false, error: "desktop_only_uses_password" };1105        }1106        try {1107          const result = await vault.unlockWithKey(masterKeyHex);1108          if (result.ok) {1109            onVaultUnlocked();1110            await publishInMemoryVault(result.entries);1111          }1112          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1113        } catch {1114          return { ok: false, error: "invalid_key" };1115        }1116      }1117      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1118      case "GET_DERIVED_KEY": {1119        if (!isNativePlatform()) {1120          return { ok: false, error: "android_only" };1121        }1122        if (!vault.isUnlocked()) {1123          return { ok: false, error: "vault_locked" };1124        }1125        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1126      }1127      case "GET_IDENTITY_SUGGESTIONS": {1128        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1129        const entries = vault.getEntries();1130        const suggestions = buildIdentitySuggestions(entries);1131        return { ok: true, data: { suggestions } };1132      }1133      case "POPULATE_INLINE_VAULT": {1134        if (!isNativePlatform()) return { ok: false };1135        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1136        const entries = vault.getEntries();1137        await publishInMemoryVault(entries);1138        return { ok: true };1139      }1140      case "ML_INIT":1141        return { ok: true };11421143      case "ML_PREDICT_BATCH": {1144        // AUD-002: shape-validate before forwarding to the ML helper.1145        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };1146        if (!Array.isArray(featuresArray)) {1147          return { ok: false, error: "invalid_payload" };1148        }1149        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };1150      }11511152      // ── Chirp Sync (v3) ───────────────────────────────────────────────1153      // Returns the public-facing local identity needed by the popup to1154      // drive Phase-1 audio pairing. The private long-term key never1155      // leaves the background.1156      case "CHIRP_GET_LOCAL_IDENTITY": {1157        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1158        const proCheck = await requirePro("sync");1159        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1160        // Identity derives from the stable root key, not the password-derived1161        // key, so pairing survives a master-password change (SEV-2-B).1162        const masterKeyHex = vault.getRootKeyHex();1163        if (!masterKeyHex) return { ok: false, error: "vault_locked" };1164        const masterKey = unhexBytes(masterKeyHex);1165        try {1166          const identity = await buildLocalIdentity(masterKey);1167          return { ok: true, data: identity };1168        } finally {1169          masterKey.fill(0);1170        }1171      }11721173      case "CHIRP_COMPLETE_PAIRING": {1174        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1175        const proCheck = await requirePro("sync");1176        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1177        const paired = (msg.payload as { paired?: unknown })?.paired;1178        if (typeof paired !== "object" || paired === null) {1179          return { ok: false, error: "invalid_payload" };1180        }1181        const candidate = paired as Record<string, unknown>;1182        if (1183          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1184          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1185          typeof candidate.deviceType !== "string" ||1186          typeof candidate.longTermPublicKeyHex !== "string" ||1187          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1188          (1189            candidate.signingPublicKeyHex !== undefined &&1190            (1191              typeof candidate.signingPublicKeyHex !== "string" ||1192              !/^[0-9a-f]{64}$/.test(candidate.signingPublicKeyHex)1193            )1194          ) ||1195          typeof candidate.pairedAt !== "number"1196        ) {1197          return { ok: false, error: "invalid_paired_device" };1198        }1199        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1200        return { ok: true };1201      }12021203      case "CHIRP_LIST_PAIRED_DEVICES": {1204        const devices = await listPairedDevicesV3();1205        return { ok: true, data: { devices } };1206      }12071208      case "CHIRP_UNPAIR_DEVICE": {1209        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1210        if (typeof deviceId !== "string" || !deviceId) {1211          return { ok: false, error: "invalid_payload" };1212        }1213        await removePairedDeviceByIdV3(deviceId);1214        return { ok: true };1215      }12161217      case "CHIRP_RENAME_LOCAL_DEVICE": {1218        const { name } = (msg.payload ?? {}) as { name?: string };1219        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1220        await setDeviceNameV3(name);1221        return { ok: true };1222      }12231224      case "TRIGGER_SYNC": {1225        const payload = (msg.payload ?? {}) as {1226          reason?: "vault_change" | "foreground" | "manual" | "mdns";1227          force?: boolean;1228          deviceId?: string;1229          discoveredIp?: string;1230          discoveredPort?: number;1231        };1232        const reason = payload.reason ?? "foreground";12331234        // mDNS discovery delivers a fresh (ip, port) resolved by the native1235        // side. Update the cached address before the sync runner tries to1236        // connect — avoids a subnet probe on the very next round.1237        if (1238          reason === "mdns" &&1239          typeof payload.deviceId === "string" &&1240          typeof payload.discoveredIp === "string"1241        ) {1242          const { findPairedDeviceById, setLastKnownIp } = await import("./paired-devices");1243          const device = await findPairedDeviceById(payload.deviceId);1244          if (device?.longTermPublicKeyHex) {1245            await setLastKnownIp(device.longTermPublicKeyHex, payload.discoveredIp).catch(() => undefined);1246          }1247        }12481249        const { triggerSyncIfReachable } = await import("./sync-trigger");1250        void triggerSyncIfReachable({ reason, force: payload.force === true });1251        return { ok: true };1252      }12531254      case "GET_SYNC_STATE": {1255        const { getSyncState } = await import("./sync-trigger");1256        return { ok: true, data: getSyncState() };1257      }12581259      default:1260        return { ok: false, error: "unknown_message_type" };1261    }1262  } catch (err) {1263    return {1264      ok: false,1265      error: err instanceof Error ? err.message : "operation_failed",1266    };1267  }1268}12691270// --- Mobile platform helpers ---12711272// Android: populates the in-memory vault used by PeachAutofillService.1273async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1274  const plugin = nativePlugin<{1275    setEntries?: (args: {1276      entries: Array<{1277        id: string;1278        title: string;1279        username: string;1280        email: string;1281        password: string;1282        url: string;1283        totp: string;1284        additionalUrls: string[];1285      }>;1286    }) => Promise<void>;1287  }>("InMemoryVaultPlugin");1288  if (!plugin?.setEntries) return;1289  await plugin.setEntries({1290    entries: entries.map((e) => ({1291      id: e.id,1292      title: e.title ?? "",1293      username: e.username ?? "",1294      email: (e as VaultEntry & { email?: string }).email ?? "",1295      password: e.password ?? "",1296      url: e.url ?? "",1297      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1298      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1299    })),1300  });1301}13021303// Android: clear the autofill in-memory store on lock.1304async function clearInMemoryVault(): Promise<void> {1305  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1306  if (!plugin?.clearEntries) return;1307  await plugin.clearEntries();1308}13091310// Returns username use-counts from the vault, sorted by frequency. Each row1311// also carries the entry's email so the popup can suggest the email/username1312// pair the user has actually used together.1313function buildIdentitySuggestions(1314  entries: VaultEntry[],1315): Array<{ email: string; username: string; count: number }> {1316  const usernameCounts = new Map<string, number>();1317  const usernameEmail = new Map<string, string>();1318  for (const entry of entries) {1319    const username = entry.username ?? "";1320    const email = (entry as VaultEntry & { email?: string }).email ?? "";1321    if (!username && !email) continue;1322    const key = username || email;1323    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1324    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1325  }1326  return Array.from(usernameCounts.entries())1327    .sort((a, b) => b[1] - a[1])1328    .map(([username, count]) => ({1329      email: usernameEmail.get(username) ?? "",1330      username,1331      count,1332    }));1333}13341335/** Notify all content scripts that the vault just became available. */1336function broadcastToContentScripts(message: { type: string }): void {1337  if (!chrome.tabs?.query) return;1338  chrome.tabs.query({}, (tabs) => {1339    for (const tab of tabs) {1340      if (tab.id !== undefined) {1341        chrome.tabs.sendMessage(tab.id, message).catch(() => {1342          // Tab may not have a content script — silently ignore1343        });1344      }1345    }1346  });1347}13481349function shouldRefreshAutoLock(type: MessageType): boolean {1350  return (1351    type !== "HAS_VAULT" &&1352    type !== "IS_UNLOCKED" &&1353    type !== "GET_VAULT_STATUS" &&1354    type !== "LOCK" &&1355    type !== "UPDATE_SETTINGS" &&1356    type !== "GET_PENDING_PASSKEY" &&1357    type !== "GET_PASSKEY_PROVIDER_STATE" &&1358    type !== "DECLINE_CARD_SAVE" &&1359    type !== "IS_CARD_DECLINED" &&1360    type !== "SUBMIT_FEEDBACK"1361  );1362}13631364function isAllowedCanaryWebhookUrl(value: string): boolean {1365  try {1366    const url = new URL(value);1367    if (url.protocol !== "https:") return false;13681369    const hostname = url.hostname.toLowerCase();1370    if (1371      hostname === "localhost" ||1372      hostname.endsWith(".localhost") ||1373      isPrivateIpv4(hostname) ||1374      isPrivateIpv6(hostname)1375    ) {1376      return false;1377    }13781379    return true;1380  } catch {1381    return false;1382  }1383}13841385function isPrivateIpv4(hostname: string): boolean {1386  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1387    return true;1388  }13891390  const octets = hostname.split(".").map((part) => Number(part));1391  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1392    return false;1393  }13941395  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1396}13971398function isPrivateIpv6(hostname: string): boolean {1399  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1400  return (1401    normalized === "::1" ||1402    normalized.startsWith("fc") ||1403    normalized.startsWith("fd") ||1404    normalized.startsWith("fe80:")1405  );1406}