vault.ts

149.4 KB · raw

1/**2 * vault.ts — sole owner of vault state and chrome.storage vault keys.3 *4 * Every read/write of `peach_vault_a`, `peach_vault_b`, and `peach_settings`5 * goes through this module. No other file accesses those keys directly.6 * External callers reach vault operations via `messages.ts` — never by7 * importing from here cross-boundary (popup/content must not). Invariants8 * for the two-slot schema, unlock timing, and key/disk atomicity are in9 * Projects.md §3.2–§3.6.10 */1112import { deriveKey, generateSalt } from "../crypto/argon2";13import { extractDomain } from "../shared/domain";14import { clampSyncTimestamp } from "../shared/sync-limits";15import { computeVaultId } from "../shared/sync-identity";16// Static, not `await import()`: runtime import() throws in an MV3 service17// worker. Neither module imports vault.ts back, so there is no cycle to break.18import { triggerSyncIfReachable } from "./sync-trigger";19import { clearPairedDevices } from "./paired-devices";20import {21  rootKeyToWords,22  wordsToRootKeyMaterial,23  deriveRecoveryKey,24} from "../shared/recovery-words";25import type {26  AccentColorName,27  BreachScanStatus,28  Canary,29  ManualSummonRecord,30  PasskeyData,31  RecoveryResult,32  SavedIdentity,33  StoredVault,34  VaultEntry,35  VaultHistory,36  VaultSnapshot,37} from "../shared/types";38import { decrypt, encrypt, zeroKey } from "./aes";39import { clearAutoLock, touchAutoLock } from "./alarms";40import { setRecoveryConfirmPending, revokeRecoveryReveal } from "./recovery-pending";41import {42  clearPairSecrets,43  dropSessionCache,44  reconcilePairSecrets,45  setSessionAllowed,46} from "./pair-secrets";4748type EntryDraft = Omit<49  VaultEntry,50  "id" | "createdAt" | "modifiedAt" | "deletedAt"51>;5253// Slot-neutral storage keys (v1.4.24+). Both slots always exist; slot B54// either holds the decoy vault (when duress is configured) or random noise55// that looks identical at rest. No external indicator is stored — duress56// configuration is recorded only inside the encrypted payload of slot A.57const SLOT_A = "peach_vault_a";58const SLOT_B = "peach_vault_b";5960// Plaintext is padded to the next multiple of this size before encryption.61// This coarsens ciphertext-length leakage into 1 KiB buckets.62const PAD_BLOCK = 1024;6364// How many past passwords to retain per entry. Generous enough to be useful as65// a recovery aid while bounding the secret material we hold (and the ciphertext66// growth) for an entry whose password is rotated frequently.67const PASSWORD_HISTORY_MAX = 50;6869// When duress is configured, BOTH slots are padded to this fixed ceiling so70// their ciphertext lengths are identical and cannot reveal that a hidden decoy71// vault exists (audit MEDIUM — plausible-deniability leak). 256 KiB comfortably72// holds a very large vault (thousands of entries incl. passkeys). The decoy73// slot can't be re-encrypted on every real-vault save (the real session has no74// decoy key), so a fixed ceiling — rather than size-matching on each write — is75// what keeps the two slots equal. A real vault whose plaintext exceeds this76// would grow past the ceiling and re-expose the bit; that is an extreme,77// documented edge well beyond normal use.78const DURESS_SLOT_SIZE = 262_144;7980let derivedKey: Uint8Array | null = null;81// 32-byte random root key, separate from the derivedKey used for vault encryption.82// The root key is wrapped (encrypted) under the recovery key derived from the83// 12-word phrase. When the user changes their password, only the wrapping changes;84// the root key and recovery words remain stable.85let rootKey: Uint8Array | null = null;86let recoveryInFlight = false;87let recoverySettled: Promise<void> = Promise.resolve();88let vaultRemovalsInFlight = 0;89let vaultRemovalEpoch = 0;90let vaultWritesInFlight = 0;91let vaultCreatesInFlight = 0;92let creationSettled: Promise<void> = Promise.resolve();93let vaultUnlocksInFlight = 0;94let vaultReplacementInFlight = false;95let entries: VaultEntry[] = [];96// Tombstones outlive their full entry records so a peer that was offline97// during a purge cannot reintroduce an old ciphertext envelope. This map is98// serialized only inside the encrypted vault payload.99let tombstones = new Map<string, number>();100let domainIndex: Map<string, VaultEntry[]> = new Map();101let vaultMode: "real" | "decoy" = "real";102// Cached post-unlock view of whether the real vault records that duress is103// configured. Only meaningful after a real-mode unlock; for decoy-mode unlock104// this stays false because we never see slot A's plaintext.105let duressConfigured = false;106107// Set to a corruption reason during the last unlock() attempt when both slots108// decrypted but failed schema validation. Consumed and cleared by109// consumeLastUnlockFailureReason() so messages.ts can surface vault_corrupted110// distinctly from wrong-password (M7/COR-007).111//112// NOTE: module-level state — if vault.ts is ever moved to a worker context,113// this must be replaced with a structured return value from unlock() or a114// postMessage channel. The signal is invisible across module-instance115// boundaries.116let lastUnlockFailureReason: string | null = null;117118export function consumeLastUnlockFailureReason(): string | null {119  const r = lastUnlockFailureReason;120  lastUnlockFailureReason = null;121  return r;122}123124// ---------------------------------------------------------------------------125// Settings (persisted inside the encrypted vault store as a sidecar key)126// ---------------------------------------------------------------------------127128export type TextSize = "small" | "medium" | "large";129130export interface VaultSettings {131  accentColor?: AccentColorName;132  theme?: "dark" | "light";133  autoLockMinutes?: number;134  clipboardClearSeconds?: number;135  lockOnClose?: boolean;136  breachMonitoring?: boolean;137  passkeyProviderEnabled?: boolean;138  trashRetentionDays?: number;139  manualSummonDomains?: Record<string, ManualSummonRecord>;140  manualSummonSalt?: string;141  declinedCardFingerprints?: string[];142143  /** Metadata is bounded because it remains outside the encrypted vault blob. */144  metadataVersion?: 1;145  /**146   * Text size scale for body copy and entry titles. Stops at "large" by147   * design — XL clips dense screens (Vault, Health) inside the fixed148   * 330×480 popup surface.149   */150  textSize?: TextSize;151  /**152   * When true, all entrance/exit transitions and ambient animations are153   * collapsed to instant. Honoured alongside the user's OS-level154   * `prefers-reduced-motion`.155   */156  reduceMotion?: boolean;157  /** Require an unlock after a worker restart before locked Sync resumes. */158  lockedSyncRequiresUnlock?: boolean;159  /** Whether this vault has a local PIN unlock wrapper configured. */160  pinEnabled?: boolean;161  /** Whether the lock screen should open on PIN instead of the password. */162  pinPreferred?: boolean;163  /**164   * User overrides for keyboard shortcuts. Keys are ShortcutAction names165   * (see src/shared/shortcuts.ts). Missing actions fall through to166   * DEFAULT_BINDINGS — `getActiveBindings(settings.shortcuts)` is the167   * canonical lookup. Storing only the deltas keeps the vault payload168   * small and lets default updates land for users who never rebind.169   */170  shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;171}172173interface StoredPinWrap {174  version: 1;175  salt: string;176  nonce: string;177  ciphertext: string;178  tag: string;179}180181const PIN_WRAP_STORAGE = "peach_pin_wrap";182const PIN_ATTEMPTS_STORAGE = "peach_pin_attempts";183const PIN_MIN_LENGTH = 4;184const PIN_MAX_LENGTH = 12;185const PIN_MAX_ATTEMPTS = 3;186187let settings: VaultSettings = {};188const CARD_DECLINE_MAX = 256;189/** Hex length of a keyed card-decline digest. Legacy records are 16 hex. */190const CARD_DECLINE_DIGEST_HEX = 32;191192async function metadataDigest(value: string, key: string): Promise<string> {193  const bytes = new TextEncoder().encode(`${key}:${value}`);194  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));195  return Array.from(digest.slice(0, 16)).map((byte) => byte.toString(16).padStart(2, "0")).join("");196}197198let inMemoryPinWrap: StoredPinWrap | null = null;199let inMemoryPinFailedAttempts = 0;200let sessionPinStorageFailed = false;201202export function getSettings(): VaultSettings {203  return settings;204}205206export async function ensureSettingsLoaded(): Promise<VaultSettings> {207  await loadSettings();208  return settings;209}210211export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {212  await loadSettings();213  // LV-7: cheap insurance against prototype pollution if a future caller ever214  // feeds parsed external JSON here (native spread keeps __proto__ an own-215  // property today, but Object.assign-style consumers and JSON revivers have216  // been burned before).217  const safe = Object.fromEntries(218    Object.entries(patch).filter(219      ([k]) => !["__proto__", "constructor", "prototype"].includes(k),220    ),221  ) as Partial<VaultSettings>;222  settings = { ...settings, ...safe };223  await persistSettings();224}225226function isValidPin(pin: string): boolean {227  return new RegExp(`^\\d{${PIN_MIN_LENGTH},${PIN_MAX_LENGTH}}$`).test(pin);228}229230/** Set up a local PIN wrapper after proving the current master password. */231export async function setupPinUnlock(currentPassword: string, pin: string): Promise<boolean> {232  if (vaultCreatesInFlight) return false;233  vaultWritesInFlight++;234  try {235  if (!derivedKey || vaultMode !== "real" || !isValidPin(pin)) return false;236  if (!(await verifyMainPassword(currentPassword))) return false;237238  const salt = generateSalt();239  const pinKey = await deriveKey(pin, salt);240  try {241    const wrapped = await encrypt(pinKey, hex(derivedKey), "pin_wrap_v1");242    await savePinWrap({ version: 1, salt: hex(salt), ...wrapped });243    await updateSettings({ pinEnabled: true });244    return true;245  } finally {246    zeroKey(pinKey);247  }248  } finally { vaultWritesInFlight--; }249}250251async function clearPinUnlockStorage(): Promise<void> {252  inMemoryPinWrap = null;253  inMemoryPinFailedAttempts = 0;254  sessionPinStorageFailed = false;255  if (chrome.storage.session) {256    await chrome.storage.session.remove([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);257  }258  await updateSettings({ pinEnabled: false });259}260261/** Remove the PIN wrapper after proving the current master password. */262export async function disablePinUnlock(currentPassword: string): Promise<boolean> {263  if (vaultCreatesInFlight) return false;264  vaultWritesInFlight++;265  try {266  if (!derivedKey || vaultMode !== "real") return false;267  if (!(await verifyMainPassword(currentPassword))) return false;268  await clearPinUnlockStorage();269  return true;270  } finally { vaultWritesInFlight--; }271}272273/** Unlock the real vault from its locally stored PIN-wrapped derived key. */274export async function unlockWithPin(pin: string): Promise<boolean> {275  vaultUnlocksInFlight++;276  try {277  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;278  if (!isValidPin(pin)) return false;279  await loadSettings();280  if (!settings.pinEnabled) return false;281282  const { stored, failedAttempts } = await loadPinState();283  if (failedAttempts >= PIN_MAX_ATTEMPTS) return false;284  if (285    !stored ||286    stored.version !== 1 ||287    !stored.salt ||288    !stored.nonce ||289    !stored.ciphertext ||290    !stored.tag291  ) return false;292293  const pinKey = await deriveKey(pin, unhex(stored.salt));294  let unwrappedKey: Uint8Array | null = null;295  try {296    const masterKeyHex = await decrypt(297      pinKey,298      stored.nonce,299      stored.ciphertext,300      stored.tag,301      "pin_wrap_v1",302    );303    if (!/^[0-9a-f]{64}$/.test(masterKeyHex)) return false;304    unwrappedKey = unhex(masterKeyHex);305    const result = await unlockWithKey(masterKeyHex);306    if (!result.ok) return false;307    await resetPinFailedAttempts();308    return true;309  } catch {310    await recordPinFailure(failedAttempts + 1);311    return false;312  } finally {313    zeroKey(pinKey);314    if (unwrappedKey) zeroKey(unwrappedKey);315  }316  } finally { vaultUnlocksInFlight--; }317}318319async function savePinWrap(stored: StoredPinWrap): Promise<void> {320  inMemoryPinWrap = stored;321  inMemoryPinFailedAttempts = 0;322  sessionPinStorageFailed = !chrome.storage.session;323  if (!chrome.storage.session) return;324  try {325    await chrome.storage.session.set({ [PIN_WRAP_STORAGE]: stored, [PIN_ATTEMPTS_STORAGE]: 0 });326    sessionPinStorageFailed = false;327  } catch {328    // Firefox fallback: keep the wrapper only in this background context.329    sessionPinStorageFailed = true;330  }331}332333async function loadPinState(): Promise<{334  stored: StoredPinWrap | undefined;335  failedAttempts: number;336}> {337  if (!chrome.storage.session) {338    return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };339  }340  try {341    const result = await chrome.storage.session.get([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);342    return {343      stored: (result[PIN_WRAP_STORAGE] as StoredPinWrap | undefined) ??344        (sessionPinStorageFailed ? inMemoryPinWrap ?? undefined : undefined),345      failedAttempts: typeof result[PIN_ATTEMPTS_STORAGE] === "number"346        ? result[PIN_ATTEMPTS_STORAGE]347        : 0,348    };349  } catch {350    return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };351  }352}353354async function recordPinFailure(failedAttempts: number): Promise<void> {355  inMemoryPinFailedAttempts = Math.min(failedAttempts, PIN_MAX_ATTEMPTS);356  if (!chrome.storage.session) return;357  try {358    await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: inMemoryPinFailedAttempts });359  } catch { /* in-memory counter remains the fallback */ }360}361362async function resetPinFailedAttempts(): Promise<void> {363  inMemoryPinFailedAttempts = 0;364  if (!chrome.storage.session) return;365  try {366    await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: 0 });367  } catch { /* in-memory counter remains the fallback */ }368}369370export async function getPinUnlockStatus(): Promise<{371  configured: boolean;372  available: boolean;373  attemptsRemaining: number;374}> {375  await loadSettings();376  if (!settings.pinEnabled) {377    return { configured: false, available: false, attemptsRemaining: 0 };378  }379  const { stored, failedAttempts } = await loadPinState();380  const available = Boolean(stored) && failedAttempts < PIN_MAX_ATTEMPTS;381  return {382    configured: true,383    available,384    attemptsRemaining: stored ? Math.max(0, PIN_MAX_ATTEMPTS - failedAttempts) : 0,385  };386}387388async function persistSettings(): Promise<void> {389  try {390    await chrome.storage.local.set({391      peach_settings: {392        ...settings,393        manualSummonDomains: undefined,394        manualSummonSalt: undefined,395        cardFingerprintSalt: undefined,396        declinedCardFingerprints: settings.declinedCardFingerprints ?? [],397        metadataVersion: 1,398      },399    });400  } catch (err) {401    throw mapStorageError(err);402  }403}404405function mapStorageError(err: unknown): Error {406  const message = err instanceof Error ? err.message : String(err);407  if (/QUOTA_BYTES|quota/i.test(message)) {408    return new Error("STORAGE_QUOTA_EXCEEDED");409  }410  return err instanceof Error ? err : new Error(message);411}412413async function loadSettings(): Promise<void> {414  const result = await chrome.storage.local.get("peach_settings");415  settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};416}417418// Fire-and-forget sync trigger after a committed vault write. A failure here419// must never fail the write that caused it.420function fireSyncTrigger(reason: "vault_change"): void {421  void Promise.resolve()422    .then(() => triggerSyncIfReachable({ reason }))423    .catch(() => {424      /* no sync runner registered, or nothing reachable — non-fatal */425    });426}427export function lockedSyncRequiresUnlock(): boolean {428  return settings.lockedSyncRequiresUnlock === true;429}430431let lockedSyncRefreshHook: (() => Promise<void>) | null = null;432let lockedSyncUnlockHook: (() => Promise<void>) | null = null;433let decoySyncTeardownHook: (() => void) | null = null;434export type IdentityHooks = {435  /** Drop the cached identity: the session is no longer a real unlocked one. */436  onSessionEnded: () => Promise<void>;437  /** Re-wrap the identity under the keys now in force, after a vault key swap. */438  onKeysRotated: () => Promise<void>;439  /** Promote a pre-vault identity once a vault exists, given the password that created it. */440  onVaultCreated: (password: string) => Promise<void>;441};442443let identityHooks: IdentityHooks | null = null;444445export function setIdentityHooks(hooks: IdentityHooks): void {446  identityHooks = hooks;447}448449async function notifyIdentitySessionEnded(): Promise<void> {450  await identityHooks?.onSessionEnded().catch((error) => {451    console.warn("[Peach] local identity cache clear failed:", error);452  });453}454455async function notifyIdentityKeysRotated(): Promise<void> {456  await identityHooks?.onKeysRotated().catch((error) => {457    console.warn("[Peach] local identity re-wrap failed:", error);458  });459}460461export type SealedBox = { nonce: string; ciphertext: string; tag: string };462export type IdentityKeyEnvelope = {463  root?: SealedBox;464  local?: SealedBox;465  pending?: SealedBox;466  pendingSalt?: string;467};468469export function setLockedSyncHooks(hooks: {470  refresh: () => Promise<void>;471  afterUnlock: () => Promise<void>;472  onDecoy?: () => void;473}): void {474  lockedSyncRefreshHook = hooks.refresh;475  lockedSyncUnlockHook = hooks.afterUnlock;476  decoySyncTeardownHook = hooks.onDecoy ?? null;477}478479async function refreshLockedSyncState(): Promise<void> {480  if (vaultMode !== "real" || !rootKey || !lockedSyncRefreshHook) return;481  await lockedSyncRefreshHook().catch((error) => {482    console.warn("[Peach sync] locked spool refresh failed:", error);483  });484}485486// ---------------------------------------------------------------------------487// HIBP breach check (k-anonymity model)488// ---------------------------------------------------------------------------489490export async function checkBreach(password: string, signal?: AbortSignal): Promise<number | null> {491  const controller = new AbortController();492  let timeout: ReturnType<typeof setTimeout> | undefined;493  let onAbort: (() => void) | undefined;494  try {495    const unavailable = new Promise<null>((resolve) => {496      onAbort = () => { controller.abort(); resolve(null); };497      signal?.addEventListener("abort", onAbort, { once: true });498      timeout = setTimeout(onAbort, 8_000);499      if (signal?.aborted) onAbort();500    });501    const lookup = async (): Promise<number | null> => {502      // HIBP's range API requires SHA-1; only the five-character prefix leaves the device.503      const hash = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(password));504      if (controller.signal.aborted) return null;505      const hex = Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, "0")).join("").toUpperCase();506      const res = await fetch(`https://api.pwnedpasswords.com/range/${hex.slice(0, 5)}`, {507        headers: { "Add-Padding": "true" },508        signal: controller.signal,509      });510      if (!res.ok) return null;511      const text = await res.text();512      const lines = text.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");513      let count = 0;514      const seen = new Set<string>();515      for (const line of lines) {516        const match = /^([A-Fa-f0-9]{35}):([0-9]+)$/.exec(line);517        if (!match) return null;518        const suffix = match[1].toUpperCase();519        const value = Number(match[2]);520        if (!Number.isSafeInteger(value) || seen.has(suffix)) return null;521        seen.add(suffix);522        if (suffix === hex.slice(5)) count = value;523      }524      return count;525    };526    return await Promise.race([lookup(), unavailable]);527  } catch {528    return null;529  } finally {530    clearTimeout(timeout);531    if (onAbort) signal?.removeEventListener("abort", onAbort);532  }533}534535type BreachCredential = { id: string; password: string; epoch: number; key: Uint8Array };536const breachChecks = new Map<string, symbol>();537538async function checkEntryBreach(credential: BreachCredential, signal?: AbortSignal): Promise<"unknown" | "unapplied" | number> {539  const { id, password, epoch } = credential;540  const isCurrent = () => {541    const entry = entries.find((entry) => entry.id === id);542    return !signal?.aborted && epoch === vaultEpoch && credential.key === derivedKey && !vaultCreatesInFlight &&543      entry?.type === "login" && !entry.deletedAt && entry.password === password;544  };545  if (!isCurrent()) return "unapplied";546  const token = Symbol();547  breachChecks.set(id, token);548  try {549    const count = await checkBreach(password, signal);550    const idx = entries.findIndex((entry) => entry.id === id);551    const current = entries[idx];552    if (signal?.aborted || epoch !== vaultEpoch || credential.key !== derivedKey || vaultCreatesInFlight ||553      breachChecks.get(id) !== token || !current || current.deletedAt || current.type !== "login" || current.password !== password) return "unapplied";554    if (count === null) return "unknown";555    if ((current.breach ?? 0) === count) return count;556    const owner = entries;557    const next = { ...current, breach: count, modifiedAt: monotonicEntryTimestamp(current.modifiedAt) };558    entries[idx] = next;559    try {560      await persistEntries();561    } catch (error) {562      if (epoch === vaultEpoch && entries === owner && entries[idx] === next && !next.deletedAt) entries[idx] = current;563      throw error;564    }565    if (!isCurrent() || breachChecks.get(id) !== token) return "unapplied";566    fireSyncTrigger("vault_change");567    return count;568  } finally {569    if (breachChecks.get(id) === token) breachChecks.delete(id);570  }571}572573function checkEntryBreachDetached(credential: BreachCredential): void {574  void checkEntryBreach(credential).catch(() => {575    console.warn("[Peach] Could not save a breach check result");576  });577}578579function emptyBreachScan(state: BreachScanStatus["state"] = "idle"): BreachScanStatus {580  return { id: null, state, total: 0, scanned: 0, unknown: 0, unapplied: 0, breached: 0, cancelled: 0 };581}582583type BreachScan = {584  epoch: number;585  key: Uint8Array | null;586  status: BreachScanStatus;587  credentials: BreachCredential[];588  controller: AbortController;589};590let breachScan: BreachScan | null = null;591592function cancelBreachScan(): void {593  breachChecks.clear();594  const scan = breachScan;595  if (!scan) return;596  scan.controller.abort();597  scan.credentials.length = 0;598  scan.key = null;599  if (scan.status.state === "running") {600    scan.status.cancelled = scan.status.total - scan.status.scanned - scan.status.unknown - scan.status.unapplied;601    scan.status.state = "cancelled";602  }603}604605/// Returns aggregate progress for the current unlock session without credential data.606export function getBreachScanStatus(): BreachScanStatus {607  if (!derivedKey) return emptyBreachScan(breachScan ? "cancelled" : "idle");608  if (!breachScan || breachScan.epoch !== vaultEpoch || breachScan.key !== derivedKey) return emptyBreachScan();609  return { ...breachScan.status };610}611612/// Starts a single background scan, or returns the current scan if it is still running.613export function startBreachScan(): BreachScanStatus {614  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");615  if (breachScan?.status.state === "running" && breachScan.epoch === vaultEpoch && breachScan.key === derivedKey) return getBreachScanStatus();616  cancelBreachScan();617  const key = derivedKey;618  const credentials = entries.filter((entry) => !entry.deletedAt && entry.type === "login" && entry.password)619    .map((entry) => ({ id: entry.id, password: entry.password!, epoch: vaultEpoch, key }));620  const scan: BreachScan = {621    epoch: vaultEpoch, key, credentials, controller: new AbortController(),622    status: { ...emptyBreachScan(credentials.length ? "running" : "complete"), id: crypto.randomUUID(), total: credentials.length },623  };624  breachScan = scan;625  void runBreachScan(scan);626  return { ...scan.status };627}628629async function runBreachScan(scan: BreachScan): Promise<void> {630  try {631    while (scan.credentials.length) {632      if (scan.epoch !== vaultEpoch || scan.key !== derivedKey || scan.controller.signal.aborted) break;633      const credential = scan.credentials.shift()!;634      let result: "unknown" | "unapplied" | number;635      try { result = await checkEntryBreach(credential, scan.controller.signal); }636      catch { result = "unknown"; console.warn("[Peach] Could not save a breach scan result"); }637      if (scan.epoch !== vaultEpoch || scan.key !== derivedKey || scan.controller.signal.aborted) break;638      if (result === "unknown") scan.status.unknown++;639      else if (result === "unapplied") scan.status.unapplied++;640      else { scan.status.scanned++; if (result > 0) scan.status.breached++; }641      if (scan.credentials.length) {642        await new Promise<void>((resolve) => {643          const done = () => { clearTimeout(timer); scan.controller.signal.removeEventListener("abort", done); resolve(); };644          const timer = setTimeout(done, 200);645          scan.controller.signal.addEventListener("abort", done, { once: true });646          if (scan.controller.signal.aborted) done();647        });648      }649    }650  } finally {651    scan.credentials.length = 0;652    if (scan.status.state === "running") {653      if (scan.epoch !== vaultEpoch || scan.key !== derivedKey || scan.controller.signal.aborted) {654        scan.status.cancelled = scan.status.total - scan.status.scanned - scan.status.unknown - scan.status.unapplied;655        scan.status.state = "cancelled";656      } else scan.status.state = "complete";657    }658  }659}660661export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {662  // Unreachable from the message layer, which gates on isUnlocked first.663  const key = await cardDeclineKey();664  if (!key) return;665  const fingerprint = await cardFingerprint(last4, expMonth, expYear);666  await loadSettings();667  settings = {668    ...settings,669    declinedCardFingerprints: [670      // Legacy records predate the keyed digest and are silently dropped here:671      // they are 16 hex characters rather than 32, and are no longer accepted.672      ...(settings.declinedCardFingerprints ?? []).filter(673        (stored) => stored.length === CARD_DECLINE_DIGEST_HEX,674      ),675      await metadataDigest(fingerprint, key),676    ].slice(-CARD_DECLINE_MAX),677  };678  await persistSettings();679}680681export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {682  await loadSettings();683  const key = await cardDeclineKey();684  if (!key) return false;685  const fingerprint = await cardFingerprint(last4, expMonth, expYear);686  const candidate = await metadataDigest(fingerprint, key);687  return (settings.declinedCardFingerprints ?? []).some(688    (stored) => stored.length === CARD_DECLINE_DIGEST_HEX && stored === candidate,689  );690}691692/**693 * Keying material for the declined-card digest, derived from the vault root694 * key so it is available only while unlocked and never written to storage.695 *696 * PB-26-108: the previous scheme stored a random salt beside the records. A697 * salt defeats precomputed tables, not an attacker holding the file — the698 * candidate space here is ~10^4 last-four values x 12 months x a few years, so699 * a stored salt left the card's last four and expiry recoverable offline in700 * seconds. `peach_settings` is unencrypted and directly readable by a content701 * script on Firefox, so the key has to live outside storage entirely.702 */703async function cardDeclineKey(): Promise<string | null> {704  const root = getRootKeyHex();705  if (!root) return null;706  const digest = new Uint8Array(707    await crypto.subtle.digest(708      "SHA-256",709      new TextEncoder().encode(`peach-card-decline-v1:${root}`),710    ),711  );712  return hex(digest);713}714715async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {716  const encoder = new TextEncoder();717  const buf = await crypto.subtle.digest("SHA-256", encoder.encode(`${last4}|${expMonth}|${expYear}`));718  return Array.from(new Uint8Array(buf).slice(0, 8))719    .map((b) => b.toString(16).padStart(2, "0"))720    .join("");721}722723function hex(buf: Uint8Array): string {724  return Array.from(buf)725    .map((b) => b.toString(16).padStart(2, "0"))726    .join("");727}728729function unhex(s: string): Uint8Array {730  const out = new Uint8Array(s.length / 2);731  for (let i = 0; i < s.length; i += 2) {732    out[i / 2] = parseInt(s.slice(i, i + 2), 16);733  }734  return out;735}736737// ---------------------------------------------------------------------------738// Root key generation and recovery word wrapping739// ---------------------------------------------------------------------------740741/**742 * Generate a random 32-byte root key and wrap it (AES-256-GCM) under a key743 * derived from the recovery word material via HKDF-SHA256. The wrapped blob744 * fields are stored in slot A alongside the password-wrapped ciphertext. The745 * root key itself is kept in memory for the session so getRecoveryWords() can746 * encode it without re-deriving.747 *748 * SECURITY MODEL (PCH-01-005): the recovery KEK is derived from the 12-word749 * material, which encodes only rootKey[0..16] (recovery-words.ts). The KEK is thus750 * derived from a PREFIX of the very plaintext it wraps, and effective recovery751 * security is 128-bit (standard for a 12-word phrase), NOT 256-bit. This is safe —752 * unwrapping requires the words, and the GCM ciphertext leaks nothing without them —753 * but it is intentional, not an oversight. A future escrow version wanting 256-bit754 * recovery must derive the words from INDEPENDENT entropy, not from the root key.755 */756async function generateAndWrapRootKey(): Promise<{757  rawRootKey: string; // hex of the plaintext root key — caller stores in rootKey758  recoverySalt: string;759  wrappedRootKey: string;760  wrappedNonce: string;761  wrappedTag: string;762}> {763  const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));764  try {765766  // Derive the recovery key from the BIP39 words encoding of the root key.767  const words = await rootKeyToWords(rootKeyBytes);768  const wordMaterial = await wordsToRootKeyMaterial(words);769  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));770  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);771772  // Wrap the root key with the recovery key using AES-256-GCM directly.773  // We hex-encode rootKeyBytes so the plaintext is always valid UTF-8.774  const nonce = crypto.getRandomValues(new Uint8Array(12));775  const encoded = new TextEncoder().encode(hex(rootKeyBytes));776  const raw = await crypto.subtle.encrypt(777    {778      name: "AES-GCM",779      iv: nonce,780      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,781      tagLength: 128,782    },783    recoveryKey,784    encoded785  );786  // WebCrypto returns ciphertext || auth tag concatenated; split them.787  const rawU8 = new Uint8Array(raw);788  const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));789  const tag = hex(rawU8.slice(rawU8.length - 16));790791  return {792    rawRootKey: hex(rootKeyBytes),793    recoverySalt: hex(recoverySalt),794    wrappedRootKey: ciphertext,795    wrappedNonce: hex(nonce),796    wrappedTag: tag,797  };798  } finally { zeroKey(rootKeyBytes); }799}800801async function wrapExistingRootKeyForRecovery(rootKeyBytes: Uint8Array): Promise<{802  recoverySalt: string;803  wrappedRootKey: string;804  wrappedNonce: string;805  wrappedTag: string;806}> {807  if (rootKeyBytes.length !== 32) {808    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");809  }810811  const words = await rootKeyToWords(rootKeyBytes);812  const wordMaterial = await wordsToRootKeyMaterial(words);813  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));814  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);815  const nonce = crypto.getRandomValues(new Uint8Array(12));816  const encoded = new TextEncoder().encode(hex(rootKeyBytes));817  const raw = await crypto.subtle.encrypt(818    {819      name: "AES-GCM",820      iv: nonce,821      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,822      tagLength: 128,823    },824    recoveryKey,825    encoded,826  );827  const rawU8 = new Uint8Array(raw);828  return {829    recoverySalt: hex(recoverySalt),830    wrappedRootKey: hex(rawU8.slice(0, rawU8.length - 16)),831    wrappedNonce: hex(nonce),832    wrappedTag: hex(rawU8.slice(rawU8.length - 16)),833  };834}835836/**837 * Unwrap the root key using recovery words. Called during recovery flow when838 * the user provides their 12-word phrase and a new password.839 */840async function unwrapRootKeyForRecovery(841  wrappedRootKey: string,842  wrappedNonce: string,843  wrappedTag: string,844  recoverySaltHex: string,845  words: string[]846): Promise<Uint8Array> {847  const wordMaterial = await wordsToRootKeyMaterial(words);848  const recoverySalt = unhex(recoverySaltHex);849  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);850851  // The root key bytes were hex-encoded before852  // encryption so the ciphertext is valid UTF-8. We inline the AES-GCM decrypt853  // here to avoid passing a CryptoKey to the string-based encrypt/decrypt helpers.854  // Each component is stored separately in the vault slot; decode them individually855  // so the nonce is always exactly the 12 bytes from wrappedNonce.856  const nonceRaw = unhex(wrappedNonce);857  const ciphertextRaw = unhex(wrappedRootKey);858  const tagRaw = unhex(wrappedTag);859  // Combine ciphertext and tag for AES-GCM (expects ciphertext||tag).860  // Use explicit ArrayBuffer allocations to satisfy TS BufferSource constraints.861  const nonceU8 = nonceRaw as unknown as Uint8Array<ArrayBuffer>;862  const combined = new Uint8Array(ciphertextRaw.length + tagRaw.length);863  combined.set(ciphertextRaw, 0);864  combined.set(tagRaw, ciphertextRaw.length);865  const raw = await crypto.subtle.decrypt(866    { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },867    recoveryKey,868    combined869  );870  const decryptedHex = new TextDecoder().decode(raw);871  const recovered = unhex(decryptedHex);872  if (recovered.length !== 32) { zeroKey(recovered); throw new Error("invalid_recovery_words"); }873  return recovered;874}875876/// Recover a locked real vault without publishing keys before its stored payload authenticates.877export async function recoverWithWords(words: string[], newPassword: string): Promise<RecoveryResult> {878  if (recoveryInFlight || derivedKey) throw new Error("recovery_requires_lock");879  if (vaultWritesInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");880  recoveryInFlight = true;881  let settle!: () => void;882  recoverySettled = new Promise<void>((resolve) => { settle = resolve; });883  cancelBreachScan();884  const epoch = ++vaultEpoch;885  const check = () => {886    if (epoch !== vaultEpoch || derivedKey) throw new Error("vault_locked");887  };888  let recoveredRoot: Uint8Array | null = null;889  let oldKey: Uint8Array | null = null;890  let newKey: Uint8Array | null = null;891  let committed = false;892  try {893    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);894    check();895    const slot = raw[SLOT_A] as StoredVault | undefined;896    if (!slot) throw new Error("no_vault");897    if (!slot.recovery_salt || !slot.recovery_wrapped_root_key) throw new Error("recovery_not_setup");898    try {899      recoveredRoot = await unwrapRootKeyForRecovery(slot.recovery_wrapped_root_key,900        slot.recovery_nonce ?? "", slot.recovery_tag ?? "", slot.recovery_salt, words);901    } catch {902      throw new Error("invalid_recovery_words");903    }904    check();905    if (!slot.recovery_vault_key) throw new Error("recovery_requires_password_unlock");906    oldKey = await openSealedKey(recoveredRoot, slot.recovery_vault_key, "recovery_vault_key_v1");907    check();908    if (!oldKey) throw new Error("recovery_data_unavailable");909    const result = await tryDecryptSlotResult(slot, oldKey, "slot_a_v1");910    check();911    if (result.status !== "ok") throw new Error("recovery_data_unavailable");912    const payload = result.payload;913    await loadSettings();914    check();915    const salt = generateSalt();916    newKey = await deriveKey(newPassword, salt);917    check();918    // Preserve the authenticated plaintext, including fields unknown to this build.919    const plaintext = await decrypt(oldKey, slot.nonce, slot.ciphertext, slot.tag, "slot_a_v1");920    const encrypted = await encrypt(newKey, plaintext, "slot_a_v1");921    const pwRoot = await wrapRootKeyForDerivedKey(newKey, recoveredRoot);922    const recoveryVaultKey = await encrypt(recoveredRoot, hex(newKey), "recovery_vault_key_v1");923    check();924    const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);925    check();926    if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");927    const history = raw[HISTORY_KEY] as VaultHistory | undefined;928    const snapshot: VaultSnapshot = {929      id: crypto.randomUUID(), savedAt: Date.now(), reason: "local_save",930      vault_a: JSON.stringify(slot), vault_b: JSON.stringify(raw[SLOT_B] ?? slot), entryCount: null,931    };932    const previousStamp = Number(raw.peach_last_modified_at);933    const nextSlot: StoredVault = { ...slot, ...encrypted, ...pwRoot,934      salt: hex(salt), recovery_vault_key: recoveryVaultKey };935    // One storage transaction keeps the rollback snapshot and all new-key fields together.936    await chrome.storage.local.set({937      [SLOT_A]: nextSlot,938      [HISTORY_KEY]: { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) },939      peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previousStamp) ? previousStamp + 1 : 0)),940    });941    committed = true;942    check();943    cancelBreachScan();944    derivedKey = newKey;945    rootKey = recoveredRoot;946    newKey = null;947    recoveredRoot = null;948    entries = payload.entries;949    tombstones = payload.tombstones;950    duressConfigured = payload.duressConfigured;951    vaultMode = "real";952    buildDomainIndexSync(entries);953    await saveSessionKey(derivedKey, "real", epoch);954    if (epoch !== vaultEpoch) throw new Error("vault_locked");955    await identityHooks?.onKeysRotated();956    if (epoch !== vaultEpoch) throw new Error("vault_locked");957    await reconcilePairSecrets(rootKey);958    if (epoch !== vaultEpoch) throw new Error("vault_locked");959    await clearPinUnlockStorage();960    if (epoch !== vaultEpoch) throw new Error("vault_locked");961    touchAutoLock();962    return { committed: true, unlocked: true };963  } catch (error) {964    if (committed) {965      console.warn("[Peach] recovery password saved; unlock required:", error);966      if (derivedKey && epoch === vaultEpoch) {967        try { await lock(); }968        catch (lockError) { console.warn("[Peach] recovery session cleanup failed:", lockError); }969      }970      return { committed: true, unlocked: false };971    }972    if (derivedKey && epoch === vaultEpoch) await lock();973    throw error;974  } finally {975    if (oldKey) zeroKey(oldKey);976    if (newKey) zeroKey(newKey);977    if (recoveredRoot) zeroKey(recoveredRoot);978    recoveryInFlight = false;979    settle();980  }981}982983/// Cancel recovery and finish its issued storage write before removing vault data.984export async function withVaultRemoval<T>(remove: () => Promise<T>): Promise<T> {985  vaultRemovalEpoch++;986  vaultRemovalsInFlight++;987  try {988    await lock();989    await recoverySettled;990    await creationSettled;991    return await remove();992  } finally {993    vaultRemovalsInFlight--;994  }995}996997/**998 * Recover the session root key by AES-GCM-decrypting the pw_root_* fields999 * (a second wrapping of the root key under the password-derived key). This1000 * is what makes GET_RECOVERY_WORDS work across lock/unlock cycles without1001 * the user re-entering their recovery phrase: the same root key bytes —1002 * and therefore the same 12 words — survive every unlock.1003 *1004 * Returns null when the escrow is absent or decryption fails.1005 */1006async function deriveRootKeyFromDerivedKey(1007  derivedKeyBytes: Uint8Array,1008  slotA: StoredVault,1009): Promise<Uint8Array | null> {1010  if (!slotA.pw_root_ciphertext || !slotA.pw_root_nonce || !slotA.pw_root_tag) {1011    return null;1012  }1013  try {1014    const rootHex = await decrypt(1015      derivedKeyBytes,1016      slotA.pw_root_nonce,1017      slotA.pw_root_ciphertext,1018      slotA.pw_root_tag,1019      "pw_root_v1",1020    );1021    return unhex(rootHex);1022  } catch {1023    return null;1024  }1025}10261027export async function sealIdentityKeyUnderVault(ik: Uint8Array): Promise<IdentityKeyEnvelope> {1028  if (vaultMode !== "real" || !rootKey || !derivedKey) throw new Error("vault_locked");1029  // The root wrap survives password change and recovery-words re-key; the1030  // local wrap is available during normal unlock. Pending is only pre-vault.1031  const [root, local] = await Promise.all([1032    encrypt(rootKey, hex(ik), "peach-local-identity-ik-root-v1"),1033    encrypt(derivedKey, hex(ik), "peach-local-identity-ik-local-v1"),1034  ]);1035  return { root, local };1036}10371038export async function sealIdentityKeyPreVault(1039  password: string,1040  ik: Uint8Array,1041): Promise<IdentityKeyEnvelope> {1042  const salt = generateSalt();1043  const key = await deriveKey(password, salt);1044  try {1045    const pending = await encrypt(key, hex(ik), "peach-local-identity-ik-pending-v1");1046    return { pending, pendingSalt: hex(salt) };1047  } finally {1048    zeroKey(key);1049  }1050}10511052/**1053 * Open the identity key with any wrapping key that is currently available:1054 * the live vault-unlock key, then the vault root key, then the pre-vault1055 * password. Each attempt is awaited only after the previous one fails, so a1056 * successful early unwrap never leaves a later decrypt rejection unobserved,1057 * and the pre-vault Argon2id is not paid when a vault key already opens the1058 * envelope.1059 */1060export async function openIdentityKey(1061  env: IdentityKeyEnvelope,1062  password?: string,1063): Promise<Uint8Array | null> {1064  if (env.local && derivedKey) {1065    const ik = await openSealedKey(derivedKey, env.local, "peach-local-identity-ik-local-v1");1066    if (ik) return ik;1067  }1068  if (env.root && rootKey) {1069    const ik = await openSealedKey(rootKey, env.root, "peach-local-identity-ik-root-v1");1070    if (ik) return ik;1071  }1072  if (!env.pending || !env.pendingSalt || password === undefined) return null;1073  let key: Uint8Array;1074  try {1075    const salt = unhex(env.pendingSalt);1076    key = await deriveKey(password, salt);1077    salt.fill(0);1078  } catch {1079    return null;1080  }1081  try {1082    return await openSealedKey(key, env.pending, "peach-local-identity-ik-pending-v1");1083  } finally {1084    zeroKey(key);1085  }1086}10871088/** Decrypt a sealed 32-byte key; null for a wrong key, a bad shape, or corrupt bytes. */1089async function openSealedKey(1090  key: Uint8Array,1091  box: SealedBox,1092  info: string,1093): Promise<Uint8Array | null> {1094  try {1095    const value = unhex(await decrypt(key, box.nonce, box.ciphertext, box.tag, info));1096    if (value.length === 32) return value;1097    value.fill(0);1098    return null;1099  } catch {1100    return null;1101  }1102}11031104// AES-GCM-wrap rootKey under derivedKey for the pw_root_* fields. Returns the1105// hex-encoded ciphertext/nonce/tag triple ready to embed in StoredVault.1106async function wrapRootKeyForDerivedKey(1107  derivedKeyBytes: Uint8Array,1108  rootKeyBytes: Uint8Array,1109): Promise<{ pw_root_ciphertext: string; pw_root_nonce: string; pw_root_tag: string }> {1110  const { nonce, ciphertext, tag } = await encrypt(derivedKeyBytes, hex(rootKeyBytes), "pw_root_v1");1111  return {1112    pw_root_ciphertext: ciphertext,1113    pw_root_nonce: nonce,1114    pw_root_tag: tag,1115  };1116}11171118/** Returns the 12 recovery words for the current session's root key. */1119export async function getRecoveryWords(): Promise<string[]> {1120  if (!rootKey) {1121    throw new Error("recovery not set up");1122  }1123  return rootKeyToWords(rootKey);1124}11251126async function loadSlot(key: string): Promise<StoredVault | null> {1127  const result = await chrome.storage.local.get(key);1128  return (result as Record<string, StoredVault | undefined>)[key] ?? null;1129}11301131async function writeSlot(key: string, vault: StoredVault): Promise<void> {1132  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");1133  vaultWritesInFlight++;1134  try {1135    await chrome.storage.local.set({ [key]: vault });1136  } catch (err) {1137    throw mapStorageError(err);1138  } finally {1139    vaultWritesInFlight--;1140  }1141}11421143/**1144 * Roll back a vault that was created by [createVaultFromRootKey] but1145 * couldn't be paired (e.g. the subsequent license activation, identity1146 * derivation, or paired-device upsert failed). Without this, a failed1147 * receiver session leaves behind an empty vault — the user has to1148 * re-pair to get a working setup, but the empty vault sits in the way.1149 *1150 * The call is idempotent: removing keys that aren't there is a no-op.1151 */1152export async function rollbackAdoptedVault(): Promise<void> {1153  await withVaultRemoval(async () => {1154    try {1155      await chrome.storage.local.remove([1156        SLOT_A,1157        SLOT_B,1158        "peach_last_modified_at",1159      ]);1160    } catch (err) {1161      throw mapStorageError(err);1162    }1163  });1164}11651166async function commitCreatedVaultSlots(slotA: StoredVault, slotB: StoredVault): Promise<void> {1167  if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1168  vaultWritesInFlight++;1169  try {1170    const raw = await chrome.storage.local.get("peach_last_modified_at");1171    const previous = Number(1172      (raw as Record<string, unknown>).peach_last_modified_at,1173    );1174    const next = Math.max(1175      Date.now(),1176      Number.isFinite(previous) ? previous + 1 : 0,1177    );1178    try {1179      if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1180      await chrome.storage.local.set({1181        [SLOT_A]: slotA,1182        [SLOT_B]: slotB,1183        peach_last_modified_at: String(next),1184      });1185    } catch (err) {1186      throw mapStorageError(err);1187    }1188  } finally {1189    vaultWritesInFlight--;1190  }1191}11921193// Monotonic clock for per-entry modifiedAt / deletedAt timestamps. Guards the1194// sync layer's last-write-wins merge against wall-clock regressions (NTP step,1195// manual clock change, DST glitch): a backwards Date.now() must never produce1196// an entry timestamp that's <= the entry's existing modifiedAt, or a genuine1197// local edit would lose to a stale remote copy. The returned value is always1198// strictly greater than both the entry's current modifiedAt and the previous1199// call's result (SEV-2-E).1200let lastEntryTimestamp = 0;1201function monotonicEntryTimestamp(currentModifiedAt?: number): number {1202  const base = Math.max(1203    Date.now(),1204    (currentModifiedAt ?? 0) + 1,1205    lastEntryTimestamp + 1,1206  );1207  lastEntryTimestamp = base;1208  return base;1209}12101211async function stampLocalVaultMutation(): Promise<void> {1212  if (vaultCreatesInFlight) throw new Error("vault_changed");1213  const raw = await chrome.storage.local.get("peach_last_modified_at");1214  const previous = Number(1215    (raw as Record<string, unknown>).peach_last_modified_at,1216  );1217  const next = Math.max(1218    Date.now(),1219    Number.isFinite(previous) ? previous + 1 : 0,1220  );1221  if (vaultCreatesInFlight) throw new Error("vault_changed");1222  await chrome.storage.local.set({1223    peach_last_modified_at: String(next),1224  });1225}12261227// ---------------------------------------------------------------------------1228// Padding + noise helpers1229// ---------------------------------------------------------------------------12301231/**1232 * Pads the plaintext string with trailing spaces so that the encoded byte1233 * length is a multiple of PAD_BLOCK. JSON.parse tolerates trailing1234 * whitespace after a complete document, so the padding is transparent on1235 * decode. Ciphertext length equals plaintext length plus a 16-byte tag.1236 */1237function padPlaintext(json: string, minBytes = 0): string {1238  const encoded = new TextEncoder().encode(json);1239  const bucket = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);1240  // minBytes lets the duress path force a fixed ceiling so both slots match.1241  const target = Math.max(bucket, minBytes);1242  const padLen = target - encoded.length;1243  return json + " ".repeat(padLen);1244}12451246/**1247 * Produces a StoredVault-shaped record filled with CSPRNG bytes. The1248 * ciphertext length matches the given byte count. Because GCM ciphertext is1249 * pseudo-random, this blob is indistinguishable at rest from a real1250 * encrypted vault without the key.1251 *1252 * crypto.getRandomValues() caps each call at 65536 bytes (the Web Crypto1253 * spec hard limit). Chunk the fill so vaults larger than that — common once1254 * the user has dozens of entries or any passkey — don't throw.1255 */1256const CSPRNG_CHUNK = 65_536;12571258function fillRandom(buf: Uint8Array): Uint8Array {1259  for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {1260    const end = Math.min(offset + CSPRNG_CHUNK, buf.length);1261    const chunk = new Uint8Array(end - offset);1262    crypto.getRandomValues(chunk);1263    buf.set(chunk, offset);1264  }1265  return buf;1266}12671268function generateNoiseBlob(ciphertextBytes: number): StoredVault {1269  const salt = crypto.getRandomValues(new Uint8Array(16));1270  const nonce = crypto.getRandomValues(new Uint8Array(12));1271  const cipher = fillRandom(new Uint8Array(ciphertextBytes));1272  const tag = crypto.getRandomValues(new Uint8Array(16));1273  return {1274    version: 1,1275    salt: hex(salt),1276    nonce: hex(nonce),1277    ciphertext: hex(cipher),1278    tag: hex(tag),1279  };1280}12811282// ---------------------------------------------------------------------------1283// Encrypted plaintext envelope1284// ---------------------------------------------------------------------------12851286type VaultPayload = {1287  entries: VaultEntry[];1288  tombstones?: Record<string, number>;1289  duressConfigured?: boolean;1290};12911292type DecryptedPayload = {1293  entries: VaultEntry[];1294  tombstones: Map<string, number>;1295  duressConfigured: boolean;1296};12971298function encodePayload(entries: VaultEntry[], duress: boolean, minBytes = 0): string {1299  const envelope: VaultPayload = {1300    entries,1301    tombstones: Object.fromEntries(tombstones),1302    duressConfigured: duress,1303  };1304  return padPlaintext(JSON.stringify(envelope), minBytes);1305}13061307function decodeTombstones(raw: unknown, allEntries: VaultEntry[]): Map<string, number> {1308  const result = new Map<string, number>();1309  if (raw && typeof raw === "object" && !Array.isArray(raw)) {1310    for (const [id, timestamp] of Object.entries(raw as Record<string, unknown>)) {1311      if (typeof timestamp === "number" && Number.isFinite(timestamp) && timestamp > 0) {1312        result.set(id, timestamp);1313      }1314    }1315  }1316  // Older payloads had no ledger. Rebuild the durable portion from any1317  // soft-deleted entries before they are eligible for a later purge.1318  for (const entry of allEntries) {1319    if (typeof entry.deletedAt !== "number" || !Number.isFinite(entry.deletedAt) || entry.deletedAt <= 0) {1320      continue;1321    }1322    if ((result.get(entry.id) ?? 0) < entry.deletedAt) {1323      result.set(entry.id, entry.deletedAt);1324    }1325  }1326  return result;1327}13281329function reconcileTombstones(): void {1330  const byId = new Map(entries.map((entry) => [entry.id, entry]));1331  for (const [id] of tombstones) {1332    if (byId.has(id) && !byId.get(id)?.deletedAt) tombstones.delete(id);1333  }1334  for (const entry of entries) {1335    if (typeof entry.deletedAt === "number" && Number.isFinite(entry.deletedAt) && entry.deletedAt > 0) {1336      if ((tombstones.get(entry.id) ?? 0) < entry.deletedAt) {1337        tombstones.set(entry.id, entry.deletedAt);1338      }1339    }1340  }1341}13421343function decodePayload(plain: string): DecryptedPayload {1344  const parsed = JSON.parse(plain) as VaultPayload;1345  if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.entries)) {1346    throw new Error("invalid vault payload");1347  }1348  const normalized = parsed.entries.map(normalizeEntry);1349  return {1350    entries: normalized,1351    tombstones: decodeTombstones(parsed.tombstones, normalized),1352    duressConfigured: parsed.duressConfigured === true,1353  };1354}13551356// Keep ambiguous records intact: an RP or account can own several credentials.1357function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {1358  let merged = false;1359  const transferable = new Set(["id", "type", "title", "username", "url", "passkey", "createdAt", "modifiedAt", "totp", "totpAlgorithm", "totpDigits", "totpPeriod"]);1360  for (const source of entries.filter((entry) => !entry.deletedAt && entry.passkey)) {1361    const passkey = source.passkey!;1362    if (source.type !== "login" && source.type !== "passkey") continue;1363    if (!passkey.userName || (source.username && source.username !== passkey.userName)) continue;1364    if (Object.entries(source).some(([key, value]) => !transferable.has(key) && value !== undefined && value !== "")) continue;1365    const targets = entries.filter((entry) => {1366      if (entry.deletedAt || entry.passkey || entry.type !== "login" || entry.username !== passkey.userName) return false;1367      return [entry.url, ...(entry.additionalUrls ?? [])].some((url) => {1368        if (!url) return false;1369        try {1370          return new URL(url.includes("://") ? url : `https://${url}`).hostname === passkey.rpId;1371        } catch {1372          return false;1373        }1374      });1375    });1376    if (targets.length !== 1) continue;1377    const target = targets[0]!;1378    if (source.totp && target.totp && (source.totp !== target.totp || source.totpAlgorithm !== target.totpAlgorithm || source.totpDigits !== target.totpDigits || source.totpPeriod !== target.totpPeriod)) continue;1379    target.passkey = passkey;1380    if (source.totp && !target.totp) {1381      target.totp = source.totp;1382      target.totpAlgorithm = source.totpAlgorithm;1383      target.totpDigits = source.totpDigits;1384      target.totpPeriod = source.totpPeriod;1385    }1386    const stamp = monotonicEntryTimestamp(Math.max(source.modifiedAt, target.modifiedAt));1387    target.modifiedAt = stamp;1388    source.modifiedAt = stamp;1389    source.deletedAt = stamp;1390    merged = true;1391  }1392  return { merged };1393}13941395// Validates that a `StoredVault` record on disk has the field shape we expect1396// before treating an AES-GCM decrypt success as a clean unlock. AES-GCM only1397// authenticates the static VERSION_BYTE AAD, not the `version` field on the1398// outer record — a corrupted `version: 42` slot still decrypts cleanly. This1399// check surfaces that as `corrupted` (M7/COR-007) so the popup can offer a1400// history-restore path instead of falsely reporting "wrong password".1401function hasValidVaultSchema(v: unknown): v is StoredVault {1402  if (typeof v !== "object" || v === null) return false;1403  const r = v as Record<string, unknown>;1404  return (1405    r.version === 1 &&1406    typeof r.salt === "string" &&1407    typeof r.nonce === "string" &&1408    typeof r.ciphertext === "string" &&1409    typeof r.tag === "string"1410  );1411}1412const MAX_HISTORY_BLOB_BYTES = 1_024 * 1_024;14131414function hasValidHistorySlot(value: unknown): value is StoredVault {1415  if (!hasValidVaultSchema(value)) return false;1416  return /^[0-9a-f]{32}$/i.test(value.salt) &&1417    /^[0-9a-f]{24}$/i.test(value.nonce) &&1418    /^[0-9a-f]+$/i.test(value.ciphertext) &&1419    value.ciphertext.length % 2 === 0 &&1420    value.ciphertext.length / 2 <= MAX_HISTORY_BLOB_BYTES &&1421    /^[0-9a-f]{32}$/i.test(value.tag);1422}14231424function parseHistorySlot(value: string): StoredVault | null {1425  try {1426    const parsed: unknown = JSON.parse(value);1427    return hasValidHistorySlot(parsed) ? parsed : null;1428  } catch {1429    return null;1430  }1431}14321433function isHistoryRecord(value: unknown): value is VaultSnapshot {1434  if (typeof value !== "object" || value === null) return false;1435  const record = value as Record<string, unknown>;1436  return typeof record.id === "string" && record.id.length > 0 && record.id.length <= 128 &&1437    typeof record.savedAt === "number" && Number.isFinite(record.savedAt) &&1438    typeof record.reason === "string" &&1439    typeof record.vault_a === "string" && record.vault_a.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1440    typeof record.vault_b === "string" && record.vault_b.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1441    (record.entryCount === null || typeof record.entryCount === "number");1442}14431444function sanitizeHistory(value: unknown): VaultSnapshot[] {1445  if (typeof value !== "object" || value === null) return [];1446  if (!("snapshots" in value) || !Array.isArray(value.snapshots)) return [];1447  return value.snapshots.filter(isHistoryRecord).slice(0, HISTORY_MAX);1448}14491450export type TryDecryptResult =1451  | { status: "ok"; payload: DecryptedPayload }1452  | { status: "wrong_key" }1453  | { status: "corrupted"; reason: string };14541455// Exported solely for `unlockFromCodex` below, which needs to verify a1456// supplied passphrase against a slotA blob *without* committing anything to1457// storage. Keep this internal otherwise — callers crossing the messages.ts1458// boundary should always go through `unlock` / `verifyMainPassword` so the1459// constant-time invariants in Projects.md §3.4 are not bypassed.1460export async function tryDecryptSlot(1461  vault: StoredVault,1462  key: Uint8Array,1463  aadTag?: string,1464): Promise<DecryptedPayload | null> {1465  const res = await tryDecryptSlotResult(vault, key, aadTag);1466  return res.status === "ok" ? res.payload : null;1467}14681469export async function tryDecryptSlotResult(1470  vault: StoredVault,1471  key: Uint8Array,1472  aadTag?: string,1473): Promise<TryDecryptResult> {1474  if (!hasValidVaultSchema(vault)) {1475    return { status: "corrupted", reason: "invalid_slot_schema" };1476  }1477  let plain: string;1478  try {1479    plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);1480  } catch {1481    return { status: "wrong_key" };1482  }1483  try {1484    const parsed = JSON.parse(plain) as unknown;1485    if (typeof parsed !== "object" || parsed === null) {1486      return { status: "corrupted", reason: "invalid_payload_shape" };1487    }1488    if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {1489      return { status: "corrupted", reason: "invalid_payload_shape" };1490    }1491    return { status: "ok", payload: decodePayload(plain) };1492  } catch {1493    return { status: "corrupted", reason: "invalid_payload_json" };1494  }1495}14961497// ---------------------------------------------------------------------------1498// Core operations1499// ---------------------------------------------------------------------------15001501function buildDomainIndexSync(all: VaultEntry[]): void {1502  domainIndex = new Map();15031504  for (const entry of all) {1505    if (entry.deletedAt) continue;1506    if (entry.type === "note" || entry.type === "card") continue;15071508    // An entry can match multiple sites via `additionalUrls`. Index each1509    // hostname so `queryDomain` returns the entry regardless of which alias1510    // the user is currently visiting. Dedupe per-entry so a single entry1511    // never appears twice in one bucket.1512    const domains = new Set<string>();1513    const primary = extractDomain(entry.url ?? "");1514    if (primary) domains.add(primary);1515    for (const extra of entry.additionalUrls ?? []) {1516      const d = extractDomain(extra);1517      if (d) domains.add(d);1518    }1519    if (domains.size === 0) continue;15201521    for (const domain of domains) {1522      const bucket = domainIndex.get(domain) ?? [];1523      bucket.push(entry);1524      domainIndex.set(domain, bucket);1525    }1526  }1527}15281529export async function createVault(password: string, replacement?: "warned-import"): Promise<{ committed: true; unlocked: boolean }> {1530  if (replacement !== undefined && replacement !== "warned-import") throw new Error("invalid_payload");1531  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");1532  vaultCreatesInFlight++;1533  let settle!: () => void;1534  creationSettled = new Promise<void>((resolve) => { settle = resolve; });1535  let nextKey: Uint8Array | null = null;1536  let nextRoot: Uint8Array | null = null;1537  let committed = false;1538  let publishedEpoch: number | null = null;1539  const epoch = vaultEpoch;1540  const check = () => {1541    if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1542  };1543  try {1544    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1545    check();1546    const occupied = raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;1547    if (occupied && replacement !== "warned-import") throw new Error("vault_already_exists");1548    const salt = generateSalt();1549    nextKey = await deriveKey(password, salt);1550    check();1551    const recovery = await generateAndWrapRootKey();1552    nextRoot = unhex(recovery.rawRootKey);1553    check();1554    const encrypted = await encrypt(nextKey, encodePayload([], false, 0), "slot_a_v1");1555    const pwRoot = await wrapRootKeyForDerivedKey(nextKey, nextRoot);1556    const recoveryVaultKey = await encrypt(nextRoot, hex(nextKey), "recovery_vault_key_v1");1557    check();1558    const slotA: StoredVault = {1559      ...encrypted, ...pwRoot, version: 1, salt: hex(salt),1560      recovery_vault_key: recoveryVaultKey,1561      recovery_salt: recovery.recoverySalt,1562      recovery_wrapped_root_key: recovery.wrappedRootKey,1563      recovery_nonce: recovery.wrappedNonce,1564      recovery_tag: recovery.wrappedTag,1565    };1566    const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1567    check();1568    if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");1569    const previous = Number(raw.peach_last_modified_at);1570    const update: Record<string, unknown> = {1571      [SLOT_A]: slotA, [SLOT_B]: generateNoiseBlob(encrypted.ciphertext.length / 2),1572      peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previous) ? previous + 1 : 0)),1573    };1574    if (occupied) {1575      const history = raw[HISTORY_KEY] as VaultHistory | undefined;1576      const snapshot: VaultSnapshot = {1577        id: crypto.randomUUID(), savedAt: Date.now(), reason: "restore", entryCount: null,1578        vault_a: JSON.stringify(raw[SLOT_A] ?? null), vault_b: JSON.stringify(raw[SLOT_B] ?? null),1579      };1580      update[HISTORY_KEY] = { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) };1581    }1582    try { await chrome.storage.local.set(update); }1583    catch (error) { throw mapStorageError(error); }1584    committed = true;1585    if (epoch !== vaultEpoch || vaultRemovalsInFlight) return { committed: true, unlocked: false };1586    const previousKey = derivedKey;1587    const previousRoot = rootKey;1588    cancelBreachScan();1589    publishedEpoch = ++vaultEpoch;1590    derivedKey = nextKey;1591    rootKey = nextRoot;1592    nextKey = null;1593    nextRoot = null;1594    entries = [];1595    tombstones = new Map();1596    vaultMode = "real";1597    duressConfigured = false;1598    buildDomainIndexSync(entries);1599    if (previousKey) zeroKey(previousKey);1600    if (previousRoot) zeroKey(previousRoot);1601    await clearSessionKey();1602    if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1603    await identityHooks?.onVaultCreated(password).catch((error) => {1604      console.warn("[Peach] local identity promotion failed:", error);1605    });1606    if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1607    touchAutoLock();1608    return { committed: true, unlocked: true };1609  } catch (error) {1610    if (!committed) throw error;1611    console.warn("[Peach] vault saved; unlock required:", error);1612    if (publishedEpoch === vaultEpoch) {1613      await lock().catch((lockError) => console.warn("[Peach] creation session cleanup failed:", lockError));1614    }1615    return { committed: true, unlocked: false };1616  } finally {1617    if (nextKey) zeroKey(nextKey);1618    if (nextRoot) zeroKey(nextRoot);1619    vaultCreatesInFlight--;1620    settle();1621  }1622}16231624/**1625 * Creates a local vault from an existing vault root key received through the1626 * SAS-gated adoption protocol. The password is local to this device; it wraps1627 * the adopted root key at rest and does not need to match the source device.1628 */1629export async function createVaultFromRootKey(1630  password: string,1631  rootKeyHex: string,1632): Promise<{ vaultId: string }> {1633  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");1634  if (typeof password !== "string" || password.length === 0) {1635    throw new Error("ADOPT_INVALID_PASSWORD");1636  }1637  if (typeof rootKeyHex !== "string" || !/^[0-9a-f]{64}$/.test(rootKeyHex)) {1638    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars");1639  }16401641  if (vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");1642  const rootKeyBytes = unhex(rootKeyHex);1643  if (rootKeyBytes.length !== 32) {1644    rootKeyBytes.fill(0);1645    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");1646  }16471648  vaultCreatesInFlight++;1649  let settle!: () => void;1650  creationSettled = new Promise<void>((resolve) => { settle = resolve; });1651  const epoch = vaultEpoch;1652  let nextDerivedKey: Uint8Array | null = null;1653  let sessionRootKey: Uint8Array | null = null;1654  let committed = false;1655  try {1656    if (await hasVault()) {1657      throw new Error("ADOPT_VAULT_ALREADY_EXISTS");1658    }16591660    const nextEntries: VaultEntry[] = [];1661    const nextDuressConfigured = false;1662    const vaultId = await computeVaultId(rootKeyBytes);1663    const salt = generateSalt();1664    nextDerivedKey = await deriveKey(password, salt);1665    const recovery = await wrapExistingRootKeyForRecovery(rootKeyBytes);16661667    sessionRootKey = new Uint8Array(rootKeyBytes);1668    const plaintext = encodePayload(nextEntries, nextDuressConfigured, 0);1669    const { nonce, ciphertext, tag } = await encrypt(nextDerivedKey, plaintext, "slot_a_v1");1670    const pwRoot = await wrapRootKeyForDerivedKey(nextDerivedKey, sessionRootKey);1671    const slotA: StoredVault = {1672      recovery_vault_key: await encrypt(sessionRootKey, hex(nextDerivedKey), "recovery_vault_key_v1"),1673      version: 1,1674      salt: hex(salt),1675      nonce,1676      ciphertext,1677      tag,1678      recovery_salt: recovery.recoverySalt,1679      recovery_wrapped_root_key: recovery.wrappedRootKey,1680      recovery_nonce: recovery.wrappedNonce,1681      recovery_tag: recovery.wrappedTag,1682      ...pwRoot,1683    };1684    const slotB = generateNoiseBlob(ciphertext.length / 2);1685    if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1686    await commitCreatedVaultSlots(slotA, slotB);1687    committed = true;1688    if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1689    cancelBreachScan();1690    vaultEpoch++;16911692    const previousDerivedKey = derivedKey;1693    const previousRootKey = rootKey;1694    derivedKey = nextDerivedKey;1695    rootKey = sessionRootKey;1696    nextDerivedKey = null;1697    sessionRootKey = null;1698    entries = nextEntries;1699    tombstones = new Map();1700    vaultMode = "real";1701    duressConfigured = nextDuressConfigured;1702    buildDomainIndexSync(entries);1703    if (previousDerivedKey && previousDerivedKey !== derivedKey) zeroKey(previousDerivedKey);1704    if (previousRootKey && previousRootKey !== rootKey) previousRootKey.fill(0);1705    touchAutoLock();17061707    // The receiver's identity was minted before this vault existed (adoption v21708    // needs it in its first frame), so re-seal it under the vault keys now.1709    await identityHooks?.onVaultCreated(password).catch((error) => {1710      console.warn("[Peach] local identity promotion failed:", error);1711    });17121713    return { vaultId };1714  } catch (error) {1715    if (committed) {1716      // Removal cannot use withVaultRemoval while this operation owns creationSettled.1717      try { await lock(); }1718      finally { await chrome.storage.local.remove([SLOT_A, SLOT_B, "peach_last_modified_at"]); }1719    }1720    throw error;1721  } finally {1722    vaultCreatesInFlight--;1723    settle();1724    rootKeyBytes.fill(0);1725    if (nextDerivedKey) zeroKey(nextDerivedKey);1726    if (sessionRootKey) sessionRootKey.fill(0);1727  }1728}17291730export async function hasVault(): Promise<boolean> {1731  const raw = await chrome.storage.local.get([SLOT_A, SLOT_B]);1732  return raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;1733}17341735/**1736 * Returns whether the real vault has recorded that a duress passphrase is1737 * configured. Reliable only after a real-mode unlock — before unlock or in1738 * decoy mode, returns false because we cannot read slot A's plaintext.1739 */1740export async function isDuressEnabled(): Promise<boolean> {1741  return vaultMode === "real" && duressConfigured;1742}17431744export async function setupDuress(duressPassword: string): Promise<void> {1745  if (vaultCreatesInFlight) throw new Error("vault_changed");1746  vaultWritesInFlight++;1747  try {1748  if (!derivedKey || vaultMode !== "real") {1749    throw new Error("vault must be unlocked in real mode");1750  }1751  // Encrypt the decoy payload (empty entries) under the duress key. Pad to1752  // at least the current slot A ciphertext size so the two slots look the1753  // same at rest at setup time.1754  const slotA = await loadSlot(SLOT_A);1755  if (!slotA) throw new Error("missing slot A");17561757  const decoySalt = generateSalt();1758  const decoyKey = await deriveKey(duressPassword, decoySalt);1759  try {1760    // Pad the decoy to the fixed duress ceiling. Slot A is re-encrypted to the1761    // same ceiling by the persistSlotA() call below (duressConfigured is now1762    // true), so both slots are exactly DURESS_SLOT_SIZE+tag at rest and their1763    // lengths cannot reveal that duress is configured (audit MEDIUM).1764    const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);1765    const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");1766    await writeSlot(SLOT_B, {1767      version: 1,1768      salt: hex(decoySalt),1769      nonce,1770      ciphertext,1771      tag,1772    });1773  } finally {1774    zeroKey(decoyKey);1775  }17761777  // Re-encrypt slot A with the duressConfigured flag set to true. No external1778  // flag is written — the bit lives inside the encrypted envelope.1779  duressConfigured = true;1780  await persistSlotA();1781  } finally { vaultWritesInFlight--; }1782}17831784export async function disableDuress(): Promise<void> {1785  if (vaultCreatesInFlight) throw new Error("vault_changed");1786  vaultWritesInFlight++;1787  try {1788  if (!derivedKey || vaultMode !== "real") {1789    throw new Error("vault must be unlocked in real mode");1790  }1791  // Overwrite slot B with fresh noise that matches slot A's size. The slot1792  // remains occupied so its mere existence does not signal that duress was1793  // ever configured.1794  const slotA = await loadSlot(SLOT_A);1795  if (slotA) {1796    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));1797  }17981799  duressConfigured = false;1800  await persistSlotA();1801  } finally { vaultWritesInFlight--; }1802}18031804// L14/COR-015: this function intentionally checks slot A (real vault) only.1805// A duress-mode user attempting changePassword is rejected earlier by the1806// vaultMode === 'decoy' check at changePassword. The real-vs-decoy1807// distinction here is by design — duress users cannot rotate the real1808// password by guessing it, and the asymmetry in error timing is acceptable1809// because duress mode is opt-in and the user knows their own decoy key.1810export async function verifyMainPassword(password: string): Promise<boolean> {1811  const slotA = await loadSlot(SLOT_A);1812  if (!slotA) return false;1813  const key = await deriveKey(password, unhex(slotA.salt));1814  try {1815    return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;1816  } finally {1817    zeroKey(key);1818  }1819}18201821export async function unlock(password: string): Promise<boolean> {1822  return attemptUnlockWithDerive(password, deriveKey);1823}18241825async function attemptUnlockWithDerive(1826  password: string,1827  derive: typeof deriveKey,1828): Promise<boolean> {1829  vaultUnlocksInFlight++;1830  try {1831  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;1832  const epoch = vaultEpoch;1833  const stale = () => epoch !== vaultEpoch;1834  await revokeRecoveryReveal();1835  if (stale()) return false;1836  // Load both current-format slots in parallel. Both exist on a supported1837  // install; the1838  // parallel load and the parallel derivation below keep wall-clock time1839  // constant regardless of which slot's passphrase (real or decoy) the1840  // caller supplied, so a timing side channel cannot distinguish the1841  // duress path from the real-unlock path (DUR-002).1842  const [slotA, slotB] = await Promise.all([1843    loadSlot(SLOT_A),1844    loadSlot(SLOT_B),1845  ]);18461847  // Derive both keys in parallel, unconditionally.1848  const [keyA, keyB] = await Promise.all([1849    slotA ? derive(password, unhex(slotA.salt)) : Promise.resolve(null),1850    slotB ? derive(password, unhex(slotB.salt)) : Promise.resolve(null),1851  ]);18521853  // Attempt both decrypts in parallel. The Result variant lets us distinguish1854  // 'wrong_key' from 'corrupted' so callers can offer a history-restore path1855  // when a slot's schema is invalid even though AES-GCM authenticated (M7).1856  const [resultA, resultB] = await Promise.all([1857    keyA && slotA1858      ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")1859      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1860    keyB && slotB1861      ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")1862      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1863  ]);1864  const payloadA = resultA.status === "ok" ? resultA.payload : null;1865  const payloadB = resultB.status === "ok" ? resultB.payload : null;18661867  if (stale()) {1868    if (keyA) zeroKey(keyA);1869    if (keyB) zeroKey(keyB);1870    return false;1871  }18721873  if (payloadA && keyA) {1874    if (stale()) {1875      zeroKey(keyA);1876      if (keyB) zeroKey(keyB);1877      return false;1878    }1879    cancelBreachScan();1880    derivedKey = keyA;1881    vaultMode = "real";1882    entries = payloadA.entries;1883    tombstones = payloadA.tombstones;1884    duressConfigured = payloadA.duressConfigured;1885    buildDomainIndexSync(entries);1886    await loadSettings();1887    if (stale()) {1888      await lock();1889      return false;1890    }1891    touchAutoLock();1892    if (keyB) zeroKey(keyB);18931894    // Current vaults always carry a password-wrapped root key. Older vaults1895    // without this escrow are outside the supported storage format.1896    rootKey = slotA ? await deriveRootKeyFromDerivedKey(keyA, slotA) : null;1897    if (!rootKey) {1898      await lock();1899      return false;1900    }19011902    // Repair missing or stale escrow only after a real password authenticates the slot.1903    if (slotA) {1904      const escrowed = slotA.recovery_vault_key1905        ? await openSealedKey(rootKey, slotA.recovery_vault_key, "recovery_vault_key_v1") : null;1906      const matches = escrowed !== null && escrowed.every((byte, i) => byte === keyA[i]);1907      if (escrowed) zeroKey(escrowed);1908      if (stale()) { await lock(); return false; }1909      if (!matches) {1910        try {1911          const recoveryVaultKey = await encrypt(rootKey, hex(keyA), "recovery_vault_key_v1");1912          if (stale()) { await lock(); return false; }1913          await writeSlot(SLOT_A, { ...slotA, recovery_vault_key: recoveryVaultKey });1914          if (stale()) { await lock(); return false; }1915        } catch (error) {1916          await lock();1917          throw error;1918        }1919      }1920    }19211922    // PB-26-213: adopt legacy plaintext pair secrets into the encrypted1923    // record and refresh the trusted-session operational copy.1924    await reconcilePairSecrets(rootKey);1925    if (stale()) {1926      await lock();1927      return false;1928    }1929    await lockedSyncUnlockHook?.().catch((error) => {1930      console.warn("[Peach sync] locked inbox drain failed:", error);1931    });1932    if (stale()) {1933      await lock();1934      return false;1935    }1936    await resetPinFailedAttempts();1937    if (stale()) {1938      await lock();1939      return false;1940    }1941    await saveSessionKey(keyA, "real", epoch);1942    if (stale()) return false;1943    return true;1944  }19451946  if (payloadB && keyB) {1947    if (stale()) {1948      zeroKey(keyB);1949      if (keyA) zeroKey(keyA);1950      return false;1951    }1952    cancelBreachScan();1953    derivedKey = keyB;1954    vaultMode = "decoy";1955    decoySyncTeardownHook?.();1956    // A duress session must not retain the real vault's root key. It gates the1957    // recovery words, the sync identity, and the root wrap of the local device1958    // identity, so leaving it live would expose all three in duress mode.1959    if (rootKey) {1960      rootKey.fill(0);1961      rootKey = null;1962    }1963    entries = payloadB.entries;1964    tombstones = payloadB.tombstones;1965    duressConfigured = false;1966    buildDomainIndexSync(entries);1967    await loadSettings();1968    touchAutoLock();1969    if (keyA) zeroKey(keyA);1970    // PB-26-213: a duress session must never serve the real pair-secret map.1971    await dropSessionCache();1972    // Nor the real device identity: a duress session is not a real one.1973    await notifyIdentitySessionEnded();1974    if (stale()) {1975      await lock();1976      return false;1977    }1978    await saveSessionKey(keyB, "decoy", epoch);1979    if (stale()) return false;1980    return true;1981  }19821983  if (keyA) zeroKey(keyA);1984  if (keyB) zeroKey(keyB);1985  // Surface corruption (good AES tag, broken schema) distinctly from1986  // wrong-password so the popup can offer history-restore (M7/COR-007).1987  if (resultA.status === "corrupted") {1988    lastUnlockFailureReason = resultA.reason;1989  } else if (resultB.status === "corrupted") {1990    lastUnlockFailureReason = resultB.reason;1991  }1992  return false;1993  } finally { vaultUnlocksInFlight--; }1994}19951996// ---------------------------------------------------------------------------1997// MV3 service worker session key — survives SW restarts within a browser session1998// ---------------------------------------------------------------------------19992000// chrome.storage.session is cleared on browser close; survives SW restart.2001// Firefox does not implement it (persistent background script, no restart risk).2002const SESSION_KEY_STORAGE = "peach_session_dk";20032004// Order writes and removals so lock's awaited removal is a barrier after2005// every escrow write that started before it.2006let sessionKeyMutation = Promise.resolve();20072008function mutateSessionKey(mutation: () => Promise<void>): Promise<void> {2009  const task = sessionKeyMutation.then(mutation, mutation);2010  sessionKeyMutation = task.catch(() => undefined);2011  return task;2012}20132014// PB-26-203: the session-key escrow may only operate where startup positively2015// established trusted-only session storage. Defaults to available so direct2016// vault imports (tests, non-entry bootstraps) keep working; entry.ts applies2017// the real hardening result before the first restore.2018let sessionEscrowAvailable = true;20192020/**2021 * Apply the storage-hardening result at startup. When the trusted-only2022 * session state cannot be established, any stored session key is removed and2023 * the escrow stays off: the user unlocks again after a worker restart2024 * instead of trusting an unproven boundary.2025 */2026export async function applyStorageHardening(sessionEscrow: boolean): Promise<void> {2027  setSessionAllowed(sessionEscrow);2028  if (sessionEscrow) return;2029  sessionEscrowAvailable = false;2030  await clearSessionKey();2031}20322033async function saveSessionKey(2034  key: Uint8Array,2035  mode: "real" | "decoy",2036  expectedEpoch = vaultEpoch,2037): Promise<void> {2038  const session = chrome.storage.session;2039  if (!session || !sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;2040  const stored = { keyHex: hex(key), mode };2041  await mutateSessionKey(async () => {2042    if (!sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;2043    await session.set({ [SESSION_KEY_STORAGE]: stored });2044  });2045}20462047async function clearSessionKey(): Promise<void> {2048  const session = chrome.storage.session;2049  if (!session) return;2050  await mutateSessionKey(() => session.remove(SESSION_KEY_STORAGE));2051}20522053// A lock that only holds while the service worker stays alive is no lock at2054// all: a cold worker's restoreFromSession() would find the surviving session2055// key and silently re-unlock ~a minute after the user locked. So lock()2056// bumps this epoch synchronously at entry and zeroes keys/indexes before any2057// await; a restore that started earlier sees the mismatch after its next2058// await and aborts instead of publishing.2059let vaultEpoch = 0;20602061// One in-flight restore shared by concurrent callers: storage is read once2062// and the locked-sync unlock hook runs once.2063let restoreInFlight: Promise<boolean> | null = null;20642065/**2066 * On SW restart, re-derive all in-memory vault state from the session key2067 * stored in chrome.storage.session (set at unlock time, cleared by lock();2068 * also cleared on browser close or when restoration fails).2069 * Returns true if the vault was restored, false if no session key was found.2070 * No-ops if the vault is already unlocked.2071 */2072export async function restoreFromSession(): Promise<boolean> {2073  vaultUnlocksInFlight++;2074  try {2075  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;2076  if (derivedKey !== null) return true;2077  if (restoreInFlight) return restoreInFlight;2078  const task = restoreFromSessionInner();2079  restoreInFlight = task;2080  try {2081    return await task;2082  } finally {2083    restoreInFlight = null;2084  }2085  } finally { vaultUnlocksInFlight--; }2086}20872088async function restoreFromSessionInner(): Promise<boolean> {2089  const epoch = vaultEpoch;2090  const stale = () => epoch !== vaultEpoch;2091  if (derivedKey !== null) return true;2092  if (!sessionEscrowAvailable) return false;2093  if (!chrome.storage.session) return false;2094  const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);2095  if (stale()) return false;2096  const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;2097  if (!entry?.keyHex) return false;20982099  const key = unhex(entry.keyHex);2100  const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;2101  const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";2102  const slot = await loadSlot(slotKey);2103  if (stale()) { zeroKey(key); return false; }2104  if (!slot) { await clearSessionKey(); return false; }21052106  const result = await tryDecryptSlotResult(slot, key, aadTag);2107  if (stale()) { zeroKey(key); return false; }2108  if (result.status !== "ok") { await clearSessionKey(); return false; }21092110  // Decrypted payload stays in locals until the final epoch-checked commit2111  // below; nothing observable is published before then.2112  const payload = result.payload;2113  await loadSettings();2114  if (stale()) { zeroKey(key); return false; }21152116  // Rehydrate the root key used by sync identity derivation from the password2117  // escrow stored on the current vault format.2118  let freshRoot: Uint8Array | null = null;2119  if (entry.mode === "real") {2120    freshRoot = await deriveRootKeyFromDerivedKey(key, slot);2121    if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }2122    if (!freshRoot) {2123      await lock();2124      return false;2125    }2126  }21272128  if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }2129  if (freshRoot) {2130    // PB-26-213: encrypted pair-secret record + session copy, before publish.2131    await reconcilePairSecrets(freshRoot);2132    if (stale()) { zeroKey(key); zeroKey(freshRoot); return false; }2133  } else {2134    // PB-26-213: a duress restore must never serve the real pair-secret map.2135    await dropSessionCache();2136    // Nor the real device identity.2137    await notifyIdentitySessionEnded();2138    if (stale()) { zeroKey(key); return false; }2139  }2140  cancelBreachScan();2141  derivedKey = key;2142  vaultMode = entry.mode;2143  if (entry.mode === "decoy") decoySyncTeardownHook?.();2144  entries = payload.entries;2145  tombstones = payload.tombstones;2146  duressConfigured = entry.mode === "real" ? payload.duressConfigured : false;2147  if (freshRoot) rootKey = freshRoot;2148  buildDomainIndexSync(entries);2149  touchAutoLock();21502151  await lockedSyncUnlockHook?.().catch((error) => {2152    console.warn("[Peach sync] locked inbox drain failed:", error);2153  });2154  if (stale()) return false;21552156  return true;2157}21582159export async function lock(): Promise<void> {2160  const recoveryRevoked = revokeRecoveryReveal();2161  // A user-initiated lock must be durable across MV3 service-worker restarts.2162  // The SW is idle-killed after ~30s of inactivity, and the popup's next open2163  // wakes a cold SW whose restoreFromSession() reads chrome.storage.session.2164  // If the session key survived lock(), that restore would silently re-unlock2165  // the vault ~a minute after the user locked it — a lock that only held2166  // while the SW happened to stay alive. The background-sync convenience the2167  // session key once bought (sync runner re-waking to a restored vault) is2168  // not worth an unlocked vault the user never asked to unlock; when locked,2169  // sync-runner correctly reports VAULT_LOCKED instead.2170  cancelBreachScan();2171  vaultEpoch++;2172  if (derivedKey) {2173    zeroKey(derivedKey);2174    derivedKey = null;2175  }2176  if (rootKey) {2177    rootKey.fill(0);2178    rootKey = null;2179  }21802181  entries = [];2182  tombstones = new Map();2183  domainIndex = new Map();2184  vaultMode = "real";2185  duressConfigured = false;2186  clearAutoLock();2187  try {2188    chrome.runtime?.sendMessage?.({ type: "VAULT_LOCKED" })?.catch?.(() => undefined);2189  } catch { /* UI contexts may already be closed */ }2190  await clearSessionKey();2191  await recoveryRevoked;2192  // The decrypted identity is session state as well, so a locked vault must not2193  // leave one behind; clear it after the in-memory state is gone.2194  await notifyIdentitySessionEnded();2195}21962197/// Identifies the current unlock session for authorization across awaited work.2198export function getVaultEpoch(): number {2199  return vaultEpoch;2200}22012202export function isUnlocked(): boolean {2203  return derivedKey !== null;2204}2205/** True only while the active session is unlocked through the decoy slot. */2206export function isDecoyMode(): boolean {2207  return derivedKey !== null && vaultMode === "decoy";2208}22092210// Opens the vault using a pre-derived AES-256 key (skipping Argon2id). The2211// PIN-unlock path unwraps this key from its PIN wrap; the passphrase path2212// always derives from scratch via Argon2id.2213export async function unlockWithKey(2214  masterKeyHex: string,2215): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {2216  vaultUnlocksInFlight++;2217  try {2218  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };2219  const epoch = vaultEpoch;2220  const stale = () => epoch !== vaultEpoch;2221  await revokeRecoveryReveal();2222  if (stale()) return { ok: false, error: "vault_locked" };2223  let masterKeyBytes: Uint8Array | null = null;2224  try {2225    masterKeyBytes = unhex(masterKeyHex);2226    const stored = await loadSlot(SLOT_A);2227    if (!stored) return { ok: false, error: "invalid_key" };2228    const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");2229    if (!payload || stale()) {2230      zeroKey(masterKeyBytes);2231      return { ok: false, error: "invalid_key" };2232    }22332234    cancelBreachScan();2235    derivedKey = masterKeyBytes;2236    vaultMode = "real";2237    entries = payload.entries;2238    tombstones = payload.tombstones;2239    duressConfigured = payload.duressConfigured;2240    buildDomainIndexSync(entries);2241    await loadSettings();2242    touchAutoLock();22432244    rootKey = await deriveRootKeyFromDerivedKey(masterKeyBytes, stored);2245    if (!rootKey) {2246      await lock();2247      return { ok: false, error: "invalid_key" };2248    }2249    await reconcilePairSecrets(rootKey);2250    if (stale()) {2251      await lock();2252      return { ok: false, error: "invalid_key" };2253    }2254    await saveSessionKey(masterKeyBytes, "real", epoch);2255    if (stale()) return { ok: false, error: "invalid_key" };2256    return { ok: true, entries };2257  } catch {2258    if (masterKeyBytes && derivedKey !== masterKeyBytes) zeroKey(masterKeyBytes);2259    return { ok: false, error: "invalid_key" };2260  }2261  } finally { vaultUnlocksInFlight--; }2262}22632264// --- Adoption duress-slot helpers (passthrough, no decrypt) ---22652266/**2267 * Adoption SOURCE helper: returns the sealed slot B as a JSON string when2268 * duress is configured and slot B exists, so the inline snapshot can ship it2269 * to the receiver. Returns null otherwise. Never decrypts.2270 */2271export async function exportDuressSlotForAdoption(): Promise<string | null> {2272  if (!(await isDuressEnabled())) return null;2273  const slotB = await loadSlot(SLOT_B);2274  if (!slotB) return null;2275  return JSON.stringify(slotB);2276}22772278/**2279 * Adoption RECEIVER helper: installs a duress slot received from a source2280 * device. Validates the StoredVault shape (same guard as unlockFromCodex)2281 * and writes it to slot B. Throws on invalid shape so the caller can treat2282 * it as a non-fatal snapshot failure. Never decrypts.2283 */2284export async function installAdoptedDuressSlot(json: string): Promise<void> {2285  if (vaultCreatesInFlight) throw new Error("vault_changed");2286  vaultWritesInFlight++;2287  try {2288  let parsed: StoredVault;2289  try {2290    const raw = JSON.parse(json) as unknown;2291    if (!hasValidVaultSchema(raw)) {2292      throw new Error("invalid_duress_slot_shape");2293    }2294    parsed = raw;2295  } catch (err) {2296    if (err instanceof SyntaxError) {2297      throw new Error("invalid_duress_slot_shape");2298    }2299    throw err;2300  }2301  await writeSlot(SLOT_B, parsed);2302  } finally { vaultWritesInFlight--; }2303}23042305/**2306 * Restore the vault from a parsed Peach Codex payload.2307 *2308 * The supplied passphrase is verified against the Codex's slotA *before* any2309 * storage mutation — wrong passphrases return without touching disk. On2310 * success, the current vault state is snapshotted (reason: "restore") so the2311 * user can revert via Settings -> Vault History, then slotA/slotB are written2312 * and `peach_last_modified_at` is set to the Codex's recorded timestamp. A2313 * regular `unlock()` follows so the rest of the SW sees the standard2314 * post-unlock state.2315 *2316 * Intentionally non-Pro-gated — see peach_codex_v2.md "Pro gating". A Codex2317 * printed by a Pro user must always be restorable, even on a free device.2318 *2319 * Timing is not held constant here (in contrast to `unlock`): the Codex flow2320 * is an explicit user action with a known passphrase, not a passive lock2321 * screen, so the duress-vs-real timing side channel does not apply.2322 */2323export async function unlockFromCodex(params: {2324  slotA: string; // JSON string of StoredVault for slot A2325  slotB: string | null; // JSON string of StoredVault for slot B, or null2326  timestamp: number;2327  masterPassphrase: string;2328}): Promise<2329  | { ok: true; entryCount: number }2330  | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" | "missing_root_escrow" }2331> {2332  if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");2333  vaultReplacementInFlight = true;2334  try {2335    let parsedSlotA: StoredVault;2336    let parsedSlotB: StoredVault | null = null;2337    try {2338      const rawA = JSON.parse(params.slotA) as unknown;2339      if (!hasValidVaultSchema(rawA)) {2340        return { ok: false, reason: "invalid_slot_format" };2341      }2342      parsedSlotA = rawA;2343      if (params.slotB !== null) {2344        const rawB = JSON.parse(params.slotB) as unknown;2345        if (!hasValidVaultSchema(rawB)) {2346          return { ok: false, reason: "invalid_slot_format" };2347        }2348        parsedSlotB = rawB;2349      }2350    } catch {2351      return { ok: false, reason: "invalid_slot_format" };2352    }23532354    // Verify the passphrase and the password-wrapped root escrow against the2355    // staged Slot A WITHOUT writing anything. Payload decoding is part of the2356    // trial decrypt, so unlock() cannot be the first place these checks run.2357    const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));2358    const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");2359    if (!trialPayload) {2360      zeroKey(trialKey);2361      return { ok: false, reason: "wrong_passphrase" };2362    }2363    const hasEscrow =2364      !!parsedSlotA.pw_root_ciphertext && !!parsedSlotA.pw_root_nonce && !!parsedSlotA.pw_root_tag;2365    if (!hasEscrow) {2366      zeroKey(trialKey);2367      return { ok: false, reason: "missing_root_escrow" };2368    }2369    const stagedRootKey = await deriveRootKeyFromDerivedKey(trialKey, parsedSlotA);2370    if (!stagedRootKey) {2371      zeroKey(trialKey);2372      return { ok: false, reason: "wrong_passphrase" };2373    }2374    zeroKey(stagedRootKey);2375    zeroKey(trialKey);23762377    // Stage the complete candidate pair in memory before touching storage.2378    const stagedSlotB = parsedSlotB ?? generateNoiseBlob(parsedSlotA.ciphertext.length / 2);23792380    // Drop the trial key; `unlock()` below derives its own copy. Holding two2381    // copies of the master key in memory at once would be a needless surface.23822383    // Snapshot the about-to-be-overwritten on-disk state so the user can revert2384    // a mistaken Codex restore via the Vault History UI. Non-fatal if it fails.2385    await takeVaultSnapshot("restore");2386    const previousSlotA = await loadSlot(SLOT_A);2387    const previousSlotB = await loadSlot(SLOT_B);2388    let slotACommitted = false;2389    let slotBCommitted = false;2390    try {2391      await writeSlot(SLOT_A, parsedSlotA);2392      slotACommitted = true;2393      await writeSlot(SLOT_B, stagedSlotB);2394      slotBCommitted = true;2395      await chrome.storage.local.set({2396        peach_last_modified_at: String(params.timestamp),2397      });2398    } catch (err) {2399      if (slotBCommitted && previousSlotB) await writeSlot(SLOT_B, previousSlotB);2400      if (slotACommitted && previousSlotA) await writeSlot(SLOT_A, previousSlotA);2401      throw err;2402    }24032404    // Standard unlock path so domain index, settings, auto-lock, and2405    // recovery-key state all populate exactly as a normal unlock would.2406    const ok = await unlock(params.masterPassphrase);2407    if (!ok) {2408      // Should be unreachable — the staged candidate passed the same checks.2409      return { ok: false, reason: "wrong_passphrase" };2410    }2411    return { ok: true, entryCount: getEntries().length };2412  } finally {2413    vaultReplacementInFlight = false;2414  }2415}24162417// Returns the current in-memory derived key as a hex string. Only the PIN2418// unlock path needs this value, and it reads module state directly; this2419// accessor exists so unlockWithKey's root-key rehydration is testable.2420export /* @testable */ function getDerivedKeyHex(): string {2421  if (!derivedKey) throw new Error("vault_not_unlocked");2422  return hex(derivedKey);2423}24242425/**2426 * Returns the vault's stable root key as hex, or null when locked / not yet2427 * populated. The root key is random per-vault, generated at creation, escrowed2428 * under the recovery words, and re-wrapped (not regenerated) on every password2429 * change — so it is INVARIANT across password rotation, unlike getDerivedKeyHex.2430 *2431 * This is the correct input for sync identity derivation (vault_id, the Noise2432 * NK static key, the Ed25519 manifest signing key, and per-entry envelope2433 * keys): paired devices keep the same identity and can still decrypt each2434 * other's entries after either side rotates its master password (SEV-2-B).2435 *2436 * Returns null rather than throwing so sync callers degrade to VAULT_LOCKED2437 * instead of crashing; rootKey is populated on every supported real-mode2438 * unlock via deriveRootKeyFromDerivedKey.2439 */2440export function getRootKeyHex(): string | null {2441  return rootKey ? hex(rootKey) : null;2442}24432444export function getEntries(): VaultEntry[] {2445  if (!derivedKey) throw new Error("vault_locked");2446  return entries.filter((entry) => !entry.deletedAt);2447}24482449const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;24502451export function getIdentities(): SavedIdentity[] {2452  if (!derivedKey) throw new Error("vault_locked");2453  const active = entries.filter((e) => !e.deletedAt && e.type === "login");24542455  const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();2456  const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();24572458  for (const entry of active) {2459    const domain = extractDomain(entry.url ?? "") ?? "";2460    const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;24612462    function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {2463      const existing = map.get(v);2464      if (!existing || modifiedAt > existing.lastUsed) {2465        map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });2466      } else {2467        map.set(v, { ...existing, count: existing.count + 1 });2468      }2469    }24702471    const uVal = entry.username?.trim();2472    if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);24732474    // Also count the dedicated email field — entries created via the inline2475    // popup new-entry form store email here rather than in username.2476    const eVal = entry.email?.trim();2477    if (eVal) tally(emailMap, eVal);2478  }24792480  const toIdentity = (type: "email" | "username") =>2481    ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({2482      value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,2483    });24842485  return [2486    ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),2487    ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),2488  ];2489}24902491export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {2492  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");24932494  const now = Date.now();2495  const added: VaultEntry[] = [];2496  for (const draft of drafts) {2497    try {2498      const sanitized = sanitizeEntryDraft(draft);2499      const nextEntry: VaultEntry = {2500        ...sanitized,2501        id: crypto.randomUUID(),2502        createdAt: now,2503        modifiedAt: monotonicEntryTimestamp(),2504      };2505      entries.push(nextEntry);2506      added.push(nextEntry);2507    } catch {2508      // Skip invalid drafts silently — caller can see diff between input and output length2509    }2510  }25112512  if (added.length > 0) {2513    await persistEntries();2514  }25152516  return added;2517}25182519/**2520 * Restore a set of entries in full fidelity — preserves id, createdAt,2521 * modifiedAt, and every other field unlike `batchAddEntries` which2522 * assigns fresh identity. Used by restore paths where the backup is the2523 * authoritative source of truth. `mode` controls how entries already in2524 * the vault are treated.2525 */2526export async function restoreEntries(2527  incoming: VaultEntry[],2528  mode: "replace" | "merge"2529): Promise<{ added: number; updated: number; skipped: number }> {2530  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");25312532  // A replace with zero incoming entries is almost certainly a caller bug2533  // (e.g. an import that silently dropped everything). Refuse rather than2534  // wipe the vault.2535  if (mode === "replace" && incoming.length === 0) {2536    throw new Error("refuse to replace with empty entry set");2537  }25382539  let added = 0;2540  let updated = 0;2541  let skipped = 0;25422543  if (mode === "replace") {2544    entries = [];2545    for (const entry of incoming) {2546      const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2547      if (!normalized) {2548        skipped += 1;2549        continue;2550      }2551      entries.push(normalized);2552      if (normalized.deletedAt) {2553        tombstones.set(2554          normalized.id,2555          Math.max(tombstones.get(normalized.id) ?? 0, normalized.deletedAt),2556        );2557      } else {2558        tombstones.delete(normalized.id);2559      }2560      added += 1;2561    }2562  } else {2563    const byId = new Map<string, VaultEntry>();2564    for (const e of entries) byId.set(e.id, e);25652566    for (const entry of incoming) {2567      const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2568      if (!normalized) {2569        skipped += 1;2570        continue;2571      }2572      const existing = byId.get(normalized.id);2573      if (!existing) {2574        entries.push(normalized);2575        if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2576        else tombstones.delete(normalized.id);2577        added += 1;2578      } else if (normalized.modifiedAt > existing.modifiedAt) {2579        const idx = entries.findIndex((e) => e.id === existing.id);2580        if (idx !== -1) {2581          entries[idx] = normalized;2582          if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2583          else tombstones.delete(normalized.id);2584          updated += 1;2585        }2586      } else {2587        skipped += 1;2588      }2589    }2590  }25912592  await persistEntries("import");2593  return { added, updated, skipped };2594}25952596/**2597 * A Peach entry id is a UUID. A restored or imported file carries whatever id2598 * its author used, and no reader bounds it, so one oversized id would ride2599 * into every future sync frame and be rejected there — a permanent, opaque2600 * failure on both platforms, caused by data that was already local.2601 *2602 * The action is mint, not reject: this is the last point where an id is still2603 * ours to choose, so the worst outcome is one duplicate if the same vault is2604 * later restored beside a device still holding the old id. Rejecting would2605 * lose the user's import.2606 *2607 * Deliberately NOT inside sanitizeRestoredEntry, which applyMergedRemoteEntries2608 * also calls. Sync has to adopt a peer's id verbatim — that is the only thing2609 * keeping two devices agreed on which entry they are discussing — so reminting2610 * there would fork identity on every device, on every round.2611 */2612const ENTRY_ID_SHAPE = /^[A-Za-z0-9_-]{1,64}$/;26132614function naturalizeRestoredId(entry: VaultEntry | null): VaultEntry | null {2615  if (!entry || ENTRY_ID_SHAPE.test(entry.id)) return entry;2616  return { ...entry, id: crypto.randomUUID() };2617}26182619/**2620 * Validate + normalise a VaultEntry coming from a backup, import, or sync2621 * peer. MV-6: this is a strict field WHITELIST — `normalizeEntry` copies2622 * only known VaultEntry fields (unknown/attacker keys are dropped), and2623 * nested `passkey`/`canary` shapes are rebuilt field-by-field, never2624 * spread. Returns null for values the live vault shouldn't accept.2625 */2626function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {2627  if (!entry || typeof entry !== "object") return null;2628  const title = typeof entry.title === "string" ? entry.title.trim() : "";2629  if (!title) return null;2630  const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();2631  const now = Date.now();2632  const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;2633  const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;26342635  // normalizeEntry whitelists every known VaultEntry field before the entry2636  // reaches the live vault.2637  const normalized = normalizeEntry({2638    ...entry,2639    id,2640    title,2641    type: entry.type ?? "login",2642    createdAt,2643    modifiedAt,2644  });26452646  if (normalized.passkey) {2647    normalized.passkey = sanitizePasskey(normalized.passkey);2648  }2649  if (normalized.canary) {2650    normalized.canary = sanitizeCanary(normalized.canary);2651  }2652  // PCH-01-016: bound tags on the restore path too, so both import funnels agree.2653  normalized.tags = sanitizeTags(normalized.tags);26542655  // Login entries from backup must carry a password (or be passkey-only,2656  // in which case the passkey sub-object replaces the password requirement).2657  if (2658    normalized.type === "login" &&2659    !normalized.passkey &&2660    typeof normalized.password !== "string"2661  ) {2662    return null;2663  }2664  if (entry.passkey && !normalized.passkey) {2665    // Entry claimed a passkey but the shape didn't validate — refuse the2666    // whole entry rather than silently importing a credential-less husk.2667    return null;2668  }26692670  return normalized;2671}26722673/**2674 * Rebuild a PasskeyData object from untrusted input, field by field.2675 * Returns undefined when required fields are missing/mistyped — a rogue2676 * passkey credential must not activate via import (MV-6 attack scenario).2677 */2678function sanitizePasskey(pk: unknown): PasskeyData | undefined {2679  if (!pk || typeof pk !== "object") return undefined;2680  const r = pk as Record<string, unknown>;2681  if (2682    typeof r.rpId !== "string" || !r.rpId ||2683    typeof r.credentialId !== "string" || !r.credentialId ||2684    typeof r.publicKeyCose !== "string" ||2685    typeof r.userHandle !== "string" ||2686    typeof r.userName !== "string"2687  ) {2688    return undefined;2689  }2690  return {2691    rpId: r.rpId,2692    rpName: typeof r.rpName === "string" ? r.rpName : r.rpId,2693    credentialId: r.credentialId,2694    publicKeyCose: r.publicKeyCose,2695    privateKeyJwk:2696      r.privateKeyJwk && typeof r.privateKeyJwk === "object"2697        ? (r.privateKeyJwk as JsonWebKey)2698        : undefined,2699    userHandle: r.userHandle,2700    userName: r.userName,2701    userDisplayName:2702      typeof r.userDisplayName === "string" ? r.userDisplayName : r.userName,2703    algorithm: r.algorithm === -8 ? -8 : -7,2704    signCount: typeof r.signCount === "number" ? r.signCount : 0,2705    aaguid: typeof r.aaguid === "string" ? r.aaguid : "",2706    backupEligible: r.backupEligible === true,2707    backupState: r.backupState === true,2708    lastUsedAt: typeof r.lastUsedAt === "number" ? r.lastUsedAt : undefined,2709    browser: r.browser === "chrome" || r.browser === "firefox" ? r.browser : undefined,2710    transports: Array.isArray(r.transports)2711      ? r.transports.filter((t): t is string => typeof t === "string")2712      : undefined,2713    createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),2714  };2715}27162717/**2718 * Rebuild a Canary object from untrusted input. The webhook must be a2719 * well-formed HTTPS URL — a poisoned canary.webhookUrl is a standing2720 * exfiltration endpoint that the canary subsystem will POST entry titles2721 * to (MV-6 attack scenario). Invalid → the canary is dropped, not the2722 * entry. FIRE_CANARY_PING revalidates the destination policy at dispatch2723 * (canaryWebhookUrl), so this import-time check is the2724 * outer of two gates.2725 */2726function sanitizeCanary(c: unknown): Canary | undefined {2727  if (!c || typeof c !== "object") return undefined;2728  const r = c as Record<string, unknown>;2729  if (typeof r.webhookUrl !== "string") return undefined;2730  let url: URL;2731  try {2732    url = new URL(r.webhookUrl);2733  } catch {2734    return undefined;2735  }2736  if (url.protocol !== "https:") return undefined;2737  return {2738    webhookUrl: url.toString(),2739    label: typeof r.label === "string" ? r.label : undefined,2740    lastPinged: typeof r.lastPinged === "number" ? r.lastPinged : undefined,2741    pingCount: typeof r.pingCount === "number" ? r.pingCount : undefined,2742  };2743}27442745/**2746 * MV-6 / PCH-01-016: tags from imported / batch-added entries are untrusted.2747 * Keep only non-empty strings, cap each at 256 chars, and cap the count at 2552748 * (the same per-entry ceiling the export codec enforces, peachPayload.ts).2749 * Non-array or all-invalid input collapses to undefined.2750 */2751function sanitizeTags(tags: unknown): string[] | undefined {2752  if (!Array.isArray(tags)) return undefined;2753  const out: string[] = [];2754  for (const t of tags) {2755    if (typeof t !== "string") continue;2756    const trimmed = t.trim();2757    if (!trimmed) continue;2758    out.push(trimmed.slice(0, 256));2759    if (out.length >= 255) break;2760  }2761  return out.length > 0 ? out : undefined;2762}27632764// Soft-deletes every non-deleted entry in one call. The literal string2765// argument is a tripwire against accidental calls — any caller that would2766// wipe the vault has to consciously type "REPLACE_ALL". Do not relax this2767// to a boolean.2768export async function clearVaultEntries(2769  confirmation: "REPLACE_ALL"2770): Promise<void> {2771  if (confirmation !== "REPLACE_ALL") {2772    throw new Error("clearVaultEntries requires explicit confirmation");2773  }2774  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");2775  for (const entry of entries) {2776    if (!entry.deletedAt) {2777      const stamp = monotonicEntryTimestamp(Math.max(2778        entry.modifiedAt,2779        tombstones.get(entry.id) ?? 0,2780      ));2781      entry.deletedAt = stamp;2782      entry.modifiedAt = stamp;2783      tombstones.set(entry.id, stamp);2784    }2785  }2786  await persistEntries();2787}27882789export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {2790  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");2791  const epoch = vaultEpoch;2792  const key = derivedKey;27932794  const sanitized = sanitizeEntryDraft(entry);2795  const now = Date.now();2796  const stamp = monotonicEntryTimestamp();2797  const nextEntry: VaultEntry = {2798    ...sanitized,2799    id: crypto.randomUUID(),2800    createdAt: now,2801    modifiedAt: stamp,2802    // Stamp passwordChangedAt at creation so age tracking is accurate from2803    // day one. Non-login entries carry the same stamp harmlessly.2804    passwordChangedAt: sanitized.password ? stamp : undefined,2805  };28062807  // Clone-and-replace so a failed persist rolls back the in-memory state2808  // (COR-008). Without this, a quota-full or storage error leaves the2809  // module-level `entries` ahead of what's actually on disk.2810  const rollback = entries;2811  entries = [...entries, nextEntry];2812  try {2813    await persistEntries();2814  } catch (err) {2815    entries = rollback;2816    throw err;2817  }28182819  if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password && epoch === vaultEpoch) {2820    checkEntryBreachDetached({ id: nextEntry.id, password: nextEntry.password, epoch, key });2821  }28222823  fireSyncTrigger("vault_change");28242825  return nextEntry;2826}28272828/// Attach unambiguous account credentials without discarding other entry data.2829export async function consolidatePasskeyEntries(): Promise<void> {2830  if (!derivedKey || vaultCreatesInFlight) return;2831  const epoch = vaultEpoch;2832  const rollback = entries;2833  const next = entries.map((entry) => ({ ...entry }));2834  if (!mergePasskeyOnlyIntoLogins(next).merged) return;2835  const unchanged = next.map((entry) => ({ entry, modifiedAt: entry.modifiedAt }));2836  entries = next;2837  try {2838    await persistEntries();2839  } catch (err) {2840    // Other writers can replace entries or mutate a deletion in this array.2841    if (epoch === vaultEpoch && entries === next && entries.length === unchanged.length &&2842      unchanged.every(({ entry, modifiedAt }, index) => entries[index] === entry && entry.modifiedAt === modifiedAt)) {2843      entries = rollback;2844      buildDomainIndexSync(entries);2845    }2846    throw err;2847  }2848}28492850export async function updateEntry(2851  id: string,2852  patch: Partial<VaultEntry>2853): Promise<void> {2854  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");28552856  const idx = entries.findIndex((entry) => entry.id === id);2857  if (idx === -1 || entries[idx].deletedAt) {2858    throw new Error("entry_not_found");2859  }28602861  const current = entries[idx];2862  const owner = entries;2863  const epoch = vaultEpoch;2864  const key = derivedKey;2865  const sanitizedPatch = sanitizeEntryPatch(patch);2866  // Refresh passwordChangedAt only when the password value actually changes —2867  // a metadata-only update (title, tags, etc.) must not reset the age clock2868  // that drives the Pro health rotation recommendation.2869  const passwordChanged =2870    "password" in patch &&2871    typeof sanitizedPatch.password === "string" &&2872    sanitizedPatch.password !== current.password;2873  const stamp = monotonicEntryTimestamp(current.modifiedAt);2874  // When the password actually changes, push the outgoing one onto the history2875  // (newest first) so the user can reveal/copy/restore it later. We record the2876  // age it carried (passwordChangedAt, falling back to createdAt) rather than2877  // `now`, so the list reflects when each password was last in effect. Only2878  // capture a non-empty prior value — clearing a password leaves no secret to2879  // keep, and we skip an immediate exact duplicate (e.g. restore-then-restore)2880  // to avoid noise.2881  const priorPassword = current.password;2882  const shouldCapture =2883    passwordChanged &&2884    typeof priorPassword === "string" &&2885    priorPassword.length > 0 &&2886    current.passwordHistory?.[0]?.password !== priorPassword;2887  const nextHistory = shouldCapture2888    ? [2889        { password: priorPassword!, changedAt: current.passwordChangedAt ?? current.createdAt },2890        ...(current.passwordHistory ?? []),2891      ].slice(0, PASSWORD_HISTORY_MAX)2892    : current.passwordHistory;2893  const next = {2894    ...current,2895    ...sanitizedPatch,2896    modifiedAt: stamp,2897    ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),2898  };2899  entries[idx] = next;29002901  // Card entries must retain their card number2902  if (entries[idx].type === "card" && !entries[idx].cardNumber) {2903    entries[idx] = current;2904    throw new Error("card number is required for card entries");2905  }29062907  // Roll the in-memory entry back to its pre-edit state if the disk write2908  // fails (e.g. storage quota). Without this the module-level `entries` array2909  // would hold an edit that never landed on disk, diverging from the vault2910  // until the next unlock silently reverts it (SEV-3-A). Mirrors addEntry.2911  try {2912    await persistEntries();2913  } catch (err) {2914    if (epoch === vaultEpoch && entries === owner && entries[idx] === next && next.modifiedAt === stamp && !next.deletedAt) entries[idx] = current;2915    throw err;2916  }29172918  if (passwordChanged && settings.breachMonitoring !== false && next.type === "login" && next.password && epoch === vaultEpoch) {2919    checkEntryBreachDetached({ id, password: next.password, epoch, key });2920  }29212922  fireSyncTrigger("vault_change");2923}29242925export async function deleteEntry(id: string): Promise<void> {2926  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");29272928  const entry = entries.find((item) => item.id === id);2929  if (!entry || entry.deletedAt) {2930    throw new Error("entry_not_found");2931  }29322933  // Tombstone timestamp must be strictly greater than the entry's last2934  // modification so the deletion wins LWW against any in-flight edit, even2935  // under clock skew (SEV-2-E).2936  const previousModifiedAt = entry.modifiedAt;2937  const previousTombstone = tombstones.get(id);2938  const stamp = monotonicEntryTimestamp(Math.max(entry.modifiedAt, previousTombstone ?? 0));2939  entry.deletedAt = stamp;2940  entry.modifiedAt = stamp;2941  tombstones.set(id, stamp);2942  // Roll the tombstone back if the disk write fails, so a quota error doesn't2943  // leave the entry deleted in memory but alive on disk (SEV-3-A).2944  try {2945    await persistEntries();2946  } catch (err) {2947    delete entry.deletedAt;2948    entry.modifiedAt = previousModifiedAt;2949    if (previousTombstone === undefined) tombstones.delete(id);2950    else tombstones.set(id, previousTombstone);2951    throw err;2952  }2953  fireSyncTrigger("vault_change");2954}29552956export function getDeletedEntries(): VaultEntry[] {2957  if (!derivedKey) return [];2958  return entries.filter((e) => !!e.deletedAt);2959}29602961/** Return all durable deletion timestamps, including purged full entries. */2962export function getTombstoneManifest(): Record<string, number> {2963  if (!derivedKey) return {};2964  return Object.fromEntries(tombstones);2965}29662967/**2968 * Returns the vault's monotonic version — the `peach_last_modified_at` value2969 * stamped on every user-initiated write. Remote (sync) writes do NOT advance2970 * this version so a sync round never cascades into a second outbound sync.2971 */2972export async function getVaultVersion(): Promise<number> {2973  try {2974    const raw = await chrome.storage.local.get("peach_last_modified_at");2975    const v = (raw as Record<string, unknown>).peach_last_modified_at;2976    if (typeof v === "number") return v;2977    if (typeof v === "string" && v !== "") {2978      const n = Number.parseInt(v, 10);2979      return Number.isFinite(n) ? n : 0;2980    }2981    return 0;2982  } catch {2983    return 0;2984  }2985}29862987/**2988 * Apply a batch of remote entries + tombstones from a sync peer.2989 * Last-write-wins by `modifiedAt`; a tombstone supersedes a live entry when2990 * `deletedAt > modifiedAt` on the local side. Mutates `entries` directly and2991 * persists with reason `sync_received` — does NOT fire the sync dispatcher, so2992 * applying a sync round cannot cascade into another outbound sync.2993 *2994 * `applied` counts entries that actually changed local state (new add,2995 * overwrite-by-newer, or new tombstone). `received` is the raw payload size2996 * the caller can surface in the sync result UI.2997 */2998export async function applyMergedRemoteEntries(2999  remoteEntries: VaultEntry[],3000  remoteTombstones: Record<string, number>,3001): Promise<{ received: number; applied: number; conflicts: number }> {3002  // DESIGN: last-write-wins is applied PER-ENTRY, not per-field. If two devices3003  // concurrently edit different fields of the same entry, the one with the3004  // newer modifiedAt wins the whole entry and the other device's field edits3005  // are dropped silently. This is the deliberate trade-off for a simple,3006  // conflict-free merge — per-field CRDT merge is out of scope. Guidance for3007  // users: edit a given entry on one device at a time.3008  if (!derivedKey || vaultCreatesInFlight || vaultMode === "decoy") throw new Error("vault_locked");30093010  const received = remoteEntries.length + Object.keys(remoteTombstones).length;3011  let applied = 0;3012  let conflicts = 0;30133014  const byId = new Map<string, VaultEntry>();3015  for (const e of entries) byId.set(e.id, e);30163017  const mergeNow = Date.now();3018  const remoteTombstoneTimes = new Map<string, number>();3019  for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {3020    if (typeof rawDeletedAt === "number" && Number.isFinite(rawDeletedAt) && rawDeletedAt > 0) {3021      remoteTombstoneTimes.set(id, clampSyncTimestamp(rawDeletedAt, mergeNow));3022    }3023  }30243025  for (const remote of remoteEntries) {3026    const sanitized = sanitizeRestoredEntry(remote);3027    if (!sanitized) continue;3028    // HV-1a: a far-future remote modifiedAt must not permanently pin a3029    // malicious value against honest local edits. Clamp BEFORE any3030    // comparison against local timestamps.3031    sanitized.modifiedAt = clampSyncTimestamp(sanitized.modifiedAt, mergeNow);3032    if (typeof sanitized.deletedAt === "number") {3033      sanitized.deletedAt = clampSyncTimestamp(sanitized.deletedAt, mergeNow);3034    }3035    const remoteTombstoneTs = remoteTombstoneTimes.get(sanitized.id);3036    const localTombstoneTs = tombstones.get(sanitized.id);3037    const tombstoneTs = Math.max(remoteTombstoneTs ?? 0, localTombstoneTs ?? 0);3038    if (tombstoneTs > 0 && tombstoneTs >= sanitized.modifiedAt) {3039      continue;3040    }3041    const local = byId.get(sanitized.id);3042    if (!local) {3043      entries.push(sanitized);3044      byId.set(sanitized.id, sanitized);3045      tombstones.delete(sanitized.id);3046      applied += 1;3047    } else if (sanitized.modifiedAt > local.modifiedAt) {3048      const idx = entries.findIndex((e) => e.id === local.id);3049      if (idx !== -1) {3050        entries[idx] = sanitized;3051        byId.set(sanitized.id, sanitized);3052        tombstones.delete(sanitized.id);3053        applied += 1;3054        if (!local.deletedAt) conflicts += 1;3055      }3056    }3057  }30583059  for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {3060    if (typeof rawDeletedAt !== "number" || !Number.isFinite(rawDeletedAt) || rawDeletedAt <= 0) continue;3061    // HV-1a/1c: clamp the tombstone timestamp before every comparison.3062    const deletedAt = remoteTombstoneTimes.get(id)!;3063    const knownTombstone = tombstones.get(id);3064    if (knownTombstone !== undefined && knownTombstone >= deletedAt) continue;3065    const local = byId.get(id);3066    if (!local) {3067      tombstones.set(id, deletedAt);3068      applied += 1;3069      continue;3070    }3071    if (local.deletedAt && local.deletedAt >= deletedAt) continue;3072    if (deletedAt < local.modifiedAt) continue;3073    const idx = entries.findIndex((e) => e.id === id);3074    if (idx !== -1) {3075      entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };3076      tombstones.set(id, deletedAt);3077      applied += 1;3078    }3079  }30803081  if (applied > 0 && vaultMode === "real") {3082    await persistEntries("sync_received");3083    buildDomainIndexSync(entries);3084    // An open popup holds the entries it loaded at mount and polls nothing, so3085    // a background round (the relay listener responding to a peer's push, or the3086    // alarm-driven dial) otherwise lands silently and the user sees stale data3087    // until they reopen. Best-effort: no popup listening is the normal case.3088    try {3089      void chrome.runtime3090        .sendMessage({ type: "VAULT_ENTRIES_CHANGED" })3091        .catch(() => undefined);3092    } catch {3093      // messaging unavailable3094    }3095  }3096  return { received, applied, conflicts };3097}30983099export async function restoreEntry(id: string): Promise<void> {3100  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3101  const entry = entries.find((e) => e.id === id && e.deletedAt);3102  if (!entry) throw new Error("deleted entry not found");3103  const previousDeletedAt = entry.deletedAt;3104  const previousModifiedAt = entry.modifiedAt;3105  const previousTombstone = tombstones.get(id);3106  delete entry.deletedAt;3107  entry.modifiedAt = monotonicEntryTimestamp(Math.max(3108    entry.modifiedAt,3109    previousTombstone ?? 0,3110  ));3111  tombstones.delete(id);3112  try {3113    await persistEntries();3114  } catch (err) {3115    entry.deletedAt = previousDeletedAt;3116    entry.modifiedAt = previousModifiedAt;3117    if (previousTombstone !== undefined) tombstones.set(id, previousTombstone);3118    throw err;3119  }3120  buildDomainIndexSync(entries);3121}31223123export async function purgeEntry(id: string): Promise<void> {3124  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3125  const idx = entries.findIndex((e) => e.id === id && e.deletedAt);3126  if (idx === -1) throw new Error("deleted entry not found");3127  const entry = entries[idx]!;3128  tombstones.set(id, Math.max(tombstones.get(id) ?? 0, entry.deletedAt!));3129  entries.splice(idx, 1);3130  await persistEntries();3131}31323133/** Permanently delete entries whose deletedAt is older than retentionMs. 0 = keep forever. */3134export async function purgeExpiredTrash(retentionMs: number): Promise<number> {3135  if (!derivedKey || vaultCreatesInFlight || retentionMs === 0) return 0;3136  const cutoff = Date.now() - retentionMs;3137  const before = entries.length;3138  for (const entry of entries) {3139    if (entry.deletedAt && entry.deletedAt < cutoff) {3140      tombstones.set(entry.id, Math.max(tombstones.get(entry.id) ?? 0, entry.deletedAt));3141    }3142  }3143  entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));3144  const purged = before - entries.length;3145  if (purged > 0) await persistEntries();3146  return purged;3147}31483149export function queryDomain(domain: string): VaultEntry[] {3150  return domainIndex.get(domain) ?? [];3151}31523153export function getEntryById(id: string): VaultEntry | undefined {3154  return entries.find((entry) => entry.id === id && !entry.deletedAt);3155}31563157async function persistSlotA(3158  reason: VaultSnapshot["reason"] = "local_save",3159): Promise<StoredVault> {3160  if (!derivedKey) throw new Error("vault_locked");3161  const epoch = vaultEpoch;3162  const throwIfStale = () => {3163    if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3164  };31653166  const slotA = await loadSlot(SLOT_A);3167  throwIfStale();3168  if (!slotA) throw new Error("missing slot A");31693170  // Snapshot the about-to-be-overwritten state BEFORE we mutate disk. Failures3171  // are swallowed by takeVaultSnapshot — history must never block a save.3172  await takeVaultSnapshot(reason);3173  throwIfStale();31743175  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3176  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");3177  throwIfStale();31783179  // Preserve existing recovery escrow fields.3180  const nextSlotA: StoredVault = {3181    ...slotA,3182    nonce,3183    ciphertext,3184    tag,3185    // recovery_salt and recovery_wrapped_root_key are already set from loadSlot3186  };31873188  // Slot A (the real vault) is now committed. Wrap every later write so a3189  // mid-persist failure (e.g. a storage error after slot A landed) restores the3190  // prior slot A before rethrowing. Without this, a "failed" save that already3191  // wrote slot A leaves disk ahead of the in-memory rollback in addEntry/3192  // updateEntry/deleteEntry — the entry stays silently on disk and resurfaces3193  // as a duplicate on the next unlock (observed under storage-quota pressure).3194  let slotACommitted = false;3195  try {3196    throwIfStale();3197    await writeSlot(SLOT_A, nextSlotA);3198    slotACommitted = true;3199    throwIfStale();32003201    // When duress is not configured, keep slot B size-matched with slot A by3202    // regenerating its noise. When duress IS configured, leave slot B alone —3203    // we don't have the decoy key to re-encrypt it. This is a known trade-off.3204    if (!duressConfigured) {3205      throwIfStale();3206      await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3207      throwIfStale();3208    }3209    // Only advance the vault version for locally-originated writes. Entries3210    // applied from a sync peer ("sync_received") must NOT bump the counter —3211    // otherwise applying a remote round makes us look newer than the peer and3212    // triggers a redundant outbound sync, defeating the no-op optimisation3213    // and risking a ping-pong between two devices (SEV-2-C).3214    if (reason !== "sync_received") {3215      throwIfStale();3216      await stampLocalVaultMutation();3217      throwIfStale();3218    }3219  } catch (err) {3220    // Best-effort restore — the prior slot A is smaller-or-equal, so this write3221    // fits even when the failure was a quota overflow.3222    if (slotACommitted) await writeSlot(SLOT_A, slotA).catch(() => {});3223    if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3224    throw err;3225  }32263227  return nextSlotA;3228}32293230async function persistSlotB(): Promise<void> {3231  if (!derivedKey) throw new Error("vault_locked");32323233  const slotB = await loadSlot(SLOT_B);3234  if (!slotB) throw new Error("missing slot B");32353236  // Decoy plaintext always reports duressConfigured=false — the decoy user3237  // sees a clean slate. persistSlotB only runs in decoy mode, which only3238  // exists once duress is configured, so pad to the fixed duress ceiling to3239  // keep slot B's length equal to slot A's (audit MEDIUM — deniability).3240  const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);3241  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");32423243  await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });3244  // Symmetric with persistSlotA: if the version stamp fails after the decoy3245  // slot committed, restore the prior slot B so a failed decoy-mode save can't3246  // leave disk ahead of the in-memory rollback.3247  try {3248    await stampLocalVaultMutation();3249  } catch (err) {3250    await writeSlot(SLOT_B, slotB).catch(() => {});3251    throw err;3252  }3253}32543255async function persistEntries(3256  reason: VaultSnapshot["reason"] = "local_save",3257): Promise<void> {3258  if (vaultCreatesInFlight) throw new Error("vault_changed");3259  vaultWritesInFlight++;3260  try {3261  if (!derivedKey) throw new Error("vault_locked");32623263  // Reconcile direct soft-delete callers while restoring the previous map if3264  // storage rejects the save.3265  const previousTombstones = tombstones;3266  const pendingTombstones = new Map(tombstones);3267  tombstones = pendingTombstones;3268  reconcileTombstones();3269  try {3270    if (vaultMode === "decoy") {3271      await persistSlotB();3272    } else {3273      await persistSlotA(reason);3274    }3275  } catch (err) {3276    if (tombstones === pendingTombstones) tombstones = previousTombstones;3277    throw err;3278  }3279  buildDomainIndexSync(entries);3280  await refreshLockedSyncState();3281  } finally { vaultWritesInFlight--; }3282}32833284// PB-26-011: drop URLs whose parsed scheme is not http(s) at the storage3285// boundary. Schemeless values (e.g. "github.com") are inert and kept — they3286// pre-date this guard in existing data. Unparseable values are kept: the3287// reviewed render paths never execute them (favicons via _favicon/, domains3288// via tldts); this is defense-in-depth against future sinks.3289function allowHttpUrl(url: string | undefined): string {3290  const trimmed = url?.trim() ?? "";3291  if (!trimmed) return "";3292  try {3293    const parsed = new URL(trimmed);3294    if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return "";3295  } catch {3296    // No scheme to reject.3297  }3298  return trimmed;3299}33003301function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {3302  if (!Array.isArray(values)) return undefined;3303  const seen = new Set<string>();3304  const cleaned: string[] = [];3305  for (const value of values) {3306    const trimmed = typeof value === "string" ? value.trim() : "";3307    if (!trimmed) continue;3308    if (!allowHttpUrl(trimmed)) continue;3309    const key = trimmed.toLowerCase();3310    if (seen.has(key)) continue;3311    seen.add(key);3312    cleaned.push(trimmed);3313  }3314  return cleaned.length > 0 ? cleaned : undefined;3315}33163317function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {3318  const title = entry.title.trim();3319  const type: VaultEntry["type"] = entry.type ?? "login";33203321  if (!title) throw new Error("title is required");33223323  if (entry.passkey) {3324    const p = entry.passkey;3325    if (3326      !p.rpId ||3327      !p.credentialId ||3328      !p.publicKeyCose ||3329      !p.userHandle ||3330      !p.userName ||3331      (p.algorithm !== -7 && p.algorithm !== -8)3332    ) {3333      throw new Error("invalid passkey credential");3334    }3335  }3336  if (type === "card") {3337    if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {3338      throw new Error("cardholder name and card number are required");3339    }3340  }33413342  return {3343    type,3344    title,3345    username: type === "login" ? entry.username?.trim() ?? "" : undefined,3346    email: type === "login" ? entry.email?.trim() || undefined : undefined,3347    password: type === "login" ? entry.password : undefined,3348    url: type === "login" ? allowHttpUrl(entry.url) : undefined,3349    additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,3350    totp: type === "login" ? entry.totp?.trim() || undefined : undefined,3351    // PCH-01-019: preserve non-default TOTP params through batch-add/import so3352    // they are not silently stripped (they fall back to SHA-1/6/30 when absent).3353    totpAlgorithm: type === "login" ? entry.totpAlgorithm : undefined,3354    totpDigits: type === "login" ? entry.totpDigits : undefined,3355    totpPeriod: type === "login" ? entry.totpPeriod : undefined,3356    notes: entry.notes?.trim() || undefined,3357    breach: type === "login" ? entry.breach : undefined,3358    // PCH-01-016: the batch-add path was bypassing the MV-6 canary/tags3359    // whitelist applied on the RESTORE_ENTRIES path. Run both sanitizers here.3360    canary: type === "login" ? sanitizeCanary(entry.canary) : undefined,3361    tags: sanitizeTags(entry.tags),3362    passkey: entry.passkey,3363    cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,3364    cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,3365    expMonth: type === "card" ? entry.expMonth?.trim() : undefined,3366    expYear: type === "card" ? entry.expYear?.trim() : undefined,3367    cvc: type === "card" ? entry.cvc?.trim() : undefined,3368    cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,3369    network: type === "card" ? entry.network : undefined,3370    last4: type === "card" ? entry.last4?.trim() : undefined,3371  };3372}33733374function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {3375  const nextPatch: Partial<VaultEntry> = {};33763377  if ("type" in patch) {3378    nextPatch.type = patch.type;3379  }33803381  if ("title" in patch) {3382    const title = patch.title?.trim() ?? "";3383    if (!title) throw new Error("title is required");3384    nextPatch.title = title;3385  }33863387  if ("url" in patch) {3388    nextPatch.url = allowHttpUrl(patch.url);3389  }33903391  if ("additionalUrls" in patch) {3392    const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];3393    const seen = new Set<string>();3394    const cleaned: string[] = [];3395    for (const value of incoming) {3396      const trimmed = typeof value === "string" ? value.trim() : "";3397      if (!trimmed || !allowHttpUrl(trimmed)) continue;3398      const key = trimmed.toLowerCase();3399      if (seen.has(key)) continue;3400      seen.add(key);3401      cleaned.push(trimmed);3402    }3403    nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;3404  }34053406  if ("username" in patch) {3407    nextPatch.username = patch.username?.trim() ?? "";3408  }34093410  if ("email" in patch) {3411    nextPatch.email = patch.email?.trim() || undefined;3412  }34133414  if ("password" in patch) {3415    const password = patch.password ?? "";3416    // Allow clearing a password (e.g. on passkey-only entries)3417    nextPatch.password = password || undefined;3418  }34193420  if ("totp" in patch) {3421    nextPatch.totp = patch.totp?.trim() || undefined;3422  }34233424  if ("totpAlgorithm" in patch) {3425    nextPatch.totpAlgorithm = patch.totpAlgorithm;3426  }34273428  if ("totpDigits" in patch) {3429    nextPatch.totpDigits = patch.totpDigits;3430  }34313432  if ("totpPeriod" in patch) {3433    nextPatch.totpPeriod = patch.totpPeriod;3434  }34353436  if ("notes" in patch) {3437    nextPatch.notes = patch.notes?.trim() || undefined;3438  }34393440  if ("breach" in patch) {3441    nextPatch.breach = patch.breach;3442  }34433444  if ("canary" in patch) {3445    // PCH-02-001: route update patches through the same canary whitelist used3446    // by add/restore/sync. Invalid shapes drop the canary; `undefined` clears it.3447    nextPatch.canary = patch.canary ? sanitizeCanary(patch.canary) : undefined;3448  }34493450  if ("passkey" in patch) {3451    // A patch with `passkey: undefined` removes the credential from the entry3452    // (used by "remove passkey" without deleting the whole entry).3453    if (patch.passkey === undefined || patch.passkey === null) {3454      nextPatch.passkey = undefined;3455    } else {3456      const sanitized = sanitizePasskey(patch.passkey);3457      if (!sanitized) throw new Error("invalid passkey credential");3458      nextPatch.passkey = sanitized;3459    }3460  }34613462  if ("tags" in patch) {3463    // PCH-02-001: bound tags exactly like both import funnels.3464    nextPatch.tags = sanitizeTags(patch.tags);3465  }34663467  if ("cardholderName" in patch) {3468    nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;3469  }3470  if ("cardNumber" in patch) {3471    const n = patch.cardNumber ?? "";3472    nextPatch.cardNumber = n || undefined;3473  }3474  if ("expMonth" in patch) {3475    nextPatch.expMonth = patch.expMonth?.trim() || undefined;3476  }3477  if ("expYear" in patch) {3478    nextPatch.expYear = patch.expYear?.trim() || undefined;3479  }3480  if ("cvc" in patch) {3481    nextPatch.cvc = patch.cvc?.trim() || undefined;3482  }3483  if ("cardNickname" in patch) {3484    nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;3485  }3486  if ("network" in patch) {3487    nextPatch.network = patch.network;3488  }3489  if ("last4" in patch) {3490    nextPatch.last4 = patch.last4?.trim() || undefined;3491  }34923493  return nextPatch;3494}34953496function normalizeEntry(entry: VaultEntry): VaultEntry {3497  const base: VaultEntry = {3498    id: entry.id,3499    type: entry.type,3500    title: entry.title,3501    username: entry.username,3502    email: entry.email,3503    password: entry.password,3504    url: entry.url,3505    additionalUrls:3506      "additionalUrls" in entry && Array.isArray(entry.additionalUrls)3507        ? entry.additionalUrls3508        : undefined,3509    totp: entry.totp,3510    // PCH-01-019: carry TOTP params through the normalize/restore path too.3511    totpAlgorithm: entry.totpAlgorithm,3512    totpDigits: entry.totpDigits,3513    totpPeriod: entry.totpPeriod,3514    notes: entry.notes,3515    breach: entry.breach,3516    // Preserve the password-age clock across lock/unlock. Without this the3517    // field is dropped on every decode and the advanced-health "aged password"3518    // signal silently resets to createdAt on each unlock (SEV-2-A).3519    passwordChangedAt:3520      "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,3521    // Preserve past-password history across lock/unlock. normalizeEntry is a3522    // field whitelist, so an unlisted field is silently dropped on every decode3523    // (same class as the passwordChangedAt SEV-2-A above).3524    passwordHistory:3525      "passwordHistory" in entry && Array.isArray(entry.passwordHistory)3526        ? entry.passwordHistory3527        : undefined,3528    canary: entry.canary,3529    passkey: entry.passkey,3530    createdAt: entry.createdAt,3531    modifiedAt: entry.modifiedAt,3532    deletedAt: entry.deletedAt,3533    tags: entry.tags,3534    cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,3535    cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,3536    expMonth: "expMonth" in entry ? entry.expMonth : undefined,3537    expYear: "expYear" in entry ? entry.expYear : undefined,3538    cvc: "cvc" in entry ? entry.cvc : undefined,3539    cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,3540    network: "network" in entry ? entry.network : undefined,3541    last4: "last4" in entry ? entry.last4 : undefined,3542  };35433544  return base;3545}354635473548// ---------------------------------------------------------------------------3549// Deduplication3550// ---------------------------------------------------------------------------35513552function entryDupeKey(e: VaultEntry): string {3553  if (e.passkey) {3554    // Equal identities can still carry different passwords, notes or TOTP data.3555    const content = Object.fromEntries(Object.entries(e)3556      .filter(([key]) => key !== "id" && key !== "createdAt" && key !== "modifiedAt")3557      .sort(([a], [b]) => a.localeCompare(b)));3558    return `passkey|${e.passkey.rpId}|${e.passkey.credentialId}|${JSON.stringify(content)}`;3559  }3560  if (e.type === "note") return `note|${e.title.toLowerCase()}`;3561  return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;3562}35633564/** Returns the number of duplicate entries (those that would be removed). */3565export function countDuplicates(): number {3566  const best = new Map<string, VaultEntry>();3567  let dupeCount = 0;3568  for (const e of entries.filter((e) => !e.deletedAt)) {3569    const key = entryDupeKey(e);3570    const existing = best.get(key);3571    if (!existing) {3572      best.set(key, e);3573    } else {3574      dupeCount++;3575      // Keep the more recently modified one in the map3576      if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3577        best.set(key, e);3578      }3579    }3580  }3581  return dupeCount;3582}35833584/**3585 * Soft-deletes duplicate entries, keeping the most recently modified copy of3586 * each group. Returns the number of entries moved to trash.3587 */3588export async function deduplicateEntries(): Promise<number> {3589  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3590  // Dedup reshapes slot B permanently under the decoy key, which is3591  // forensically distinguishable from a freshly-seeded decoy vault. Refuse.3592  if (vaultMode === "decoy") {3593    throw new Error("deduplicate disabled in decoy mode");3594  }35953596  const best = new Map<string, VaultEntry>();3597  for (const e of entries.filter((en) => !en.deletedAt)) {3598    const key = entryDupeKey(e);3599    const existing = best.get(key);3600    if (!existing) {3601      best.set(key, e);3602    } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3603      best.set(key, e);3604    }3605  }36063607  const keepIds = new Set(Array.from(best.values()).map((e) => e.id));3608  let removed = 0;3609  entries = entries.map((e) => {3610    if (!e.deletedAt && !keepIds.has(e.id)) {3611      removed++;3612      const deletedAt = monotonicEntryTimestamp(Math.max(3613        e.modifiedAt,3614        tombstones.get(e.id) ?? 0,3615      ));3616      tombstones.set(e.id, deletedAt);3617      return { ...e, deletedAt };3618    }3619    return e;3620  });36213622  if (removed > 0) await persistEntries();3623  return removed;3624}36253626// ---------------------------------------------------------------------------3627// Vault history — snapshot BEFORE every vault write so the saved blob is3628// what is about to be lost, not what was just written. Capped at 5. The3629// stored blobs are AES-256-GCM ciphertext under the master password, so3630// history adds zero security surface.3631// ---------------------------------------------------------------------------36323633const HISTORY_KEY = "peach_vault_history";3634const HISTORY_MAX = 5;36353636// PCH-01-023: coarsen a live-entry count into a low-resolution bucket so the3637// plaintext snapshot field cannot reveal exact vault size or single-entry change3638// deltas. Buckets widen as the vault grows so absolute leakage stays roughly3639// proportional rather than exact.3640function bucketEntryCount(n: number): number {3641  if (n <= 0) return 0;3642  if (n <= 10) return 10;3643  if (n <= 25) return 25;3644  if (n <= 50) return 50;3645  if (n <= 100) return 100;3646  if (n <= 250) return 250;3647  if (n <= 500) return 500;3648  return Math.ceil(n / 500) * 500;3649}36503651/**3652 * Snapshot the CURRENT on-disk vault state into history. Call this BEFORE3653 * overwriting peach_vault_a so the saved blob captures the about-to-be-lost3654 * state. Identical-to-most-recent blobs are skipped to avoid filling history3655 * with no-op writes.3656 */3657export async function takeVaultSnapshot(3658  reason: VaultSnapshot["reason"],3659): Promise<void> {3660  if (recoveryInFlight || vaultCreatesInFlight) return;3661  // The history store is real-mode state by construction, so it must not be3662  // written from a decoy session either. The guard lives here rather than only3663  // at the call sites so the invariant survives a new caller (PB-26-915).3664  if (vaultMode === "decoy") return;3665  vaultWritesInFlight++;3666  try {3667    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);3668    const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];3669    const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];36703671    // Nothing to snapshot if the real slot doesn't exist yet (fresh install,3672    // pre-createVault). createVault skips snapshots intentionally — there is3673    // no prior state to preserve.3674    if (!slotA) return;36753676    const vault_a = JSON.stringify(slotA);3677    const vault_b = JSON.stringify(slotB ?? slotA);36783679    // Best-effort entry count: only meaningful when the in-memory state is3680    // unlocked AND in real mode. Decoy mode would leak the decoy entry3681    // count; locked mode has no entries to count. Both fall through to null.3682    // PCH-01-023: store a coarse bucket, not the exact count — chrome.storage3683    // .local sits next to the AES-GCM blobs in plaintext, so an exact count would3684    // leak vault size and per-write deltas (the metadata padding hides this).3685    let entryCount: number | null = null;3686    if (derivedKey && vaultMode === "real") {3687      try {3688        entryCount = bucketEntryCount(entries.filter((e) => !e.deletedAt).length);3689      } catch {3690        entryCount = null;3691      }3692    }36933694    const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];3695    const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)3696      ? existingRaw3697      : { snapshots: [] };36983699    // Deduplication: if the most recent snapshot has byte-identical blobs,3700    // skip — saves the same vault N times in a row would otherwise burn the3701    // entire history window with no recovery value.3702    const latest = history.snapshots[0];3703    if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {3704      return;3705    }37063707    const snapshot: VaultSnapshot = {3708      id: crypto.randomUUID(),3709      savedAt: Date.now(),3710      reason,3711      vault_a,3712      vault_b,3713      entryCount,3714    };37153716    history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);3717    if (recoveryInFlight || vaultCreatesInFlight) return;3718    await chrome.storage.local.set({ [HISTORY_KEY]: history });3719  } catch (err) {3720    // Non-fatal — history must never block a save. A failed snapshot just3721    // means the user loses one rung of the safety ladder for this write.3722    // M4/QUA-006: log so the failure is visible; if it looks like a quota3723    // problem, notify the popup so the user can prune history themselves.3724    console.warn('[Peach] takeVaultSnapshot failed:', err);3725    if (String(err).includes('QUOTA') || String(err).includes('quota')) {3726      try {3727        await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });3728      } catch {3729        // popup may be closed; surfaced via console.warn above3730      }3731    }3732  } finally { vaultWritesInFlight--; }3733}37343735/** Wipe all vault history. Called by Panic / DESTROY_VAULT. */3736export async function clearVaultHistory(): Promise<void> {3737  if (recoveryInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");3738  vaultWritesInFlight++;3739  try {3740    await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });3741  } catch {3742    // Non-fatal — DESTROY_VAULT also runs storage.local.clear().3743  } finally { vaultWritesInFlight--; }3744}37453746/** Read all snapshots, newest first, for the Settings vault history view. */3747export async function getVaultHistory(): Promise<VaultSnapshot[]> {3748  if (vaultMode === "decoy") return [];3749  const raw = await chrome.storage.local.get(HISTORY_KEY);3750  const value = (raw as Record<string, unknown>)[HISTORY_KEY];3751  return sanitizeHistory(value);3752}37533754/**3755 * Replace the on-disk vault with the chosen snapshot's blobs and lock the3756 * vault. The current state is itself snapshotted before replacement.3757 */3758export async function restoreVaultSnapshot(3759  snapshotId: string,3760): Promise<{ ok: true } | { ok: false; error: string }> {3761  if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "vault_changed" };3762  vaultReplacementInFlight = true;3763  try {3764    if (vaultMode === "decoy") return { ok: false, error: "vault_locked" };3765    const history = await getVaultHistory();3766    const snapshot = history.find((s) => s.id === snapshotId);3767    if (!snapshot) return { ok: false, error: "snapshot_not_found" };37683769    const restoredA = parseHistorySlot(snapshot.vault_a);3770    const restoredB = parseHistorySlot(snapshot.vault_b);3771    if (!restoredA || !restoredB) return { ok: false, error: "snapshot_corrupt" };37723773    await takeVaultSnapshot("restore");3774    const current = await chrome.storage.local.get([SLOT_A, SLOT_B]);3775    const previousA = (current as Record<string, unknown>)[SLOT_A];3776    const previousB = (current as Record<string, unknown>)[SLOT_B];3777    try {3778      if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };3779      await chrome.storage.local.set({ [SLOT_A]: restoredA, [SLOT_B]: restoredB });3780      await stampLocalVaultMutation();3781    } catch {3782      try {3783        await chrome.storage.local.set({ [SLOT_A]: previousA, [SLOT_B]: previousB });3784      } catch {3785        // Preserve the restore failure if storage cannot complete the rollback.3786      }3787      return { ok: false, error: "snapshot_corrupt" };3788    }37893790    await lock();3791    return { ok: true };3792  } finally {3793    vaultReplacementInFlight = false;3794  }3795}37963797/**3798 * Rotate the vault's sync identity by generating a FRESH ROOT KEY and3799 * re-wrapping everything under it (MV-8). Because every sync credential —3800 * vault_id, the Noise static keypair, the Ed25519 manifest signing key,3801 * and the per-entry envelope keys — derives from the root key, rotation3802 * makes a lost/stolen device's retained key material useless. All paired3803 * devices must re-pair afterwards.3804 *3805 * CONSEQUENCE THE UI MUST SURFACE: the 12 recovery words also derive from3806 * the root key, so rotation INVALIDATES the old recovery phrase. The flow3807 * sets peach_recovery_pending so the popup re-presents the new words for3808 * confirmation, same as the initial recovery-word confirmation path.3809 */3810export async function rotateSyncIdentity(): Promise<{ ok: boolean; error?: string }> {3811  if (vaultCreatesInFlight) throw new Error("vault_changed");3812  const rotationEpoch = vaultEpoch;3813  const removalEpoch = vaultRemovalEpoch;3814  vaultWritesInFlight++;3815  try {3816  if (!derivedKey || vaultMode !== "real") {3817    return { ok: false, error: "vault_locked" };3818  }3819  const slotA = await loadSlot(SLOT_A);3820  if (!slotA) return { ok: false, error: "missing_slot_a" };38213822  // 1. Fresh root key + recovery escrow (new words).3823  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =3824    await generateAndWrapRootKey();38253826  // 2. Re-wrap the new root key under the current password-derived key.3827  const newRootKey = unhex(rawRootKey);3828  const recoveryVaultKey = await encrypt(newRootKey, hex(derivedKey), "recovery_vault_key_v1");3829  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, newRootKey);38303831  // 3. Snapshot, then single atomic slot write — both escrow wrappings of3832  //    the new root key land together (same transactional rule as3833  //    changePassword). Entries are untouched: they are sealed under the3834  //    password-derived key, not the root key.3835  await takeVaultSnapshot("local_save");3836  const nextSlotA: StoredVault = {3837    ...slotA,3838    recovery_vault_key: recoveryVaultKey,3839    recovery_salt: recoverySalt,3840    recovery_wrapped_root_key: wrappedRootKey,3841    recovery_nonce: wrappedNonce,3842    recovery_tag: wrappedTag,3843    ...pwRoot,3844  };3845  await writeSlot(SLOT_A, nextSlotA);38463847  // 4. Swap in memory only after disk committed.3848  if (rotationEpoch === vaultEpoch && derivedKey) {3849    if (rootKey) zeroKey(rootKey);3850    rootKey = newRootKey;3851  } else {3852    zeroKey(newRootKey);3853  }38543855  // 4b. The identity's root wrap was encrypted under the dead root. Without3856  //     this the identity survives only until the unlock key also changes.3857  await notifyIdentityKeysRotated();38583859  // 5. Old peers' identities derive from the dead root key — drop them all,3860  // with their rendezvous secrets (PB-26-213: rotation clears the map, so3861  // there is nothing to rewrap under the new key).3862  await clearPairedDevices();3863  await clearPairSecrets();38643865  // 6. Force re-presentation of the NEW recovery words on next popup view.3866  if (removalEpoch === vaultRemovalEpoch) {3867    await setRecoveryConfirmPending(rotationEpoch === vaultEpoch && isUnlocked());3868    touchAutoLock();3869  }38703871  await stampLocalVaultMutation();3872  return { ok: true };3873  } finally { vaultWritesInFlight--; }3874}38753876/**3877 * Change the master password. Re-encrypts slot A with a fresh salt + new3878 * derived key. Slot B (duress or noise) is left untouched when duress is3879 * configured — it uses an independent key derived from the duress password —3880 * and regenerated as noise when duress is not configured.3881 */3882export async function changePassword(3883  currentPassword: string,3884  newPassword: string3885): Promise<boolean> {3886  if (vaultCreatesInFlight) throw new Error("vault_changed");3887  vaultWritesInFlight++;3888  try {38893890  const epoch = vaultEpoch;3891  const stale = () => epoch !== vaultEpoch;3892  if (!derivedKey || vaultMode !== "real") return false;38933894  // Verify current password before allowing any change3895  const valid = await verifyMainPassword(currentPassword);3896  if (!valid) return false;38973898  const slotA = await loadSlot(SLOT_A);3899  if (!slotA) return false;3900  if (!rootKey) return false;39013902  // Derive fresh key from new password + new random salt3903  const newSalt = generateSalt();3904  const newKey = await deriveKey(newPassword, newSalt);3905  if (stale()) {3906    zeroKey(newKey);3907    return false;3908  }39093910  // Re-encrypt the in-memory entries with the new key3911  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3912  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");39133914  // Pre-wrap root key under the new derived key. Recovery fields wrap rootKey3915  // under recovery words and remain untouched — recovery phrase keeps working3916  // across password changes (H4/COR-002).3917  const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);39183919  const recoveryVaultKey = await encrypt(rootKey, hex(newKey), "recovery_vault_key_v1");3920  const finalSlotA: StoredVault = {3921    ...slotA,3922    recovery_vault_key: recoveryVaultKey,3923    salt: hex(newSalt),3924    nonce,3925    ciphertext,3926    tag,3927    ...pwRoot,3928  };39293930  // Snapshot the OLD-key blob before overwriting it. If the user later3931  // restores from this snapshot they will need the OLD password — the3932  // post-restore lock surfaces that immediately.3933  await takeVaultSnapshot("local_save");39343935  // Single atomic write: ciphertext, salt, and pw_root_* fields all land in3936  // one storage transaction. An SW kill before this point leaves the old3937  // slot intact; after this point everything tied to the new password is3938  // already on disk together (M6/COR-004).3939  await writeSlot(SLOT_A, finalSlotA);3940  if (stale()) {3941    zeroKey(newKey);3942    return false;3943  }39443945  // Swap the in-memory key synchronously before any further await. If we3946  // threw between the Slot A write and this swap, the next persistEntries()3947  // would overwrite Slot A with old-key ciphertext, locking the user out.3948  zeroKey(derivedKey);3949  cancelBreachScan();3950  derivedKey = newKey;39513952  // PCH-01-008: the MV3 session escrow still holds the OLD key. Without this,3953  // the next service-worker restore decrypts the new-key Slot A with the stale3954  // key, fails tryDecryptSlotResult, and silently drops the user to a lock3955  // screen. Re-escrow the new key so restore survives a password change.3956  if (stale()) {3957    await lock();3958    return false;3959  }3960  await saveSessionKey(newKey, "real", epoch);3961  if (stale()) return false;39623963  // The identity envelope holds one wrap per recovering key. Swapping the3964  // unlock key kills the local wrap, so re-wrap now or the next key swap3965  // orphans the identity -- and until then the old password still opens it.3966  await notifyIdentityKeysRotated();3967  if (stale()) return false;39683969  // Regenerate noise for slot B when duress is not in use. Runs after the3970  // key swap so a failure here is a disposable noise regeneration, not a3971  // lockout.3972  if (!duressConfigured) {3973    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3974  }3975  await clearPinUnlockStorage();3976  await stampLocalVaultMutation();39773978  return true;3979  } finally { vaultWritesInFlight--; }3980}