vault.ts

99.5 KB · raw

1/**2 * vault.ts — sole owner of vault state and chrome.storage vault keys.3 *4 * Every read/write of `peach_vault_a`, `peach_vault_b`, and `peach_settings`5 * goes through this module. No other file accesses those keys directly.6 * External callers reach vault operations via `messages.ts` — never by7 * importing from here cross-boundary (popup/content must not). Invariants8 * for the two-slot schema, unlock timing, and key/disk atomicity are in9 * Projects.md §3.2–§3.6.10 */1112import { deriveKey, generateSalt } from "../crypto/argon2";13import { extractDomain } from "../shared/domain";14import { clampSyncTimestamp } from "../shared/sync-limits";15import { 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";3536type EntryDraft = Omit<37  VaultEntry,38  "id" | "createdAt" | "modifiedAt" | "deletedAt"39>;4041// Slot-neutral storage keys (v1.4.24+). Both slots always exist; slot B42// either holds the decoy vault (when duress is configured) or random noise43// that looks identical at rest. No external indicator is stored — duress44// configuration is recorded only inside the encrypted payload of slot A.45const SLOT_A = "peach_vault_a";46const SLOT_B = "peach_vault_b";4748// Legacy keys, migrated away on first access.49const LEGACY_MAIN = "peach_vault";50const LEGACY_DECOY = "peach_decoy_vault";51const LEGACY_DURESS_FLAG = "peach_duress";5253// Plaintext is padded to the next multiple of this size before encryption.54// This coarsens ciphertext-length leakage into 1 KiB buckets.55const PAD_BLOCK = 1024;5657// How many past passwords to retain per entry. Generous enough to be useful as58// a recovery aid while bounding the secret material we hold (and the ciphertext59// growth) for an entry whose password is rotated frequently.60const PASSWORD_HISTORY_MAX = 50;6162// When duress is configured, BOTH slots are padded to this fixed ceiling so63// their ciphertext lengths are identical and cannot reveal that a hidden decoy64// vault exists (audit MEDIUM — plausible-deniability leak). 256 KiB comfortably65// holds a very large vault (thousands of entries incl. passkeys). The decoy66// slot can't be re-encrypted on every real-vault save (the real session has no67// decoy key), so a fixed ceiling — rather than size-matching on each write — is68// what keeps the two slots equal. A real vault whose plaintext exceeds this69// would grow past the ceiling and re-expose the bit; that is an extreme,70// documented edge well beyond normal use.71const DURESS_SLOT_SIZE = 262_144;7273let derivedKey: Uint8Array | null = null;74// 32-byte random root key, separate from the derivedKey used for vault encryption.75// The root key is wrapped (encrypted) under the recovery key derived from the76// 12-word phrase. When the user changes their password, only the wrapping changes;77// the root key and recovery words remain stable.78let rootKey: Uint8Array | null = null;79let entries: VaultEntry[] = [];80let domainIndex: Map<string, VaultEntry[]> = new Map();81let vaultMode: "real" | "decoy" = "real";82// Cached post-unlock view of whether the real vault records that duress is83// configured. Only meaningful after a real-mode unlock; for decoy-mode unlock84// this stays false because we never see slot A's plaintext.85let duressConfigured = false;8687let migrationRan = false;8889// Set to a corruption reason during the last unlock() attempt when both slots90// decrypted but failed schema validation. Consumed and cleared by91// consumeLastUnlockFailureReason() so messages.ts can surface vault_corrupted92// distinctly from wrong-password (M7/COR-007).93//94// NOTE: module-level state — if vault.ts is ever moved to a worker context,95// this must be replaced with a structured return value from unlock() or a96// postMessage channel. The signal is invisible across module-instance97// boundaries.98let lastUnlockFailureReason: string | null = null;99100export function consumeLastUnlockFailureReason(): string | null {101  const r = lastUnlockFailureReason;102  lastUnlockFailureReason = null;103  return r;104}105106// ---------------------------------------------------------------------------107// Settings (persisted inside the encrypted vault store as a sidecar key)108// ---------------------------------------------------------------------------109110export type TextSize = "small" | "medium" | "large";111112export interface VaultSettings {113  accentColor?: AccentColorName;114  theme?: "dark" | "light";115  autoLockMinutes?: number;116  clipboardClearSeconds?: number;117  lockOnClose?: boolean;118  breachMonitoring?: boolean;119  passkeyProviderEnabled?: boolean;120  trashRetentionDays?: number;121  manualSummonDomains?: Record<string, ManualSummonRecord>;122  declinedCardFingerprints?: string[];123  /**124   * Text size scale for body copy and entry titles. Stops at "large" by125   * design — XL clips dense screens (Vault, Health) inside the fixed126   * 330×480 popup surface.127   */128  textSize?: TextSize;129  /**130   * When true, all entrance/exit transitions and ambient animations are131   * collapsed to instant. Honoured alongside the user's OS-level132   * `prefers-reduced-motion`.133   */134  reduceMotion?: boolean;135  /**136   * Android-only: when true, the master key is escrowed in AndroidKeyStore137   * and the lock screen offers biometric unlock. Toggled from Settings →138   * Security → Biometrics. Has no effect on desktop builds.139   */140  biometricsEnabled?: boolean;141  /**142   * User overrides for keyboard shortcuts. Keys are ShortcutAction names143   * (see src/shared/shortcuts.ts). Missing actions fall through to144   * DEFAULT_BINDINGS — `getActiveBindings(settings.shortcuts)` is the145   * canonical lookup. Storing only the deltas keeps the vault payload146   * small and lets default updates land for users who never rebind.147   */148  shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;149}150151let settings: VaultSettings = {};152153export function getSettings(): VaultSettings {154  return settings;155}156157export async function ensureSettingsLoaded(): Promise<VaultSettings> {158  await loadSettings();159  return settings;160}161162export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {163  await loadSettings();164  settings = { ...settings, ...patch };165  await persistSettings();166}167168async function persistSettings(): Promise<void> {169  try {170    await chrome.storage.local.set({ peach_settings: settings });171  } catch (err) {172    throw mapStorageError(err);173  }174}175176function mapStorageError(err: unknown): Error {177  const message = err instanceof Error ? err.message : String(err);178  if (/QUOTA_BYTES|quota/i.test(message)) {179    return new Error("STORAGE_QUOTA_EXCEEDED");180  }181  return err instanceof Error ? err : new Error(message);182}183184async function loadSettings(): Promise<void> {185  const result = await chrome.storage.local.get("peach_settings");186  settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};187}188189// Fire-and-forget sync trigger after a committed vault write. Lazy190// dynamic import avoids a circular dependency between vault.ts and191// sync-trigger.ts (the trigger imports paired-devices, which only reads192// storage, but the lazy load also gives us a clean opt-out path in193// tests where sync-trigger has not been initialised).194function fireSyncTrigger(reason: "vault_change"): void {195  void import("./sync-trigger")196    .then((mod) => mod.triggerSyncIfReachable({ reason }))197    .catch(() => {198      /* sync trigger module not available — non-fatal */199    });200}201202// ---------------------------------------------------------------------------203// HIBP breach check (k-anonymity model)204// ---------------------------------------------------------------------------205206export async function checkBreach(password: string): Promise<number> {207  // HIBP k-anonymity API is keyed on SHA-1 prefixes — this is dictated by208  // the public API, not a security choice. Do not migrate to SHA-256 here.209  const encoder = new TextEncoder();210  const hashBuffer = await crypto.subtle.digest("SHA-1", encoder.encode(password));211  const hashHex = Array.from(new Uint8Array(hashBuffer))212    .map((b) => b.toString(16).padStart(2, "0"))213    .join("")214    .toUpperCase();215216  const prefix = hashHex.slice(0, 5);217  const suffix = hashHex.slice(5);218219  try {220    const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`);221    if (!res.ok) return 0;222    const text = await res.text();223    const match = text.split("\r\n").find((l) => l.startsWith(suffix));224    return match ? parseInt(match.split(":")[1], 10) : 0;225  } catch {226    return 0; // Network unavailable — don't block227  }228}229230export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {231  const fingerprint = await cardFingerprint(last4, expMonth, expYear);232  await loadSettings();233  settings = {234    ...settings,235    declinedCardFingerprints: [...(settings.declinedCardFingerprints ?? []), fingerprint],236  };237  await persistSettings();238}239240export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {241  await loadSettings();242  const fingerprint = await cardFingerprint(last4, expMonth, expYear);243  return (settings.declinedCardFingerprints ?? []).includes(fingerprint);244}245246async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {247  const encoder = new TextEncoder();248  const buf = await crypto.subtle.digest("SHA-256", encoder.encode(`${last4}|${expMonth}|${expYear}`));249  return Array.from(new Uint8Array(buf).slice(0, 8))250    .map((b) => b.toString(16).padStart(2, "0"))251    .join("");252}253254function hex(buf: Uint8Array): string {255  return Array.from(buf)256    .map((b) => b.toString(16).padStart(2, "0"))257    .join("");258}259260function unhex(s: string): Uint8Array {261  const out = new Uint8Array(s.length / 2);262  for (let i = 0; i < s.length; i += 2) {263    out[i / 2] = parseInt(s.slice(i, i + 2), 16);264  }265  return out;266}267268// ---------------------------------------------------------------------------269// Root key generation and recovery word wrapping270// ---------------------------------------------------------------------------271272/**273 * Generate a random 32-byte root key and wrap it (AES-256-GCM) under a key274 * derived from the recovery word material via HKDF-SHA256. The wrapped blob275 * fields are stored in slot A alongside the password-wrapped ciphertext. The276 * root key itself is kept in memory for the session so getRecoveryWords() can277 * encode it without re-deriving.278 */279async function generateAndWrapRootKey(): Promise<{280  rawRootKey: string; // hex of the plaintext root key — caller stores in rootKey281  recoverySalt: string;282  wrappedRootKey: string;283  wrappedNonce: string;284  wrappedTag: string;285}> {286  const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));287288  // Derive the recovery key from the BIP39 words encoding of the root key.289  const words = await rootKeyToWords(rootKeyBytes);290  const wordMaterial = await wordsToRootKeyMaterial(words);291  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));292  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);293294  // Wrap the root key with the recovery key using AES-256-GCM directly.295  // We hex-encode rootKeyBytes so the plaintext is always valid UTF-8.296  const nonce = crypto.getRandomValues(new Uint8Array(12));297  const encoded = new TextEncoder().encode(hex(rootKeyBytes));298  const raw = await crypto.subtle.encrypt(299    {300      name: "AES-GCM",301      iv: nonce,302      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,303      tagLength: 128,304    },305    recoveryKey,306    encoded307  );308  // WebCrypto returns ciphertext || auth tag concatenated; split them.309  const rawU8 = new Uint8Array(raw);310  const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));311  const tag = hex(rawU8.slice(rawU8.length - 16));312313  return {314    rawRootKey: hex(rootKeyBytes),315    recoverySalt: hex(recoverySalt),316    wrappedRootKey: ciphertext,317    wrappedNonce: hex(nonce),318    wrappedTag: tag,319  };320}321322/**323 * Unwrap the root key using recovery words. Called during recovery flow when324 * the user provides their 12-word phrase and a new password.325 * Exported for use by the RECOVER_WITH_WORDS message handler.326 */327export async function unwrapRootKeyForRecovery(328  wrappedRootKey: string,329  wrappedNonce: string,330  wrappedTag: string,331  recoverySaltHex: string,332  words: string[]333): Promise<void> {334  const wordMaterial = await wordsToRootKeyMaterial(words);335  const recoverySalt = unhex(recoverySaltHex);336  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);337338  // Decrypt and cache the root key. The root key bytes were hex-encoded before339  // encryption so the ciphertext is valid UTF-8. We inline the AES-GCM decrypt340  // here to avoid passing a CryptoKey to the string-based encrypt/decrypt helpers.341  // Each component is stored separately in the vault slot; decode them individually342  // so the nonce is always exactly the 12 bytes from wrappedNonce.343  const nonceRaw = unhex(wrappedNonce);344  const ciphertextRaw = unhex(wrappedRootKey);345  const tagRaw = unhex(wrappedTag);346  // Combine ciphertext and tag for AES-GCM (expects ciphertext||tag).347  // Use explicit ArrayBuffer allocations to satisfy TS BufferSource constraints.348  const nonceU8 = nonceRaw as unknown as Uint8Array<ArrayBuffer>;349  const combined = new Uint8Array(ciphertextRaw.length + tagRaw.length);350  combined.set(ciphertextRaw, 0);351  combined.set(tagRaw, ciphertextRaw.length);352  const raw = await crypto.subtle.decrypt(353    { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },354    recoveryKey,355    combined356  );357  const decryptedHex = new TextDecoder().decode(raw);358  rootKey = unhex(decryptedHex);359}360361/**362 * Re-wrap the cached root key under a new derived key (from the user's new363 * password). Called after password change and after recovery re-key so the364 * same recovery words continue to work with the updated password — and so365 * subsequent unlocks can rehydrate rootKey via deriveRootKeyFromDerivedKey.366 *367 * recovery_* fields are intentionally not touched: those wrap rootKey under368 * the recovery words, which do not change when the password changes.369 */370export async function rewrapRootKeyForPassword(371  newDerivedKey: Uint8Array,372  _newSalt: Uint8Array373): Promise<void> {374  if (!rootKey) throw new Error("root key not set");375  const slotA = await loadSlot(SLOT_A);376  if (!slotA) throw new Error("missing slot A");377  const pwRoot = await wrapRootKeyForDerivedKey(newDerivedKey, rootKey);378  await writeSlot(SLOT_A, { ...slotA, ...pwRoot });379}380381/**382 * Change the vault encryption to a new derived key (already derived from383 * the user's new password). Used by RECOVER_WITH_WORDS and changePassword.384 * Caller is responsible for key swap and snapshot.385 */386async function reencryptVaultForNewKey(387  newKey: Uint8Array,388  slotA: StoredVault389): Promise<void> {390  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);391  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");392  await writeSlot(SLOT_A, {393    ...slotA,394    nonce,395    ciphertext,396    tag,397  });398}399400/**401 * Full password change with an already-derived key (used after recovery).402 * Unlike changePassword(), this skips re-verification of current password403 * since recovery flow has already validated the user's identity via words.404 */405export async function changePasswordWithNewKey(406  newSalt: Uint8Array,407  newKey: Uint8Array408): Promise<void> {409  const slotA = await loadSlot(SLOT_A);410  if (!slotA) throw new Error("missing slot A");411  // reencryptVaultForNewKey must receive the updated salt so that subsequent412  // UNLOCK calls with the new password can re-derive the correct key.413  await reencryptVaultForNewKey(newKey, { ...slotA, salt: hex(newSalt) });414  if (derivedKey) zeroKey(derivedKey);415  derivedKey = newKey;416  // Refresh pw_root_* under the new key so deriveRootKeyFromDerivedKey works417  // on the next unlock (H2/COR-006). If rootKey is missing — recovery flow418  // should have populated it — fall back silently rather than blowing up the419  // recovery path; migrateToRecovery will rehydrate on the next unlock.420  if (rootKey) {421    const slotAfter = await loadSlot(SLOT_A);422    if (slotAfter) {423      const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);424      await writeSlot(SLOT_A, { ...slotAfter, ...pwRoot });425    }426  }427  if (!duressConfigured) {428    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));429  }430  await stampLocalVaultMutation();431}432433// ---------------------------------------------------------------------------434// Salt generation --- exported so the RECOVER_WITH_WORDS handler can derive435// a new key after password reset without re-importing the crypto module.436// ---------------------------------------------------------------------------437438export { deriveKey, generateSalt };439440export async function loadSlotA(): Promise<StoredVault | null> {441  return loadSlot(SLOT_A);442}443444/**445 * Recover the session root key by AES-GCM-decrypting the pw_root_* fields446 * (a second wrapping of the root key under the password-derived key). This447 * is what makes GET_RECOVERY_WORDS work across lock/unlock cycles without448 * the user re-entering their recovery phrase: the same root key bytes —449 * and therefore the same 12 words — survive every unlock.450 *451 * Returns null when the pw_root fields are absent (pre-v2.12 vault that452 * hasn't been migrated yet) or when decryption fails (wrong derived key,453 * tampered ciphertext). On null the caller should fall through to454 * migrateToRecovery() to populate the fields.455 */456async function deriveRootKeyFromDerivedKey(457  derivedKeyBytes: Uint8Array,458  slotA: StoredVault,459): Promise<Uint8Array | null> {460  if (!slotA.pw_root_ciphertext || !slotA.pw_root_nonce || !slotA.pw_root_tag) {461    return null;462  }463  try {464    const rootHex = await decrypt(465      derivedKeyBytes,466      slotA.pw_root_nonce,467      slotA.pw_root_ciphertext,468      slotA.pw_root_tag,469      "pw_root_v1",470    );471    return unhex(rootHex);472  } catch {473    return null;474  }475}476477// AES-GCM-wrap rootKey under derivedKey for the pw_root_* fields. Returns the478// hex-encoded ciphertext/nonce/tag triple ready to embed in StoredVault.479async function wrapRootKeyForDerivedKey(480  derivedKeyBytes: Uint8Array,481  rootKeyBytes: Uint8Array,482): Promise<{ pw_root_ciphertext: string; pw_root_nonce: string; pw_root_tag: string }> {483  const { nonce, ciphertext, tag } = await encrypt(derivedKeyBytes, hex(rootKeyBytes), "pw_root_v1");484  return {485    pw_root_ciphertext: ciphertext,486    pw_root_nonce: nonce,487    pw_root_tag: tag,488  };489}490491/**492 * For vaults created before v2.12 (no recovery_salt/recovery_wrapped_root_key),493 * generate the root key, wrap it under the recovery words, and persist the494 * recovery escrow into slot A. The caller must show the recovery words to the495 * user before calling this — once called, those words are the vault's recovery496 * path. This runs once, on the first unlock of an upgraded vault.497 */498export async function migrateToRecovery(): Promise<void> {499  if (!derivedKey || vaultMode !== "real") {500    throw new Error("vault must be unlocked in real mode");501  }502  const slotA = await loadSlot(SLOT_A);503  if (!slotA) throw new Error("missing slot A");504  const hasRecoveryEscrow =505    !!slotA.recovery_salt && !!slotA.recovery_wrapped_root_key;506  const hasPwRoot = !!slotA.pw_root_ciphertext && !!slotA.pw_root_nonce;507  if (hasRecoveryEscrow && hasPwRoot) return; // already done508509  // If recovery escrow already exists but pw_root doesn't, we cannot recover510  // the original rootKey without the user's words. The least-surprising path511  // is to rotate to a fresh root key — the user's old recovery words become512  // invalid but we surface peach_recovery_pending so the popup re-presents513  // the words. The unlock-path callers all set that flag.514  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =515    await generateAndWrapRootKey();516  rootKey = unhex(rawRootKey);517518  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);519  const nextSlotA: StoredVault = {520    ...slotA,521    recovery_salt: recoverySalt,522    recovery_wrapped_root_key: wrappedRootKey,523    recovery_nonce: wrappedNonce,524    recovery_tag: wrappedTag,525    ...pwRoot,526  };527  await writeSlot(SLOT_A, nextSlotA);528  await stampLocalVaultMutation();529}530531/**532 * Returns the 12 recovery words for the current session's root key.533 * Must be called while the vault is unlocked. Throws if recovery has not534 * been set up (pre-v2.12 vault that hasn't migrated yet).535 */536export async function getRecoveryWords(): Promise<string[]> {537  if (!rootKey) {538    throw new Error("recovery not set up — vault may need migration");539  }540  return rootKeyToWords(rootKey);541}542543async function loadSlot(key: string): Promise<StoredVault | null> {544  const result = await chrome.storage.local.get(key);545  return (result as Record<string, StoredVault | undefined>)[key] ?? null;546}547548async function writeSlot(key: string, vault: StoredVault): Promise<void> {549  try {550    await chrome.storage.local.set({ [key]: vault });551  } catch (err) {552    throw mapStorageError(err);553  }554}555556// Monotonic clock for per-entry modifiedAt / deletedAt timestamps. Guards the557// sync layer's last-write-wins merge against wall-clock regressions (NTP step,558// manual clock change, DST glitch): a backwards Date.now() must never produce559// an entry timestamp that's <= the entry's existing modifiedAt, or a genuine560// local edit would lose to a stale remote copy. The returned value is always561// strictly greater than both the entry's current modifiedAt and the previous562// call's result (SEV-2-E).563let lastEntryTimestamp = 0;564function monotonicEntryTimestamp(currentModifiedAt?: number): number {565  const base = Math.max(566    Date.now(),567    (currentModifiedAt ?? 0) + 1,568    lastEntryTimestamp + 1,569  );570  lastEntryTimestamp = base;571  return base;572}573574async function stampLocalVaultMutation(): Promise<void> {575  const raw = await chrome.storage.local.get("peach_last_modified_at");576  const previous = Number(577    (raw as Record<string, unknown>).peach_last_modified_at,578  );579  const next = Math.max(580    Date.now(),581    Number.isFinite(previous) ? previous + 1 : 0,582  );583  await chrome.storage.local.set({584    peach_last_modified_at: String(next),585  });586}587588/**589 * One-shot migration from the pre-A-2 schema (peach_vault + peach_decoy_vault590 * + peach_duress flag) to the slot-neutral schema (peach_vault_a +591 * peach_vault_b). Runs at most once per session; safe to call repeatedly.592 */593async function ensureMigrated(): Promise<void> {594  if (migrationRan) return;595  migrationRan = true;596597  const keys = [LEGACY_MAIN, LEGACY_DECOY, LEGACY_DURESS_FLAG, SLOT_A, SLOT_B];598  const raw = await chrome.storage.local.get(keys);599  const slotAExists = raw[SLOT_A] !== undefined;600  const slotBExists = raw[SLOT_B] !== undefined;601  const legacyMain = raw[LEGACY_MAIN] as StoredVault | undefined;602  const legacyDecoy = raw[LEGACY_DECOY] as StoredVault | undefined;603604  // Fresh install with nothing in storage — nothing to do; createVault() sets up both slots.605  if (!slotAExists && !legacyMain) return;606607  // Already migrated.608  if (slotAExists && slotBExists && !legacyMain && !legacyDecoy) return;609610  let didMigrate = false;611  if (legacyMain && !slotAExists) {612    await writeSlot(SLOT_A, legacyMain);613    didMigrate = true;614  }615616  // If slot B isn't set, populate it: use legacy decoy when present, else noise.617  if (!slotBExists) {618    const target = (legacyMain ?? raw[SLOT_A]) as StoredVault | undefined;619    if (legacyDecoy) {620      await writeSlot(SLOT_B, legacyDecoy);621      didMigrate = true;622    } else if (target) {623      await writeSlot(SLOT_B, generateNoiseBlob(target.ciphertext.length / 2));624      didMigrate = true;625    }626  }627628  const toRemove: string[] = [];629  if (legacyMain) toRemove.push(LEGACY_MAIN);630  if (legacyDecoy) toRemove.push(LEGACY_DECOY);631  if (raw[LEGACY_DURESS_FLAG] !== undefined) toRemove.push(LEGACY_DURESS_FLAG);632  if (toRemove.length > 0) {633    await chrome.storage.local.remove(toRemove);634    didMigrate = true;635  }636  if (didMigrate) {637    await stampLocalVaultMutation();638  }639}640641// ---------------------------------------------------------------------------642// Padding + noise helpers643// ---------------------------------------------------------------------------644645/**646 * Pads the plaintext string with trailing spaces so that the encoded byte647 * length is a multiple of PAD_BLOCK. JSON.parse tolerates trailing648 * whitespace after a complete document, so the padding is transparent on649 * decode. Ciphertext length equals plaintext length plus a 16-byte tag.650 */651function padPlaintext(json: string, minBytes = 0): string {652  const encoded = new TextEncoder().encode(json);653  const bucket = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);654  // minBytes lets the duress path force a fixed ceiling so both slots match.655  const target = Math.max(bucket, minBytes);656  const padLen = target - encoded.length;657  return json + " ".repeat(padLen);658}659660/**661 * Produces a StoredVault-shaped record filled with CSPRNG bytes. The662 * ciphertext length matches the given byte count. Because GCM ciphertext is663 * pseudo-random, this blob is indistinguishable at rest from a real664 * encrypted vault without the key.665 *666 * crypto.getRandomValues() caps each call at 65536 bytes (the Web Crypto667 * spec hard limit). Chunk the fill so vaults larger than that — common once668 * the user has dozens of entries or any passkey — don't throw.669 */670const CSPRNG_CHUNK = 65_536;671672function fillRandom(buf: Uint8Array): Uint8Array {673  for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {674    const end = Math.min(offset + CSPRNG_CHUNK, buf.length);675    const chunk = new Uint8Array(end - offset);676    crypto.getRandomValues(chunk);677    buf.set(chunk, offset);678  }679  return buf;680}681682function generateNoiseBlob(ciphertextBytes: number): StoredVault {683  const salt = crypto.getRandomValues(new Uint8Array(16));684  const nonce = crypto.getRandomValues(new Uint8Array(12));685  const cipher = fillRandom(new Uint8Array(ciphertextBytes));686  const tag = crypto.getRandomValues(new Uint8Array(16));687  return {688    version: 1,689    salt: hex(salt),690    nonce: hex(nonce),691    ciphertext: hex(cipher),692    tag: hex(tag),693  };694}695696// ---------------------------------------------------------------------------697// Encrypted plaintext envelope698// ---------------------------------------------------------------------------699700type VaultPayload = {701  entries: VaultEntry[];702  duressConfigured?: boolean;703};704705type DecryptedPayload = {706  entries: VaultEntry[];707  duressConfigured: boolean;708  /**709   * True when at least one entry in the on-disk payload had a legacy shape710   * (pre-v2.11.0 passkey type/flat fields, or pre-A-2 created/updated keys)711   * and got rewritten by normalizeEntry. The unlock path uses this to712   * persist the new shape immediately — without it, the migration would713   * re-run on every unlock and old shape never disappears from disk.714   */715  migratedFromLegacy: boolean;716};717718function encodePayload(entries: VaultEntry[], duress: boolean, minBytes = 0): string {719  const envelope: VaultPayload = { entries, duressConfigured: duress };720  return padPlaintext(JSON.stringify(envelope), minBytes);721}722723function rawNeedsMigration(raw: VaultEntry | LegacyVaultEntry): boolean {724  if ("created" in raw || "updated" in raw) return true;725  const flat = raw as Partial<VaultEntry>;726  if (flat.type === "passkey") return true;727  // Flat rpId without a passkey sub-object means pre-v2.11.0 schema.728  if (flat.rpId !== undefined && flat.passkey === undefined) return true;729  return false;730}731732function decodePayload(plain: string): DecryptedPayload {733  const parsed = JSON.parse(plain) as734    | Array<VaultEntry | LegacyVaultEntry>735    | VaultPayload;736737  const rawEntries = Array.isArray(parsed) ? parsed : parsed.entries ?? [];738  const flatMigrationNeeded = rawEntries.some(rawNeedsMigration);739740  const normalized = rawEntries.map(normalizeEntry);741  const { merged } = mergePasskeyOnlyIntoLogins(normalized);742743  if (Array.isArray(parsed)) {744    return {745      entries: normalized,746      duressConfigured: false,747      migratedFromLegacy: true, // pre-A-2 array shape always needs save748    };749  }750751  return {752    entries: normalized,753    duressConfigured: parsed.duressConfigured === true,754    migratedFromLegacy: flatMigrationNeeded || merged,755  };756}757758/**759 * One-time consolidation pass run alongside the legacy passkey migration.760 *761 * Pre-v2.11.0 the Chrome passkey path always created a fresh `type:"passkey"`762 * entry per registration — so users who tested registration multiple times763 * accumulated several passkey-bearing entries for the same RP, and the764 * migration to the unified shape carried that duplication forward. This765 * pass collapses the duplicates:766 *767 *   1. Group passkey-bearing (and not deleted) entries by `passkey.rpId`.768 *   2. Within each group, the most recently-active credential wins (prefer769 *      lastUsedAt, fall back to passkey.createdAt, fall back to modifiedAt).770 *   3. If a NON-passkey login entry exists for that RP (matched by url or771 *      additionalUrls hostname), attach the winning passkey to it and772 *      soft-delete every passkey-bearing entry in the group.773 *   4. Otherwise, soft-delete every loser in the group, keeping the winner774 *      as a passkey-only entry.775 *776 * Soft delete (deletedAt) rather than splice — the trash flow keeps the777 * record around for retention and the user can restore if the heuristic778 * picked wrong. The `merged` flag goes back to decodePayload so the779 * unlock path persists the consolidated shape immediately.780 */781function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {782  let merged = false;783  const now = Date.now();784785  const candidates = entries.filter((e) => !e.deletedAt && e.passkey);786  const byRpId = new Map<string, VaultEntry[]>();787  for (const e of candidates) {788    const rpId = e.passkey!.rpId;789    const list = byRpId.get(rpId);790    if (list) list.push(e);791    else byRpId.set(rpId, [e]);792  }793794  for (const [rpId, group] of byRpId) {795    if (group.length === 0) continue;796    group.sort((a, b) => {797      const aT =798        a.passkey!.lastUsedAt ?? a.passkey!.createdAt ?? a.modifiedAt ?? a.createdAt;799      const bT =800        b.passkey!.lastUsedAt ?? b.passkey!.createdAt ?? b.modifiedAt ?? b.createdAt;801      return bT - aT;802    });803    const winner = group[0]!;804805    // Look for a NON-passkey login entry matching this RP. Use the URL806    // hostname rather than a substring search so a "login.foo.com" entry807    // doesn't accidentally absorb a passkey for "foo.com".808    const loginTarget = entries.find((e) => {809      if (e.deletedAt || e.passkey || e.type !== "login") return false;810      if (e.url && extractDomain(e.url) === rpId) return true;811      for (const extra of e.additionalUrls ?? []) {812        if (extractDomain(extra) === rpId) return true;813      }814      return false;815    });816817    if (loginTarget) {818      loginTarget.passkey = winner.passkey;819      loginTarget.modifiedAt = now;820      for (const dup of group) {821        if (!dup.deletedAt) {822          dup.deletedAt = now;823          dup.modifiedAt = now;824        }825      }826      merged = true;827    } else if (group.length > 1) {828      for (let i = 1; i < group.length; i += 1) {829        const dup = group[i]!;830        if (!dup.deletedAt) {831          dup.deletedAt = now;832          dup.modifiedAt = now;833        }834      }835      merged = true;836    }837  }838839  return { merged };840}841842// Validates that a `StoredVault` record on disk has the field shape we expect843// before treating an AES-GCM decrypt success as a clean unlock. AES-GCM only844// authenticates the static VERSION_BYTE AAD, not the `version` field on the845// outer record — a corrupted `version: 42` slot still decrypts cleanly. This846// check surfaces that as `corrupted` (M7/COR-007) so the popup can offer a847// history-restore path instead of falsely reporting "wrong password".848function hasValidVaultSchema(v: unknown): v is StoredVault {849  if (typeof v !== "object" || v === null) return false;850  const r = v as Record<string, unknown>;851  return (852    r.version === 1 &&853    typeof r.salt === "string" &&854    typeof r.nonce === "string" &&855    typeof r.ciphertext === "string" &&856    typeof r.tag === "string"857  );858}859860export type TryDecryptResult =861  | { status: "ok"; payload: DecryptedPayload }862  | { status: "wrong_key" }863  | { status: "corrupted"; reason: string };864865// Exported solely for `unlockFromCodex` below, which needs to verify a866// supplied passphrase against a slotA blob *without* committing anything to867// storage. Keep this internal otherwise — callers crossing the messages.ts868// boundary should always go through `unlock` / `verifyMainPassword` so the869// constant-time invariants in Projects.md §3.4 are not bypassed.870export async function tryDecryptSlot(871  vault: StoredVault,872  key: Uint8Array,873  aadTag?: string,874): Promise<DecryptedPayload | null> {875  const res = await tryDecryptSlotResult(vault, key, aadTag);876  return res.status === "ok" ? res.payload : null;877}878879export async function tryDecryptSlotResult(880  vault: StoredVault,881  key: Uint8Array,882  aadTag?: string,883): Promise<TryDecryptResult> {884  if (!hasValidVaultSchema(vault)) {885    return { status: "corrupted", reason: "invalid_slot_schema" };886  }887  let plain: string;888  try {889    plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);890  } catch {891    return { status: "wrong_key" };892  }893  try {894    const parsed = JSON.parse(plain) as unknown;895    if (typeof parsed !== "object" || parsed === null) {896      return { status: "corrupted", reason: "invalid_payload_shape" };897    }898    if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {899      return { status: "corrupted", reason: "invalid_payload_shape" };900    }901    return { status: "ok", payload: decodePayload(plain) };902  } catch {903    return { status: "corrupted", reason: "invalid_payload_json" };904  }905}906907// ---------------------------------------------------------------------------908// Core operations909// ---------------------------------------------------------------------------910911function buildDomainIndexSync(all: VaultEntry[]): void {912  domainIndex = new Map();913914  for (const entry of all) {915    if (entry.deletedAt) continue;916    if (entry.type === "note" || entry.type === "card") continue;917918    // An entry can match multiple sites via `additionalUrls`. Index each919    // hostname so `queryDomain` returns the entry regardless of which alias920    // the user is currently visiting. Dedupe per-entry so a single entry921    // never appears twice in one bucket.922    const domains = new Set<string>();923    const primary = extractDomain(entry.url ?? "");924    if (primary) domains.add(primary);925    for (const extra of entry.additionalUrls ?? []) {926      const d = extractDomain(extra);927      if (d) domains.add(d);928    }929    if (domains.size === 0) continue;930931    for (const domain of domains) {932      const bucket = domainIndex.get(domain) ?? [];933      bucket.push(entry);934      domainIndex.set(domain, bucket);935    }936  }937}938939export async function createVault(password: string): Promise<void> {940  await ensureMigrated();941942  const salt = generateSalt();943  derivedKey = await deriveKey(password, salt);944  entries = [];945  vaultMode = "real";946  duressConfigured = false;947  buildDomainIndexSync(entries);948949  // Generate and wrap the root key for recovery word escrow.950  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =951    await generateAndWrapRootKey();952  rootKey = unhex(rawRootKey);953954  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);955  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");956957  // Second wrapping of rootKey under derivedKey so future unlocks can rehydrate958  // it without recovery words (H2/COR-006).959  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);960961  const slotA: StoredVault = {962    version: 1,963    salt: hex(salt),964    nonce,965    ciphertext,966    tag,967    recovery_salt: recoverySalt,968    recovery_wrapped_root_key: wrappedRootKey,969    recovery_nonce: wrappedNonce,970    recovery_tag: wrappedTag,971    ...pwRoot,972  };973  await writeSlot(SLOT_A, slotA);974975  // Matching-size noise blob for slot B, so a fresh install shows two976  // similarly-shaped records regardless of whether duress is ever set up.977  await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));978  await stampLocalVaultMutation();979980  touchAutoLock();981}982983export async function hasVault(): Promise<boolean> {984  await ensureMigrated();985  return (await loadSlot(SLOT_A)) !== null;986}987988/**989 * Returns whether the real vault has recorded that a duress passphrase is990 * configured. Reliable only after a real-mode unlock — before unlock or in991 * decoy mode, returns false because we cannot read slot A's plaintext.992 */993export async function isDuressEnabled(): Promise<boolean> {994  return vaultMode === "real" && duressConfigured;995}996997export async function setupDuress(duressPassword: string): Promise<void> {998  if (!derivedKey || vaultMode !== "real") {999    throw new Error("vault must be unlocked in real mode");1000  }1001  await ensureMigrated();10021003  // Encrypt the decoy payload (empty entries) under the duress key. Pad to1004  // at least the current slot A ciphertext size so the two slots look the1005  // same at rest at setup time.1006  const slotA = await loadSlot(SLOT_A);1007  if (!slotA) throw new Error("missing slot A");10081009  const decoySalt = generateSalt();1010  const decoyKey = await deriveKey(duressPassword, decoySalt);1011  try {1012    // Pad the decoy to the fixed duress ceiling. Slot A is re-encrypted to the1013    // same ceiling by the persistSlotA() call below (duressConfigured is now1014    // true), so both slots are exactly DURESS_SLOT_SIZE+tag at rest and their1015    // lengths cannot reveal that duress is configured (audit MEDIUM).1016    const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);1017    const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");1018    await writeSlot(SLOT_B, {1019      version: 1,1020      salt: hex(decoySalt),1021      nonce,1022      ciphertext,1023      tag,1024    });1025  } finally {1026    zeroKey(decoyKey);1027  }10281029  // Re-encrypt slot A with the duressConfigured flag set to true. No external1030  // flag is written — the bit lives inside the encrypted envelope.1031  duressConfigured = true;1032  await persistSlotA();1033}10341035export async function disableDuress(): Promise<void> {1036  if (!derivedKey || vaultMode !== "real") {1037    throw new Error("vault must be unlocked in real mode");1038  }1039  await ensureMigrated();10401041  // Overwrite slot B with fresh noise that matches slot A's size. The slot1042  // remains occupied so its mere existence does not signal that duress was1043  // ever configured.1044  const slotA = await loadSlot(SLOT_A);1045  if (slotA) {1046    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));1047  }10481049  duressConfigured = false;1050  await persistSlotA();1051}10521053// L14/COR-015: this function intentionally checks slot A (real vault) only.1054// A duress-mode user attempting changePassword is rejected earlier by the1055// vaultMode === 'decoy' check at changePassword. The real-vs-decoy1056// distinction here is by design — duress users cannot rotate the real1057// password by guessing it, and the asymmetry in error timing is acceptable1058// because duress mode is opt-in and the user knows their own decoy key.1059export async function verifyMainPassword(password: string): Promise<boolean> {1060  await ensureMigrated();1061  const slotA = await loadSlot(SLOT_A);1062  if (!slotA) return false;1063  const key = await deriveKey(password, unhex(slotA.salt));1064  try {1065    return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;1066  } finally {1067    zeroKey(key);1068  }1069}10701071export async function unlock(password: string): Promise<boolean> {1072  await ensureMigrated();10731074  // Load both slots in parallel. Both always exist post-migration; the1075  // parallel load and the parallel derivation below keep wall-clock time1076  // constant regardless of which slot's passphrase (real or decoy) the1077  // caller supplied, so a timing side channel cannot distinguish the1078  // duress path from the real-unlock path (DUR-002).1079  const [slotA, slotB] = await Promise.all([1080    loadSlot(SLOT_A),1081    loadSlot(SLOT_B),1082  ]);10831084  // Derive both keys in parallel, unconditionally.1085  const [keyA, keyB] = await Promise.all([1086    slotA ? deriveKey(password, unhex(slotA.salt)) : Promise.resolve(null),1087    slotB ? deriveKey(password, unhex(slotB.salt)) : Promise.resolve(null),1088  ]);10891090  // Attempt both decrypts in parallel. The Result variant lets us distinguish1091  // 'wrong_key' from 'corrupted' so callers can offer a history-restore path1092  // when a slot's schema is invalid even though AES-GCM authenticated (M7).1093  const [resultA, resultB] = await Promise.all([1094    keyA && slotA1095      ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")1096      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1097    keyB && slotB1098      ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")1099      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1100  ]);1101  const payloadA = resultA.status === "ok" ? resultA.payload : null;1102  const payloadB = resultB.status === "ok" ? resultB.payload : null;11031104  if (payloadA && keyA) {1105    derivedKey = keyA;1106    void saveSessionKey(keyA, "real");1107    vaultMode = "real";1108    entries = payloadA.entries;1109    duressConfigured = payloadA.duressConfigured;1110    buildDomainIndexSync(entries);1111    await loadSettings();1112    touchAutoLock();1113    if (keyB) zeroKey(keyB);11141115    // slotA is non-null when payloadA is truthy (keyA was derived from slotA).1116    if (slotA) {1117      const needsRecoverySetup =1118        !slotA.recovery_salt || !slotA.recovery_wrapped_root_key;1119      if (!needsRecoverySetup) {1120        rootKey = await deriveRootKeyFromDerivedKey(keyA, slotA);1121      }1122      // Pre-v2.12 vault, or a vault whose pw_root_* fields haven't been written1123      // yet: generate the recovery escrow and seed pw_root_* so subsequent1124      // unlocks can rehydrate rootKey without the user's recovery words.1125      // Best-effort — a failure here must not block unlock.1126      if (needsRecoverySetup || !rootKey) {1127        try {1128          await migrateToRecovery();1129          if (needsRecoverySetup) {1130            // String "1" matches the popup's existing peach_recovery_pending1131            // check; surfaced so the user re-confirms recovery words after a1132            // legacy-vault unlock (H2/COR-006).1133            await chrome.storage.local.set({ peach_recovery_pending: '1' });1134          }1135        } catch (migrationErr) {1136          console.warn('[Peach] recovery migration failed:', migrationErr);1137        }1138      }1139    }11401141    // If the payload had a pre-v2.11.0 shape (legacy passkey type, flat1142    // passkey fields, or pre-A-2 created/updated keys), rewrite it now so1143    // the next save uses the new format and migration doesn't re-run forever.1144    if (payloadA.migratedFromLegacy) {1145      await persistSlotA();1146    }1147    return true;1148  }11491150  if (payloadB && keyB) {1151    derivedKey = keyB;1152    void saveSessionKey(keyB, "decoy");1153    vaultMode = "decoy";1154    entries = payloadB.entries;1155    duressConfigured = false;1156    buildDomainIndexSync(entries);1157    await loadSettings();1158    touchAutoLock();1159    if (keyA) zeroKey(keyA);1160    return true;1161  }11621163  if (keyA) zeroKey(keyA);1164  if (keyB) zeroKey(keyB);1165  // Surface corruption (good AES tag, broken schema) distinctly from1166  // wrong-password so the popup can offer history-restore (M7/COR-007).1167  if (resultA.status === "corrupted") {1168    lastUnlockFailureReason = resultA.reason;1169  } else if (resultB.status === "corrupted") {1170    lastUnlockFailureReason = resultB.reason;1171  }1172  return false;1173}11741175// ---------------------------------------------------------------------------1176// MV3 service worker session key — survives SW restarts within a browser session1177// ---------------------------------------------------------------------------11781179// chrome.storage.session is cleared on browser close; survives SW restart.1180// Firefox does not implement it (persistent background script, no restart risk).1181const SESSION_KEY_STORAGE = "peach_session_dk";11821183async function saveSessionKey(key: Uint8Array, mode: "real" | "decoy"): Promise<void> {1184  if (!chrome.storage.session) return;1185  await chrome.storage.session.set({ [SESSION_KEY_STORAGE]: { keyHex: hex(key), mode } });1186}11871188async function clearSessionKey(): Promise<void> {1189  if (!chrome.storage.session) return;1190  await chrome.storage.session.remove(SESSION_KEY_STORAGE);1191}11921193/**1194 * On SW restart, re-derive all in-memory vault state from the session key1195 * stored in chrome.storage.session (set at unlock time, cleared on lock).1196 * Returns true if the vault was restored, false if no session key was found.1197 * No-ops if the vault is already unlocked.1198 */1199export async function restoreFromSession(): Promise<boolean> {1200  if (derivedKey !== null) return true;1201  if (!chrome.storage.session) return false;1202  const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);1203  const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;1204  if (!entry?.keyHex) return false;12051206  const key = unhex(entry.keyHex);1207  const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;1208  const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";1209  const slot = await loadSlot(slotKey);1210  if (!slot) { await clearSessionKey(); return false; }12111212  const result = await tryDecryptSlotResult(slot, key, aadTag);1213  if (result.status !== "ok") { await clearSessionKey(); return false; }12141215  derivedKey = key;1216  vaultMode = entry.mode;1217  entries = result.payload.entries;1218  duressConfigured = entry.mode === "real" ? result.payload.duressConfigured : false;1219  buildDomainIndexSync(entries);1220  await loadSettings();1221  touchAutoLock();12221223  if (entry.mode === "real" && slot.recovery_salt && slot.recovery_wrapped_root_key) {1224    try { rootKey = await deriveRootKeyFromDerivedKey(key, slot); } catch { /* non-fatal */ }1225  }12261227  return true;1228}12291230export function lock(): void {1231  void clearSessionKey();1232  if (derivedKey) {1233    zeroKey(derivedKey);1234    derivedKey = null;1235  }1236  if (rootKey) {1237    rootKey.fill(0);1238    rootKey = null;1239  }12401241  entries = [];1242  domainIndex = new Map();1243  vaultMode = "real";1244  duressConfigured = false;1245  clearAutoLock();1246}12471248export function isUnlocked(): boolean {1249  return derivedKey !== null;1250}12511252// Opens the vault using a pre-derived AES-256 key (skipping Argon2id).1253// Used by Android biometric unlock — the key was derived on the native side.1254export async function unlockWithKey(1255  masterKeyHex: string,1256): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {1257  try {1258    const masterKeyBytes = unhex(masterKeyHex);1259    const stored = await loadSlot(SLOT_A);1260    if (!stored) return { ok: false, error: "invalid_key" };1261    const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");1262    if (!payload) return { ok: false, error: "invalid_key" };12631264    derivedKey = masterKeyBytes;1265    vaultMode = "real";1266    entries = payload.entries;1267    duressConfigured = payload.duressConfigured;1268    buildDomainIndexSync(entries);1269    await loadSettings();1270    touchAutoLock();1271    return { ok: true, entries };1272  } catch {1273    return { ok: false, error: "invalid_key" };1274  }1275}12761277/**1278 * Restore the vault from a parsed Peach Codex payload.1279 *1280 * The supplied passphrase is verified against the Codex's slotA *before* any1281 * storage mutation — wrong passphrases return without touching disk. On1282 * success, the current vault state is snapshotted (reason: "restore") so the1283 * user can revert via Settings -> Vault History, then slotA/slotB are written1284 * and `peach_last_modified_at` is set to the Codex's recorded timestamp. A1285 * regular `unlock()` follows so the rest of the SW sees the standard1286 * post-unlock state.1287 *1288 * Intentionally non-Pro-gated — see peach_codex_v2.md "Pro gating". A Codex1289 * printed by a Pro user must always be restorable, even on a free device.1290 *1291 * Timing is not held constant here (in contrast to `unlock`): the Codex flow1292 * is an explicit user action with a known passphrase, not a passive lock1293 * screen, so the duress-vs-real timing side channel does not apply.1294 */1295export async function unlockFromCodex(params: {1296  slotA: string; // JSON string of StoredVault for slot A1297  slotB: string | null; // JSON string of StoredVault for slot B, or null1298  timestamp: number;1299  masterPassphrase: string;1300}): Promise<1301  | { ok: true; entryCount: number }1302  | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" }1303> {1304  let parsedSlotA: StoredVault;1305  let parsedSlotB: StoredVault | null = null;1306  try {1307    const rawA = JSON.parse(params.slotA) as unknown;1308    if (!hasValidVaultSchema(rawA)) {1309      return { ok: false, reason: "invalid_slot_format" };1310    }1311    parsedSlotA = rawA;1312    if (params.slotB !== null) {1313      const rawB = JSON.parse(params.slotB) as unknown;1314      if (!hasValidVaultSchema(rawB)) {1315        return { ok: false, reason: "invalid_slot_format" };1316      }1317      parsedSlotB = rawB;1318    }1319  } catch {1320    return { ok: false, reason: "invalid_slot_format" };1321  }13221323  // Verify the passphrase against the supplied slotA WITHOUT writing anything.1324  // If this fails the on-disk vault is left completely untouched.1325  const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));1326  const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");1327  if (!trialPayload) {1328    zeroKey(trialKey);1329    return { ok: false, reason: "wrong_passphrase" };1330  }1331  // Drop the trial key; `unlock()` below derives its own copy. Holding two1332  // copies of the master key in memory at once would be a needless surface.1333  zeroKey(trialKey);13341335  // Snapshot the about-to-be-overwritten on-disk state so the user can revert1336  // a mistaken Codex restore via the Vault History UI. Non-fatal if it fails.1337  await takeVaultSnapshot("restore");13381339  await writeSlot(SLOT_A, parsedSlotA);1340  if (parsedSlotB) {1341    await writeSlot(SLOT_B, parsedSlotB);1342  } else {1343    // Slot B must always exist with ciphertext length matching slot A1344    // (Projects.md §3.2). Codex prints may omit slot B (duress wasn't1345    // configured); regenerate noise to satisfy the invariant.1346    await writeSlot(1347      SLOT_B,1348      generateNoiseBlob(parsedSlotA.ciphertext.length / 2),1349    );1350  }1351  await chrome.storage.local.set({1352    peach_last_modified_at: String(params.timestamp),1353  });13541355  // Standard unlock path so domain index, settings, auto-lock, and1356  // recovery-key state all populate exactly as a normal unlock would.1357  const ok = await unlock(params.masterPassphrase);1358  if (!ok) {1359    // Should be unreachable — we just verified the passphrase against the1360    // same slotA we wrote. Treat as wrong_passphrase to keep the contract1361    // simple if some race or storage anomaly intrudes.1362    return { ok: false, reason: "wrong_passphrase" };1363  }1364  return { ok: true, entryCount: getEntries().length };1365}13661367// Returns the current in-memory derived key as a hex string.1368// Used by the biometric enable flow in Settings to store the key in Android Keystore.1369export function getDerivedKeyHex(): string {1370  if (!derivedKey) throw new Error("vault_not_unlocked");1371  return hex(derivedKey);1372}13731374/**1375 * Returns the vault's stable root key as hex, or null when locked / not yet1376 * populated. The root key is random per-vault, generated at creation, escrowed1377 * under the recovery words, and re-wrapped (not regenerated) on every password1378 * change — so it is INVARIANT across password rotation, unlike getDerivedKeyHex.1379 *1380 * This is the correct input for sync identity derivation (vault_id, the Noise1381 * XX static key, the Ed25519 manifest signing key, and per-entry envelope1382 * keys): paired devices keep the same identity and can still decrypt each1383 * other's entries after either side rotates its master password (SEV-2-B).1384 *1385 * Returns null rather than throwing so sync callers degrade to VAULT_LOCKED1386 * instead of crashing; rootKey is populated on every real-mode unlock via1387 * deriveRootKeyFromDerivedKey / migrateToRecovery.1388 */1389export function getRootKeyHex(): string | null {1390  return rootKey ? hex(rootKey) : null;1391}13921393export function getEntries(): VaultEntry[] {1394  if (!derivedKey) throw new Error("vault_locked");1395  return entries.filter((entry) => !entry.deletedAt);1396}13971398const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;13991400export function getIdentities(): SavedIdentity[] {1401  if (!derivedKey) throw new Error("vault_locked");1402  const active = entries.filter((e) => !e.deletedAt && e.type === "login");14031404  const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();1405  const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();14061407  for (const entry of active) {1408    const domain = extractDomain(entry.url ?? "") ?? "";1409    const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;14101411    function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {1412      const existing = map.get(v);1413      if (!existing || modifiedAt > existing.lastUsed) {1414        map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });1415      } else {1416        map.set(v, { ...existing, count: existing.count + 1 });1417      }1418    }14191420    const uVal = entry.username?.trim();1421    if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);14221423    // Also count the dedicated email field — entries created via the inline1424    // popup new-entry form store email here rather than in username.1425    const eVal = entry.email?.trim();1426    if (eVal) tally(emailMap, eVal);1427  }14281429  const toIdentity = (type: "email" | "username") =>1430    ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({1431      value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,1432    });14331434  return [1435    ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),1436    ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),1437  ];1438}14391440export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {1441  if (!derivedKey) throw new Error("vault_locked");14421443  const now = Date.now();1444  const added: VaultEntry[] = [];1445  for (const draft of drafts) {1446    try {1447      const sanitized = sanitizeEntryDraft(draft);1448      const nextEntry: VaultEntry = {1449        ...sanitized,1450        id: crypto.randomUUID(),1451        createdAt: now,1452        modifiedAt: monotonicEntryTimestamp(),1453      };1454      entries.push(nextEntry);1455      added.push(nextEntry);1456    } catch {1457      // Skip invalid drafts silently — caller can see diff between input and output length1458    }1459  }14601461  if (added.length > 0) {1462    await persistEntries();1463  }14641465  return added;1466}14671468/**1469 * Restore a set of entries in full fidelity — preserves id, createdAt,1470 * modifiedAt, and every other field unlike `batchAddEntries` which1471 * assigns fresh identity. Used by restore paths where the backup is the1472 * authoritative source of truth. `mode` controls how entries already in1473 * the vault are treated.1474 */1475export async function restoreEntries(1476  incoming: VaultEntry[],1477  mode: "replace" | "merge"1478): Promise<{ added: number; updated: number; skipped: number }> {1479  if (!derivedKey) throw new Error("vault_locked");14801481  // A replace with zero incoming entries is almost certainly a caller bug1482  // (e.g. an import that silently dropped everything). Refuse rather than1483  // wipe the vault.1484  if (mode === "replace" && incoming.length === 0) {1485    throw new Error("refuse to replace with empty entry set");1486  }14871488  let added = 0;1489  let updated = 0;1490  let skipped = 0;14911492  if (mode === "replace") {1493    entries = [];1494    for (const entry of incoming) {1495      const normalized = sanitizeRestoredEntry(entry);1496      if (!normalized) {1497        skipped += 1;1498        continue;1499      }1500      entries.push(normalized);1501      added += 1;1502    }1503  } else {1504    const byId = new Map<string, VaultEntry>();1505    for (const e of entries) byId.set(e.id, e);15061507    for (const entry of incoming) {1508      const normalized = sanitizeRestoredEntry(entry);1509      if (!normalized) {1510        skipped += 1;1511        continue;1512      }1513      const existing = byId.get(normalized.id);1514      if (!existing) {1515        entries.push(normalized);1516        added += 1;1517      } else if (normalized.modifiedAt > existing.modifiedAt) {1518        const idx = entries.findIndex((e) => e.id === existing.id);1519        if (idx !== -1) {1520          entries[idx] = normalized;1521          updated += 1;1522        }1523      } else {1524        skipped += 1;1525      }1526    }1527  }15281529  await persistEntries("import");1530  return { added, updated, skipped };1531}15321533/**1534 * Validate + normalise a VaultEntry coming from a backup, import, or sync1535 * peer. MV-6: this is a strict field WHITELIST — `normalizeEntry` copies1536 * only known VaultEntry fields (unknown/attacker keys are dropped), and1537 * nested `passkey`/`canary` shapes are rebuilt field-by-field, never1538 * spread. Returns null for values the live vault shouldn't accept.1539 */1540function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {1541  if (!entry || typeof entry !== "object") return null;1542  const title = typeof entry.title === "string" ? entry.title.trim() : "";1543  if (!title) return null;1544  const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();1545  const now = Date.now();1546  const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;1547  const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;15481549  // normalizeEntry whitelists every known VaultEntry field and runs the1550  // same legacy-passkey migration as the on-disk read path — pre-v2.11.01551  // backups with flat passkey fields still import correctly because the1552  // legacy flat fields are themselves whitelisted VaultEntry members.1553  const normalized = normalizeEntry({1554    ...entry,1555    id,1556    title,1557    type: entry.type ?? "login",1558    createdAt,1559    modifiedAt,1560  });15611562  if (normalized.passkey) {1563    normalized.passkey = sanitizePasskey(normalized.passkey);1564  }1565  if (normalized.canary) {1566    normalized.canary = sanitizeCanary(normalized.canary);1567  }15681569  // Login entries from backup must carry a password (or be passkey-only,1570  // in which case the passkey sub-object replaces the password requirement).1571  if (1572    normalized.type === "login" &&1573    !normalized.passkey &&1574    typeof normalized.password !== "string"1575  ) {1576    return null;1577  }1578  if (entry.passkey && !normalized.passkey) {1579    // Entry claimed a passkey but the shape didn't validate — refuse the1580    // whole entry rather than silently importing a credential-less husk.1581    return null;1582  }15831584  return normalized;1585}15861587/**1588 * Rebuild a PasskeyData object from untrusted input, field by field.1589 * Returns undefined when required fields are missing/mistyped — a rogue1590 * passkey credential must not activate via import (MV-6 attack scenario).1591 */1592function sanitizePasskey(pk: unknown): PasskeyData | undefined {1593  if (!pk || typeof pk !== "object") return undefined;1594  const r = pk as Record<string, unknown>;1595  if (1596    typeof r.rpId !== "string" || !r.rpId ||1597    typeof r.credentialId !== "string" || !r.credentialId ||1598    typeof r.publicKeyCose !== "string" ||1599    typeof r.userHandle !== "string" ||1600    typeof r.userName !== "string"1601  ) {1602    return undefined;1603  }1604  return {1605    rpId: r.rpId,1606    rpName: typeof r.rpName === "string" ? r.rpName : r.rpId,1607    credentialId: r.credentialId,1608    publicKeyCose: r.publicKeyCose,1609    privateKeyJwk:1610      r.privateKeyJwk && typeof r.privateKeyJwk === "object"1611        ? (r.privateKeyJwk as JsonWebKey)1612        : undefined,1613    userHandle: r.userHandle,1614    userName: r.userName,1615    userDisplayName:1616      typeof r.userDisplayName === "string" ? r.userDisplayName : r.userName,1617    algorithm: r.algorithm === -8 ? -8 : -7,1618    signCount: typeof r.signCount === "number" ? r.signCount : 0,1619    aaguid: typeof r.aaguid === "string" ? r.aaguid : "",1620    backupEligible: r.backupEligible === true,1621    backupState: r.backupState === true,1622    lastUsedAt: typeof r.lastUsedAt === "number" ? r.lastUsedAt : undefined,1623    browser: r.browser === "chrome" || r.browser === "firefox" ? r.browser : undefined,1624    transports: Array.isArray(r.transports)1625      ? r.transports.filter((t): t is string => typeof t === "string")1626      : undefined,1627    createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),1628  };1629}16301631/**1632 * Rebuild a Canary object from untrusted input. The webhook must be a1633 * well-formed HTTPS URL — a poisoned canary.webhookUrl is a standing1634 * exfiltration endpoint that the canary subsystem will POST entry titles1635 * to (MV-6 attack scenario). Invalid → the canary is dropped, not the1636 * entry. FIRE_CANARY_PING re-validates with the full SSRF guard at fire1637 * time (isAllowedCanaryWebhookUrl), so this import-time check is the1638 * outer of two gates.1639 */1640function sanitizeCanary(c: unknown): Canary | undefined {1641  if (!c || typeof c !== "object") return undefined;1642  const r = c as Record<string, unknown>;1643  if (typeof r.webhookUrl !== "string") return undefined;1644  let url: URL;1645  try {1646    url = new URL(r.webhookUrl);1647  } catch {1648    return undefined;1649  }1650  if (url.protocol !== "https:") return undefined;1651  return {1652    webhookUrl: url.toString(),1653    label: typeof r.label === "string" ? r.label : undefined,1654    lastPinged: typeof r.lastPinged === "number" ? r.lastPinged : undefined,1655    pingCount: typeof r.pingCount === "number" ? r.pingCount : undefined,1656  };1657}16581659// Soft-deletes every non-deleted entry in one call. The literal string1660// argument is a tripwire against accidental calls — any caller that would1661// wipe the vault has to consciously type "REPLACE_ALL". Do not relax this1662// to a boolean.1663export async function clearVaultEntries(1664  confirmation: "REPLACE_ALL"1665): Promise<void> {1666  if (confirmation !== "REPLACE_ALL") {1667    throw new Error("clearVaultEntries requires explicit confirmation");1668  }1669  if (!derivedKey) throw new Error("vault_locked");1670  for (const entry of entries) {1671    if (!entry.deletedAt) {1672      const stamp = monotonicEntryTimestamp(entry.modifiedAt);1673      entry.deletedAt = stamp;1674      entry.modifiedAt = stamp;1675    }1676  }1677  await persistEntries();1678}16791680export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {1681  if (!derivedKey) throw new Error("vault_locked");16821683  const sanitized = sanitizeEntryDraft(entry);1684  const now = Date.now();1685  const stamp = monotonicEntryTimestamp();1686  const nextEntry: VaultEntry = {1687    ...sanitized,1688    id: crypto.randomUUID(),1689    createdAt: now,1690    modifiedAt: stamp,1691    // Stamp passwordChangedAt at creation so age tracking is accurate from1692    // day one. Non-login entries carry the same stamp harmlessly.1693    passwordChangedAt: sanitized.password ? stamp : undefined,1694  };16951696  // Clone-and-replace so a failed persist rolls back the in-memory state1697  // (COR-008). Without this, a quota-full or storage error leaves the1698  // module-level `entries` ahead of what's actually on disk.1699  const rollback = entries;1700  entries = [...entries, nextEntry];1701  try {1702    await persistEntries();1703  } catch (err) {1704    entries = rollback;1705    throw err;1706  }17071708  // Fire-and-forget breach check (only for login entries if breach monitoring is enabled or not set)1709  if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {1710    checkBreach(nextEntry.password).then(async (count) => {1711      if (count > 0) {1712        const idx = entries.findIndex((e) => e.id === nextEntry.id);1713        if (idx !== -1) {1714          entries[idx] = { ...entries[idx], breach: count, modifiedAt: monotonicEntryTimestamp(entries[idx].modifiedAt) };1715          await persistEntries();1716        }1717      }1718    });1719  }17201721  fireSyncTrigger("vault_change");17221723  return nextEntry;1724}17251726/**1727 * Run the passkey-merge pass on the live in-memory entries and persist if1728 * anything changed. Called immediately after any passkey registration so that1729 * a same-domain TOTP-only entry already in the vault gets consolidated right1730 * away instead of waiting until the next lock/unlock cycle.1731 */1732export async function consolidatePasskeyEntries(): Promise<void> {1733  if (!derivedKey) return;1734  const { merged } = mergePasskeyOnlyIntoLogins(entries);1735  if (merged) {1736    await persistEntries();1737  }1738}17391740export async function updateEntry(1741  id: string,1742  patch: Partial<VaultEntry>1743): Promise<void> {1744  if (!derivedKey) throw new Error("vault_locked");17451746  const idx = entries.findIndex((entry) => entry.id === id);1747  if (idx === -1 || entries[idx].deletedAt) {1748    throw new Error("entry_not_found");1749  }17501751  const current = entries[idx];1752  const sanitizedPatch = sanitizeEntryPatch(patch);1753  // Refresh passwordChangedAt only when the password value actually changes —1754  // a metadata-only update (title, tags, etc.) must not reset the age clock1755  // that drives the Pro health rotation recommendation.1756  const passwordChanged =1757    "password" in patch &&1758    typeof sanitizedPatch.password === "string" &&1759    sanitizedPatch.password !== current.password;1760  const stamp = monotonicEntryTimestamp(current.modifiedAt);1761  // When the password actually changes, push the outgoing one onto the history1762  // (newest first) so the user can reveal/copy/restore it later. We record the1763  // age it carried (passwordChangedAt, falling back to createdAt) rather than1764  // `now`, so the list reflects when each password was last in effect. Only1765  // capture a non-empty prior value — clearing a password leaves no secret to1766  // keep, and we skip an immediate exact duplicate (e.g. restore-then-restore)1767  // to avoid noise.1768  const priorPassword = current.password;1769  const shouldCapture =1770    passwordChanged &&1771    typeof priorPassword === "string" &&1772    priorPassword.length > 0 &&1773    current.passwordHistory?.[0]?.password !== priorPassword;1774  const nextHistory = shouldCapture1775    ? [1776        { password: priorPassword!, changedAt: current.passwordChangedAt ?? current.createdAt },1777        ...(current.passwordHistory ?? []),1778      ].slice(0, PASSWORD_HISTORY_MAX)1779    : current.passwordHistory;1780  entries[idx] = {1781    ...current,1782    ...sanitizedPatch,1783    modifiedAt: stamp,1784    ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),1785  };1786178717881789  // Card entries must retain their card number1790  if (entries[idx].type === "card" && !entries[idx].cardNumber) {1791    entries[idx] = current;1792    throw new Error("card number is required for card entries");1793  }17941795  // Roll the in-memory entry back to its pre-edit state if the disk write1796  // fails (e.g. storage quota). Without this the module-level `entries` array1797  // would hold an edit that never landed on disk, diverging from the vault1798  // until the next unlock silently reverts it (SEV-3-A). Mirrors addEntry.1799  try {1800    await persistEntries();1801  } catch (err) {1802    entries[idx] = current;1803    throw err;1804  }18051806  // Breach check when password changes: clear immediately so old breach doesn't linger,1807  // then async-check the new password and only re-set if it's also found.1808  if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {1809    entries[idx] = { ...entries[idx], breach: undefined };1810    await persistEntries();1811    const password = entries[idx].password;1812    if (password) {1813      checkBreach(password).then(async (count) => {1814        const i = entries.findIndex((e) => e.id === id);1815        if (i !== -1 && count > 0) {1816          entries[i] = { ...entries[i], breach: count, modifiedAt: monotonicEntryTimestamp(entries[i].modifiedAt) };1817          await persistEntries();1818        }1819      });1820    }1821  }18221823  fireSyncTrigger("vault_change");1824}18251826export async function deleteEntry(id: string): Promise<void> {1827  if (!derivedKey) throw new Error("vault_locked");18281829  const entry = entries.find((item) => item.id === id);1830  if (!entry || entry.deletedAt) {1831    throw new Error("entry_not_found");1832  }18331834  // Tombstone timestamp must be strictly greater than the entry's last1835  // modification so the deletion wins LWW against any in-flight edit, even1836  // under clock skew (SEV-2-E).1837  const previousModifiedAt = entry.modifiedAt;1838  const stamp = monotonicEntryTimestamp(entry.modifiedAt);1839  entry.deletedAt = stamp;1840  entry.modifiedAt = stamp;1841  // Roll the tombstone back if the disk write fails, so a quota error doesn't1842  // leave the entry deleted in memory but alive on disk (SEV-3-A).1843  try {1844    await persistEntries();1845  } catch (err) {1846    delete entry.deletedAt;1847    entry.modifiedAt = previousModifiedAt;1848    throw err;1849  }1850  fireSyncTrigger("vault_change");1851}18521853export function getDeletedEntries(): VaultEntry[] {1854  if (!derivedKey) return [];1855  return entries.filter((e) => !!e.deletedAt);1856}18571858/**1859 * Returns the vault's monotonic version — the `peach_last_modified_at` value1860 * stamped on every user-initiated write. Remote (sync) writes do NOT advance1861 * this version so a sync round never cascades into a second outbound sync.1862 */1863export async function getVaultVersion(): Promise<number> {1864  try {1865    const raw = await chrome.storage.local.get("peach_last_modified_at");1866    const v = (raw as Record<string, unknown>).peach_last_modified_at;1867    if (typeof v === "number") return v;1868    if (typeof v === "string" && v !== "") {1869      const n = Number.parseInt(v, 10);1870      return Number.isFinite(n) ? n : 0;1871    }1872    return 0;1873  } catch {1874    return 0;1875  }1876}18771878/**1879 * Internal write variants — bypass `fireSyncTrigger` so the sync layer can1880 * apply entries without cascading into another outbound sync round.1881 *1882 * INVARIANT: callers must not pass entries whose IDs collide with existing1883 * active (non-deleted) entries unless the intent is an explicit overwrite.1884 * These functions do not validate field-level constraints (password required,1885 * card number required, etc.) — they are trust-the-caller paths for sync and1886 * test harness use only.1887 */1888export async function addEntryDirect(entry: VaultEntry): Promise<void> {1889  if (!derivedKey) throw new Error("vault_locked");1890  entries = [...entries, entry];1891  await persistEntries("sync_received");1892}18931894export async function updateEntryDirect(patch: VaultEntry): Promise<void> {1895  if (!derivedKey) throw new Error("vault_locked");1896  const idx = entries.findIndex((e) => e.id === patch.id);1897  if (idx === -1) throw new Error("entry_not_found");1898  entries[idx] = { ...entries[idx], ...patch };1899  await persistEntries("sync_received");1900}19011902export async function deleteEntryDirect(id: string, deletedAt: number): Promise<void> {1903  if (!derivedKey) throw new Error("vault_locked");1904  const idx = entries.findIndex((e) => e.id === id);1905  if (idx === -1) throw new Error("entry_not_found");1906  entries[idx] = { ...entries[idx], deletedAt, modifiedAt: deletedAt };1907  await persistEntries("sync_received");1908}19091910/**1911 * Apply a batch of remote entries + tombstones from a chirp-sync peer.1912 * Last-write-wins by `modifiedAt`; a tombstone supersedes a live entry when1913 * `deletedAt > modifiedAt` on the local side. Mutates `entries` directly and1914 * persists with reason `sync_received` — does NOT fire the sync dispatcher, so1915 * applying a sync round cannot cascade into another outbound sync.1916 *1917 * `applied` counts entries that actually changed local state (new add,1918 * overwrite-by-newer, or new tombstone). `received` is the raw payload size1919 * the caller can surface in the sync result UI.1920 */1921export async function applyMergedRemoteEntries(1922  remoteEntries: VaultEntry[],1923  remoteTombstones: Record<string, number>,1924  context: { deviceName?: string } = {},1925): Promise<{ received: number; applied: number; conflicts: number }> {1926  // DESIGN: last-write-wins is applied PER-ENTRY, not per-field. If two devices1927  // concurrently edit different fields of the same entry, the one with the1928  // newer modifiedAt wins the whole entry and the other device's field edits1929  // are dropped silently. This is the deliberate trade-off for a simple,1930  // conflict-free merge — per-field CRDT merge is out of scope. Guidance for1931  // users: edit a given entry on one device at a time.1932  if (!derivedKey) throw new Error("vault_locked");19331934  const received = remoteEntries.length + Object.keys(remoteTombstones).length;1935  let applied = 0;1936  let conflicts = 0;19371938  const byId = new Map<string, VaultEntry>();1939  for (const e of entries) byId.set(e.id, e);19401941  const alerts: SyncAlert[] = [];1942  const deviceName = context.deviceName ?? "paired device";1943  const mergeNow = Date.now();19441945  for (const remote of remoteEntries) {1946    const sanitized = sanitizeRestoredEntry(remote);1947    if (!sanitized) continue;1948    // HV-1a: a far-future remote modifiedAt must not permanently pin a1949    // malicious value against honest local edits. Clamp BEFORE any1950    // comparison against local timestamps.1951    sanitized.modifiedAt = clampSyncTimestamp(sanitized.modifiedAt, mergeNow);1952    if (typeof sanitized.deletedAt === "number") {1953      sanitized.deletedAt = clampSyncTimestamp(sanitized.deletedAt, mergeNow);1954    }1955    const tombstoneTs = remoteTombstones[sanitized.id];1956    if (tombstoneTs !== undefined && clampSyncTimestamp(tombstoneTs, mergeNow) >= sanitized.modifiedAt) {1957      continue;1958    }1959    const local = byId.get(sanitized.id);1960    if (!local) {1961      entries.push(sanitized);1962      byId.set(sanitized.id, sanitized);1963      applied += 1;1964    } else if (sanitized.modifiedAt > local.modifiedAt) {1965      const idx = entries.findIndex((e) => e.id === local.id);1966      if (idx !== -1) {1967        // HV-1b: surface remote password REPLACEMENTS (existing id, password1968        // differs) so a compromised peer can't silently rewrite credentials.1969        if (1970          !local.deletedAt &&1971          typeof sanitized.password === "string" &&1972          typeof local.password === "string" &&1973          sanitized.password !== local.password1974        ) {1975          alerts.push({1976            type: "REMOTE_PASSWORD_CHANGE",1977            entryId: sanitized.id,1978            entryTitle: sanitized.title,1979            deviceName,1980            timestamp: mergeNow,1981          });1982        }1983        entries[idx] = sanitized;1984        byId.set(sanitized.id, sanitized);1985        applied += 1;1986        if (!local.deletedAt) conflicts += 1;1987      }1988    }1989  }19901991  for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {1992    if (typeof rawDeletedAt !== "number" || !Number.isFinite(rawDeletedAt)) continue;1993    // HV-1a/1c: clamp the tombstone timestamp before every comparison.1994    const deletedAt = clampSyncTimestamp(rawDeletedAt, mergeNow);1995    const local = byId.get(id);1996    if (!local) continue;1997    if (local.deletedAt && local.deletedAt >= deletedAt) continue;1998    if (deletedAt < local.modifiedAt) continue;1999    const idx = entries.findIndex((e) => e.id === id);2000    if (idx !== -1) {2001      // HV-1b: surface remote deletes of live local entries.2002      if (!local.deletedAt) {2003        alerts.push({2004          type: "REMOTE_DELETE",2005          entryId: id,2006          entryTitle: local.title,2007          deviceName,2008          timestamp: mergeNow,2009        });2010      }2011      entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };2012      applied += 1;2013    }2014  }20152016  if (applied > 0) {2017    await persistEntries("sync_received");2018    buildDomainIndexSync(entries);2019  }2020  // Queued after the merge committed — an alert must describe a mutation2021  // that actually landed. recordSyncAlerts never throws.2022  await recordSyncAlerts(alerts);2023  return { received, applied, conflicts };2024}20252026export async function restoreEntry(id: string): Promise<void> {2027  if (!derivedKey) throw new Error("vault_locked");2028  const entry = entries.find((e) => e.id === id && e.deletedAt);2029  if (!entry) throw new Error("deleted entry not found");2030  delete entry.deletedAt;2031  entry.modifiedAt = monotonicEntryTimestamp(entry.modifiedAt);2032  await persistEntries();2033  buildDomainIndexSync(entries);2034}20352036export async function purgeEntry(id: string): Promise<void> {2037  if (!derivedKey) throw new Error("vault_locked");2038  const idx = entries.findIndex((e) => e.id === id && e.deletedAt);2039  if (idx === -1) throw new Error("deleted entry not found");2040  entries.splice(idx, 1);2041  await persistEntries();2042}20432044/** Permanently delete entries whose deletedAt is older than retentionMs. 0 = keep forever. */2045export async function purgeExpiredTrash(retentionMs: number): Promise<number> {2046  if (!derivedKey || retentionMs === 0) return 0;2047  const cutoff = Date.now() - retentionMs;2048  const before = entries.length;2049  entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));2050  const purged = before - entries.length;2051  if (purged > 0) await persistEntries();2052  return purged;2053}20542055export function queryDomain(domain: string): VaultEntry[] {2056  return domainIndex.get(domain) ?? [];2057}20582059export function getEntryById(id: string): VaultEntry | undefined {2060  return entries.find((entry) => entry.id === id && !entry.deletedAt);2061}20622063async function persistSlotA(2064  reason: VaultSnapshot["reason"] = "local_save",2065): Promise<StoredVault> {2066  if (!derivedKey) throw new Error("vault_locked");20672068  const slotA = await loadSlot(SLOT_A);2069  if (!slotA) throw new Error("missing slot A");20702071  // Snapshot the about-to-be-overwritten state BEFORE we mutate disk. Failures2072  // are swallowed by takeVaultSnapshot — history must never block a save.2073  await takeVaultSnapshot(reason);20742075  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);2076  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");20772078  // Preserve existing recovery escrow fields.2079  const nextSlotA: StoredVault = {2080    ...slotA,2081    nonce,2082    ciphertext,2083    tag,2084    // recovery_salt and recovery_wrapped_root_key are already set from loadSlot2085  };2086  await writeSlot(SLOT_A, nextSlotA);20872088  // Slot A (the real vault) is now committed. Wrap every later write so a2089  // mid-persist failure (e.g. a storage error after slot A landed) restores the2090  // prior slot A before rethrowing. Without this, a "failed" save that already2091  // wrote slot A leaves disk ahead of the in-memory rollback in addEntry/2092  // updateEntry/deleteEntry — the entry stays silently on disk and resurfaces2093  // as a duplicate on the next unlock (observed under storage-quota pressure).2094  try {2095    // When duress is not configured, keep slot B size-matched with slot A by2096    // regenerating its noise. When duress IS configured, leave slot B alone —2097    // we don't have the decoy key to re-encrypt it. This is a known trade-off.2098    if (!duressConfigured) {2099      await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));2100    }2101    // Only advance the vault version for locally-originated writes. Entries2102    // applied from a sync peer ("sync_received") must NOT bump the counter —2103    // otherwise applying a remote round makes us look newer than the peer and2104    // triggers a redundant outbound sync, defeating the no-op optimisation2105    // and risking a ping-pong between two devices (SEV-2-C).2106    if (reason !== "sync_received") {2107      await stampLocalVaultMutation();2108    }2109  } catch (err) {2110    // Best-effort restore — the prior slot A is smaller-or-equal, so this write2111    // fits even when the failure was a quota overflow.2112    await writeSlot(SLOT_A, slotA).catch(() => {});2113    throw err;2114  }21152116  return nextSlotA;2117}21182119async function persistSlotB(): Promise<void> {2120  if (!derivedKey) throw new Error("vault_locked");21212122  const slotB = await loadSlot(SLOT_B);2123  if (!slotB) throw new Error("missing slot B");21242125  // Decoy plaintext always reports duressConfigured=false — the decoy user2126  // sees a clean slate. persistSlotB only runs in decoy mode, which only2127  // exists once duress is configured, so pad to the fixed duress ceiling to2128  // keep slot B's length equal to slot A's (audit MEDIUM — deniability).2129  const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);2130  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");21312132  await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });2133  // Symmetric with persistSlotA: if the version stamp fails after the decoy2134  // slot committed, restore the prior slot B so a failed decoy-mode save can't2135  // leave disk ahead of the in-memory rollback.2136  try {2137    await stampLocalVaultMutation();2138  } catch (err) {2139    await writeSlot(SLOT_B, slotB).catch(() => {});2140    throw err;2141  }2142}21432144async function persistEntries(2145  reason: VaultSnapshot["reason"] = "local_save",2146): Promise<void> {2147  if (!derivedKey) throw new Error("vault_locked");21482149  if (vaultMode === "decoy") {2150    await persistSlotB();2151  } else {2152    await persistSlotA(reason);2153  }2154  buildDomainIndexSync(entries);2155}21562157function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {2158  if (!Array.isArray(values)) return undefined;2159  const seen = new Set<string>();2160  const cleaned: string[] = [];2161  for (const value of values) {2162    const trimmed = typeof value === "string" ? value.trim() : "";2163    if (!trimmed) continue;2164    const key = trimmed.toLowerCase();2165    if (seen.has(key)) continue;2166    seen.add(key);2167    cleaned.push(trimmed);2168  }2169  return cleaned.length > 0 ? cleaned : undefined;2170}21712172function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {2173  const title = entry.title.trim();2174  // Accept legacy `type:"passkey"` drafts but rewrite to "login" — the new2175  // model is "any entry, optionally with a passkey sub-object." Imports and2176  // any in-flight callers from before v2.11.0 keep working without throwing.2177  let type: VaultEntry["type"] = entry.type ?? "login";2178  if (type === "passkey") type = "login";21792180  if (!title) throw new Error("title is required");21812182  if (entry.passkey) {2183    const p = entry.passkey;2184    if (2185      !p.rpId ||2186      !p.credentialId ||2187      !p.publicKeyCose ||2188      !p.userHandle ||2189      !p.userName ||2190      (p.algorithm !== -7 && p.algorithm !== -8)2191    ) {2192      throw new Error("invalid passkey credential");2193    }2194  }2195  if (type === "card") {2196    if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {2197      throw new Error("cardholder name and card number are required");2198    }2199  }22002201  return {2202    type,2203    title,2204    username: type === "login" ? entry.username?.trim() ?? "" : undefined,2205    email: type === "login" ? entry.email?.trim() || undefined : undefined,2206    password: type === "login" ? entry.password : undefined,2207    url: type === "login" ? entry.url?.trim() ?? "" : undefined,2208    additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,2209    totp: type === "login" ? entry.totp?.trim() || undefined : undefined,2210    notes: entry.notes?.trim() || undefined,2211    breach: type === "login" ? entry.breach : undefined,2212    canary: type === "login" ? entry.canary : undefined,2213    tags: entry.tags,2214    passkey: entry.passkey,2215    cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,2216    cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,2217    expMonth: type === "card" ? entry.expMonth?.trim() : undefined,2218    expYear: type === "card" ? entry.expYear?.trim() : undefined,2219    cvc: type === "card" ? entry.cvc?.trim() : undefined,2220    cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,2221    network: type === "card" ? entry.network : undefined,2222    last4: type === "card" ? entry.last4?.trim() : undefined,2223  };2224}22252226function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {2227  const nextPatch: Partial<VaultEntry> = {};22282229  if ("type" in patch) {2230    nextPatch.type = patch.type;2231  }22322233  if ("title" in patch) {2234    const title = patch.title?.trim() ?? "";2235    if (!title) throw new Error("title is required");2236    nextPatch.title = title;2237  }22382239  if ("url" in patch) {2240    nextPatch.url = patch.url?.trim() ?? "";2241  }22422243  if ("additionalUrls" in patch) {2244    const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];2245    const seen = new Set<string>();2246    const cleaned: string[] = [];2247    for (const value of incoming) {2248      const trimmed = typeof value === "string" ? value.trim() : "";2249      if (!trimmed) continue;2250      const key = trimmed.toLowerCase();2251      if (seen.has(key)) continue;2252      seen.add(key);2253      cleaned.push(trimmed);2254    }2255    nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;2256  }22572258  if ("username" in patch) {2259    nextPatch.username = patch.username?.trim() ?? "";2260  }22612262  if ("email" in patch) {2263    nextPatch.email = patch.email?.trim() || undefined;2264  }22652266  if ("password" in patch) {2267    const password = patch.password ?? "";2268    // Allow clearing a password (e.g. on passkey-only entries)2269    nextPatch.password = password || undefined;2270  }22712272  if ("totp" in patch) {2273    nextPatch.totp = patch.totp?.trim() || undefined;2274  }22752276  if ("notes" in patch) {2277    nextPatch.notes = patch.notes?.trim() || undefined;2278  }22792280  if ("breach" in patch) {2281    nextPatch.breach = patch.breach;2282  }22832284  if ("canary" in patch) {2285    nextPatch.canary = patch.canary;2286  }22872288  if ("passkey" in patch) {2289    // Passkey sub-object replaces all the legacy flat passkey fields. A2290    // patch with `passkey: undefined` removes the credential from the entry2291    // (used by "remove passkey" without deleting the whole entry).2292    nextPatch.passkey = patch.passkey;2293  }22942295  if ("tags" in patch) {2296    nextPatch.tags = patch.tags;2297  }22982299  if ("cardholderName" in patch) {2300    nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;2301  }2302  if ("cardNumber" in patch) {2303    const n = patch.cardNumber ?? "";2304    nextPatch.cardNumber = n || undefined;2305  }2306  if ("expMonth" in patch) {2307    nextPatch.expMonth = patch.expMonth?.trim() || undefined;2308  }2309  if ("expYear" in patch) {2310    nextPatch.expYear = patch.expYear?.trim() || undefined;2311  }2312  if ("cvc" in patch) {2313    nextPatch.cvc = patch.cvc?.trim() || undefined;2314  }2315  if ("cardNickname" in patch) {2316    nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;2317  }2318  if ("network" in patch) {2319    nextPatch.network = patch.network;2320  }2321  if ("last4" in patch) {2322    nextPatch.last4 = patch.last4?.trim() || undefined;2323  }23242325  return nextPatch;2326}23272328function normalizeEntry(entry: VaultEntry | LegacyVaultEntry): VaultEntry {2329  const createdAt = "createdAt" in entry ? entry.createdAt : entry.created;2330  const modifiedAt =2331    "modifiedAt" in entry ? entry.modifiedAt : entry.updated;23322333  const base: VaultEntry = {2334    id: entry.id,2335    type: "type" in entry ? entry.type : "login",2336    title: entry.title,2337    username: entry.username,2338    email: "email" in entry ? entry.email : undefined,2339    password: entry.password,2340    url: entry.url,2341    additionalUrls:2342      "additionalUrls" in entry && Array.isArray(entry.additionalUrls)2343        ? entry.additionalUrls2344        : undefined,2345    totp: entry.totp,2346    notes: entry.notes,2347    breach: entry.breach,2348    // Preserve the password-age clock across lock/unlock. Without this the2349    // field is dropped on every decode and the advanced-health "aged password"2350    // signal silently resets to createdAt on each unlock (SEV-2-A).2351    passwordChangedAt:2352      "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,2353    // Preserve past-password history across lock/unlock. normalizeEntry is a2354    // field whitelist, so an unlisted field is silently dropped on every decode2355    // (same class as the passwordChangedAt SEV-2-A above).2356    passwordHistory:2357      "passwordHistory" in entry && Array.isArray(entry.passwordHistory)2358        ? entry.passwordHistory2359        : undefined,2360    canary: "canary" in entry ? entry.canary : undefined,2361    passkey: "passkey" in entry ? entry.passkey : undefined,2362    createdAt,2363    modifiedAt,2364    deletedAt: entry.deletedAt,2365    tags: "tags" in entry ? entry.tags : undefined,2366    cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,2367    cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,2368    expMonth: "expMonth" in entry ? entry.expMonth : undefined,2369    expYear: "expYear" in entry ? entry.expYear : undefined,2370    cvc: "cvc" in entry ? entry.cvc : undefined,2371    cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,2372    network: "network" in entry ? entry.network : undefined,2373    last4: "last4" in entry ? entry.last4 : undefined,2374  };23752376  return migrateLegacyPasskey(base, entry);2377}23782379/**2380 * v2.11.0 read migration. Pre-v2.11.0 passkey entries used `type:"passkey"`2381 * with flat top-level fields (rpId, credentialId, etc.). This converts them2382 * to the new shape — `type:"login"` with a `passkey` sub-object — so all2383 * downstream consumers can rely on the new model. The result is rewritten2384 * to disk on next vault save (hasLegacyShape detects the un-migrated case).2385 */2386function migrateLegacyPasskey(2387  base: VaultEntry,2388  raw: VaultEntry | LegacyVaultEntry2389): VaultEntry {2390  if (base.passkey) return base;2391  const flat = raw as Partial<VaultEntry>;2392  const isPasskeyType = base.type === "passkey";2393  const hasFlatPasskeyFields =2394    typeof flat.rpId === "string" &&2395    typeof flat.credentialId === "string" &&2396    typeof flat.publicKeyCose === "string" &&2397    typeof flat.userHandle === "string" &&2398    typeof flat.userName === "string";2399  if (!isPasskeyType && !hasFlatPasskeyFields) return base;2400  if (!hasFlatPasskeyFields) return base;24012402  const algorithm: -7 | -8 = flat.algorithm === -8 ? -8 : -7;2403  base.passkey = {2404    rpId: flat.rpId!,2405    rpName: flat.rpName ?? flat.rpId!,2406    credentialId: flat.credentialId!,2407    publicKeyCose: flat.publicKeyCose!,2408    privateKeyJwk: flat.privateKeyJwk,2409    userHandle: flat.userHandle!,2410    userName: flat.userName!,2411    userDisplayName: flat.userDisplayName ?? flat.userName!,2412    algorithm,2413    signCount: flat.signCount ?? 0,2414    aaguid: flat.aaguid ?? "",2415    backupEligible: flat.backupEligible === true,2416    backupState: flat.backupState === true,2417    lastUsedAt: flat.lastUsedAt,2418    browser: flat.browser,2419    transports: flat.transports,2420    createdAt: base.createdAt,2421  };2422  // Promote to "login" so the unified Entry view renders. Username gets2423  // populated from the passkey's userName so the entry is searchable in the2424  // existing autofill flow without a separate code path.2425  if (isPasskeyType) base.type = "login";2426  if (!base.username) base.username = flat.userName;2427  if (!base.url) base.url = `https://${flat.rpId}`;2428  return base;2429}243024312432// ---------------------------------------------------------------------------2433// Deduplication2434// ---------------------------------------------------------------------------24352436function entryDupeKey(e: VaultEntry): string {2437  if (e.type === "note") return `note|${e.title.toLowerCase()}`;2438  // Passkey-bearing entries dedupe by the credential's RP + user. Two logins2439  // on different sites that happen to share a username are still distinct;2440  // two passkey credentials for the same RP+user are duplicates regardless2441  // of any login fields they may also carry.2442  if (e.passkey) {2443    return `passkey|${e.passkey.rpId.toLowerCase()}|${e.passkey.userName.toLowerCase()}`;2444  }2445  return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;2446}24472448/** Returns the number of duplicate entries (those that would be removed). */2449export function countDuplicates(): number {2450  const best = new Map<string, VaultEntry>();2451  let dupeCount = 0;2452  for (const e of entries.filter((e) => !e.deletedAt)) {2453    const key = entryDupeKey(e);2454    const existing = best.get(key);2455    if (!existing) {2456      best.set(key, e);2457    } else {2458      dupeCount++;2459      // Keep the more recently modified one in the map2460      if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2461        best.set(key, e);2462      }2463    }2464  }2465  return dupeCount;2466}24672468/**2469 * Soft-deletes duplicate entries, keeping the most recently modified copy of2470 * each group. Returns the number of entries moved to trash.2471 */2472export async function deduplicateEntries(): Promise<number> {2473  if (!derivedKey) throw new Error("vault_locked");2474  // Dedup reshapes slot B permanently under the decoy key, which is2475  // forensically distinguishable from a freshly-seeded decoy vault. Refuse.2476  if (vaultMode === "decoy") {2477    throw new Error("deduplicate disabled in decoy mode");2478  }24792480  const best = new Map<string, VaultEntry>();2481  for (const e of entries.filter((en) => !en.deletedAt)) {2482    const key = entryDupeKey(e);2483    const existing = best.get(key);2484    if (!existing) {2485      best.set(key, e);2486    } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2487      best.set(key, e);2488    }2489  }24902491  const keepIds = new Set(Array.from(best.values()).map((e) => e.id));2492  let removed = 0;2493  entries = entries.map((e) => {2494    if (!e.deletedAt && !keepIds.has(e.id)) {2495      removed++;2496      return { ...e, deletedAt: monotonicEntryTimestamp(e.modifiedAt) };2497    }2498    return e;2499  });25002501  if (removed > 0) await persistEntries();2502  return removed;2503}25042505// ---------------------------------------------------------------------------2506// Vault history — snapshot BEFORE every vault write so the saved blob is2507// what is about to be lost, not what was just written. Capped at 5. The2508// stored blobs are AES-256-GCM ciphertext under the master password, so2509// history adds zero security surface.2510// ---------------------------------------------------------------------------25112512const HISTORY_KEY = "peach_vault_history";2513const HISTORY_MAX = 5;25142515/**2516 * Snapshot the CURRENT on-disk vault state into history. Call this BEFORE2517 * overwriting peach_vault_a so the saved blob captures the about-to-be-lost2518 * state. Identical-to-most-recent blobs are skipped to avoid filling history2519 * with no-op writes.2520 */2521export async function takeVaultSnapshot(2522  reason: VaultSnapshot["reason"],2523): Promise<void> {2524  try {2525    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);2526    const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];2527    const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];25282529    // Nothing to snapshot if the real slot doesn't exist yet (fresh install,2530    // pre-createVault). createVault skips snapshots intentionally — there is2531    // no prior state to preserve.2532    if (!slotA) return;25332534    const vault_a = JSON.stringify(slotA);2535    const vault_b = JSON.stringify(slotB ?? slotA);25362537    // Best-effort entry count: only meaningful when the in-memory state is2538    // unlocked AND in real mode. Decoy mode would leak the decoy entry2539    // count; locked mode has no entries to count. Both fall through to null.2540    let entryCount: number | null = null;2541    if (derivedKey && vaultMode === "real") {2542      try {2543        entryCount = entries.filter((e) => !e.deletedAt).length;2544      } catch {2545        entryCount = null;2546      }2547    }25482549    const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];2550    const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)2551      ? existingRaw2552      : { snapshots: [] };25532554    // Deduplication: if the most recent snapshot has byte-identical blobs,2555    // skip — saves the same vault N times in a row would otherwise burn the2556    // entire history window with no recovery value.2557    const latest = history.snapshots[0];2558    if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {2559      return;2560    }25612562    const snapshot: VaultSnapshot = {2563      id: crypto.randomUUID(),2564      savedAt: Date.now(),2565      reason,2566      vault_a,2567      vault_b,2568      entryCount,2569    };25702571    history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);2572    await chrome.storage.local.set({ [HISTORY_KEY]: history });2573  } catch (err) {2574    // Non-fatal — history must never block a save. A failed snapshot just2575    // means the user loses one rung of the safety ladder for this write.2576    // M4/QUA-006: log so the failure is visible; if it looks like a quota2577    // problem, notify the popup so the user can prune history themselves.2578    console.warn('[Peach] takeVaultSnapshot failed:', err);2579    if (String(err).includes('QUOTA') || String(err).includes('quota')) {2580      try {2581        await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });2582      } catch {2583        // popup may be closed; surfaced via console.warn above2584      }2585    }2586  }2587}25882589/** Wipe all vault history. Called by Panic / DESTROY_VAULT. */2590export async function clearVaultHistory(): Promise<void> {2591  try {2592    await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });2593  } catch {2594    // Non-fatal — DESTROY_VAULT also runs storage.local.clear().2595  }2596}25972598/** Read all snapshots, newest first, for the Settings vault history view. */2599export async function getVaultHistory(): Promise<VaultSnapshot[]> {2600  const raw = await chrome.storage.local.get(HISTORY_KEY);2601  const history = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];2602  if (!history || !Array.isArray(history.snapshots)) return [];2603  return history.snapshots;2604}26052606/**2607 * Replace the on-disk vault with the chosen snapshot's blobs and lock the2608 * vault. The current state is itself snapshotted with reason 'restore' first2609 * so the restore is reversible. After this returns, the user must unlock2610 * with the password that matches the restored blob.2611 */2612export async function restoreVaultSnapshot(2613  snapshotId: string,2614): Promise<{ ok: true } | { ok: false; error: string }> {2615  const history = await getVaultHistory();2616  const snapshot = history.find((s) => s.id === snapshotId);2617  if (!snapshot) return { ok: false, error: "snapshot_not_found" };26182619  // Snapshot the about-to-be-replaced current state so the restore is2620  // reversible. takeVaultSnapshot is no-op when the most recent entry is2621  // byte-identical, so a restore-of-a-restore stays clean.2622  await takeVaultSnapshot("restore");26232624  let restoredA: StoredVault;2625  let restoredB: StoredVault;2626  try {2627    restoredA = JSON.parse(snapshot.vault_a) as StoredVault;2628    restoredB = JSON.parse(snapshot.vault_b) as StoredVault;2629  } catch {2630    return { ok: false, error: "snapshot_corrupt" };2631  }26322633  await writeSlot(SLOT_A, restoredA);2634  await writeSlot(SLOT_B, restoredB);2635  await stampLocalVaultMutation();26362637  // Lock so the user must prove they can decrypt the restored blob. If they2638  // restored a pre-password-change snapshot they discover it immediately at2639  // the lock screen rather than silently holding an inaccessible vault.2640  lock();26412642  return { ok: true };2643}26442645/**2646 * Change the master password. Re-encrypts slot A with a fresh salt + new2647 * derived key. Slot B (duress or noise) is left untouched when duress is2648 * configured — it uses an independent key derived from the duress password —2649 * and regenerated as noise when duress is not configured.2650 */2651export async function changePassword(2652  currentPassword: string,2653  newPassword: string2654): Promise<boolean> {2655  if (!derivedKey || vaultMode !== "real") return false;26562657  // Verify current password before allowing any change2658  const valid = await verifyMainPassword(currentPassword);2659  if (!valid) return false;26602661  const slotA = await loadSlot(SLOT_A);2662  if (!slotA) return false;2663  if (!rootKey) return false;26642665  // Derive fresh key from new password + new random salt2666  const newSalt = generateSalt();2667  const newKey = await deriveKey(newPassword, newSalt);26682669  // Re-encrypt the in-memory entries with the new key2670  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);2671  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");26722673  // Pre-wrap root key under the new derived key. Recovery fields wrap rootKey2674  // under recovery words and remain untouched — recovery phrase keeps working2675  // across password changes (H4/COR-002).2676  const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);26772678  const finalSlotA: StoredVault = {2679    ...slotA,2680    salt: hex(newSalt),2681    nonce,2682    ciphertext,2683    tag,2684    ...pwRoot,2685  };26862687  // Snapshot the OLD-key blob before overwriting it. If the user later2688  // restores from this snapshot they will need the OLD password — the2689  // post-restore lock surfaces that immediately.2690  await takeVaultSnapshot("local_save");26912692  // Single atomic write: ciphertext, salt, and pw_root_* fields all land in2693  // one storage transaction. An SW kill before this point leaves the old2694  // slot intact; after this point everything tied to the new password is2695  // already on disk together (M6/COR-004).2696  await writeSlot(SLOT_A, finalSlotA);26972698  // Swap the in-memory key synchronously before any further await. If we2699  // threw between the Slot A write and this swap, the next persistEntries()2700  // would overwrite Slot A with old-key ciphertext, locking the user out.2701  zeroKey(derivedKey);2702  derivedKey = newKey;27032704  // Regenerate noise for slot B when duress is not in use. Runs after the2705  // key swap so a failure here is a disposable noise regeneration, not a2706  // lockout.2707  if (!duressConfigured) {2708    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));2709  }2710  await stampLocalVaultMutation();27112712  return true;2713}