vault.ts

88.7 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 {15  rootKeyToWords,16  wordsToRootKeyMaterial,17  deriveRecoveryKey,18} from "../shared/recovery-words";19import type {20  AccentColorName,21  LegacyVaultEntry,22  ManualSummonRecord,23  SavedIdentity,24  StoredVault,25  VaultEntry,26  VaultHistory,27  VaultSnapshot,28} from "../shared/types";29import { decrypt, encrypt, zeroKey } from "./aes";30import { clearAutoLock, touchAutoLock } from "./alarms";3132type EntryDraft = Omit<33  VaultEntry,34  "id" | "createdAt" | "modifiedAt" | "deletedAt"35>;3637// Slot-neutral storage keys (v1.4.24+). Both slots always exist; slot B38// either holds the decoy vault (when duress is configured) or random noise39// that looks identical at rest. No external indicator is stored — duress40// configuration is recorded only inside the encrypted payload of slot A.41const SLOT_A = "peach_vault_a";42const SLOT_B = "peach_vault_b";4344// Legacy keys, migrated away on first access.45const LEGACY_MAIN = "peach_vault";46const LEGACY_DECOY = "peach_decoy_vault";47const LEGACY_DURESS_FLAG = "peach_duress";4849// Plaintext is padded to the next multiple of this size before encryption.50// This coarsens ciphertext-length leakage into 1 KiB buckets.51const PAD_BLOCK = 1024;5253let derivedKey: Uint8Array | null = null;54// 32-byte random root key, separate from the derivedKey used for vault encryption.55// The root key is wrapped (encrypted) under the recovery key derived from the56// 12-word phrase. When the user changes their password, only the wrapping changes;57// the root key and recovery words remain stable.58let rootKey: Uint8Array | null = null;59let entries: VaultEntry[] = [];60let domainIndex: Map<string, VaultEntry[]> = new Map();61let vaultMode: "real" | "decoy" = "real";62// Cached post-unlock view of whether the real vault records that duress is63// configured. Only meaningful after a real-mode unlock; for decoy-mode unlock64// this stays false because we never see slot A's plaintext.65let duressConfigured = false;6667let migrationRan = false;6869// Set to a corruption reason during the last unlock() attempt when both slots70// decrypted but failed schema validation. Consumed and cleared by71// consumeLastUnlockFailureReason() so messages.ts can surface vault_corrupted72// distinctly from wrong-password (M7/COR-007).73//74// NOTE: module-level state — if vault.ts is ever moved to a worker context,75// this must be replaced with a structured return value from unlock() or a76// postMessage channel. The signal is invisible across module-instance77// boundaries.78let lastUnlockFailureReason: string | null = null;7980export function consumeLastUnlockFailureReason(): string | null {81  const r = lastUnlockFailureReason;82  lastUnlockFailureReason = null;83  return r;84}8586// ---------------------------------------------------------------------------87// Settings (persisted inside the encrypted vault store as a sidecar key)88// ---------------------------------------------------------------------------8990export type TextSize = "small" | "medium" | "large";9192export interface VaultSettings {93  accentColor?: AccentColorName;94  theme?: "dark" | "light";95  autoLockMinutes?: number;96  clipboardClearSeconds?: number;97  lockOnClose?: boolean;98  breachMonitoring?: boolean;99  passkeyProviderEnabled?: boolean;100  trashRetentionDays?: number;101  manualSummonDomains?: Record<string, ManualSummonRecord>;102  declinedCardFingerprints?: string[];103  /**104   * Text size scale for body copy and entry titles. Stops at "large" by105   * design — XL clips dense screens (Vault, Health) inside the fixed106   * 330×480 popup surface.107   */108  textSize?: TextSize;109  /**110   * When true, all entrance/exit transitions and ambient animations are111   * collapsed to instant. Honoured alongside the user's OS-level112   * `prefers-reduced-motion`.113   */114  reduceMotion?: boolean;115  /**116   * Android-only: when true, the master key is escrowed in AndroidKeyStore117   * and the lock screen offers biometric unlock. Toggled from Settings →118   * Security → Biometrics. Has no effect on desktop builds.119   */120  biometricsEnabled?: boolean;121  /**122   * User overrides for keyboard shortcuts. Keys are ShortcutAction names123   * (see src/shared/shortcuts.ts). Missing actions fall through to124   * DEFAULT_BINDINGS — `getActiveBindings(settings.shortcuts)` is the125   * canonical lookup. Storing only the deltas keeps the vault payload126   * small and lets default updates land for users who never rebind.127   */128  shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;129}130131let settings: VaultSettings = {};132133export function getSettings(): VaultSettings {134  return settings;135}136137export async function ensureSettingsLoaded(): Promise<VaultSettings> {138  await loadSettings();139  return settings;140}141142export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {143  await loadSettings();144  settings = { ...settings, ...patch };145  await persistSettings();146}147148async function persistSettings(): Promise<void> {149  try {150    await chrome.storage.local.set({ peach_settings: settings });151  } catch (err) {152    throw mapStorageError(err);153  }154}155156function mapStorageError(err: unknown): Error {157  const message = err instanceof Error ? err.message : String(err);158  if (/QUOTA_BYTES|quota/i.test(message)) {159    return new Error("STORAGE_QUOTA_EXCEEDED");160  }161  return err instanceof Error ? err : new Error(message);162}163164async function loadSettings(): Promise<void> {165  const result = await chrome.storage.local.get("peach_settings");166  settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};167}168169// Fire-and-forget sync trigger after a committed vault write. Lazy170// dynamic import avoids a circular dependency between vault.ts and171// sync-trigger.ts (the trigger imports paired-devices, which only reads172// storage, but the lazy load also gives us a clean opt-out path in173// tests where sync-trigger has not been initialised).174function fireSyncTrigger(reason: "vault_change"): void {175  void import("./sync-trigger")176    .then((mod) => mod.triggerSyncIfReachable({ reason }))177    .catch(() => {178      /* sync trigger module not available — non-fatal */179    });180}181182// ---------------------------------------------------------------------------183// HIBP breach check (k-anonymity model)184// ---------------------------------------------------------------------------185186export async function checkBreach(password: string): Promise<number> {187  // HIBP k-anonymity API is keyed on SHA-1 prefixes — this is dictated by188  // the public API, not a security choice. Do not migrate to SHA-256 here.189  const encoder = new TextEncoder();190  const hashBuffer = await crypto.subtle.digest("SHA-1", encoder.encode(password));191  const hashHex = Array.from(new Uint8Array(hashBuffer))192    .map((b) => b.toString(16).padStart(2, "0"))193    .join("")194    .toUpperCase();195196  const prefix = hashHex.slice(0, 5);197  const suffix = hashHex.slice(5);198199  try {200    const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`);201    if (!res.ok) return 0;202    const text = await res.text();203    const match = text.split("\r\n").find((l) => l.startsWith(suffix));204    return match ? parseInt(match.split(":")[1], 10) : 0;205  } catch {206    return 0; // Network unavailable — don't block207  }208}209210export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {211  const fingerprint = await cardFingerprint(last4, expMonth, expYear);212  await loadSettings();213  settings = {214    ...settings,215    declinedCardFingerprints: [...(settings.declinedCardFingerprints ?? []), fingerprint],216  };217  await persistSettings();218}219220export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {221  await loadSettings();222  const fingerprint = await cardFingerprint(last4, expMonth, expYear);223  return (settings.declinedCardFingerprints ?? []).includes(fingerprint);224}225226async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {227  const encoder = new TextEncoder();228  const buf = await crypto.subtle.digest("SHA-256", encoder.encode(`${last4}|${expMonth}|${expYear}`));229  return Array.from(new Uint8Array(buf).slice(0, 8))230    .map((b) => b.toString(16).padStart(2, "0"))231    .join("");232}233234function hex(buf: Uint8Array): string {235  return Array.from(buf)236    .map((b) => b.toString(16).padStart(2, "0"))237    .join("");238}239240function unhex(s: string): Uint8Array {241  const out = new Uint8Array(s.length / 2);242  for (let i = 0; i < s.length; i += 2) {243    out[i / 2] = parseInt(s.slice(i, i + 2), 16);244  }245  return out;246}247248// ---------------------------------------------------------------------------249// Root key generation and recovery word wrapping250// ---------------------------------------------------------------------------251252/**253 * Generate a random 32-byte root key and wrap it (AES-256-GCM) under a key254 * derived from the recovery word material via HKDF-SHA256. The wrapped blob255 * fields are stored in slot A alongside the password-wrapped ciphertext. The256 * root key itself is kept in memory for the session so getRecoveryWords() can257 * encode it without re-deriving.258 */259async function generateAndWrapRootKey(): Promise<{260  rawRootKey: string; // hex of the plaintext root key — caller stores in rootKey261  recoverySalt: string;262  wrappedRootKey: string;263  wrappedNonce: string;264  wrappedTag: string;265}> {266  const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));267268  // Derive the recovery key from the BIP39 words encoding of the root key.269  const words = await rootKeyToWords(rootKeyBytes);270  const wordMaterial = await wordsToRootKeyMaterial(words);271  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));272  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);273274  // Wrap the root key with the recovery key using AES-256-GCM directly.275  // We hex-encode rootKeyBytes so the plaintext is always valid UTF-8.276  const nonce = crypto.getRandomValues(new Uint8Array(12));277  const encoded = new TextEncoder().encode(hex(rootKeyBytes));278  const raw = await crypto.subtle.encrypt(279    {280      name: "AES-GCM",281      iv: nonce,282      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,283      tagLength: 128,284    },285    recoveryKey,286    encoded287  );288  // WebCrypto returns ciphertext || auth tag concatenated; split them.289  const rawU8 = new Uint8Array(raw);290  const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));291  const tag = hex(rawU8.slice(rawU8.length - 16));292293  return {294    rawRootKey: hex(rootKeyBytes),295    recoverySalt: hex(recoverySalt),296    wrappedRootKey: ciphertext,297    wrappedNonce: hex(nonce),298    wrappedTag: tag,299  };300}301302/**303 * Unwrap the root key using recovery words. Called during recovery flow when304 * the user provides their 12-word phrase and a new password.305 * Exported for use by the RECOVER_WITH_WORDS message handler.306 */307export async function unwrapRootKeyForRecovery(308  wrappedRootKey: string,309  wrappedNonce: string,310  wrappedTag: string,311  recoverySaltHex: string,312  words: string[]313): Promise<void> {314  const wordMaterial = await wordsToRootKeyMaterial(words);315  const recoverySalt = unhex(recoverySaltHex);316  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);317318  // Decrypt and cache the root key. The root key bytes were hex-encoded before319  // encryption so the ciphertext is valid UTF-8. We inline the AES-GCM decrypt320  // here to avoid passing a CryptoKey to the string-based encrypt/decrypt helpers.321  // Each component is stored separately in the vault slot; decode them individually322  // so the nonce is always exactly the 12 bytes from wrappedNonce.323  const nonceRaw = unhex(wrappedNonce);324  const ciphertextRaw = unhex(wrappedRootKey);325  const tagRaw = unhex(wrappedTag);326  // Combine ciphertext and tag for AES-GCM (expects ciphertext||tag).327  // Use explicit ArrayBuffer allocations to satisfy TS BufferSource constraints.328  const nonceU8 = nonceRaw as unknown as Uint8Array<ArrayBuffer>;329  const combined = new Uint8Array(ciphertextRaw.length + tagRaw.length);330  combined.set(ciphertextRaw, 0);331  combined.set(tagRaw, ciphertextRaw.length);332  const raw = await crypto.subtle.decrypt(333    { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },334    recoveryKey,335    combined336  );337  const decryptedHex = new TextDecoder().decode(raw);338  rootKey = unhex(decryptedHex);339}340341/**342 * Re-wrap the cached root key under a new derived key (from the user's new343 * password). Called after password change and after recovery re-key so the344 * same recovery words continue to work with the updated password — and so345 * subsequent unlocks can rehydrate rootKey via deriveRootKeyFromDerivedKey.346 *347 * recovery_* fields are intentionally not touched: those wrap rootKey under348 * the recovery words, which do not change when the password changes.349 */350export async function rewrapRootKeyForPassword(351  newDerivedKey: Uint8Array,352  _newSalt: Uint8Array353): Promise<void> {354  if (!rootKey) throw new Error("root key not set");355  const slotA = await loadSlot(SLOT_A);356  if (!slotA) throw new Error("missing slot A");357  const pwRoot = await wrapRootKeyForDerivedKey(newDerivedKey, rootKey);358  await writeSlot(SLOT_A, { ...slotA, ...pwRoot });359}360361/**362 * Change the vault encryption to a new derived key (already derived from363 * the user's new password). Used by RECOVER_WITH_WORDS and changePassword.364 * Caller is responsible for key swap and snapshot.365 */366async function reencryptVaultForNewKey(367  newKey: Uint8Array,368  slotA: StoredVault369): Promise<void> {370  const plaintext = encodePayload(entries, duressConfigured);371  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");372  await writeSlot(SLOT_A, {373    ...slotA,374    nonce,375    ciphertext,376    tag,377  });378}379380/**381 * Full password change with an already-derived key (used after recovery).382 * Unlike changePassword(), this skips re-verification of current password383 * since recovery flow has already validated the user's identity via words.384 */385export async function changePasswordWithNewKey(386  newSalt: Uint8Array,387  newKey: Uint8Array388): Promise<void> {389  const slotA = await loadSlot(SLOT_A);390  if (!slotA) throw new Error("missing slot A");391  // reencryptVaultForNewKey must receive the updated salt so that subsequent392  // UNLOCK calls with the new password can re-derive the correct key.393  await reencryptVaultForNewKey(newKey, { ...slotA, salt: hex(newSalt) });394  if (derivedKey) zeroKey(derivedKey);395  derivedKey = newKey;396  // Refresh pw_root_* under the new key so deriveRootKeyFromDerivedKey works397  // on the next unlock (H2/COR-006). If rootKey is missing — recovery flow398  // should have populated it — fall back silently rather than blowing up the399  // recovery path; migrateToRecovery will rehydrate on the next unlock.400  if (rootKey) {401    const slotAfter = await loadSlot(SLOT_A);402    if (slotAfter) {403      const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);404      await writeSlot(SLOT_A, { ...slotAfter, ...pwRoot });405    }406  }407  if (!duressConfigured) {408    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));409  }410  await stampLocalVaultMutation();411}412413// ---------------------------------------------------------------------------414// Salt generation --- exported so the RECOVER_WITH_WORDS handler can derive415// a new key after password reset without re-importing the crypto module.416// ---------------------------------------------------------------------------417418export { deriveKey, generateSalt };419420export async function loadSlotA(): Promise<StoredVault | null> {421  return loadSlot(SLOT_A);422}423424/**425 * Recover the session root key by AES-GCM-decrypting the pw_root_* fields426 * (a second wrapping of the root key under the password-derived key). This427 * is what makes GET_RECOVERY_WORDS work across lock/unlock cycles without428 * the user re-entering their recovery phrase: the same root key bytes —429 * and therefore the same 12 words — survive every unlock.430 *431 * Returns null when the pw_root fields are absent (pre-v2.12 vault that432 * hasn't been migrated yet) or when decryption fails (wrong derived key,433 * tampered ciphertext). On null the caller should fall through to434 * migrateToRecovery() to populate the fields.435 */436async function deriveRootKeyFromDerivedKey(437  derivedKeyBytes: Uint8Array,438  slotA: StoredVault,439): Promise<Uint8Array | null> {440  if (!slotA.pw_root_ciphertext || !slotA.pw_root_nonce || !slotA.pw_root_tag) {441    return null;442  }443  try {444    const rootHex = await decrypt(445      derivedKeyBytes,446      slotA.pw_root_nonce,447      slotA.pw_root_ciphertext,448      slotA.pw_root_tag,449      "pw_root_v1",450    );451    return unhex(rootHex);452  } catch {453    return null;454  }455}456457// AES-GCM-wrap rootKey under derivedKey for the pw_root_* fields. Returns the458// hex-encoded ciphertext/nonce/tag triple ready to embed in StoredVault.459async function wrapRootKeyForDerivedKey(460  derivedKeyBytes: Uint8Array,461  rootKeyBytes: Uint8Array,462): Promise<{ pw_root_ciphertext: string; pw_root_nonce: string; pw_root_tag: string }> {463  const { nonce, ciphertext, tag } = await encrypt(derivedKeyBytes, hex(rootKeyBytes), "pw_root_v1");464  return {465    pw_root_ciphertext: ciphertext,466    pw_root_nonce: nonce,467    pw_root_tag: tag,468  };469}470471/**472 * For vaults created before v2.12 (no recovery_salt/recovery_wrapped_root_key),473 * generate the root key, wrap it under the recovery words, and persist the474 * recovery escrow into slot A. The caller must show the recovery words to the475 * user before calling this — once called, those words are the vault's recovery476 * path. This runs once, on the first unlock of an upgraded vault.477 */478export async function migrateToRecovery(): Promise<void> {479  if (!derivedKey || vaultMode !== "real") {480    throw new Error("vault must be unlocked in real mode");481  }482  const slotA = await loadSlot(SLOT_A);483  if (!slotA) throw new Error("missing slot A");484  const hasRecoveryEscrow =485    !!slotA.recovery_salt && !!slotA.recovery_wrapped_root_key;486  const hasPwRoot = !!slotA.pw_root_ciphertext && !!slotA.pw_root_nonce;487  if (hasRecoveryEscrow && hasPwRoot) return; // already done488489  // If recovery escrow already exists but pw_root doesn't, we cannot recover490  // the original rootKey without the user's words. The least-surprising path491  // is to rotate to a fresh root key — the user's old recovery words become492  // invalid but we surface peach_recovery_pending so the popup re-presents493  // the words. The unlock-path callers all set that flag.494  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =495    await generateAndWrapRootKey();496  rootKey = unhex(rawRootKey);497498  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);499  const nextSlotA: StoredVault = {500    ...slotA,501    recovery_salt: recoverySalt,502    recovery_wrapped_root_key: wrappedRootKey,503    recovery_nonce: wrappedNonce,504    recovery_tag: wrappedTag,505    ...pwRoot,506  };507  await writeSlot(SLOT_A, nextSlotA);508  await stampLocalVaultMutation();509}510511/**512 * Returns the 12 recovery words for the current session's root key.513 * Must be called while the vault is unlocked. Throws if recovery has not514 * been set up (pre-v2.12 vault that hasn't migrated yet).515 */516export async function getRecoveryWords(): Promise<string[]> {517  if (!rootKey) {518    throw new Error("recovery not set up — vault may need migration");519  }520  return rootKeyToWords(rootKey);521}522523async function loadSlot(key: string): Promise<StoredVault | null> {524  const result = await chrome.storage.local.get(key);525  return (result as Record<string, StoredVault | undefined>)[key] ?? null;526}527528async function writeSlot(key: string, vault: StoredVault): Promise<void> {529  try {530    await chrome.storage.local.set({ [key]: vault });531  } catch (err) {532    throw mapStorageError(err);533  }534}535536// Monotonic clock for per-entry modifiedAt / deletedAt timestamps. Guards the537// sync layer's last-write-wins merge against wall-clock regressions (NTP step,538// manual clock change, DST glitch): a backwards Date.now() must never produce539// an entry timestamp that's <= the entry's existing modifiedAt, or a genuine540// local edit would lose to a stale remote copy. The returned value is always541// strictly greater than both the entry's current modifiedAt and the previous542// call's result (SEV-2-E).543let lastEntryTimestamp = 0;544function monotonicEntryTimestamp(currentModifiedAt?: number): number {545  const base = Math.max(546    Date.now(),547    (currentModifiedAt ?? 0) + 1,548    lastEntryTimestamp + 1,549  );550  lastEntryTimestamp = base;551  return base;552}553554async function stampLocalVaultMutation(): Promise<void> {555  const raw = await chrome.storage.local.get("peach_last_modified_at");556  const previous = Number(557    (raw as Record<string, unknown>).peach_last_modified_at,558  );559  const next = Math.max(560    Date.now(),561    Number.isFinite(previous) ? previous + 1 : 0,562  );563  await chrome.storage.local.set({564    peach_last_modified_at: String(next),565  });566}567568/**569 * One-shot migration from the pre-A-2 schema (peach_vault + peach_decoy_vault570 * + peach_duress flag) to the slot-neutral schema (peach_vault_a +571 * peach_vault_b). Runs at most once per session; safe to call repeatedly.572 */573async function ensureMigrated(): Promise<void> {574  if (migrationRan) return;575  migrationRan = true;576577  const keys = [LEGACY_MAIN, LEGACY_DECOY, LEGACY_DURESS_FLAG, SLOT_A, SLOT_B];578  const raw = await chrome.storage.local.get(keys);579  const slotAExists = raw[SLOT_A] !== undefined;580  const slotBExists = raw[SLOT_B] !== undefined;581  const legacyMain = raw[LEGACY_MAIN] as StoredVault | undefined;582  const legacyDecoy = raw[LEGACY_DECOY] as StoredVault | undefined;583584  // Fresh install with nothing in storage — nothing to do; createVault() sets up both slots.585  if (!slotAExists && !legacyMain) return;586587  // Already migrated.588  if (slotAExists && slotBExists && !legacyMain && !legacyDecoy) return;589590  let didMigrate = false;591  if (legacyMain && !slotAExists) {592    await writeSlot(SLOT_A, legacyMain);593    didMigrate = true;594  }595596  // If slot B isn't set, populate it: use legacy decoy when present, else noise.597  if (!slotBExists) {598    const target = (legacyMain ?? raw[SLOT_A]) as StoredVault | undefined;599    if (legacyDecoy) {600      await writeSlot(SLOT_B, legacyDecoy);601      didMigrate = true;602    } else if (target) {603      await writeSlot(SLOT_B, generateNoiseBlob(target.ciphertext.length / 2));604      didMigrate = true;605    }606  }607608  const toRemove: string[] = [];609  if (legacyMain) toRemove.push(LEGACY_MAIN);610  if (legacyDecoy) toRemove.push(LEGACY_DECOY);611  if (raw[LEGACY_DURESS_FLAG] !== undefined) toRemove.push(LEGACY_DURESS_FLAG);612  if (toRemove.length > 0) {613    await chrome.storage.local.remove(toRemove);614    didMigrate = true;615  }616  if (didMigrate) {617    await stampLocalVaultMutation();618  }619}620621// ---------------------------------------------------------------------------622// Padding + noise helpers623// ---------------------------------------------------------------------------624625/**626 * Pads the plaintext string with trailing spaces so that the encoded byte627 * length is a multiple of PAD_BLOCK. JSON.parse tolerates trailing628 * whitespace after a complete document, so the padding is transparent on629 * decode. Ciphertext length equals plaintext length plus a 16-byte tag.630 */631function padPlaintext(json: string): string {632  const encoded = new TextEncoder().encode(json);633  const target = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);634  const padLen = target - encoded.length;635  return json + " ".repeat(padLen);636}637638/**639 * Produces a StoredVault-shaped record filled with CSPRNG bytes. The640 * ciphertext length matches the given byte count. Because GCM ciphertext is641 * pseudo-random, this blob is indistinguishable at rest from a real642 * encrypted vault without the key.643 *644 * crypto.getRandomValues() caps each call at 65536 bytes (the Web Crypto645 * spec hard limit). Chunk the fill so vaults larger than that — common once646 * the user has dozens of entries or any passkey — don't throw.647 */648const CSPRNG_CHUNK = 65_536;649650function fillRandom(buf: Uint8Array): Uint8Array {651  for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {652    const end = Math.min(offset + CSPRNG_CHUNK, buf.length);653    const chunk = new Uint8Array(end - offset);654    crypto.getRandomValues(chunk);655    buf.set(chunk, offset);656  }657  return buf;658}659660function generateNoiseBlob(ciphertextBytes: number): StoredVault {661  const salt = crypto.getRandomValues(new Uint8Array(16));662  const nonce = crypto.getRandomValues(new Uint8Array(12));663  const cipher = fillRandom(new Uint8Array(ciphertextBytes));664  const tag = crypto.getRandomValues(new Uint8Array(16));665  return {666    version: 1,667    salt: hex(salt),668    nonce: hex(nonce),669    ciphertext: hex(cipher),670    tag: hex(tag),671  };672}673674// ---------------------------------------------------------------------------675// Encrypted plaintext envelope676// ---------------------------------------------------------------------------677678type VaultPayload = {679  entries: VaultEntry[];680  duressConfigured?: boolean;681};682683type DecryptedPayload = {684  entries: VaultEntry[];685  duressConfigured: boolean;686  /**687   * True when at least one entry in the on-disk payload had a legacy shape688   * (pre-v2.11.0 passkey type/flat fields, or pre-A-2 created/updated keys)689   * and got rewritten by normalizeEntry. The unlock path uses this to690   * persist the new shape immediately — without it, the migration would691   * re-run on every unlock and old shape never disappears from disk.692   */693  migratedFromLegacy: boolean;694};695696function encodePayload(entries: VaultEntry[], duress: boolean): string {697  const envelope: VaultPayload = { entries, duressConfigured: duress };698  return padPlaintext(JSON.stringify(envelope));699}700701function rawNeedsMigration(raw: VaultEntry | LegacyVaultEntry): boolean {702  if ("created" in raw || "updated" in raw) return true;703  const flat = raw as Partial<VaultEntry>;704  if (flat.type === "passkey") return true;705  // Flat rpId without a passkey sub-object means pre-v2.11.0 schema.706  if (flat.rpId !== undefined && flat.passkey === undefined) return true;707  return false;708}709710function decodePayload(plain: string): DecryptedPayload {711  const parsed = JSON.parse(plain) as712    | Array<VaultEntry | LegacyVaultEntry>713    | VaultPayload;714715  const rawEntries = Array.isArray(parsed) ? parsed : parsed.entries ?? [];716  const flatMigrationNeeded = rawEntries.some(rawNeedsMigration);717718  const normalized = rawEntries.map(normalizeEntry);719  const { merged } = mergePasskeyOnlyIntoLogins(normalized);720721  if (Array.isArray(parsed)) {722    return {723      entries: normalized,724      duressConfigured: false,725      migratedFromLegacy: true, // pre-A-2 array shape always needs save726    };727  }728729  return {730    entries: normalized,731    duressConfigured: parsed.duressConfigured === true,732    migratedFromLegacy: flatMigrationNeeded || merged,733  };734}735736/**737 * One-time consolidation pass run alongside the legacy passkey migration.738 *739 * Pre-v2.11.0 the Chrome passkey path always created a fresh `type:"passkey"`740 * entry per registration — so users who tested registration multiple times741 * accumulated several passkey-bearing entries for the same RP, and the742 * migration to the unified shape carried that duplication forward. This743 * pass collapses the duplicates:744 *745 *   1. Group passkey-bearing (and not deleted) entries by `passkey.rpId`.746 *   2. Within each group, the most recently-active credential wins (prefer747 *      lastUsedAt, fall back to passkey.createdAt, fall back to modifiedAt).748 *   3. If a NON-passkey login entry exists for that RP (matched by url or749 *      additionalUrls hostname), attach the winning passkey to it and750 *      soft-delete every passkey-bearing entry in the group.751 *   4. Otherwise, soft-delete every loser in the group, keeping the winner752 *      as a passkey-only entry.753 *754 * Soft delete (deletedAt) rather than splice — the trash flow keeps the755 * record around for retention and the user can restore if the heuristic756 * picked wrong. The `merged` flag goes back to decodePayload so the757 * unlock path persists the consolidated shape immediately.758 */759function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {760  let merged = false;761  const now = Date.now();762763  const candidates = entries.filter((e) => !e.deletedAt && e.passkey);764  const byRpId = new Map<string, VaultEntry[]>();765  for (const e of candidates) {766    const rpId = e.passkey!.rpId;767    const list = byRpId.get(rpId);768    if (list) list.push(e);769    else byRpId.set(rpId, [e]);770  }771772  for (const [rpId, group] of byRpId) {773    if (group.length === 0) continue;774    group.sort((a, b) => {775      const aT =776        a.passkey!.lastUsedAt ?? a.passkey!.createdAt ?? a.modifiedAt ?? a.createdAt;777      const bT =778        b.passkey!.lastUsedAt ?? b.passkey!.createdAt ?? b.modifiedAt ?? b.createdAt;779      return bT - aT;780    });781    const winner = group[0]!;782783    // Look for a NON-passkey login entry matching this RP. Use the URL784    // hostname rather than a substring search so a "login.foo.com" entry785    // doesn't accidentally absorb a passkey for "foo.com".786    const loginTarget = entries.find((e) => {787      if (e.deletedAt || e.passkey || e.type !== "login") return false;788      if (e.url && extractDomain(e.url) === rpId) return true;789      for (const extra of e.additionalUrls ?? []) {790        if (extractDomain(extra) === rpId) return true;791      }792      return false;793    });794795    if (loginTarget) {796      loginTarget.passkey = winner.passkey;797      loginTarget.modifiedAt = now;798      for (const dup of group) {799        if (!dup.deletedAt) {800          dup.deletedAt = now;801          dup.modifiedAt = now;802        }803      }804      merged = true;805    } else if (group.length > 1) {806      for (let i = 1; i < group.length; i += 1) {807        const dup = group[i]!;808        if (!dup.deletedAt) {809          dup.deletedAt = now;810          dup.modifiedAt = now;811        }812      }813      merged = true;814    }815  }816817  return { merged };818}819820// Validates that a `StoredVault` record on disk has the field shape we expect821// before treating an AES-GCM decrypt success as a clean unlock. AES-GCM only822// authenticates the static VERSION_BYTE AAD, not the `version` field on the823// outer record — a corrupted `version: 42` slot still decrypts cleanly. This824// check surfaces that as `corrupted` (M7/COR-007) so the popup can offer a825// history-restore path instead of falsely reporting "wrong password".826function hasValidVaultSchema(v: unknown): v is StoredVault {827  if (typeof v !== "object" || v === null) return false;828  const r = v as Record<string, unknown>;829  return (830    r.version === 1 &&831    typeof r.salt === "string" &&832    typeof r.nonce === "string" &&833    typeof r.ciphertext === "string" &&834    typeof r.tag === "string"835  );836}837838export type TryDecryptResult =839  | { status: "ok"; payload: DecryptedPayload }840  | { status: "wrong_key" }841  | { status: "corrupted"; reason: string };842843// Exported solely for `unlockFromCodex` below, which needs to verify a844// supplied passphrase against a slotA blob *without* committing anything to845// storage. Keep this internal otherwise — callers crossing the messages.ts846// boundary should always go through `unlock` / `verifyMainPassword` so the847// constant-time invariants in Projects.md §3.4 are not bypassed.848export async function tryDecryptSlot(849  vault: StoredVault,850  key: Uint8Array,851  aadTag?: string,852): Promise<DecryptedPayload | null> {853  const res = await tryDecryptSlotResult(vault, key, aadTag);854  return res.status === "ok" ? res.payload : null;855}856857export async function tryDecryptSlotResult(858  vault: StoredVault,859  key: Uint8Array,860  aadTag?: string,861): Promise<TryDecryptResult> {862  if (!hasValidVaultSchema(vault)) {863    return { status: "corrupted", reason: "invalid_slot_schema" };864  }865  let plain: string;866  try {867    plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);868  } catch {869    return { status: "wrong_key" };870  }871  try {872    const parsed = JSON.parse(plain) as unknown;873    if (typeof parsed !== "object" || parsed === null) {874      return { status: "corrupted", reason: "invalid_payload_shape" };875    }876    if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {877      return { status: "corrupted", reason: "invalid_payload_shape" };878    }879    return { status: "ok", payload: decodePayload(plain) };880  } catch {881    return { status: "corrupted", reason: "invalid_payload_json" };882  }883}884885// ---------------------------------------------------------------------------886// Core operations887// ---------------------------------------------------------------------------888889function buildDomainIndexSync(all: VaultEntry[]): void {890  domainIndex = new Map();891892  for (const entry of all) {893    if (entry.deletedAt) continue;894    if (entry.type === "note" || entry.type === "card") continue;895896    // An entry can match multiple sites via `additionalUrls`. Index each897    // hostname so `queryDomain` returns the entry regardless of which alias898    // the user is currently visiting. Dedupe per-entry so a single entry899    // never appears twice in one bucket.900    const domains = new Set<string>();901    const primary = extractDomain(entry.url ?? "");902    if (primary) domains.add(primary);903    for (const extra of entry.additionalUrls ?? []) {904      const d = extractDomain(extra);905      if (d) domains.add(d);906    }907    if (domains.size === 0) continue;908909    for (const domain of domains) {910      const bucket = domainIndex.get(domain) ?? [];911      bucket.push(entry);912      domainIndex.set(domain, bucket);913    }914  }915}916917export async function createVault(password: string): Promise<void> {918  await ensureMigrated();919920  const salt = generateSalt();921  derivedKey = await deriveKey(password, salt);922  entries = [];923  vaultMode = "real";924  duressConfigured = false;925  buildDomainIndexSync(entries);926927  // Generate and wrap the root key for recovery word escrow.928  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =929    await generateAndWrapRootKey();930  rootKey = unhex(rawRootKey);931932  const plaintext = encodePayload(entries, duressConfigured);933  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");934935  // Second wrapping of rootKey under derivedKey so future unlocks can rehydrate936  // it without recovery words (H2/COR-006).937  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);938939  const slotA: StoredVault = {940    version: 1,941    salt: hex(salt),942    nonce,943    ciphertext,944    tag,945    recovery_salt: recoverySalt,946    recovery_wrapped_root_key: wrappedRootKey,947    recovery_nonce: wrappedNonce,948    recovery_tag: wrappedTag,949    ...pwRoot,950  };951  await writeSlot(SLOT_A, slotA);952953  // Matching-size noise blob for slot B, so a fresh install shows two954  // similarly-shaped records regardless of whether duress is ever set up.955  await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));956  await stampLocalVaultMutation();957958  touchAutoLock();959}960961export async function hasVault(): Promise<boolean> {962  await ensureMigrated();963  return (await loadSlot(SLOT_A)) !== null;964}965966/**967 * Returns whether the real vault has recorded that a duress passphrase is968 * configured. Reliable only after a real-mode unlock — before unlock or in969 * decoy mode, returns false because we cannot read slot A's plaintext.970 */971export async function isDuressEnabled(): Promise<boolean> {972  return vaultMode === "real" && duressConfigured;973}974975export async function setupDuress(duressPassword: string): Promise<void> {976  if (!derivedKey || vaultMode !== "real") {977    throw new Error("vault must be unlocked in real mode");978  }979  await ensureMigrated();980981  // Encrypt the decoy payload (empty entries) under the duress key. Pad to982  // at least the current slot A ciphertext size so the two slots look the983  // same at rest at setup time.984  const slotA = await loadSlot(SLOT_A);985  if (!slotA) throw new Error("missing slot A");986987  const decoySalt = generateSalt();988  const decoyKey = await deriveKey(duressPassword, decoySalt);989  try {990    // Pad the decoy plaintext to match slot A's ciphertext length (minus the991    // 16-byte tag) so encrypted sizes align exactly.992    const targetBytes = slotA.ciphertext.length / 2;993    let plaintext = encodePayload([], false);994    const encoded = new TextEncoder().encode(plaintext);995    if (encoded.length < targetBytes) {996      plaintext = plaintext + " ".repeat(targetBytes - encoded.length);997    }998    const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");999    await writeSlot(SLOT_B, {1000      version: 1,1001      salt: hex(decoySalt),1002      nonce,1003      ciphertext,1004      tag,1005    });1006  } finally {1007    zeroKey(decoyKey);1008  }10091010  // Re-encrypt slot A with the duressConfigured flag set to true. No external1011  // flag is written — the bit lives inside the encrypted envelope.1012  duressConfigured = true;1013  await persistSlotA();1014}10151016export async function disableDuress(): Promise<void> {1017  if (!derivedKey || vaultMode !== "real") {1018    throw new Error("vault must be unlocked in real mode");1019  }1020  await ensureMigrated();10211022  // Overwrite slot B with fresh noise that matches slot A's size. The slot1023  // remains occupied so its mere existence does not signal that duress was1024  // ever configured.1025  const slotA = await loadSlot(SLOT_A);1026  if (slotA) {1027    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));1028  }10291030  duressConfigured = false;1031  await persistSlotA();1032}10331034// L14/COR-015: this function intentionally checks slot A (real vault) only.1035// A duress-mode user attempting changePassword is rejected earlier by the1036// vaultMode === 'decoy' check at changePassword. The real-vs-decoy1037// distinction here is by design — duress users cannot rotate the real1038// password by guessing it, and the asymmetry in error timing is acceptable1039// because duress mode is opt-in and the user knows their own decoy key.1040export async function verifyMainPassword(password: string): Promise<boolean> {1041  await ensureMigrated();1042  const slotA = await loadSlot(SLOT_A);1043  if (!slotA) return false;1044  const key = await deriveKey(password, unhex(slotA.salt));1045  try {1046    return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;1047  } finally {1048    zeroKey(key);1049  }1050}10511052export async function unlock(password: string): Promise<boolean> {1053  await ensureMigrated();10541055  // Load both slots in parallel. Both always exist post-migration; the1056  // parallel load and the parallel derivation below keep wall-clock time1057  // constant regardless of which slot's passphrase (real or decoy) the1058  // caller supplied, so a timing side channel cannot distinguish the1059  // duress path from the real-unlock path (DUR-002).1060  const [slotA, slotB] = await Promise.all([1061    loadSlot(SLOT_A),1062    loadSlot(SLOT_B),1063  ]);10641065  // Derive both keys in parallel, unconditionally.1066  const [keyA, keyB] = await Promise.all([1067    slotA ? deriveKey(password, unhex(slotA.salt)) : Promise.resolve(null),1068    slotB ? deriveKey(password, unhex(slotB.salt)) : Promise.resolve(null),1069  ]);10701071  // Attempt both decrypts in parallel. The Result variant lets us distinguish1072  // 'wrong_key' from 'corrupted' so callers can offer a history-restore path1073  // when a slot's schema is invalid even though AES-GCM authenticated (M7).1074  const [resultA, resultB] = await Promise.all([1075    keyA && slotA1076      ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")1077      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1078    keyB && slotB1079      ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")1080      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1081  ]);1082  const payloadA = resultA.status === "ok" ? resultA.payload : null;1083  const payloadB = resultB.status === "ok" ? resultB.payload : null;10841085  if (payloadA && keyA) {1086    derivedKey = keyA;1087    void saveSessionKey(keyA, "real");1088    vaultMode = "real";1089    entries = payloadA.entries;1090    duressConfigured = payloadA.duressConfigured;1091    buildDomainIndexSync(entries);1092    await loadSettings();1093    touchAutoLock();1094    if (keyB) zeroKey(keyB);10951096    // slotA is non-null when payloadA is truthy (keyA was derived from slotA).1097    if (slotA) {1098      const needsRecoverySetup =1099        !slotA.recovery_salt || !slotA.recovery_wrapped_root_key;1100      if (!needsRecoverySetup) {1101        rootKey = await deriveRootKeyFromDerivedKey(keyA, slotA);1102      }1103      // Pre-v2.12 vault, or a vault whose pw_root_* fields haven't been written1104      // yet: generate the recovery escrow and seed pw_root_* so subsequent1105      // unlocks can rehydrate rootKey without the user's recovery words.1106      // Best-effort — a failure here must not block unlock.1107      if (needsRecoverySetup || !rootKey) {1108        try {1109          await migrateToRecovery();1110          if (needsRecoverySetup) {1111            // String "1" matches the popup's existing peach_recovery_pending1112            // check; surfaced so the user re-confirms recovery words after a1113            // legacy-vault unlock (H2/COR-006).1114            await chrome.storage.local.set({ peach_recovery_pending: '1' });1115          }1116        } catch (migrationErr) {1117          console.warn('[Peach] recovery migration failed:', migrationErr);1118        }1119      }1120    }11211122    // If the payload had a pre-v2.11.0 shape (legacy passkey type, flat1123    // passkey fields, or pre-A-2 created/updated keys), rewrite it now so1124    // the next save uses the new format and migration doesn't re-run forever.1125    if (payloadA.migratedFromLegacy) {1126      await persistSlotA();1127    }1128    return true;1129  }11301131  if (payloadB && keyB) {1132    derivedKey = keyB;1133    void saveSessionKey(keyB, "decoy");1134    vaultMode = "decoy";1135    entries = payloadB.entries;1136    duressConfigured = false;1137    buildDomainIndexSync(entries);1138    await loadSettings();1139    touchAutoLock();1140    if (keyA) zeroKey(keyA);1141    return true;1142  }11431144  if (keyA) zeroKey(keyA);1145  if (keyB) zeroKey(keyB);1146  // Surface corruption (good AES tag, broken schema) distinctly from1147  // wrong-password so the popup can offer history-restore (M7/COR-007).1148  if (resultA.status === "corrupted") {1149    lastUnlockFailureReason = resultA.reason;1150  } else if (resultB.status === "corrupted") {1151    lastUnlockFailureReason = resultB.reason;1152  }1153  return false;1154}11551156// ---------------------------------------------------------------------------1157// MV3 service worker session key — survives SW restarts within a browser session1158// ---------------------------------------------------------------------------11591160// chrome.storage.session is cleared on browser close; survives SW restart.1161// Firefox does not implement it (persistent background script, no restart risk).1162const SESSION_KEY_STORAGE = "peach_session_dk";11631164async function saveSessionKey(key: Uint8Array, mode: "real" | "decoy"): Promise<void> {1165  if (!chrome.storage.session) return;1166  await chrome.storage.session.set({ [SESSION_KEY_STORAGE]: { keyHex: hex(key), mode } });1167}11681169async function clearSessionKey(): Promise<void> {1170  if (!chrome.storage.session) return;1171  await chrome.storage.session.remove(SESSION_KEY_STORAGE);1172}11731174/**1175 * On SW restart, re-derive all in-memory vault state from the session key1176 * stored in chrome.storage.session (set at unlock time, cleared on lock).1177 * Returns true if the vault was restored, false if no session key was found.1178 * No-ops if the vault is already unlocked.1179 */1180export async function restoreFromSession(): Promise<boolean> {1181  if (derivedKey !== null) return true;1182  if (!chrome.storage.session) return false;1183  const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);1184  const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;1185  if (!entry?.keyHex) return false;11861187  const key = unhex(entry.keyHex);1188  const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;1189  const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";1190  const slot = await loadSlot(slotKey);1191  if (!slot) { await clearSessionKey(); return false; }11921193  const result = await tryDecryptSlotResult(slot, key, aadTag);1194  if (result.status !== "ok") { await clearSessionKey(); return false; }11951196  derivedKey = key;1197  vaultMode = entry.mode;1198  entries = result.payload.entries;1199  duressConfigured = entry.mode === "real" ? result.payload.duressConfigured : false;1200  buildDomainIndexSync(entries);1201  await loadSettings();1202  touchAutoLock();12031204  if (entry.mode === "real" && slot.recovery_salt && slot.recovery_wrapped_root_key) {1205    try { rootKey = await deriveRootKeyFromDerivedKey(key, slot); } catch { /* non-fatal */ }1206  }12071208  return true;1209}12101211export function lock(): void {1212  void clearSessionKey();1213  if (derivedKey) {1214    zeroKey(derivedKey);1215    derivedKey = null;1216  }1217  if (rootKey) {1218    rootKey.fill(0);1219    rootKey = null;1220  }12211222  entries = [];1223  domainIndex = new Map();1224  vaultMode = "real";1225  duressConfigured = false;1226  clearAutoLock();1227}12281229export function isUnlocked(): boolean {1230  return derivedKey !== null;1231}12321233// Opens the vault using a pre-derived AES-256 key (skipping Argon2id).1234// Used by Android biometric unlock — the key was derived on the native side.1235export async function unlockWithKey(1236  masterKeyHex: string,1237): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {1238  try {1239    const masterKeyBytes = unhex(masterKeyHex);1240    const stored = await loadSlot(SLOT_A);1241    if (!stored) return { ok: false, error: "invalid_key" };1242    const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");1243    if (!payload) return { ok: false, error: "invalid_key" };12441245    derivedKey = masterKeyBytes;1246    vaultMode = "real";1247    entries = payload.entries;1248    duressConfigured = payload.duressConfigured;1249    buildDomainIndexSync(entries);1250    await loadSettings();1251    touchAutoLock();1252    return { ok: true, entries };1253  } catch {1254    return { ok: false, error: "invalid_key" };1255  }1256}12571258/**1259 * Restore the vault from a parsed Peach Codex payload.1260 *1261 * The supplied passphrase is verified against the Codex's slotA *before* any1262 * storage mutation — wrong passphrases return without touching disk. On1263 * success, the current vault state is snapshotted (reason: "restore") so the1264 * user can revert via Settings -> Vault History, then slotA/slotB are written1265 * and `peach_last_modified_at` is set to the Codex's recorded timestamp. A1266 * regular `unlock()` follows so the rest of the SW sees the standard1267 * post-unlock state.1268 *1269 * Intentionally non-Pro-gated — see peach_codex_v2.md "Pro gating". A Codex1270 * printed by a Pro user must always be restorable, even on a free device.1271 *1272 * Timing is not held constant here (in contrast to `unlock`): the Codex flow1273 * is an explicit user action with a known passphrase, not a passive lock1274 * screen, so the duress-vs-real timing side channel does not apply.1275 */1276export async function unlockFromCodex(params: {1277  slotA: string; // JSON string of StoredVault for slot A1278  slotB: string | null; // JSON string of StoredVault for slot B, or null1279  timestamp: number;1280  masterPassphrase: string;1281}): Promise<1282  | { ok: true; entryCount: number }1283  | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" }1284> {1285  let parsedSlotA: StoredVault;1286  let parsedSlotB: StoredVault | null = null;1287  try {1288    const rawA = JSON.parse(params.slotA) as unknown;1289    if (!hasValidVaultSchema(rawA)) {1290      return { ok: false, reason: "invalid_slot_format" };1291    }1292    parsedSlotA = rawA;1293    if (params.slotB !== null) {1294      const rawB = JSON.parse(params.slotB) as unknown;1295      if (!hasValidVaultSchema(rawB)) {1296        return { ok: false, reason: "invalid_slot_format" };1297      }1298      parsedSlotB = rawB;1299    }1300  } catch {1301    return { ok: false, reason: "invalid_slot_format" };1302  }13031304  // Verify the passphrase against the supplied slotA WITHOUT writing anything.1305  // If this fails the on-disk vault is left completely untouched.1306  const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));1307  const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");1308  if (!trialPayload) {1309    zeroKey(trialKey);1310    return { ok: false, reason: "wrong_passphrase" };1311  }1312  // Drop the trial key; `unlock()` below derives its own copy. Holding two1313  // copies of the master key in memory at once would be a needless surface.1314  zeroKey(trialKey);13151316  // Snapshot the about-to-be-overwritten on-disk state so the user can revert1317  // a mistaken Codex restore via the Vault History UI. Non-fatal if it fails.1318  await takeVaultSnapshot("restore");13191320  await writeSlot(SLOT_A, parsedSlotA);1321  if (parsedSlotB) {1322    await writeSlot(SLOT_B, parsedSlotB);1323  } else {1324    // Slot B must always exist with ciphertext length matching slot A1325    // (Projects.md §3.2). Codex prints may omit slot B (duress wasn't1326    // configured); regenerate noise to satisfy the invariant.1327    await writeSlot(1328      SLOT_B,1329      generateNoiseBlob(parsedSlotA.ciphertext.length / 2),1330    );1331  }1332  await chrome.storage.local.set({1333    peach_last_modified_at: String(params.timestamp),1334  });13351336  // Standard unlock path so domain index, settings, auto-lock, and1337  // recovery-key state all populate exactly as a normal unlock would.1338  const ok = await unlock(params.masterPassphrase);1339  if (!ok) {1340    // Should be unreachable — we just verified the passphrase against the1341    // same slotA we wrote. Treat as wrong_passphrase to keep the contract1342    // simple if some race or storage anomaly intrudes.1343    return { ok: false, reason: "wrong_passphrase" };1344  }1345  return { ok: true, entryCount: getEntries().length };1346}13471348// Returns the current in-memory derived key as a hex string.1349// Used by the biometric enable flow in Settings to store the key in Android Keystore.1350export function getDerivedKeyHex(): string {1351  if (!derivedKey) throw new Error("vault_not_unlocked");1352  return hex(derivedKey);1353}13541355export function getEntries(): VaultEntry[] {1356  if (!derivedKey) throw new Error("vault_locked");1357  return entries.filter((entry) => !entry.deletedAt);1358}13591360const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;13611362export function getIdentities(): SavedIdentity[] {1363  if (!derivedKey) throw new Error("vault_locked");1364  const active = entries.filter((e) => !e.deletedAt && e.type === "login");13651366  const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();1367  const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();13681369  for (const entry of active) {1370    const domain = extractDomain(entry.url ?? "") ?? "";1371    const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;13721373    function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {1374      const existing = map.get(v);1375      if (!existing || modifiedAt > existing.lastUsed) {1376        map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });1377      } else {1378        map.set(v, { ...existing, count: existing.count + 1 });1379      }1380    }13811382    const uVal = entry.username?.trim();1383    if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);13841385    // Also count the dedicated email field — entries created via the inline1386    // popup new-entry form store email here rather than in username.1387    const eVal = entry.email?.trim();1388    if (eVal) tally(emailMap, eVal);1389  }13901391  const toIdentity = (type: "email" | "username") =>1392    ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({1393      value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,1394    });13951396  return [1397    ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),1398    ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),1399  ];1400}14011402export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {1403  if (!derivedKey) throw new Error("vault_locked");14041405  const now = Date.now();1406  const added: VaultEntry[] = [];1407  for (const draft of drafts) {1408    try {1409      const sanitized = sanitizeEntryDraft(draft);1410      const nextEntry: VaultEntry = {1411        ...sanitized,1412        id: crypto.randomUUID(),1413        createdAt: now,1414        modifiedAt: monotonicEntryTimestamp(),1415      };1416      entries.push(nextEntry);1417      added.push(nextEntry);1418    } catch {1419      // Skip invalid drafts silently — caller can see diff between input and output length1420    }1421  }14221423  if (added.length > 0) {1424    await persistEntries();1425  }14261427  return added;1428}14291430/**1431 * Restore a set of entries in full fidelity — preserves id, createdAt,1432 * modifiedAt, and every other field unlike `batchAddEntries` which1433 * assigns fresh identity. Used by restore paths where the backup is the1434 * authoritative source of truth. `mode` controls how entries already in1435 * the vault are treated.1436 */1437export async function restoreEntries(1438  incoming: VaultEntry[],1439  mode: "replace" | "merge"1440): Promise<{ added: number; updated: number; skipped: number }> {1441  if (!derivedKey) throw new Error("vault_locked");14421443  // A replace with zero incoming entries is almost certainly a caller bug1444  // (e.g. an import that silently dropped everything). Refuse rather than1445  // wipe the vault.1446  if (mode === "replace" && incoming.length === 0) {1447    throw new Error("refuse to replace with empty entry set");1448  }14491450  let added = 0;1451  let updated = 0;1452  let skipped = 0;14531454  if (mode === "replace") {1455    entries = [];1456    for (const entry of incoming) {1457      const normalized = sanitizeRestoredEntry(entry);1458      if (!normalized) {1459        skipped += 1;1460        continue;1461      }1462      entries.push(normalized);1463      added += 1;1464    }1465  } else {1466    const byId = new Map<string, VaultEntry>();1467    for (const e of entries) byId.set(e.id, e);14681469    for (const entry of incoming) {1470      const normalized = sanitizeRestoredEntry(entry);1471      if (!normalized) {1472        skipped += 1;1473        continue;1474      }1475      const existing = byId.get(normalized.id);1476      if (!existing) {1477        entries.push(normalized);1478        added += 1;1479      } else if (normalized.modifiedAt > existing.modifiedAt) {1480        const idx = entries.findIndex((e) => e.id === existing.id);1481        if (idx !== -1) {1482          entries[idx] = normalized;1483          updated += 1;1484        }1485      } else {1486        skipped += 1;1487      }1488    }1489  }14901491  await persistEntries("import");1492  return { added, updated, skipped };1493}14941495/**1496 * Validate + normalise a VaultEntry coming from a backup. Accepts1497 * anything structurally sound; keeps all metadata verbatim. Returns1498 * null for values the live vault shouldn't accept (e.g., missing title).1499 */1500function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {1501  if (!entry || typeof entry !== "object") return null;1502  const title = typeof entry.title === "string" ? entry.title.trim() : "";1503  if (!title) return null;1504  const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();1505  const now = Date.now();1506  const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;1507  const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;15081509  // Migrate legacy passkey shape on import (same logic as on-disk read).1510  // Imports from pre-v2.11.0 vault backups still carry type:"passkey" with1511  // flat fields; bring them into the new shape immediately.1512  const migrated: VaultEntry = migrateLegacyPasskey(1513    {1514      ...entry,1515      id,1516      title,1517      type: entry.type ?? "login",1518      createdAt,1519      modifiedAt,1520    },1521    entry1522  );15231524  // Login entries from backup must carry a password (or be passkey-only,1525  // in which case the passkey sub-object replaces the password requirement).1526  if (1527    migrated.type === "login" &&1528    !migrated.passkey &&1529    typeof migrated.password !== "string"1530  ) {1531    return null;1532  }1533  if (migrated.passkey && !migrated.passkey.credentialId) {1534    return null;1535  }15361537  return migrated;1538}15391540// Soft-deletes every non-deleted entry in one call. The literal string1541// argument is a tripwire against accidental calls — any caller that would1542// wipe the vault has to consciously type "REPLACE_ALL". Do not relax this1543// to a boolean.1544export async function clearVaultEntries(1545  confirmation: "REPLACE_ALL"1546): Promise<void> {1547  if (confirmation !== "REPLACE_ALL") {1548    throw new Error("clearVaultEntries requires explicit confirmation");1549  }1550  if (!derivedKey) throw new Error("vault_locked");1551  for (const entry of entries) {1552    if (!entry.deletedAt) {1553      const stamp = monotonicEntryTimestamp(entry.modifiedAt);1554      entry.deletedAt = stamp;1555      entry.modifiedAt = stamp;1556    }1557  }1558  await persistEntries();1559}15601561export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {1562  if (!derivedKey) throw new Error("vault_locked");15631564  const sanitized = sanitizeEntryDraft(entry);1565  const now = Date.now();1566  const stamp = monotonicEntryTimestamp();1567  const nextEntry: VaultEntry = {1568    ...sanitized,1569    id: crypto.randomUUID(),1570    createdAt: now,1571    modifiedAt: stamp,1572    // Stamp passwordChangedAt at creation so age tracking is accurate from1573    // day one. Non-login entries carry the same stamp harmlessly.1574    passwordChangedAt: sanitized.password ? stamp : undefined,1575  };15761577  // Clone-and-replace so a failed persist rolls back the in-memory state1578  // (COR-008). Without this, a quota-full or storage error leaves the1579  // module-level `entries` ahead of what's actually on disk.1580  const rollback = entries;1581  entries = [...entries, nextEntry];1582  try {1583    await persistEntries();1584  } catch (err) {1585    entries = rollback;1586    throw err;1587  }15881589  // Fire-and-forget breach check (only for login entries if breach monitoring is enabled or not set)1590  if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {1591    checkBreach(nextEntry.password).then(async (count) => {1592      if (count > 0) {1593        const idx = entries.findIndex((e) => e.id === nextEntry.id);1594        if (idx !== -1) {1595          entries[idx] = { ...entries[idx], breach: count, modifiedAt: monotonicEntryTimestamp(entries[idx].modifiedAt) };1596          await persistEntries();1597        }1598      }1599    });1600  }16011602  fireSyncTrigger("vault_change");16031604  return nextEntry;1605}16061607export async function updateEntry(1608  id: string,1609  patch: Partial<VaultEntry>1610): Promise<void> {1611  if (!derivedKey) throw new Error("vault_locked");16121613  const idx = entries.findIndex((entry) => entry.id === id);1614  if (idx === -1 || entries[idx].deletedAt) {1615    throw new Error("entry_not_found");1616  }16171618  const current = entries[idx];1619  const sanitizedPatch = sanitizeEntryPatch(patch);1620  // Refresh passwordChangedAt only when the password value actually changes —1621  // a metadata-only update (title, tags, etc.) must not reset the age clock1622  // that drives the Pro health rotation recommendation.1623  const passwordChanged =1624    "password" in patch &&1625    typeof sanitizedPatch.password === "string" &&1626    sanitizedPatch.password !== current.password;1627  const stamp = monotonicEntryTimestamp(current.modifiedAt);1628  entries[idx] = {1629    ...current,1630    ...sanitizedPatch,1631    modifiedAt: stamp,1632    ...(passwordChanged ? { passwordChangedAt: stamp } : {}),1633  };1634163516361637  // Card entries must retain their card number1638  if (entries[idx].type === "card" && !entries[idx].cardNumber) {1639    entries[idx] = current;1640    throw new Error("card number is required for card entries");1641  }16421643  // Roll the in-memory entry back to its pre-edit state if the disk write1644  // fails (e.g. storage quota). Without this the module-level `entries` array1645  // would hold an edit that never landed on disk, diverging from the vault1646  // until the next unlock silently reverts it (SEV-3-A). Mirrors addEntry.1647  try {1648    await persistEntries();1649  } catch (err) {1650    entries[idx] = current;1651    throw err;1652  }16531654  // Breach check when password changes: clear immediately so old breach doesn't linger,1655  // then async-check the new password and only re-set if it's also found.1656  if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {1657    entries[idx] = { ...entries[idx], breach: undefined };1658    await persistEntries();1659    const password = entries[idx].password;1660    if (password) {1661      checkBreach(password).then(async (count) => {1662        const i = entries.findIndex((e) => e.id === id);1663        if (i !== -1 && count > 0) {1664          entries[i] = { ...entries[i], breach: count, modifiedAt: monotonicEntryTimestamp(entries[i].modifiedAt) };1665          await persistEntries();1666        }1667      });1668    }1669  }16701671  fireSyncTrigger("vault_change");1672}16731674export async function deleteEntry(id: string): Promise<void> {1675  if (!derivedKey) throw new Error("vault_locked");16761677  const entry = entries.find((item) => item.id === id);1678  if (!entry || entry.deletedAt) {1679    throw new Error("entry_not_found");1680  }16811682  // Tombstone timestamp must be strictly greater than the entry's last1683  // modification so the deletion wins LWW against any in-flight edit, even1684  // under clock skew (SEV-2-E).1685  const previousModifiedAt = entry.modifiedAt;1686  const stamp = monotonicEntryTimestamp(entry.modifiedAt);1687  entry.deletedAt = stamp;1688  entry.modifiedAt = stamp;1689  // Roll the tombstone back if the disk write fails, so a quota error doesn't1690  // leave the entry deleted in memory but alive on disk (SEV-3-A).1691  try {1692    await persistEntries();1693  } catch (err) {1694    delete entry.deletedAt;1695    entry.modifiedAt = previousModifiedAt;1696    throw err;1697  }1698  fireSyncTrigger("vault_change");1699}17001701export function getDeletedEntries(): VaultEntry[] {1702  if (!derivedKey) return [];1703  return entries.filter((e) => !!e.deletedAt);1704}17051706/**1707 * Returns the vault's monotonic version — the `peach_last_modified_at` value1708 * stamped on every user-initiated write. Remote (sync) writes do NOT advance1709 * this version so a sync round never cascades into a second outbound sync.1710 */1711export async function getVaultVersion(): Promise<number> {1712  try {1713    const raw = await chrome.storage.local.get("peach_last_modified_at");1714    const v = (raw as Record<string, unknown>).peach_last_modified_at;1715    if (typeof v === "number") return v;1716    if (typeof v === "string" && v !== "") {1717      const n = Number.parseInt(v, 10);1718      return Number.isFinite(n) ? n : 0;1719    }1720    return 0;1721  } catch {1722    return 0;1723  }1724}17251726/**1727 * Internal write variants — bypass `fireSyncTrigger` so the sync layer can1728 * apply entries without cascading into another outbound sync round.1729 *1730 * INVARIANT: callers must not pass entries whose IDs collide with existing1731 * active (non-deleted) entries unless the intent is an explicit overwrite.1732 * These functions do not validate field-level constraints (password required,1733 * card number required, etc.) — they are trust-the-caller paths for sync and1734 * test harness use only.1735 */1736export async function addEntryDirect(entry: VaultEntry): Promise<void> {1737  if (!derivedKey) throw new Error("vault_locked");1738  entries = [...entries, entry];1739  await persistEntries("sync_received");1740}17411742export async function updateEntryDirect(patch: VaultEntry): Promise<void> {1743  if (!derivedKey) throw new Error("vault_locked");1744  const idx = entries.findIndex((e) => e.id === patch.id);1745  if (idx === -1) throw new Error("entry_not_found");1746  entries[idx] = { ...entries[idx], ...patch };1747  await persistEntries("sync_received");1748}17491750export async function deleteEntryDirect(id: string, deletedAt: number): Promise<void> {1751  if (!derivedKey) throw new Error("vault_locked");1752  const idx = entries.findIndex((e) => e.id === id);1753  if (idx === -1) throw new Error("entry_not_found");1754  entries[idx] = { ...entries[idx], deletedAt, modifiedAt: deletedAt };1755  await persistEntries("sync_received");1756}17571758/**1759 * Apply a batch of remote entries + tombstones from a chirp-sync peer.1760 * Last-write-wins by `modifiedAt`; a tombstone supersedes a live entry when1761 * `deletedAt > modifiedAt` on the local side. Mutates `entries` directly and1762 * persists with reason `sync_received` — does NOT fire the sync dispatcher, so1763 * applying a sync round cannot cascade into another outbound sync.1764 *1765 * `applied` counts entries that actually changed local state (new add,1766 * overwrite-by-newer, or new tombstone). `received` is the raw payload size1767 * the caller can surface in the sync result UI.1768 */1769export async function applyMergedRemoteEntries(1770  remoteEntries: VaultEntry[],1771  remoteTombstones: Record<string, number>,1772): Promise<{ received: number; applied: number; conflicts: number }> {1773  if (!derivedKey) throw new Error("vault_locked");17741775  const received = remoteEntries.length + Object.keys(remoteTombstones).length;1776  let applied = 0;1777  let conflicts = 0;17781779  const byId = new Map<string, VaultEntry>();1780  for (const e of entries) byId.set(e.id, e);17811782  for (const remote of remoteEntries) {1783    const sanitized = sanitizeRestoredEntry(remote);1784    if (!sanitized) continue;1785    const tombstoneTs = remoteTombstones[sanitized.id];1786    if (tombstoneTs !== undefined && tombstoneTs >= sanitized.modifiedAt) {1787      continue;1788    }1789    const local = byId.get(sanitized.id);1790    if (!local) {1791      entries.push(sanitized);1792      byId.set(sanitized.id, sanitized);1793      applied += 1;1794    } else if (sanitized.modifiedAt > local.modifiedAt) {1795      const idx = entries.findIndex((e) => e.id === local.id);1796      if (idx !== -1) {1797        entries[idx] = sanitized;1798        byId.set(sanitized.id, sanitized);1799        applied += 1;1800        if (!local.deletedAt) conflicts += 1;1801      }1802    }1803  }18041805  for (const [id, deletedAt] of Object.entries(remoteTombstones)) {1806    if (typeof deletedAt !== "number" || !Number.isFinite(deletedAt)) continue;1807    const local = byId.get(id);1808    if (!local) continue;1809    if (local.deletedAt && local.deletedAt >= deletedAt) continue;1810    if (deletedAt < local.modifiedAt) continue;1811    const idx = entries.findIndex((e) => e.id === id);1812    if (idx !== -1) {1813      entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };1814      applied += 1;1815    }1816  }18171818  if (applied > 0) {1819    await persistEntries("sync_received");1820    buildDomainIndexSync(entries);1821  }1822  return { received, applied, conflicts };1823}18241825export async function restoreEntry(id: string): Promise<void> {1826  if (!derivedKey) throw new Error("vault_locked");1827  const entry = entries.find((e) => e.id === id && e.deletedAt);1828  if (!entry) throw new Error("deleted entry not found");1829  delete entry.deletedAt;1830  entry.modifiedAt = monotonicEntryTimestamp(entry.modifiedAt);1831  await persistEntries();1832  buildDomainIndexSync(entries);1833}18341835export async function purgeEntry(id: string): Promise<void> {1836  if (!derivedKey) throw new Error("vault_locked");1837  const idx = entries.findIndex((e) => e.id === id && e.deletedAt);1838  if (idx === -1) throw new Error("deleted entry not found");1839  entries.splice(idx, 1);1840  await persistEntries();1841}18421843/** Permanently delete entries whose deletedAt is older than retentionMs. 0 = keep forever. */1844export async function purgeExpiredTrash(retentionMs: number): Promise<number> {1845  if (!derivedKey || retentionMs === 0) return 0;1846  const cutoff = Date.now() - retentionMs;1847  const before = entries.length;1848  entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));1849  const purged = before - entries.length;1850  if (purged > 0) await persistEntries();1851  return purged;1852}18531854export function queryDomain(domain: string): VaultEntry[] {1855  return domainIndex.get(domain) ?? [];1856}18571858export function getEntryById(id: string): VaultEntry | undefined {1859  return entries.find((entry) => entry.id === id && !entry.deletedAt);1860}18611862async function persistSlotA(1863  reason: VaultSnapshot["reason"] = "local_save",1864): Promise<StoredVault> {1865  if (!derivedKey) throw new Error("vault_locked");18661867  const slotA = await loadSlot(SLOT_A);1868  if (!slotA) throw new Error("missing slot A");18691870  // Snapshot the about-to-be-overwritten state BEFORE we mutate disk. Failures1871  // are swallowed by takeVaultSnapshot — history must never block a save.1872  await takeVaultSnapshot(reason);18731874  const plaintext = encodePayload(entries, duressConfigured);1875  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");18761877  // Preserve existing recovery escrow fields.1878  const nextSlotA: StoredVault = {1879    ...slotA,1880    nonce,1881    ciphertext,1882    tag,1883    // recovery_salt and recovery_wrapped_root_key are already set from loadSlot1884  };1885  await writeSlot(SLOT_A, nextSlotA);18861887  // When duress is not configured, keep slot B size-matched with slot A by1888  // regenerating its noise. When duress IS configured, leave slot B alone —1889  // we don't have the decoy key to re-encrypt it. This is a known trade-off.1890  if (!duressConfigured) {1891    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));1892  }1893  // Only advance the vault version for locally-originated writes. Entries1894  // applied from a sync peer ("sync_received") must NOT bump the counter —1895  // otherwise applying a remote round makes us look newer than the peer and1896  // triggers a redundant outbound sync, defeating the no-op optimisation1897  // and risking a ping-pong between two devices (SEV-2-C).1898  if (reason !== "sync_received") {1899    await stampLocalVaultMutation();1900  }19011902  return nextSlotA;1903}19041905async function persistSlotB(): Promise<void> {1906  if (!derivedKey) throw new Error("vault_locked");19071908  const slotB = await loadSlot(SLOT_B);1909  if (!slotB) throw new Error("missing slot B");19101911  // Decoy plaintext always reports duressConfigured=false — the decoy user1912  // sees a clean slate.1913  const plaintext = encodePayload(entries, false);1914  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");19151916  await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });1917  await stampLocalVaultMutation();1918}19191920async function persistEntries(1921  reason: VaultSnapshot["reason"] = "local_save",1922): Promise<void> {1923  if (!derivedKey) throw new Error("vault_locked");19241925  if (vaultMode === "decoy") {1926    await persistSlotB();1927  } else {1928    await persistSlotA(reason);1929  }1930  buildDomainIndexSync(entries);1931}19321933function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {1934  if (!Array.isArray(values)) return undefined;1935  const seen = new Set<string>();1936  const cleaned: string[] = [];1937  for (const value of values) {1938    const trimmed = typeof value === "string" ? value.trim() : "";1939    if (!trimmed) continue;1940    const key = trimmed.toLowerCase();1941    if (seen.has(key)) continue;1942    seen.add(key);1943    cleaned.push(trimmed);1944  }1945  return cleaned.length > 0 ? cleaned : undefined;1946}19471948function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {1949  const title = entry.title.trim();1950  // Accept legacy `type:"passkey"` drafts but rewrite to "login" — the new1951  // model is "any entry, optionally with a passkey sub-object." Imports and1952  // any in-flight callers from before v2.11.0 keep working without throwing.1953  let type: VaultEntry["type"] = entry.type ?? "login";1954  if (type === "passkey") type = "login";19551956  if (!title) throw new Error("title is required");19571958  if (entry.passkey) {1959    const p = entry.passkey;1960    if (1961      !p.rpId ||1962      !p.credentialId ||1963      !p.publicKeyCose ||1964      !p.userHandle ||1965      !p.userName ||1966      (p.algorithm !== -7 && p.algorithm !== -8)1967    ) {1968      throw new Error("invalid passkey credential");1969    }1970  }1971  if (type === "card") {1972    if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {1973      throw new Error("cardholder name and card number are required");1974    }1975  }19761977  return {1978    type,1979    title,1980    username: type === "login" ? entry.username?.trim() ?? "" : undefined,1981    email: type === "login" ? entry.email?.trim() || undefined : undefined,1982    password: type === "login" ? entry.password : undefined,1983    url: type === "login" ? entry.url?.trim() ?? "" : undefined,1984    additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,1985    totp: type === "login" ? entry.totp?.trim() || undefined : undefined,1986    notes: entry.notes?.trim() || undefined,1987    breach: type === "login" ? entry.breach : undefined,1988    canary: type === "login" ? entry.canary : undefined,1989    tags: entry.tags,1990    passkey: entry.passkey,1991    cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,1992    cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,1993    expMonth: type === "card" ? entry.expMonth?.trim() : undefined,1994    expYear: type === "card" ? entry.expYear?.trim() : undefined,1995    cvc: type === "card" ? entry.cvc?.trim() : undefined,1996    cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,1997    network: type === "card" ? entry.network : undefined,1998    last4: type === "card" ? entry.last4?.trim() : undefined,1999  };2000}20012002function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {2003  const nextPatch: Partial<VaultEntry> = {};20042005  if ("type" in patch) {2006    nextPatch.type = patch.type;2007  }20082009  if ("title" in patch) {2010    const title = patch.title?.trim() ?? "";2011    if (!title) throw new Error("title is required");2012    nextPatch.title = title;2013  }20142015  if ("url" in patch) {2016    nextPatch.url = patch.url?.trim() ?? "";2017  }20182019  if ("additionalUrls" in patch) {2020    const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];2021    const seen = new Set<string>();2022    const cleaned: string[] = [];2023    for (const value of incoming) {2024      const trimmed = typeof value === "string" ? value.trim() : "";2025      if (!trimmed) continue;2026      const key = trimmed.toLowerCase();2027      if (seen.has(key)) continue;2028      seen.add(key);2029      cleaned.push(trimmed);2030    }2031    nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;2032  }20332034  if ("username" in patch) {2035    nextPatch.username = patch.username?.trim() ?? "";2036  }20372038  if ("email" in patch) {2039    nextPatch.email = patch.email?.trim() || undefined;2040  }20412042  if ("password" in patch) {2043    const password = patch.password ?? "";2044    // Allow clearing a password (e.g. on passkey-only entries)2045    nextPatch.password = password || undefined;2046  }20472048  if ("totp" in patch) {2049    nextPatch.totp = patch.totp?.trim() || undefined;2050  }20512052  if ("notes" in patch) {2053    nextPatch.notes = patch.notes?.trim() || undefined;2054  }20552056  if ("breach" in patch) {2057    nextPatch.breach = patch.breach;2058  }20592060  if ("canary" in patch) {2061    nextPatch.canary = patch.canary;2062  }20632064  if ("passkey" in patch) {2065    // Passkey sub-object replaces all the legacy flat passkey fields. A2066    // patch with `passkey: undefined` removes the credential from the entry2067    // (used by "remove passkey" without deleting the whole entry).2068    nextPatch.passkey = patch.passkey;2069  }20702071  if ("tags" in patch) {2072    nextPatch.tags = patch.tags;2073  }20742075  if ("cardholderName" in patch) {2076    nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;2077  }2078  if ("cardNumber" in patch) {2079    const n = patch.cardNumber ?? "";2080    nextPatch.cardNumber = n || undefined;2081  }2082  if ("expMonth" in patch) {2083    nextPatch.expMonth = patch.expMonth?.trim() || undefined;2084  }2085  if ("expYear" in patch) {2086    nextPatch.expYear = patch.expYear?.trim() || undefined;2087  }2088  if ("cvc" in patch) {2089    nextPatch.cvc = patch.cvc?.trim() || undefined;2090  }2091  if ("cardNickname" in patch) {2092    nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;2093  }2094  if ("network" in patch) {2095    nextPatch.network = patch.network;2096  }2097  if ("last4" in patch) {2098    nextPatch.last4 = patch.last4?.trim() || undefined;2099  }21002101  return nextPatch;2102}21032104function normalizeEntry(entry: VaultEntry | LegacyVaultEntry): VaultEntry {2105  const createdAt = "createdAt" in entry ? entry.createdAt : entry.created;2106  const modifiedAt =2107    "modifiedAt" in entry ? entry.modifiedAt : entry.updated;21082109  const base: VaultEntry = {2110    id: entry.id,2111    type: "type" in entry ? entry.type : "login",2112    title: entry.title,2113    username: entry.username,2114    email: "email" in entry ? entry.email : undefined,2115    password: entry.password,2116    url: entry.url,2117    additionalUrls:2118      "additionalUrls" in entry && Array.isArray(entry.additionalUrls)2119        ? entry.additionalUrls2120        : undefined,2121    totp: entry.totp,2122    notes: entry.notes,2123    breach: entry.breach,2124    // Preserve the password-age clock across lock/unlock. Without this the2125    // field is dropped on every decode and the advanced-health "aged password"2126    // signal silently resets to createdAt on each unlock (SEV-2-A).2127    passwordChangedAt:2128      "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,2129    canary: "canary" in entry ? entry.canary : undefined,2130    passkey: "passkey" in entry ? entry.passkey : undefined,2131    createdAt,2132    modifiedAt,2133    deletedAt: entry.deletedAt,2134    tags: "tags" in entry ? entry.tags : undefined,2135    cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,2136    cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,2137    expMonth: "expMonth" in entry ? entry.expMonth : undefined,2138    expYear: "expYear" in entry ? entry.expYear : undefined,2139    cvc: "cvc" in entry ? entry.cvc : undefined,2140    cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,2141    network: "network" in entry ? entry.network : undefined,2142    last4: "last4" in entry ? entry.last4 : undefined,2143  };21442145  return migrateLegacyPasskey(base, entry);2146}21472148/**2149 * v2.11.0 read migration. Pre-v2.11.0 passkey entries used `type:"passkey"`2150 * with flat top-level fields (rpId, credentialId, etc.). This converts them2151 * to the new shape — `type:"login"` with a `passkey` sub-object — so all2152 * downstream consumers can rely on the new model. The result is rewritten2153 * to disk on next vault save (hasLegacyShape detects the un-migrated case).2154 */2155function migrateLegacyPasskey(2156  base: VaultEntry,2157  raw: VaultEntry | LegacyVaultEntry2158): VaultEntry {2159  if (base.passkey) return base;2160  const flat = raw as Partial<VaultEntry>;2161  const isPasskeyType = base.type === "passkey";2162  const hasFlatPasskeyFields =2163    typeof flat.rpId === "string" &&2164    typeof flat.credentialId === "string" &&2165    typeof flat.publicKeyCose === "string" &&2166    typeof flat.userHandle === "string" &&2167    typeof flat.userName === "string";2168  if (!isPasskeyType && !hasFlatPasskeyFields) return base;2169  if (!hasFlatPasskeyFields) return base;21702171  const algorithm: -7 | -8 = flat.algorithm === -8 ? -8 : -7;2172  base.passkey = {2173    rpId: flat.rpId!,2174    rpName: flat.rpName ?? flat.rpId!,2175    credentialId: flat.credentialId!,2176    publicKeyCose: flat.publicKeyCose!,2177    privateKeyJwk: flat.privateKeyJwk,2178    userHandle: flat.userHandle!,2179    userName: flat.userName!,2180    userDisplayName: flat.userDisplayName ?? flat.userName!,2181    algorithm,2182    signCount: flat.signCount ?? 0,2183    aaguid: flat.aaguid ?? "",2184    backupEligible: flat.backupEligible === true,2185    backupState: flat.backupState === true,2186    lastUsedAt: flat.lastUsedAt,2187    browser: flat.browser,2188    transports: flat.transports,2189    createdAt: base.createdAt,2190  };2191  // Promote to "login" so the unified Entry view renders. Username gets2192  // populated from the passkey's userName so the entry is searchable in the2193  // existing autofill flow without a separate code path.2194  if (isPasskeyType) base.type = "login";2195  if (!base.username) base.username = flat.userName;2196  if (!base.url) base.url = `https://${flat.rpId}`;2197  return base;2198}219922002201// ---------------------------------------------------------------------------2202// Deduplication2203// ---------------------------------------------------------------------------22042205function entryDupeKey(e: VaultEntry): string {2206  if (e.type === "note") return `note|${e.title.toLowerCase()}`;2207  // Passkey-bearing entries dedupe by the credential's RP + user. Two logins2208  // on different sites that happen to share a username are still distinct;2209  // two passkey credentials for the same RP+user are duplicates regardless2210  // of any login fields they may also carry.2211  if (e.passkey) {2212    return `passkey|${e.passkey.rpId.toLowerCase()}|${e.passkey.userName.toLowerCase()}`;2213  }2214  return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;2215}22162217/** Returns the number of duplicate entries (those that would be removed). */2218export function countDuplicates(): number {2219  const best = new Map<string, VaultEntry>();2220  let dupeCount = 0;2221  for (const e of entries.filter((e) => !e.deletedAt)) {2222    const key = entryDupeKey(e);2223    const existing = best.get(key);2224    if (!existing) {2225      best.set(key, e);2226    } else {2227      dupeCount++;2228      // Keep the more recently modified one in the map2229      if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2230        best.set(key, e);2231      }2232    }2233  }2234  return dupeCount;2235}22362237/**2238 * Soft-deletes duplicate entries, keeping the most recently modified copy of2239 * each group. Returns the number of entries moved to trash.2240 */2241export async function deduplicateEntries(): Promise<number> {2242  if (!derivedKey) throw new Error("vault_locked");2243  // Dedup reshapes slot B permanently under the decoy key, which is2244  // forensically distinguishable from a freshly-seeded decoy vault. Refuse.2245  if (vaultMode === "decoy") {2246    throw new Error("deduplicate disabled in decoy mode");2247  }22482249  const best = new Map<string, VaultEntry>();2250  for (const e of entries.filter((en) => !en.deletedAt)) {2251    const key = entryDupeKey(e);2252    const existing = best.get(key);2253    if (!existing) {2254      best.set(key, e);2255    } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2256      best.set(key, e);2257    }2258  }22592260  const keepIds = new Set(Array.from(best.values()).map((e) => e.id));2261  let removed = 0;2262  entries = entries.map((e) => {2263    if (!e.deletedAt && !keepIds.has(e.id)) {2264      removed++;2265      return { ...e, deletedAt: monotonicEntryTimestamp(e.modifiedAt) };2266    }2267    return e;2268  });22692270  if (removed > 0) await persistEntries();2271  return removed;2272}22732274// ---------------------------------------------------------------------------2275// Vault history — snapshot BEFORE every vault write so the saved blob is2276// what is about to be lost, not what was just written. Capped at 10. The2277// stored blobs are AES-256-GCM ciphertext under the master password, so2278// history adds zero security surface.2279// ---------------------------------------------------------------------------22802281const HISTORY_KEY = "peach_vault_history";2282const HISTORY_MAX = 10;22832284/**2285 * Snapshot the CURRENT on-disk vault state into history. Call this BEFORE2286 * overwriting peach_vault_a so the saved blob captures the about-to-be-lost2287 * state. Identical-to-most-recent blobs are skipped to avoid filling history2288 * with no-op writes.2289 */2290export async function takeVaultSnapshot(2291  reason: VaultSnapshot["reason"],2292): Promise<void> {2293  try {2294    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);2295    const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];2296    const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];22972298    // Nothing to snapshot if the real slot doesn't exist yet (fresh install,2299    // pre-createVault). createVault skips snapshots intentionally — there is2300    // no prior state to preserve.2301    if (!slotA) return;23022303    const vault_a = JSON.stringify(slotA);2304    const vault_b = JSON.stringify(slotB ?? slotA);23052306    // Best-effort entry count: only meaningful when the in-memory state is2307    // unlocked AND in real mode. Decoy mode would leak the decoy entry2308    // count; locked mode has no entries to count. Both fall through to null.2309    let entryCount: number | null = null;2310    if (derivedKey && vaultMode === "real") {2311      try {2312        entryCount = entries.filter((e) => !e.deletedAt).length;2313      } catch {2314        entryCount = null;2315      }2316    }23172318    const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];2319    const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)2320      ? existingRaw2321      : { snapshots: [] };23222323    // Deduplication: if the most recent snapshot has byte-identical blobs,2324    // skip — saves the same vault N times in a row would otherwise burn the2325    // entire history window with no recovery value.2326    const latest = history.snapshots[0];2327    if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {2328      return;2329    }23302331    const snapshot: VaultSnapshot = {2332      id: crypto.randomUUID(),2333      savedAt: Date.now(),2334      reason,2335      vault_a,2336      vault_b,2337      entryCount,2338    };23392340    history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);2341    await chrome.storage.local.set({ [HISTORY_KEY]: history });2342  } catch (err) {2343    // Non-fatal — history must never block a save. A failed snapshot just2344    // means the user loses one rung of the safety ladder for this write.2345    // M4/QUA-006: log so the failure is visible; if it looks like a quota2346    // problem, notify the popup so the user can prune history themselves.2347    console.warn('[Peach] takeVaultSnapshot failed:', err);2348    if (String(err).includes('QUOTA') || String(err).includes('quota')) {2349      try {2350        await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });2351      } catch {2352        // popup may be closed; surfaced via console.warn above2353      }2354    }2355  }2356}23572358/** Wipe all vault history. Called by Panic / DESTROY_VAULT. */2359export async function clearVaultHistory(): Promise<void> {2360  try {2361    await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });2362  } catch {2363    // Non-fatal — DESTROY_VAULT also runs storage.local.clear().2364  }2365}23662367/** Read all snapshots, newest first, for the Settings vault history view. */2368export async function getVaultHistory(): Promise<VaultSnapshot[]> {2369  const raw = await chrome.storage.local.get(HISTORY_KEY);2370  const history = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];2371  if (!history || !Array.isArray(history.snapshots)) return [];2372  return history.snapshots;2373}23742375/**2376 * Replace the on-disk vault with the chosen snapshot's blobs and lock the2377 * vault. The current state is itself snapshotted with reason 'restore' first2378 * so the restore is reversible. After this returns, the user must unlock2379 * with the password that matches the restored blob.2380 */2381export async function restoreVaultSnapshot(2382  snapshotId: string,2383): Promise<{ ok: true } | { ok: false; error: string }> {2384  const history = await getVaultHistory();2385  const snapshot = history.find((s) => s.id === snapshotId);2386  if (!snapshot) return { ok: false, error: "snapshot_not_found" };23872388  // Snapshot the about-to-be-replaced current state so the restore is2389  // reversible. takeVaultSnapshot is no-op when the most recent entry is2390  // byte-identical, so a restore-of-a-restore stays clean.2391  await takeVaultSnapshot("restore");23922393  let restoredA: StoredVault;2394  let restoredB: StoredVault;2395  try {2396    restoredA = JSON.parse(snapshot.vault_a) as StoredVault;2397    restoredB = JSON.parse(snapshot.vault_b) as StoredVault;2398  } catch {2399    return { ok: false, error: "snapshot_corrupt" };2400  }24012402  await writeSlot(SLOT_A, restoredA);2403  await writeSlot(SLOT_B, restoredB);2404  await stampLocalVaultMutation();24052406  // Lock so the user must prove they can decrypt the restored blob. If they2407  // restored a pre-password-change snapshot they discover it immediately at2408  // the lock screen rather than silently holding an inaccessible vault.2409  lock();24102411  return { ok: true };2412}24132414/**2415 * Change the master password. Re-encrypts slot A with a fresh salt + new2416 * derived key. Slot B (duress or noise) is left untouched when duress is2417 * configured — it uses an independent key derived from the duress password —2418 * and regenerated as noise when duress is not configured.2419 */2420export async function changePassword(2421  currentPassword: string,2422  newPassword: string2423): Promise<boolean> {2424  if (!derivedKey || vaultMode !== "real") return false;24252426  // Verify current password before allowing any change2427  const valid = await verifyMainPassword(currentPassword);2428  if (!valid) return false;24292430  const slotA = await loadSlot(SLOT_A);2431  if (!slotA) return false;2432  if (!rootKey) return false;24332434  // Derive fresh key from new password + new random salt2435  const newSalt = generateSalt();2436  const newKey = await deriveKey(newPassword, newSalt);24372438  // Re-encrypt the in-memory entries with the new key2439  const plaintext = encodePayload(entries, duressConfigured);2440  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");24412442  // Pre-wrap root key under the new derived key. Recovery fields wrap rootKey2443  // under recovery words and remain untouched — recovery phrase keeps working2444  // across password changes (H4/COR-002).2445  const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);24462447  const finalSlotA: StoredVault = {2448    ...slotA,2449    salt: hex(newSalt),2450    nonce,2451    ciphertext,2452    tag,2453    ...pwRoot,2454  };24552456  // Snapshot the OLD-key blob before overwriting it. If the user later2457  // restores from this snapshot they will need the OLD password — the2458  // post-restore lock surfaces that immediately.2459  await takeVaultSnapshot("local_save");24602461  // Single atomic write: ciphertext, salt, and pw_root_* fields all land in2462  // one storage transaction. An SW kill before this point leaves the old2463  // slot intact; after this point everything tied to the new password is2464  // already on disk together (M6/COR-004).2465  await writeSlot(SLOT_A, finalSlotA);24662467  // Swap the in-memory key synchronously before any further await. If we2468  // threw between the Slot A write and this swap, the next persistEntries()2469  // would overwrite Slot A with old-key ciphertext, locking the user out.2470  zeroKey(derivedKey);2471  derivedKey = newKey;24722473  // Regenerate noise for slot B when duress is not in use. Runs after the2474  // key swap so a failure here is a disposable noise regeneration, not a2475  // lockout.2476  if (!duressConfigured) {2477    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));2478  }2479  await stampLocalVaultMutation();24802481  return true;2482}