vault.ts

66.3 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 type {15  AccentColorName,16  LegacyVaultEntry,17  ManualSummonRecord,18  SavedIdentity,19  StoredVault,20  VaultEntry,21  VaultHistory,22  VaultSnapshot,23} from "../shared/types";24import { decrypt, encrypt, zeroKey } from "./aes";25import { clearAutoLock, touchAutoLock } from "./alarms";2627type EntryDraft = Omit<28  VaultEntry,29  "id" | "createdAt" | "modifiedAt" | "deletedAt"30>;3132// Slot-neutral storage keys (v1.4.24+). Both slots always exist; slot B33// either holds the decoy vault (when duress is configured) or random noise34// that looks identical at rest. No external indicator is stored — duress35// configuration is recorded only inside the encrypted payload of slot A.36const SLOT_A = "peach_vault_a";37const SLOT_B = "peach_vault_b";3839// Legacy keys, migrated away on first access.40const LEGACY_MAIN = "peach_vault";41const LEGACY_DECOY = "peach_decoy_vault";42const LEGACY_DURESS_FLAG = "peach_duress";4344// Plaintext is padded to the next multiple of this size before encryption.45// This coarsens ciphertext-length leakage into 1 KiB buckets.46const PAD_BLOCK = 1024;4748let derivedKey: Uint8Array | null = null;49// 32-byte random root key, separate from the derivedKey used for vault encryption.50// The root key is wrapped (encrypted) under the recovery key derived from the51// 12-word phrase. When the user changes their password, only the wrapping changes;52// the root key and recovery words remain stable.53let rootKey: Uint8Array | null = null;54let entries: VaultEntry[] = [];55let domainIndex: Map<string, VaultEntry[]> = new Map();56let vaultMode: "real" | "decoy" = "real";57// Cached post-unlock view of whether the real vault records that duress is58// configured. Only meaningful after a real-mode unlock; for decoy-mode unlock59// this stays false because we never see slot A's plaintext.60let duressConfigured = false;6162let migrationRan = false;6364// ---------------------------------------------------------------------------65// Settings (persisted inside the encrypted vault store as a sidecar key)66// ---------------------------------------------------------------------------6768export type DisplayFont = "cormorant-italic" | "cormorant" | "inter" | "system";69export type TextSize = "small" | "medium" | "large";7071export interface VaultSettings {72  accentColor?: AccentColorName;73  theme?: "dark" | "light";74  autoLockMinutes?: number;75  clipboardClearSeconds?: number;76  lockOnClose?: boolean;77  breachMonitoring?: boolean;78  passkeyProviderEnabled?: boolean;79  trashRetentionDays?: number;80  manualSummonDomains?: Record<string, ManualSummonRecord>;81  declinedCardFingerprints?: string[];82  /**83   * Display font for headlines, brand wordmark, and narrative copy. Default84   * is "cormorant-italic" — the bold italic serif that ships as Peach's85   * voice. Non-italic options exist for users who prefer upright type.86   */87  displayFont?: DisplayFont;88  /**89   * Text size scale for body copy and entry titles. Stops at "large" by90   * design — XL clips dense screens (Vault, Health) inside the fixed91   * 330×480 popup surface.92   */93  textSize?: TextSize;94  /**95   * When true, all entrance/exit transitions and ambient animations are96   * collapsed to instant. Honoured alongside the user's OS-level97   * `prefers-reduced-motion`.98   */99  reduceMotion?: boolean;100  /**101   * User overrides for keyboard shortcuts. Keys are ShortcutAction names102   * (see src/shared/shortcuts.ts). Missing actions fall through to103   * DEFAULT_BINDINGS — `getActiveBindings(settings.shortcuts)` is the104   * canonical lookup. Storing only the deltas keeps the vault payload105   * small and lets default updates land for users who never rebind.106   */107  shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;108}109110let settings: VaultSettings = {};111112export function getSettings(): VaultSettings {113  return settings;114}115116export async function ensureSettingsLoaded(): Promise<VaultSettings> {117  await loadSettings();118  return settings;119}120121export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {122  await loadSettings();123  settings = { ...settings, ...patch };124  await persistSettings();125}126127async function persistSettings(): Promise<void> {128  try {129    await chrome.storage.local.set({ peach_settings: settings });130  } catch (err) {131    throw mapStorageError(err);132  }133}134135function mapStorageError(err: unknown): Error {136  const message = err instanceof Error ? err.message : String(err);137  if (/QUOTA_BYTES|quota/i.test(message)) {138    return new Error("STORAGE_QUOTA_EXCEEDED");139  }140  return err instanceof Error ? err : new Error(message);141}142143async function loadSettings(): Promise<void> {144  const result = await chrome.storage.local.get("peach_settings");145  settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};146}147148// ---------------------------------------------------------------------------149// HIBP breach check (k-anonymity model)150// ---------------------------------------------------------------------------151152export async function checkBreach(password: string): Promise<number> {153  const encoder = new TextEncoder();154  const hashBuffer = await crypto.subtle.digest("SHA-1", encoder.encode(password));155  const hashHex = Array.from(new Uint8Array(hashBuffer))156    .map((b) => b.toString(16).padStart(2, "0"))157    .join("")158    .toUpperCase();159160  const prefix = hashHex.slice(0, 5);161  const suffix = hashHex.slice(5);162163  try {164    const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`);165    if (!res.ok) return 0;166    const text = await res.text();167    const match = text.split("\r\n").find((l) => l.startsWith(suffix));168    return match ? parseInt(match.split(":")[1], 10) : 0;169  } catch {170    return 0; // Network unavailable — don't block171  }172}173174export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {175  const fingerprint = await cardFingerprint(last4, expMonth, expYear);176  await loadSettings();177  settings = {178    ...settings,179    declinedCardFingerprints: [...(settings.declinedCardFingerprints ?? []), fingerprint],180  };181  await persistSettings();182}183184export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {185  await loadSettings();186  const fingerprint = await cardFingerprint(last4, expMonth, expYear);187  return (settings.declinedCardFingerprints ?? []).includes(fingerprint);188}189190async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {191  const encoder = new TextEncoder();192  const buf = await crypto.subtle.digest("SHA-1", encoder.encode(`${last4}${expMonth}${expYear}`));193  return Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2, "0")).join("");194}195196function hex(buf: Uint8Array): string {197  return Array.from(buf)198    .map((b) => b.toString(16).padStart(2, "0"))199    .join("");200}201202function unhex(s: string): Uint8Array {203  const out = new Uint8Array(s.length / 2);204  for (let i = 0; i < s.length; i += 2) {205    out[i / 2] = parseInt(s.slice(i, i + 2), 16);206  }207  return out;208}209210// ---------------------------------------------------------------------------211// Root key generation and recovery word wrapping212// ---------------------------------------------------------------------------213214/**215 * Generate a random 32-byte root key and wrap it (AES-256-GCM) under a key216 * derived from the recovery word material via HKDF-SHA256. The wrapped blob217 * fields are stored in slot A alongside the password-wrapped ciphertext. The218 * root key itself is kept in memory for the session so getRecoveryWords() can219 * encode it without re-deriving.220 */221async function generateAndWrapRootKey(): Promise<{222  recoverySalt: string;223  wrappedRootKey: string;224  wrappedNonce: string;225  wrappedTag: string;226}> {227  const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));228229  // Encode the root key as 12 BIP39 words for user-facing display.230  const words = await import("../shared/recovery-words").then((m) =>231    m.rootKeyToWords(rootKeyBytes)232  );233  void words; // returned to caller for getRecoveryWords()234235  // Derive the recovery key from the words using HKDF-SHA256.236  const { wordsToRootKeyMaterial, deriveRecoveryKey } = await import(237    "../shared/recovery-words"238  );239  const wordMaterial = await wordsToRootKeyMaterial(words);240  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));241  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);242243  // Wrap the root key with the recovery key using AES-256-GCM directly.244  // We hex-encode rootKeyBytes so the plaintext is always valid UTF-8.245  const nonce = crypto.getRandomValues(new Uint8Array(12));246  const encoded = new TextEncoder().encode(hex(rootKeyBytes));247  const raw = await crypto.subtle.encrypt(248    {249      name: "AES-GCM",250      iv: nonce,251      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,252      tagLength: 128,253    },254    recoveryKey,255    encoded256  );257  // WebCrypto returns ciphertext || auth tag concatenated; split them.258  const rawU8 = new Uint8Array(raw);259  const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));260  const tag = hex(rawU8.slice(rawU8.length - 16));261262  return {263    recoverySalt: hex(recoverySalt),264    wrappedRootKey: ciphertext,265    wrappedNonce: hex(nonce),266    wrappedTag: tag,267  };268}269270/**271 * Unwrap the root key using recovery words. Called during recovery flow when272 * the user provides their 12-word phrase and a new password.273 * Exported for use by the RECOVER_WITH_WORDS message handler.274 */275export async function unwrapRootKeyForRecovery(276  wrappedRootKey: string,277  wrappedNonce: string,278  wrappedTag: string,279  recoverySaltHex: string,280  words: string[]281): Promise<void> {282  const { wordsToRootKeyMaterial, deriveRecoveryKey } = await import(283    "../shared/recovery-words"284  );285  const wordMaterial = await wordsToRootKeyMaterial(words);286  const recoverySalt = unhex(recoverySaltHex);287  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);288289  // Decrypt and cache the root key. The root key bytes were hex-encoded before290  // encryption so the ciphertext is valid UTF-8. We inline the AES-GCM decrypt291  // here to avoid passing a CryptoKey to the string-based encrypt/decrypt helpers.292  const combined = unhex(wrappedRootKey + wrappedNonce + wrappedTag);293  const nonceU8 = combined.slice(0, 12);294  const ciphertext = combined.slice(12, combined.length - 16);295  const storedTag = combined.slice(combined.length - 16);296  const raw = await crypto.subtle.decrypt(297    { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },298    recoveryKey,299    new Uint8Array([...ciphertext, ...storedTag])300  );301  const decryptedHex = new TextDecoder().decode(raw);302  rootKey = unhex(decryptedHex);303}304305/**306 * Re-wrap the cached root key under a new derived key (from the user's new307 * password). Called after password change and after recovery re-key so the308 * same recovery words continue to work with the updated password.309 */310export async function rewrapRootKeyForPassword(311  newDerivedKey: Uint8Array,312  _newSalt: Uint8Array313): Promise<void> {314  if (!rootKey) throw new Error("root key not set");315  const { nonce, ciphertext, tag } = await encrypt(316    newDerivedKey,317    hex(rootKey)318  );319  const slotA = await loadSlot(SLOT_A);320  if (!slotA) throw new Error("missing slot A");321  await writeSlot(SLOT_A, {322    ...slotA,323    recovery_wrapped_root_key: ciphertext,324    recovery_nonce: nonce,325    recovery_tag: tag,326    // recovery_salt does NOT change when password changes — the recovery327    // words always derive the same key; only the wrapping key changes.328  });329}330331/**332 * Change the vault encryption to a new derived key (already derived from333 * the user's new password). Used by RECOVER_WITH_WORDS and changePassword.334 * Caller is responsible for key swap and snapshot.335 */336async function reencryptVaultForNewKey(337  newKey: Uint8Array,338  slotA: StoredVault339): Promise<void> {340  const plaintext = encodePayload(entries, duressConfigured);341  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext);342  await writeSlot(SLOT_A, {343    ...slotA,344    nonce,345    ciphertext,346    tag,347  });348}349350/**351 * Full password change with an already-derived key (used after recovery).352 * Unlike changePassword(), this skips re-verification of current password353 * since recovery flow has already validated the user's identity via words.354 */355export async function changePasswordWithNewKey(356  newSalt: Uint8Array,357  newKey: Uint8Array358): Promise<void> {359  const slotA = await loadSlot(SLOT_A);360  if (!slotA) throw new Error("missing slot A");361  await reencryptVaultForNewKey(newKey, slotA);362  zeroKey(derivedKey!);363  derivedKey = newKey;364  if (!duressConfigured) {365    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));366  }367}368369// ---------------------------------------------------------------------------370// Salt generation --- exported so the RECOVER_WITH_WORDS handler can derive371// a new key after password reset without re-importing the crypto module.372// ---------------------------------------------------------------------------373374export { deriveKey, generateSalt };375376export async function loadSlotA(): Promise<StoredVault | null> {377  return loadSlot(SLOT_A);378}379380/**381 * Re-derive the session root key from the already-derived AES key (keyA from382 * unlock) and the recovery salt stored in slot A. This is the inverse of383 * generateAndWrapRootKey() — both operations use the same HKDF with the same384 * salt and info string, so they cancel out.385 *386 * The derivedKey and rootKey are related by:387 *   derivedKey = Argon2id(password, slotA.salt)   → AES key for vault payload388 *   rootKey    = HKDF-SHA256(recovery_words, recovery_salt)  → wrapped by HKDF389 *390 * Since we only store the wrapped root key and the recovery salt, we can391 * only re-derive rootKey during an active (unlocked) session where we have392 * the derivedKey already. On lock, rootKey is zeroed.393 *394 * For pre-v2.12 vaults that have no recovery_salt, this returns null and395 * the caller must invoke migrateToRecovery() to generate the recovery escrow.396 */397async function deriveRootKeyFromDerivedKey(398  _derivedKey: Uint8Array,399  _recoverySaltHex: string400): Promise<Uint8Array | null> {401  // The root key is stored wrapped under the recovery key derived from the402  // 12-word phrase. It cannot be re-derived from derivedKey alone — that would403  // require knowing the original recovery words. The in-memory rootKey is set404  // during unlock if recovery data is present.405  // This function exists as a potential future path if we ever store an406  // additional derived-key → root-key relationship. Currently rootKey is407  // cached directly during unlock.408  return null;409}410411/**412 * For vaults created before v2.12 (no recovery_salt/recovery_wrapped_root_key),413 * generate the root key, wrap it under the recovery words, and persist the414 * recovery escrow into slot A. The caller must show the recovery words to the415 * user before calling this — once called, those words are the vault's recovery416 * path. This runs once, on the first unlock of an upgraded vault.417 */418export async function migrateToRecovery(): Promise<void> {419  if (!derivedKey || vaultMode !== "real") {420    throw new Error("vault must be unlocked in real mode");421  }422  const slotA = await loadSlot(SLOT_A);423  if (!slotA) throw new Error("missing slot A");424  if (slotA.recovery_salt && slotA.recovery_wrapped_root_key) return; // already done425426  const { recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =427    await generateAndWrapRootKey();428429  rootKey = unhex(wrappedRootKey); // keep for getRecoveryWords()430431  const nextSlotA: StoredVault = {432    ...slotA,433    recovery_salt: recoverySalt,434    recovery_wrapped_root_key: wrappedRootKey,435  };436  await writeSlot(SLOT_A, nextSlotA);437}438439/**440 * Returns the 12 recovery words for the current session's root key.441 * Must be called while the vault is unlocked. Throws if recovery has not442 * been set up (pre-v2.12 vault that hasn't migrated yet).443 */444export async function getRecoveryWords(): Promise<string[]> {445  if (!rootKey) {446    throw new Error("recovery not set up — vault may need migration");447  }448  const { rootKeyToWords } = await import("../shared/recovery-words");449  return rootKeyToWords(rootKey);450}451452async function loadSlot(key: string): Promise<StoredVault | null> {453  const result = await chrome.storage.local.get(key);454  return (result as Record<string, StoredVault | undefined>)[key] ?? null;455}456457async function writeSlot(key: string, vault: StoredVault): Promise<void> {458  try {459    await chrome.storage.local.set({ [key]: vault });460  } catch (err) {461    throw mapStorageError(err);462  }463}464465/**466 * One-shot migration from the pre-A-2 schema (peach_vault + peach_decoy_vault467 * + peach_duress flag) to the slot-neutral schema (peach_vault_a +468 * peach_vault_b). Runs at most once per session; safe to call repeatedly.469 */470async function ensureMigrated(): Promise<void> {471  if (migrationRan) return;472  migrationRan = true;473474  const keys = [LEGACY_MAIN, LEGACY_DECOY, LEGACY_DURESS_FLAG, SLOT_A, SLOT_B];475  const raw = await chrome.storage.local.get(keys);476  const slotAExists = raw[SLOT_A] !== undefined;477  const slotBExists = raw[SLOT_B] !== undefined;478  const legacyMain = raw[LEGACY_MAIN] as StoredVault | undefined;479  const legacyDecoy = raw[LEGACY_DECOY] as StoredVault | undefined;480481  // Fresh install with nothing in storage — nothing to do; createVault() sets up both slots.482  if (!slotAExists && !legacyMain) return;483484  // Already migrated.485  if (slotAExists && slotBExists && !legacyMain && !legacyDecoy) return;486487  if (legacyMain && !slotAExists) {488    await writeSlot(SLOT_A, legacyMain);489  }490491  // If slot B isn't set, populate it: use legacy decoy when present, else noise.492  if (!slotBExists) {493    const target = (legacyMain ?? raw[SLOT_A]) as StoredVault | undefined;494    if (legacyDecoy) {495      await writeSlot(SLOT_B, legacyDecoy);496    } else if (target) {497      await writeSlot(SLOT_B, generateNoiseBlob(target.ciphertext.length / 2));498    }499  }500501  const toRemove: string[] = [];502  if (legacyMain) toRemove.push(LEGACY_MAIN);503  if (legacyDecoy) toRemove.push(LEGACY_DECOY);504  if (raw[LEGACY_DURESS_FLAG] !== undefined) toRemove.push(LEGACY_DURESS_FLAG);505  if (toRemove.length > 0) {506    await chrome.storage.local.remove(toRemove);507  }508}509510// ---------------------------------------------------------------------------511// Padding + noise helpers512// ---------------------------------------------------------------------------513514/**515 * Pads the plaintext string with trailing spaces so that the encoded byte516 * length is a multiple of PAD_BLOCK. JSON.parse tolerates trailing517 * whitespace after a complete document, so the padding is transparent on518 * decode. Ciphertext length equals plaintext length plus a 16-byte tag.519 */520function padPlaintext(json: string): string {521  const encoded = new TextEncoder().encode(json);522  const target = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);523  const padLen = target - encoded.length;524  return json + " ".repeat(padLen);525}526527/**528 * Produces a StoredVault-shaped record filled with CSPRNG bytes. The529 * ciphertext length matches the given byte count. Because GCM ciphertext is530 * pseudo-random, this blob is indistinguishable at rest from a real531 * encrypted vault without the key.532 *533 * crypto.getRandomValues() caps each call at 65536 bytes (the Web Crypto534 * spec hard limit). Chunk the fill so vaults larger than that — common once535 * the user has dozens of entries or any passkey — don't throw.536 */537const CSPRNG_CHUNK = 65_536;538539function fillRandom(buf: Uint8Array): Uint8Array {540  for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {541    const end = Math.min(offset + CSPRNG_CHUNK, buf.length);542    const chunk = new Uint8Array(end - offset);543    crypto.getRandomValues(chunk);544    buf.set(chunk, offset);545  }546  return buf;547}548549function generateNoiseBlob(ciphertextBytes: number): StoredVault {550  const salt = crypto.getRandomValues(new Uint8Array(16));551  const nonce = crypto.getRandomValues(new Uint8Array(12));552  const cipher = fillRandom(new Uint8Array(ciphertextBytes));553  const tag = crypto.getRandomValues(new Uint8Array(16));554  return {555    version: 1,556    salt: hex(salt),557    nonce: hex(nonce),558    ciphertext: hex(cipher),559    tag: hex(tag),560  };561}562563// ---------------------------------------------------------------------------564// Encrypted plaintext envelope565// ---------------------------------------------------------------------------566567type VaultPayload = {568  entries: VaultEntry[];569  duressConfigured?: boolean;570};571572type DecryptedPayload = {573  entries: VaultEntry[];574  duressConfigured: boolean;575  /**576   * True when at least one entry in the on-disk payload had a legacy shape577   * (pre-v2.11.0 passkey type/flat fields, or pre-A-2 created/updated keys)578   * and got rewritten by normalizeEntry. The unlock path uses this to579   * persist the new shape immediately — without it, the migration would580   * re-run on every unlock and old shape never disappears from disk.581   */582  migratedFromLegacy: boolean;583};584585function encodePayload(entries: VaultEntry[], duress: boolean): string {586  const envelope: VaultPayload = { entries, duressConfigured: duress };587  return padPlaintext(JSON.stringify(envelope));588}589590function rawNeedsMigration(raw: VaultEntry | LegacyVaultEntry): boolean {591  if ("created" in raw || "updated" in raw) return true;592  const flat = raw as Partial<VaultEntry>;593  if (flat.type === "passkey") return true;594  // Flat rpId without a passkey sub-object means pre-v2.11.0 schema.595  if (flat.rpId !== undefined && flat.passkey === undefined) return true;596  return false;597}598599function decodePayload(plain: string): DecryptedPayload {600  const parsed = JSON.parse(plain) as601    | Array<VaultEntry | LegacyVaultEntry>602    | VaultPayload;603604  const rawEntries = Array.isArray(parsed) ? parsed : parsed.entries ?? [];605  const flatMigrationNeeded = rawEntries.some(rawNeedsMigration);606607  const normalized = rawEntries.map(normalizeEntry);608  const { merged } = mergePasskeyOnlyIntoLogins(normalized);609610  if (Array.isArray(parsed)) {611    return {612      entries: normalized,613      duressConfigured: false,614      migratedFromLegacy: true, // pre-A-2 array shape always needs save615    };616  }617618  return {619    entries: normalized,620    duressConfigured: parsed.duressConfigured === true,621    migratedFromLegacy: flatMigrationNeeded || merged,622  };623}624625/**626 * One-time consolidation pass run alongside the legacy passkey migration.627 *628 * Pre-v2.11.0 the Chrome passkey path always created a fresh `type:"passkey"`629 * entry per registration — so users who tested registration multiple times630 * accumulated several passkey-bearing entries for the same RP, and the631 * migration to the unified shape carried that duplication forward. This632 * pass collapses the duplicates:633 *634 *   1. Group passkey-bearing (and not deleted) entries by `passkey.rpId`.635 *   2. Within each group, the most recently-active credential wins (prefer636 *      lastUsedAt, fall back to passkey.createdAt, fall back to modifiedAt).637 *   3. If a NON-passkey login entry exists for that RP (matched by url or638 *      additionalUrls hostname), attach the winning passkey to it and639 *      soft-delete every passkey-bearing entry in the group.640 *   4. Otherwise, soft-delete every loser in the group, keeping the winner641 *      as a passkey-only entry.642 *643 * Soft delete (deletedAt) rather than splice — the trash flow keeps the644 * record around for retention and the user can restore if the heuristic645 * picked wrong. The `merged` flag goes back to decodePayload so the646 * unlock path persists the consolidated shape immediately.647 */648function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {649  let merged = false;650  const now = Date.now();651652  const candidates = entries.filter((e) => !e.deletedAt && e.passkey);653  const byRpId = new Map<string, VaultEntry[]>();654  for (const e of candidates) {655    const rpId = e.passkey!.rpId;656    const list = byRpId.get(rpId);657    if (list) list.push(e);658    else byRpId.set(rpId, [e]);659  }660661  for (const [rpId, group] of byRpId) {662    if (group.length === 0) continue;663    group.sort((a, b) => {664      const aT =665        a.passkey!.lastUsedAt ?? a.passkey!.createdAt ?? a.modifiedAt ?? a.createdAt;666      const bT =667        b.passkey!.lastUsedAt ?? b.passkey!.createdAt ?? b.modifiedAt ?? b.createdAt;668      return bT - aT;669    });670    const winner = group[0]!;671672    // Look for a NON-passkey login entry matching this RP. Use the URL673    // hostname rather than a substring search so a "login.foo.com" entry674    // doesn't accidentally absorb a passkey for "foo.com".675    const loginTarget = entries.find((e) => {676      if (e.deletedAt || e.passkey || e.type !== "login") return false;677      if (e.url && extractDomain(e.url) === rpId) return true;678      for (const extra of e.additionalUrls ?? []) {679        if (extractDomain(extra) === rpId) return true;680      }681      return false;682    });683684    if (loginTarget) {685      loginTarget.passkey = winner.passkey;686      loginTarget.modifiedAt = now;687      for (const dup of group) {688        if (!dup.deletedAt) {689          dup.deletedAt = now;690          dup.modifiedAt = now;691        }692      }693      merged = true;694    } else if (group.length > 1) {695      for (let i = 1; i < group.length; i += 1) {696        const dup = group[i]!;697        if (!dup.deletedAt) {698          dup.deletedAt = now;699          dup.modifiedAt = now;700        }701      }702      merged = true;703    }704  }705706  return { merged };707}708709async function tryDecryptSlot(710  vault: StoredVault,711  key: Uint8Array712): Promise<DecryptedPayload | null> {713  try {714    const plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag);715    return decodePayload(plain);716  } catch {717    return null;718  }719}720721// ---------------------------------------------------------------------------722// Core operations723// ---------------------------------------------------------------------------724725function buildDomainIndexSync(all: VaultEntry[]): void {726  domainIndex = new Map();727728  for (const entry of all) {729    if (entry.deletedAt) continue;730    if (entry.type === "note" || entry.type === "card") continue;731732    // An entry can match multiple sites via `additionalUrls`. Index each733    // hostname so `queryDomain` returns the entry regardless of which alias734    // the user is currently visiting. Dedupe per-entry so a single entry735    // never appears twice in one bucket.736    const domains = new Set<string>();737    const primary = extractDomain(entry.url ?? "");738    if (primary) domains.add(primary);739    for (const extra of entry.additionalUrls ?? []) {740      const d = extractDomain(extra);741      if (d) domains.add(d);742    }743    if (domains.size === 0) continue;744745    for (const domain of domains) {746      const bucket = domainIndex.get(domain) ?? [];747      bucket.push(entry);748      domainIndex.set(domain, bucket);749    }750  }751}752753export async function createVault(password: string): Promise<void> {754  await ensureMigrated();755756  const salt = generateSalt();757  derivedKey = await deriveKey(password, salt);758  entries = [];759  vaultMode = "real";760  duressConfigured = false;761  buildDomainIndexSync(entries);762763  // Generate and wrap the root key for recovery word escrow.764  const { recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =765    await generateAndWrapRootKey();766  rootKey = unhex(wrappedRootKey); // keep for getRecoveryWords()767768  const plaintext = encodePayload(entries, duressConfigured);769  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext);770771  const slotA: StoredVault = {772    version: 1,773    salt: hex(salt),774    nonce,775    ciphertext,776    tag,777    recovery_salt: recoverySalt,778    recovery_wrapped_root_key: wrappedRootKey,779  };780  await writeSlot(SLOT_A, slotA);781782  // Matching-size noise blob for slot B, so a fresh install shows two783  // similarly-shaped records regardless of whether duress is ever set up.784  await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));785786  touchAutoLock();787}788789export async function hasVault(): Promise<boolean> {790  await ensureMigrated();791  return (await loadSlot(SLOT_A)) !== null;792}793794/**795 * Returns whether the real vault has recorded that a duress passphrase is796 * configured. Reliable only after a real-mode unlock — before unlock or in797 * decoy mode, returns false because we cannot read slot A's plaintext.798 */799export async function isDuressEnabled(): Promise<boolean> {800  return vaultMode === "real" && duressConfigured;801}802803export async function hasDecoyVault(): Promise<boolean> {804  return isDuressEnabled();805}806807export async function setupDuress(duressPassword: string): Promise<void> {808  if (!derivedKey || vaultMode !== "real") {809    throw new Error("vault must be unlocked in real mode");810  }811  await ensureMigrated();812813  // Encrypt the decoy payload (empty entries) under the duress key. Pad to814  // at least the current slot A ciphertext size so the two slots look the815  // same at rest at setup time.816  const slotA = await loadSlot(SLOT_A);817  if (!slotA) throw new Error("missing slot A");818819  const decoySalt = generateSalt();820  const decoyKey = await deriveKey(duressPassword, decoySalt);821  try {822    // Pad the decoy plaintext to match slot A's ciphertext length (minus the823    // 16-byte tag) so encrypted sizes align exactly.824    const targetBytes = slotA.ciphertext.length / 2;825    let plaintext = encodePayload([], false);826    const encoded = new TextEncoder().encode(plaintext);827    if (encoded.length < targetBytes) {828      plaintext = plaintext + " ".repeat(targetBytes - encoded.length);829    }830    const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext);831    await writeSlot(SLOT_B, {832      version: 1,833      salt: hex(decoySalt),834      nonce,835      ciphertext,836      tag,837    });838  } finally {839    zeroKey(decoyKey);840  }841842  // Re-encrypt slot A with the duressConfigured flag set to true. No external843  // flag is written — the bit lives inside the encrypted envelope.844  duressConfigured = true;845  await persistSlotA();846}847848export async function disableDuress(): Promise<void> {849  if (!derivedKey || vaultMode !== "real") {850    throw new Error("vault must be unlocked in real mode");851  }852  await ensureMigrated();853854  // Overwrite slot B with fresh noise that matches slot A's size. The slot855  // remains occupied so its mere existence does not signal that duress was856  // ever configured.857  const slotA = await loadSlot(SLOT_A);858  if (slotA) {859    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));860  }861862  duressConfigured = false;863  await persistSlotA();864}865866export async function verifyMainPassword(password: string): Promise<boolean> {867  await ensureMigrated();868  const slotA = await loadSlot(SLOT_A);869  if (!slotA) return false;870  const key = await deriveKey(password, unhex(slotA.salt));871  try {872    return (await tryDecryptSlot(slotA, key)) !== null;873  } finally {874    zeroKey(key);875  }876}877878export async function unlock(password: string): Promise<boolean> {879  await ensureMigrated();880881  // Load both slots in parallel. Both always exist post-migration; the882  // parallel load and the parallel derivation below keep wall-clock time883  // constant regardless of which slot's passphrase (real or decoy) the884  // caller supplied, so a timing side channel cannot distinguish the885  // duress path from the real-unlock path (DUR-002).886  const [slotA, slotB] = await Promise.all([887    loadSlot(SLOT_A),888    loadSlot(SLOT_B),889  ]);890891  // Derive both keys in parallel, unconditionally.892  const [keyA, keyB] = await Promise.all([893    slotA ? deriveKey(password, unhex(slotA.salt)) : Promise.resolve(null),894    slotB ? deriveKey(password, unhex(slotB.salt)) : Promise.resolve(null),895  ]);896897  // Attempt both decrypts in parallel.898  const [payloadA, payloadB] = await Promise.all([899    keyA && slotA ? tryDecryptSlot(slotA, keyA) : Promise.resolve(null),900    keyB && slotB ? tryDecryptSlot(slotB, keyB) : Promise.resolve(null),901  ]);902903  if (payloadA && keyA) {904    derivedKey = keyA;905    vaultMode = "real";906    entries = payloadA.entries;907    duressConfigured = payloadA.duressConfigured;908    buildDomainIndexSync(entries);909    await loadSettings();910    touchAutoLock();911    if (keyB) zeroKey(keyB);912913    // slotA is non-null when payloadA is truthy (keyA was derived from slotA).914    if (slotA) {915      const needsRecoverySetup =916        !slotA.recovery_salt || !slotA.recovery_wrapped_root_key;917      if (!needsRecoverySetup) {918        rootKey = await deriveRootKeyFromDerivedKey(919          keyA,920          slotA.recovery_salt!921        );922      }923    }924925    // If the payload had a pre-v2.11.0 shape (legacy passkey type, flat926    // passkey fields, or pre-A-2 created/updated keys), rewrite it now so927    // the next save uses the new format and migration doesn't re-run forever.928    if (payloadA.migratedFromLegacy) {929      await persistSlotA();930    }931    return true;932  }933934  if (payloadB && keyB) {935    derivedKey = keyB;936    vaultMode = "decoy";937    entries = payloadB.entries;938    duressConfigured = false;939    buildDomainIndexSync(entries);940    await loadSettings();941    touchAutoLock();942    if (keyA) zeroKey(keyA);943    return true;944  }945946  if (keyA) zeroKey(keyA);947  if (keyB) zeroKey(keyB);948  return false;949}950951export function lock(): void {952  if (derivedKey) {953    zeroKey(derivedKey);954    derivedKey = null;955  }956  if (rootKey) {957    rootKey.fill(0);958    rootKey = null;959  }960961  entries = [];962  domainIndex = new Map();963  vaultMode = "real";964  duressConfigured = false;965  clearAutoLock();966}967968export function isUnlocked(): boolean {969  return derivedKey !== null;970}971972// Opens the vault using a pre-derived AES-256 key (skipping Argon2id).973// Used by Android biometric unlock — the key was derived on the native side.974export async function unlockWithKey(975  masterKeyHex: string,976): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {977  try {978    const masterKeyBytes = unhex(masterKeyHex);979    const stored = await loadSlot(SLOT_A);980    if (!stored) return { ok: false, error: "invalid_key" };981    const payload = await tryDecryptSlot(stored, masterKeyBytes);982    if (!payload) return { ok: false, error: "invalid_key" };983984    derivedKey = masterKeyBytes;985    vaultMode = "real";986    entries = payload.entries;987    duressConfigured = payload.duressConfigured;988    buildDomainIndexSync(entries);989    await loadSettings();990    touchAutoLock();991    return { ok: true, entries };992  } catch {993    return { ok: false, error: "invalid_key" };994  }995}996997// Returns the current in-memory derived key as a hex string.998// Used by the biometric enable flow in Settings to store the key in Android Keystore.999export function getDerivedKeyHex(): string {1000  if (!derivedKey) throw new Error("vault_not_unlocked");1001  return hex(derivedKey);1002}10031004export function getEntries(): VaultEntry[] {1005  if (!derivedKey) throw new Error("vault locked");1006  return entries.filter((entry) => !entry.deletedAt);1007}10081009const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;10101011export function getIdentities(): SavedIdentity[] {1012  if (!derivedKey) throw new Error("vault locked");1013  const active = entries.filter((e) => !e.deletedAt && e.type === "login");10141015  const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();1016  const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();10171018  for (const entry of active) {1019    const value = entry.username?.trim();1020    if (!value) continue;1021    const map = EMAIL_RE.test(value) ? emailMap : usernameMap;1022    const existing = map.get(value);1023    const domain = extractDomain(entry.url ?? "") ?? "";1024    const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;1025    if (!existing || modifiedAt > existing.lastUsed) {1026      map.set(value, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });1027    } else {1028      map.set(value, { ...existing, count: existing.count + 1 });1029    }1030  }10311032  const toIdentity = (type: "email" | "username") =>1033    ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({1034      value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,1035    });10361037  return [1038    ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),1039    ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),1040  ];1041}10421043export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {1044  if (!derivedKey) throw new Error("vault locked");10451046  const now = Date.now();1047  const added: VaultEntry[] = [];1048  for (const draft of drafts) {1049    try {1050      const sanitized = sanitizeEntryDraft(draft);1051      const nextEntry: VaultEntry = {1052        ...sanitized,1053        id: crypto.randomUUID(),1054        createdAt: now,1055        modifiedAt: now,1056      };1057      entries.push(nextEntry);1058      added.push(nextEntry);1059    } catch {1060      // Skip invalid drafts silently — caller can see diff between input and output length1061    }1062  }10631064  if (added.length > 0) {1065    await persistEntries();1066  }10671068  return added;1069}10701071/**1072 * Restore a set of entries in full fidelity — preserves id, createdAt,1073 * modifiedAt, and every other field unlike `batchAddEntries` which1074 * assigns fresh identity. Used by restore paths where the backup is the1075 * authoritative source of truth. `mode` controls how entries already in1076 * the vault are treated.1077 */1078export async function restoreEntries(1079  incoming: VaultEntry[],1080  mode: "replace" | "merge"1081): Promise<{ added: number; updated: number; skipped: number }> {1082  if (!derivedKey) throw new Error("vault locked");10831084  // A replace with zero incoming entries is almost certainly a caller bug1085  // (e.g. an import that silently dropped everything). Refuse rather than1086  // wipe the vault.1087  if (mode === "replace" && incoming.length === 0) {1088    throw new Error("refuse to replace with empty entry set");1089  }10901091  let added = 0;1092  let updated = 0;1093  let skipped = 0;10941095  if (mode === "replace") {1096    entries = [];1097    for (const entry of incoming) {1098      const normalized = sanitizeRestoredEntry(entry);1099      if (!normalized) {1100        skipped += 1;1101        continue;1102      }1103      entries.push(normalized);1104      added += 1;1105    }1106  } else {1107    const byId = new Map<string, VaultEntry>();1108    for (const e of entries) byId.set(e.id, e);11091110    for (const entry of incoming) {1111      const normalized = sanitizeRestoredEntry(entry);1112      if (!normalized) {1113        skipped += 1;1114        continue;1115      }1116      const existing = byId.get(normalized.id);1117      if (!existing) {1118        entries.push(normalized);1119        added += 1;1120      } else if (normalized.modifiedAt > existing.modifiedAt) {1121        const idx = entries.findIndex((e) => e.id === existing.id);1122        if (idx !== -1) {1123          entries[idx] = normalized;1124          updated += 1;1125        }1126      } else {1127        skipped += 1;1128      }1129    }1130  }11311132  await persistEntries("import");1133  return { added, updated, skipped };1134}11351136/**1137 * Validate + normalise a VaultEntry coming from a backup. Accepts1138 * anything structurally sound; keeps all metadata verbatim. Returns1139 * null for values the live vault shouldn't accept (e.g., missing title).1140 */1141function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {1142  if (!entry || typeof entry !== "object") return null;1143  const title = typeof entry.title === "string" ? entry.title.trim() : "";1144  if (!title) return null;1145  const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();1146  const now = Date.now();1147  const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;1148  const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;11491150  // Migrate legacy passkey shape on import (same logic as on-disk read).1151  // Imports from pre-v2.11.0 vault backups still carry type:"passkey" with1152  // flat fields; bring them into the new shape immediately.1153  const migrated: VaultEntry = migrateLegacyPasskey(1154    {1155      ...entry,1156      id,1157      title,1158      type: entry.type ?? "login",1159      createdAt,1160      modifiedAt,1161    },1162    entry1163  );11641165  // Login entries from backup must carry a password (or be passkey-only,1166  // in which case the passkey sub-object replaces the password requirement).1167  if (1168    migrated.type === "login" &&1169    !migrated.passkey &&1170    typeof migrated.password !== "string"1171  ) {1172    return null;1173  }1174  if (migrated.passkey && !migrated.passkey.credentialId) {1175    return null;1176  }11771178  return migrated;1179}11801181// Soft-deletes every non-deleted entry in one call. The literal string1182// argument is a tripwire against accidental calls — any caller that would1183// wipe the vault has to consciously type "REPLACE_ALL". Do not relax this1184// to a boolean.1185export async function clearVaultEntries(1186  confirmation: "REPLACE_ALL"1187): Promise<void> {1188  if (confirmation !== "REPLACE_ALL") {1189    throw new Error("clearVaultEntries requires explicit confirmation");1190  }1191  if (!derivedKey) throw new Error("vault locked");1192  for (const entry of entries) {1193    if (!entry.deletedAt) {1194      entry.deletedAt = Date.now();1195      entry.modifiedAt = Date.now();1196    }1197  }1198  await persistEntries();1199}12001201export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {1202  if (!derivedKey) throw new Error("vault locked");12031204  const sanitized = sanitizeEntryDraft(entry);1205  const now = Date.now();1206  const nextEntry: VaultEntry = {1207    ...sanitized,1208    id: crypto.randomUUID(),1209    createdAt: now,1210    modifiedAt: now,1211    // Stamp passwordChangedAt at creation so age tracking is accurate from1212    // day one. Non-login entries carry the same stamp harmlessly.1213    passwordChangedAt: sanitized.password ? now : undefined,1214  };12151216  entries.push(nextEntry);1217  await persistEntries();12181219  // Fire-and-forget breach check (only for login entries if breach monitoring is enabled or not set)1220  if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {1221    checkBreach(nextEntry.password).then(async (count) => {1222      if (count > 0) {1223        const idx = entries.findIndex((e) => e.id === nextEntry.id);1224        if (idx !== -1) {1225          entries[idx] = { ...entries[idx], breach: count, modifiedAt: Date.now() };1226          await persistEntries();1227        }1228      }1229    });1230  }12311232  return nextEntry;1233}12341235export async function updateEntry(1236  id: string,1237  patch: Partial<VaultEntry>1238): Promise<void> {1239  if (!derivedKey) throw new Error("vault locked");12401241  const idx = entries.findIndex((entry) => entry.id === id);1242  if (idx === -1 || entries[idx].deletedAt) {1243    throw new Error("entry not found");1244  }12451246  const current = entries[idx];1247  const sanitizedPatch = sanitizeEntryPatch(patch);1248  // Refresh passwordChangedAt only when the password value actually changes —1249  // a metadata-only update (title, tags, etc.) must not reset the age clock1250  // that drives the Pro health rotation recommendation.1251  const passwordChanged =1252    "password" in patch &&1253    typeof sanitizedPatch.password === "string" &&1254    sanitizedPatch.password !== current.password;1255  entries[idx] = {1256    ...current,1257    ...sanitizedPatch,1258    modifiedAt: Date.now(),1259    ...(passwordChanged ? { passwordChangedAt: Date.now() } : {}),1260  };12611262  // A login entry must carry SOMETHING fillable — either a password or a1263  // passkey credential. An empty-password login with no passkey is dead1264  // state. Permit the password-clear when a passkey is attached (that's1265  // the legitimate "drop the password, keep the passkey" path).1266  if (1267    entries[idx].type === "login" &&1268    !entries[idx].password &&1269    !entries[idx].passkey1270  ) {1271    entries[idx] = current;1272    throw new Error("password or passkey required");1273  }12741275  // Card entries must retain their card number1276  if (entries[idx].type === "card" && !entries[idx].cardNumber) {1277    entries[idx] = current;1278    throw new Error("card number is required for card entries");1279  }12801281  await persistEntries();12821283  // Breach check when password changes: clear immediately so old breach doesn't linger,1284  // then async-check the new password and only re-set if it's also found.1285  if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {1286    entries[idx] = { ...entries[idx], breach: undefined };1287    await persistEntries();1288    const password = entries[idx].password;1289    if (password) {1290      checkBreach(password).then(async (count) => {1291        const i = entries.findIndex((e) => e.id === id);1292        if (i !== -1 && count > 0) {1293          entries[i] = { ...entries[i], breach: count, modifiedAt: Date.now() };1294          await persistEntries();1295        }1296      });1297    }1298  }1299}13001301export async function deleteEntry(id: string): Promise<void> {1302  if (!derivedKey) throw new Error("vault locked");13031304  const entry = entries.find((item) => item.id === id);1305  if (!entry || entry.deletedAt) {1306    throw new Error("entry not found");1307  }13081309  entry.deletedAt = Date.now();1310  entry.modifiedAt = Date.now();1311  await persistEntries();1312}13131314export function getDeletedEntries(): VaultEntry[] {1315  if (!derivedKey) return [];1316  return entries.filter((e) => !!e.deletedAt);1317}13181319export async function restoreEntry(id: string): Promise<void> {1320  if (!derivedKey) throw new Error("vault locked");1321  const entry = entries.find((e) => e.id === id && e.deletedAt);1322  if (!entry) throw new Error("deleted entry not found");1323  delete entry.deletedAt;1324  entry.modifiedAt = Date.now();1325  await persistEntries();1326  buildDomainIndexSync(entries);1327}13281329export async function purgeEntry(id: string): Promise<void> {1330  if (!derivedKey) throw new Error("vault locked");1331  const idx = entries.findIndex((e) => e.id === id && e.deletedAt);1332  if (idx === -1) throw new Error("deleted entry not found");1333  entries.splice(idx, 1);1334  await persistEntries();1335}13361337/** Permanently delete entries whose deletedAt is older than retentionMs. 0 = keep forever. */1338export async function purgeExpiredTrash(retentionMs: number): Promise<number> {1339  if (!derivedKey || retentionMs === 0) return 0;1340  const cutoff = Date.now() - retentionMs;1341  const before = entries.length;1342  entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));1343  const purged = before - entries.length;1344  if (purged > 0) await persistEntries();1345  return purged;1346}13471348export function queryDomain(domain: string): VaultEntry[] {1349  return domainIndex.get(domain) ?? [];1350}13511352export function getEntryById(id: string): VaultEntry | undefined {1353  return entries.find((entry) => entry.id === id && !entry.deletedAt);1354}13551356async function persistSlotA(1357  reason: VaultSnapshot["reason"] = "local_save",1358): Promise<StoredVault> {1359  if (!derivedKey) throw new Error("vault locked");13601361  const slotA = await loadSlot(SLOT_A);1362  if (!slotA) throw new Error("missing slot A");13631364  // Snapshot the about-to-be-overwritten state BEFORE we mutate disk. Failures1365  // are swallowed by takeVaultSnapshot — history must never block a save.1366  await takeVaultSnapshot(reason);13671368  const plaintext = encodePayload(entries, duressConfigured);1369  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext);13701371  // Preserve existing recovery escrow fields.1372  const nextSlotA: StoredVault = {1373    ...slotA,1374    nonce,1375    ciphertext,1376    tag,1377    // recovery_salt and recovery_wrapped_root_key are already set from loadSlot1378  };1379  await writeSlot(SLOT_A, nextSlotA);13801381  // When duress is not configured, keep slot B size-matched with slot A by1382  // regenerating its noise. When duress IS configured, leave slot B alone —1383  // we don't have the decoy key to re-encrypt it. This is a known trade-off.1384  if (!duressConfigured) {1385    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));1386  }13871388  return nextSlotA;1389}13901391async function persistSlotB(): Promise<void> {1392  if (!derivedKey) throw new Error("vault locked");13931394  const slotB = await loadSlot(SLOT_B);1395  if (!slotB) throw new Error("missing slot B");13961397  // Decoy plaintext always reports duressConfigured=false — the decoy user1398  // sees a clean slate.1399  const plaintext = encodePayload(entries, false);1400  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext);14011402  await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });1403}14041405async function persistEntries(1406  reason: VaultSnapshot["reason"] = "local_save",1407): Promise<void> {1408  if (!derivedKey) throw new Error("vault locked");14091410  if (vaultMode === "decoy") {1411    await persistSlotB();1412  } else {1413    await persistSlotA(reason);1414  }1415  buildDomainIndexSync(entries);1416}14171418function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {1419  if (!Array.isArray(values)) return undefined;1420  const seen = new Set<string>();1421  const cleaned: string[] = [];1422  for (const value of values) {1423    const trimmed = typeof value === "string" ? value.trim() : "";1424    if (!trimmed) continue;1425    const key = trimmed.toLowerCase();1426    if (seen.has(key)) continue;1427    seen.add(key);1428    cleaned.push(trimmed);1429  }1430  return cleaned.length > 0 ? cleaned : undefined;1431}14321433function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {1434  const title = entry.title.trim();1435  // Accept legacy `type:"passkey"` drafts but rewrite to "login" — the new1436  // model is "any entry, optionally with a passkey sub-object." Imports and1437  // any in-flight callers from before v2.11.0 keep working without throwing.1438  let type: VaultEntry["type"] = entry.type ?? "login";1439  if (type === "passkey") type = "login";14401441  if (!title) throw new Error("title is required");1442  // A login entry needs either a password or a passkey credential to be useful.1443  // Passkey-only entries (passkey present, no password) are valid.1444  if (type === "login" && !entry.password?.trim() && !entry.passkey) {1445    throw new Error("password or passkey required");1446  }1447  if (entry.passkey) {1448    const p = entry.passkey;1449    if (1450      !p.rpId ||1451      !p.credentialId ||1452      !p.publicKeyCose ||1453      !p.userHandle ||1454      !p.userName ||1455      (p.algorithm !== -7 && p.algorithm !== -8)1456    ) {1457      throw new Error("invalid passkey credential");1458    }1459  }1460  if (type === "card") {1461    if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {1462      throw new Error("cardholder name and card number are required");1463    }1464  }14651466  return {1467    type,1468    title,1469    username: type === "login" ? entry.username?.trim() ?? "" : undefined,1470    password: type === "login" ? entry.password : undefined,1471    url: type === "login" ? entry.url?.trim() ?? "" : undefined,1472    additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,1473    totp: type === "login" ? entry.totp?.trim() || undefined : undefined,1474    notes: entry.notes?.trim() || undefined,1475    breach: type === "login" ? entry.breach : undefined,1476    canary: type === "login" ? entry.canary : undefined,1477    tags: entry.tags,1478    passkey: entry.passkey,1479    cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,1480    cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,1481    expMonth: type === "card" ? entry.expMonth?.trim() : undefined,1482    expYear: type === "card" ? entry.expYear?.trim() : undefined,1483    cvc: type === "card" ? entry.cvc?.trim() : undefined,1484    cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,1485    network: type === "card" ? entry.network : undefined,1486    last4: type === "card" ? entry.last4?.trim() : undefined,1487  };1488}14891490function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {1491  const nextPatch: Partial<VaultEntry> = {};14921493  if ("type" in patch) {1494    nextPatch.type = patch.type;1495  }14961497  if ("title" in patch) {1498    const title = patch.title?.trim() ?? "";1499    if (!title) throw new Error("title is required");1500    nextPatch.title = title;1501  }15021503  if ("url" in patch) {1504    nextPatch.url = patch.url?.trim() ?? "";1505  }15061507  if ("additionalUrls" in patch) {1508    const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];1509    const seen = new Set<string>();1510    const cleaned: string[] = [];1511    for (const value of incoming) {1512      const trimmed = typeof value === "string" ? value.trim() : "";1513      if (!trimmed) continue;1514      const key = trimmed.toLowerCase();1515      if (seen.has(key)) continue;1516      seen.add(key);1517      cleaned.push(trimmed);1518    }1519    nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;1520  }15211522  if ("username" in patch) {1523    nextPatch.username = patch.username?.trim() ?? "";1524  }15251526  if ("password" in patch) {1527    const password = patch.password ?? "";1528    // Allow clearing a password (e.g. on passkey-only entries)1529    nextPatch.password = password || undefined;1530  }15311532  if ("totp" in patch) {1533    nextPatch.totp = patch.totp?.trim() || undefined;1534  }15351536  if ("notes" in patch) {1537    nextPatch.notes = patch.notes?.trim() || undefined;1538  }15391540  if ("breach" in patch) {1541    nextPatch.breach = patch.breach;1542  }15431544  if ("canary" in patch) {1545    nextPatch.canary = patch.canary;1546  }15471548  if ("passkey" in patch) {1549    // Passkey sub-object replaces all the legacy flat passkey fields. A1550    // patch with `passkey: undefined` removes the credential from the entry1551    // (used by "remove passkey" without deleting the whole entry).1552    nextPatch.passkey = patch.passkey;1553  }15541555  if ("tags" in patch) {1556    nextPatch.tags = patch.tags;1557  }15581559  if ("cardholderName" in patch) {1560    nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;1561  }1562  if ("cardNumber" in patch) {1563    const n = patch.cardNumber ?? "";1564    nextPatch.cardNumber = n || undefined;1565  }1566  if ("expMonth" in patch) {1567    nextPatch.expMonth = patch.expMonth?.trim() || undefined;1568  }1569  if ("expYear" in patch) {1570    nextPatch.expYear = patch.expYear?.trim() || undefined;1571  }1572  if ("cvc" in patch) {1573    nextPatch.cvc = patch.cvc?.trim() || undefined;1574  }1575  if ("cardNickname" in patch) {1576    nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;1577  }1578  if ("network" in patch) {1579    nextPatch.network = patch.network;1580  }1581  if ("last4" in patch) {1582    nextPatch.last4 = patch.last4?.trim() || undefined;1583  }15841585  return nextPatch;1586}15871588function normalizeEntry(entry: VaultEntry | LegacyVaultEntry): VaultEntry {1589  const createdAt = "createdAt" in entry ? entry.createdAt : entry.created;1590  const modifiedAt =1591    "modifiedAt" in entry ? entry.modifiedAt : entry.updated;15921593  const base: VaultEntry = {1594    id: entry.id,1595    type: "type" in entry ? entry.type : "login",1596    title: entry.title,1597    username: entry.username,1598    password: entry.password,1599    url: entry.url,1600    totp: entry.totp,1601    notes: entry.notes,1602    breach: entry.breach,1603    canary: "canary" in entry ? entry.canary : undefined,1604    passkey: "passkey" in entry ? entry.passkey : undefined,1605    createdAt,1606    modifiedAt,1607    deletedAt: entry.deletedAt,1608    tags: "tags" in entry ? entry.tags : undefined,1609    cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,1610    cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,1611    expMonth: "expMonth" in entry ? entry.expMonth : undefined,1612    expYear: "expYear" in entry ? entry.expYear : undefined,1613    cvc: "cvc" in entry ? entry.cvc : undefined,1614    cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,1615    network: "network" in entry ? entry.network : undefined,1616    last4: "last4" in entry ? entry.last4 : undefined,1617  };16181619  return migrateLegacyPasskey(base, entry);1620}16211622/**1623 * v2.11.0 read migration. Pre-v2.11.0 passkey entries used `type:"passkey"`1624 * with flat top-level fields (rpId, credentialId, etc.). This converts them1625 * to the new shape — `type:"login"` with a `passkey` sub-object — so all1626 * downstream consumers can rely on the new model. The result is rewritten1627 * to disk on next vault save (hasLegacyShape detects the un-migrated case).1628 */1629function migrateLegacyPasskey(1630  base: VaultEntry,1631  raw: VaultEntry | LegacyVaultEntry1632): VaultEntry {1633  if (base.passkey) return base;1634  const flat = raw as Partial<VaultEntry>;1635  const isPasskeyType = base.type === "passkey";1636  const hasFlatPasskeyFields =1637    typeof flat.rpId === "string" &&1638    typeof flat.credentialId === "string" &&1639    typeof flat.publicKeyCose === "string" &&1640    typeof flat.userHandle === "string" &&1641    typeof flat.userName === "string";1642  if (!isPasskeyType && !hasFlatPasskeyFields) return base;1643  if (!hasFlatPasskeyFields) return base;16441645  const algorithm: -7 | -8 = flat.algorithm === -8 ? -8 : -7;1646  base.passkey = {1647    rpId: flat.rpId!,1648    rpName: flat.rpName ?? flat.rpId!,1649    credentialId: flat.credentialId!,1650    publicKeyCose: flat.publicKeyCose!,1651    privateKeyJwk: flat.privateKeyJwk,1652    userHandle: flat.userHandle!,1653    userName: flat.userName!,1654    userDisplayName: flat.userDisplayName ?? flat.userName!,1655    algorithm,1656    signCount: flat.signCount ?? 0,1657    aaguid: flat.aaguid ?? "",1658    backupEligible: flat.backupEligible === true,1659    backupState: flat.backupState === true,1660    lastUsedAt: flat.lastUsedAt,1661    browser: flat.browser,1662    transports: flat.transports,1663    createdAt: base.createdAt,1664  };1665  // Promote to "login" so the unified Entry view renders. Username gets1666  // populated from the passkey's userName so the entry is searchable in the1667  // existing autofill flow without a separate code path.1668  if (isPasskeyType) base.type = "login";1669  if (!base.username) base.username = flat.userName;1670  if (!base.url) base.url = `https://${flat.rpId}`;1671  return base;1672}167316741675// ---------------------------------------------------------------------------1676// Deduplication1677// ---------------------------------------------------------------------------16781679function entryDupeKey(e: VaultEntry): string {1680  if (e.type === "note") return `note|${e.title.toLowerCase()}`;1681  // Passkey-bearing entries dedupe by the credential's RP + user. Two logins1682  // on different sites that happen to share a username are still distinct;1683  // two passkey credentials for the same RP+user are duplicates regardless1684  // of any login fields they may also carry.1685  if (e.passkey) {1686    return `passkey|${e.passkey.rpId.toLowerCase()}|${e.passkey.userName.toLowerCase()}`;1687  }1688  return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;1689}16901691/** Returns the number of duplicate entries (those that would be removed). */1692export function countDuplicates(): number {1693  const best = new Map<string, VaultEntry>();1694  let dupeCount = 0;1695  for (const e of entries.filter((e) => !e.deletedAt)) {1696    const key = entryDupeKey(e);1697    const existing = best.get(key);1698    if (!existing) {1699      best.set(key, e);1700    } else {1701      dupeCount++;1702      // Keep the more recently modified one in the map1703      if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {1704        best.set(key, e);1705      }1706    }1707  }1708  return dupeCount;1709}17101711/**1712 * Soft-deletes duplicate entries, keeping the most recently modified copy of1713 * each group. Returns the number of entries moved to trash.1714 */1715export async function deduplicateEntries(): Promise<number> {1716  if (!derivedKey) throw new Error("vault locked");1717  // Dedup reshapes slot B permanently under the decoy key, which is1718  // forensically distinguishable from a freshly-seeded decoy vault. Refuse.1719  if (vaultMode === "decoy") {1720    throw new Error("deduplicate disabled in decoy mode");1721  }17221723  const best = new Map<string, VaultEntry>();1724  for (const e of entries.filter((en) => !en.deletedAt)) {1725    const key = entryDupeKey(e);1726    const existing = best.get(key);1727    if (!existing) {1728      best.set(key, e);1729    } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {1730      best.set(key, e);1731    }1732  }17331734  const keepIds = new Set(Array.from(best.values()).map((e) => e.id));1735  const now = Date.now();1736  let removed = 0;1737  entries = entries.map((e) => {1738    if (!e.deletedAt && !keepIds.has(e.id)) {1739      removed++;1740      return { ...e, deletedAt: now };1741    }1742    return e;1743  });17441745  if (removed > 0) await persistEntries();1746  return removed;1747}17481749// ---------------------------------------------------------------------------1750// Vault history — snapshot BEFORE every vault write so the saved blob is1751// what is about to be lost, not what was just written. Capped at 10. The1752// stored blobs are AES-256-GCM ciphertext under the master password, so1753// history adds zero security surface.1754// ---------------------------------------------------------------------------17551756const HISTORY_KEY = "peach_vault_history";1757const HISTORY_MAX = 10;17581759/**1760 * Snapshot the CURRENT on-disk vault state into history. Call this BEFORE1761 * overwriting peach_vault_a so the saved blob captures the about-to-be-lost1762 * state. Identical-to-most-recent blobs are skipped to avoid filling history1763 * with no-op writes.1764 */1765export async function takeVaultSnapshot(1766  reason: VaultSnapshot["reason"],1767): Promise<void> {1768  try {1769    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);1770    const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];1771    const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];17721773    // Nothing to snapshot if the real slot doesn't exist yet (fresh install,1774    // pre-createVault). createVault skips snapshots intentionally — there is1775    // no prior state to preserve.1776    if (!slotA) return;17771778    const vault_a = JSON.stringify(slotA);1779    const vault_b = JSON.stringify(slotB ?? slotA);17801781    // Best-effort entry count: only meaningful when the in-memory state is1782    // unlocked AND in real mode. Decoy mode would leak the decoy entry1783    // count; locked mode has no entries to count. Both fall through to null.1784    let entryCount: number | null = null;1785    if (derivedKey && vaultMode === "real") {1786      try {1787        entryCount = entries.filter((e) => !e.deletedAt).length;1788      } catch {1789        entryCount = null;1790      }1791    }17921793    const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];1794    const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)1795      ? existingRaw1796      : { snapshots: [] };17971798    // Deduplication: if the most recent snapshot has byte-identical blobs,1799    // skip — saves the same vault N times in a row would otherwise burn the1800    // entire history window with no recovery value.1801    const latest = history.snapshots[0];1802    if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {1803      return;1804    }18051806    const snapshot: VaultSnapshot = {1807      id: crypto.randomUUID(),1808      savedAt: Date.now(),1809      reason,1810      vault_a,1811      vault_b,1812      entryCount,1813    };18141815    history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);1816    await chrome.storage.local.set({ [HISTORY_KEY]: history });1817  } catch {1818    // Non-fatal — history must never block a save. A failed snapshot just1819    // means the user loses one rung of the safety ladder for this write.1820  }1821}18221823/** Wipe all vault history. Called by Panic / DESTROY_VAULT. */1824export async function clearVaultHistory(): Promise<void> {1825  try {1826    await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });1827  } catch {1828    // Non-fatal — DESTROY_VAULT also runs storage.local.clear().1829  }1830}18311832/** Read all snapshots, newest first, for the Settings vault history view. */1833export async function getVaultHistory(): Promise<VaultSnapshot[]> {1834  const raw = await chrome.storage.local.get(HISTORY_KEY);1835  const history = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];1836  if (!history || !Array.isArray(history.snapshots)) return [];1837  return history.snapshots;1838}18391840/**1841 * Replace the on-disk vault with the chosen snapshot's blobs and lock the1842 * vault. The current state is itself snapshotted with reason 'restore' first1843 * so the restore is reversible. After this returns, the user must unlock1844 * with the password that matches the restored blob.1845 */1846export async function restoreVaultSnapshot(1847  snapshotId: string,1848): Promise<{ ok: true } | { ok: false; error: string }> {1849  const history = await getVaultHistory();1850  const snapshot = history.find((s) => s.id === snapshotId);1851  if (!snapshot) return { ok: false, error: "snapshot_not_found" };18521853  // Snapshot the about-to-be-replaced current state so the restore is1854  // reversible. takeVaultSnapshot is no-op when the most recent entry is1855  // byte-identical, so a restore-of-a-restore stays clean.1856  await takeVaultSnapshot("restore");18571858  let restoredA: StoredVault;1859  let restoredB: StoredVault;1860  try {1861    restoredA = JSON.parse(snapshot.vault_a) as StoredVault;1862    restoredB = JSON.parse(snapshot.vault_b) as StoredVault;1863  } catch {1864    return { ok: false, error: "snapshot_corrupt" };1865  }18661867  await writeSlot(SLOT_A, restoredA);1868  await writeSlot(SLOT_B, restoredB);18691870  // Lock so the user must prove they can decrypt the restored blob. If they1871  // restored a pre-password-change snapshot they discover it immediately at1872  // the lock screen rather than silently holding an inaccessible vault.1873  lock();18741875  return { ok: true };1876}18771878/**1879 * Change the master password. Re-encrypts slot A with a fresh salt + new1880 * derived key. Slot B (duress or noise) is left untouched when duress is1881 * configured — it uses an independent key derived from the duress password —1882 * and regenerated as noise when duress is not configured.1883 */1884export async function changePassword(1885  currentPassword: string,1886  newPassword: string1887): Promise<boolean> {1888  if (!derivedKey || vaultMode !== "real") return false;18891890  // Verify current password before allowing any change1891  const valid = await verifyMainPassword(currentPassword);1892  if (!valid) return false;18931894  const slotA = await loadSlot(SLOT_A);1895  if (!slotA) return false;18961897  // Derive fresh key from new password + new random salt1898  const newSalt = generateSalt();1899  const newKey = await deriveKey(newPassword, newSalt);19001901  // Re-encrypt the in-memory entries with the new key1902  const plaintext = encodePayload(entries, duressConfigured);1903  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext);19041905  const freshSlotA: StoredVault = {1906    ...slotA,1907    salt: hex(newSalt),1908    nonce,1909    ciphertext,1910    tag,1911  };1912  // Snapshot the OLD-key blob before overwriting it. If the user later1913  // restores from this snapshot they will need the OLD password — the1914  // post-restore lock surfaces that immediately.1915  await takeVaultSnapshot("local_save");1916  await writeSlot(SLOT_A, freshSlotA);19171918  // Swap the in-memory key synchronously before any further await. If we1919  // threw between the Slot A write and this swap, the next persistEntries()1920  // would overwrite Slot A with old-key ciphertext, locking the user out.1921  zeroKey(derivedKey);1922  derivedKey = newKey;19231924  // Re-wrap the root key under the new derived key so recovery words1925  // continue to work after the password change.1926  await rewrapRootKeyForPassword(newKey, newSalt);19271928  // Regenerate noise for slot B when duress is not in use. Runs after the1929  // key swap so a failure here is a disposable noise regeneration, not a1930  // lockout.1931  if (!duressConfigured) {1932    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));1933  }19341935  return true;1936}