messages.ts

65.3 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 * as vault from "./vault";15import {16  handleEstimateCodexPages,17  handleGetCodexVaultData,18  handleRestoreFromCodex,19} from "./codex-handlers";20import type { CodexRestorePayload } from "../shared/codex-types";21import {22  activateLicense,23  deactivateLicense,24  getLicenseInfo,25  getLicenseKey,26  isProUser,27  markCelebrationPlayed,28  shouldPlayCelebration,29} from "./license";30import {31  completeFirefoxPasskeyCreate,32  getPasskeyProviderState,33  getPendingPasskeyRequest,34  handleFirefoxPasskeyCreate,35  handleFirefoxPasskeyGet,36  handlePasskeyHasCredentials,37  initiateFirefoxPasskeyCreate,38  isPasskeyOfferDeclined,39  onVaultUnlocked,40  recordPasskeyOfferDecline,41  resolvePendingPasskeyRequest,42  setPasskeyProviderEnabled,43} from "./passkey";44import { buildAdvancedHealthReport, resolveResetUrl } from "./health";45import { storageClear, storageGet } from "../shared/storage";46import { findInvalidWords } from "../shared/recovery-words";47import {48  addPairedDevice,49  addTrustedNetwork,50  clearIncomingPairingRequest,51  getIncomingPairingRequest,52  getPairedDevices,53  getTrustedNetworks,54  removePairedDevice,55  removeTrustedNetwork,56  setIncomingPairingRequest,57  updatePairedDevice,58} from "./sync-storage";59import { getCurrentNetwork, isOnTailscale } from "./sync-network";60import {61  consumeRecentPairing,62  setActivePairingToken,63} from "./pairing-server-state";64import type {65  Message,66  MessageResponse,67  MessageType,68  ProFeature,69  VaultEntry,70} from "../shared/types";71import { isPasskeyOnly } from "../shared/types";72import type { SyncStatus, SyncableDevice } from "../shared/sync-types";73import { isNativePlatform, nativePlugin } from "../shared/native";74import { runBlobSyncSession, type SyncResult } from "./sync-coordinator";75import type { SyncDeps } from "./sync-coordinator";76import { createWebSocketSyncTransport } from "../shared/websocket-sync-transport";77import { performResponderAuth, bytesToHex as noiseBytesToHex } from "../shared/noise-js";78import { getLocalSubnet, discoverDevice, scanForPairingPhone } from "../shared/local-network";79import { predictBatch as mlPredictBatch } from "./ml";80import type { MLFieldFeatures } from "../shared/ml";81import { base64ToBytes, bytesToBase64 } from "../shared/sync-wire";8283/**84 * The single Pro gate. Every gated handler calls this first; the broadcast85 * lets the popup react (navigate to the License section, highlight the86 * relevant feature). Background never touches the popup view directly —87 * the popup owns navigation. See Projects.md "Pro gate rule".88 */89async function requirePro(90  feature: ProFeature,91  trigger: "user" | "background" = "user"92): Promise<{ allowed: boolean }> {93  if (await isProUser()) return { allowed: true };9495  if (trigger === "user") {96    // User deliberately triggered this feature — redirect the popup immediately.97    chrome.runtime98      .sendMessage({ type: "PRO_GATE_TRIGGERED", payload: { feature } })99      .catch(() => {100        // Popup may be closed — the gate signal is best-effort.101      });102  } else {103    // Background trigger (e.g. passive sync initiation) — no popup is open.104    // Queue a notice so the next popup open shows a soft banner instead of105    // silently failing.106    if (chrome.storage.session) {107      chrome.storage.session108        .set({ pendingProNotice: { feature, triggeredAt: Date.now() } })109        .catch(() => {});110    }111  }112113  return { allowed: false };114}115116// ---------------------------------------------------------------------------117// 6-digit code pairing.118119const PAIRING_TOKEN_TTL_MS = 5 * 60 * 1000;120121122function generateSixDigitToken(): string {123  // crypto.getRandomValues, not Math.random — the token is the only secret124  // protecting the pairing window from a same-LAN attacker. 6 decimal digits125  // is 1 in 1,000,000; combined with a 5-minute TTL and pairing-mode gating126  // on the responder this is the right tradeoff between UX and security.127  const buf = new Uint32Array(1);128  crypto.getRandomValues(buf);129  const value = buf[0] % 1_000_000;130  return value.toString().padStart(6, "0");131}132133// ---------------------------------------------------------------------------134// Peer discovery glue (Phase 7 popup pairing flow).135136const PRIVATE_IPV4_RANGES = [137  { prefix: "10." },138  { prefix: "127." },139  { prefix: "169.254." },140  { prefix: "192.168." },141];142143// Empty disables network submission while the UI continues to function as a144// no-op (the handler returns ok:true without calling fetch). When set, the145// URL is validated by `isAllowedCanaryWebhookUrl` before any request, so the146// same private-IP/HTTPS rules that gate canary webhooks apply here.147const FEEDBACK_ENDPOINT = "";148149// ---------------------------------------------------------------------------150// Sync helpers151// ---------------------------------------------------------------------------152153/**154 * Short-lived registry of x25519 public keys that just completed a real Noise155 * NK handshake + initiator-auth proof. The PAIRING_COMPLETED handler must156 * find the supplied publicKeyHex here before it will call addPairedDevice —157 * otherwise an attacker could forge the message and pair an arbitrary key158 * (M13/SEC-005).159 *160 * Entries auto-expire after 30s. Each entry is consumed on first successful161 * PAIRING_COMPLETED so a single handshake cannot pair twice.162 */163const PENDING_PAIRS = new Map<string, ReturnType<typeof setTimeout>>();164const PENDING_PAIR_TTL_MS = 30_000;165166export function markPairingHandshakeVerified(publicKeyHex: string): void {167  if (!publicKeyHex) return;168  const existing = PENDING_PAIRS.get(publicKeyHex);169  if (existing) clearTimeout(existing);170  const t = setTimeout(() => PENDING_PAIRS.delete(publicKeyHex), PENDING_PAIR_TTL_MS);171  PENDING_PAIRS.set(publicKeyHex, t);172}173174function consumePendingPair(publicKeyHex: string): boolean {175  const t = PENDING_PAIRS.get(publicKeyHex);176  if (!t) return false;177  clearTimeout(t);178  PENDING_PAIRS.delete(publicKeyHex);179  return true;180}181182export function buildSyncDeps(): SyncDeps {183  return {184    isVaultUnlocked: () => vault.isUnlocked(),185    getVaultBlobForSync: async () => {186      const base = await vault.getVaultBlobForSync();187      if (!base) return null;188      const paired = await getPairedDevices();189      return {190        ...base,191        devices: paired192          .filter(d => d.x25519PublicKey)193          .map(d => ({194            publicKeyHex: d.x25519PublicKey,195            deviceName: d.displayName,196            pairedAt: d.pairedAt,197          })),198      };199    },200    applyIncomingVault: async (blob, ts, license, devices) => {201      const applied = await vault.applyIncomingVault(blob, ts, license);202      if (devices?.length) await mergeDeviceRegistry(devices);203      if (applied) {204        const reloaded = await vault.reloadEntriesAfterSync();205        if (!reloaded) {206          // The remote vault was encrypted under a different key (the remote207          // changed password). Our in-memory entries are now stale and cannot208          // be re-encrypted without overwriting the just-applied blob. Lock209          // to force a re-unlock with the new password (H3/COR-005).210          vault.lock();211          chrome.runtime212            .sendMessage({ type: "VAULT_RELOCK_AFTER_SYNC" })213            .catch(() => {});214        }215      }216      return applied;217    },218  };219}220221async function doVaultSync(ip: string, publicKeyHex: string): Promise<SyncResult> {222  // Defensive: refuse to drive a sync to a key not in the paired-devices223  // list. The WebSocket transport already authenticates the peer via Noise224  // NK + the initiator auth proof (H1), but pinning the key to the paired225  // set here makes "talk to anyone matching this static key" the only path226  // to vault application — there is no orphan-key window between pair and227  // sync (M11/COR-014).228  const paired = await getPairedDevices();229  if (!paired.some(d => d.x25519PublicKey === publicKeyHex)) {230    return { status: 'errored', applied: false, error: 'remote_not_paired' };231  }232  try {233    const identity = await vault.getSyncIdentity();234    const transport = await createWebSocketSyncTransport(235      `ws://${ip}:44100`,236      publicKeyHex,237      identity.privateKeyBytes,238      identity.publicKeyBytes,239    );240    const result = await runBlobSyncSession('initiator', transport, buildSyncDeps());241    // Reaching this point means createWebSocketSyncTransport completed both242    // the Noise NK handshake and the initiator-auth proof — the remote243    // proved possession of the matching static key (M13/SEC-005).244    if (result.status === 'completed') {245      markPairingHandshakeVerified(publicKeyHex);246    }247    return result;248  } catch (err) {249    return { status: 'errored', applied: false, error: String(err) };250  }251}252253async function mergeDeviceRegistry(incoming: SyncableDevice[]): Promise<void> {254  const existing = await getPairedDevices();255  const existingKeys = new Set(existing.map(d => d.x25519PublicKey));256  for (const device of incoming) {257    if (!existingKeys.has(device.publicKeyHex)) {258      await addPairedDevice({259        deviceId: device.publicKeyHex,260        displayName: device.deviceName,261        x25519PublicKey: device.publicKeyHex,262        pairedAt: device.pairedAt,263        lastSeenAt: 0,264        lastKnownIp: '',265      }).catch(() => {});266    }267  }268}269270// Background pairing scan — runs after START_PAIRING_SERVER fires on desktop.271// Scans the local subnet for a phone that has accepted the pairing token,272// stores it, runs the initial vault exchange, then notifies the popup.273async function runPairingSubnetScan(token: string): Promise<void> {274  const subnet = await getLocalSubnet();275  if (!subnet) return;276277  const found = await scanForPairingPhone(subnet, token);278  if (!found) return;279280  const { ip, publicKeyHex } = found;281282  try {283    await addPairedDevice({284      deviceId: publicKeyHex,285      displayName: 'Peach',286      x25519PublicKey: publicKeyHex,287      pairedAt: Date.now(),288      lastSeenAt: Date.now(),289      lastKnownIp: ip,290    });291  } catch {292    // Already paired — update IP293    await updatePairedDevice(publicKeyHex, { lastKnownIp: ip, lastSeenAt: Date.now() });294  }295296  // Immediate vault exchange — the free one-time transfer297  await doVaultSync(ip, publicKeyHex);298299  chrome.runtime.sendMessage({300    type: 'PAIRING_COMPLETED',301    payload: { deviceName: 'Peach', publicKeyHex, deviceIp: ip },302  }).catch(() => {});303}304305export function setupMessageHandler(): void {306  chrome.runtime.onMessage.addListener(307    (msg: unknown, sender, sendResponse) => {308      if (!isMessage(msg)) {309        sendResponse({ ok: false, error: "invalid_message" });310        return true;311      }312      handleMessage(msg, sender)313        .then(sendResponse)314        .catch((err) =>315          sendResponse({316            ok: false,317            error: err instanceof Error ? err.message : String(err),318          })319        );320      return true;321    }322  );323324  // Android: the chrome shim queues sendMessage calls until this handler is325  // registered. Without this hookup, every message hangs on Capacitor builds.326  // eslint-disable-next-line @typescript-eslint/no-explicit-any327  const reg = (globalThis as any).__peachRegisterMessageHandler;328  if (typeof reg === "function") {329    reg(async (m: unknown) => {330      if (!isMessage(m)) return { ok: false, error: "invalid_message" };331      try {332        return await handleMessage(m);333      } catch (err) {334        return {335          ok: false,336          error: err instanceof Error ? err.message : String(err),337        };338      }339    });340  }341342  // Android: subscribe to SyncPlugin events.343  if (isNativePlatform()) {344    const syncPlug = nativePlugin<{345      addListener: (346        event: string,347        handler: (data: Record<string, string>) => void348      ) => void;349    }>("SyncPlugin");350351    // Pairing probe answered — store the paired device (desktop, no IP needed352    // since the desktop never acts as a WS server).353    syncPlug?.addListener?.("peach:pair-probe-answered", (data) => {354      const deviceName = data.deviceName ?? "Peach";355      const publicKeyHex = data.publicKeyHex ?? "";356      // Native handled the pairing handshake — trust this entry into the357      // verified-handshake set (M13/SEC-005). The subsequent PAIRING_COMPLETED358      // message will consume it.359      if (publicKeyHex) markPairingHandshakeVerified(publicKeyHex);360      void (async () => {361        const { addPairedDevice, setHasPaired: setPaired } = await import("./sync-storage");362        await addPairedDevice({363          deviceId: publicKeyHex || (data.connectionId ?? "unknown"),364          displayName: deviceName,365          x25519PublicKey: publicKeyHex,366          pairedAt: Date.now(),367          lastSeenAt: Date.now(),368        }).catch(() => {});369        await setPaired();370        chrome.runtime.sendMessage({371          type: "PAIRING_COMPLETED",372          payload: { deviceName, publicKeyHex },373        }).catch(() => {});374      })();375    });376377    // Sync frame received — route to the waiting responder session.378    syncPlug?.addListener?.("peach:sync-frame", (data) => {379      const { connectionId, frame } = data;380      if (connectionId && frame) deliverAndroidSyncFrame(connectionId, frame);381    });382383    // Sync session started (SYNC_HELLO received by SyncPlugin) — dispatch as384    // a background message so SYNC_SESSION_STARTED handler runs the responder.385    syncPlug?.addListener?.("peach:sync-session-started", (data) => {386      const { connectionId } = data;387      if (!connectionId) return;388      void handleMessage({ type: "SYNC_SESSION_STARTED", payload: { connectionId } });389    });390  }391}392393function isMessage(m: unknown): m is Message {394  return typeof m === "object" && m !== null && "type" in m;395}396397export async function handleMessage(398  msg: Message,399  sender: Partial<chrome.runtime.MessageSender> = {}400): Promise<MessageResponse> {401  try {402    // Validate sender — only allow messages from our extension pages/scripts.403    // `sender.id` is undefined for messages originating from extension UI404    // (popup/options), which is legitimate; reject only when it is defined405    // and does not match our extension id.406    if (407      sender.id !== undefined &&408      sender.id !== chrome.runtime.id409    ) {410      return { ok: false, error: "invalid_sender" };411    }412413    if (shouldRefreshAutoLock(msg.type) && vault.isUnlocked()) {414      touchAutoLock();415    }416417    switch (msg.type) {418      case "CREATE_VAULT": {419        const { password } = msg.payload as { password: string };420        await vault.createVault(password);421        await setupAutoLock();422        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });423        onVaultUnlocked();424        return { ok: true };425      }426      case "UNLOCK": {427        const { password } = msg.payload as { password: string };428        const ok = await vault.unlock(password);429        if (ok) {430          await setupAutoLock();431          broadcastToContentScripts({ type: "VAULT_UNLOCKED" });432          onVaultUnlocked();433          if (isNativePlatform()) await publishInMemoryVault(vault.getEntries());434          return { ok: true };435        }436        // Distinguish corruption from wrong password so the popup can offer437        // a history-restore path instead of falsely accusing the user of438        // mistyping (M7/COR-007).439        const failure = vault.consumeLastUnlockFailureReason();440        if (failure) {441          return {442            ok: false,443            error: "vault_corrupted",444            canRestoreFromHistory: true,445          } as MessageResponse;446        }447        return { ok: false };448      }449      case "VALIDATE_RECOVERY_WORDS": {450        const { words } = msg.payload as { words: string[] };451        const invalid = findInvalidWords(words);452        return { ok: true, data: { valid: invalid.length === 0, invalid } };453      }454      case "GET_RECOVERY_WORDS": {455        // Must be unlocked and have recovery set up (vault must be v2.12+).456        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };457        try {458          const words = await vault.getRecoveryWords();459          return { ok: true, data: words };460        } catch (e) {461          // pre-v2.12 vault that hasn't migrated462          return { ok: false, error: "recovery_not_setup" };463        }464      }465      case "RECOVER_WITH_WORDS": {466        // User has lost their password but has their 12 recovery words.467        // We: (1) validate the words, (2) re-encrypt vault with new password.468        const { words, newPassword } = msg.payload as {469          words: string[];470          newPassword: string;471        };472        const stored = await vault.loadSlotA();473        if (!stored) return { ok: false, error: "no_vault" };474        if (!stored.recovery_salt || !stored.recovery_wrapped_root_key) {475          return { ok: false, error: "recovery_not_setup" };476        }477        // Unwrap the root key from the recovery escrow.478        try {479          await vault.unwrapRootKeyForRecovery(480            stored.recovery_wrapped_root_key,481            stored.recovery_nonce ?? "",482            stored.recovery_tag ?? "",483            stored.recovery_salt,484            words485          );486        } catch {487          return { ok: false, error: "invalid_recovery_words" };488        }489        // Re-key: derive fresh salt + key from new password.490        const newSalt = vault.generateSalt();491        const newKey = await vault.deriveKey(newPassword, newSalt);492        // Re-wrap root key under the new password's derived key so the same493        // recovery words continue to work after the password change.494        await vault.rewrapRootKeyForPassword(newKey, newSalt);495        // Re-encrypt vault entries with the new key.496        await vault.changePasswordWithNewKey(newSalt, newKey);497        await setupAutoLock();498        broadcastToContentScripts({ type: "VAULT_UNLOCKED" });499        return { ok: true };500      }501      case "LOCK":502        vault.lock();503        if (isNativePlatform()) await clearInMemoryVault();504        return { ok: true };505      case "IS_UNLOCKED":506        return { ok: true, data: vault.isUnlocked() };507      case "GET_VAULT_STATUS":508        return { ok: true, unlocked: vault.isUnlocked() };509      case "HAS_VAULT":510        return { ok: true, data: await vault.hasVault() };511      case "GET_ENTRIES":512        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };513        return { ok: true, data: vault.getEntries() };514      case "ADD_ENTRY": {515        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };516        const payload = msg.payload;517        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {518          return { ok: false, error: "invalid_payload" };519        }520        const entry = await vault.addEntry(payload as Parameters<typeof vault.addEntry>[0]);521        return { ok: true, data: entry };522      }523      case "BATCH_ADD_ENTRIES": {524        const payload = msg.payload as { entries?: unknown } | null | undefined;525        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {526          return { ok: false, error: "invalid_payload" };527        }528        if (!Array.isArray(payload.entries)) {529          return { ok: false, error: "invalid_payload" };530        }531        const added = await vault.batchAddEntries(payload.entries as Parameters<typeof vault.batchAddEntries>[0]);532        return { ok: true, data: added };533      }534      case "RESTORE_ENTRIES": {535        const payload = msg.payload as536          | { entries?: unknown; mode?: unknown; settings?: unknown }537          | null538          | undefined;539        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {540          return { ok: false, error: "invalid_payload" };541        }542        if (!Array.isArray(payload.entries)) {543          return { ok: false, error: "invalid_payload" };544        }545        if (payload.mode !== "replace" && payload.mode !== "merge") {546          return { ok: false, error: "invalid_payload" };547        }548        const summary = await vault.restoreEntries(549          payload.entries as Parameters<typeof vault.restoreEntries>[0],550          payload.mode551        );552        if (payload.settings && typeof payload.settings === "object" && !Array.isArray(payload.settings)) {553          await vault.updateSettings(payload.settings as vault.VaultSettings);554        }555        return { ok: true, data: summary };556      }557      case "CLEAR_VAULT_ENTRIES": {558        await vault.clearVaultEntries("REPLACE_ALL");559        return { ok: true };560      }561      case "GET_VAULT_HISTORY": {562        const snapshots = await vault.getVaultHistory();563        return { ok: true, data: snapshots };564      }565      case "RESTORE_VAULT_SNAPSHOT": {566        const { snapshotId } = msg.payload as { snapshotId: string };567        const result = await vault.restoreVaultSnapshot(snapshotId);568        if (!result.ok) return { ok: false, error: result.error };569        broadcastToContentScripts({ type: "VAULT_LOCKED" });570        return { ok: true };571      }572      case "COUNT_DUPLICATES": {573        return { ok: true, data: vault.countDuplicates() };574      }575      case "DEDUPLICATE_ENTRIES": {576        const removed = await vault.deduplicateEntries();577        return { ok: true, data: removed };578      }579      case "UPDATE_ENTRY": {580        const payload = msg.payload as { id?: unknown; patch?: unknown } | null | undefined;581        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {582          return { ok: false, error: "invalid_payload" };583        }584        const { id, patch } = payload;585        if (typeof id !== "string" || !id || !patch || typeof patch !== "object" || Array.isArray(patch)) {586          return { ok: false, error: "invalid_payload" };587        }588        await vault.updateEntry(id, patch as Parameters<typeof vault.updateEntry>[1]);589        return { ok: true };590      }591      case "ADD_ADDITIONAL_URL": {592        const { id, url } = msg.payload as { id: string; url: string };593        const trimmed = typeof url === "string" ? url.trim() : "";594        if (!trimmed) return { ok: false, error: "url_required" };595        const existing = vault.getEntryById(id);596        if (!existing) return { ok: false, error: "entry_not_found" };597        if (existing.type !== "login") return { ok: false, error: "login_entries_only" };598        const merged = [...(existing.additionalUrls ?? []), trimmed];599        await vault.updateEntry(id, { additionalUrls: merged });600        return { ok: true };601      }602      case "DELETE_ENTRY": {603        const { id } = msg.payload as { id: string };604        await vault.deleteEntry(id);605        return { ok: true };606      }607      case "GET_DELETED_ENTRIES":608        return { ok: true, data: vault.getDeletedEntries() };609      case "RESTORE_ENTRY": {610        const { id } = msg.payload as { id: string };611        await vault.restoreEntry(id);612        return { ok: true };613      }614      case "PURGE_ENTRY": {615        const { id } = msg.payload as { id: string };616        await vault.purgeEntry(id);617        return { ok: true };618      }619      case "PURGE_EXPIRED_TRASH": {620        const { retentionMs } = msg.payload as { retentionMs: number };621        const purged = await vault.purgeExpiredTrash(retentionMs);622        return { ok: true, data: purged };623      }624      case "SAVE_NOTE": {625        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };626        const { id, title, body } = msg.payload as { id?: string; title: string; body: string };627        const now = Date.now();628        if (id) {629          const existing = vault.getEntryById(id);630          if (!existing) return { ok: false, error: "not_found" };631          await vault.updateEntry(id, { title: title || "Untitled", notes: body, modifiedAt: now });632          return { ok: true, data: vault.getEntryById(id) };633        } else {634          const entry = await vault.addEntry({635            type: "note",636            title: title || "Untitled",637            notes: body,638            createdAt: now,639            modifiedAt: now,640          } as any);641          return { ok: true, data: entry };642        }643      }644      case "DELETE_NOTE": {645        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };646        const { id } = msg.payload as { id: string };647        await vault.deleteEntry(id);648        return { ok: true };649      }650      case "GET_NOTES": {651        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };652        const notes = vault.getEntries().filter(653          (e) => e.type === "note" && !e.deletedAt654        );655        return { ok: true, data: notes } as MessageResponse;656      }657      case "SEARCH_VAULT": {658        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };659        const { query } = msg.payload as { query: string };660        const q = query.toLowerCase();661        const searchResults = vault.getEntries().filter(662          (e) =>663            !e.deletedAt &&664            (e.title.toLowerCase().includes(q) ||665              e.notes?.toLowerCase().includes(q) ||666              e.username?.toLowerCase().includes(q))667        );668        return { ok: true, data: searchResults } as MessageResponse;669      }670      case "PAIRING_COMPLETED": {671        const { deviceName, publicKeyHex, deviceIp } = (msg.payload ?? {}) as {672          deviceName?: string;673          publicKeyHex?: string;674          deviceIp?: string;675        };676        if (!publicKeyHex) return { ok: false, error: "publickeyhex_required" };677        // Only accept publicKeyHex values that just completed a real Noise NK678        // handshake (initiator or responder side). Without this gate, anyone679        // who can sendMessage to the background can pair an arbitrary key680        // (M13/SEC-005). Re-confirming an already-paired device is allowed681        // so legitimate update-IP retries still work.682        const alreadyPaired = (await getPairedDevices()).some(683          d => d.x25519PublicKey === publicKeyHex,684        );685        const verified = consumePendingPair(publicKeyHex);686        if (!verified && !alreadyPaired) {687          return { ok: false, error: "pairing_not_verified" };688        }689        const { setHasPaired: setPaired } = await import("./sync-storage");690        await setPaired();691        try {692          await addPairedDevice({693            deviceId: publicKeyHex,694            displayName: deviceName ?? "Unknown",695            x25519PublicKey: publicKeyHex,696            pairedAt: Date.now(),697            lastSeenAt: Date.now(),698            lastKnownIp: deviceIp,699          });700        } catch {701          // Already paired — update IP if provided702          if (deviceIp) {703            await updatePairedDevice(publicKeyHex, { lastKnownIp: deviceIp, lastSeenAt: Date.now() });704          }705        }706        return { ok: true };707      }708      case "AUTOFILL_QUERY": {709        if (!vault.isUnlocked()) {710          return { ok: false, error: "vault_locked" };711        }712        const { domain, includeAll, kind } = msg.payload as {713          domain: string;714          includeAll?: boolean;715          kind?: "login" | "card";716        };717        // kind="card": return saved cards as compact summaries for the718        // inline card silver platter. Cards are not domain-scoped — every719        // saved card is a candidate on every checkout page — so domain is720        // ignored when kind === "card".721        if (kind === "card") {722          const cards = vault.getEntries().filter((e) => e.type === "card");723          return {724            ok: true,725            data: cards.map((e) => ({726              id: e.id,727              title: e.cardNickname || e.title,728              cardholderName: e.cardholderName,729              last4: e.last4,730              expMonth: e.expMonth,731              expYear: e.expYear,732              network: e.network,733            })),734          };735        }736        // The inline selector fills username+password into a form. Passkey-737        // only entries have no password to fill; sign-in for those goes738        // through the WebAuthn path instead. Filter them out everywhere so739        // the user doesn't see four "GitHub" rows that mostly do nothing.740        // Notes and cards never belonged here either.741        const matches = (742          includeAll743            ? vault744                .getEntries()745                .filter((entry) => entry.type !== "note" && entry.type !== "card")746            : vault.queryDomain(domain)747        ).filter((entry) => !isPasskeyOnly(entry));748        return {749          ok: true,750          data: matches.map((e) =>751            includeAll752              ? {753                  id: e.id,754                  title: e.title,755                  hasPasskey: e.passkey !== undefined,756                }757              : {758                  id: e.id,759                  title: e.title,760                  username: e.username,761                  email: e.email,762                  url: e.url,763                  hasTotp: Boolean(e.totp),764                  hasPasskey: e.passkey !== undefined,765                }766          ),767        };768      }769      case "GET_ENTRY_FOR_FILL": {770        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };771        const { id } = msg.payload as { id: string };772        const entry = vault.getEntryById(id);773        if (!entry) return { ok: false, error: "entry_not_found" };774        // Passkey-only entries (passkey credential, no password) cannot be775        // filled into a form — sign-in goes through the WebAuthn path. A776        // login that ALSO has a passkey is still fillable for its password.777        if (isPasskeyOnly(entry)) return { ok: false, error: "passkey_not_fillable" };778        // Strip the passkey credential from the response — content scripts779        // never need the private key, and there's no reason to expose the780        // public credential metadata over the boundary either.781        const { passkey: _strippedPasskey, ...safeEntry } = entry;782        return { ok: true, data: safeEntry };783      }784      case "COPY": {785        const { text, label, alreadyWritten } = msg.payload as {786          text: string;787          label: string;788          alreadyWritten?: boolean;789        };790        await copyToClipboard(text, label, Boolean(alreadyWritten));791        return { ok: true };792      }793      case "CHECK_ALL_BREACHES": {794        const allEntries = vault.getEntries();795        const results: Record<string, number> = {};796        for (const entry of allEntries) {797          if (entry.type === "note") continue;798          if (!entry.password) continue;799          results[entry.id] = await vault.checkBreach(entry.password);800          // Small delay — be a good citizen to the HIBP API801          await new Promise((r) => setTimeout(r, 200));802        }803        // Persist any non-zero counts back to entries804        for (const [id, count] of Object.entries(results)) {805          const entry = vault.getEntryById(id);806          if (entry && (entry.breach ?? 0) !== count) {807            await vault.updateEntry(id, { breach: count > 0 ? count : undefined });808          }809        }810        return { ok: true, data: results };811      }812      case "GET_SETTINGS":813        return { ok: true, data: await vault.ensureSettingsLoaded() };814      case "UPDATE_SETTINGS": {815        const patch = msg.payload;816        if (!patch || typeof patch !== "object" || Array.isArray(patch)) {817          return { ok: false, error: "invalid_payload" };818        }819        await vault.updateSettings(patch as vault.VaultSettings);820        if (typeof (patch as Record<string, unknown>).autoLockMinutes === "number") {821          await setupAutoLock();822          if (vault.isUnlocked()) touchAutoLock();823        }824        return { ok: true };825      }826      case "GET_PENDING_PASSKEY":827        return { ok: true, data: await getPendingPasskeyRequest() };828      case "APPROVE_PASSKEY": {829        const { requestId } = msg.payload as { requestId: number };830        await resolvePendingPasskeyRequest(requestId, true);831        return { ok: true };832      }833      case "DENY_PASSKEY": {834        const { requestId } = msg.payload as { requestId: number };835        await resolvePendingPasskeyRequest(requestId, false);836        return { ok: true };837      }838      case "GET_PASSKEY_PROVIDER_STATE":839        return { ok: true, data: await getPasskeyProviderState() };840      case "SET_PASSKEY_PROVIDER_ENABLED": {841        const { enabled } = msg.payload as { enabled: boolean };842        // Disabling is always free; gating fires only when a free user is843        // trying to turn passkey interception on.844        if (enabled) {845          const gate = await requirePro("passkeys");846          if (!gate.allowed) return { ok: false, error: "pro_required" };847        }848        return { ok: true, data: await setPasskeyProviderEnabled(enabled) };849      }850      case "FIRE_CANARY_PING": {851        const { webhookUrl, entryTitle, trigger } = msg.payload as {852          webhookUrl: string;853          entryTitle: string;854          trigger: "password_copied" | "username_copied" | "autofilled" | "submitted" | "test";855        };856        if (!isAllowedCanaryWebhookUrl(webhookUrl)) {857          return { ok: false, error: "invalid_webhook_url" };858        }859        const body = JSON.stringify({860          event: trigger === "test" ? "peach_canary_test" : "peach_canary_accessed",861          entry: entryTitle,862          trigger,863          timestamp: new Date().toISOString(),864          source: "peach-extension",865        });866        if (trigger === "test") {867          // Permitted outbound fetch: user-configured canary alert endpoint868          // (validated by isAllowedCanaryWebhookUrl above). This is the869          // only non-HIBP outbound call in the extension — see870          // Projects.md §3.7. Test pings are awaited so the UI can show871          // success/failure.872          try {873            const res = await fetch(webhookUrl, {874              method: "POST",875              headers: { "Content-Type": "application/json" },876              body,877            });878            return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };879          } catch (err) {880            return { ok: false, error: err instanceof Error ? err.message : "network_error" };881          }882        }883        // Non-test triggers are fire-and-forget884        fetch(webhookUrl, {885          method: "POST",886          headers: { "Content-Type": "application/json" },887          body,888        }).catch(() => {});889        return { ok: true };890      }891      case "ACTIVATE_LICENSE": {892        const { key } = msg.payload as { key: string };893        const licenseInfo = await activateLicense(key);894        return { ok: true, data: licenseInfo };895      }896      case "GET_LICENSE": {897        const licenseInfo = await getLicenseInfo();898        return { ok: true, data: licenseInfo };899      }900      case "GET_LICENSE_KEY": {901        const key = await getLicenseKey();902        return { ok: true, data: key };903      }904      case "DEACTIVATE_LICENSE": {905        await deactivateLicense();906        return { ok: true };907      }908      case "SHOULD_PLAY_CELEBRATION": {909        const should = await shouldPlayCelebration();910        return { ok: true, data: should };911      }912      case "MARK_CELEBRATION_PLAYED": {913        await markCelebrationPlayed();914        return { ok: true };915      }916      case "GET_CODEX_VAULT_DATA": {917        // Pro-gated. requirePro broadcasts PRO_GATE_TRIGGERED on miss so the918        // popup navigates to the License section without further coordination.919        const gate = await requirePro("codex");920        if (!gate.allowed) return { ok: false, error: "pro_required" };921        return await handleGetCodexVaultData();922      }923      case "ESTIMATE_CODEX_PAGES": {924        const gate = await requirePro("codex");925        if (!gate.allowed) return { ok: false, error: "pro_required" };926        return await handleEstimateCodexPages();927      }928      case "RESTORE_FROM_CODEX": {929        // !! IMPORTANT: intentionally NOT Pro-gated. A free device must still930        // be able to restore a vault that was printed by a Pro user.931        // DO NOT add a Pro gate here.932        const payload = msg.payload as CodexRestorePayload;933        return await handleRestoreFromCodex(payload);934      }935      case "OPEN_PRO_GATE": {936        // Content script requests: open popup and navigate to License section.937        const { feature } = (msg.payload ?? {}) as { feature?: string };938        if (chrome.storage.session) {939          await chrome.storage.session.set({ pendingProGate: { feature: feature ?? "passkeys" } });940        }941        try { await chrome.action.openPopup(); } catch { /* badge fallback */ }942        return { ok: true };943      }944      case "GET_IDENTITIES": {945        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };946        return { ok: true, data: vault.getIdentities() };947      }948      case "TOUCH_AUTO_LOCK": {949        // touchAutoLock() is already called by shouldRefreshAutoLock above;950        // this case just gives the popup a typed message to keep the session alive.951        return { ok: true };952      }953      case "GET_ADVANCED_HEALTH_REPORT": {954        const gate = await requirePro("advanced_health");955        if (!gate.allowed) return { ok: false, error: "pro_required" };956        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };957        const report = await buildAdvancedHealthReport(vault.getEntries());958        return { ok: true, data: report };959      }960      case "INITIATE_PASSWORD_CHANGE": {961        const gate = await requirePro("smart_password_change");962        if (!gate.allowed) return { ok: false, error: "pro_required" };963        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };964        const { id } = msg.payload as { id: string };965        const entry = vault.getEntryById(id);966        if (!entry) return { ok: false, error: "entry_not_found" };967        const url = resolveResetUrl(entry);968        if (!url) return { ok: false, error: "no_reset_url" };969        try {970          await chrome.tabs.create({ url });971          return { ok: true, data: { url } };972        } catch (err) {973          return {974            ok: false,975            error: err instanceof Error ? err.message : "failed_to_open_tab",976          };977        }978      }979      case "IS_DURESS_ENABLED": {980        const enabled = await vault.isDuressEnabled();981        return { ok: true, data: enabled };982      }983      case "SETUP_DURESS": {984        const { duressPassword } = msg.payload as { duressPassword: string };985        await vault.setupDuress(duressPassword);986        return { ok: true };987      }988      case "DISABLE_DURESS": {989        await vault.disableDuress();990        return { ok: true };991      }992      case "VERIFY_MAIN_PASSWORD": {993        const { password } = msg.payload as { password: string };994        const ok = await vault.verifyMainPassword(password);995        return { ok: true, data: ok };996      }997      case "CHANGE_PASSWORD": {998        const { currentPassword, newPassword } = msg.payload as {999          currentPassword: string;1000          newPassword: string;1001        };1002        const changed = await vault.changePassword(currentPassword, newPassword);1003        return changed1004          ? { ok: true }1005          : { ok: false, error: "incorrect_current_password" };1006      }1007      case "GET_SITE_PASSWORD_POLICY": {1008        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1009        if (!tab?.id) return { ok: true, data: null };1010        try {1011          const response = await chrome.tabs.sendMessage(tab.id, {1012            type: "GET_SITE_PASSWORD_POLICY",1013          });1014          return (response as MessageResponse) ?? { ok: true, data: null };1015        } catch {1016          return { ok: true, data: null };1017        }1018      }1019      case "GET_SYNC_STATE": {1020        const pairedDevices = await getPairedDevices();1021        const trustedNetworks = await getTrustedNetworks();1022        const tailscale = await isOnTailscale();1023        const pro = await isProUser();10241025        let status: SyncStatus = "offline";1026        if (tailscale || trustedNetworks.some((n: { isTailscale?: boolean }) => !n.isTailscale)) {1027          if (pairedDevices.length === 0) {1028            status = "no_peers";1029          } else {1030            status = "synced";1031          }1032        } else {1033          status = "not_trusted";1034        }10351036        const lastSyncRaw = await storageGet("peach_last_sync_at");1037        const lastSyncParsed = lastSyncRaw ? Number.parseInt(lastSyncRaw, 10) : NaN;1038        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : undefined;10391040        return { ok: true, data: { pairedDevices, trustedNetworks, status, lastSyncAt, isPro: pro } };1041      }1042      case "GET_PAIRED_DEVICES": {1043        const devices = await getPairedDevices();1044        return { ok: true, data: { devices } };1045      }1046      case "GET_SYNC_STATUS": {1047        const lastSyncRaw = await storageGet("peach_last_sync_at");1048        const lastSyncParsed = lastSyncRaw ? parseInt(lastSyncRaw, 10) : NaN;1049        const lastSyncAt = Number.isFinite(lastSyncParsed) ? lastSyncParsed : null;1050        const status: 'up_to_date' | 'never' = lastSyncAt ? 'up_to_date' : 'never';1051        return { ok: true, data: { status, lastSyncAt } };1052      }1053      case "ACCEPT_PAIRING": {1054        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.1055        return { ok: true };1056      }1057      case "REMOVE_PAIRED_DEVICE": {1058        const { deviceId } = msg.payload as { deviceId: string };1059        await removePairedDevice(deviceId);1060        return { ok: true };1061      }1062      case "REMOVE_TRUSTED_NETWORK": {1063        const payload = msg.payload as1064          | { ssid?: unknown; bssid?: unknown; isTailscale?: unknown }1065          | null1066          | undefined;1067        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {1068          return { ok: false, error: "invalid_payload" };1069        }1070        const { ssid, bssid, isTailscale } = payload as { ssid?: string; bssid?: string; isTailscale?: boolean };1071        const networks = await getTrustedNetworks();1072        const network = networks.find((n: { ssid?: string; bssid?: string; isTailscale?: boolean }) => 1073          (isTailscale ? n.isTailscale : n.ssid === ssid) && 1074          (!bssid || n.bssid === bssid)1075        );1076        if (network) {1077          await removeTrustedNetwork(network.addedAt);1078        }1079        return { ok: true };1080      }1081      case "MARK_NETWORK_TRUSTED": {1082        const network = await getCurrentNetwork();1083        await addTrustedNetwork({1084          ssid: network.ssid,1085          bssid: network.bssid,1086          isTailscale: network.isTailscale,1087          addedAt: Date.now(),1088        });1089        return { ok: true };1090      }1091      case "GET_INCOMING_PAIRING_REQUEST": {1092        const request = await getIncomingPairingRequest();1093        return { ok: true, data: request };1094      }1095      case "RESPOND_INCOMING_PAIRING": {1096        const { accept } = msg.payload as { accept: boolean };1097        const request = await getIncomingPairingRequest();1098        if (!request) return { ok: false, error: "no_pending_request" };1099        if (Date.now() > request.expiresAt) {1100          await clearIncomingPairingRequest();1101          return { ok: false, error: "expired" };1102        }1103        await clearIncomingPairingRequest();1104        if (accept) {1105          await addPairedDevice({1106            deviceId: request.publicKeyHex,1107            displayName: request.deviceName,1108            x25519PublicKey: request.publicKeyHex,1109            pairedAt: Date.now(),1110            lastSeenAt: Date.now(),1111          });1112        }1113        return { ok: true, data: { accepted: accept, deviceName: request.deviceName } };1114      }1115      case "START_PAIRING_SERVER": {1116        // One-time mobile→desktop transfer is free; only continuous sync gates on Pro.1117        const token = generateSixDigitToken();1118        const expiresAt = Date.now() + PAIRING_TOKEN_TTL_MS;1119        await setActivePairingToken({ token, expiresAt });1120        // Fire-and-forget subnet scan — finds the phone after it scans the QR1121        // and calls SCAN_PAIRING_QR to register the token with SyncPlugin.1122        if (!isNativePlatform()) {1123          void runPairingSubnetScan(token);1124        }1125        return { ok: true, data: { token, expiresAt } };1126      }1127      case "STOP_PAIRING_SERVER": {1128        try {1129          await setActivePairingToken(null);1130        } catch { /* best-effort */ }1131        return { ok: true };1132      }1133      case "GET_RECENT_PAIRING": {1134        const recent = await consumeRecentPairing();1135        return { ok: true, data: recent };1136      }1137      case "DEBUG_INJECT_INCOMING_PAIRING": {1138        // M14/SEC-007: blocked in production builds. The handler exists for1139        // Phase 7 banner UX rehearsal without a live native host; shipping1140        // it in production lets any background-message sender inject a1141        // synthetic pairing prompt. Allowed in 'development' and 'test'1142        // modes; vite sets MODE='production' for release builds.1143        if (import.meta.env.MODE === "production") {1144          return { ok: false, error: "not_available" };1145        }1146        const { deviceName, publicKeyHex } = (msg.payload ?? {}) as {1147          deviceName?: string;1148          publicKeyHex?: string;1149        };1150        if (!deviceName || !publicKeyHex) {1151          return { ok: false, error: "missing_payload" };1152        }1153        const now = Date.now();1154        await setIncomingPairingRequest({1155          deviceName,1156          publicKeyHex,1157          receivedAt: now,1158          expiresAt: now + 60_000,1159        });1160        return { ok: true };1161      }1162      case "RESET_SYNC_IDENTITY": {1163        const gate = await requirePro("sync");1164        if (!gate.allowed) return { ok: false, error: "pro_required" };1165        const devices = await getPairedDevices();1166        for (const device of devices) {1167          await removePairedDevice(device.deviceId);1168        }1169        return { ok: true, data: { removedDevices: devices.length, nativePublicKey: null } };1170      }1171      case "RECORD_MANUAL_SUMMON": {1172        const { domain } = msg.payload as { domain: string };1173        const settings = vault.getSettings();1174        const existing = settings.manualSummonDomains?.[domain];1175        const now = Date.now();1176        await vault.updateSettings({1177          manualSummonDomains: {1178            ...settings.manualSummonDomains,1179            [domain]: {1180              firstSummonedAt: existing?.firstSummonedAt ?? now,1181              summonCount: (existing?.summonCount ?? 0) + 1,1182              lastSummonedAt: now,1183            },1184          },1185        });1186        return { ok: true };1187      }1188      case "DECLINE_CARD_SAVE": {1189        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1190        await vault.declineCardSaveOffer(last4, expMonth, expYear);1191        return { ok: true };1192      }1193      case "IS_CARD_DECLINED": {1194        const { last4, expMonth, expYear } = msg.payload as { last4: string; expMonth: string; expYear: string };1195        const declined = await vault.isCardDeclined(last4, expMonth, expYear);1196        return { ok: true, data: declined };1197      }1198      case "INITIATE_FIREFOX_PASSKEY_CREATE": {1199        const { rpId, rpName, userName, userDisplayName } = (msg.payload ?? {}) as {1200          rpId?: string;1201          rpName?: string;1202          userName?: string;1203          userDisplayName?: string;1204        };1205        if (!rpId || !userName) return { ok: false, error: "rpid_and_username_required" };1206        return await initiateFirefoxPasskeyCreate({1207          rpId,1208          rpName: rpName ?? rpId,1209          userName,1210          userDisplayName,1211        });1212      }12131214      case "COMPLETE_FIREFOX_PASSKEY_CREATE": {1215        const payload = msg.payload as Parameters<typeof completeFirefoxPasskeyCreate>[0] | undefined;1216        if (!payload) return { ok: false, error: "missing_payload" };1217        return await completeFirefoxPasskeyCreate(payload);1218      }12191220      case "PASSKEY_OFFER_DECLINE": {1221        const { domain } = (msg.payload ?? {}) as { domain?: string };1222        if (!domain) return { ok: false, error: "domain_required" };1223        await recordPasskeyOfferDecline(domain);1224        return { ok: true };1225      }12261227      case "GET_PASSKEY_OFFER_DECLINED": {1228        const { domain } = (msg.payload ?? {}) as { domain?: string };1229        if (!domain) return { ok: false, error: "domain_required" };1230        return { ok: true, data: await isPasskeyOfferDeclined(domain) };1231      }12321233      case "PASSKEY_HAS_CREDENTIALS": {1234        const payload = msg.payload as {1235          rpId?: string;1236          allowCredentials?: Array<{ id: string; type?: string }>;1237        } | undefined;1238        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1239        return await handlePasskeyHasCredentials({1240          rpId: payload.rpId,1241          allowCredentials: payload.allowCredentials ?? [],1242        });1243      }12441245      case "PASSKEY_CREATE": {1246        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyCreate>[0] | undefined;1247        if (!payload?.rpId || !payload?.userName) {1248          return { ok: false, error: "rpid_and_username_required" };1249        }1250        return await handleFirefoxPasskeyCreate(payload);1251      }12521253      case "PASSKEY_GET": {1254        const payload = msg.payload as Parameters<typeof handleFirefoxPasskeyGet>[0] | undefined;1255        if (!payload?.rpId) return { ok: false, error: "rpid_required" };1256        return await handleFirefoxPasskeyGet(payload);1257      }12581259      case "PASSKEY_AUTH_RESPONSE": {1260        const { requestId, approved } = (msg.payload ?? {}) as {1261          requestId?: string | number;1262          approved?: boolean;1263        };1264        if (requestId === undefined || requestId === null || typeof approved !== 'boolean') {1265          return { ok: false, error: 'requestId and approved required' };1266        }1267        await resolvePendingPasskeyRequest(Number(requestId), approved);1268        return { ok: true };1269      }12701271      case "GET_PASSKEY_FOR_DOMAIN": {1272        const { domain } = (msg.payload ?? {}) as { domain?: string };1273        if (!domain) return { ok: false, error: "domain_required" };1274        if (!vault.isUnlocked()) return { ok: true, data: null };1275        const match = vault1276          .getEntries()1277          .find((entry) => entry.passkey?.rpId === domain);1278        if (!match || !match.passkey) return { ok: true, data: null };1279        // Slim shape — only the fields State 11 needs. Never expose private1280        // key material, even though this is locked behind isUnlocked.1281        return {1282          ok: true,1283          data: {1284            rpId: match.passkey.rpId,1285            userName: match.passkey.userName,1286            browser: match.passkey.browser,1287          },1288        };1289      }12901291      case "DESTROY_VAULT": {1292        // Irreversible by design. Lock zeroes the derived key + in-memory entries;1293        // storage.local.clear() wipes every Peach key (slots, settings, license,1294        // onboarded flag, history, sync state, declined cards, recall, etc.);1295        // session.clear() wipes pending passkey requests + pro-notice queues.1296        // Caller (Panic.tsx) handles UI navigation back to onboarding.1297        vault.lock();1298        await storageClear();1299        await vault.clearVaultHistory();1300        if (chrome.storage.session) {1301          await chrome.storage.session.clear();1302        }1303        return { ok: true };1304      }13051306      case "SUBMIT_FEEDBACK": {1307        const { category, message, version, browser } = msg.payload as {1308          category: string;1309          message: string;1310          version: string;1311          browser: string;1312        };1313        if (!message.trim()) return { ok: false, error: "message_empty" };1314        if (!FEEDBACK_ENDPOINT) return { ok: true };1315        if (!isAllowedCanaryWebhookUrl(FEEDBACK_ENDPOINT)) {1316          return { ok: false, error: "invalid_feedback_endpoint" };1317        }1318        try {1319          const res = await fetch(FEEDBACK_ENDPOINT, {1320            method: "POST",1321            headers: { "Content-Type": "application/json" },1322            body: JSON.stringify({ category, message, version, browser, source: "peach-extension" }),1323          });1324          return { ok: res.ok, error: res.ok ? undefined : `HTTP ${res.status}` };1325        } catch (err) {1326          return { ok: false, error: err instanceof Error ? err.message : "network_error" };1327        }1328      }1329      case "TRIGGER_SYNC": {1330        const gate = await requirePro("sync");1331        if (!gate.allowed) return { ok: false, error: "pro_required" };1332        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };13331334        if (isNativePlatform()) {1335          // Phone is the server — ensure it's listening for desktop connections.1336          syncBridge()?.ensureServerRunning?.();1337          return { ok: true, data: { syncedCount: 0, mode: "server" as const } };1338        }13391340        // Desktop: iterate all paired devices and sync with each.1341        const paired = await getPairedDevices();1342        if (!paired.length) return { ok: true, data: { syncedCount: 0, reason: "no_paired_devices" } };13431344        const subnet = await getLocalSubnet();1345        const results: Array<{ device: string } & SyncResult> = [];13461347        for (const device of paired) {1348          if (!device.x25519PublicKey) continue;13491350          let result: SyncResult;13511352          // Fast path — use last known IP1353          if (device.lastKnownIp) {1354            result = await doVaultSync(device.lastKnownIp, device.x25519PublicKey);1355          } else {1356            result = { status: 'errored', applied: false, error: 'no_ip' };1357          }13581359          // Discovery path — scan if fast path failed1360          if (result.status === 'errored' && subnet) {1361            const newIp = await discoverDevice(subnet, device.x25519PublicKey);1362            if (newIp) {1363              await updatePairedDevice(device.x25519PublicKey, { lastKnownIp: newIp });1364              result = await doVaultSync(newIp, device.x25519PublicKey);1365            }1366          }13671368          if (result.status === 'completed') {1369            await updatePairedDevice(device.x25519PublicKey, {1370              lastSeenAt: Date.now(),1371              lastSyncAt: Date.now(),1372            });1373          }13741375          results.push({ device: device.displayName, ...result });1376        }13771378        const syncedCount = results.filter(r => r.status === 'completed').length;1379        if (syncedCount > 0) {1380          await chrome.storage.local.set({ peach_last_sync_at: String(Date.now()) });1381        }1382        return { ok: true, data: { syncedCount, results } };1383      }1384      // Android-only: biometric unlock with pre-derived key.1385      case "UNLOCK_WITH_KEY": {1386        const { masterKeyHex } = msg.payload as { masterKeyHex: string };1387        if (!isNativePlatform()) {1388          return { ok: false, error: "desktop_only_uses_password" };1389        }1390        try {1391          const result = await vault.unlockWithKey(masterKeyHex);1392          if (result.ok) {1393            onVaultUnlocked();1394            await publishInMemoryVault(result.entries);1395          }1396          return { ok: result.ok, data: result.ok ? { entries: result.entries } : undefined, error: result.ok ? undefined : result.error };1397        } catch {1398          return { ok: false, error: "invalid_key" };1399        }1400      }1401      // Android: returns current in-memory derived key as hex. Used by biometric enable flow.1402      case "GET_DERIVED_KEY": {1403        if (!isNativePlatform()) {1404          return { ok: false, error: "android_only" };1405        }1406        if (!vault.isUnlocked()) {1407          return { ok: false, error: "vault_locked" };1408        }1409        return { ok: true, data: { masterKeyHex: vault.getDerivedKeyHex() } };1410      }1411      // Android: scanned a QR containing a desktop pairing token.1412      case "SCAN_PAIRING_QR": {1413        if (!isNativePlatform()) {1414          return { ok: false, error: "android_only" };1415        }1416        const { token } = msg.payload as { token: string };1417        syncBridge()?.startPairingSession?.({ token });1418        return { ok: true };1419      }1420      // Android: desktop opened a sync connection to the phone's WS server.1421      // Run the responder side of the vault exchange.1422      case "SYNC_SESSION_STARTED": {1423        if (!isNativePlatform()) return { ok: false };1424        if (!vault.isUnlocked()) {1425          return { ok: false, error: "vault_locked" };1426        }1427        const { connectionId } = (msg.payload ?? {}) as { connectionId?: string };1428        if (!connectionId) return { ok: false, error: "missing_connection_id" };14291430        const transport = createAndroidResponderTransport(connectionId);14311432        // Authenticate the initiator before exchanging any vault data. The1433        // native side has already completed the Noise NK handshake; auth1434        // frames here ride the Noise transport (native encrypts/decrypts).1435        const identity = await vault.getSyncIdentity();1436        try {1437          // CAUTION: noiseSessionStub is a structural placeholder — the real1438          // Noise NK handshake runs natively, so JS never holds the session1439          // object. performResponderAuth currently `void`s this argument,1440          // which is why identity-passthrough encrypt/decrypt and a zero1441          // handshake hash are safe. If performResponderAuth is ever updated1442          // to actually use this argument, this auth path will silently break1443          // (no type error). Revisit this stub if that helper changes.1444          const noiseSessionStub = {1445            encrypt: (b: Uint8Array) => b,1446            decrypt: (b: Uint8Array) => b,1447            handshakeHash: new Uint8Array(32),1448          };1449          const { initiatorPublicKey } = await performResponderAuth(1450            noiseSessionStub,1451            identity.privateKeyBytes,1452            identity.publicKeyBytes,1453            transport.send,1454            transport.receive,1455          );1456          const initiatorHex = noiseBytesToHex(initiatorPublicKey);1457          const paired = await getPairedDevices();1458          if (!paired.some(d => d.x25519PublicKey === initiatorHex)) {1459            await transport.close();1460            return { ok: false, error: "sync_rejected_unpaired_initiator" };1461          }1462          // Initiator just proved control of the matching static key; mark it1463          // as a verified handshake so a follow-up PAIRING_COMPLETED message1464          // can be trusted (M13/SEC-005).1465          markPairingHandshakeVerified(initiatorHex);1466        } catch (err) {1467          await transport.close();1468          return { ok: false, error: `sync_auth_failed: ${String(err)}` };1469        }14701471        const result = await runBlobSyncSession('responder', transport, buildSyncDeps());1472        if (result.applied) {1473          await publishInMemoryVault(vault.getEntries());1474        }1475        return { ok: true, data: result };1476      }1477      // Android: returns the phone's WiFi IP address.1478      case "GET_LOCAL_IP": {1479        if (!isNativePlatform()) {1480          return { ok: false, error: "android_only" };1481        }1482        const { ip } = (await syncBridge()?.getLocalIp?.()) ?? { ip: "" };1483        return { ok: true, data: { ip } };1484      }1485      case "GET_IDENTITY_SUGGESTIONS": {1486        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1487        const entries = vault.getEntries();1488        const suggestions = buildIdentitySuggestions(entries);1489        return { ok: true, data: { suggestions } };1490      }1491      case "POPULATE_INLINE_VAULT": {1492        if (!isNativePlatform()) return { ok: false };1493        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1494        const entries = vault.getEntries();1495        await publishInMemoryVault(entries);1496        return { ok: true };1497      }1498      case "ML_INIT":1499        return { ok: true };15001501      case "ML_PREDICT_BATCH": {1502        const { featuresArray } = msg.payload as { featuresArray: MLFieldFeatures[] };1503        return { ok: true, data: mlPredictBatch(featuresArray) };1504      }15051506      default:1507        return { ok: false, error: "unknown_message_type" };1508    }1509  } catch (err) {1510    return {1511      ok: false,1512      error: err instanceof Error ? err.message : "operation_failed",1513    };1514  }1515}15161517// --- Mobile platform helpers ---15181519// Android: populates the in-memory vault used by PeachAutofillService.1520async function publishInMemoryVault(entries: VaultEntry[]): Promise<void> {1521  const plugin = nativePlugin<{1522    setEntries?: (args: {1523      entries: Array<{1524        id: string;1525        title: string;1526        username: string;1527        email: string;1528        password: string;1529        url: string;1530        totp: string;1531        additionalUrls: string[];1532      }>;1533    }) => Promise<void>;1534  }>("InMemoryVaultPlugin");1535  if (!plugin?.setEntries) return;1536  await plugin.setEntries({1537    entries: entries.map((e) => ({1538      id: e.id,1539      title: e.title ?? "",1540      username: e.username ?? "",1541      email: (e as VaultEntry & { email?: string }).email ?? "",1542      password: e.password ?? "",1543      url: e.url ?? "",1544      totp: (e as VaultEntry & { totp?: string }).totp ?? "",1545      additionalUrls: (e as VaultEntry & { additionalUrls?: string[] }).additionalUrls ?? [],1546    })),1547  });1548}15491550// Android: clear the autofill in-memory store on lock.1551async function clearInMemoryVault(): Promise<void> {1552  const plugin = nativePlugin<{ clearEntries?: () => Promise<void> }>("InMemoryVaultPlugin");1553  if (!plugin?.clearEntries) return;1554  await plugin.clearEntries();1555}15561557interface SyncBridge {1558  ensureServerRunning?: () => void;1559  startPairingSession?: (args: { token: string }) => void;1560  getLocalIp?: () => Promise<{ ip: string }>;1561  sendToConnection?: (args: { connectionId: string; data: string }) => Promise<void>;1562  addListener?: (event: string, handler: (data: Record<string, string>) => void) => void;1563}15641565// Resolve the Capacitor SyncPlugin at call time — module-load resolution1566// races with Capacitor's plugin registration on the Android WebView.1567function syncBridge(): SyncBridge | null {1568  return nativePlugin<SyncBridge>("SyncPlugin");1569}15701571// Build a SyncTransport for the Android responder path — the phone's WS server1572// already has an open connection from the desktop. We send back via1573// SyncPlugin.sendToConnection and receive via the peach:sync-frame queue.1574const androidSyncFrameQueues = new Map<string, Array<(frame: string) => void>>();15751576export function deliverAndroidSyncFrame(connectionId: string, frame: string): void {1577  const queue = androidSyncFrameQueues.get(connectionId);1578  if (queue?.length) queue.shift()!(frame);1579}15801581function createAndroidResponderTransport(connectionId: string) {1582  const pendingReceivers: Array<(frame: string) => void> = [];1583  androidSyncFrameQueues.set(connectionId, pendingReceivers);15841585  return {1586    send: async (data: Uint8Array) => {1587      await syncBridge()?.sendToConnection?.({ connectionId, data: bytesToBase64(data) });1588    },1589    receive: (): Promise<Uint8Array> => new Promise((res) => {1590      pendingReceivers.push((frame) => {1591        res(frame ? base64ToBytes(frame) : new Uint8Array(0));1592      });1593    }),1594    close: async () => {1595      androidSyncFrameQueues.delete(connectionId);1596    },1597  };1598}15991600// Returns username use-counts from the vault, sorted by frequency. Each row1601// also carries the entry's email so the popup can suggest the email/username1602// pair the user has actually used together.1603function buildIdentitySuggestions(1604  entries: VaultEntry[],1605): Array<{ email: string; username: string; count: number }> {1606  const usernameCounts = new Map<string, number>();1607  const usernameEmail = new Map<string, string>();1608  for (const entry of entries) {1609    const username = entry.username ?? "";1610    const email = (entry as VaultEntry & { email?: string }).email ?? "";1611    if (!username && !email) continue;1612    const key = username || email;1613    usernameCounts.set(key, (usernameCounts.get(key) ?? 0) + 1);1614    if (!usernameEmail.has(key)) usernameEmail.set(key, email);1615  }1616  return Array.from(usernameCounts.entries())1617    .sort((a, b) => b[1] - a[1])1618    .map(([username, count]) => ({1619      email: usernameEmail.get(username) ?? "",1620      username,1621      count,1622    }));1623}16241625/** Notify all content scripts that the vault just became available. */1626function broadcastToContentScripts(message: { type: string }): void {1627  if (!chrome.tabs?.query) return;1628  chrome.tabs.query({}, (tabs) => {1629    for (const tab of tabs) {1630      if (tab.id !== undefined) {1631        chrome.tabs.sendMessage(tab.id, message).catch(() => {1632          // Tab may not have a content script — silently ignore1633        });1634      }1635    }1636  });1637}16381639function shouldRefreshAutoLock(type: MessageType): boolean {1640  return (1641    type !== "HAS_VAULT" &&1642    type !== "IS_UNLOCKED" &&1643    type !== "GET_VAULT_STATUS" &&1644    type !== "LOCK" &&1645    type !== "UPDATE_SETTINGS" &&1646    type !== "GET_PENDING_PASSKEY" &&1647    type !== "GET_PASSKEY_PROVIDER_STATE" &&1648    type !== "DECLINE_CARD_SAVE" &&1649    type !== "IS_CARD_DECLINED" &&1650    type !== "SUBMIT_FEEDBACK"1651  );1652}16531654function isAllowedCanaryWebhookUrl(value: string): boolean {1655  try {1656    const url = new URL(value);1657    if (url.protocol !== "https:") return false;16581659    const hostname = url.hostname.toLowerCase();1660    if (1661      hostname === "localhost" ||1662      hostname.endsWith(".localhost") ||1663      isPrivateIpv4(hostname) ||1664      isPrivateIpv6(hostname)1665    ) {1666      return false;1667    }16681669    return true;1670  } catch {1671    return false;1672  }1673}16741675function isPrivateIpv4(hostname: string): boolean {1676  if (PRIVATE_IPV4_RANGES.some((range) => hostname.startsWith(range.prefix))) {1677    return true;1678  }16791680  const octets = hostname.split(".").map((part) => Number(part));1681  if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {1682    return false;1683  }16841685  return octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31;1686}16871688function isPrivateIpv6(hostname: string): boolean {1689  const normalized = hostname.replace(/^\[|\]$/g, "").toLowerCase();1690  return (1691    normalized === "::1" ||1692    normalized.startsWith("fc") ||1693    normalized.startsWith("fd") ||1694    normalized.startsWith("fe80:")1695  );1696}