vault.ts

103.1 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, deriveKeyRaw, generateSalt } from "../crypto/argon2";13import { extractDomain } from "../shared/domain";14import { clampSyncTimestamp } from "../shared/sync-limits";15import { recordSyncAlerts, type SyncAlert } from "./sync-alerts";16import {17  rootKeyToWords,18  wordsToRootKeyMaterial,19  deriveRecoveryKey,20} from "../shared/recovery-words";21import type {22  AccentColorName,23  Canary,24  LegacyVaultEntry,25  ManualSummonRecord,26  PasskeyData,27  SavedIdentity,28  StoredVault,29  VaultEntry,30  VaultHistory,31  VaultSnapshot,32} from "../shared/types";33import { decrypt, encrypt, zeroKey } from "./aes";34import { clearAutoLock, touchAutoLock } from "./alarms";35import { setRecoveryConfirmPending } from "./recovery-pending";3637type EntryDraft = Omit<38  VaultEntry,39  "id" | "createdAt" | "modifiedAt" | "deletedAt"40>;4142// Slot-neutral storage keys (v1.4.24+). Both slots always exist; slot B43// either holds the decoy vault (when duress is configured) or random noise44// that looks identical at rest. No external indicator is stored — duress45// configuration is recorded only inside the encrypted payload of slot A.46const SLOT_A = "peach_vault_a";47const SLOT_B = "peach_vault_b";4849// Legacy keys, migrated away on first access.50const LEGACY_MAIN = "peach_vault";51const LEGACY_DECOY = "peach_decoy_vault";52const LEGACY_DURESS_FLAG = "peach_duress";5354// Plaintext is padded to the next multiple of this size before encryption.55// This coarsens ciphertext-length leakage into 1 KiB buckets.56const PAD_BLOCK = 1024;5758// How many past passwords to retain per entry. Generous enough to be useful as59// a recovery aid while bounding the secret material we hold (and the ciphertext60// growth) for an entry whose password is rotated frequently.61const PASSWORD_HISTORY_MAX = 50;6263// When duress is configured, BOTH slots are padded to this fixed ceiling so64// their ciphertext lengths are identical and cannot reveal that a hidden decoy65// vault exists (audit MEDIUM — plausible-deniability leak). 256 KiB comfortably66// holds a very large vault (thousands of entries incl. passkeys). The decoy67// slot can't be re-encrypted on every real-vault save (the real session has no68// decoy key), so a fixed ceiling — rather than size-matching on each write — is69// what keeps the two slots equal. A real vault whose plaintext exceeds this70// would grow past the ceiling and re-expose the bit; that is an extreme,71// documented edge well beyond normal use.72const DURESS_SLOT_SIZE = 262_144;7374let derivedKey: Uint8Array | null = null;75// 32-byte random root key, separate from the derivedKey used for vault encryption.76// The root key is wrapped (encrypted) under the recovery key derived from the77// 12-word phrase. When the user changes their password, only the wrapping changes;78// the root key and recovery words remain stable.79let rootKey: Uint8Array | null = null;80let entries: VaultEntry[] = [];81let domainIndex: Map<string, VaultEntry[]> = new Map();82let vaultMode: "real" | "decoy" = "real";83// Cached post-unlock view of whether the real vault records that duress is84// configured. Only meaningful after a real-mode unlock; for decoy-mode unlock85// this stays false because we never see slot A's plaintext.86let duressConfigured = false;8788let migrationRan = false;8990// Set to a corruption reason during the last unlock() attempt when both slots91// decrypted but failed schema validation. Consumed and cleared by92// consumeLastUnlockFailureReason() so messages.ts can surface vault_corrupted93// distinctly from wrong-password (M7/COR-007).94//95// NOTE: module-level state — if vault.ts is ever moved to a worker context,96// this must be replaced with a structured return value from unlock() or a97// postMessage channel. The signal is invisible across module-instance98// boundaries.99let lastUnlockFailureReason: string | null = null;100101export function consumeLastUnlockFailureReason(): string | null {102  const r = lastUnlockFailureReason;103  lastUnlockFailureReason = null;104  return r;105}106107// ---------------------------------------------------------------------------108// Settings (persisted inside the encrypted vault store as a sidecar key)109// ---------------------------------------------------------------------------110111export type TextSize = "small" | "medium" | "large";112113export interface VaultSettings {114  accentColor?: AccentColorName;115  theme?: "dark" | "light";116  autoLockMinutes?: number;117  clipboardClearSeconds?: number;118  lockOnClose?: boolean;119  breachMonitoring?: boolean;120  passkeyProviderEnabled?: boolean;121  trashRetentionDays?: number;122  manualSummonDomains?: Record<string, ManualSummonRecord>;123  declinedCardFingerprints?: string[];124  /**125   * Text size scale for body copy and entry titles. Stops at "large" by126   * design — XL clips dense screens (Vault, Health) inside the fixed127   * 330×480 popup surface.128   */129  textSize?: TextSize;130  /**131   * When true, all entrance/exit transitions and ambient animations are132   * collapsed to instant. Honoured alongside the user's OS-level133   * `prefers-reduced-motion`.134   */135  reduceMotion?: boolean;136  /**137   * Android-only: when true, the master key is escrowed in AndroidKeyStore138   * and the lock screen offers biometric unlock. Toggled from Settings →139   * Security → Biometrics. Has no effect on desktop builds.140   */141  biometricsEnabled?: boolean;142  /**143   * User overrides for keyboard shortcuts. Keys are ShortcutAction names144   * (see src/shared/shortcuts.ts). Missing actions fall through to145   * DEFAULT_BINDINGS — `getActiveBindings(settings.shortcuts)` is the146   * canonical lookup. Storing only the deltas keeps the vault payload147   * small and lets default updates land for users who never rebind.148   */149  shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;150}151152let settings: VaultSettings = {};153154export function getSettings(): VaultSettings {155  return settings;156}157158export async function ensureSettingsLoaded(): Promise<VaultSettings> {159  await loadSettings();160  return settings;161}162163export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {164  await loadSettings();165  settings = { ...settings, ...patch };166  await persistSettings();167}168169async function persistSettings(): Promise<void> {170  try {171    await chrome.storage.local.set({ peach_settings: settings });172  } catch (err) {173    throw mapStorageError(err);174  }175}176177function mapStorageError(err: unknown): Error {178  const message = err instanceof Error ? err.message : String(err);179  if (/QUOTA_BYTES|quota/i.test(message)) {180    return new Error("STORAGE_QUOTA_EXCEEDED");181  }182  return err instanceof Error ? err : new Error(message);183}184185async function loadSettings(): Promise<void> {186  const result = await chrome.storage.local.get("peach_settings");187  settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};188}189190// Fire-and-forget sync trigger after a committed vault write. Lazy191// dynamic import avoids a circular dependency between vault.ts and192// sync-trigger.ts (the trigger imports paired-devices, which only reads193// storage, but the lazy load also gives us a clean opt-out path in194// tests where sync-trigger has not been initialised).195function fireSyncTrigger(reason: "vault_change"): void {196  void import("./sync-trigger")197    .then((mod) => mod.triggerSyncIfReachable({ reason }))198    .catch(() => {199      /* sync trigger module not available — non-fatal */200    });201}202203// ---------------------------------------------------------------------------204// HIBP breach check (k-anonymity model)205// ---------------------------------------------------------------------------206207export async function checkBreach(password: string): Promise<number> {208  // HIBP k-anonymity API is keyed on SHA-1 prefixes — this is dictated by209  // the public API, not a security choice. Do not migrate to SHA-256 here.210  const encoder = new TextEncoder();211  const hashBuffer = await crypto.subtle.digest("SHA-1", encoder.encode(password));212  const hashHex = Array.from(new Uint8Array(hashBuffer))213    .map((b) => b.toString(16).padStart(2, "0"))214    .join("")215    .toUpperCase();216217  const prefix = hashHex.slice(0, 5);218  const suffix = hashHex.slice(5);219220  try {221    const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`);222    if (!res.ok) return 0;223    const text = await res.text();224    const match = text.split("\r\n").find((l) => l.startsWith(suffix));225    return match ? parseInt(match.split(":")[1], 10) : 0;226  } catch {227    return 0; // Network unavailable — don't block228  }229}230231export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {232  const fingerprint = await cardFingerprint(last4, expMonth, expYear);233  await loadSettings();234  settings = {235    ...settings,236    declinedCardFingerprints: [...(settings.declinedCardFingerprints ?? []), fingerprint],237  };238  await persistSettings();239}240241export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {242  await loadSettings();243  const fingerprint = await cardFingerprint(last4, expMonth, expYear);244  return (settings.declinedCardFingerprints ?? []).includes(fingerprint);245}246247async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {248  const encoder = new TextEncoder();249  const buf = await crypto.subtle.digest("SHA-256", encoder.encode(`${last4}|${expMonth}|${expYear}`));250  return Array.from(new Uint8Array(buf).slice(0, 8))251    .map((b) => b.toString(16).padStart(2, "0"))252    .join("");253}254255function hex(buf: Uint8Array): string {256  return Array.from(buf)257    .map((b) => b.toString(16).padStart(2, "0"))258    .join("");259}260261function unhex(s: string): Uint8Array {262  const out = new Uint8Array(s.length / 2);263  for (let i = 0; i < s.length; i += 2) {264    out[i / 2] = parseInt(s.slice(i, i + 2), 16);265  }266  return out;267}268269// ---------------------------------------------------------------------------270// Root key generation and recovery word wrapping271// ---------------------------------------------------------------------------272273/**274 * Generate a random 32-byte root key and wrap it (AES-256-GCM) under a key275 * derived from the recovery word material via HKDF-SHA256. The wrapped blob276 * fields are stored in slot A alongside the password-wrapped ciphertext. The277 * root key itself is kept in memory for the session so getRecoveryWords() can278 * encode it without re-deriving.279 */280async function generateAndWrapRootKey(): Promise<{281  rawRootKey: string; // hex of the plaintext root key — caller stores in rootKey282  recoverySalt: string;283  wrappedRootKey: string;284  wrappedNonce: string;285  wrappedTag: string;286}> {287  const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));288289  // Derive the recovery key from the BIP39 words encoding of the root key.290  const words = await rootKeyToWords(rootKeyBytes);291  const wordMaterial = await wordsToRootKeyMaterial(words);292  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));293  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);294295  // Wrap the root key with the recovery key using AES-256-GCM directly.296  // We hex-encode rootKeyBytes so the plaintext is always valid UTF-8.297  const nonce = crypto.getRandomValues(new Uint8Array(12));298  const encoded = new TextEncoder().encode(hex(rootKeyBytes));299  const raw = await crypto.subtle.encrypt(300    {301      name: "AES-GCM",302      iv: nonce,303      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,304      tagLength: 128,305    },306    recoveryKey,307    encoded308  );309  // WebCrypto returns ciphertext || auth tag concatenated; split them.310  const rawU8 = new Uint8Array(raw);311  const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));312  const tag = hex(rawU8.slice(rawU8.length - 16));313314  return {315    rawRootKey: hex(rootKeyBytes),316    recoverySalt: hex(recoverySalt),317    wrappedRootKey: ciphertext,318    wrappedNonce: hex(nonce),319    wrappedTag: tag,320  };321}322323/**324 * Unwrap the root key using recovery words. Called during recovery flow when325 * the user provides their 12-word phrase and a new password.326 * Exported for use by the RECOVER_WITH_WORDS message handler.327 */328export async function unwrapRootKeyForRecovery(329  wrappedRootKey: string,330  wrappedNonce: string,331  wrappedTag: string,332  recoverySaltHex: string,333  words: string[]334): Promise<void> {335  const wordMaterial = await wordsToRootKeyMaterial(words);336  const recoverySalt = unhex(recoverySaltHex);337  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);338339  // Decrypt and cache the root key. The root key bytes were hex-encoded before340  // encryption so the ciphertext is valid UTF-8. We inline the AES-GCM decrypt341  // here to avoid passing a CryptoKey to the string-based encrypt/decrypt helpers.342  // Each component is stored separately in the vault slot; decode them individually343  // so the nonce is always exactly the 12 bytes from wrappedNonce.344  const nonceRaw = unhex(wrappedNonce);345  const ciphertextRaw = unhex(wrappedRootKey);346  const tagRaw = unhex(wrappedTag);347  // Combine ciphertext and tag for AES-GCM (expects ciphertext||tag).348  // Use explicit ArrayBuffer allocations to satisfy TS BufferSource constraints.349  const nonceU8 = nonceRaw as unknown as Uint8Array<ArrayBuffer>;350  const combined = new Uint8Array(ciphertextRaw.length + tagRaw.length);351  combined.set(ciphertextRaw, 0);352  combined.set(tagRaw, ciphertextRaw.length);353  const raw = await crypto.subtle.decrypt(354    { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },355    recoveryKey,356    combined357  );358  const decryptedHex = new TextDecoder().decode(raw);359  rootKey = unhex(decryptedHex);360}361362/**363 * Re-wrap the cached root key under a new derived key (from the user's new364 * password). Called after password change and after recovery re-key so the365 * same recovery words continue to work with the updated password — and so366 * subsequent unlocks can rehydrate rootKey via deriveRootKeyFromDerivedKey.367 *368 * recovery_* fields are intentionally not touched: those wrap rootKey under369 * the recovery words, which do not change when the password changes.370 */371export async function rewrapRootKeyForPassword(372  newDerivedKey: Uint8Array,373  _newSalt: Uint8Array374): Promise<void> {375  if (!rootKey) throw new Error("root key not set");376  const slotA = await loadSlot(SLOT_A);377  if (!slotA) throw new Error("missing slot A");378  const pwRoot = await wrapRootKeyForDerivedKey(newDerivedKey, rootKey);379  await writeSlot(SLOT_A, { ...slotA, ...pwRoot });380}381382/**383 * Change the vault encryption to a new derived key (already derived from384 * the user's new password). Used by RECOVER_WITH_WORDS and changePassword.385 * Caller is responsible for key swap and snapshot.386 */387async function reencryptVaultForNewKey(388  newKey: Uint8Array,389  slotA: StoredVault390): Promise<void> {391  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);392  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");393  await writeSlot(SLOT_A, {394    ...slotA,395    nonce,396    ciphertext,397    tag,398  });399}400401/**402 * Full password change with an already-derived key (used after recovery).403 * Unlike changePassword(), this skips re-verification of current password404 * since recovery flow has already validated the user's identity via words.405 */406export async function changePasswordWithNewKey(407  newSalt: Uint8Array,408  newKey: Uint8Array409): Promise<void> {410  const slotA = await loadSlot(SLOT_A);411  if (!slotA) throw new Error("missing slot A");412  // reencryptVaultForNewKey must receive the updated salt so that subsequent413  // UNLOCK calls with the new password can re-derive the correct key.414  await reencryptVaultForNewKey(newKey, { ...slotA, salt: hex(newSalt) });415  if (derivedKey) zeroKey(derivedKey);416  derivedKey = newKey;417  // Refresh pw_root_* under the new key so deriveRootKeyFromDerivedKey works418  // on the next unlock (H2/COR-006). If rootKey is missing — recovery flow419  // should have populated it — fall back silently rather than blowing up the420  // recovery path; migrateToRecovery will rehydrate on the next unlock.421  if (rootKey) {422    const slotAfter = await loadSlot(SLOT_A);423    if (slotAfter) {424      const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);425      await writeSlot(SLOT_A, { ...slotAfter, ...pwRoot });426    }427  }428  if (!duressConfigured) {429    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));430  }431  await stampLocalVaultMutation();432}433434// ---------------------------------------------------------------------------435// Salt generation --- exported so the RECOVER_WITH_WORDS handler can derive436// a new key after password reset without re-importing the crypto module.437// ---------------------------------------------------------------------------438439export { deriveKey, generateSalt };440441export async function loadSlotA(): Promise<StoredVault | null> {442  return loadSlot(SLOT_A);443}444445/**446 * Recover the session root key by AES-GCM-decrypting the pw_root_* fields447 * (a second wrapping of the root key under the password-derived key). This448 * is what makes GET_RECOVERY_WORDS work across lock/unlock cycles without449 * the user re-entering their recovery phrase: the same root key bytes —450 * and therefore the same 12 words — survive every unlock.451 *452 * Returns null when the pw_root fields are absent (pre-v2.12 vault that453 * hasn't been migrated yet) or when decryption fails (wrong derived key,454 * tampered ciphertext). On null the caller should fall through to455 * migrateToRecovery() to populate the fields.456 */457async function deriveRootKeyFromDerivedKey(458  derivedKeyBytes: Uint8Array,459  slotA: StoredVault,460): Promise<Uint8Array | null> {461  if (!slotA.pw_root_ciphertext || !slotA.pw_root_nonce || !slotA.pw_root_tag) {462    return null;463  }464  try {465    const rootHex = await decrypt(466      derivedKeyBytes,467      slotA.pw_root_nonce,468      slotA.pw_root_ciphertext,469      slotA.pw_root_tag,470      "pw_root_v1",471    );472    return unhex(rootHex);473  } catch {474    return null;475  }476}477478// AES-GCM-wrap rootKey under derivedKey for the pw_root_* fields. Returns the479// hex-encoded ciphertext/nonce/tag triple ready to embed in StoredVault.480async function wrapRootKeyForDerivedKey(481  derivedKeyBytes: Uint8Array,482  rootKeyBytes: Uint8Array,483): Promise<{ pw_root_ciphertext: string; pw_root_nonce: string; pw_root_tag: string }> {484  const { nonce, ciphertext, tag } = await encrypt(derivedKeyBytes, hex(rootKeyBytes), "pw_root_v1");485  return {486    pw_root_ciphertext: ciphertext,487    pw_root_nonce: nonce,488    pw_root_tag: tag,489  };490}491492/**493 * For vaults created before v2.12 (no recovery_salt/recovery_wrapped_root_key),494 * generate the root key, wrap it under the recovery words, and persist the495 * recovery escrow into slot A. The caller must show the recovery words to the496 * user before calling this — once called, those words are the vault's recovery497 * path. This runs once, on the first unlock of an upgraded vault.498 */499export async function migrateToRecovery(): Promise<void> {500  if (!derivedKey || vaultMode !== "real") {501    throw new Error("vault must be unlocked in real mode");502  }503  const slotA = await loadSlot(SLOT_A);504  if (!slotA) throw new Error("missing slot A");505  const hasRecoveryEscrow =506    !!slotA.recovery_salt && !!slotA.recovery_wrapped_root_key;507  const hasPwRoot = !!slotA.pw_root_ciphertext && !!slotA.pw_root_nonce;508  if (hasRecoveryEscrow && hasPwRoot) return; // already done509510  // If recovery escrow already exists but pw_root doesn't, we cannot recover511  // the original rootKey without the user's words. The least-surprising path512  // is to rotate to a fresh root key — the user's old recovery words become513  // invalid but we surface peach_recovery_pending so the popup re-presents514  // the words. The unlock-path callers all set that flag.515  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =516    await generateAndWrapRootKey();517  rootKey = unhex(rawRootKey);518519  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);520  const nextSlotA: StoredVault = {521    ...slotA,522    recovery_salt: recoverySalt,523    recovery_wrapped_root_key: wrappedRootKey,524    recovery_nonce: wrappedNonce,525    recovery_tag: wrappedTag,526    ...pwRoot,527  };528  await writeSlot(SLOT_A, nextSlotA);529  await stampLocalVaultMutation();530}531532/**533 * Returns the 12 recovery words for the current session's root key.534 * Must be called while the vault is unlocked. Throws if recovery has not535 * been set up (pre-v2.12 vault that hasn't migrated yet).536 */537export async function getRecoveryWords(): Promise<string[]> {538  if (!rootKey) {539    throw new Error("recovery not set up — vault may need migration");540  }541  return rootKeyToWords(rootKey);542}543544async function loadSlot(key: string): Promise<StoredVault | null> {545  const result = await chrome.storage.local.get(key);546  return (result as Record<string, StoredVault | undefined>)[key] ?? null;547}548549async function writeSlot(key: string, vault: StoredVault): Promise<void> {550  try {551    await chrome.storage.local.set({ [key]: vault });552  } catch (err) {553    throw mapStorageError(err);554  }555}556557// Monotonic clock for per-entry modifiedAt / deletedAt timestamps. Guards the558// sync layer's last-write-wins merge against wall-clock regressions (NTP step,559// manual clock change, DST glitch): a backwards Date.now() must never produce560// an entry timestamp that's <= the entry's existing modifiedAt, or a genuine561// local edit would lose to a stale remote copy. The returned value is always562// strictly greater than both the entry's current modifiedAt and the previous563// call's result (SEV-2-E).564let lastEntryTimestamp = 0;565function monotonicEntryTimestamp(currentModifiedAt?: number): number {566  const base = Math.max(567    Date.now(),568    (currentModifiedAt ?? 0) + 1,569    lastEntryTimestamp + 1,570  );571  lastEntryTimestamp = base;572  return base;573}574575async function stampLocalVaultMutation(): Promise<void> {576  const raw = await chrome.storage.local.get("peach_last_modified_at");577  const previous = Number(578    (raw as Record<string, unknown>).peach_last_modified_at,579  );580  const next = Math.max(581    Date.now(),582    Number.isFinite(previous) ? previous + 1 : 0,583  );584  await chrome.storage.local.set({585    peach_last_modified_at: String(next),586  });587}588589/**590 * One-shot migration from the pre-A-2 schema (peach_vault + peach_decoy_vault591 * + peach_duress flag) to the slot-neutral schema (peach_vault_a +592 * peach_vault_b). Runs at most once per session; safe to call repeatedly.593 */594async function ensureMigrated(): Promise<void> {595  if (migrationRan) return;596  migrationRan = true;597598  const keys = [LEGACY_MAIN, LEGACY_DECOY, LEGACY_DURESS_FLAG, SLOT_A, SLOT_B];599  const raw = await chrome.storage.local.get(keys);600  const slotAExists = raw[SLOT_A] !== undefined;601  const slotBExists = raw[SLOT_B] !== undefined;602  const legacyMain = raw[LEGACY_MAIN] as StoredVault | undefined;603  const legacyDecoy = raw[LEGACY_DECOY] as StoredVault | undefined;604605  // Fresh install with nothing in storage — nothing to do; createVault() sets up both slots.606  if (!slotAExists && !legacyMain) return;607608  // Already migrated.609  if (slotAExists && slotBExists && !legacyMain && !legacyDecoy) return;610611  let didMigrate = false;612  if (legacyMain && !slotAExists) {613    await writeSlot(SLOT_A, legacyMain);614    didMigrate = true;615  }616617  // If slot B isn't set, populate it: use legacy decoy when present, else noise.618  if (!slotBExists) {619    const target = (legacyMain ?? raw[SLOT_A]) as StoredVault | undefined;620    if (legacyDecoy) {621      await writeSlot(SLOT_B, legacyDecoy);622      didMigrate = true;623    } else if (target) {624      await writeSlot(SLOT_B, generateNoiseBlob(target.ciphertext.length / 2));625      didMigrate = true;626    }627  }628629  const toRemove: string[] = [];630  if (legacyMain) toRemove.push(LEGACY_MAIN);631  if (legacyDecoy) toRemove.push(LEGACY_DECOY);632  if (raw[LEGACY_DURESS_FLAG] !== undefined) toRemove.push(LEGACY_DURESS_FLAG);633  if (toRemove.length > 0) {634    await chrome.storage.local.remove(toRemove);635    didMigrate = true;636  }637  if (didMigrate) {638    await stampLocalVaultMutation();639  }640}641642// ---------------------------------------------------------------------------643// Padding + noise helpers644// ---------------------------------------------------------------------------645646/**647 * Pads the plaintext string with trailing spaces so that the encoded byte648 * length is a multiple of PAD_BLOCK. JSON.parse tolerates trailing649 * whitespace after a complete document, so the padding is transparent on650 * decode. Ciphertext length equals plaintext length plus a 16-byte tag.651 */652function padPlaintext(json: string, minBytes = 0): string {653  const encoded = new TextEncoder().encode(json);654  const bucket = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);655  // minBytes lets the duress path force a fixed ceiling so both slots match.656  const target = Math.max(bucket, minBytes);657  const padLen = target - encoded.length;658  return json + " ".repeat(padLen);659}660661/**662 * Produces a StoredVault-shaped record filled with CSPRNG bytes. The663 * ciphertext length matches the given byte count. Because GCM ciphertext is664 * pseudo-random, this blob is indistinguishable at rest from a real665 * encrypted vault without the key.666 *667 * crypto.getRandomValues() caps each call at 65536 bytes (the Web Crypto668 * spec hard limit). Chunk the fill so vaults larger than that — common once669 * the user has dozens of entries or any passkey — don't throw.670 */671const CSPRNG_CHUNK = 65_536;672673function fillRandom(buf: Uint8Array): Uint8Array {674  for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {675    const end = Math.min(offset + CSPRNG_CHUNK, buf.length);676    const chunk = new Uint8Array(end - offset);677    crypto.getRandomValues(chunk);678    buf.set(chunk, offset);679  }680  return buf;681}682683function generateNoiseBlob(ciphertextBytes: number): StoredVault {684  const salt = crypto.getRandomValues(new Uint8Array(16));685  const nonce = crypto.getRandomValues(new Uint8Array(12));686  const cipher = fillRandom(new Uint8Array(ciphertextBytes));687  const tag = crypto.getRandomValues(new Uint8Array(16));688  return {689    version: 1,690    salt: hex(salt),691    nonce: hex(nonce),692    ciphertext: hex(cipher),693    tag: hex(tag),694  };695}696697// ---------------------------------------------------------------------------698// Encrypted plaintext envelope699// ---------------------------------------------------------------------------700701type VaultPayload = {702  entries: VaultEntry[];703  duressConfigured?: boolean;704};705706type DecryptedPayload = {707  entries: VaultEntry[];708  duressConfigured: boolean;709  /**710   * True when at least one entry in the on-disk payload had a legacy shape711   * (pre-v2.11.0 passkey type/flat fields, or pre-A-2 created/updated keys)712   * and got rewritten by normalizeEntry. The unlock path uses this to713   * persist the new shape immediately — without it, the migration would714   * re-run on every unlock and old shape never disappears from disk.715   */716  migratedFromLegacy: boolean;717};718719function encodePayload(entries: VaultEntry[], duress: boolean, minBytes = 0): string {720  const envelope: VaultPayload = { entries, duressConfigured: duress };721  return padPlaintext(JSON.stringify(envelope), minBytes);722}723724function rawNeedsMigration(raw: VaultEntry | LegacyVaultEntry): boolean {725  if ("created" in raw || "updated" in raw) return true;726  const flat = raw as Partial<VaultEntry>;727  if (flat.type === "passkey") return true;728  // Flat rpId without a passkey sub-object means pre-v2.11.0 schema.729  if (flat.rpId !== undefined && flat.passkey === undefined) return true;730  return false;731}732733function decodePayload(plain: string): DecryptedPayload {734  const parsed = JSON.parse(plain) as735    | Array<VaultEntry | LegacyVaultEntry>736    | VaultPayload;737738  const rawEntries = Array.isArray(parsed) ? parsed : parsed.entries ?? [];739  const flatMigrationNeeded = rawEntries.some(rawNeedsMigration);740741  const normalized = rawEntries.map(normalizeEntry);742  const { merged } = mergePasskeyOnlyIntoLogins(normalized);743744  if (Array.isArray(parsed)) {745    return {746      entries: normalized,747      duressConfigured: false,748      migratedFromLegacy: true, // pre-A-2 array shape always needs save749    };750  }751752  return {753    entries: normalized,754    duressConfigured: parsed.duressConfigured === true,755    migratedFromLegacy: flatMigrationNeeded || merged,756  };757}758759/**760 * One-time consolidation pass run alongside the legacy passkey migration.761 *762 * Pre-v2.11.0 the Chrome passkey path always created a fresh `type:"passkey"`763 * entry per registration — so users who tested registration multiple times764 * accumulated several passkey-bearing entries for the same RP, and the765 * migration to the unified shape carried that duplication forward. This766 * pass collapses the duplicates:767 *768 *   1. Group passkey-bearing (and not deleted) entries by `passkey.rpId`.769 *   2. Within each group, the most recently-active credential wins (prefer770 *      lastUsedAt, fall back to passkey.createdAt, fall back to modifiedAt).771 *   3. If a NON-passkey login entry exists for that RP (matched by url or772 *      additionalUrls hostname), attach the winning passkey to it and773 *      soft-delete every passkey-bearing entry in the group.774 *   4. Otherwise, soft-delete every loser in the group, keeping the winner775 *      as a passkey-only entry.776 *777 * Soft delete (deletedAt) rather than splice — the trash flow keeps the778 * record around for retention and the user can restore if the heuristic779 * picked wrong. The `merged` flag goes back to decodePayload so the780 * unlock path persists the consolidated shape immediately.781 */782function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {783  let merged = false;784  const now = Date.now();785786  const candidates = entries.filter((e) => !e.deletedAt && e.passkey);787  const byRpId = new Map<string, VaultEntry[]>();788  for (const e of candidates) {789    const rpId = e.passkey!.rpId;790    const list = byRpId.get(rpId);791    if (list) list.push(e);792    else byRpId.set(rpId, [e]);793  }794795  for (const [rpId, group] of byRpId) {796    if (group.length === 0) continue;797    group.sort((a, b) => {798      const aT =799        a.passkey!.lastUsedAt ?? a.passkey!.createdAt ?? a.modifiedAt ?? a.createdAt;800      const bT =801        b.passkey!.lastUsedAt ?? b.passkey!.createdAt ?? b.modifiedAt ?? b.createdAt;802      return bT - aT;803    });804    const winner = group[0]!;805806    // Look for a NON-passkey login entry matching this RP. Use the URL807    // hostname rather than a substring search so a "login.foo.com" entry808    // doesn't accidentally absorb a passkey for "foo.com".809    const loginTarget = entries.find((e) => {810      if (e.deletedAt || e.passkey || e.type !== "login") return false;811      if (e.url && extractDomain(e.url) === rpId) return true;812      for (const extra of e.additionalUrls ?? []) {813        if (extractDomain(extra) === rpId) return true;814      }815      return false;816    });817818    if (loginTarget) {819      loginTarget.passkey = winner.passkey;820      loginTarget.modifiedAt = now;821      for (const dup of group) {822        if (!dup.deletedAt) {823          dup.deletedAt = now;824          dup.modifiedAt = now;825        }826      }827      merged = true;828    } else if (group.length > 1) {829      for (let i = 1; i < group.length; i += 1) {830        const dup = group[i]!;831        if (!dup.deletedAt) {832          dup.deletedAt = now;833          dup.modifiedAt = now;834        }835      }836      merged = true;837    }838  }839840  return { merged };841}842843// Validates that a `StoredVault` record on disk has the field shape we expect844// before treating an AES-GCM decrypt success as a clean unlock. AES-GCM only845// authenticates the static VERSION_BYTE AAD, not the `version` field on the846// outer record — a corrupted `version: 42` slot still decrypts cleanly. This847// check surfaces that as `corrupted` (M7/COR-007) so the popup can offer a848// history-restore path instead of falsely reporting "wrong password".849function hasValidVaultSchema(v: unknown): v is StoredVault {850  if (typeof v !== "object" || v === null) return false;851  const r = v as Record<string, unknown>;852  return (853    r.version === 1 &&854    typeof r.salt === "string" &&855    typeof r.nonce === "string" &&856    typeof r.ciphertext === "string" &&857    typeof r.tag === "string"858  );859}860861export type TryDecryptResult =862  | { status: "ok"; payload: DecryptedPayload }863  | { status: "wrong_key" }864  | { status: "corrupted"; reason: string };865866// Exported solely for `unlockFromCodex` below, which needs to verify a867// supplied passphrase against a slotA blob *without* committing anything to868// storage. Keep this internal otherwise — callers crossing the messages.ts869// boundary should always go through `unlock` / `verifyMainPassword` so the870// constant-time invariants in Projects.md §3.4 are not bypassed.871export async function tryDecryptSlot(872  vault: StoredVault,873  key: Uint8Array,874  aadTag?: string,875): Promise<DecryptedPayload | null> {876  const res = await tryDecryptSlotResult(vault, key, aadTag);877  return res.status === "ok" ? res.payload : null;878}879880export async function tryDecryptSlotResult(881  vault: StoredVault,882  key: Uint8Array,883  aadTag?: string,884): Promise<TryDecryptResult> {885  if (!hasValidVaultSchema(vault)) {886    return { status: "corrupted", reason: "invalid_slot_schema" };887  }888  let plain: string;889  try {890    plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);891  } catch {892    return { status: "wrong_key" };893  }894  try {895    const parsed = JSON.parse(plain) as unknown;896    if (typeof parsed !== "object" || parsed === null) {897      return { status: "corrupted", reason: "invalid_payload_shape" };898    }899    if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {900      return { status: "corrupted", reason: "invalid_payload_shape" };901    }902    return { status: "ok", payload: decodePayload(plain) };903  } catch {904    return { status: "corrupted", reason: "invalid_payload_json" };905  }906}907908// ---------------------------------------------------------------------------909// Core operations910// ---------------------------------------------------------------------------911912function buildDomainIndexSync(all: VaultEntry[]): void {913  domainIndex = new Map();914915  for (const entry of all) {916    if (entry.deletedAt) continue;917    if (entry.type === "note" || entry.type === "card") continue;918919    // An entry can match multiple sites via `additionalUrls`. Index each920    // hostname so `queryDomain` returns the entry regardless of which alias921    // the user is currently visiting. Dedupe per-entry so a single entry922    // never appears twice in one bucket.923    const domains = new Set<string>();924    const primary = extractDomain(entry.url ?? "");925    if (primary) domains.add(primary);926    for (const extra of entry.additionalUrls ?? []) {927      const d = extractDomain(extra);928      if (d) domains.add(d);929    }930    if (domains.size === 0) continue;931932    for (const domain of domains) {933      const bucket = domainIndex.get(domain) ?? [];934      bucket.push(entry);935      domainIndex.set(domain, bucket);936    }937  }938}939940export async function createVault(password: string): Promise<void> {941  await ensureMigrated();942943  const salt = generateSalt();944  derivedKey = await deriveKey(password, salt);945  entries = [];946  vaultMode = "real";947  duressConfigured = false;948  buildDomainIndexSync(entries);949950  // Generate and wrap the root key for recovery word escrow.951  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =952    await generateAndWrapRootKey();953  rootKey = unhex(rawRootKey);954955  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);956  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");957958  // Second wrapping of rootKey under derivedKey so future unlocks can rehydrate959  // it without recovery words (H2/COR-006).960  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);961962  const slotA: StoredVault = {963    version: 1,964    salt: hex(salt),965    nonce,966    ciphertext,967    tag,968    recovery_salt: recoverySalt,969    recovery_wrapped_root_key: wrappedRootKey,970    recovery_nonce: wrappedNonce,971    recovery_tag: wrappedTag,972    ...pwRoot,973  };974  await writeSlot(SLOT_A, slotA);975976  // Matching-size noise blob for slot B, so a fresh install shows two977  // similarly-shaped records regardless of whether duress is ever set up.978  await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));979  await stampLocalVaultMutation();980981  touchAutoLock();982}983984export async function hasVault(): Promise<boolean> {985  await ensureMigrated();986  return (await loadSlot(SLOT_A)) !== null;987}988989/**990 * Returns whether the real vault has recorded that a duress passphrase is991 * configured. Reliable only after a real-mode unlock — before unlock or in992 * decoy mode, returns false because we cannot read slot A's plaintext.993 */994export async function isDuressEnabled(): Promise<boolean> {995  return vaultMode === "real" && duressConfigured;996}997998export async function setupDuress(duressPassword: string): Promise<void> {999  if (!derivedKey || vaultMode !== "real") {1000    throw new Error("vault must be unlocked in real mode");1001  }1002  await ensureMigrated();10031004  // Encrypt the decoy payload (empty entries) under the duress key. Pad to1005  // at least the current slot A ciphertext size so the two slots look the1006  // same at rest at setup time.1007  const slotA = await loadSlot(SLOT_A);1008  if (!slotA) throw new Error("missing slot A");10091010  const decoySalt = generateSalt();1011  const decoyKey = await deriveKey(duressPassword, decoySalt);1012  try {1013    // Pad the decoy to the fixed duress ceiling. Slot A is re-encrypted to the1014    // same ceiling by the persistSlotA() call below (duressConfigured is now1015    // true), so both slots are exactly DURESS_SLOT_SIZE+tag at rest and their1016    // lengths cannot reveal that duress is configured (audit MEDIUM).1017    const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);1018    const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");1019    await writeSlot(SLOT_B, {1020      version: 1,1021      salt: hex(decoySalt),1022      nonce,1023      ciphertext,1024      tag,1025    });1026  } finally {1027    zeroKey(decoyKey);1028  }10291030  // Re-encrypt slot A with the duressConfigured flag set to true. No external1031  // flag is written — the bit lives inside the encrypted envelope.1032  duressConfigured = true;1033  await persistSlotA();1034}10351036export async function disableDuress(): Promise<void> {1037  if (!derivedKey || vaultMode !== "real") {1038    throw new Error("vault must be unlocked in real mode");1039  }1040  await ensureMigrated();10411042  // Overwrite slot B with fresh noise that matches slot A's size. The slot1043  // remains occupied so its mere existence does not signal that duress was1044  // ever configured.1045  const slotA = await loadSlot(SLOT_A);1046  if (slotA) {1047    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));1048  }10491050  duressConfigured = false;1051  await persistSlotA();1052}10531054// L14/COR-015: this function intentionally checks slot A (real vault) only.1055// A duress-mode user attempting changePassword is rejected earlier by the1056// vaultMode === 'decoy' check at changePassword. The real-vs-decoy1057// distinction here is by design — duress users cannot rotate the real1058// password by guessing it, and the asymmetry in error timing is acceptable1059// because duress mode is opt-in and the user knows their own decoy key.1060export async function verifyMainPassword(password: string): Promise<boolean> {1061  await ensureMigrated();1062  const slotA = await loadSlot(SLOT_A);1063  if (!slotA) return false;1064  const key = await deriveKey(password, unhex(slotA.salt));1065  try {1066    return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;1067  } finally {1068    zeroKey(key);1069  }1070}10711072export async function unlock(password: string): Promise<boolean> {1073  // LV-1: the normal path NFC-normalizes inside deriveKey. If that fails and1074  // the supplied password is not already in NFC form, the vault may have been1075  // sealed (pre-LV-1) with the raw, un-normalized bytes — retry with those.1076  if (await attemptUnlockWithDerive(password, deriveKey)) return true;10771078  const nfc = password.normalize("NFC");1079  if (password === nfc) return false; // ASCII/NFC password — no legacy form to try10801081  if (await attemptUnlockWithDerive(password, deriveKeyRaw)) {1082    // Heal: re-seal the real slot under the NFC-normalized key so every1083    // future unlock takes the normal path. Only the real vault is re-sealed;1084    // a non-NFC duress password keeps working through this fallback.1085    if (vaultMode === "real") {1086      try {1087        const newSalt = generateSalt();1088        const newKey = await deriveKey(password, newSalt);1089        await changePasswordWithNewKey(newSalt, newKey);1090      } catch (healErr) {1091        console.warn("[Peach] LV-1 NFC heal failed:", healErr);1092      }1093    }1094    return true;1095  }1096  return false;1097}10981099async function attemptUnlockWithDerive(1100  password: string,1101  derive: typeof deriveKey,1102): Promise<boolean> {1103  await ensureMigrated();11041105  // Load both slots in parallel. Both always exist post-migration; the1106  // parallel load and the parallel derivation below keep wall-clock time1107  // constant regardless of which slot's passphrase (real or decoy) the1108  // caller supplied, so a timing side channel cannot distinguish the1109  // duress path from the real-unlock path (DUR-002).1110  const [slotA, slotB] = await Promise.all([1111    loadSlot(SLOT_A),1112    loadSlot(SLOT_B),1113  ]);11141115  // Derive both keys in parallel, unconditionally.1116  const [keyA, keyB] = await Promise.all([1117    slotA ? derive(password, unhex(slotA.salt)) : Promise.resolve(null),1118    slotB ? derive(password, unhex(slotB.salt)) : Promise.resolve(null),1119  ]);11201121  // Attempt both decrypts in parallel. The Result variant lets us distinguish1122  // 'wrong_key' from 'corrupted' so callers can offer a history-restore path1123  // when a slot's schema is invalid even though AES-GCM authenticated (M7).1124  const [resultA, resultB] = await Promise.all([1125    keyA && slotA1126      ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")1127      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1128    keyB && slotB1129      ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")1130      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1131  ]);1132  const payloadA = resultA.status === "ok" ? resultA.payload : null;1133  const payloadB = resultB.status === "ok" ? resultB.payload : null;11341135  if (payloadA && keyA) {1136    derivedKey = keyA;1137    void saveSessionKey(keyA, "real");1138    vaultMode = "real";1139    entries = payloadA.entries;1140    duressConfigured = payloadA.duressConfigured;1141    buildDomainIndexSync(entries);1142    await loadSettings();1143    touchAutoLock();1144    if (keyB) zeroKey(keyB);11451146    // slotA is non-null when payloadA is truthy (keyA was derived from slotA).1147    if (slotA) {1148      const needsRecoverySetup =1149        !slotA.recovery_salt || !slotA.recovery_wrapped_root_key;1150      if (!needsRecoverySetup) {1151        rootKey = await deriveRootKeyFromDerivedKey(keyA, slotA);1152      }1153      // Pre-v2.12 vault, or a vault whose pw_root_* fields haven't been written1154      // yet: generate the recovery escrow and seed pw_root_* so subsequent1155      // unlocks can rehydrate rootKey without the user's recovery words.1156      // Best-effort — a failure here must not block unlock.1157      if (needsRecoverySetup || !rootKey) {1158        try {1159          await migrateToRecovery();1160          if (needsRecoverySetup) {1161            // String "1" matches the popup's existing peach_recovery_pending1162            // check; surfaced so the user re-confirms recovery words after a1163            // legacy-vault unlock (H2/COR-006).1164            await chrome.storage.local.set({ peach_recovery_pending: '1' });1165          }1166        } catch (migrationErr) {1167          console.warn('[Peach] recovery migration failed:', migrationErr);1168        }1169      }1170    }11711172    // If the payload had a pre-v2.11.0 shape (legacy passkey type, flat1173    // passkey fields, or pre-A-2 created/updated keys), rewrite it now so1174    // the next save uses the new format and migration doesn't re-run forever.1175    if (payloadA.migratedFromLegacy) {1176      await persistSlotA();1177    }1178    return true;1179  }11801181  if (payloadB && keyB) {1182    derivedKey = keyB;1183    void saveSessionKey(keyB, "decoy");1184    vaultMode = "decoy";1185    entries = payloadB.entries;1186    duressConfigured = false;1187    buildDomainIndexSync(entries);1188    await loadSettings();1189    touchAutoLock();1190    if (keyA) zeroKey(keyA);1191    return true;1192  }11931194  if (keyA) zeroKey(keyA);1195  if (keyB) zeroKey(keyB);1196  // Surface corruption (good AES tag, broken schema) distinctly from1197  // wrong-password so the popup can offer history-restore (M7/COR-007).1198  if (resultA.status === "corrupted") {1199    lastUnlockFailureReason = resultA.reason;1200  } else if (resultB.status === "corrupted") {1201    lastUnlockFailureReason = resultB.reason;1202  }1203  return false;1204}12051206// ---------------------------------------------------------------------------1207// MV3 service worker session key — survives SW restarts within a browser session1208// ---------------------------------------------------------------------------12091210// chrome.storage.session is cleared on browser close; survives SW restart.1211// Firefox does not implement it (persistent background script, no restart risk).1212const SESSION_KEY_STORAGE = "peach_session_dk";12131214async function saveSessionKey(key: Uint8Array, mode: "real" | "decoy"): Promise<void> {1215  if (!chrome.storage.session) return;1216  await chrome.storage.session.set({ [SESSION_KEY_STORAGE]: { keyHex: hex(key), mode } });1217}12181219async function clearSessionKey(): Promise<void> {1220  if (!chrome.storage.session) return;1221  await chrome.storage.session.remove(SESSION_KEY_STORAGE);1222}12231224/**1225 * On SW restart, re-derive all in-memory vault state from the session key1226 * stored in chrome.storage.session (set at unlock time, cleared on lock).1227 * Returns true if the vault was restored, false if no session key was found.1228 * No-ops if the vault is already unlocked.1229 */1230export async function restoreFromSession(): Promise<boolean> {1231  if (derivedKey !== null) return true;1232  if (!chrome.storage.session) return false;1233  const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);1234  const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;1235  if (!entry?.keyHex) return false;12361237  const key = unhex(entry.keyHex);1238  const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;1239  const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";1240  const slot = await loadSlot(slotKey);1241  if (!slot) { await clearSessionKey(); return false; }12421243  const result = await tryDecryptSlotResult(slot, key, aadTag);1244  if (result.status !== "ok") { await clearSessionKey(); return false; }12451246  derivedKey = key;1247  vaultMode = entry.mode;1248  entries = result.payload.entries;1249  duressConfigured = entry.mode === "real" ? result.payload.duressConfigured : false;1250  buildDomainIndexSync(entries);1251  await loadSettings();1252  touchAutoLock();12531254  if (entry.mode === "real" && slot.recovery_salt && slot.recovery_wrapped_root_key) {1255    try { rootKey = await deriveRootKeyFromDerivedKey(key, slot); } catch { /* non-fatal */ }1256  }12571258  return true;1259}12601261export function lock(): void {1262  void clearSessionKey();1263  if (derivedKey) {1264    zeroKey(derivedKey);1265    derivedKey = null;1266  }1267  if (rootKey) {1268    rootKey.fill(0);1269    rootKey = null;1270  }12711272  entries = [];1273  domainIndex = new Map();1274  vaultMode = "real";1275  duressConfigured = false;1276  clearAutoLock();1277}12781279export function isUnlocked(): boolean {1280  return derivedKey !== null;1281}12821283// Opens the vault using a pre-derived AES-256 key (skipping Argon2id).1284// Used by Android biometric unlock — the key was derived on the native side.1285export async function unlockWithKey(1286  masterKeyHex: string,1287): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {1288  try {1289    const masterKeyBytes = unhex(masterKeyHex);1290    const stored = await loadSlot(SLOT_A);1291    if (!stored) return { ok: false, error: "invalid_key" };1292    const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");1293    if (!payload) return { ok: false, error: "invalid_key" };12941295    derivedKey = masterKeyBytes;1296    vaultMode = "real";1297    entries = payload.entries;1298    duressConfigured = payload.duressConfigured;1299    buildDomainIndexSync(entries);1300    await loadSettings();1301    touchAutoLock();1302    return { ok: true, entries };1303  } catch {1304    return { ok: false, error: "invalid_key" };1305  }1306}13071308/**1309 * Restore the vault from a parsed Peach Codex payload.1310 *1311 * The supplied passphrase is verified against the Codex's slotA *before* any1312 * storage mutation — wrong passphrases return without touching disk. On1313 * success, the current vault state is snapshotted (reason: "restore") so the1314 * user can revert via Settings -> Vault History, then slotA/slotB are written1315 * and `peach_last_modified_at` is set to the Codex's recorded timestamp. A1316 * regular `unlock()` follows so the rest of the SW sees the standard1317 * post-unlock state.1318 *1319 * Intentionally non-Pro-gated — see peach_codex_v2.md "Pro gating". A Codex1320 * printed by a Pro user must always be restorable, even on a free device.1321 *1322 * Timing is not held constant here (in contrast to `unlock`): the Codex flow1323 * is an explicit user action with a known passphrase, not a passive lock1324 * screen, so the duress-vs-real timing side channel does not apply.1325 */1326export async function unlockFromCodex(params: {1327  slotA: string; // JSON string of StoredVault for slot A1328  slotB: string | null; // JSON string of StoredVault for slot B, or null1329  timestamp: number;1330  masterPassphrase: string;1331}): Promise<1332  | { ok: true; entryCount: number }1333  | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" }1334> {1335  let parsedSlotA: StoredVault;1336  let parsedSlotB: StoredVault | null = null;1337  try {1338    const rawA = JSON.parse(params.slotA) as unknown;1339    if (!hasValidVaultSchema(rawA)) {1340      return { ok: false, reason: "invalid_slot_format" };1341    }1342    parsedSlotA = rawA;1343    if (params.slotB !== null) {1344      const rawB = JSON.parse(params.slotB) as unknown;1345      if (!hasValidVaultSchema(rawB)) {1346        return { ok: false, reason: "invalid_slot_format" };1347      }1348      parsedSlotB = rawB;1349    }1350  } catch {1351    return { ok: false, reason: "invalid_slot_format" };1352  }13531354  // Verify the passphrase against the supplied slotA WITHOUT writing anything.1355  // If this fails the on-disk vault is left completely untouched.1356  const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));1357  const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");1358  if (!trialPayload) {1359    zeroKey(trialKey);1360    return { ok: false, reason: "wrong_passphrase" };1361  }1362  // Drop the trial key; `unlock()` below derives its own copy. Holding two1363  // copies of the master key in memory at once would be a needless surface.1364  zeroKey(trialKey);13651366  // Snapshot the about-to-be-overwritten on-disk state so the user can revert1367  // a mistaken Codex restore via the Vault History UI. Non-fatal if it fails.1368  await takeVaultSnapshot("restore");13691370  await writeSlot(SLOT_A, parsedSlotA);1371  if (parsedSlotB) {1372    await writeSlot(SLOT_B, parsedSlotB);1373  } else {1374    // Slot B must always exist with ciphertext length matching slot A1375    // (Projects.md §3.2). Codex prints may omit slot B (duress wasn't1376    // configured); regenerate noise to satisfy the invariant.1377    await writeSlot(1378      SLOT_B,1379      generateNoiseBlob(parsedSlotA.ciphertext.length / 2),1380    );1381  }1382  await chrome.storage.local.set({1383    peach_last_modified_at: String(params.timestamp),1384  });13851386  // Standard unlock path so domain index, settings, auto-lock, and1387  // recovery-key state all populate exactly as a normal unlock would.1388  const ok = await unlock(params.masterPassphrase);1389  if (!ok) {1390    // Should be unreachable — we just verified the passphrase against the1391    // same slotA we wrote. Treat as wrong_passphrase to keep the contract1392    // simple if some race or storage anomaly intrudes.1393    return { ok: false, reason: "wrong_passphrase" };1394  }1395  return { ok: true, entryCount: getEntries().length };1396}13971398// Returns the current in-memory derived key as a hex string.1399// Used by the biometric enable flow in Settings to store the key in Android Keystore.1400export function getDerivedKeyHex(): string {1401  if (!derivedKey) throw new Error("vault_not_unlocked");1402  return hex(derivedKey);1403}14041405/**1406 * Returns the vault's stable root key as hex, or null when locked / not yet1407 * populated. The root key is random per-vault, generated at creation, escrowed1408 * under the recovery words, and re-wrapped (not regenerated) on every password1409 * change — so it is INVARIANT across password rotation, unlike getDerivedKeyHex.1410 *1411 * This is the correct input for sync identity derivation (vault_id, the Noise1412 * XX static key, the Ed25519 manifest signing key, and per-entry envelope1413 * keys): paired devices keep the same identity and can still decrypt each1414 * other's entries after either side rotates its master password (SEV-2-B).1415 *1416 * Returns null rather than throwing so sync callers degrade to VAULT_LOCKED1417 * instead of crashing; rootKey is populated on every real-mode unlock via1418 * deriveRootKeyFromDerivedKey / migrateToRecovery.1419 */1420export function getRootKeyHex(): string | null {1421  return rootKey ? hex(rootKey) : null;1422}14231424export function getEntries(): VaultEntry[] {1425  if (!derivedKey) throw new Error("vault_locked");1426  return entries.filter((entry) => !entry.deletedAt);1427}14281429const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;14301431export function getIdentities(): SavedIdentity[] {1432  if (!derivedKey) throw new Error("vault_locked");1433  const active = entries.filter((e) => !e.deletedAt && e.type === "login");14341435  const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();1436  const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();14371438  for (const entry of active) {1439    const domain = extractDomain(entry.url ?? "") ?? "";1440    const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;14411442    function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {1443      const existing = map.get(v);1444      if (!existing || modifiedAt > existing.lastUsed) {1445        map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });1446      } else {1447        map.set(v, { ...existing, count: existing.count + 1 });1448      }1449    }14501451    const uVal = entry.username?.trim();1452    if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);14531454    // Also count the dedicated email field — entries created via the inline1455    // popup new-entry form store email here rather than in username.1456    const eVal = entry.email?.trim();1457    if (eVal) tally(emailMap, eVal);1458  }14591460  const toIdentity = (type: "email" | "username") =>1461    ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({1462      value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,1463    });14641465  return [1466    ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),1467    ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),1468  ];1469}14701471export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {1472  if (!derivedKey) throw new Error("vault_locked");14731474  const now = Date.now();1475  const added: VaultEntry[] = [];1476  for (const draft of drafts) {1477    try {1478      const sanitized = sanitizeEntryDraft(draft);1479      const nextEntry: VaultEntry = {1480        ...sanitized,1481        id: crypto.randomUUID(),1482        createdAt: now,1483        modifiedAt: monotonicEntryTimestamp(),1484      };1485      entries.push(nextEntry);1486      added.push(nextEntry);1487    } catch {1488      // Skip invalid drafts silently — caller can see diff between input and output length1489    }1490  }14911492  if (added.length > 0) {1493    await persistEntries();1494  }14951496  return added;1497}14981499/**1500 * Restore a set of entries in full fidelity — preserves id, createdAt,1501 * modifiedAt, and every other field unlike `batchAddEntries` which1502 * assigns fresh identity. Used by restore paths where the backup is the1503 * authoritative source of truth. `mode` controls how entries already in1504 * the vault are treated.1505 */1506export async function restoreEntries(1507  incoming: VaultEntry[],1508  mode: "replace" | "merge"1509): Promise<{ added: number; updated: number; skipped: number }> {1510  if (!derivedKey) throw new Error("vault_locked");15111512  // A replace with zero incoming entries is almost certainly a caller bug1513  // (e.g. an import that silently dropped everything). Refuse rather than1514  // wipe the vault.1515  if (mode === "replace" && incoming.length === 0) {1516    throw new Error("refuse to replace with empty entry set");1517  }15181519  let added = 0;1520  let updated = 0;1521  let skipped = 0;15221523  if (mode === "replace") {1524    entries = [];1525    for (const entry of incoming) {1526      const normalized = sanitizeRestoredEntry(entry);1527      if (!normalized) {1528        skipped += 1;1529        continue;1530      }1531      entries.push(normalized);1532      added += 1;1533    }1534  } else {1535    const byId = new Map<string, VaultEntry>();1536    for (const e of entries) byId.set(e.id, e);15371538    for (const entry of incoming) {1539      const normalized = sanitizeRestoredEntry(entry);1540      if (!normalized) {1541        skipped += 1;1542        continue;1543      }1544      const existing = byId.get(normalized.id);1545      if (!existing) {1546        entries.push(normalized);1547        added += 1;1548      } else if (normalized.modifiedAt > existing.modifiedAt) {1549        const idx = entries.findIndex((e) => e.id === existing.id);1550        if (idx !== -1) {1551          entries[idx] = normalized;1552          updated += 1;1553        }1554      } else {1555        skipped += 1;1556      }1557    }1558  }15591560  await persistEntries("import");1561  return { added, updated, skipped };1562}15631564/**1565 * Validate + normalise a VaultEntry coming from a backup, import, or sync1566 * peer. MV-6: this is a strict field WHITELIST — `normalizeEntry` copies1567 * only known VaultEntry fields (unknown/attacker keys are dropped), and1568 * nested `passkey`/`canary` shapes are rebuilt field-by-field, never1569 * spread. Returns null for values the live vault shouldn't accept.1570 */1571function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {1572  if (!entry || typeof entry !== "object") return null;1573  const title = typeof entry.title === "string" ? entry.title.trim() : "";1574  if (!title) return null;1575  const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();1576  const now = Date.now();1577  const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;1578  const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;15791580  // normalizeEntry whitelists every known VaultEntry field and runs the1581  // same legacy-passkey migration as the on-disk read path — pre-v2.11.01582  // backups with flat passkey fields still import correctly because the1583  // legacy flat fields are themselves whitelisted VaultEntry members.1584  const normalized = normalizeEntry({1585    ...entry,1586    id,1587    title,1588    type: entry.type ?? "login",1589    createdAt,1590    modifiedAt,1591  });15921593  if (normalized.passkey) {1594    normalized.passkey = sanitizePasskey(normalized.passkey);1595  }1596  if (normalized.canary) {1597    normalized.canary = sanitizeCanary(normalized.canary);1598  }15991600  // Login entries from backup must carry a password (or be passkey-only,1601  // in which case the passkey sub-object replaces the password requirement).1602  if (1603    normalized.type === "login" &&1604    !normalized.passkey &&1605    typeof normalized.password !== "string"1606  ) {1607    return null;1608  }1609  if (entry.passkey && !normalized.passkey) {1610    // Entry claimed a passkey but the shape didn't validate — refuse the1611    // whole entry rather than silently importing a credential-less husk.1612    return null;1613  }16141615  return normalized;1616}16171618/**1619 * Rebuild a PasskeyData object from untrusted input, field by field.1620 * Returns undefined when required fields are missing/mistyped — a rogue1621 * passkey credential must not activate via import (MV-6 attack scenario).1622 */1623function sanitizePasskey(pk: unknown): PasskeyData | undefined {1624  if (!pk || typeof pk !== "object") return undefined;1625  const r = pk as Record<string, unknown>;1626  if (1627    typeof r.rpId !== "string" || !r.rpId ||1628    typeof r.credentialId !== "string" || !r.credentialId ||1629    typeof r.publicKeyCose !== "string" ||1630    typeof r.userHandle !== "string" ||1631    typeof r.userName !== "string"1632  ) {1633    return undefined;1634  }1635  return {1636    rpId: r.rpId,1637    rpName: typeof r.rpName === "string" ? r.rpName : r.rpId,1638    credentialId: r.credentialId,1639    publicKeyCose: r.publicKeyCose,1640    privateKeyJwk:1641      r.privateKeyJwk && typeof r.privateKeyJwk === "object"1642        ? (r.privateKeyJwk as JsonWebKey)1643        : undefined,1644    userHandle: r.userHandle,1645    userName: r.userName,1646    userDisplayName:1647      typeof r.userDisplayName === "string" ? r.userDisplayName : r.userName,1648    algorithm: r.algorithm === -8 ? -8 : -7,1649    signCount: typeof r.signCount === "number" ? r.signCount : 0,1650    aaguid: typeof r.aaguid === "string" ? r.aaguid : "",1651    backupEligible: r.backupEligible === true,1652    backupState: r.backupState === true,1653    lastUsedAt: typeof r.lastUsedAt === "number" ? r.lastUsedAt : undefined,1654    browser: r.browser === "chrome" || r.browser === "firefox" ? r.browser : undefined,1655    transports: Array.isArray(r.transports)1656      ? r.transports.filter((t): t is string => typeof t === "string")1657      : undefined,1658    createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),1659  };1660}16611662/**1663 * Rebuild a Canary object from untrusted input. The webhook must be a1664 * well-formed HTTPS URL — a poisoned canary.webhookUrl is a standing1665 * exfiltration endpoint that the canary subsystem will POST entry titles1666 * to (MV-6 attack scenario). Invalid → the canary is dropped, not the1667 * entry. FIRE_CANARY_PING re-validates with the full SSRF guard at fire1668 * time (isAllowedCanaryWebhookUrl), so this import-time check is the1669 * outer of two gates.1670 */1671function sanitizeCanary(c: unknown): Canary | undefined {1672  if (!c || typeof c !== "object") return undefined;1673  const r = c as Record<string, unknown>;1674  if (typeof r.webhookUrl !== "string") return undefined;1675  let url: URL;1676  try {1677    url = new URL(r.webhookUrl);1678  } catch {1679    return undefined;1680  }1681  if (url.protocol !== "https:") return undefined;1682  return {1683    webhookUrl: url.toString(),1684    label: typeof r.label === "string" ? r.label : undefined,1685    lastPinged: typeof r.lastPinged === "number" ? r.lastPinged : undefined,1686    pingCount: typeof r.pingCount === "number" ? r.pingCount : undefined,1687  };1688}16891690// Soft-deletes every non-deleted entry in one call. The literal string1691// argument is a tripwire against accidental calls — any caller that would1692// wipe the vault has to consciously type "REPLACE_ALL". Do not relax this1693// to a boolean.1694export async function clearVaultEntries(1695  confirmation: "REPLACE_ALL"1696): Promise<void> {1697  if (confirmation !== "REPLACE_ALL") {1698    throw new Error("clearVaultEntries requires explicit confirmation");1699  }1700  if (!derivedKey) throw new Error("vault_locked");1701  for (const entry of entries) {1702    if (!entry.deletedAt) {1703      const stamp = monotonicEntryTimestamp(entry.modifiedAt);1704      entry.deletedAt = stamp;1705      entry.modifiedAt = stamp;1706    }1707  }1708  await persistEntries();1709}17101711export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {1712  if (!derivedKey) throw new Error("vault_locked");17131714  const sanitized = sanitizeEntryDraft(entry);1715  const now = Date.now();1716  const stamp = monotonicEntryTimestamp();1717  const nextEntry: VaultEntry = {1718    ...sanitized,1719    id: crypto.randomUUID(),1720    createdAt: now,1721    modifiedAt: stamp,1722    // Stamp passwordChangedAt at creation so age tracking is accurate from1723    // day one. Non-login entries carry the same stamp harmlessly.1724    passwordChangedAt: sanitized.password ? stamp : undefined,1725  };17261727  // Clone-and-replace so a failed persist rolls back the in-memory state1728  // (COR-008). Without this, a quota-full or storage error leaves the1729  // module-level `entries` ahead of what's actually on disk.1730  const rollback = entries;1731  entries = [...entries, nextEntry];1732  try {1733    await persistEntries();1734  } catch (err) {1735    entries = rollback;1736    throw err;1737  }17381739  // Fire-and-forget breach check (only for login entries if breach monitoring is enabled or not set)1740  if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {1741    checkBreach(nextEntry.password).then(async (count) => {1742      if (count > 0) {1743        const idx = entries.findIndex((e) => e.id === nextEntry.id);1744        if (idx !== -1) {1745          entries[idx] = { ...entries[idx], breach: count, modifiedAt: monotonicEntryTimestamp(entries[idx].modifiedAt) };1746          await persistEntries();1747        }1748      }1749    });1750  }17511752  fireSyncTrigger("vault_change");17531754  return nextEntry;1755}17561757/**1758 * Run the passkey-merge pass on the live in-memory entries and persist if1759 * anything changed. Called immediately after any passkey registration so that1760 * a same-domain TOTP-only entry already in the vault gets consolidated right1761 * away instead of waiting until the next lock/unlock cycle.1762 */1763export async function consolidatePasskeyEntries(): Promise<void> {1764  if (!derivedKey) return;1765  const { merged } = mergePasskeyOnlyIntoLogins(entries);1766  if (merged) {1767    await persistEntries();1768  }1769}17701771export async function updateEntry(1772  id: string,1773  patch: Partial<VaultEntry>1774): Promise<void> {1775  if (!derivedKey) throw new Error("vault_locked");17761777  const idx = entries.findIndex((entry) => entry.id === id);1778  if (idx === -1 || entries[idx].deletedAt) {1779    throw new Error("entry_not_found");1780  }17811782  const current = entries[idx];1783  const sanitizedPatch = sanitizeEntryPatch(patch);1784  // Refresh passwordChangedAt only when the password value actually changes —1785  // a metadata-only update (title, tags, etc.) must not reset the age clock1786  // that drives the Pro health rotation recommendation.1787  const passwordChanged =1788    "password" in patch &&1789    typeof sanitizedPatch.password === "string" &&1790    sanitizedPatch.password !== current.password;1791  const stamp = monotonicEntryTimestamp(current.modifiedAt);1792  // When the password actually changes, push the outgoing one onto the history1793  // (newest first) so the user can reveal/copy/restore it later. We record the1794  // age it carried (passwordChangedAt, falling back to createdAt) rather than1795  // `now`, so the list reflects when each password was last in effect. Only1796  // capture a non-empty prior value — clearing a password leaves no secret to1797  // keep, and we skip an immediate exact duplicate (e.g. restore-then-restore)1798  // to avoid noise.1799  const priorPassword = current.password;1800  const shouldCapture =1801    passwordChanged &&1802    typeof priorPassword === "string" &&1803    priorPassword.length > 0 &&1804    current.passwordHistory?.[0]?.password !== priorPassword;1805  const nextHistory = shouldCapture1806    ? [1807        { password: priorPassword!, changedAt: current.passwordChangedAt ?? current.createdAt },1808        ...(current.passwordHistory ?? []),1809      ].slice(0, PASSWORD_HISTORY_MAX)1810    : current.passwordHistory;1811  entries[idx] = {1812    ...current,1813    ...sanitizedPatch,1814    modifiedAt: stamp,1815    ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),1816  };1817181818191820  // Card entries must retain their card number1821  if (entries[idx].type === "card" && !entries[idx].cardNumber) {1822    entries[idx] = current;1823    throw new Error("card number is required for card entries");1824  }18251826  // Roll the in-memory entry back to its pre-edit state if the disk write1827  // fails (e.g. storage quota). Without this the module-level `entries` array1828  // would hold an edit that never landed on disk, diverging from the vault1829  // until the next unlock silently reverts it (SEV-3-A). Mirrors addEntry.1830  try {1831    await persistEntries();1832  } catch (err) {1833    entries[idx] = current;1834    throw err;1835  }18361837  // Breach check when password changes: clear immediately so old breach doesn't linger,1838  // then async-check the new password and only re-set if it's also found.1839  if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {1840    entries[idx] = { ...entries[idx], breach: undefined };1841    await persistEntries();1842    const password = entries[idx].password;1843    if (password) {1844      checkBreach(password).then(async (count) => {1845        const i = entries.findIndex((e) => e.id === id);1846        if (i !== -1 && count > 0) {1847          entries[i] = { ...entries[i], breach: count, modifiedAt: monotonicEntryTimestamp(entries[i].modifiedAt) };1848          await persistEntries();1849        }1850      });1851    }1852  }18531854  fireSyncTrigger("vault_change");1855}18561857export async function deleteEntry(id: string): Promise<void> {1858  if (!derivedKey) throw new Error("vault_locked");18591860  const entry = entries.find((item) => item.id === id);1861  if (!entry || entry.deletedAt) {1862    throw new Error("entry_not_found");1863  }18641865  // Tombstone timestamp must be strictly greater than the entry's last1866  // modification so the deletion wins LWW against any in-flight edit, even1867  // under clock skew (SEV-2-E).1868  const previousModifiedAt = entry.modifiedAt;1869  const stamp = monotonicEntryTimestamp(entry.modifiedAt);1870  entry.deletedAt = stamp;1871  entry.modifiedAt = stamp;1872  // Roll the tombstone back if the disk write fails, so a quota error doesn't1873  // leave the entry deleted in memory but alive on disk (SEV-3-A).1874  try {1875    await persistEntries();1876  } catch (err) {1877    delete entry.deletedAt;1878    entry.modifiedAt = previousModifiedAt;1879    throw err;1880  }1881  fireSyncTrigger("vault_change");1882}18831884export function getDeletedEntries(): VaultEntry[] {1885  if (!derivedKey) return [];1886  return entries.filter((e) => !!e.deletedAt);1887}18881889/**1890 * Returns the vault's monotonic version — the `peach_last_modified_at` value1891 * stamped on every user-initiated write. Remote (sync) writes do NOT advance1892 * this version so a sync round never cascades into a second outbound sync.1893 */1894export async function getVaultVersion(): Promise<number> {1895  try {1896    const raw = await chrome.storage.local.get("peach_last_modified_at");1897    const v = (raw as Record<string, unknown>).peach_last_modified_at;1898    if (typeof v === "number") return v;1899    if (typeof v === "string" && v !== "") {1900      const n = Number.parseInt(v, 10);1901      return Number.isFinite(n) ? n : 0;1902    }1903    return 0;1904  } catch {1905    return 0;1906  }1907}19081909/**1910 * Internal write variants — bypass `fireSyncTrigger` so the sync layer can1911 * apply entries without cascading into another outbound sync round.1912 *1913 * INVARIANT: callers must not pass entries whose IDs collide with existing1914 * active (non-deleted) entries unless the intent is an explicit overwrite.1915 * These functions do not validate field-level constraints (password required,1916 * card number required, etc.) — they are trust-the-caller paths for sync and1917 * test harness use only.1918 */1919export async function addEntryDirect(entry: VaultEntry): Promise<void> {1920  if (!derivedKey) throw new Error("vault_locked");1921  entries = [...entries, entry];1922  await persistEntries("sync_received");1923}19241925export async function updateEntryDirect(patch: VaultEntry): Promise<void> {1926  if (!derivedKey) throw new Error("vault_locked");1927  const idx = entries.findIndex((e) => e.id === patch.id);1928  if (idx === -1) throw new Error("entry_not_found");1929  entries[idx] = { ...entries[idx], ...patch };1930  await persistEntries("sync_received");1931}19321933export async function deleteEntryDirect(id: string, deletedAt: number): Promise<void> {1934  if (!derivedKey) throw new Error("vault_locked");1935  const idx = entries.findIndex((e) => e.id === id);1936  if (idx === -1) throw new Error("entry_not_found");1937  entries[idx] = { ...entries[idx], deletedAt, modifiedAt: deletedAt };1938  await persistEntries("sync_received");1939}19401941/**1942 * Apply a batch of remote entries + tombstones from a chirp-sync peer.1943 * Last-write-wins by `modifiedAt`; a tombstone supersedes a live entry when1944 * `deletedAt > modifiedAt` on the local side. Mutates `entries` directly and1945 * persists with reason `sync_received` — does NOT fire the sync dispatcher, so1946 * applying a sync round cannot cascade into another outbound sync.1947 *1948 * `applied` counts entries that actually changed local state (new add,1949 * overwrite-by-newer, or new tombstone). `received` is the raw payload size1950 * the caller can surface in the sync result UI.1951 */1952export async function applyMergedRemoteEntries(1953  remoteEntries: VaultEntry[],1954  remoteTombstones: Record<string, number>,1955  context: { deviceName?: string } = {},1956): Promise<{ received: number; applied: number; conflicts: number }> {1957  // DESIGN: last-write-wins is applied PER-ENTRY, not per-field. If two devices1958  // concurrently edit different fields of the same entry, the one with the1959  // newer modifiedAt wins the whole entry and the other device's field edits1960  // are dropped silently. This is the deliberate trade-off for a simple,1961  // conflict-free merge — per-field CRDT merge is out of scope. Guidance for1962  // users: edit a given entry on one device at a time.1963  if (!derivedKey) throw new Error("vault_locked");19641965  const received = remoteEntries.length + Object.keys(remoteTombstones).length;1966  let applied = 0;1967  let conflicts = 0;19681969  const byId = new Map<string, VaultEntry>();1970  for (const e of entries) byId.set(e.id, e);19711972  const alerts: SyncAlert[] = [];1973  const deviceName = context.deviceName ?? "paired device";1974  const mergeNow = Date.now();19751976  for (const remote of remoteEntries) {1977    const sanitized = sanitizeRestoredEntry(remote);1978    if (!sanitized) continue;1979    // HV-1a: a far-future remote modifiedAt must not permanently pin a1980    // malicious value against honest local edits. Clamp BEFORE any1981    // comparison against local timestamps.1982    sanitized.modifiedAt = clampSyncTimestamp(sanitized.modifiedAt, mergeNow);1983    if (typeof sanitized.deletedAt === "number") {1984      sanitized.deletedAt = clampSyncTimestamp(sanitized.deletedAt, mergeNow);1985    }1986    const tombstoneTs = remoteTombstones[sanitized.id];1987    if (tombstoneTs !== undefined && clampSyncTimestamp(tombstoneTs, mergeNow) >= sanitized.modifiedAt) {1988      continue;1989    }1990    const local = byId.get(sanitized.id);1991    if (!local) {1992      entries.push(sanitized);1993      byId.set(sanitized.id, sanitized);1994      applied += 1;1995    } else if (sanitized.modifiedAt > local.modifiedAt) {1996      const idx = entries.findIndex((e) => e.id === local.id);1997      if (idx !== -1) {1998        // HV-1b: surface remote password REPLACEMENTS (existing id, password1999        // differs) so a compromised peer can't silently rewrite credentials.2000        if (2001          !local.deletedAt &&2002          typeof sanitized.password === "string" &&2003          typeof local.password === "string" &&2004          sanitized.password !== local.password2005        ) {2006          alerts.push({2007            type: "REMOTE_PASSWORD_CHANGE",2008            entryId: sanitized.id,2009            entryTitle: sanitized.title,2010            deviceName,2011            timestamp: mergeNow,2012          });2013        }2014        entries[idx] = sanitized;2015        byId.set(sanitized.id, sanitized);2016        applied += 1;2017        if (!local.deletedAt) conflicts += 1;2018      }2019    }2020  }20212022  for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2023    if (typeof rawDeletedAt !== "number" || !Number.isFinite(rawDeletedAt)) continue;2024    // HV-1a/1c: clamp the tombstone timestamp before every comparison.2025    const deletedAt = clampSyncTimestamp(rawDeletedAt, mergeNow);2026    const local = byId.get(id);2027    if (!local) continue;2028    if (local.deletedAt && local.deletedAt >= deletedAt) continue;2029    if (deletedAt < local.modifiedAt) continue;2030    const idx = entries.findIndex((e) => e.id === id);2031    if (idx !== -1) {2032      // HV-1b: surface remote deletes of live local entries.2033      if (!local.deletedAt) {2034        alerts.push({2035          type: "REMOTE_DELETE",2036          entryId: id,2037          entryTitle: local.title,2038          deviceName,2039          timestamp: mergeNow,2040        });2041      }2042      entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };2043      applied += 1;2044    }2045  }20462047  if (applied > 0) {2048    await persistEntries("sync_received");2049    buildDomainIndexSync(entries);2050  }2051  // Queued after the merge committed — an alert must describe a mutation2052  // that actually landed. recordSyncAlerts never throws.2053  await recordSyncAlerts(alerts);2054  return { received, applied, conflicts };2055}20562057export async function restoreEntry(id: string): Promise<void> {2058  if (!derivedKey) throw new Error("vault_locked");2059  const entry = entries.find((e) => e.id === id && e.deletedAt);2060  if (!entry) throw new Error("deleted entry not found");2061  delete entry.deletedAt;2062  entry.modifiedAt = monotonicEntryTimestamp(entry.modifiedAt);2063  await persistEntries();2064  buildDomainIndexSync(entries);2065}20662067export async function purgeEntry(id: string): Promise<void> {2068  if (!derivedKey) throw new Error("vault_locked");2069  const idx = entries.findIndex((e) => e.id === id && e.deletedAt);2070  if (idx === -1) throw new Error("deleted entry not found");2071  entries.splice(idx, 1);2072  await persistEntries();2073}20742075/** Permanently delete entries whose deletedAt is older than retentionMs. 0 = keep forever. */2076export async function purgeExpiredTrash(retentionMs: number): Promise<number> {2077  if (!derivedKey || retentionMs === 0) return 0;2078  const cutoff = Date.now() - retentionMs;2079  const before = entries.length;2080  entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));2081  const purged = before - entries.length;2082  if (purged > 0) await persistEntries();2083  return purged;2084}20852086export function queryDomain(domain: string): VaultEntry[] {2087  return domainIndex.get(domain) ?? [];2088}20892090export function getEntryById(id: string): VaultEntry | undefined {2091  return entries.find((entry) => entry.id === id && !entry.deletedAt);2092}20932094async function persistSlotA(2095  reason: VaultSnapshot["reason"] = "local_save",2096): Promise<StoredVault> {2097  if (!derivedKey) throw new Error("vault_locked");20982099  const slotA = await loadSlot(SLOT_A);2100  if (!slotA) throw new Error("missing slot A");21012102  // Snapshot the about-to-be-overwritten state BEFORE we mutate disk. Failures2103  // are swallowed by takeVaultSnapshot — history must never block a save.2104  await takeVaultSnapshot(reason);21052106  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);2107  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");21082109  // Preserve existing recovery escrow fields.2110  const nextSlotA: StoredVault = {2111    ...slotA,2112    nonce,2113    ciphertext,2114    tag,2115    // recovery_salt and recovery_wrapped_root_key are already set from loadSlot2116  };2117  await writeSlot(SLOT_A, nextSlotA);21182119  // Slot A (the real vault) is now committed. Wrap every later write so a2120  // mid-persist failure (e.g. a storage error after slot A landed) restores the2121  // prior slot A before rethrowing. Without this, a "failed" save that already2122  // wrote slot A leaves disk ahead of the in-memory rollback in addEntry/2123  // updateEntry/deleteEntry — the entry stays silently on disk and resurfaces2124  // as a duplicate on the next unlock (observed under storage-quota pressure).2125  try {2126    // When duress is not configured, keep slot B size-matched with slot A by2127    // regenerating its noise. When duress IS configured, leave slot B alone —2128    // we don't have the decoy key to re-encrypt it. This is a known trade-off.2129    if (!duressConfigured) {2130      await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));2131    }2132    // Only advance the vault version for locally-originated writes. Entries2133    // applied from a sync peer ("sync_received") must NOT bump the counter —2134    // otherwise applying a remote round makes us look newer than the peer and2135    // triggers a redundant outbound sync, defeating the no-op optimisation2136    // and risking a ping-pong between two devices (SEV-2-C).2137    if (reason !== "sync_received") {2138      await stampLocalVaultMutation();2139    }2140  } catch (err) {2141    // Best-effort restore — the prior slot A is smaller-or-equal, so this write2142    // fits even when the failure was a quota overflow.2143    await writeSlot(SLOT_A, slotA).catch(() => {});2144    throw err;2145  }21462147  return nextSlotA;2148}21492150async function persistSlotB(): Promise<void> {2151  if (!derivedKey) throw new Error("vault_locked");21522153  const slotB = await loadSlot(SLOT_B);2154  if (!slotB) throw new Error("missing slot B");21552156  // Decoy plaintext always reports duressConfigured=false — the decoy user2157  // sees a clean slate. persistSlotB only runs in decoy mode, which only2158  // exists once duress is configured, so pad to the fixed duress ceiling to2159  // keep slot B's length equal to slot A's (audit MEDIUM — deniability).2160  const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);2161  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");21622163  await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });2164  // Symmetric with persistSlotA: if the version stamp fails after the decoy2165  // slot committed, restore the prior slot B so a failed decoy-mode save can't2166  // leave disk ahead of the in-memory rollback.2167  try {2168    await stampLocalVaultMutation();2169  } catch (err) {2170    await writeSlot(SLOT_B, slotB).catch(() => {});2171    throw err;2172  }2173}21742175async function persistEntries(2176  reason: VaultSnapshot["reason"] = "local_save",2177): Promise<void> {2178  if (!derivedKey) throw new Error("vault_locked");21792180  if (vaultMode === "decoy") {2181    await persistSlotB();2182  } else {2183    await persistSlotA(reason);2184  }2185  buildDomainIndexSync(entries);2186}21872188function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {2189  if (!Array.isArray(values)) return undefined;2190  const seen = new Set<string>();2191  const cleaned: string[] = [];2192  for (const value of values) {2193    const trimmed = typeof value === "string" ? value.trim() : "";2194    if (!trimmed) continue;2195    const key = trimmed.toLowerCase();2196    if (seen.has(key)) continue;2197    seen.add(key);2198    cleaned.push(trimmed);2199  }2200  return cleaned.length > 0 ? cleaned : undefined;2201}22022203function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {2204  const title = entry.title.trim();2205  // Accept legacy `type:"passkey"` drafts but rewrite to "login" — the new2206  // model is "any entry, optionally with a passkey sub-object." Imports and2207  // any in-flight callers from before v2.11.0 keep working without throwing.2208  let type: VaultEntry["type"] = entry.type ?? "login";2209  if (type === "passkey") type = "login";22102211  if (!title) throw new Error("title is required");22122213  if (entry.passkey) {2214    const p = entry.passkey;2215    if (2216      !p.rpId ||2217      !p.credentialId ||2218      !p.publicKeyCose ||2219      !p.userHandle ||2220      !p.userName ||2221      (p.algorithm !== -7 && p.algorithm !== -8)2222    ) {2223      throw new Error("invalid passkey credential");2224    }2225  }2226  if (type === "card") {2227    if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {2228      throw new Error("cardholder name and card number are required");2229    }2230  }22312232  return {2233    type,2234    title,2235    username: type === "login" ? entry.username?.trim() ?? "" : undefined,2236    email: type === "login" ? entry.email?.trim() || undefined : undefined,2237    password: type === "login" ? entry.password : undefined,2238    url: type === "login" ? entry.url?.trim() ?? "" : undefined,2239    additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,2240    totp: type === "login" ? entry.totp?.trim() || undefined : undefined,2241    notes: entry.notes?.trim() || undefined,2242    breach: type === "login" ? entry.breach : undefined,2243    canary: type === "login" ? entry.canary : undefined,2244    tags: entry.tags,2245    passkey: entry.passkey,2246    cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,2247    cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,2248    expMonth: type === "card" ? entry.expMonth?.trim() : undefined,2249    expYear: type === "card" ? entry.expYear?.trim() : undefined,2250    cvc: type === "card" ? entry.cvc?.trim() : undefined,2251    cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,2252    network: type === "card" ? entry.network : undefined,2253    last4: type === "card" ? entry.last4?.trim() : undefined,2254  };2255}22562257function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {2258  const nextPatch: Partial<VaultEntry> = {};22592260  if ("type" in patch) {2261    nextPatch.type = patch.type;2262  }22632264  if ("title" in patch) {2265    const title = patch.title?.trim() ?? "";2266    if (!title) throw new Error("title is required");2267    nextPatch.title = title;2268  }22692270  if ("url" in patch) {2271    nextPatch.url = patch.url?.trim() ?? "";2272  }22732274  if ("additionalUrls" in patch) {2275    const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];2276    const seen = new Set<string>();2277    const cleaned: string[] = [];2278    for (const value of incoming) {2279      const trimmed = typeof value === "string" ? value.trim() : "";2280      if (!trimmed) continue;2281      const key = trimmed.toLowerCase();2282      if (seen.has(key)) continue;2283      seen.add(key);2284      cleaned.push(trimmed);2285    }2286    nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;2287  }22882289  if ("username" in patch) {2290    nextPatch.username = patch.username?.trim() ?? "";2291  }22922293  if ("email" in patch) {2294    nextPatch.email = patch.email?.trim() || undefined;2295  }22962297  if ("password" in patch) {2298    const password = patch.password ?? "";2299    // Allow clearing a password (e.g. on passkey-only entries)2300    nextPatch.password = password || undefined;2301  }23022303  if ("totp" in patch) {2304    nextPatch.totp = patch.totp?.trim() || undefined;2305  }23062307  if ("notes" in patch) {2308    nextPatch.notes = patch.notes?.trim() || undefined;2309  }23102311  if ("breach" in patch) {2312    nextPatch.breach = patch.breach;2313  }23142315  if ("canary" in patch) {2316    nextPatch.canary = patch.canary;2317  }23182319  if ("passkey" in patch) {2320    // Passkey sub-object replaces all the legacy flat passkey fields. A2321    // patch with `passkey: undefined` removes the credential from the entry2322    // (used by "remove passkey" without deleting the whole entry).2323    nextPatch.passkey = patch.passkey;2324  }23252326  if ("tags" in patch) {2327    nextPatch.tags = patch.tags;2328  }23292330  if ("cardholderName" in patch) {2331    nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;2332  }2333  if ("cardNumber" in patch) {2334    const n = patch.cardNumber ?? "";2335    nextPatch.cardNumber = n || undefined;2336  }2337  if ("expMonth" in patch) {2338    nextPatch.expMonth = patch.expMonth?.trim() || undefined;2339  }2340  if ("expYear" in patch) {2341    nextPatch.expYear = patch.expYear?.trim() || undefined;2342  }2343  if ("cvc" in patch) {2344    nextPatch.cvc = patch.cvc?.trim() || undefined;2345  }2346  if ("cardNickname" in patch) {2347    nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;2348  }2349  if ("network" in patch) {2350    nextPatch.network = patch.network;2351  }2352  if ("last4" in patch) {2353    nextPatch.last4 = patch.last4?.trim() || undefined;2354  }23552356  return nextPatch;2357}23582359function normalizeEntry(entry: VaultEntry | LegacyVaultEntry): VaultEntry {2360  const createdAt = "createdAt" in entry ? entry.createdAt : entry.created;2361  const modifiedAt =2362    "modifiedAt" in entry ? entry.modifiedAt : entry.updated;23632364  const base: VaultEntry = {2365    id: entry.id,2366    type: "type" in entry ? entry.type : "login",2367    title: entry.title,2368    username: entry.username,2369    email: "email" in entry ? entry.email : undefined,2370    password: entry.password,2371    url: entry.url,2372    additionalUrls:2373      "additionalUrls" in entry && Array.isArray(entry.additionalUrls)2374        ? entry.additionalUrls2375        : undefined,2376    totp: entry.totp,2377    notes: entry.notes,2378    breach: entry.breach,2379    // Preserve the password-age clock across lock/unlock. Without this the2380    // field is dropped on every decode and the advanced-health "aged password"2381    // signal silently resets to createdAt on each unlock (SEV-2-A).2382    passwordChangedAt:2383      "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,2384    // Preserve past-password history across lock/unlock. normalizeEntry is a2385    // field whitelist, so an unlisted field is silently dropped on every decode2386    // (same class as the passwordChangedAt SEV-2-A above).2387    passwordHistory:2388      "passwordHistory" in entry && Array.isArray(entry.passwordHistory)2389        ? entry.passwordHistory2390        : undefined,2391    canary: "canary" in entry ? entry.canary : undefined,2392    passkey: "passkey" in entry ? entry.passkey : undefined,2393    createdAt,2394    modifiedAt,2395    deletedAt: entry.deletedAt,2396    tags: "tags" in entry ? entry.tags : undefined,2397    cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,2398    cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,2399    expMonth: "expMonth" in entry ? entry.expMonth : undefined,2400    expYear: "expYear" in entry ? entry.expYear : undefined,2401    cvc: "cvc" in entry ? entry.cvc : undefined,2402    cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,2403    network: "network" in entry ? entry.network : undefined,2404    last4: "last4" in entry ? entry.last4 : undefined,2405  };24062407  return migrateLegacyPasskey(base, entry);2408}24092410/**2411 * v2.11.0 read migration. Pre-v2.11.0 passkey entries used `type:"passkey"`2412 * with flat top-level fields (rpId, credentialId, etc.). This converts them2413 * to the new shape — `type:"login"` with a `passkey` sub-object — so all2414 * downstream consumers can rely on the new model. The result is rewritten2415 * to disk on next vault save (hasLegacyShape detects the un-migrated case).2416 */2417function migrateLegacyPasskey(2418  base: VaultEntry,2419  raw: VaultEntry | LegacyVaultEntry2420): VaultEntry {2421  if (base.passkey) return base;2422  const flat = raw as Partial<VaultEntry>;2423  const isPasskeyType = base.type === "passkey";2424  const hasFlatPasskeyFields =2425    typeof flat.rpId === "string" &&2426    typeof flat.credentialId === "string" &&2427    typeof flat.publicKeyCose === "string" &&2428    typeof flat.userHandle === "string" &&2429    typeof flat.userName === "string";2430  if (!isPasskeyType && !hasFlatPasskeyFields) return base;2431  if (!hasFlatPasskeyFields) return base;24322433  const algorithm: -7 | -8 = flat.algorithm === -8 ? -8 : -7;2434  base.passkey = {2435    rpId: flat.rpId!,2436    rpName: flat.rpName ?? flat.rpId!,2437    credentialId: flat.credentialId!,2438    publicKeyCose: flat.publicKeyCose!,2439    privateKeyJwk: flat.privateKeyJwk,2440    userHandle: flat.userHandle!,2441    userName: flat.userName!,2442    userDisplayName: flat.userDisplayName ?? flat.userName!,2443    algorithm,2444    signCount: flat.signCount ?? 0,2445    aaguid: flat.aaguid ?? "",2446    backupEligible: flat.backupEligible === true,2447    backupState: flat.backupState === true,2448    lastUsedAt: flat.lastUsedAt,2449    browser: flat.browser,2450    transports: flat.transports,2451    createdAt: base.createdAt,2452  };2453  // Promote to "login" so the unified Entry view renders. Username gets2454  // populated from the passkey's userName so the entry is searchable in the2455  // existing autofill flow without a separate code path.2456  if (isPasskeyType) base.type = "login";2457  if (!base.username) base.username = flat.userName;2458  if (!base.url) base.url = `https://${flat.rpId}`;2459  return base;2460}246124622463// ---------------------------------------------------------------------------2464// Deduplication2465// ---------------------------------------------------------------------------24662467function entryDupeKey(e: VaultEntry): string {2468  if (e.type === "note") return `note|${e.title.toLowerCase()}`;2469  // Passkey-bearing entries dedupe by the credential's RP + user. Two logins2470  // on different sites that happen to share a username are still distinct;2471  // two passkey credentials for the same RP+user are duplicates regardless2472  // of any login fields they may also carry.2473  if (e.passkey) {2474    return `passkey|${e.passkey.rpId.toLowerCase()}|${e.passkey.userName.toLowerCase()}`;2475  }2476  return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;2477}24782479/** Returns the number of duplicate entries (those that would be removed). */2480export function countDuplicates(): number {2481  const best = new Map<string, VaultEntry>();2482  let dupeCount = 0;2483  for (const e of entries.filter((e) => !e.deletedAt)) {2484    const key = entryDupeKey(e);2485    const existing = best.get(key);2486    if (!existing) {2487      best.set(key, e);2488    } else {2489      dupeCount++;2490      // Keep the more recently modified one in the map2491      if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2492        best.set(key, e);2493      }2494    }2495  }2496  return dupeCount;2497}24982499/**2500 * Soft-deletes duplicate entries, keeping the most recently modified copy of2501 * each group. Returns the number of entries moved to trash.2502 */2503export async function deduplicateEntries(): Promise<number> {2504  if (!derivedKey) throw new Error("vault_locked");2505  // Dedup reshapes slot B permanently under the decoy key, which is2506  // forensically distinguishable from a freshly-seeded decoy vault. Refuse.2507  if (vaultMode === "decoy") {2508    throw new Error("deduplicate disabled in decoy mode");2509  }25102511  const best = new Map<string, VaultEntry>();2512  for (const e of entries.filter((en) => !en.deletedAt)) {2513    const key = entryDupeKey(e);2514    const existing = best.get(key);2515    if (!existing) {2516      best.set(key, e);2517    } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2518      best.set(key, e);2519    }2520  }25212522  const keepIds = new Set(Array.from(best.values()).map((e) => e.id));2523  let removed = 0;2524  entries = entries.map((e) => {2525    if (!e.deletedAt && !keepIds.has(e.id)) {2526      removed++;2527      return { ...e, deletedAt: monotonicEntryTimestamp(e.modifiedAt) };2528    }2529    return e;2530  });25312532  if (removed > 0) await persistEntries();2533  return removed;2534}25352536// ---------------------------------------------------------------------------2537// Vault history — snapshot BEFORE every vault write so the saved blob is2538// what is about to be lost, not what was just written. Capped at 5. The2539// stored blobs are AES-256-GCM ciphertext under the master password, so2540// history adds zero security surface.2541// ---------------------------------------------------------------------------25422543const HISTORY_KEY = "peach_vault_history";2544const HISTORY_MAX = 5;25452546/**2547 * Snapshot the CURRENT on-disk vault state into history. Call this BEFORE2548 * overwriting peach_vault_a so the saved blob captures the about-to-be-lost2549 * state. Identical-to-most-recent blobs are skipped to avoid filling history2550 * with no-op writes.2551 */2552export async function takeVaultSnapshot(2553  reason: VaultSnapshot["reason"],2554): Promise<void> {2555  try {2556    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);2557    const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];2558    const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];25592560    // Nothing to snapshot if the real slot doesn't exist yet (fresh install,2561    // pre-createVault). createVault skips snapshots intentionally — there is2562    // no prior state to preserve.2563    if (!slotA) return;25642565    const vault_a = JSON.stringify(slotA);2566    const vault_b = JSON.stringify(slotB ?? slotA);25672568    // Best-effort entry count: only meaningful when the in-memory state is2569    // unlocked AND in real mode. Decoy mode would leak the decoy entry2570    // count; locked mode has no entries to count. Both fall through to null.2571    let entryCount: number | null = null;2572    if (derivedKey && vaultMode === "real") {2573      try {2574        entryCount = entries.filter((e) => !e.deletedAt).length;2575      } catch {2576        entryCount = null;2577      }2578    }25792580    const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];2581    const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)2582      ? existingRaw2583      : { snapshots: [] };25842585    // Deduplication: if the most recent snapshot has byte-identical blobs,2586    // skip — saves the same vault N times in a row would otherwise burn the2587    // entire history window with no recovery value.2588    const latest = history.snapshots[0];2589    if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {2590      return;2591    }25922593    const snapshot: VaultSnapshot = {2594      id: crypto.randomUUID(),2595      savedAt: Date.now(),2596      reason,2597      vault_a,2598      vault_b,2599      entryCount,2600    };26012602    history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);2603    await chrome.storage.local.set({ [HISTORY_KEY]: history });2604  } catch (err) {2605    // Non-fatal — history must never block a save. A failed snapshot just2606    // means the user loses one rung of the safety ladder for this write.2607    // M4/QUA-006: log so the failure is visible; if it looks like a quota2608    // problem, notify the popup so the user can prune history themselves.2609    console.warn('[Peach] takeVaultSnapshot failed:', err);2610    if (String(err).includes('QUOTA') || String(err).includes('quota')) {2611      try {2612        await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });2613      } catch {2614        // popup may be closed; surfaced via console.warn above2615      }2616    }2617  }2618}26192620/** Wipe all vault history. Called by Panic / DESTROY_VAULT. */2621export async function clearVaultHistory(): Promise<void> {2622  try {2623    await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });2624  } catch {2625    // Non-fatal — DESTROY_VAULT also runs storage.local.clear().2626  }2627}26282629/** Read all snapshots, newest first, for the Settings vault history view. */2630export async function getVaultHistory(): Promise<VaultSnapshot[]> {2631  const raw = await chrome.storage.local.get(HISTORY_KEY);2632  const history = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];2633  if (!history || !Array.isArray(history.snapshots)) return [];2634  return history.snapshots;2635}26362637/**2638 * Replace the on-disk vault with the chosen snapshot's blobs and lock the2639 * vault. The current state is itself snapshotted with reason 'restore' first2640 * so the restore is reversible. After this returns, the user must unlock2641 * with the password that matches the restored blob.2642 */2643export async function restoreVaultSnapshot(2644  snapshotId: string,2645): Promise<{ ok: true } | { ok: false; error: string }> {2646  const history = await getVaultHistory();2647  const snapshot = history.find((s) => s.id === snapshotId);2648  if (!snapshot) return { ok: false, error: "snapshot_not_found" };26492650  // Snapshot the about-to-be-replaced current state so the restore is2651  // reversible. takeVaultSnapshot is no-op when the most recent entry is2652  // byte-identical, so a restore-of-a-restore stays clean.2653  await takeVaultSnapshot("restore");26542655  let restoredA: StoredVault;2656  let restoredB: StoredVault;2657  try {2658    restoredA = JSON.parse(snapshot.vault_a) as StoredVault;2659    restoredB = JSON.parse(snapshot.vault_b) as StoredVault;2660  } catch {2661    return { ok: false, error: "snapshot_corrupt" };2662  }26632664  await writeSlot(SLOT_A, restoredA);2665  await writeSlot(SLOT_B, restoredB);2666  await stampLocalVaultMutation();26672668  // Lock so the user must prove they can decrypt the restored blob. If they2669  // restored a pre-password-change snapshot they discover it immediately at2670  // the lock screen rather than silently holding an inaccessible vault.2671  lock();26722673  return { ok: true };2674}26752676/**2677 * Rotate the vault's sync identity by generating a FRESH ROOT KEY and2678 * re-wrapping everything under it (MV-8). Because every sync credential —2679 * vault_id, the Noise XX static keypair, the Ed25519 manifest signing key,2680 * and the per-entry envelope keys — derives from the root key, rotation2681 * makes a lost/stolen device's retained key material useless. All paired2682 * devices must re-pair afterwards.2683 *2684 * CONSEQUENCE THE UI MUST SURFACE: the 12 recovery words also derive from2685 * the root key, so rotation INVALIDATES the old recovery phrase. The flow2686 * sets peach_recovery_pending so the popup re-presents the new words for2687 * confirmation, same as the migrateToRecovery rotate path.2688 */2689export async function rotateSyncIdentity(): Promise<{ ok: boolean; error?: string }> {2690  if (!derivedKey || vaultMode !== "real") {2691    return { ok: false, error: "vault_locked" };2692  }2693  const slotA = await loadSlot(SLOT_A);2694  if (!slotA) return { ok: false, error: "missing_slot_a" };26952696  // 1. Fresh root key + recovery escrow (new words).2697  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =2698    await generateAndWrapRootKey();26992700  // 2. Re-wrap the new root key under the current password-derived key.2701  const newRootKey = unhex(rawRootKey);2702  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, newRootKey);27032704  // 3. Snapshot, then single atomic slot write — both escrow wrappings of2705  //    the new root key land together (same transactional rule as2706  //    changePassword). Entries are untouched: they are sealed under the2707  //    password-derived key, not the root key.2708  await takeVaultSnapshot("local_save");2709  const nextSlotA: StoredVault = {2710    ...slotA,2711    recovery_salt: recoverySalt,2712    recovery_wrapped_root_key: wrappedRootKey,2713    recovery_nonce: wrappedNonce,2714    recovery_tag: wrappedTag,2715    ...pwRoot,2716  };2717  await writeSlot(SLOT_A, nextSlotA);27182719  // 4. Swap in memory only after disk committed.2720  if (rootKey) zeroKey(rootKey);2721  rootKey = newRootKey;27222723  // 5. Old peers' identities derive from the dead root key — drop them all.2724  const { clearPairedDevices } = await import("./paired-devices");2725  await clearPairedDevices();27262727  // 6. Force re-presentation of the NEW recovery words on next popup view.2728  await setRecoveryConfirmPending(); // same flag the create-vault flow uses27292730  await stampLocalVaultMutation();2731  return { ok: true };2732}27332734/**2735 * Change the master password. Re-encrypts slot A with a fresh salt + new2736 * derived key. Slot B (duress or noise) is left untouched when duress is2737 * configured — it uses an independent key derived from the duress password —2738 * and regenerated as noise when duress is not configured.2739 */2740export async function changePassword(2741  currentPassword: string,2742  newPassword: string2743): Promise<boolean> {2744  if (!derivedKey || vaultMode !== "real") return false;27452746  // Verify current password before allowing any change2747  const valid = await verifyMainPassword(currentPassword);2748  if (!valid) return false;27492750  const slotA = await loadSlot(SLOT_A);2751  if (!slotA) return false;2752  if (!rootKey) return false;27532754  // Derive fresh key from new password + new random salt2755  const newSalt = generateSalt();2756  const newKey = await deriveKey(newPassword, newSalt);27572758  // Re-encrypt the in-memory entries with the new key2759  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);2760  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");27612762  // Pre-wrap root key under the new derived key. Recovery fields wrap rootKey2763  // under recovery words and remain untouched — recovery phrase keeps working2764  // across password changes (H4/COR-002).2765  const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);27662767  const finalSlotA: StoredVault = {2768    ...slotA,2769    salt: hex(newSalt),2770    nonce,2771    ciphertext,2772    tag,2773    ...pwRoot,2774  };27752776  // Snapshot the OLD-key blob before overwriting it. If the user later2777  // restores from this snapshot they will need the OLD password — the2778  // post-restore lock surfaces that immediately.2779  await takeVaultSnapshot("local_save");27802781  // Single atomic write: ciphertext, salt, and pw_root_* fields all land in2782  // one storage transaction. An SW kill before this point leaves the old2783  // slot intact; after this point everything tied to the new password is2784  // already on disk together (M6/COR-004).2785  await writeSlot(SLOT_A, finalSlotA);27862787  // Swap the in-memory key synchronously before any further await. If we2788  // threw between the Slot A write and this swap, the next persistEntries()2789  // would overwrite Slot A with old-key ciphertext, locking the user out.2790  zeroKey(derivedKey);2791  derivedKey = newKey;27922793  // Regenerate noise for slot B when duress is not in use. Runs after the2794  // key swap so a failure here is a disposable noise regeneration, not a2795  // lockout.2796  if (!duressConfigured) {2797    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));2798  }2799  await stampLocalVaultMutation();28002801  return true;2802}