vault.ts

66.9 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  rawRootKey: string; // hex of the plaintext root key — caller stores in rootKey223  recoverySalt: string;224  wrappedRootKey: string;225  wrappedNonce: string;226  wrappedTag: string;227}> {228  const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));229230  // Derive the recovery key from the BIP39 words encoding of the root key.231  const { rootKeyToWords, wordsToRootKeyMaterial, deriveRecoveryKey } =232    await import("../shared/recovery-words");233  const words = await rootKeyToWords(rootKeyBytes);234  const wordMaterial = await wordsToRootKeyMaterial(words);235  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));236  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);237238  // Wrap the root key with the recovery key using AES-256-GCM directly.239  // We hex-encode rootKeyBytes so the plaintext is always valid UTF-8.240  const nonce = crypto.getRandomValues(new Uint8Array(12));241  const encoded = new TextEncoder().encode(hex(rootKeyBytes));242  const raw = await crypto.subtle.encrypt(243    {244      name: "AES-GCM",245      iv: nonce,246      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,247      tagLength: 128,248    },249    recoveryKey,250    encoded251  );252  // WebCrypto returns ciphertext || auth tag concatenated; split them.253  const rawU8 = new Uint8Array(raw);254  const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));255  const tag = hex(rawU8.slice(rawU8.length - 16));256257  return {258    rawRootKey: hex(rootKeyBytes),259    recoverySalt: hex(recoverySalt),260    wrappedRootKey: ciphertext,261    wrappedNonce: hex(nonce),262    wrappedTag: tag,263  };264}265266/**267 * Unwrap the root key using recovery words. Called during recovery flow when268 * the user provides their 12-word phrase and a new password.269 * Exported for use by the RECOVER_WITH_WORDS message handler.270 */271export async function unwrapRootKeyForRecovery(272  wrappedRootKey: string,273  wrappedNonce: string,274  wrappedTag: string,275  recoverySaltHex: string,276  words: string[]277): Promise<void> {278  const { wordsToRootKeyMaterial, deriveRecoveryKey } = await import(279    "../shared/recovery-words"280  );281  const wordMaterial = await wordsToRootKeyMaterial(words);282  const recoverySalt = unhex(recoverySaltHex);283  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);284285  // Decrypt and cache the root key. The root key bytes were hex-encoded before286  // encryption so the ciphertext is valid UTF-8. We inline the AES-GCM decrypt287  // here to avoid passing a CryptoKey to the string-based encrypt/decrypt helpers.288  const combined = unhex(wrappedRootKey + wrappedNonce + wrappedTag);289  const nonceU8 = combined.slice(0, 12);290  const ciphertext = combined.slice(12, combined.length - 16);291  const storedTag = combined.slice(combined.length - 16);292  const raw = await crypto.subtle.decrypt(293    { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },294    recoveryKey,295    new Uint8Array([...ciphertext, ...storedTag])296  );297  const decryptedHex = new TextDecoder().decode(raw);298  rootKey = unhex(decryptedHex);299}300301/**302 * Re-wrap the cached root key under a new derived key (from the user's new303 * password). Called after password change and after recovery re-key so the304 * same recovery words continue to work with the updated password.305 */306export async function rewrapRootKeyForPassword(307  newDerivedKey: Uint8Array,308  _newSalt: Uint8Array309): Promise<void> {310  if (!rootKey) throw new Error("root key not set");311  const { nonce, ciphertext, tag } = await encrypt(312    newDerivedKey,313    hex(rootKey)314  );315  const slotA = await loadSlot(SLOT_A);316  if (!slotA) throw new Error("missing slot A");317  await writeSlot(SLOT_A, {318    ...slotA,319    recovery_wrapped_root_key: ciphertext,320    recovery_nonce: nonce,321    recovery_tag: tag,322    // recovery_salt does NOT change when password changes — the recovery323    // words always derive the same key; only the wrapping key changes.324  });325}326327/**328 * Change the vault encryption to a new derived key (already derived from329 * the user's new password). Used by RECOVER_WITH_WORDS and changePassword.330 * Caller is responsible for key swap and snapshot.331 */332async function reencryptVaultForNewKey(333  newKey: Uint8Array,334  slotA: StoredVault335): Promise<void> {336  const plaintext = encodePayload(entries, duressConfigured);337  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext);338  await writeSlot(SLOT_A, {339    ...slotA,340    nonce,341    ciphertext,342    tag,343  });344}345346/**347 * Full password change with an already-derived key (used after recovery).348 * Unlike changePassword(), this skips re-verification of current password349 * since recovery flow has already validated the user's identity via words.350 */351export async function changePasswordWithNewKey(352  newSalt: Uint8Array,353  newKey: Uint8Array354): Promise<void> {355  const slotA = await loadSlot(SLOT_A);356  if (!slotA) throw new Error("missing slot A");357  await reencryptVaultForNewKey(newKey, slotA);358  zeroKey(derivedKey!);359  derivedKey = newKey;360  if (!duressConfigured) {361    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));362  }363}364365// ---------------------------------------------------------------------------366// Salt generation --- exported so the RECOVER_WITH_WORDS handler can derive367// a new key after password reset without re-importing the crypto module.368// ---------------------------------------------------------------------------369370export { deriveKey, generateSalt };371372export async function loadSlotA(): Promise<StoredVault | null> {373  return loadSlot(SLOT_A);374}375376/**377 * Re-derive the session root key from the already-derived AES key (keyA from378 * unlock) and the recovery salt stored in slot A. This is the inverse of379 * generateAndWrapRootKey() — both operations use the same HKDF with the same380 * salt and info string, so they cancel out.381 *382 * The derivedKey and rootKey are related by:383 *   derivedKey = Argon2id(password, slotA.salt)   → AES key for vault payload384 *   rootKey    = HKDF-SHA256(recovery_words, recovery_salt)  → wrapped by HKDF385 *386 * Since we only store the wrapped root key and the recovery salt, we can387 * only re-derive rootKey during an active (unlocked) session where we have388 * the derivedKey already. On lock, rootKey is zeroed.389 *390 * For pre-v2.12 vaults that have no recovery_salt, this returns null and391 * the caller must invoke migrateToRecovery() to generate the recovery escrow.392 */393async function deriveRootKeyFromDerivedKey(394  _derivedKey: Uint8Array,395  _recoverySaltHex: string396): Promise<Uint8Array | null> {397  // The root key is stored wrapped under the recovery key derived from the398  // 12-word phrase. It cannot be re-derived from derivedKey alone — that would399  // require knowing the original recovery words. The in-memory rootKey is set400  // during unlock if recovery data is present.401  // This function exists as a potential future path if we ever store an402  // additional derived-key → root-key relationship. Currently rootKey is403  // cached directly during unlock.404  return null;405}406407/**408 * For vaults created before v2.12 (no recovery_salt/recovery_wrapped_root_key),409 * generate the root key, wrap it under the recovery words, and persist the410 * recovery escrow into slot A. The caller must show the recovery words to the411 * user before calling this — once called, those words are the vault's recovery412 * path. This runs once, on the first unlock of an upgraded vault.413 */414export async function migrateToRecovery(): Promise<void> {415  if (!derivedKey || vaultMode !== "real") {416    throw new Error("vault must be unlocked in real mode");417  }418  const slotA = await loadSlot(SLOT_A);419  if (!slotA) throw new Error("missing slot A");420  if (slotA.recovery_salt && slotA.recovery_wrapped_root_key) return; // already done421422  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =423    await generateAndWrapRootKey();424425  rootKey = unhex(rawRootKey);426427  const nextSlotA: StoredVault = {428    ...slotA,429    recovery_salt: recoverySalt,430    recovery_wrapped_root_key: wrappedRootKey,431    recovery_nonce: wrappedNonce,432    recovery_tag: wrappedTag,433  };434  await writeSlot(SLOT_A, nextSlotA);435}436437/**438 * Returns the 12 recovery words for the current session's root key.439 * Must be called while the vault is unlocked. Throws if recovery has not440 * been set up (pre-v2.12 vault that hasn't migrated yet).441 */442export async function getRecoveryWords(): Promise<string[]> {443  if (!rootKey) {444    throw new Error("recovery not set up — vault may need migration");445  }446  const { rootKeyToWords } = await import("../shared/recovery-words");447  return rootKeyToWords(rootKey);448}449450async function loadSlot(key: string): Promise<StoredVault | null> {451  const result = await chrome.storage.local.get(key);452  return (result as Record<string, StoredVault | undefined>)[key] ?? null;453}454455async function writeSlot(key: string, vault: StoredVault): Promise<void> {456  try {457    await chrome.storage.local.set({ [key]: vault });458  } catch (err) {459    throw mapStorageError(err);460  }461}462463/**464 * One-shot migration from the pre-A-2 schema (peach_vault + peach_decoy_vault465 * + peach_duress flag) to the slot-neutral schema (peach_vault_a +466 * peach_vault_b). Runs at most once per session; safe to call repeatedly.467 */468async function ensureMigrated(): Promise<void> {469  if (migrationRan) return;470  migrationRan = true;471472  const keys = [LEGACY_MAIN, LEGACY_DECOY, LEGACY_DURESS_FLAG, SLOT_A, SLOT_B];473  const raw = await chrome.storage.local.get(keys);474  const slotAExists = raw[SLOT_A] !== undefined;475  const slotBExists = raw[SLOT_B] !== undefined;476  const legacyMain = raw[LEGACY_MAIN] as StoredVault | undefined;477  const legacyDecoy = raw[LEGACY_DECOY] as StoredVault | undefined;478479  // Fresh install with nothing in storage — nothing to do; createVault() sets up both slots.480  if (!slotAExists && !legacyMain) return;481482  // Already migrated.483  if (slotAExists && slotBExists && !legacyMain && !legacyDecoy) return;484485  if (legacyMain && !slotAExists) {486    await writeSlot(SLOT_A, legacyMain);487  }488489  // If slot B isn't set, populate it: use legacy decoy when present, else noise.490  if (!slotBExists) {491    const target = (legacyMain ?? raw[SLOT_A]) as StoredVault | undefined;492    if (legacyDecoy) {493      await writeSlot(SLOT_B, legacyDecoy);494    } else if (target) {495      await writeSlot(SLOT_B, generateNoiseBlob(target.ciphertext.length / 2));496    }497  }498499  const toRemove: string[] = [];500  if (legacyMain) toRemove.push(LEGACY_MAIN);501  if (legacyDecoy) toRemove.push(LEGACY_DECOY);502  if (raw[LEGACY_DURESS_FLAG] !== undefined) toRemove.push(LEGACY_DURESS_FLAG);503  if (toRemove.length > 0) {504    await chrome.storage.local.remove(toRemove);505  }506}507508// ---------------------------------------------------------------------------509// Padding + noise helpers510// ---------------------------------------------------------------------------511512/**513 * Pads the plaintext string with trailing spaces so that the encoded byte514 * length is a multiple of PAD_BLOCK. JSON.parse tolerates trailing515 * whitespace after a complete document, so the padding is transparent on516 * decode. Ciphertext length equals plaintext length plus a 16-byte tag.517 */518function padPlaintext(json: string): string {519  const encoded = new TextEncoder().encode(json);520  const target = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);521  const padLen = target - encoded.length;522  return json + " ".repeat(padLen);523}524525/**526 * Produces a StoredVault-shaped record filled with CSPRNG bytes. The527 * ciphertext length matches the given byte count. Because GCM ciphertext is528 * pseudo-random, this blob is indistinguishable at rest from a real529 * encrypted vault without the key.530 *531 * crypto.getRandomValues() caps each call at 65536 bytes (the Web Crypto532 * spec hard limit). Chunk the fill so vaults larger than that — common once533 * the user has dozens of entries or any passkey — don't throw.534 */535const CSPRNG_CHUNK = 65_536;536537function fillRandom(buf: Uint8Array): Uint8Array {538  for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {539    const end = Math.min(offset + CSPRNG_CHUNK, buf.length);540    const chunk = new Uint8Array(end - offset);541    crypto.getRandomValues(chunk);542    buf.set(chunk, offset);543  }544  return buf;545}546547function generateNoiseBlob(ciphertextBytes: number): StoredVault {548  const salt = crypto.getRandomValues(new Uint8Array(16));549  const nonce = crypto.getRandomValues(new Uint8Array(12));550  const cipher = fillRandom(new Uint8Array(ciphertextBytes));551  const tag = crypto.getRandomValues(new Uint8Array(16));552  return {553    version: 1,554    salt: hex(salt),555    nonce: hex(nonce),556    ciphertext: hex(cipher),557    tag: hex(tag),558  };559}560561// ---------------------------------------------------------------------------562// Encrypted plaintext envelope563// ---------------------------------------------------------------------------564565type VaultPayload = {566  entries: VaultEntry[];567  duressConfigured?: boolean;568};569570type DecryptedPayload = {571  entries: VaultEntry[];572  duressConfigured: boolean;573  /**574   * True when at least one entry in the on-disk payload had a legacy shape575   * (pre-v2.11.0 passkey type/flat fields, or pre-A-2 created/updated keys)576   * and got rewritten by normalizeEntry. The unlock path uses this to577   * persist the new shape immediately — without it, the migration would578   * re-run on every unlock and old shape never disappears from disk.579   */580  migratedFromLegacy: boolean;581};582583function encodePayload(entries: VaultEntry[], duress: boolean): string {584  const envelope: VaultPayload = { entries, duressConfigured: duress };585  return padPlaintext(JSON.stringify(envelope));586}587588function rawNeedsMigration(raw: VaultEntry | LegacyVaultEntry): boolean {589  if ("created" in raw || "updated" in raw) return true;590  const flat = raw as Partial<VaultEntry>;591  if (flat.type === "passkey") return true;592  // Flat rpId without a passkey sub-object means pre-v2.11.0 schema.593  if (flat.rpId !== undefined && flat.passkey === undefined) return true;594  return false;595}596597function decodePayload(plain: string): DecryptedPayload {598  const parsed = JSON.parse(plain) as599    | Array<VaultEntry | LegacyVaultEntry>600    | VaultPayload;601602  const rawEntries = Array.isArray(parsed) ? parsed : parsed.entries ?? [];603  const flatMigrationNeeded = rawEntries.some(rawNeedsMigration);604605  const normalized = rawEntries.map(normalizeEntry);606  const { merged } = mergePasskeyOnlyIntoLogins(normalized);607608  if (Array.isArray(parsed)) {609    return {610      entries: normalized,611      duressConfigured: false,612      migratedFromLegacy: true, // pre-A-2 array shape always needs save613    };614  }615616  return {617    entries: normalized,618    duressConfigured: parsed.duressConfigured === true,619    migratedFromLegacy: flatMigrationNeeded || merged,620  };621}622623/**624 * One-time consolidation pass run alongside the legacy passkey migration.625 *626 * Pre-v2.11.0 the Chrome passkey path always created a fresh `type:"passkey"`627 * entry per registration — so users who tested registration multiple times628 * accumulated several passkey-bearing entries for the same RP, and the629 * migration to the unified shape carried that duplication forward. This630 * pass collapses the duplicates:631 *632 *   1. Group passkey-bearing (and not deleted) entries by `passkey.rpId`.633 *   2. Within each group, the most recently-active credential wins (prefer634 *      lastUsedAt, fall back to passkey.createdAt, fall back to modifiedAt).635 *   3. If a NON-passkey login entry exists for that RP (matched by url or636 *      additionalUrls hostname), attach the winning passkey to it and637 *      soft-delete every passkey-bearing entry in the group.638 *   4. Otherwise, soft-delete every loser in the group, keeping the winner639 *      as a passkey-only entry.640 *641 * Soft delete (deletedAt) rather than splice — the trash flow keeps the642 * record around for retention and the user can restore if the heuristic643 * picked wrong. The `merged` flag goes back to decodePayload so the644 * unlock path persists the consolidated shape immediately.645 */646function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {647  let merged = false;648  const now = Date.now();649650  const candidates = entries.filter((e) => !e.deletedAt && e.passkey);651  const byRpId = new Map<string, VaultEntry[]>();652  for (const e of candidates) {653    const rpId = e.passkey!.rpId;654    const list = byRpId.get(rpId);655    if (list) list.push(e);656    else byRpId.set(rpId, [e]);657  }658659  for (const [rpId, group] of byRpId) {660    if (group.length === 0) continue;661    group.sort((a, b) => {662      const aT =663        a.passkey!.lastUsedAt ?? a.passkey!.createdAt ?? a.modifiedAt ?? a.createdAt;664      const bT =665        b.passkey!.lastUsedAt ?? b.passkey!.createdAt ?? b.modifiedAt ?? b.createdAt;666      return bT - aT;667    });668    const winner = group[0]!;669670    // Look for a NON-passkey login entry matching this RP. Use the URL671    // hostname rather than a substring search so a "login.foo.com" entry672    // doesn't accidentally absorb a passkey for "foo.com".673    const loginTarget = entries.find((e) => {674      if (e.deletedAt || e.passkey || e.type !== "login") return false;675      if (e.url && extractDomain(e.url) === rpId) return true;676      for (const extra of e.additionalUrls ?? []) {677        if (extractDomain(extra) === rpId) return true;678      }679      return false;680    });681682    if (loginTarget) {683      loginTarget.passkey = winner.passkey;684      loginTarget.modifiedAt = now;685      for (const dup of group) {686        if (!dup.deletedAt) {687          dup.deletedAt = now;688          dup.modifiedAt = now;689        }690      }691      merged = true;692    } else if (group.length > 1) {693      for (let i = 1; i < group.length; i += 1) {694        const dup = group[i]!;695        if (!dup.deletedAt) {696          dup.deletedAt = now;697          dup.modifiedAt = now;698        }699      }700      merged = true;701    }702  }703704  return { merged };705}706707async function tryDecryptSlot(708  vault: StoredVault,709  key: Uint8Array710): Promise<DecryptedPayload | null> {711  try {712    const plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag);713    return decodePayload(plain);714  } catch {715    return null;716  }717}718719// ---------------------------------------------------------------------------720// Core operations721// ---------------------------------------------------------------------------722723function buildDomainIndexSync(all: VaultEntry[]): void {724  domainIndex = new Map();725726  for (const entry of all) {727    if (entry.deletedAt) continue;728    if (entry.type === "note" || entry.type === "card") continue;729730    // An entry can match multiple sites via `additionalUrls`. Index each731    // hostname so `queryDomain` returns the entry regardless of which alias732    // the user is currently visiting. Dedupe per-entry so a single entry733    // never appears twice in one bucket.734    const domains = new Set<string>();735    const primary = extractDomain(entry.url ?? "");736    if (primary) domains.add(primary);737    for (const extra of entry.additionalUrls ?? []) {738      const d = extractDomain(extra);739      if (d) domains.add(d);740    }741    if (domains.size === 0) continue;742743    for (const domain of domains) {744      const bucket = domainIndex.get(domain) ?? [];745      bucket.push(entry);746      domainIndex.set(domain, bucket);747    }748  }749}750751export async function createVault(password: string): Promise<void> {752  await ensureMigrated();753754  const salt = generateSalt();755  derivedKey = await deriveKey(password, salt);756  entries = [];757  vaultMode = "real";758  duressConfigured = false;759  buildDomainIndexSync(entries);760761  // Generate and wrap the root key for recovery word escrow.762  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =763    await generateAndWrapRootKey();764  rootKey = unhex(rawRootKey);765766  const plaintext = encodePayload(entries, duressConfigured);767  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext);768769  const slotA: StoredVault = {770    version: 1,771    salt: hex(salt),772    nonce,773    ciphertext,774    tag,775    recovery_salt: recoverySalt,776    recovery_wrapped_root_key: wrappedRootKey,777    recovery_nonce: wrappedNonce,778    recovery_tag: wrappedTag,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 ("email" in patch) {1527    nextPatch.email = patch.email?.trim() || undefined;1528  }15291530  if ("password" in patch) {1531    const password = patch.password ?? "";1532    // Allow clearing a password (e.g. on passkey-only entries)1533    nextPatch.password = password || undefined;1534  }15351536  if ("totp" in patch) {1537    nextPatch.totp = patch.totp?.trim() || undefined;1538  }15391540  if ("notes" in patch) {1541    nextPatch.notes = patch.notes?.trim() || undefined;1542  }15431544  if ("breach" in patch) {1545    nextPatch.breach = patch.breach;1546  }15471548  if ("canary" in patch) {1549    nextPatch.canary = patch.canary;1550  }15511552  if ("passkey" in patch) {1553    // Passkey sub-object replaces all the legacy flat passkey fields. A1554    // patch with `passkey: undefined` removes the credential from the entry1555    // (used by "remove passkey" without deleting the whole entry).1556    nextPatch.passkey = patch.passkey;1557  }15581559  if ("tags" in patch) {1560    nextPatch.tags = patch.tags;1561  }15621563  if ("cardholderName" in patch) {1564    nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;1565  }1566  if ("cardNumber" in patch) {1567    const n = patch.cardNumber ?? "";1568    nextPatch.cardNumber = n || undefined;1569  }1570  if ("expMonth" in patch) {1571    nextPatch.expMonth = patch.expMonth?.trim() || undefined;1572  }1573  if ("expYear" in patch) {1574    nextPatch.expYear = patch.expYear?.trim() || undefined;1575  }1576  if ("cvc" in patch) {1577    nextPatch.cvc = patch.cvc?.trim() || undefined;1578  }1579  if ("cardNickname" in patch) {1580    nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;1581  }1582  if ("network" in patch) {1583    nextPatch.network = patch.network;1584  }1585  if ("last4" in patch) {1586    nextPatch.last4 = patch.last4?.trim() || undefined;1587  }15881589  return nextPatch;1590}15911592function normalizeEntry(entry: VaultEntry | LegacyVaultEntry): VaultEntry {1593  const createdAt = "createdAt" in entry ? entry.createdAt : entry.created;1594  const modifiedAt =1595    "modifiedAt" in entry ? entry.modifiedAt : entry.updated;15961597  const base: VaultEntry = {1598    id: entry.id,1599    type: "type" in entry ? entry.type : "login",1600    title: entry.title,1601    username: entry.username,1602    password: entry.password,1603    url: entry.url,1604    totp: entry.totp,1605    notes: entry.notes,1606    breach: entry.breach,1607    canary: "canary" in entry ? entry.canary : undefined,1608    passkey: "passkey" in entry ? entry.passkey : undefined,1609    createdAt,1610    modifiedAt,1611    deletedAt: entry.deletedAt,1612    tags: "tags" in entry ? entry.tags : undefined,1613    cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,1614    cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,1615    expMonth: "expMonth" in entry ? entry.expMonth : undefined,1616    expYear: "expYear" in entry ? entry.expYear : undefined,1617    cvc: "cvc" in entry ? entry.cvc : undefined,1618    cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,1619    network: "network" in entry ? entry.network : undefined,1620    last4: "last4" in entry ? entry.last4 : undefined,1621  };16221623  return migrateLegacyPasskey(base, entry);1624}16251626/**1627 * v2.11.0 read migration. Pre-v2.11.0 passkey entries used `type:"passkey"`1628 * with flat top-level fields (rpId, credentialId, etc.). This converts them1629 * to the new shape — `type:"login"` with a `passkey` sub-object — so all1630 * downstream consumers can rely on the new model. The result is rewritten1631 * to disk on next vault save (hasLegacyShape detects the un-migrated case).1632 */1633function migrateLegacyPasskey(1634  base: VaultEntry,1635  raw: VaultEntry | LegacyVaultEntry1636): VaultEntry {1637  if (base.passkey) return base;1638  const flat = raw as Partial<VaultEntry>;1639  const isPasskeyType = base.type === "passkey";1640  const hasFlatPasskeyFields =1641    typeof flat.rpId === "string" &&1642    typeof flat.credentialId === "string" &&1643    typeof flat.publicKeyCose === "string" &&1644    typeof flat.userHandle === "string" &&1645    typeof flat.userName === "string";1646  if (!isPasskeyType && !hasFlatPasskeyFields) return base;1647  if (!hasFlatPasskeyFields) return base;16481649  const algorithm: -7 | -8 = flat.algorithm === -8 ? -8 : -7;1650  base.passkey = {1651    rpId: flat.rpId!,1652    rpName: flat.rpName ?? flat.rpId!,1653    credentialId: flat.credentialId!,1654    publicKeyCose: flat.publicKeyCose!,1655    privateKeyJwk: flat.privateKeyJwk,1656    userHandle: flat.userHandle!,1657    userName: flat.userName!,1658    userDisplayName: flat.userDisplayName ?? flat.userName!,1659    algorithm,1660    signCount: flat.signCount ?? 0,1661    aaguid: flat.aaguid ?? "",1662    backupEligible: flat.backupEligible === true,1663    backupState: flat.backupState === true,1664    lastUsedAt: flat.lastUsedAt,1665    browser: flat.browser,1666    transports: flat.transports,1667    createdAt: base.createdAt,1668  };1669  // Promote to "login" so the unified Entry view renders. Username gets1670  // populated from the passkey's userName so the entry is searchable in the1671  // existing autofill flow without a separate code path.1672  if (isPasskeyType) base.type = "login";1673  if (!base.username) base.username = flat.userName;1674  if (!base.url) base.url = `https://${flat.rpId}`;1675  return base;1676}167716781679// ---------------------------------------------------------------------------1680// Deduplication1681// ---------------------------------------------------------------------------16821683function entryDupeKey(e: VaultEntry): string {1684  if (e.type === "note") return `note|${e.title.toLowerCase()}`;1685  // Passkey-bearing entries dedupe by the credential's RP + user. Two logins1686  // on different sites that happen to share a username are still distinct;1687  // two passkey credentials for the same RP+user are duplicates regardless1688  // of any login fields they may also carry.1689  if (e.passkey) {1690    return `passkey|${e.passkey.rpId.toLowerCase()}|${e.passkey.userName.toLowerCase()}`;1691  }1692  return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;1693}16941695/** Returns the number of duplicate entries (those that would be removed). */1696export function countDuplicates(): number {1697  const best = new Map<string, VaultEntry>();1698  let dupeCount = 0;1699  for (const e of entries.filter((e) => !e.deletedAt)) {1700    const key = entryDupeKey(e);1701    const existing = best.get(key);1702    if (!existing) {1703      best.set(key, e);1704    } else {1705      dupeCount++;1706      // Keep the more recently modified one in the map1707      if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {1708        best.set(key, e);1709      }1710    }1711  }1712  return dupeCount;1713}17141715/**1716 * Soft-deletes duplicate entries, keeping the most recently modified copy of1717 * each group. Returns the number of entries moved to trash.1718 */1719export async function deduplicateEntries(): Promise<number> {1720  if (!derivedKey) throw new Error("vault locked");1721  // Dedup reshapes slot B permanently under the decoy key, which is1722  // forensically distinguishable from a freshly-seeded decoy vault. Refuse.1723  if (vaultMode === "decoy") {1724    throw new Error("deduplicate disabled in decoy mode");1725  }17261727  const best = new Map<string, VaultEntry>();1728  for (const e of entries.filter((en) => !en.deletedAt)) {1729    const key = entryDupeKey(e);1730    const existing = best.get(key);1731    if (!existing) {1732      best.set(key, e);1733    } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {1734      best.set(key, e);1735    }1736  }17371738  const keepIds = new Set(Array.from(best.values()).map((e) => e.id));1739  const now = Date.now();1740  let removed = 0;1741  entries = entries.map((e) => {1742    if (!e.deletedAt && !keepIds.has(e.id)) {1743      removed++;1744      return { ...e, deletedAt: now };1745    }1746    return e;1747  });17481749  if (removed > 0) await persistEntries();1750  return removed;1751}17521753// ---------------------------------------------------------------------------1754// Vault history — snapshot BEFORE every vault write so the saved blob is1755// what is about to be lost, not what was just written. Capped at 10. The1756// stored blobs are AES-256-GCM ciphertext under the master password, so1757// history adds zero security surface.1758// ---------------------------------------------------------------------------17591760const HISTORY_KEY = "peach_vault_history";1761const HISTORY_MAX = 10;17621763/**1764 * Snapshot the CURRENT on-disk vault state into history. Call this BEFORE1765 * overwriting peach_vault_a so the saved blob captures the about-to-be-lost1766 * state. Identical-to-most-recent blobs are skipped to avoid filling history1767 * with no-op writes.1768 */1769export async function takeVaultSnapshot(1770  reason: VaultSnapshot["reason"],1771): Promise<void> {1772  try {1773    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);1774    const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];1775    const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];17761777    // Nothing to snapshot if the real slot doesn't exist yet (fresh install,1778    // pre-createVault). createVault skips snapshots intentionally — there is1779    // no prior state to preserve.1780    if (!slotA) return;17811782    const vault_a = JSON.stringify(slotA);1783    const vault_b = JSON.stringify(slotB ?? slotA);17841785    // Best-effort entry count: only meaningful when the in-memory state is1786    // unlocked AND in real mode. Decoy mode would leak the decoy entry1787    // count; locked mode has no entries to count. Both fall through to null.1788    let entryCount: number | null = null;1789    if (derivedKey && vaultMode === "real") {1790      try {1791        entryCount = entries.filter((e) => !e.deletedAt).length;1792      } catch {1793        entryCount = null;1794      }1795    }17961797    const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];1798    const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)1799      ? existingRaw1800      : { snapshots: [] };18011802    // Deduplication: if the most recent snapshot has byte-identical blobs,1803    // skip — saves the same vault N times in a row would otherwise burn the1804    // entire history window with no recovery value.1805    const latest = history.snapshots[0];1806    if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {1807      return;1808    }18091810    const snapshot: VaultSnapshot = {1811      id: crypto.randomUUID(),1812      savedAt: Date.now(),1813      reason,1814      vault_a,1815      vault_b,1816      entryCount,1817    };18181819    history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);1820    await chrome.storage.local.set({ [HISTORY_KEY]: history });1821  } catch {1822    // Non-fatal — history must never block a save. A failed snapshot just1823    // means the user loses one rung of the safety ladder for this write.1824  }1825}18261827/** Wipe all vault history. Called by Panic / DESTROY_VAULT. */1828export async function clearVaultHistory(): Promise<void> {1829  try {1830    await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });1831  } catch {1832    // Non-fatal — DESTROY_VAULT also runs storage.local.clear().1833  }1834}18351836/** Read all snapshots, newest first, for the Settings vault history view. */1837export async function getVaultHistory(): Promise<VaultSnapshot[]> {1838  const raw = await chrome.storage.local.get(HISTORY_KEY);1839  const history = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];1840  if (!history || !Array.isArray(history.snapshots)) return [];1841  return history.snapshots;1842}18431844/**1845 * Replace the on-disk vault with the chosen snapshot's blobs and lock the1846 * vault. The current state is itself snapshotted with reason 'restore' first1847 * so the restore is reversible. After this returns, the user must unlock1848 * with the password that matches the restored blob.1849 */1850export async function restoreVaultSnapshot(1851  snapshotId: string,1852): Promise<{ ok: true } | { ok: false; error: string }> {1853  const history = await getVaultHistory();1854  const snapshot = history.find((s) => s.id === snapshotId);1855  if (!snapshot) return { ok: false, error: "snapshot_not_found" };18561857  // Snapshot the about-to-be-replaced current state so the restore is1858  // reversible. takeVaultSnapshot is no-op when the most recent entry is1859  // byte-identical, so a restore-of-a-restore stays clean.1860  await takeVaultSnapshot("restore");18611862  let restoredA: StoredVault;1863  let restoredB: StoredVault;1864  try {1865    restoredA = JSON.parse(snapshot.vault_a) as StoredVault;1866    restoredB = JSON.parse(snapshot.vault_b) as StoredVault;1867  } catch {1868    return { ok: false, error: "snapshot_corrupt" };1869  }18701871  await writeSlot(SLOT_A, restoredA);1872  await writeSlot(SLOT_B, restoredB);18731874  // Lock so the user must prove they can decrypt the restored blob. If they1875  // restored a pre-password-change snapshot they discover it immediately at1876  // the lock screen rather than silently holding an inaccessible vault.1877  lock();18781879  return { ok: true };1880}18811882/**1883 * Change the master password. Re-encrypts slot A with a fresh salt + new1884 * derived key. Slot B (duress or noise) is left untouched when duress is1885 * configured — it uses an independent key derived from the duress password —1886 * and regenerated as noise when duress is not configured.1887 */1888export async function changePassword(1889  currentPassword: string,1890  newPassword: string1891): Promise<boolean> {1892  if (!derivedKey || vaultMode !== "real") return false;18931894  // Verify current password before allowing any change1895  const valid = await verifyMainPassword(currentPassword);1896  if (!valid) return false;18971898  const slotA = await loadSlot(SLOT_A);1899  if (!slotA) return false;19001901  // Derive fresh key from new password + new random salt1902  const newSalt = generateSalt();1903  const newKey = await deriveKey(newPassword, newSalt);19041905  // Re-encrypt the in-memory entries with the new key1906  const plaintext = encodePayload(entries, duressConfigured);1907  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext);19081909  const freshSlotA: StoredVault = {1910    ...slotA,1911    salt: hex(newSalt),1912    nonce,1913    ciphertext,1914    tag,1915  };1916  // Snapshot the OLD-key blob before overwriting it. If the user later1917  // restores from this snapshot they will need the OLD password — the1918  // post-restore lock surfaces that immediately.1919  await takeVaultSnapshot("local_save");1920  await writeSlot(SLOT_A, freshSlotA);19211922  // Swap the in-memory key synchronously before any further await. If we1923  // threw between the Slot A write and this swap, the next persistEntries()1924  // would overwrite Slot A with old-key ciphertext, locking the user out.1925  zeroKey(derivedKey);1926  derivedKey = newKey;19271928  // Rotate the root key so the old recovery words are immediately invalidated.1929  // After this point getRecoveryWords() returns a fresh 12-word set.1930  const {1931    rawRootKey: freshRawKey,1932    recoverySalt: freshSalt,1933    wrappedRootKey: freshWrapped,1934    wrappedNonce: freshNonce,1935    wrappedTag: freshTag,1936  } = await generateAndWrapRootKey();1937  rootKey = unhex(freshRawKey);1938  const slotAfterRekey = await loadSlot(SLOT_A);1939  if (slotAfterRekey) {1940    await writeSlot(SLOT_A, {1941      ...slotAfterRekey,1942      recovery_salt: freshSalt,1943      recovery_wrapped_root_key: freshWrapped,1944      recovery_nonce: freshNonce,1945      recovery_tag: freshTag,1946    });1947  }19481949  // Regenerate noise for slot B when duress is not in use. Runs after the1950  // key swap so a failure here is a disposable noise regeneration, not a1951  // lockout.1952  if (!duressConfigured) {1953    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));1954  }19551956  return true;1957}