messages.ts

46.1 KB · raw

1/**2 * messages.ts — the only background message handler.3 *4 * All `chrome.runtime.onMessage` handling for the service worker lives here.5 * Do not handle messages inline in entry.ts, alarms.ts, or any other6 * background file. Every background-bound MessageType in shared/types.ts7 * must have a case below. Content-script-bound message types (PING,8 * SUMMON_AUTOFILL, VAULT_LOCKED) are documented in shared/types.ts and9 * intentionally have no case here — they are sent *to* content scripts.10 */1112import { copyToClipboard } from "./clipboard";13import { setupAutoLock, touchAutoLock } from "./alarms";14import { runSelfTest } from "./self-test";15import * as vault from "./vault";16import {17  handleEstimateCodexPages,18  handleGetCodexVaultData,19  handleRestoreFromCodex,20} from "./codex-handlers";21import type { CodexRestorePayload } from "../shared/codex-types";22import {23  activateLicense,24  deactivateLicense,25  getLicenseInfo,26  getLicenseKey,27  isProUser,28  markCelebrationPlayed,29  shouldPlayCelebration,30} from "./license";31import {32  completeFirefoxPasskeyCreate,33  getPasskeyProviderState,34  getPendingPasskeyRequest,35  handleFirefoxPasskeyCreate,36  handleFirefoxPasskeyGet,37  handlePasskeyHasCredentials,38  initiateFirefoxPasskeyCreate,39  isPasskeyOfferDeclined,40  onVaultUnlocked,41  recordPasskeyOfferDecline,42  resolvePendingPasskeyRequest,43  setPasskeyProviderEnabled,44} from "./passkey";45import { buildAdvancedHealthReport, resolveResetUrl } 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 { isNativePlatform, nativePlugin } from "../shared/native";57import { predictBatch as mlPredictBatch } from "./ml";58import type { MLFieldFeatures } from "../shared/ml";59import { buildLocalIdentity, setDeviceName as setDeviceNameV3 } from "./chirp-identity";60import {61  listPairedDevices as listPairedDevicesV3,62  removePairedDeviceById as removePairedDeviceByIdV3,63  upsertPairedDevice as upsertPairedDeviceV3,64} from "./paired-devices";6566function unhexBytes(hex: string): Uint8Array {67  if (hex.length % 2 !== 0) throw new Error("invalid hex");68  const out = new Uint8Array(hex.length / 2);69  for (let i = 0; i < out.length; i++) {70    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);71  }72  return out;73}7475/**76 * The single Pro gate. Every gated handler calls this first; the broadcast77 * lets the popup react (navigate to the License section, highlight the78 * relevant feature). Background never touches the popup view directly —79 * the popup owns navigation. See Projects.md "Pro gate rule".80 */81async function requirePro(82  feature: ProFeature,83  trigger: "user" | "background" = "user"84): Promise<{ allowed: boolean }> {85  if (await isProUser()) return { allowed: true };8687  if (trigger === "user") {88    // User deliberately triggered this feature — redirect the popup immediately.89    chrome.runtime90      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })91      .catch(() => {92        // Popup may be closed — the gate signal is best-effort.93      });94  } else {95    // Background trigger (e.g. passive sync initiation) — no popup is open.96    // Queue a notice so the next popup open shows a soft banner instead of97    // silently failing.98    if (chrome.storage.session) {99      chrome.storage.session100        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })101        .catch(() => {});102    }103  }104105  return { allowed: false };106}107108// ---------------------------------------------------------------------------109// Feedback submission target. Empty disables network submission while the UI110// continues to function as a no-op (the handler returns ok:true without111// calling fetch). When set, the URL is validated by112// `isAllowedCanaryWebhookUrl` before any request.113// ---------------------------------------------------------------------------114115const FEEDBACK_ENDPOINT = "";116117const PRIVATE_IPV4_RANGES = [118  { prefix: "10." },119  { prefix: "127." },120  { prefix: "169.254." },121  { prefix: "192.168." },122];123124export function setupMessageHandler(): void {125  chrome.runtime.onMessage.addListener(126    (msg: unknown, sender, sendResponse) => {127      if (!isMessage(msg)) {128        sendResponse({ ok: false, error: "invalid_message" });129        return true;130      }131      handleMessage(msg, sender)132        .then(sendResponse)133        .catch((err) =>134          sendResponse({135            ok: false,136            error: err instanceof Error ? err.message : String(err),137          })138        );139      return true;140    }141  );142143  // Android: the chrome shim queues sendMessage calls until this handler is144  // registered. Without this hookup, every message hangs on Capacitor builds.145  // eslint-disable-next-line @typescript-eslint/no-explicit-any146  const reg = (globalThis as any).__peachRegisterMessageHandler;147  if (typeof reg === "function") {148    reg(async (m: unknown) => {149      if (!isMessage(m)) return { ok: false, error: "invalid_message" };150      try {151        return await handleMessage(m);152      } catch (err) {153        return {154          ok: false,155          error: err instanceof Error ? err.message : String(err),156        };157      }158    });159  }160161}162163function isMessage(m: unknown): m is Message {164  return typeof m === "object" && m !== null && "type" in m;165}166167export async function handleMessage(168  msg: Message,169  sender: Partial<chrome.runtime.MessageSender> = {}170): Promise<MessageResponse> {171  try {172    // Validate sender — only allow messages from our extension pages/scripts.173    // `sender.id` is undefined for messages originating from extension UI174    // (popup/options), which is legitimate; reject only when it is defined175    // and does not match our extension id.176    if (177      sender.id !== undefined &&178      sender.id !== chrome.runtime.id179    ) {180      return { ok: false, error: "invalid_sender" };181    }182183    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {184      touchAutoLock();185    }186187    switch (msg.type) {188      case "CREATE_VAULT": {189        const { password } = msg.payload as { password: string };190        await vault.createVault(password);191        await setupAutoLock();192        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });193        onVaultUnlocked();194        return { ok: true };195      }196      case "UNLOCK": {197        const { password } = msg.payload as { password: string };198        const ok = await vault.unlock(password);199        if (ok) {200          // KAT: verify the WebCrypto stack is healthy before the user relies on it.201          // Runs after unlock so latency is hidden behind the vault-load time.202          const kat = await runSelfTest();203          if (!kat.ok) {204            console.error("[Peach] Crypto self-test FAILED:", kat.error);205            await vault.lock();206            return { ok: false, error: "self_test_failed" };207          }208          await setupAutoLock();209          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });210          onVaultUnlocked();211          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());212          return { ok: true };213        }214        // Distinguish corruption from wrong password so the popup can offer215        // a history-restore path instead of falsely accusing the user of216        // mistyping (M7/COR-007).217        const failure = vault.consumeLastUnlockFailureReason();218        if (failure) {219          return {220            ok: false,221            error: "vault_corrupted",222            canRestoreFromHistory: true,223          } as MessageResponse;224        }225        return { ok: false };226      }227      case "VALIDATE_RECOVERY_WORDS": {228        const { words } = msg.payload as { words: string[] };229        const invalid = findInvalidWords(words);230        return { ok: true, data: { valid: invalid.length === 0, invalid } };231      }232      case "GET_RECOVERY_WORDS": {233        // Must be unlocked and have recovery set up (vault must be v2.12+).234        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };235        try {236          const words = await vault.getRecoveryWords();237          return { ok: true, data: words };238        } catch (e) {239          // pre-v2.12 vault that hasn't migrated240          return { ok: false, error: "recovery_not_setup" };241        }242      }243      case "RECOVER_WITH_WORDS": {244        // User has lost their password but has their 12 recovery words.245        // We: (1) validate the words, (2) re-encrypt vault with new password.246        const { words, newPassword } = msg.payload as {247          words: string[];248          newPassword: string;249        };250        const stored = await vault.loadSlotA();251        if (!stored) return { ok: false, error: "no_vault" };252        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {253          return { ok: false, error: "recovery_not_setup" };254        }255        // Unwrap the root key from the recovery escrow.256        try {257          await vault.unwrapRootKeyForRecovery(258            stored.recovery_wrapped_root_key,259            stored.recovery_nonce ?? "",260            stored.recovery_tag ?? "",261            stored.recovery_salt,262            words263          );264        } catch {265          return { ok: false, error: "invalid_recovery_words" };266        }267        // Re-key: derive fresh salt + key from new password.268        const newSalt = vault.generateSalt();269        const newKey = await vault.deriveKey(newPassword, newSalt);270        // Re-wrap root key under the new password's derived key so the same271        // recovery words continue to work after the password change.272        await vault.rewrapRootKeyForPassword(newKey, newSalt);273        // Re-encrypt vault entries with the new key.274        await vault.changePasswordWithNewKey(newSalt, newKey);275        await setupAutoLock();276        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });277        return { ok: true };278      }279      case "LOCK":280        vault.lock();281        if (isNativePlatform()) await clearInMemoryVault();282        return { ok: true };283      case "IS_UNLOCKED":284        return { ok: true, data: vault.isUnlocked() };285      case "GET_VAULT_STATUS":286        return { ok: true, unlocked: vault.isUnlocked() };287      case "HAS_VAULT":288        return { ok: true, data: await vault.hasVault() };289      case "GET_ENTRIES":290        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };291        return { ok: true, data: vault.getEntries() };292      case "ADD_ENTRY": {293        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };294        const payload = msg.payload;295        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {296          return { ok: false, error: "invalid_payload" };297        }298        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);299        return { ok: true, data: entry };300      }301      case "BATCH_ADD_ENTRIES": {302        const payload = msg.payload as { entries?: unknown } | null | undefined;303        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {304          return { ok: false, error: "invalid_payload" };305        }306        if (!Array.isArray(payload.entries)) {307          return { ok: false, error: "invalid_payload" };308        }309        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);310        return { ok: true, data: added };311      }312      case "RESTORE_ENTRIES": {313        const payload = msg.payload as314          | { entries?: unknown; mode?: unknown; settings?: unknown }315          | null316          | undefined;317        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {318          return { ok: false, error: "invalid_payload" };319        }320        if (!Array.isArray(payload.entries)) {321          return { ok: false, error: "invalid_payload" };322        }323        if (payload.mode !== "replace" && payload.mode !== "merge") {324          return { ok: false, error: "invalid_payload" };325        }326        const summary = await vault.restoreEntries(327          payload.entries as Parameters<typeof vault.restoreEntries>[0],328          payload.mode329        );330        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {331          await vault.updateSettings(payload.settings as vault.VaultSettings);332        }333        return { ok: true, data: summary };334      }335      case "CLEAR_VAULT_ENTRIES": {336        await vault.clearVaultEntries("REPLACE_ALL");337        return { ok: true };338      }339      case "GET_VAULT_HISTORY": {340        const snapshots = await vault.getVaultHistory();341        return { ok: true, data: snapshots };342      }343      case "RESTORE_VAULT_SNAPSHOT": {344        const { snapshotId } = msg.payload as { snapshotId: string };345        const result = await vault.restoreVaultSnapshot(snapshotId);346        if (!result.ok) return { ok: false, error: result.error };347        broadcastToContentScripts({ type: "VAULT_LOCKED" });348        return { ok: true };349      }350      case "COUNT_DUPLICATES": {351        return { ok: true, data: vault.countDuplicates() };352      }353      case "DEDUPLICATE_ENTRIES": {354        const removed = await vault.deduplicateEntries();355        return { ok: true, data: removed };356      }357      case "UPDATE_ENTRY": {358        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;359        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {360          return { ok: false, error: "invalid_payload" };361        }362        const { id, patch } = payload;363        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {364          return { ok: false, error: "invalid_payload" };365        }366        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);367        return { ok: true };368      }369      case "ADD_ADDITIONAL_URL": {370        const { id, url } = msg.payload as { id: string; url: string };371        const trimmed = typeof url === "string" ? url.trim() : "";372        if (!trimmed) return { ok: false, error: "url_required" };373        const existing = vault.getEntryById(id);374        if (!existing) return { ok: false, error: "entry_not_found" };375        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };376        const merged = [...(existing.additionalUrls ?? []), trimmed];377        await vault.updateEntry(id, { additionalUrls: merged });378        return { ok: true };379      }380      case "DELETE_ENTRY": {381        const { id } = msg.payload as { id: string };382        await vault.deleteEntry(id);383        return { ok: true };384      }385      case "GET_DELETED_ENTRIES":386        return { ok: true, data: vault.getDeletedEntries() };387      case "RESTORE_ENTRY": {388        const { id } = msg.payload as { id: string };389        await vault.restoreEntry(id);390        return { ok: true };391      }392      case "PURGE_ENTRY": {393        const { id } = msg.payload as { id: string };394        await vault.purgeEntry(id);395        return { ok: true };396      }397      case "PURGE_EXPIRED_TRASH": {398        const { retentionMs } = msg.payload as { retentionMs: number };399        const purged = await vault.purgeExpiredTrash(retentionMs);400        return { ok: true, data: purged };401      }402      case "SAVE_NOTE": {403        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };404        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };405        const now = Date.now();406        if (id) {407          const existing = vault.getEntryById(id);408          if (!existing) return { ok: false, error: "not_found" };409          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });410          return { ok: true, data: vault.getEntryById(id) };411        } else {412          const entry = await vault.addEntry({413            type: "note",414            title: title || "Untitled",415            notes: body,416            createdAt: now,417            modifiedAt: now,418          } as any);419          return { ok: true, data: entry };420        }421      }422      case "DELETE_NOTE": {423        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };424        const { id } = msg.payload as { id: string };425        await vault.deleteEntry(id);426        return { ok: true };427      }428      case "GET_NOTES": {429        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };430        const notes = vault.getEntries().filter(431          (e) => e.type === "note" && !e.deletedAt432        );433        return { ok: true, data: notes } as MessageResponse;434      }435      case "SEARCH_VAULT": {436        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };437        // AUD-002: shape-validate the payload before calling string methods.438        // A raw cast lets a malformed message crash the handler with TypeError.439        const { query } = (msg.payload ?? {}) as { query?: unknown };440        if (typeof query !== "string") {441          return { ok: false, error: "invalid_payload" };442        }443        const q = query.toLowerCase();444        const searchResults = vault.getEntries().filter(445          (e) =>446            !e.deletedAt &&447            (e.title.toLowerCase().includes(q) ||448              e.notes?.toLowerCase().includes(q) ||449              e.username?.toLowerCase().includes(q))450        );451        return { ok: true, data: searchResults } as MessageResponse;452      }453      case "AUTOFILL_QUERY": {454        if (!vault.isUnlocked()) {455          return { ok: false, error: "vault_locked" };456        }457        const { domain, includeAll, kind } = msg.payload as {458          domain: string;459          includeAll?: boolean;460          kind?: "login" | "card";461        };462        // kind="card": return saved cards as compact summaries for the463        // inline card silver platter. Cards are not domain-scoped — every464        // saved card is a candidate on every checkout page — so domain is465        // ignored when kind === "card".466        if (kind === "card") {467          const cards = vault.getEntries().filter((e) => e.type === "card");468          return {469            ok: true,470            data: cards.map((e) => ({471              id: e.id,472              title: e.cardNickname || e.title,473              cardholderName: e.cardholderName,474              last4: e.last4,475              expMonth: e.expMonth,476              expYear: e.expYear,477              network: e.network,478            })),479          };480        }481        // The inline selector fills username+password into a form. Passkey-482        // only entries have no password to fill; sign-in for those goes483        // through the WebAuthn path instead. Filter them out everywhere so484        // the user doesn't see four "GitHub" rows that mostly do nothing.485        // Notes and cards never belonged here either.486        const matches = (487          includeAll488            ? vault489                .getEntries()490                .filter((entry) => entry.type !== "note" && entry.type !== "card")491            : vault.queryDomain(domain)492        ).filter((entry) => !isPasskeyOnly(entry));493        return {494          ok: true,495          data: matches.map((e) =>496            includeAll497              ? {498                  id: e.id,499                  title: e.title,500                  hasPasskey: e.passkey !== undefined,501                }502              : {503                  id: e.id,504                  title: e.title,505                  username: e.username,506                  email: e.email,507                  url: e.url,508                  hasTotp: Boolean(e.totp),509                  hasPasskey: e.passkey !== undefined,510                }511          ),512        };513      }514      case "GET_ENTRY_FOR_FILL": {515        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };516        const { id } = msg.payload as { id: string };517        const entry = vault.getEntryById(id);518        if (!entry) return { ok: false, error: "entry_not_found" };519        // Passkey-only entries (passkey credential, no password) cannot be520        // filled into a form — sign-in goes through the WebAuthn path. A521        // login that ALSO has a passkey is still fillable for its password.522        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };523        // Strip the passkey credential from the response — content scripts524        // never need the private key, and there's no reason to expose the525        // public credential metadata over the boundary either.526        const { passkey: _strippedPasskey, ...safeEntry } = entry;527        return { ok: true, data: safeEntry };528      }529      case "COPY": {530        // AUD-002: shape-validate the payload before passing to the clipboard531        // helper. A raw cast lets a malformed message reach the clipboard API532        // with a non-string and throw.533        const { text, label, alreadyWritten } = (msg.payload ?? {}) as {534          text?: unknown;535          label?: unknown;536          alreadyWritten?: unknown;537        };538        if (typeof text !== "string" || typeof label !== "string") {539          return { ok: false, error: "invalid_payload" };540        }541        await copyToClipboard(text, label, Boolean(alreadyWritten));542        return { ok: true };543      }544      case "CHECK_ALL_BREACHES": {545        const allEntries = vault.getEntries();546        const results: Record<string, number> = {};547        for (const entry of allEntries) {548          if (entry.type === "note") continue;549          if (!entry.password) continue;550          results[entry.id] = await vault.checkBreach(entry.password);551          // Small delay — be a good citizen to the HIBP API552          await new Promise((r) => setTimeout(r, 200));553        }554        // Persist any non-zero counts back to entries555        for (const [id, count] of Object.entries(results)) {556          const entry = vault.getEntryById(id);557          if (entry && (entry.breach ?? 0) !== count) {558            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });559          }560        }561        return { ok: true, data: results };562      }563      case "GET_SETTINGS":564        return { ok: true, data: await vault.ensureSettingsLoaded() };565      case "UPDATE_SETTINGS": {566        const patch = msg.payload;567        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {568          return { ok: false, error: "invalid_payload" };569        }570        await vault.updateSettings(patch as vault.VaultSettings);571        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {572          await setupAutoLock();573          if (vault.isUnlocked()) touchAutoLock();574        }575        return { ok: true };576      }577      case "GET_PENDING_PASSKEY":578        return { ok: true, data: await getPendingPasskeyRequest() };579      case "APPROVE_PASSKEY": {580        const { requestId } = msg.payload as { requestId: number };581        await resolvePendingPasskeyRequest(requestId, true);582        return { ok: true };583      }584      case "DENY_PASSKEY": {585        const { requestId } = msg.payload as { requestId: number };586        await resolvePendingPasskeyRequest(requestId, false);587        return { ok: true };588      }589      case "GET_PASSKEY_PROVIDER_STATE":590        return { ok: true, data: await getPasskeyProviderState() };591      case "SET_PASSKEY_PROVIDER_ENABLED": {592        const { enabled } = msg.payload as { enabled: boolean };593        // Disabling is always free; gating fires only when a free user is594        // trying to turn passkey interception on.595        if (enabled) {596          const gate = await requirePro("passkeys");597          if (!gate.allowed) return { ok: false, error: "pro_required" };598        }599        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };600      }601      // AUD-003: this handler POSTs `entryTitle` to a user-configured HTTPS602      // endpoint. Intentional product behavior — users configure their own603      // dead-man's-switch. isAllowedCanaryWebhookUrl blocks localhost, private604      // IPs, and non-HTTPS schemes, but cannot defend against every DNS-605      // rebinding case. The UI under CanarySection (Entry.tsx) discloses to606      // users that the entry title leaves the device when the canary fires.607      case "FIRE_CANARY_PING": {608        const { webhookUrl, entryTitle, trigger } = msg.payload as {609          webhookUrl: string;610          entryTitle: string;611          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";612        };613        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {614          return { ok: false, error: "invalid_webhook_url" };615        }616        const body = JSON.stringify({617          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",618          entry: entryTitle,619          trigger,620          timestamp: new Date().toISOString(),621          source: "peach-extension",622        });623        if (trigger === "test") {624          // Permitted outbound fetch: user-configured canary alert endpoint625          // (validated by isAllowedCanaryWebhookUrl above). This is the626          // only non-HIBP outbound call in the extension — see627          // Projects.md §3.7. Test pings are awaited so the UI can show628          // success/failure.629          try {630            const res = await fetch(webhookUrl, {631              method: "POST",632              headers: { "Content-Type": "application/json" },633              body,634            });635            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };636          } catch (err) {637            return { ok: false, error: err instanceof Error ? err.message : "network_error" };638          }639        }640        // Non-test triggers are fire-and-forget641        fetch(webhookUrl, {642          method: "POST",643          headers: { "Content-Type": "application/json" },644          body,645        }).catch(() => {});646        return { ok: true };647      }648      case "ACTIVATE_LICENSE": {649        const { key } = msg.payload as { key: string };650        const licenseInfo = await activateLicense(key);651        return { ok: true, data: licenseInfo };652      }653      case "GET_LICENSE": {654        const licenseInfo = await getLicenseInfo();655        return { ok: true, data: licenseInfo };656      }657      case "GET_LICENSE_KEY": {658        const key = await getLicenseKey();659        return { ok: true, data: key };660      }661      case "DEACTIVATE_LICENSE": {662        await deactivateLicense();663        return { ok: true };664      }665      case "SHOULD_PLAY_CELEBRATION": {666        const should = await shouldPlayCelebration();667        return { ok: true, data: should };668      }669      case "MARK_CELEBRATION_PLAYED": {670        await markCelebrationPlayed();671        return { ok: true };672      }673      case "GET_CODEX_VAULT_DATA": {674        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the675        // popup navigates to the License section without further coordination.676        const gate = await requirePro("codex");677        if (!gate.allowed) return { ok: false, error: "pro_required" };678        return await handleGetCodexVaultData();679      }680      case "ESTIMATE_CODEX_PAGES": {681        const gate = await requirePro("codex");682        if (!gate.allowed) return { ok: false, error: "pro_required" };683        return await handleEstimateCodexPages();684      }685      case "RESTORE_FROM_CODEX": {686        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still687        // be able to restore a vault that was printed by a Pro user.688        // DO NOT add a Pro gate here.689        const payload = msg.payload as CodexRestorePayload;690        return await handleRestoreFromCodex(payload);691      }692      case "OPEN_PRO_GATE": {693        // Content script requests: open popup and navigate to License section.694        const { feature } = (msg.payload ?? {}) as { feature?: string };695        if (chrome.storage.session) {696          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });697        }698        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }699        return { ok: true };700      }701      case "GET_IDENTITIES": {702        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };703        return { ok: true, data: vault.getIdentities() };704      }705      case "TOUCH_AUTO_LOCK": {706        // touchAutoLock() is already called by shouldRefreshAutoLock above;707        // this case just gives the popup a typed message to keep the session alive.708        return { ok: true };709      }710      case "GET_ADVANCED_HEALTH_REPORT": {711        const gate = await requirePro("advanced_health");712        if (!gate.allowed) return { ok: false, error: "pro_required" };713        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };714        const report = await buildAdvancedHealthReport(vault.getEntries());715        return { ok: true, data: report };716      }717      case "INITIATE_PASSWORD_CHANGE": {718        const gate = await requirePro("smart_password_change");719        if (!gate.allowed) return { ok: false, error: "pro_required" };720        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };721        const { id } = msg.payload as { id: string };722        const entry = vault.getEntryById(id);723        if (!entry) return { ok: false, error: "entry_not_found" };724        const url = resolveResetUrl(entry);725        if (!url) return { ok: false, error: "no_reset_url" };726        try {727          await chrome.tabs.create({ url });728          return { ok: true, data: { url } };729        } catch (err) {730          return {731            ok: false,732            error: err instanceof Error ? err.message : "failed_to_open_tab",733          };734        }735      }736      case "IS_DURESS_ENABLED": {737        const enabled = await vault.isDuressEnabled();738        return { ok: true, data: enabled };739      }740      case "SETUP_DURESS": {741        const { duressPassword } = msg.payload as { duressPassword: string };742        await vault.setupDuress(duressPassword);743        return { ok: true };744      }745      case "DISABLE_DURESS": {746        await vault.disableDuress();747        return { ok: true };748      }749      case "VERIFY_MAIN_PASSWORD": {750        const { password } = msg.payload as { password: string };751        const ok = await vault.verifyMainPassword(password);752        return { ok: true, data: ok };753      }754      case "CHANGE_PASSWORD": {755        const { currentPassword, newPassword } = msg.payload as {756          currentPassword: string;757          newPassword: string;758        };759        const changed = await vault.changePassword(currentPassword, newPassword);760        return changed761          ? { ok: true }762          : { ok: false, error: "incorrect_current_password" };763      }764      case "GET_SITE_PASSWORD_POLICY": {765        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });766        if (!tab?.id) return { ok: true, data: null };767        try {768          const response = await chrome.tabs.sendMessage(tab.id, {769            type: "GET_SITE_PASSWORD_POLICY",770          });771          return (response as MessageResponse) ?? { ok: true, data: null };772        } catch {773          return { ok: true, data: null };774        }775      }776      case "RECORD_MANUAL_SUMMON": {777        const { domain } = msg.payload as { domain: string };778        const settings = vault.getSettings();779        const existing = settings.manualSummonDomains?.[domain];780        const now = Date.now();781        await vault.updateSettings({782          manualSummonDomains: {783            ...settings.manualSummonDomains,784            [domain]: {785              firstSummonedAt: existing?.firstSummonedAt ?? now,786              summonCount: (existing?.summonCount ?? 0) + 1,787              lastSummonedAt: now,788            },789          },790        });791        return { ok: true };792      }793      case "DECLINE_CARD_SAVE": {794        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };795        await vault.declineCardSaveOffer(last4, expMonth, expYear);796        return { ok: true };797      }798      case "IS_CARD_DECLINED": {799        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };800        const declined = await vault.isCardDeclined(last4, expMonth, expYear);801        return { ok: true, data: declined };802      }803      case "INITIATE_FIREFOX_PASSKEY_CREATE": {804        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {805          rpId?: string;806          rpName?: string;807          userName?: string;808          userDisplayName?: string;809        };810        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };811        return await initiateFirefoxPasskeyCreate({812          rpId,813          rpName: rpName ?? rpId,814          userName,815          userDisplayName,816        });817      }818819      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {820        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;821        if (!payload) return { ok: false, error: "missing_payload" };822        return await completeFirefoxPasskeyCreate(payload);823      }824825      case "PASSKEY_OFFER_DECLINE": {826        const { domain } = (msg.payload ?? {}) as { domain?: string };827        if (!domain) return { ok: false, error: "domain_required" };828        await recordPasskeyOfferDecline(domain);829        return { ok: true };830      }831832      case "GET_PASSKEY_OFFER_DECLINED": {833        const { domain } = (msg.payload ?? {}) as { domain?: string };834        if (!domain) return { ok: false, error: "domain_required" };835        return { ok: true, data: await isPasskeyOfferDeclined(domain) };836      }837838      case "PASSKEY_HAS_CREDENTIALS": {839        const payload = msg.payload as {840          rpId?: string;841          allowCredentials?: Array<{ id: string; type?: string }>;842        } | undefined;843        if (!payload?.rpId) return { ok: false, error: "rpid_required" };844        return await handlePasskeyHasCredentials({845          rpId: payload.rpId,846          allowCredentials: payload.allowCredentials ?? [],847        });848      }849850      case "PASSKEY_CREATE": {851        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;852        if (!payload?.rpId || !payload?.userName) {853          return { ok: false, error: "rpid_and_username_required" };854        }855        return await handleFirefoxPasskeyCreate(payload);856      }857858      case "PASSKEY_GET": {859        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;860        if (!payload?.rpId) return { ok: false, error: "rpid_required" };861        return await handleFirefoxPasskeyGet(payload);862      }863864      case "PASSKEY_AUTH_RESPONSE": {865        const { requestId, approved } = (msg.payload ?? {}) as {866          requestId?: string | number;867          approved?: boolean;868        };869        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {870          return { ok: false, error: 'requestId and approved required' };871        }872        await resolvePendingPasskeyRequest(Number(requestId), approved);873        return { ok: true };874      }875876      case "GET_PASSKEY_FOR_DOMAIN": {877        const { domain } = (msg.payload ?? {}) as { domain?: string };878        if (!domain) return { ok: false, error: "domain_required" };879        if (!vault.isUnlocked()) return { ok: true, data: null };880        const match = vault881          .getEntries()882          .find((entry) => entry.passkey?.rpId === domain);883        if (!match || !match.passkey) return { ok: true, data: null };884        // Slim shape — only the fields State 11 needs. Never expose private885        // key material, even though this is locked behind isUnlocked.886        return {887          ok: true,888          data: {889            rpId: match.passkey.rpId,890            userName: match.passkey.userName,891            browser: match.passkey.browser,892          },893        };894      }895896      case "DESTROY_VAULT": {897        // Irreversible by design. Lock zeroes the derived key + in-memory entries;898        // storage.local.clear() wipes every Peach key (slots, settings, license,899        // onboarded flag, history, sync state, declined cards, recall, etc.);900        // session.clear() wipes pending passkey requests + pro-notice queues.901        // Caller (Panic.tsx) handles UI navigation back to onboarding.902        vault.lock();903        await storageClear();904        await vault.clearVaultHistory();905        if (chrome.storage.session) {906          await chrome.storage.session.clear();907        }908        return { ok: true };909      }910911      case "SUBMIT_FEEDBACK": {912        const { category, message, version, browser } = msg.payload as {913          category: string;914          message: string;915          version: string;916          browser: string;917        };918        if (!message.trim()) return { ok: false, error: "message_empty" };919        if (!FEEDBACK_ENDPOINT) return { ok: true };920        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {921          return { ok: false, error: "invalid_feedback_endpoint" };922        }923        try {924          const res = await fetch(FEEDBACK_ENDPOINT, {925            method: "POST",926            headers: { "Content-Type": "application/json" },927            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),928          });929          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };930        } catch (err) {931          return { ok: false, error: err instanceof Error ? err.message : "network_error" };932        }933      }934      // Android-only: biometric unlock with pre-derived key.935      case "UNLOCK_WITH_KEY": {936        const { masterKeyHex } = msg.payload as { masterKeyHex: string };937        if (!isNativePlatform()) {938          return { ok: false, error: "desktop_only_uses_password" };939        }940        try {941          const result = await vault.unlockWithKey(masterKeyHex);942          if (result.ok) {943            onVaultUnlocked();944            await publishInMemoryVault(result.entries);945          }946          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };947        } catch {948          return { ok: false, error: "invalid_key" };949        }950      }951      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.952      case "GET_DERIVED_KEY": {953        if (!isNativePlatform()) {954          return { ok: false, error: "android_only" };955        }956        if (!vault.isUnlocked()) {957          return { ok: false, error: "vault_locked" };958        }959        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };960      }961      case "GET_IDENTITY_SUGGESTIONS": {962        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };963        const entries = vault.getEntries();964        const suggestions = buildIdentitySuggestions(entries);965        return { ok: true, data: { suggestions } };966      }967      case "POPULATE_INLINE_VAULT": {968        if (!isNativePlatform()) return { ok: false };969        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };970        const entries = vault.getEntries();971        await publishInMemoryVault(entries);972        return { ok: true };973      }974      case "ML_INIT":975        return { ok: true };976977      case "ML_PREDICT_BATCH": {978        // AUD-002: shape-validate before forwarding to the ML helper.979        const { featuresArray } = (msg.payload ?? {}) as { featuresArray?: unknown };980        if (!Array.isArray(featuresArray)) {981          return { ok: false, error: "invalid_payload" };982        }983        return { ok: true, data: mlPredictBatch(featuresArray as MLFieldFeatures[]) };984      }985986      // ── Chirp Sync (v3) ───────────────────────────────────────────────987      // Returns the public-facing local identity needed by the popup to988      // drive Phase-1 audio pairing. The private long-term key never989      // leaves the background.990      case "CHIRP_GET_LOCAL_IDENTITY": {991        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };992        const proCheck = await requirePro("sync");993        if (!proCheck.allowed) return { ok: false, error: "pro_required" };994        const masterKeyHex = vault.getDerivedKeyHex();995        const masterKey = unhexBytes(masterKeyHex);996        try {997          const identity = await buildLocalIdentity(masterKey);998          return { ok: true, data: identity };999        } finally {1000          masterKey.fill(0);1001        }1002      }10031004      case "CHIRP_COMPLETE_PAIRING": {1005        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1006        const proCheck = await requirePro("sync");1007        if (!proCheck.allowed) return { ok: false, error: "pro_required" };1008        const paired = (msg.payload as { paired?: unknown })?.paired;1009        if (typeof paired !== "object" || paired === null) {1010          return { ok: false, error: "invalid_payload" };1011        }1012        const candidate = paired as Record<string, unknown>;1013        if (1014          typeof candidate.deviceId !== "string" || !candidate.deviceId ||1015          typeof candidate.deviceName !== "string" || !candidate.deviceName ||1016          typeof candidate.deviceType !== "string" ||1017          typeof candidate.longTermPublicKeyHex !== "string" ||1018          !/^[0-9a-f]{64}$/.test(candidate.longTermPublicKeyHex) ||1019          typeof candidate.pairedAt !== "number"1020        ) {1021          return { ok: false, error: "invalid_paired_device" };1022        }1023        await upsertPairedDeviceV3(candidate as unknown as import("../shared/sync-types").PairedDevice);1024        return { ok: true };1025      }10261027      case "CHIRP_LIST_PAIRED_DEVICES": {1028        const devices = await listPairedDevicesV3();1029        return { ok: true, data: { devices } };1030      }10311032      case "CHIRP_UNPAIR_DEVICE": {1033        const { deviceId } = (msg.payload ?? {}) as { deviceId?: string };1034        if (typeof deviceId !== "string" || !deviceId) {1035          return { ok: false, error: "invalid_payload" };1036        }1037        await removePairedDeviceByIdV3(deviceId);1038        return { ok: true };1039      }10401041      case "CHIRP_RENAME_LOCAL_DEVICE": {1042        const { name } = (msg.payload ?? {}) as { name?: string };1043        if (typeof name !== "string") return { ok: false, error: "invalid_payload" };1044        await setDeviceNameV3(name);1045        return { ok: true };1046      }10471048      default:1049        return { ok: false, error: "unknown_message_type" };1050    }1051  } catch (err) {1052    return {1053      ok: false,1054      error: err instanceof Error ? err.message : "operation_failed",1055    };1056  }1057}10581059// --- Mobile platform helpers ---10601061// Android: populates the in-memory vault used by PeachAutofillService.1062async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1063  const plugin = nativePlugin<{1064    setEntries?: (args: {1065      entries: Array<{1066        id: string;1067        title: string;1068        username: string;1069        email: string;1070        password: string;1071        url: string;1072        totp: string;1073        additionalUrls: string[];1074      }>;1075    }) => Promise<void>;1076  }>("InMemoryVaultPlugin");1077  if (!plugin?.setEntries) return;1078  await plugin.setEntries({1079    entries: entries.map((e) => ({1080      id: e.id,1081      title: e.title ?? "",1082      username: e.username ?? "",1083      email: (e as VaultEntry & { email?: string }).email ?? "",1084      password: e.password ?? "",1085      url: e.url ?? "",1086      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1087      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1088    })),1089  });1090}10911092// Android: clear the autofill in-memory store on lock.1093async function clearInMemoryVault(): Promise<void> {1094  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1095  if (!plugin?.clearEntries) return;1096  await plugin.clearEntries();1097}10981099// Returns username use-counts from the vault, sorted by frequency. Each row1100// also carries the entry's email so the popup can suggest the email/username1101// pair the user has actually used together.1102function buildIdentitySuggestions(1103  entries: VaultEntry[],1104): Array<{ email: string; username: string; count: number }> {1105  const usernameCounts = new Map<string, number>();1106  const usernameEmail = new Map<string, string>();1107  for (const entry of entries) {1108    const username = entry.username ?? "";1109    const email = (entry as VaultEntry & { email?: string }).email ?? "";1110    if (!username && !email) continue;1111    const key = username || email;1112    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1113    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1114  }1115  return Array.from(usernameCounts.entries())1116    .sort((a, b) => b[1] - a[1])1117    .map(([username, count]) => ({1118      email: usernameEmail.get(username) ?? "",1119      username,1120      count,1121    }));1122}11231124/** Notify all content scripts that the vault just became available. */1125function broadcastToContentScripts(message: { type: string }): void {1126  if (!chrome.tabs?.query) return;1127  chrome.tabs.query({}, (tabs) => {1128    for (const tab of tabs) {1129      if (tab.id !== undefined) {1130        chrome.tabs.sendMessage(tab.id, message).catch(() => {1131          // Tab may not have a content script — silently ignore1132        });1133      }1134    }1135  });1136}11371138function shouldRefreshAutoLock(type: MessageType): boolean {1139  return (1140    type !== "HAS_VAULT" &&1141    type !== "IS_UNLOCKED" &&1142    type !== "GET_VAULT_STATUS" &&1143    type !== "LOCK" &&1144    type !== "UPDATE_SETTINGS" &&1145    type !== "GET_PENDING_PASSKEY" &&1146    type !== "GET_PASSKEY_PROVIDER_STATE" &&1147    type !== "DECLINE_CARD_SAVE" &&1148    type !== "IS_CARD_DECLINED" &&1149    type !== "SUBMIT_FEEDBACK"1150  );1151}11521153function isAllowedCanaryWebhookUrl(value: string): boolean {1154  try {1155    const url = new URL(value);1156    if (url.protocol !== "https:") return false;11571158    const hostname = url.hostname.toLowerCase();1159    if (1160      hostname === "localhost" ||1161      hostname.endsWith(".localhost") ||1162      isPrivateIpv4(hostname) ||1163      isPrivateIpv6(hostname)1164    ) {1165      return false;1166    }11671168    return true;1169  } catch {1170    return false;1171  }1172}11731174function isPrivateIpv4(hostname: string): boolean {1175  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1176    return true;1177  }11781179  const octets = hostname.split(".").map((part) => Number(part));1180  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1181    return false;1182  }11831184  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1185}11861187function isPrivateIpv6(hostname: string): boolean {1188  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1189  return (1190    normalized === "::1" ||1191    normalized.startsWith("fc") ||1192    normalized.startsWith("fd") ||1193    normalized.startsWith("fe80:")1194  );1195}