vault.ts

86.1 KB · raw

1/**2 * vault.ts — sole owner of vault state and chrome.storage vault keys.3 *4 * Every read/write of `peach_vault_a`, `peach_vault_b`, and `peach_settings`5 * goes through this module. No other file accesses those keys directly.6 * External callers reach vault operations via `messages.ts` — never by7 * importing from here cross-boundary (popup/content must not). Invariants8 * for the two-slot schema, unlock timing, and key/disk atomicity are in9 * Projects.md §3.2–§3.6.10 */1112import { deriveKey, 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}535536async function stampLocalVaultMutation(): Promise<void> {537  const raw = await chrome.storage.local.get("peach_last_modified_at");538  const previous = Number(539    (raw as Record<string, unknown>).peach_last_modified_at,540  );541  const next = Math.max(542    Date.now(),543    Number.isFinite(previous) ? previous + 1 : 0,544  );545  await chrome.storage.local.set({546    peach_last_modified_at: String(next),547  });548}549550/**551 * One-shot migration from the pre-A-2 schema (peach_vault + peach_decoy_vault552 * + peach_duress flag) to the slot-neutral schema (peach_vault_a +553 * peach_vault_b). Runs at most once per session; safe to call repeatedly.554 */555async function ensureMigrated(): Promise<void> {556  if (migrationRan) return;557  migrationRan = true;558559  const keys = [LEGACY_MAIN, LEGACY_DECOY, LEGACY_DURESS_FLAG, SLOT_A, SLOT_B];560  const raw = await chrome.storage.local.get(keys);561  const slotAExists = raw[SLOT_A] !== undefined;562  const slotBExists = raw[SLOT_B] !== undefined;563  const legacyMain = raw[LEGACY_MAIN] as StoredVault | undefined;564  const legacyDecoy = raw[LEGACY_DECOY] as StoredVault | undefined;565566  // Fresh install with nothing in storage — nothing to do; createVault() sets up both slots.567  if (!slotAExists && !legacyMain) return;568569  // Already migrated.570  if (slotAExists && slotBExists && !legacyMain && !legacyDecoy) return;571572  let didMigrate = false;573  if (legacyMain && !slotAExists) {574    await writeSlot(SLOT_A, legacyMain);575    didMigrate = true;576  }577578  // If slot B isn't set, populate it: use legacy decoy when present, else noise.579  if (!slotBExists) {580    const target = (legacyMain ?? raw[SLOT_A]) as StoredVault | undefined;581    if (legacyDecoy) {582      await writeSlot(SLOT_B, legacyDecoy);583      didMigrate = true;584    } else if (target) {585      await writeSlot(SLOT_B, generateNoiseBlob(target.ciphertext.length / 2));586      didMigrate = true;587    }588  }589590  const toRemove: string[] = [];591  if (legacyMain) toRemove.push(LEGACY_MAIN);592  if (legacyDecoy) toRemove.push(LEGACY_DECOY);593  if (raw[LEGACY_DURESS_FLAG] !== undefined) toRemove.push(LEGACY_DURESS_FLAG);594  if (toRemove.length > 0) {595    await chrome.storage.local.remove(toRemove);596    didMigrate = true;597  }598  if (didMigrate) {599    await stampLocalVaultMutation();600  }601}602603// ---------------------------------------------------------------------------604// Padding + noise helpers605// ---------------------------------------------------------------------------606607/**608 * Pads the plaintext string with trailing spaces so that the encoded byte609 * length is a multiple of PAD_BLOCK. JSON.parse tolerates trailing610 * whitespace after a complete document, so the padding is transparent on611 * decode. Ciphertext length equals plaintext length plus a 16-byte tag.612 */613function padPlaintext(json: string): string {614  const encoded = new TextEncoder().encode(json);615  const target = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);616  const padLen = target - encoded.length;617  return json + " ".repeat(padLen);618}619620/**621 * Produces a StoredVault-shaped record filled with CSPRNG bytes. The622 * ciphertext length matches the given byte count. Because GCM ciphertext is623 * pseudo-random, this blob is indistinguishable at rest from a real624 * encrypted vault without the key.625 *626 * crypto.getRandomValues() caps each call at 65536 bytes (the Web Crypto627 * spec hard limit). Chunk the fill so vaults larger than that — common once628 * the user has dozens of entries or any passkey — don't throw.629 */630const CSPRNG_CHUNK = 65_536;631632function fillRandom(buf: Uint8Array): Uint8Array {633  for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {634    const end = Math.min(offset + CSPRNG_CHUNK, buf.length);635    const chunk = new Uint8Array(end - offset);636    crypto.getRandomValues(chunk);637    buf.set(chunk, offset);638  }639  return buf;640}641642function generateNoiseBlob(ciphertextBytes: number): StoredVault {643  const salt = crypto.getRandomValues(new Uint8Array(16));644  const nonce = crypto.getRandomValues(new Uint8Array(12));645  const cipher = fillRandom(new Uint8Array(ciphertextBytes));646  const tag = crypto.getRandomValues(new Uint8Array(16));647  return {648    version: 1,649    salt: hex(salt),650    nonce: hex(nonce),651    ciphertext: hex(cipher),652    tag: hex(tag),653  };654}655656// ---------------------------------------------------------------------------657// Encrypted plaintext envelope658// ---------------------------------------------------------------------------659660type VaultPayload = {661  entries: VaultEntry[];662  duressConfigured?: boolean;663};664665type DecryptedPayload = {666  entries: VaultEntry[];667  duressConfigured: boolean;668  /**669   * True when at least one entry in the on-disk payload had a legacy shape670   * (pre-v2.11.0 passkey type/flat fields, or pre-A-2 created/updated keys)671   * and got rewritten by normalizeEntry. The unlock path uses this to672   * persist the new shape immediately — without it, the migration would673   * re-run on every unlock and old shape never disappears from disk.674   */675  migratedFromLegacy: boolean;676};677678function encodePayload(entries: VaultEntry[], duress: boolean): string {679  const envelope: VaultPayload = { entries, duressConfigured: duress };680  return padPlaintext(JSON.stringify(envelope));681}682683function rawNeedsMigration(raw: VaultEntry | LegacyVaultEntry): boolean {684  if ("created" in raw || "updated" in raw) return true;685  const flat = raw as Partial<VaultEntry>;686  if (flat.type === "passkey") return true;687  // Flat rpId without a passkey sub-object means pre-v2.11.0 schema.688  if (flat.rpId !== undefined && flat.passkey === undefined) return true;689  return false;690}691692function decodePayload(plain: string): DecryptedPayload {693  const parsed = JSON.parse(plain) as694    | Array<VaultEntry | LegacyVaultEntry>695    | VaultPayload;696697  const rawEntries = Array.isArray(parsed) ? parsed : parsed.entries ?? [];698  const flatMigrationNeeded = rawEntries.some(rawNeedsMigration);699700  const normalized = rawEntries.map(normalizeEntry);701  const { merged } = mergePasskeyOnlyIntoLogins(normalized);702703  if (Array.isArray(parsed)) {704    return {705      entries: normalized,706      duressConfigured: false,707      migratedFromLegacy: true, // pre-A-2 array shape always needs save708    };709  }710711  return {712    entries: normalized,713    duressConfigured: parsed.duressConfigured === true,714    migratedFromLegacy: flatMigrationNeeded || merged,715  };716}717718/**719 * One-time consolidation pass run alongside the legacy passkey migration.720 *721 * Pre-v2.11.0 the Chrome passkey path always created a fresh `type:"passkey"`722 * entry per registration — so users who tested registration multiple times723 * accumulated several passkey-bearing entries for the same RP, and the724 * migration to the unified shape carried that duplication forward. This725 * pass collapses the duplicates:726 *727 *   1. Group passkey-bearing (and not deleted) entries by `passkey.rpId`.728 *   2. Within each group, the most recently-active credential wins (prefer729 *      lastUsedAt, fall back to passkey.createdAt, fall back to modifiedAt).730 *   3. If a NON-passkey login entry exists for that RP (matched by url or731 *      additionalUrls hostname), attach the winning passkey to it and732 *      soft-delete every passkey-bearing entry in the group.733 *   4. Otherwise, soft-delete every loser in the group, keeping the winner734 *      as a passkey-only entry.735 *736 * Soft delete (deletedAt) rather than splice — the trash flow keeps the737 * record around for retention and the user can restore if the heuristic738 * picked wrong. The `merged` flag goes back to decodePayload so the739 * unlock path persists the consolidated shape immediately.740 */741function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {742  let merged = false;743  const now = Date.now();744745  const candidates = entries.filter((e) => !e.deletedAt && e.passkey);746  const byRpId = new Map<string, VaultEntry[]>();747  for (const e of candidates) {748    const rpId = e.passkey!.rpId;749    const list = byRpId.get(rpId);750    if (list) list.push(e);751    else byRpId.set(rpId, [e]);752  }753754  for (const [rpId, group] of byRpId) {755    if (group.length === 0) continue;756    group.sort((a, b) => {757      const aT =758        a.passkey!.lastUsedAt ?? a.passkey!.createdAt ?? a.modifiedAt ?? a.createdAt;759      const bT =760        b.passkey!.lastUsedAt ?? b.passkey!.createdAt ?? b.modifiedAt ?? b.createdAt;761      return bT - aT;762    });763    const winner = group[0]!;764765    // Look for a NON-passkey login entry matching this RP. Use the URL766    // hostname rather than a substring search so a "login.foo.com" entry767    // doesn't accidentally absorb a passkey for "foo.com".768    const loginTarget = entries.find((e) => {769      if (e.deletedAt || e.passkey || e.type !== "login") return false;770      if (e.url && extractDomain(e.url) === rpId) return true;771      for (const extra of e.additionalUrls ?? []) {772        if (extractDomain(extra) === rpId) return true;773      }774      return false;775    });776777    if (loginTarget) {778      loginTarget.passkey = winner.passkey;779      loginTarget.modifiedAt = now;780      for (const dup of group) {781        if (!dup.deletedAt) {782          dup.deletedAt = now;783          dup.modifiedAt = now;784        }785      }786      merged = true;787    } else if (group.length > 1) {788      for (let i = 1; i < group.length; i += 1) {789        const dup = group[i]!;790        if (!dup.deletedAt) {791          dup.deletedAt = now;792          dup.modifiedAt = now;793        }794      }795      merged = true;796    }797  }798799  return { merged };800}801802// Validates that a `StoredVault` record on disk has the field shape we expect803// before treating an AES-GCM decrypt success as a clean unlock. AES-GCM only804// authenticates the static VERSION_BYTE AAD, not the `version` field on the805// outer record — a corrupted `version: 42` slot still decrypts cleanly. This806// check surfaces that as `corrupted` (M7/COR-007) so the popup can offer a807// history-restore path instead of falsely reporting "wrong password".808function hasValidVaultSchema(v: unknown): v is StoredVault {809  if (typeof v !== "object" || v === null) return false;810  const r = v as Record<string, unknown>;811  return (812    r.version === 1 &&813    typeof r.salt === "string" &&814    typeof r.nonce === "string" &&815    typeof r.ciphertext === "string" &&816    typeof r.tag === "string"817  );818}819820export type TryDecryptResult =821  | { status: "ok"; payload: DecryptedPayload }822  | { status: "wrong_key" }823  | { status: "corrupted"; reason: string };824825// Exported solely for `unlockFromCodex` below, which needs to verify a826// supplied passphrase against a slotA blob *without* committing anything to827// storage. Keep this internal otherwise — callers crossing the messages.ts828// boundary should always go through `unlock` / `verifyMainPassword` so the829// constant-time invariants in Projects.md §3.4 are not bypassed.830export async function tryDecryptSlot(831  vault: StoredVault,832  key: Uint8Array,833  aadTag?: string,834): Promise<DecryptedPayload | null> {835  const res = await tryDecryptSlotResult(vault, key, aadTag);836  return res.status === "ok" ? res.payload : null;837}838839export async function tryDecryptSlotResult(840  vault: StoredVault,841  key: Uint8Array,842  aadTag?: string,843): Promise<TryDecryptResult> {844  if (!hasValidVaultSchema(vault)) {845    return { status: "corrupted", reason: "invalid_slot_schema" };846  }847  let plain: string;848  try {849    plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);850  } catch {851    return { status: "wrong_key" };852  }853  try {854    const parsed = JSON.parse(plain) as unknown;855    if (typeof parsed !== "object" || parsed === null) {856      return { status: "corrupted", reason: "invalid_payload_shape" };857    }858    if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {859      return { status: "corrupted", reason: "invalid_payload_shape" };860    }861    return { status: "ok", payload: decodePayload(plain) };862  } catch {863    return { status: "corrupted", reason: "invalid_payload_json" };864  }865}866867// ---------------------------------------------------------------------------868// Core operations869// ---------------------------------------------------------------------------870871function buildDomainIndexSync(all: VaultEntry[]): void {872  domainIndex = new Map();873874  for (const entry of all) {875    if (entry.deletedAt) continue;876    if (entry.type === "note" || entry.type === "card") continue;877878    // An entry can match multiple sites via `additionalUrls`. Index each879    // hostname so `queryDomain` returns the entry regardless of which alias880    // the user is currently visiting. Dedupe per-entry so a single entry881    // never appears twice in one bucket.882    const domains = new Set<string>();883    const primary = extractDomain(entry.url ?? "");884    if (primary) domains.add(primary);885    for (const extra of entry.additionalUrls ?? []) {886      const d = extractDomain(extra);887      if (d) domains.add(d);888    }889    if (domains.size === 0) continue;890891    for (const domain of domains) {892      const bucket = domainIndex.get(domain) ?? [];893      bucket.push(entry);894      domainIndex.set(domain, bucket);895    }896  }897}898899export async function createVault(password: string): Promise<void> {900  await ensureMigrated();901902  const salt = generateSalt();903  derivedKey = await deriveKey(password, salt);904  entries = [];905  vaultMode = "real";906  duressConfigured = false;907  buildDomainIndexSync(entries);908909  // Generate and wrap the root key for recovery word escrow.910  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =911    await generateAndWrapRootKey();912  rootKey = unhex(rawRootKey);913914  const plaintext = encodePayload(entries, duressConfigured);915  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");916917  // Second wrapping of rootKey under derivedKey so future unlocks can rehydrate918  // it without recovery words (H2/COR-006).919  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);920921  const slotA: StoredVault = {922    version: 1,923    salt: hex(salt),924    nonce,925    ciphertext,926    tag,927    recovery_salt: recoverySalt,928    recovery_wrapped_root_key: wrappedRootKey,929    recovery_nonce: wrappedNonce,930    recovery_tag: wrappedTag,931    ...pwRoot,932  };933  await writeSlot(SLOT_A, slotA);934935  // Matching-size noise blob for slot B, so a fresh install shows two936  // similarly-shaped records regardless of whether duress is ever set up.937  await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));938  await stampLocalVaultMutation();939940  touchAutoLock();941}942943export async function hasVault(): Promise<boolean> {944  await ensureMigrated();945  return (await loadSlot(SLOT_A)) !== null;946}947948/**949 * Returns whether the real vault has recorded that a duress passphrase is950 * configured. Reliable only after a real-mode unlock — before unlock or in951 * decoy mode, returns false because we cannot read slot A's plaintext.952 */953export async function isDuressEnabled(): Promise<boolean> {954  return vaultMode === "real" && duressConfigured;955}956957export async function setupDuress(duressPassword: string): Promise<void> {958  if (!derivedKey || vaultMode !== "real") {959    throw new Error("vault must be unlocked in real mode");960  }961  await ensureMigrated();962963  // Encrypt the decoy payload (empty entries) under the duress key. Pad to964  // at least the current slot A ciphertext size so the two slots look the965  // same at rest at setup time.966  const slotA = await loadSlot(SLOT_A);967  if (!slotA) throw new Error("missing slot A");968969  const decoySalt = generateSalt();970  const decoyKey = await deriveKey(duressPassword, decoySalt);971  try {972    // Pad the decoy plaintext to match slot A's ciphertext length (minus the973    // 16-byte tag) so encrypted sizes align exactly.974    const targetBytes = slotA.ciphertext.length / 2;975    let plaintext = encodePayload([], false);976    const encoded = new TextEncoder().encode(plaintext);977    if (encoded.length < targetBytes) {978      plaintext = plaintext + " ".repeat(targetBytes - encoded.length);979    }980    const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");981    await writeSlot(SLOT_B, {982      version: 1,983      salt: hex(decoySalt),984      nonce,985      ciphertext,986      tag,987    });988  } finally {989    zeroKey(decoyKey);990  }991992  // Re-encrypt slot A with the duressConfigured flag set to true. No external993  // flag is written — the bit lives inside the encrypted envelope.994  duressConfigured = true;995  await persistSlotA();996}997998export async function disableDuress(): Promise<void> {999  if (!derivedKey || vaultMode !== "real") {1000    throw new Error("vault must be unlocked in real mode");1001  }1002  await ensureMigrated();10031004  // Overwrite slot B with fresh noise that matches slot A's size. The slot1005  // remains occupied so its mere existence does not signal that duress was1006  // ever configured.1007  const slotA = await loadSlot(SLOT_A);1008  if (slotA) {1009    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));1010  }10111012  duressConfigured = false;1013  await persistSlotA();1014}10151016// L14/COR-015: this function intentionally checks slot A (real vault) only.1017// A duress-mode user attempting changePassword is rejected earlier by the1018// vaultMode === 'decoy' check at changePassword. The real-vs-decoy1019// distinction here is by design — duress users cannot rotate the real1020// password by guessing it, and the asymmetry in error timing is acceptable1021// because duress mode is opt-in and the user knows their own decoy key.1022export async function verifyMainPassword(password: string): Promise<boolean> {1023  await ensureMigrated();1024  const slotA = await loadSlot(SLOT_A);1025  if (!slotA) return false;1026  const key = await deriveKey(password, unhex(slotA.salt));1027  try {1028    return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;1029  } finally {1030    zeroKey(key);1031  }1032}10331034export async function unlock(password: string): Promise<boolean> {1035  await ensureMigrated();10361037  // Load both slots in parallel. Both always exist post-migration; the1038  // parallel load and the parallel derivation below keep wall-clock time1039  // constant regardless of which slot's passphrase (real or decoy) the1040  // caller supplied, so a timing side channel cannot distinguish the1041  // duress path from the real-unlock path (DUR-002).1042  const [slotA, slotB] = await Promise.all([1043    loadSlot(SLOT_A),1044    loadSlot(SLOT_B),1045  ]);10461047  // Derive both keys in parallel, unconditionally.1048  const [keyA, keyB] = await Promise.all([1049    slotA ? deriveKey(password, unhex(slotA.salt)) : Promise.resolve(null),1050    slotB ? deriveKey(password, unhex(slotB.salt)) : Promise.resolve(null),1051  ]);10521053  // Attempt both decrypts in parallel. The Result variant lets us distinguish1054  // 'wrong_key' from 'corrupted' so callers can offer a history-restore path1055  // when a slot's schema is invalid even though AES-GCM authenticated (M7).1056  const [resultA, resultB] = await Promise.all([1057    keyA && slotA1058      ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")1059      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1060    keyB && slotB1061      ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")1062      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1063  ]);1064  const payloadA = resultA.status === "ok" ? resultA.payload : null;1065  const payloadB = resultB.status === "ok" ? resultB.payload : null;10661067  if (payloadA && keyA) {1068    derivedKey = keyA;1069    void saveSessionKey(keyA, "real");1070    vaultMode = "real";1071    entries = payloadA.entries;1072    duressConfigured = payloadA.duressConfigured;1073    buildDomainIndexSync(entries);1074    await loadSettings();1075    touchAutoLock();1076    if (keyB) zeroKey(keyB);10771078    // slotA is non-null when payloadA is truthy (keyA was derived from slotA).1079    if (slotA) {1080      const needsRecoverySetup =1081        !slotA.recovery_salt || !slotA.recovery_wrapped_root_key;1082      if (!needsRecoverySetup) {1083        rootKey = await deriveRootKeyFromDerivedKey(keyA, slotA);1084      }1085      // Pre-v2.12 vault, or a vault whose pw_root_* fields haven't been written1086      // yet: generate the recovery escrow and seed pw_root_* so subsequent1087      // unlocks can rehydrate rootKey without the user's recovery words.1088      // Best-effort — a failure here must not block unlock.1089      if (needsRecoverySetup || !rootKey) {1090        try {1091          await migrateToRecovery();1092          if (needsRecoverySetup) {1093            // String "1" matches the popup's existing peach_recovery_pending1094            // check; surfaced so the user re-confirms recovery words after a1095            // legacy-vault unlock (H2/COR-006).1096            await chrome.storage.local.set({ peach_recovery_pending: '1' });1097          }1098        } catch (migrationErr) {1099          console.warn('[Peach] recovery migration failed:', migrationErr);1100        }1101      }1102    }11031104    // If the payload had a pre-v2.11.0 shape (legacy passkey type, flat1105    // passkey fields, or pre-A-2 created/updated keys), rewrite it now so1106    // the next save uses the new format and migration doesn't re-run forever.1107    if (payloadA.migratedFromLegacy) {1108      await persistSlotA();1109    }1110    return true;1111  }11121113  if (payloadB && keyB) {1114    derivedKey = keyB;1115    void saveSessionKey(keyB, "decoy");1116    vaultMode = "decoy";1117    entries = payloadB.entries;1118    duressConfigured = false;1119    buildDomainIndexSync(entries);1120    await loadSettings();1121    touchAutoLock();1122    if (keyA) zeroKey(keyA);1123    return true;1124  }11251126  if (keyA) zeroKey(keyA);1127  if (keyB) zeroKey(keyB);1128  // Surface corruption (good AES tag, broken schema) distinctly from1129  // wrong-password so the popup can offer history-restore (M7/COR-007).1130  if (resultA.status === "corrupted") {1131    lastUnlockFailureReason = resultA.reason;1132  } else if (resultB.status === "corrupted") {1133    lastUnlockFailureReason = resultB.reason;1134  }1135  return false;1136}11371138// ---------------------------------------------------------------------------1139// MV3 service worker session key — survives SW restarts within a browser session1140// ---------------------------------------------------------------------------11411142// chrome.storage.session is cleared on browser close; survives SW restart.1143// Firefox does not implement it (persistent background script, no restart risk).1144const SESSION_KEY_STORAGE = "peach_session_dk";11451146async function saveSessionKey(key: Uint8Array, mode: "real" | "decoy"): Promise<void> {1147  if (!chrome.storage.session) return;1148  await chrome.storage.session.set({ [SESSION_KEY_STORAGE]: { keyHex: hex(key), mode } });1149}11501151async function clearSessionKey(): Promise<void> {1152  if (!chrome.storage.session) return;1153  await chrome.storage.session.remove(SESSION_KEY_STORAGE);1154}11551156/**1157 * On SW restart, re-derive all in-memory vault state from the session key1158 * stored in chrome.storage.session (set at unlock time, cleared on lock).1159 * Returns true if the vault was restored, false if no session key was found.1160 * No-ops if the vault is already unlocked.1161 */1162export async function restoreFromSession(): Promise<boolean> {1163  if (derivedKey !== null) return true;1164  if (!chrome.storage.session) return false;1165  const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);1166  const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;1167  if (!entry?.keyHex) return false;11681169  const key = unhex(entry.keyHex);1170  const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;1171  const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";1172  const slot = await loadSlot(slotKey);1173  if (!slot) { await clearSessionKey(); return false; }11741175  const result = await tryDecryptSlotResult(slot, key, aadTag);1176  if (result.status !== "ok") { await clearSessionKey(); return false; }11771178  derivedKey = key;1179  vaultMode = entry.mode;1180  entries = result.payload.entries;1181  duressConfigured = entry.mode === "real" ? result.payload.duressConfigured : false;1182  buildDomainIndexSync(entries);1183  await loadSettings();1184  touchAutoLock();11851186  if (entry.mode === "real" && slot.recovery_salt && slot.recovery_wrapped_root_key) {1187    try { rootKey = await deriveRootKeyFromDerivedKey(key, slot); } catch { /* non-fatal */ }1188  }11891190  return true;1191}11921193export function lock(): void {1194  void clearSessionKey();1195  if (derivedKey) {1196    zeroKey(derivedKey);1197    derivedKey = null;1198  }1199  if (rootKey) {1200    rootKey.fill(0);1201    rootKey = null;1202  }12031204  entries = [];1205  domainIndex = new Map();1206  vaultMode = "real";1207  duressConfigured = false;1208  clearAutoLock();1209}12101211export function isUnlocked(): boolean {1212  return derivedKey !== null;1213}12141215// Opens the vault using a pre-derived AES-256 key (skipping Argon2id).1216// Used by Android biometric unlock — the key was derived on the native side.1217export async function unlockWithKey(1218  masterKeyHex: string,1219): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {1220  try {1221    const masterKeyBytes = unhex(masterKeyHex);1222    const stored = await loadSlot(SLOT_A);1223    if (!stored) return { ok: false, error: "invalid_key" };1224    const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");1225    if (!payload) return { ok: false, error: "invalid_key" };12261227    derivedKey = masterKeyBytes;1228    vaultMode = "real";1229    entries = payload.entries;1230    duressConfigured = payload.duressConfigured;1231    buildDomainIndexSync(entries);1232    await loadSettings();1233    touchAutoLock();1234    return { ok: true, entries };1235  } catch {1236    return { ok: false, error: "invalid_key" };1237  }1238}12391240/**1241 * Restore the vault from a parsed Peach Codex payload.1242 *1243 * The supplied passphrase is verified against the Codex's slotA *before* any1244 * storage mutation — wrong passphrases return without touching disk. On1245 * success, the current vault state is snapshotted (reason: "restore") so the1246 * user can revert via Settings -> Vault History, then slotA/slotB are written1247 * and `peach_last_modified_at` is set to the Codex's recorded timestamp. A1248 * regular `unlock()` follows so the rest of the SW sees the standard1249 * post-unlock state.1250 *1251 * Intentionally non-Pro-gated — see peach_codex_v2.md "Pro gating". A Codex1252 * printed by a Pro user must always be restorable, even on a free device.1253 *1254 * Timing is not held constant here (in contrast to `unlock`): the Codex flow1255 * is an explicit user action with a known passphrase, not a passive lock1256 * screen, so the duress-vs-real timing side channel does not apply.1257 */1258export async function unlockFromCodex(params: {1259  slotA: string; // JSON string of StoredVault for slot A1260  slotB: string | null; // JSON string of StoredVault for slot B, or null1261  timestamp: number;1262  masterPassphrase: string;1263}): Promise<1264  | { ok: true; entryCount: number }1265  | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" }1266> {1267  let parsedSlotA: StoredVault;1268  let parsedSlotB: StoredVault | null = null;1269  try {1270    const rawA = JSON.parse(params.slotA) as unknown;1271    if (!hasValidVaultSchema(rawA)) {1272      return { ok: false, reason: "invalid_slot_format" };1273    }1274    parsedSlotA = rawA;1275    if (params.slotB !== null) {1276      const rawB = JSON.parse(params.slotB) as unknown;1277      if (!hasValidVaultSchema(rawB)) {1278        return { ok: false, reason: "invalid_slot_format" };1279      }1280      parsedSlotB = rawB;1281    }1282  } catch {1283    return { ok: false, reason: "invalid_slot_format" };1284  }12851286  // Verify the passphrase against the supplied slotA WITHOUT writing anything.1287  // If this fails the on-disk vault is left completely untouched.1288  const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));1289  const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");1290  if (!trialPayload) {1291    zeroKey(trialKey);1292    return { ok: false, reason: "wrong_passphrase" };1293  }1294  // Drop the trial key; `unlock()` below derives its own copy. Holding two1295  // copies of the master key in memory at once would be a needless surface.1296  zeroKey(trialKey);12971298  // Snapshot the about-to-be-overwritten on-disk state so the user can revert1299  // a mistaken Codex restore via the Vault History UI. Non-fatal if it fails.1300  await takeVaultSnapshot("restore");13011302  await writeSlot(SLOT_A, parsedSlotA);1303  if (parsedSlotB) {1304    await writeSlot(SLOT_B, parsedSlotB);1305  } else {1306    // Slot B must always exist with ciphertext length matching slot A1307    // (Projects.md §3.2). Codex prints may omit slot B (duress wasn't1308    // configured); regenerate noise to satisfy the invariant.1309    await writeSlot(1310      SLOT_B,1311      generateNoiseBlob(parsedSlotA.ciphertext.length / 2),1312    );1313  }1314  await chrome.storage.local.set({1315    peach_last_modified_at: String(params.timestamp),1316  });13171318  // Standard unlock path so domain index, settings, auto-lock, and1319  // recovery-key state all populate exactly as a normal unlock would.1320  const ok = await unlock(params.masterPassphrase);1321  if (!ok) {1322    // Should be unreachable — we just verified the passphrase against the1323    // same slotA we wrote. Treat as wrong_passphrase to keep the contract1324    // simple if some race or storage anomaly intrudes.1325    return { ok: false, reason: "wrong_passphrase" };1326  }1327  return { ok: true, entryCount: getEntries().length };1328}13291330// Returns the current in-memory derived key as a hex string.1331// Used by the biometric enable flow in Settings to store the key in Android Keystore.1332export function getDerivedKeyHex(): string {1333  if (!derivedKey) throw new Error("vault_not_unlocked");1334  return hex(derivedKey);1335}13361337export function getEntries(): VaultEntry[] {1338  if (!derivedKey) throw new Error("vault_locked");1339  return entries.filter((entry) => !entry.deletedAt);1340}13411342const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;13431344export function getIdentities(): SavedIdentity[] {1345  if (!derivedKey) throw new Error("vault_locked");1346  const active = entries.filter((e) => !e.deletedAt && e.type === "login");13471348  const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();1349  const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();13501351  for (const entry of active) {1352    const domain = extractDomain(entry.url ?? "") ?? "";1353    const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;13541355    function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {1356      const existing = map.get(v);1357      if (!existing || modifiedAt > existing.lastUsed) {1358        map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });1359      } else {1360        map.set(v, { ...existing, count: existing.count + 1 });1361      }1362    }13631364    const uVal = entry.username?.trim();1365    if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);13661367    // Also count the dedicated email field — entries created via the inline1368    // popup new-entry form store email here rather than in username.1369    const eVal = entry.email?.trim();1370    if (eVal) tally(emailMap, eVal);1371  }13721373  const toIdentity = (type: "email" | "username") =>1374    ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({1375      value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,1376    });13771378  return [1379    ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),1380    ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),1381  ];1382}13831384export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {1385  if (!derivedKey) throw new Error("vault_locked");13861387  const now = Date.now();1388  const added: VaultEntry[] = [];1389  for (const draft of drafts) {1390    try {1391      const sanitized = sanitizeEntryDraft(draft);1392      const nextEntry: VaultEntry = {1393        ...sanitized,1394        id: crypto.randomUUID(),1395        createdAt: now,1396        modifiedAt: now,1397      };1398      entries.push(nextEntry);1399      added.push(nextEntry);1400    } catch {1401      // Skip invalid drafts silently — caller can see diff between input and output length1402    }1403  }14041405  if (added.length > 0) {1406    await persistEntries();1407  }14081409  return added;1410}14111412/**1413 * Restore a set of entries in full fidelity — preserves id, createdAt,1414 * modifiedAt, and every other field unlike `batchAddEntries` which1415 * assigns fresh identity. Used by restore paths where the backup is the1416 * authoritative source of truth. `mode` controls how entries already in1417 * the vault are treated.1418 */1419export async function restoreEntries(1420  incoming: VaultEntry[],1421  mode: "replace" | "merge"1422): Promise<{ added: number; updated: number; skipped: number }> {1423  if (!derivedKey) throw new Error("vault_locked");14241425  // A replace with zero incoming entries is almost certainly a caller bug1426  // (e.g. an import that silently dropped everything). Refuse rather than1427  // wipe the vault.1428  if (mode === "replace" && incoming.length === 0) {1429    throw new Error("refuse to replace with empty entry set");1430  }14311432  let added = 0;1433  let updated = 0;1434  let skipped = 0;14351436  if (mode === "replace") {1437    entries = [];1438    for (const entry of incoming) {1439      const normalized = sanitizeRestoredEntry(entry);1440      if (!normalized) {1441        skipped += 1;1442        continue;1443      }1444      entries.push(normalized);1445      added += 1;1446    }1447  } else {1448    const byId = new Map<string, VaultEntry>();1449    for (const e of entries) byId.set(e.id, e);14501451    for (const entry of incoming) {1452      const normalized = sanitizeRestoredEntry(entry);1453      if (!normalized) {1454        skipped += 1;1455        continue;1456      }1457      const existing = byId.get(normalized.id);1458      if (!existing) {1459        entries.push(normalized);1460        added += 1;1461      } else if (normalized.modifiedAt > existing.modifiedAt) {1462        const idx = entries.findIndex((e) => e.id === existing.id);1463        if (idx !== -1) {1464          entries[idx] = normalized;1465          updated += 1;1466        }1467      } else {1468        skipped += 1;1469      }1470    }1471  }14721473  await persistEntries("import");1474  return { added, updated, skipped };1475}14761477/**1478 * Validate + normalise a VaultEntry coming from a backup. Accepts1479 * anything structurally sound; keeps all metadata verbatim. Returns1480 * null for values the live vault shouldn't accept (e.g., missing title).1481 */1482function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {1483  if (!entry || typeof entry !== "object") return null;1484  const title = typeof entry.title === "string" ? entry.title.trim() : "";1485  if (!title) return null;1486  const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();1487  const now = Date.now();1488  const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;1489  const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;14901491  // Migrate legacy passkey shape on import (same logic as on-disk read).1492  // Imports from pre-v2.11.0 vault backups still carry type:"passkey" with1493  // flat fields; bring them into the new shape immediately.1494  const migrated: VaultEntry = migrateLegacyPasskey(1495    {1496      ...entry,1497      id,1498      title,1499      type: entry.type ?? "login",1500      createdAt,1501      modifiedAt,1502    },1503    entry1504  );15051506  // Login entries from backup must carry a password (or be passkey-only,1507  // in which case the passkey sub-object replaces the password requirement).1508  if (1509    migrated.type === "login" &&1510    !migrated.passkey &&1511    typeof migrated.password !== "string"1512  ) {1513    return null;1514  }1515  if (migrated.passkey && !migrated.passkey.credentialId) {1516    return null;1517  }15181519  return migrated;1520}15211522// Soft-deletes every non-deleted entry in one call. The literal string1523// argument is a tripwire against accidental calls — any caller that would1524// wipe the vault has to consciously type "REPLACE_ALL". Do not relax this1525// to a boolean.1526export async function clearVaultEntries(1527  confirmation: "REPLACE_ALL"1528): Promise<void> {1529  if (confirmation !== "REPLACE_ALL") {1530    throw new Error("clearVaultEntries requires explicit confirmation");1531  }1532  if (!derivedKey) throw new Error("vault_locked");1533  for (const entry of entries) {1534    if (!entry.deletedAt) {1535      entry.deletedAt = Date.now();1536      entry.modifiedAt = Date.now();1537    }1538  }1539  await persistEntries();1540}15411542export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {1543  if (!derivedKey) throw new Error("vault_locked");15441545  const sanitized = sanitizeEntryDraft(entry);1546  const now = Date.now();1547  const nextEntry: VaultEntry = {1548    ...sanitized,1549    id: crypto.randomUUID(),1550    createdAt: now,1551    modifiedAt: now,1552    // Stamp passwordChangedAt at creation so age tracking is accurate from1553    // day one. Non-login entries carry the same stamp harmlessly.1554    passwordChangedAt: sanitized.password ? now : undefined,1555  };15561557  // Clone-and-replace so a failed persist rolls back the in-memory state1558  // (COR-008). Without this, a quota-full or storage error leaves the1559  // module-level `entries` ahead of what's actually on disk.1560  const rollback = entries;1561  entries = [...entries, nextEntry];1562  try {1563    await persistEntries();1564  } catch (err) {1565    entries = rollback;1566    throw err;1567  }15681569  // Fire-and-forget breach check (only for login entries if breach monitoring is enabled or not set)1570  if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {1571    checkBreach(nextEntry.password).then(async (count) => {1572      if (count > 0) {1573        const idx = entries.findIndex((e) => e.id === nextEntry.id);1574        if (idx !== -1) {1575          entries[idx] = { ...entries[idx], breach: count, modifiedAt: Date.now() };1576          await persistEntries();1577        }1578      }1579    });1580  }15811582  fireSyncTrigger("vault_change");15831584  return nextEntry;1585}15861587export async function updateEntry(1588  id: string,1589  patch: Partial<VaultEntry>1590): Promise<void> {1591  if (!derivedKey) throw new Error("vault_locked");15921593  const idx = entries.findIndex((entry) => entry.id === id);1594  if (idx === -1 || entries[idx].deletedAt) {1595    throw new Error("entry_not_found");1596  }15971598  const current = entries[idx];1599  const sanitizedPatch = sanitizeEntryPatch(patch);1600  // Refresh passwordChangedAt only when the password value actually changes —1601  // a metadata-only update (title, tags, etc.) must not reset the age clock1602  // that drives the Pro health rotation recommendation.1603  const passwordChanged =1604    "password" in patch &&1605    typeof sanitizedPatch.password === "string" &&1606    sanitizedPatch.password !== current.password;1607  entries[idx] = {1608    ...current,1609    ...sanitizedPatch,1610    modifiedAt: Date.now(),1611    ...(passwordChanged ? { passwordChangedAt: Date.now() } : {}),1612  };1613161416151616  // Card entries must retain their card number1617  if (entries[idx].type === "card" && !entries[idx].cardNumber) {1618    entries[idx] = current;1619    throw new Error("card number is required for card entries");1620  }16211622  await persistEntries();16231624  // Breach check when password changes: clear immediately so old breach doesn't linger,1625  // then async-check the new password and only re-set if it's also found.1626  if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {1627    entries[idx] = { ...entries[idx], breach: undefined };1628    await persistEntries();1629    const password = entries[idx].password;1630    if (password) {1631      checkBreach(password).then(async (count) => {1632        const i = entries.findIndex((e) => e.id === id);1633        if (i !== -1 && count > 0) {1634          entries[i] = { ...entries[i], breach: count, modifiedAt: Date.now() };1635          await persistEntries();1636        }1637      });1638    }1639  }16401641  fireSyncTrigger("vault_change");1642}16431644export async function deleteEntry(id: string): Promise<void> {1645  if (!derivedKey) throw new Error("vault_locked");16461647  const entry = entries.find((item) => item.id === id);1648  if (!entry || entry.deletedAt) {1649    throw new Error("entry_not_found");1650  }16511652  entry.deletedAt = Date.now();1653  entry.modifiedAt = Date.now();1654  await persistEntries();1655  fireSyncTrigger("vault_change");1656}16571658export function getDeletedEntries(): VaultEntry[] {1659  if (!derivedKey) return [];1660  return entries.filter((e) => !!e.deletedAt);1661}16621663/**1664 * Returns the vault's monotonic version — the `peach_last_modified_at` value1665 * stamped on every user-initiated write. Remote (sync) writes do NOT advance1666 * this version so a sync round never cascades into a second outbound sync.1667 */1668export async function getVaultVersion(): Promise<number> {1669  try {1670    const raw = await chrome.storage.local.get("peach_last_modified_at");1671    const v = (raw as Record<string, unknown>).peach_last_modified_at;1672    if (typeof v === "number") return v;1673    if (typeof v === "string" && v !== "") {1674      const n = Number.parseInt(v, 10);1675      return Number.isFinite(n) ? n : 0;1676    }1677    return 0;1678  } catch {1679    return 0;1680  }1681}16821683/**1684 * Internal write variants — bypass `fireSyncTrigger` so the sync layer can1685 * apply entries without cascading into another outbound sync round.1686 *1687 * INVARIANT: callers must not pass entries whose IDs collide with existing1688 * active (non-deleted) entries unless the intent is an explicit overwrite.1689 * These functions do not validate field-level constraints (password required,1690 * card number required, etc.) — they are trust-the-caller paths for sync and1691 * test harness use only.1692 */1693export async function addEntryDirect(entry: VaultEntry): Promise<void> {1694  if (!derivedKey) throw new Error("vault_locked");1695  entries = [...entries, entry];1696  await persistEntries("sync_received");1697}16981699export async function updateEntryDirect(patch: VaultEntry): Promise<void> {1700  if (!derivedKey) throw new Error("vault_locked");1701  const idx = entries.findIndex((e) => e.id === patch.id);1702  if (idx === -1) throw new Error("entry_not_found");1703  entries[idx] = { ...entries[idx], ...patch };1704  await persistEntries("sync_received");1705}17061707export async function deleteEntryDirect(id: string, deletedAt: number): Promise<void> {1708  if (!derivedKey) throw new Error("vault_locked");1709  const idx = entries.findIndex((e) => e.id === id);1710  if (idx === -1) throw new Error("entry_not_found");1711  entries[idx] = { ...entries[idx], deletedAt, modifiedAt: deletedAt };1712  await persistEntries("sync_received");1713}17141715/**1716 * Apply a batch of remote entries + tombstones from a chirp-sync peer.1717 * Last-write-wins by `modifiedAt`; a tombstone supersedes a live entry when1718 * `deletedAt > modifiedAt` on the local side. Mutates `entries` directly and1719 * persists with reason `sync_received` — does NOT fire the sync dispatcher, so1720 * applying a sync round cannot cascade into another outbound sync.1721 *1722 * `applied` counts entries that actually changed local state (new add,1723 * overwrite-by-newer, or new tombstone). `received` is the raw payload size1724 * the caller can surface in the sync result UI.1725 */1726export async function applyMergedRemoteEntries(1727  remoteEntries: VaultEntry[],1728  remoteTombstones: Record<string, number>,1729): Promise<{ received: number; applied: number; conflicts: number }> {1730  if (!derivedKey) throw new Error("vault_locked");17311732  const received = remoteEntries.length + Object.keys(remoteTombstones).length;1733  let applied = 0;1734  let conflicts = 0;17351736  const byId = new Map<string, VaultEntry>();1737  for (const e of entries) byId.set(e.id, e);17381739  for (const remote of remoteEntries) {1740    const sanitized = sanitizeRestoredEntry(remote);1741    if (!sanitized) continue;1742    const tombstoneTs = remoteTombstones[sanitized.id];1743    if (tombstoneTs !== undefined && tombstoneTs >= sanitized.modifiedAt) {1744      continue;1745    }1746    const local = byId.get(sanitized.id);1747    if (!local) {1748      entries.push(sanitized);1749      byId.set(sanitized.id, sanitized);1750      applied += 1;1751    } else if (sanitized.modifiedAt > local.modifiedAt) {1752      const idx = entries.findIndex((e) => e.id === local.id);1753      if (idx !== -1) {1754        entries[idx] = sanitized;1755        byId.set(sanitized.id, sanitized);1756        applied += 1;1757        if (!local.deletedAt) conflicts += 1;1758      }1759    }1760  }17611762  for (const [id, deletedAt] of Object.entries(remoteTombstones)) {1763    if (typeof deletedAt !== "number" || !Number.isFinite(deletedAt)) continue;1764    const local = byId.get(id);1765    if (!local) continue;1766    if (local.deletedAt && local.deletedAt >= deletedAt) continue;1767    if (deletedAt < local.modifiedAt) continue;1768    const idx = entries.findIndex((e) => e.id === id);1769    if (idx !== -1) {1770      entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };1771      applied += 1;1772    }1773  }17741775  if (applied > 0) {1776    await persistEntries("sync_received");1777    buildDomainIndexSync(entries);1778  }1779  return { received, applied, conflicts };1780}17811782export async function restoreEntry(id: string): Promise<void> {1783  if (!derivedKey) throw new Error("vault_locked");1784  const entry = entries.find((e) => e.id === id && e.deletedAt);1785  if (!entry) throw new Error("deleted entry not found");1786  delete entry.deletedAt;1787  entry.modifiedAt = Date.now();1788  await persistEntries();1789  buildDomainIndexSync(entries);1790}17911792export async function purgeEntry(id: string): Promise<void> {1793  if (!derivedKey) throw new Error("vault_locked");1794  const idx = entries.findIndex((e) => e.id === id && e.deletedAt);1795  if (idx === -1) throw new Error("deleted entry not found");1796  entries.splice(idx, 1);1797  await persistEntries();1798}17991800/** Permanently delete entries whose deletedAt is older than retentionMs. 0 = keep forever. */1801export async function purgeExpiredTrash(retentionMs: number): Promise<number> {1802  if (!derivedKey || retentionMs === 0) return 0;1803  const cutoff = Date.now() - retentionMs;1804  const before = entries.length;1805  entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));1806  const purged = before - entries.length;1807  if (purged > 0) await persistEntries();1808  return purged;1809}18101811export function queryDomain(domain: string): VaultEntry[] {1812  return domainIndex.get(domain) ?? [];1813}18141815export function getEntryById(id: string): VaultEntry | undefined {1816  return entries.find((entry) => entry.id === id && !entry.deletedAt);1817}18181819async function persistSlotA(1820  reason: VaultSnapshot["reason"] = "local_save",1821): Promise<StoredVault> {1822  if (!derivedKey) throw new Error("vault_locked");18231824  const slotA = await loadSlot(SLOT_A);1825  if (!slotA) throw new Error("missing slot A");18261827  // Snapshot the about-to-be-overwritten state BEFORE we mutate disk. Failures1828  // are swallowed by takeVaultSnapshot — history must never block a save.1829  await takeVaultSnapshot(reason);18301831  const plaintext = encodePayload(entries, duressConfigured);1832  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");18331834  // Preserve existing recovery escrow fields.1835  const nextSlotA: StoredVault = {1836    ...slotA,1837    nonce,1838    ciphertext,1839    tag,1840    // recovery_salt and recovery_wrapped_root_key are already set from loadSlot1841  };1842  await writeSlot(SLOT_A, nextSlotA);18431844  // When duress is not configured, keep slot B size-matched with slot A by1845  // regenerating its noise. When duress IS configured, leave slot B alone —1846  // we don't have the decoy key to re-encrypt it. This is a known trade-off.1847  if (!duressConfigured) {1848    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));1849  }1850  await stampLocalVaultMutation();18511852  return nextSlotA;1853}18541855async function persistSlotB(): Promise<void> {1856  if (!derivedKey) throw new Error("vault_locked");18571858  const slotB = await loadSlot(SLOT_B);1859  if (!slotB) throw new Error("missing slot B");18601861  // Decoy plaintext always reports duressConfigured=false — the decoy user1862  // sees a clean slate.1863  const plaintext = encodePayload(entries, false);1864  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");18651866  await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });1867  await stampLocalVaultMutation();1868}18691870async function persistEntries(1871  reason: VaultSnapshot["reason"] = "local_save",1872): Promise<void> {1873  if (!derivedKey) throw new Error("vault_locked");18741875  if (vaultMode === "decoy") {1876    await persistSlotB();1877  } else {1878    await persistSlotA(reason);1879  }1880  buildDomainIndexSync(entries);1881}18821883function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {1884  if (!Array.isArray(values)) return undefined;1885  const seen = new Set<string>();1886  const cleaned: string[] = [];1887  for (const value of values) {1888    const trimmed = typeof value === "string" ? value.trim() : "";1889    if (!trimmed) continue;1890    const key = trimmed.toLowerCase();1891    if (seen.has(key)) continue;1892    seen.add(key);1893    cleaned.push(trimmed);1894  }1895  return cleaned.length > 0 ? cleaned : undefined;1896}18971898function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {1899  const title = entry.title.trim();1900  // Accept legacy `type:"passkey"` drafts but rewrite to "login" — the new1901  // model is "any entry, optionally with a passkey sub-object." Imports and1902  // any in-flight callers from before v2.11.0 keep working without throwing.1903  let type: VaultEntry["type"] = entry.type ?? "login";1904  if (type === "passkey") type = "login";19051906  if (!title) throw new Error("title is required");19071908  if (entry.passkey) {1909    const p = entry.passkey;1910    if (1911      !p.rpId ||1912      !p.credentialId ||1913      !p.publicKeyCose ||1914      !p.userHandle ||1915      !p.userName ||1916      (p.algorithm !== -7 && p.algorithm !== -8)1917    ) {1918      throw new Error("invalid passkey credential");1919    }1920  }1921  if (type === "card") {1922    if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {1923      throw new Error("cardholder name and card number are required");1924    }1925  }19261927  return {1928    type,1929    title,1930    username: type === "login" ? entry.username?.trim() ?? "" : undefined,1931    email: type === "login" ? entry.email?.trim() || undefined : undefined,1932    password: type === "login" ? entry.password : undefined,1933    url: type === "login" ? entry.url?.trim() ?? "" : undefined,1934    additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,1935    totp: type === "login" ? entry.totp?.trim() || undefined : undefined,1936    notes: entry.notes?.trim() || undefined,1937    breach: type === "login" ? entry.breach : undefined,1938    canary: type === "login" ? entry.canary : undefined,1939    tags: entry.tags,1940    passkey: entry.passkey,1941    cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,1942    cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,1943    expMonth: type === "card" ? entry.expMonth?.trim() : undefined,1944    expYear: type === "card" ? entry.expYear?.trim() : undefined,1945    cvc: type === "card" ? entry.cvc?.trim() : undefined,1946    cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,1947    network: type === "card" ? entry.network : undefined,1948    last4: type === "card" ? entry.last4?.trim() : undefined,1949  };1950}19511952function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {1953  const nextPatch: Partial<VaultEntry> = {};19541955  if ("type" in patch) {1956    nextPatch.type = patch.type;1957  }19581959  if ("title" in patch) {1960    const title = patch.title?.trim() ?? "";1961    if (!title) throw new Error("title is required");1962    nextPatch.title = title;1963  }19641965  if ("url" in patch) {1966    nextPatch.url = patch.url?.trim() ?? "";1967  }19681969  if ("additionalUrls" in patch) {1970    const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];1971    const seen = new Set<string>();1972    const cleaned: string[] = [];1973    for (const value of incoming) {1974      const trimmed = typeof value === "string" ? value.trim() : "";1975      if (!trimmed) continue;1976      const key = trimmed.toLowerCase();1977      if (seen.has(key)) continue;1978      seen.add(key);1979      cleaned.push(trimmed);1980    }1981    nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;1982  }19831984  if ("username" in patch) {1985    nextPatch.username = patch.username?.trim() ?? "";1986  }19871988  if ("email" in patch) {1989    nextPatch.email = patch.email?.trim() || undefined;1990  }19911992  if ("password" in patch) {1993    const password = patch.password ?? "";1994    // Allow clearing a password (e.g. on passkey-only entries)1995    nextPatch.password = password || undefined;1996  }19971998  if ("totp" in patch) {1999    nextPatch.totp = patch.totp?.trim() || undefined;2000  }20012002  if ("notes" in patch) {2003    nextPatch.notes = patch.notes?.trim() || undefined;2004  }20052006  if ("breach" in patch) {2007    nextPatch.breach = patch.breach;2008  }20092010  if ("canary" in patch) {2011    nextPatch.canary = patch.canary;2012  }20132014  if ("passkey" in patch) {2015    // Passkey sub-object replaces all the legacy flat passkey fields. A2016    // patch with `passkey: undefined` removes the credential from the entry2017    // (used by "remove passkey" without deleting the whole entry).2018    nextPatch.passkey = patch.passkey;2019  }20202021  if ("tags" in patch) {2022    nextPatch.tags = patch.tags;2023  }20242025  if ("cardholderName" in patch) {2026    nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;2027  }2028  if ("cardNumber" in patch) {2029    const n = patch.cardNumber ?? "";2030    nextPatch.cardNumber = n || undefined;2031  }2032  if ("expMonth" in patch) {2033    nextPatch.expMonth = patch.expMonth?.trim() || undefined;2034  }2035  if ("expYear" in patch) {2036    nextPatch.expYear = patch.expYear?.trim() || undefined;2037  }2038  if ("cvc" in patch) {2039    nextPatch.cvc = patch.cvc?.trim() || undefined;2040  }2041  if ("cardNickname" in patch) {2042    nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;2043  }2044  if ("network" in patch) {2045    nextPatch.network = patch.network;2046  }2047  if ("last4" in patch) {2048    nextPatch.last4 = patch.last4?.trim() || undefined;2049  }20502051  return nextPatch;2052}20532054function normalizeEntry(entry: VaultEntry | LegacyVaultEntry): VaultEntry {2055  const createdAt = "createdAt" in entry ? entry.createdAt : entry.created;2056  const modifiedAt =2057    "modifiedAt" in entry ? entry.modifiedAt : entry.updated;20582059  const base: VaultEntry = {2060    id: entry.id,2061    type: "type" in entry ? entry.type : "login",2062    title: entry.title,2063    username: entry.username,2064    email: "email" in entry ? entry.email : undefined,2065    password: entry.password,2066    url: entry.url,2067    additionalUrls:2068      "additionalUrls" in entry && Array.isArray(entry.additionalUrls)2069        ? entry.additionalUrls2070        : undefined,2071    totp: entry.totp,2072    notes: entry.notes,2073    breach: entry.breach,2074    canary: "canary" in entry ? entry.canary : undefined,2075    passkey: "passkey" in entry ? entry.passkey : undefined,2076    createdAt,2077    modifiedAt,2078    deletedAt: entry.deletedAt,2079    tags: "tags" in entry ? entry.tags : undefined,2080    cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,2081    cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,2082    expMonth: "expMonth" in entry ? entry.expMonth : undefined,2083    expYear: "expYear" in entry ? entry.expYear : undefined,2084    cvc: "cvc" in entry ? entry.cvc : undefined,2085    cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,2086    network: "network" in entry ? entry.network : undefined,2087    last4: "last4" in entry ? entry.last4 : undefined,2088  };20892090  return migrateLegacyPasskey(base, entry);2091}20922093/**2094 * v2.11.0 read migration. Pre-v2.11.0 passkey entries used `type:"passkey"`2095 * with flat top-level fields (rpId, credentialId, etc.). This converts them2096 * to the new shape — `type:"login"` with a `passkey` sub-object — so all2097 * downstream consumers can rely on the new model. The result is rewritten2098 * to disk on next vault save (hasLegacyShape detects the un-migrated case).2099 */2100function migrateLegacyPasskey(2101  base: VaultEntry,2102  raw: VaultEntry | LegacyVaultEntry2103): VaultEntry {2104  if (base.passkey) return base;2105  const flat = raw as Partial<VaultEntry>;2106  const isPasskeyType = base.type === "passkey";2107  const hasFlatPasskeyFields =2108    typeof flat.rpId === "string" &&2109    typeof flat.credentialId === "string" &&2110    typeof flat.publicKeyCose === "string" &&2111    typeof flat.userHandle === "string" &&2112    typeof flat.userName === "string";2113  if (!isPasskeyType && !hasFlatPasskeyFields) return base;2114  if (!hasFlatPasskeyFields) return base;21152116  const algorithm: -7 | -8 = flat.algorithm === -8 ? -8 : -7;2117  base.passkey = {2118    rpId: flat.rpId!,2119    rpName: flat.rpName ?? flat.rpId!,2120    credentialId: flat.credentialId!,2121    publicKeyCose: flat.publicKeyCose!,2122    privateKeyJwk: flat.privateKeyJwk,2123    userHandle: flat.userHandle!,2124    userName: flat.userName!,2125    userDisplayName: flat.userDisplayName ?? flat.userName!,2126    algorithm,2127    signCount: flat.signCount ?? 0,2128    aaguid: flat.aaguid ?? "",2129    backupEligible: flat.backupEligible === true,2130    backupState: flat.backupState === true,2131    lastUsedAt: flat.lastUsedAt,2132    browser: flat.browser,2133    transports: flat.transports,2134    createdAt: base.createdAt,2135  };2136  // Promote to "login" so the unified Entry view renders. Username gets2137  // populated from the passkey's userName so the entry is searchable in the2138  // existing autofill flow without a separate code path.2139  if (isPasskeyType) base.type = "login";2140  if (!base.username) base.username = flat.userName;2141  if (!base.url) base.url = `https://${flat.rpId}`;2142  return base;2143}214421452146// ---------------------------------------------------------------------------2147// Deduplication2148// ---------------------------------------------------------------------------21492150function entryDupeKey(e: VaultEntry): string {2151  if (e.type === "note") return `note|${e.title.toLowerCase()}`;2152  // Passkey-bearing entries dedupe by the credential's RP + user. Two logins2153  // on different sites that happen to share a username are still distinct;2154  // two passkey credentials for the same RP+user are duplicates regardless2155  // of any login fields they may also carry.2156  if (e.passkey) {2157    return `passkey|${e.passkey.rpId.toLowerCase()}|${e.passkey.userName.toLowerCase()}`;2158  }2159  return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;2160}21612162/** Returns the number of duplicate entries (those that would be removed). */2163export function countDuplicates(): number {2164  const best = new Map<string, VaultEntry>();2165  let dupeCount = 0;2166  for (const e of entries.filter((e) => !e.deletedAt)) {2167    const key = entryDupeKey(e);2168    const existing = best.get(key);2169    if (!existing) {2170      best.set(key, e);2171    } else {2172      dupeCount++;2173      // Keep the more recently modified one in the map2174      if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2175        best.set(key, e);2176      }2177    }2178  }2179  return dupeCount;2180}21812182/**2183 * Soft-deletes duplicate entries, keeping the most recently modified copy of2184 * each group. Returns the number of entries moved to trash.2185 */2186export async function deduplicateEntries(): Promise<number> {2187  if (!derivedKey) throw new Error("vault_locked");2188  // Dedup reshapes slot B permanently under the decoy key, which is2189  // forensically distinguishable from a freshly-seeded decoy vault. Refuse.2190  if (vaultMode === "decoy") {2191    throw new Error("deduplicate disabled in decoy mode");2192  }21932194  const best = new Map<string, VaultEntry>();2195  for (const e of entries.filter((en) => !en.deletedAt)) {2196    const key = entryDupeKey(e);2197    const existing = best.get(key);2198    if (!existing) {2199      best.set(key, e);2200    } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2201      best.set(key, e);2202    }2203  }22042205  const keepIds = new Set(Array.from(best.values()).map((e) => e.id));2206  const now = Date.now();2207  let removed = 0;2208  entries = entries.map((e) => {2209    if (!e.deletedAt && !keepIds.has(e.id)) {2210      removed++;2211      return { ...e, deletedAt: now };2212    }2213    return e;2214  });22152216  if (removed > 0) await persistEntries();2217  return removed;2218}22192220// ---------------------------------------------------------------------------2221// Vault history — snapshot BEFORE every vault write so the saved blob is2222// what is about to be lost, not what was just written. Capped at 10. The2223// stored blobs are AES-256-GCM ciphertext under the master password, so2224// history adds zero security surface.2225// ---------------------------------------------------------------------------22262227const HISTORY_KEY = "peach_vault_history";2228const HISTORY_MAX = 10;22292230/**2231 * Snapshot the CURRENT on-disk vault state into history. Call this BEFORE2232 * overwriting peach_vault_a so the saved blob captures the about-to-be-lost2233 * state. Identical-to-most-recent blobs are skipped to avoid filling history2234 * with no-op writes.2235 */2236export async function takeVaultSnapshot(2237  reason: VaultSnapshot["reason"],2238): Promise<void> {2239  try {2240    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);2241    const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];2242    const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];22432244    // Nothing to snapshot if the real slot doesn't exist yet (fresh install,2245    // pre-createVault). createVault skips snapshots intentionally — there is2246    // no prior state to preserve.2247    if (!slotA) return;22482249    const vault_a = JSON.stringify(slotA);2250    const vault_b = JSON.stringify(slotB ?? slotA);22512252    // Best-effort entry count: only meaningful when the in-memory state is2253    // unlocked AND in real mode. Decoy mode would leak the decoy entry2254    // count; locked mode has no entries to count. Both fall through to null.2255    let entryCount: number | null = null;2256    if (derivedKey && vaultMode === "real") {2257      try {2258        entryCount = entries.filter((e) => !e.deletedAt).length;2259      } catch {2260        entryCount = null;2261      }2262    }22632264    const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];2265    const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)2266      ? existingRaw2267      : { snapshots: [] };22682269    // Deduplication: if the most recent snapshot has byte-identical blobs,2270    // skip — saves the same vault N times in a row would otherwise burn the2271    // entire history window with no recovery value.2272    const latest = history.snapshots[0];2273    if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {2274      return;2275    }22762277    const snapshot: VaultSnapshot = {2278      id: crypto.randomUUID(),2279      savedAt: Date.now(),2280      reason,2281      vault_a,2282      vault_b,2283      entryCount,2284    };22852286    history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);2287    await chrome.storage.local.set({ [HISTORY_KEY]: history });2288  } catch (err) {2289    // Non-fatal — history must never block a save. A failed snapshot just2290    // means the user loses one rung of the safety ladder for this write.2291    // M4/QUA-006: log so the failure is visible; if it looks like a quota2292    // problem, notify the popup so the user can prune history themselves.2293    console.warn('[Peach] takeVaultSnapshot failed:', err);2294    if (String(err).includes('QUOTA') || String(err).includes('quota')) {2295      try {2296        await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });2297      } catch {2298        // popup may be closed; surfaced via console.warn above2299      }2300    }2301  }2302}23032304/** Wipe all vault history. Called by Panic / DESTROY_VAULT. */2305export async function clearVaultHistory(): Promise<void> {2306  try {2307    await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });2308  } catch {2309    // Non-fatal — DESTROY_VAULT also runs storage.local.clear().2310  }2311}23122313/** Read all snapshots, newest first, for the Settings vault history view. */2314export async function getVaultHistory(): Promise<VaultSnapshot[]> {2315  const raw = await chrome.storage.local.get(HISTORY_KEY);2316  const history = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];2317  if (!history || !Array.isArray(history.snapshots)) return [];2318  return history.snapshots;2319}23202321/**2322 * Replace the on-disk vault with the chosen snapshot's blobs and lock the2323 * vault. The current state is itself snapshotted with reason 'restore' first2324 * so the restore is reversible. After this returns, the user must unlock2325 * with the password that matches the restored blob.2326 */2327export async function restoreVaultSnapshot(2328  snapshotId: string,2329): Promise<{ ok: true } | { ok: false; error: string }> {2330  const history = await getVaultHistory();2331  const snapshot = history.find((s) => s.id === snapshotId);2332  if (!snapshot) return { ok: false, error: "snapshot_not_found" };23332334  // Snapshot the about-to-be-replaced current state so the restore is2335  // reversible. takeVaultSnapshot is no-op when the most recent entry is2336  // byte-identical, so a restore-of-a-restore stays clean.2337  await takeVaultSnapshot("restore");23382339  let restoredA: StoredVault;2340  let restoredB: StoredVault;2341  try {2342    restoredA = JSON.parse(snapshot.vault_a) as StoredVault;2343    restoredB = JSON.parse(snapshot.vault_b) as StoredVault;2344  } catch {2345    return { ok: false, error: "snapshot_corrupt" };2346  }23472348  await writeSlot(SLOT_A, restoredA);2349  await writeSlot(SLOT_B, restoredB);2350  await stampLocalVaultMutation();23512352  // Lock so the user must prove they can decrypt the restored blob. If they2353  // restored a pre-password-change snapshot they discover it immediately at2354  // the lock screen rather than silently holding an inaccessible vault.2355  lock();23562357  return { ok: true };2358}23592360/**2361 * Change the master password. Re-encrypts slot A with a fresh salt + new2362 * derived key. Slot B (duress or noise) is left untouched when duress is2363 * configured — it uses an independent key derived from the duress password —2364 * and regenerated as noise when duress is not configured.2365 */2366export async function changePassword(2367  currentPassword: string,2368  newPassword: string2369): Promise<boolean> {2370  if (!derivedKey || vaultMode !== "real") return false;23712372  // Verify current password before allowing any change2373  const valid = await verifyMainPassword(currentPassword);2374  if (!valid) return false;23752376  const slotA = await loadSlot(SLOT_A);2377  if (!slotA) return false;2378  if (!rootKey) return false;23792380  // Derive fresh key from new password + new random salt2381  const newSalt = generateSalt();2382  const newKey = await deriveKey(newPassword, newSalt);23832384  // Re-encrypt the in-memory entries with the new key2385  const plaintext = encodePayload(entries, duressConfigured);2386  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");23872388  // Pre-wrap root key under the new derived key. Recovery fields wrap rootKey2389  // under recovery words and remain untouched — recovery phrase keeps working2390  // across password changes (H4/COR-002).2391  const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);23922393  const finalSlotA: StoredVault = {2394    ...slotA,2395    salt: hex(newSalt),2396    nonce,2397    ciphertext,2398    tag,2399    ...pwRoot,2400  };24012402  // Snapshot the OLD-key blob before overwriting it. If the user later2403  // restores from this snapshot they will need the OLD password — the2404  // post-restore lock surfaces that immediately.2405  await takeVaultSnapshot("local_save");24062407  // Single atomic write: ciphertext, salt, and pw_root_* fields all land in2408  // one storage transaction. An SW kill before this point leaves the old2409  // slot intact; after this point everything tied to the new password is2410  // already on disk together (M6/COR-004).2411  await writeSlot(SLOT_A, finalSlotA);24122413  // Swap the in-memory key synchronously before any further await. If we2414  // threw between the Slot A write and this swap, the next persistEntries()2415  // would overwrite Slot A with old-key ciphertext, locking the user out.2416  zeroKey(derivedKey);2417  derivedKey = newKey;24182419  // Regenerate noise for slot B when duress is not in use. Runs after the2420  // key swap so a failure here is a disposable noise regeneration, not a2421  // lockout.2422  if (!duressConfigured) {2423    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));2424  }2425  await stampLocalVaultMutation();24262427  return true;2428}