vault.ts

67.0 KB · raw

1/**2 * vault.ts — sole owner of vault state and chrome.storage vault keys.3 *4 * Every read/write of `peach_vault_a`, `peach_vault_b`, and `peach_settings`5 * goes through this module. No other file accesses those keys directly.6 * External callers reach vault operations via `messages.ts` — never by7 * importing from here cross-boundary (popup/content must not). Invariants8 * for the two-slot schema, unlock timing, and key/disk atomicity are in9 * Projects.md §3.2–§3.6.10 */1112import { deriveKey, generateSalt } from "../crypto/argon2";13import { extractDomain } from "../shared/domain";14import {15  rootKeyToWords,16  wordsToRootKeyMaterial,17  deriveRecoveryKey,18} from "../shared/recovery-words";19import type {20  AccentColorName,21  LegacyVaultEntry,22  ManualSummonRecord,23  SavedIdentity,24  StoredVault,25  VaultEntry,26  VaultHistory,27  VaultSnapshot,28} from "../shared/types";29import { decrypt, encrypt, zeroKey } from "./aes";30import { clearAutoLock, touchAutoLock } from "./alarms";3132type EntryDraft = Omit<33  VaultEntry,34  "id" | "createdAt" | "modifiedAt" | "deletedAt"35>;3637// Slot-neutral storage keys (v1.4.24+). Both slots always exist; slot B38// either holds the decoy vault (when duress is configured) or random noise39// that looks identical at rest. No external indicator is stored — duress40// configuration is recorded only inside the encrypted payload of slot A.41const SLOT_A = "peach_vault_a";42const SLOT_B = "peach_vault_b";4344// Legacy keys, migrated away on first access.45const LEGACY_MAIN = "peach_vault";46const LEGACY_DECOY = "peach_decoy_vault";47const LEGACY_DURESS_FLAG = "peach_duress";4849// Plaintext is padded to the next multiple of this size before encryption.50// This coarsens ciphertext-length leakage into 1 KiB buckets.51const PAD_BLOCK = 1024;5253let derivedKey: Uint8Array | null = null;54// 32-byte random root key, separate from the derivedKey used for vault encryption.55// The root key is wrapped (encrypted) under the recovery key derived from the56// 12-word phrase. When the user changes their password, only the wrapping changes;57// the root key and recovery words remain stable.58let rootKey: Uint8Array | null = null;59let entries: VaultEntry[] = [];60let domainIndex: Map<string, VaultEntry[]> = new Map();61let vaultMode: "real" | "decoy" = "real";62// Cached post-unlock view of whether the real vault records that duress is63// configured. Only meaningful after a real-mode unlock; for decoy-mode unlock64// this stays false because we never see slot A's plaintext.65let duressConfigured = false;6667let migrationRan = false;6869// ---------------------------------------------------------------------------70// Settings (persisted inside the encrypted vault store as a sidecar key)71// ---------------------------------------------------------------------------7273export type DisplayFont = "cormorant-italic" | "cormorant" | "inter" | "system";74export type TextSize = "small" | "medium" | "large";7576export interface VaultSettings {77  accentColor?: AccentColorName;78  theme?: "dark" | "light";79  autoLockMinutes?: number;80  clipboardClearSeconds?: number;81  lockOnClose?: boolean;82  breachMonitoring?: boolean;83  passkeyProviderEnabled?: boolean;84  trashRetentionDays?: number;85  manualSummonDomains?: Record<string, ManualSummonRecord>;86  declinedCardFingerprints?: string[];87  /**88   * Display font for headlines, brand wordmark, and narrative copy. Default89   * is "cormorant-italic" — the bold italic serif that ships as Peach's90   * voice. Non-italic options exist for users who prefer upright type.91   */92  displayFont?: DisplayFont;93  /**94   * Text size scale for body copy and entry titles. Stops at "large" by95   * design — XL clips dense screens (Vault, Health) inside the fixed96   * 330×480 popup surface.97   */98  textSize?: TextSize;99  /**100   * When true, all entrance/exit transitions and ambient animations are101   * collapsed to instant. Honoured alongside the user's OS-level102   * `prefers-reduced-motion`.103   */104  reduceMotion?: boolean;105  /**106   * Android-only: when true, the master key is escrowed in AndroidKeyStore107   * and the lock screen offers biometric unlock. Toggled from Settings →108   * Security → Biometrics. Has no effect on desktop builds.109   */110  biometricsEnabled?: boolean;111  /**112   * User overrides for keyboard shortcuts. Keys are ShortcutAction names113   * (see src/shared/shortcuts.ts). Missing actions fall through to114   * DEFAULT_BINDINGS — `getActiveBindings(settings.shortcuts)` is the115   * canonical lookup. Storing only the deltas keeps the vault payload116   * small and lets default updates land for users who never rebind.117   */118  shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;119}120121let settings: VaultSettings = {};122123export function getSettings(): VaultSettings {124  return settings;125}126127export async function ensureSettingsLoaded(): Promise<VaultSettings> {128  await loadSettings();129  return settings;130}131132export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {133  await loadSettings();134  settings = { ...settings, ...patch };135  await persistSettings();136}137138async function persistSettings(): Promise<void> {139  try {140    await chrome.storage.local.set({ peach_settings: settings });141  } catch (err) {142    throw mapStorageError(err);143  }144}145146function mapStorageError(err: unknown): Error {147  const message = err instanceof Error ? err.message : String(err);148  if (/QUOTA_BYTES|quota/i.test(message)) {149    return new Error("STORAGE_QUOTA_EXCEEDED");150  }151  return err instanceof Error ? err : new Error(message);152}153154async function loadSettings(): Promise<void> {155  const result = await chrome.storage.local.get("peach_settings");156  settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};157}158159// ---------------------------------------------------------------------------160// HIBP breach check (k-anonymity model)161// ---------------------------------------------------------------------------162163export async function checkBreach(password: string): Promise<number> {164  const encoder = new TextEncoder();165  const hashBuffer = await crypto.subtle.digest("SHA-1", encoder.encode(password));166  const hashHex = Array.from(new Uint8Array(hashBuffer))167    .map((b) => b.toString(16).padStart(2, "0"))168    .join("")169    .toUpperCase();170171  const prefix = hashHex.slice(0, 5);172  const suffix = hashHex.slice(5);173174  try {175    const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`);176    if (!res.ok) return 0;177    const text = await res.text();178    const match = text.split("\r\n").find((l) => l.startsWith(suffix));179    return match ? parseInt(match.split(":")[1], 10) : 0;180  } catch {181    return 0; // Network unavailable — don't block182  }183}184185export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {186  const fingerprint = await cardFingerprint(last4, expMonth, expYear);187  await loadSettings();188  settings = {189    ...settings,190    declinedCardFingerprints: [...(settings.declinedCardFingerprints ?? []), fingerprint],191  };192  await persistSettings();193}194195export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {196  await loadSettings();197  const fingerprint = await cardFingerprint(last4, expMonth, expYear);198  return (settings.declinedCardFingerprints ?? []).includes(fingerprint);199}200201async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {202  const encoder = new TextEncoder();203  const buf = await crypto.subtle.digest("SHA-1", encoder.encode(`${last4}${expMonth}${expYear}`));204  return Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2, "0")).join("");205}206207function hex(buf: Uint8Array): string {208  return Array.from(buf)209    .map((b) => b.toString(16).padStart(2, "0"))210    .join("");211}212213function unhex(s: string): Uint8Array {214  const out = new Uint8Array(s.length / 2);215  for (let i = 0; i < s.length; i += 2) {216    out[i / 2] = parseInt(s.slice(i, i + 2), 16);217  }218  return out;219}220221// ---------------------------------------------------------------------------222// Root key generation and recovery word wrapping223// ---------------------------------------------------------------------------224225/**226 * Generate a random 32-byte root key and wrap it (AES-256-GCM) under a key227 * derived from the recovery word material via HKDF-SHA256. The wrapped blob228 * fields are stored in slot A alongside the password-wrapped ciphertext. The229 * root key itself is kept in memory for the session so getRecoveryWords() can230 * encode it without re-deriving.231 */232async function generateAndWrapRootKey(): Promise<{233  rawRootKey: string; // hex of the plaintext root key — caller stores in rootKey234  recoverySalt: string;235  wrappedRootKey: string;236  wrappedNonce: string;237  wrappedTag: string;238}> {239  const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));240241  // Derive the recovery key from the BIP39 words encoding of the root key.242  const words = await rootKeyToWords(rootKeyBytes);243  const wordMaterial = await wordsToRootKeyMaterial(words);244  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));245  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);246247  // Wrap the root key with the recovery key using AES-256-GCM directly.248  // We hex-encode rootKeyBytes so the plaintext is always valid UTF-8.249  const nonce = crypto.getRandomValues(new Uint8Array(12));250  const encoded = new TextEncoder().encode(hex(rootKeyBytes));251  const raw = await crypto.subtle.encrypt(252    {253      name: "AES-GCM",254      iv: nonce,255      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,256      tagLength: 128,257    },258    recoveryKey,259    encoded260  );261  // WebCrypto returns ciphertext || auth tag concatenated; split them.262  const rawU8 = new Uint8Array(raw);263  const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));264  const tag = hex(rawU8.slice(rawU8.length - 16));265266  return {267    rawRootKey: hex(rootKeyBytes),268    recoverySalt: hex(recoverySalt),269    wrappedRootKey: ciphertext,270    wrappedNonce: hex(nonce),271    wrappedTag: tag,272  };273}274275/**276 * Unwrap the root key using recovery words. Called during recovery flow when277 * the user provides their 12-word phrase and a new password.278 * Exported for use by the RECOVER_WITH_WORDS message handler.279 */280export async function unwrapRootKeyForRecovery(281  wrappedRootKey: string,282  wrappedNonce: string,283  wrappedTag: string,284  recoverySaltHex: string,285  words: string[]286): Promise<void> {287  const wordMaterial = await wordsToRootKeyMaterial(words);288  const recoverySalt = unhex(recoverySaltHex);289  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);290291  // Decrypt and cache the root key. The root key bytes were hex-encoded before292  // encryption so the ciphertext is valid UTF-8. We inline the AES-GCM decrypt293  // here to avoid passing a CryptoKey to the string-based encrypt/decrypt helpers.294  const combined = unhex(wrappedRootKey + wrappedNonce + wrappedTag);295  const nonceU8 = combined.slice(0, 12);296  const ciphertext = combined.slice(12, combined.length - 16);297  const storedTag = combined.slice(combined.length - 16);298  const raw = await crypto.subtle.decrypt(299    { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },300    recoveryKey,301    new Uint8Array([...ciphertext, ...storedTag])302  );303  const decryptedHex = new TextDecoder().decode(raw);304  rootKey = unhex(decryptedHex);305}306307/**308 * Re-wrap the cached root key under a new derived key (from the user's new309 * password). Called after password change and after recovery re-key so the310 * same recovery words continue to work with the updated password.311 */312export async function rewrapRootKeyForPassword(313  newDerivedKey: Uint8Array,314  _newSalt: Uint8Array315): Promise<void> {316  if (!rootKey) throw new Error("root key not set");317  const { nonce, ciphertext, tag } = await encrypt(318    newDerivedKey,319    hex(rootKey)320  );321  const slotA = await loadSlot(SLOT_A);322  if (!slotA) throw new Error("missing slot A");323  await writeSlot(SLOT_A, {324    ...slotA,325    recovery_wrapped_root_key: ciphertext,326    recovery_nonce: nonce,327    recovery_tag: tag,328    // recovery_salt does NOT change when password changes — the recovery329    // words always derive the same key; only the wrapping key changes.330  });331}332333/**334 * Change the vault encryption to a new derived key (already derived from335 * the user's new password). Used by RECOVER_WITH_WORDS and changePassword.336 * Caller is responsible for key swap and snapshot.337 */338async function reencryptVaultForNewKey(339  newKey: Uint8Array,340  slotA: StoredVault341): Promise<void> {342  const plaintext = encodePayload(entries, duressConfigured);343  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext);344  await writeSlot(SLOT_A, {345    ...slotA,346    nonce,347    ciphertext,348    tag,349  });350}351352/**353 * Full password change with an already-derived key (used after recovery).354 * Unlike changePassword(), this skips re-verification of current password355 * since recovery flow has already validated the user's identity via words.356 */357export async function changePasswordWithNewKey(358  newSalt: Uint8Array,359  newKey: Uint8Array360): Promise<void> {361  const slotA = await loadSlot(SLOT_A);362  if (!slotA) throw new Error("missing slot A");363  await reencryptVaultForNewKey(newKey, slotA);364  zeroKey(derivedKey!);365  derivedKey = newKey;366  if (!duressConfigured) {367    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));368  }369}370371// ---------------------------------------------------------------------------372// Salt generation --- exported so the RECOVER_WITH_WORDS handler can derive373// a new key after password reset without re-importing the crypto module.374// ---------------------------------------------------------------------------375376export { deriveKey, generateSalt };377378export async function loadSlotA(): Promise<StoredVault | null> {379  return loadSlot(SLOT_A);380}381382/**383 * Re-derive the session root key from the already-derived AES key (keyA from384 * unlock) and the recovery salt stored in slot A. This is the inverse of385 * generateAndWrapRootKey() — both operations use the same HKDF with the same386 * salt and info string, so they cancel out.387 *388 * The derivedKey and rootKey are related by:389 *   derivedKey = Argon2id(password, slotA.salt)   → AES key for vault payload390 *   rootKey    = HKDF-SHA256(recovery_words, recovery_salt)  → wrapped by HKDF391 *392 * Since we only store the wrapped root key and the recovery salt, we can393 * only re-derive rootKey during an active (unlocked) session where we have394 * the derivedKey already. On lock, rootKey is zeroed.395 *396 * For pre-v2.12 vaults that have no recovery_salt, this returns null and397 * the caller must invoke migrateToRecovery() to generate the recovery escrow.398 */399async function deriveRootKeyFromDerivedKey(400  _derivedKey: Uint8Array,401  _recoverySaltHex: string402): Promise<Uint8Array | null> {403  // The root key is stored wrapped under the recovery key derived from the404  // 12-word phrase. It cannot be re-derived from derivedKey alone — that would405  // require knowing the original recovery words. The in-memory rootKey is set406  // during unlock if recovery data is present.407  // This function exists as a potential future path if we ever store an408  // additional derived-key → root-key relationship. Currently rootKey is409  // cached directly during unlock.410  return null;411}412413/**414 * For vaults created before v2.12 (no recovery_salt/recovery_wrapped_root_key),415 * generate the root key, wrap it under the recovery words, and persist the416 * recovery escrow into slot A. The caller must show the recovery words to the417 * user before calling this — once called, those words are the vault's recovery418 * path. This runs once, on the first unlock of an upgraded vault.419 */420export async function migrateToRecovery(): Promise<void> {421  if (!derivedKey || vaultMode !== "real") {422    throw new Error("vault must be unlocked in real mode");423  }424  const slotA = await loadSlot(SLOT_A);425  if (!slotA) throw new Error("missing slot A");426  if (slotA.recovery_salt && slotA.recovery_wrapped_root_key) return; // already done427428  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =429    await generateAndWrapRootKey();430431  rootKey = unhex(rawRootKey);432433  const nextSlotA: StoredVault = {434    ...slotA,435    recovery_salt: recoverySalt,436    recovery_wrapped_root_key: wrappedRootKey,437    recovery_nonce: wrappedNonce,438    recovery_tag: wrappedTag,439  };440  await writeSlot(SLOT_A, nextSlotA);441}442443/**444 * Returns the 12 recovery words for the current session's root key.445 * Must be called while the vault is unlocked. Throws if recovery has not446 * been set up (pre-v2.12 vault that hasn't migrated yet).447 */448export async function getRecoveryWords(): Promise<string[]> {449  if (!rootKey) {450    throw new Error("recovery not set up — vault may need migration");451  }452  return rootKeyToWords(rootKey);453}454455async function loadSlot(key: string): Promise<StoredVault | null> {456  const result = await chrome.storage.local.get(key);457  return (result as Record<string, StoredVault | undefined>)[key] ?? null;458}459460async function writeSlot(key: string, vault: StoredVault): Promise<void> {461  try {462    await chrome.storage.local.set({ [key]: vault });463  } catch (err) {464    throw mapStorageError(err);465  }466}467468/**469 * One-shot migration from the pre-A-2 schema (peach_vault + peach_decoy_vault470 * + peach_duress flag) to the slot-neutral schema (peach_vault_a +471 * peach_vault_b). Runs at most once per session; safe to call repeatedly.472 */473async function ensureMigrated(): Promise<void> {474  if (migrationRan) return;475  migrationRan = true;476477  const keys = [LEGACY_MAIN, LEGACY_DECOY, LEGACY_DURESS_FLAG, SLOT_A, SLOT_B];478  const raw = await chrome.storage.local.get(keys);479  const slotAExists = raw[SLOT_A] !== undefined;480  const slotBExists = raw[SLOT_B] !== undefined;481  const legacyMain = raw[LEGACY_MAIN] as StoredVault | undefined;482  const legacyDecoy = raw[LEGACY_DECOY] as StoredVault | undefined;483484  // Fresh install with nothing in storage — nothing to do; createVault() sets up both slots.485  if (!slotAExists && !legacyMain) return;486487  // Already migrated.488  if (slotAExists && slotBExists && !legacyMain && !legacyDecoy) return;489490  if (legacyMain && !slotAExists) {491    await writeSlot(SLOT_A, legacyMain);492  }493494  // If slot B isn't set, populate it: use legacy decoy when present, else noise.495  if (!slotBExists) {496    const target = (legacyMain ?? raw[SLOT_A]) as StoredVault | undefined;497    if (legacyDecoy) {498      await writeSlot(SLOT_B, legacyDecoy);499    } else if (target) {500      await writeSlot(SLOT_B, generateNoiseBlob(target.ciphertext.length / 2));501    }502  }503504  const toRemove: string[] = [];505  if (legacyMain) toRemove.push(LEGACY_MAIN);506  if (legacyDecoy) toRemove.push(LEGACY_DECOY);507  if (raw[LEGACY_DURESS_FLAG] !== undefined) toRemove.push(LEGACY_DURESS_FLAG);508  if (toRemove.length > 0) {509    await chrome.storage.local.remove(toRemove);510  }511}512513// ---------------------------------------------------------------------------514// Padding + noise helpers515// ---------------------------------------------------------------------------516517/**518 * Pads the plaintext string with trailing spaces so that the encoded byte519 * length is a multiple of PAD_BLOCK. JSON.parse tolerates trailing520 * whitespace after a complete document, so the padding is transparent on521 * decode. Ciphertext length equals plaintext length plus a 16-byte tag.522 */523function padPlaintext(json: string): string {524  const encoded = new TextEncoder().encode(json);525  const target = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);526  const padLen = target - encoded.length;527  return json + " ".repeat(padLen);528}529530/**531 * Produces a StoredVault-shaped record filled with CSPRNG bytes. The532 * ciphertext length matches the given byte count. Because GCM ciphertext is533 * pseudo-random, this blob is indistinguishable at rest from a real534 * encrypted vault without the key.535 *536 * crypto.getRandomValues() caps each call at 65536 bytes (the Web Crypto537 * spec hard limit). Chunk the fill so vaults larger than that — common once538 * the user has dozens of entries or any passkey — don't throw.539 */540const CSPRNG_CHUNK = 65_536;541542function fillRandom(buf: Uint8Array): Uint8Array {543  for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {544    const end = Math.min(offset + CSPRNG_CHUNK, buf.length);545    const chunk = new Uint8Array(end - offset);546    crypto.getRandomValues(chunk);547    buf.set(chunk, offset);548  }549  return buf;550}551552function generateNoiseBlob(ciphertextBytes: number): StoredVault {553  const salt = crypto.getRandomValues(new Uint8Array(16));554  const nonce = crypto.getRandomValues(new Uint8Array(12));555  const cipher = fillRandom(new Uint8Array(ciphertextBytes));556  const tag = crypto.getRandomValues(new Uint8Array(16));557  return {558    version: 1,559    salt: hex(salt),560    nonce: hex(nonce),561    ciphertext: hex(cipher),562    tag: hex(tag),563  };564}565566// ---------------------------------------------------------------------------567// Encrypted plaintext envelope568// ---------------------------------------------------------------------------569570type VaultPayload = {571  entries: VaultEntry[];572  duressConfigured?: boolean;573};574575type DecryptedPayload = {576  entries: VaultEntry[];577  duressConfigured: boolean;578  /**579   * True when at least one entry in the on-disk payload had a legacy shape580   * (pre-v2.11.0 passkey type/flat fields, or pre-A-2 created/updated keys)581   * and got rewritten by normalizeEntry. The unlock path uses this to582   * persist the new shape immediately — without it, the migration would583   * re-run on every unlock and old shape never disappears from disk.584   */585  migratedFromLegacy: boolean;586};587588function encodePayload(entries: VaultEntry[], duress: boolean): string {589  const envelope: VaultPayload = { entries, duressConfigured: duress };590  return padPlaintext(JSON.stringify(envelope));591}592593function rawNeedsMigration(raw: VaultEntry | LegacyVaultEntry): boolean {594  if ("created" in raw || "updated" in raw) return true;595  const flat = raw as Partial<VaultEntry>;596  if (flat.type === "passkey") return true;597  // Flat rpId without a passkey sub-object means pre-v2.11.0 schema.598  if (flat.rpId !== undefined && flat.passkey === undefined) return true;599  return false;600}601602function decodePayload(plain: string): DecryptedPayload {603  const parsed = JSON.parse(plain) as604    | Array<VaultEntry | LegacyVaultEntry>605    | VaultPayload;606607  const rawEntries = Array.isArray(parsed) ? parsed : parsed.entries ?? [];608  const flatMigrationNeeded = rawEntries.some(rawNeedsMigration);609610  const normalized = rawEntries.map(normalizeEntry);611  const { merged } = mergePasskeyOnlyIntoLogins(normalized);612613  if (Array.isArray(parsed)) {614    return {615      entries: normalized,616      duressConfigured: false,617      migratedFromLegacy: true, // pre-A-2 array shape always needs save618    };619  }620621  return {622    entries: normalized,623    duressConfigured: parsed.duressConfigured === true,624    migratedFromLegacy: flatMigrationNeeded || merged,625  };626}627628/**629 * One-time consolidation pass run alongside the legacy passkey migration.630 *631 * Pre-v2.11.0 the Chrome passkey path always created a fresh `type:"passkey"`632 * entry per registration — so users who tested registration multiple times633 * accumulated several passkey-bearing entries for the same RP, and the634 * migration to the unified shape carried that duplication forward. This635 * pass collapses the duplicates:636 *637 *   1. Group passkey-bearing (and not deleted) entries by `passkey.rpId`.638 *   2. Within each group, the most recently-active credential wins (prefer639 *      lastUsedAt, fall back to passkey.createdAt, fall back to modifiedAt).640 *   3. If a NON-passkey login entry exists for that RP (matched by url or641 *      additionalUrls hostname), attach the winning passkey to it and642 *      soft-delete every passkey-bearing entry in the group.643 *   4. Otherwise, soft-delete every loser in the group, keeping the winner644 *      as a passkey-only entry.645 *646 * Soft delete (deletedAt) rather than splice — the trash flow keeps the647 * record around for retention and the user can restore if the heuristic648 * picked wrong. The `merged` flag goes back to decodePayload so the649 * unlock path persists the consolidated shape immediately.650 */651function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {652  let merged = false;653  const now = Date.now();654655  const candidates = entries.filter((e) => !e.deletedAt && e.passkey);656  const byRpId = new Map<string, VaultEntry[]>();657  for (const e of candidates) {658    const rpId = e.passkey!.rpId;659    const list = byRpId.get(rpId);660    if (list) list.push(e);661    else byRpId.set(rpId, [e]);662  }663664  for (const [rpId, group] of byRpId) {665    if (group.length === 0) continue;666    group.sort((a, b) => {667      const aT =668        a.passkey!.lastUsedAt ?? a.passkey!.createdAt ?? a.modifiedAt ?? a.createdAt;669      const bT =670        b.passkey!.lastUsedAt ?? b.passkey!.createdAt ?? b.modifiedAt ?? b.createdAt;671      return bT - aT;672    });673    const winner = group[0]!;674675    // Look for a NON-passkey login entry matching this RP. Use the URL676    // hostname rather than a substring search so a "login.foo.com" entry677    // doesn't accidentally absorb a passkey for "foo.com".678    const loginTarget = entries.find((e) => {679      if (e.deletedAt || e.passkey || e.type !== "login") return false;680      if (e.url && extractDomain(e.url) === rpId) return true;681      for (const extra of e.additionalUrls ?? []) {682        if (extractDomain(extra) === rpId) return true;683      }684      return false;685    });686687    if (loginTarget) {688      loginTarget.passkey = winner.passkey;689      loginTarget.modifiedAt = now;690      for (const dup of group) {691        if (!dup.deletedAt) {692          dup.deletedAt = now;693          dup.modifiedAt = now;694        }695      }696      merged = true;697    } else if (group.length > 1) {698      for (let i = 1; i < group.length; i += 1) {699        const dup = group[i]!;700        if (!dup.deletedAt) {701          dup.deletedAt = now;702          dup.modifiedAt = now;703        }704      }705      merged = true;706    }707  }708709  return { merged };710}711712async function tryDecryptSlot(713  vault: StoredVault,714  key: Uint8Array715): Promise<DecryptedPayload | null> {716  try {717    const plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag);718    return decodePayload(plain);719  } catch {720    return null;721  }722}723724// ---------------------------------------------------------------------------725// Core operations726// ---------------------------------------------------------------------------727728function buildDomainIndexSync(all: VaultEntry[]): void {729  domainIndex = new Map();730731  for (const entry of all) {732    if (entry.deletedAt) continue;733    if (entry.type === "note" || entry.type === "card") continue;734735    // An entry can match multiple sites via `additionalUrls`. Index each736    // hostname so `queryDomain` returns the entry regardless of which alias737    // the user is currently visiting. Dedupe per-entry so a single entry738    // never appears twice in one bucket.739    const domains = new Set<string>();740    const primary = extractDomain(entry.url ?? "");741    if (primary) domains.add(primary);742    for (const extra of entry.additionalUrls ?? []) {743      const d = extractDomain(extra);744      if (d) domains.add(d);745    }746    if (domains.size === 0) continue;747748    for (const domain of domains) {749      const bucket = domainIndex.get(domain) ?? [];750      bucket.push(entry);751      domainIndex.set(domain, bucket);752    }753  }754}755756export async function createVault(password: string): Promise<void> {757  await ensureMigrated();758759  const salt = generateSalt();760  derivedKey = await deriveKey(password, salt);761  entries = [];762  vaultMode = "real";763  duressConfigured = false;764  buildDomainIndexSync(entries);765766  // Generate and wrap the root key for recovery word escrow.767  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =768    await generateAndWrapRootKey();769  rootKey = unhex(rawRootKey);770771  const plaintext = encodePayload(entries, duressConfigured);772  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext);773774  const slotA: StoredVault = {775    version: 1,776    salt: hex(salt),777    nonce,778    ciphertext,779    tag,780    recovery_salt: recoverySalt,781    recovery_wrapped_root_key: wrappedRootKey,782    recovery_nonce: wrappedNonce,783    recovery_tag: wrappedTag,784  };785  await writeSlot(SLOT_A, slotA);786787  // Matching-size noise blob for slot B, so a fresh install shows two788  // similarly-shaped records regardless of whether duress is ever set up.789  await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));790791  touchAutoLock();792}793794export async function hasVault(): Promise<boolean> {795  await ensureMigrated();796  return (await loadSlot(SLOT_A)) !== null;797}798799/**800 * Returns whether the real vault has recorded that a duress passphrase is801 * configured. Reliable only after a real-mode unlock — before unlock or in802 * decoy mode, returns false because we cannot read slot A's plaintext.803 */804export async function isDuressEnabled(): Promise<boolean> {805  return vaultMode === "real" && duressConfigured;806}807808export async function hasDecoyVault(): Promise<boolean> {809  return isDuressEnabled();810}811812export async function setupDuress(duressPassword: string): Promise<void> {813  if (!derivedKey || vaultMode !== "real") {814    throw new Error("vault must be unlocked in real mode");815  }816  await ensureMigrated();817818  // Encrypt the decoy payload (empty entries) under the duress key. Pad to819  // at least the current slot A ciphertext size so the two slots look the820  // same at rest at setup time.821  const slotA = await loadSlot(SLOT_A);822  if (!slotA) throw new Error("missing slot A");823824  const decoySalt = generateSalt();825  const decoyKey = await deriveKey(duressPassword, decoySalt);826  try {827    // Pad the decoy plaintext to match slot A's ciphertext length (minus the828    // 16-byte tag) so encrypted sizes align exactly.829    const targetBytes = slotA.ciphertext.length / 2;830    let plaintext = encodePayload([], false);831    const encoded = new TextEncoder().encode(plaintext);832    if (encoded.length < targetBytes) {833      plaintext = plaintext + " ".repeat(targetBytes - encoded.length);834    }835    const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext);836    await writeSlot(SLOT_B, {837      version: 1,838      salt: hex(decoySalt),839      nonce,840      ciphertext,841      tag,842    });843  } finally {844    zeroKey(decoyKey);845  }846847  // Re-encrypt slot A with the duressConfigured flag set to true. No external848  // flag is written — the bit lives inside the encrypted envelope.849  duressConfigured = true;850  await persistSlotA();851}852853export async function disableDuress(): Promise<void> {854  if (!derivedKey || vaultMode !== "real") {855    throw new Error("vault must be unlocked in real mode");856  }857  await ensureMigrated();858859  // Overwrite slot B with fresh noise that matches slot A's size. The slot860  // remains occupied so its mere existence does not signal that duress was861  // ever configured.862  const slotA = await loadSlot(SLOT_A);863  if (slotA) {864    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));865  }866867  duressConfigured = false;868  await persistSlotA();869}870871export async function verifyMainPassword(password: string): Promise<boolean> {872  await ensureMigrated();873  const slotA = await loadSlot(SLOT_A);874  if (!slotA) return false;875  const key = await deriveKey(password, unhex(slotA.salt));876  try {877    return (await tryDecryptSlot(slotA, key)) !== null;878  } finally {879    zeroKey(key);880  }881}882883export async function unlock(password: string): Promise<boolean> {884  await ensureMigrated();885886  // Load both slots in parallel. Both always exist post-migration; the887  // parallel load and the parallel derivation below keep wall-clock time888  // constant regardless of which slot's passphrase (real or decoy) the889  // caller supplied, so a timing side channel cannot distinguish the890  // duress path from the real-unlock path (DUR-002).891  const [slotA, slotB] = await Promise.all([892    loadSlot(SLOT_A),893    loadSlot(SLOT_B),894  ]);895896  // Derive both keys in parallel, unconditionally.897  const [keyA, keyB] = await Promise.all([898    slotA ? deriveKey(password, unhex(slotA.salt)) : Promise.resolve(null),899    slotB ? deriveKey(password, unhex(slotB.salt)) : Promise.resolve(null),900  ]);901902  // Attempt both decrypts in parallel.903  const [payloadA, payloadB] = await Promise.all([904    keyA && slotA ? tryDecryptSlot(slotA, keyA) : Promise.resolve(null),905    keyB && slotB ? tryDecryptSlot(slotB, keyB) : Promise.resolve(null),906  ]);907908  if (payloadA && keyA) {909    derivedKey = keyA;910    vaultMode = "real";911    entries = payloadA.entries;912    duressConfigured = payloadA.duressConfigured;913    buildDomainIndexSync(entries);914    await loadSettings();915    touchAutoLock();916    if (keyB) zeroKey(keyB);917918    // slotA is non-null when payloadA is truthy (keyA was derived from slotA).919    if (slotA) {920      const needsRecoverySetup =921        !slotA.recovery_salt || !slotA.recovery_wrapped_root_key;922      if (!needsRecoverySetup) {923        rootKey = await deriveRootKeyFromDerivedKey(924          keyA,925          slotA.recovery_salt!926        );927      }928    }929930    // If the payload had a pre-v2.11.0 shape (legacy passkey type, flat931    // passkey fields, or pre-A-2 created/updated keys), rewrite it now so932    // the next save uses the new format and migration doesn't re-run forever.933    if (payloadA.migratedFromLegacy) {934      await persistSlotA();935    }936    return true;937  }938939  if (payloadB && keyB) {940    derivedKey = keyB;941    vaultMode = "decoy";942    entries = payloadB.entries;943    duressConfigured = false;944    buildDomainIndexSync(entries);945    await loadSettings();946    touchAutoLock();947    if (keyA) zeroKey(keyA);948    return true;949  }950951  if (keyA) zeroKey(keyA);952  if (keyB) zeroKey(keyB);953  return false;954}955956export function lock(): void {957  if (derivedKey) {958    zeroKey(derivedKey);959    derivedKey = null;960  }961  if (rootKey) {962    rootKey.fill(0);963    rootKey = null;964  }965966  entries = [];967  domainIndex = new Map();968  vaultMode = "real";969  duressConfigured = false;970  clearAutoLock();971}972973export function isUnlocked(): boolean {974  return derivedKey !== null;975}976977// Opens the vault using a pre-derived AES-256 key (skipping Argon2id).978// Used by Android biometric unlock — the key was derived on the native side.979export async function unlockWithKey(980  masterKeyHex: string,981): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {982  try {983    const masterKeyBytes = unhex(masterKeyHex);984    const stored = await loadSlot(SLOT_A);985    if (!stored) return { ok: false, error: "invalid_key" };986    const payload = await tryDecryptSlot(stored, masterKeyBytes);987    if (!payload) return { ok: false, error: "invalid_key" };988989    derivedKey = masterKeyBytes;990    vaultMode = "real";991    entries = payload.entries;992    duressConfigured = payload.duressConfigured;993    buildDomainIndexSync(entries);994    await loadSettings();995    touchAutoLock();996    return { ok: true, entries };997  } catch {998    return { ok: false, error: "invalid_key" };999  }1000}10011002// Returns the current in-memory derived key as a hex string.1003// Used by the biometric enable flow in Settings to store the key in Android Keystore.1004export function getDerivedKeyHex(): string {1005  if (!derivedKey) throw new Error("vault_not_unlocked");1006  return hex(derivedKey);1007}10081009export function getEntries(): VaultEntry[] {1010  if (!derivedKey) throw new Error("vault locked");1011  return entries.filter((entry) => !entry.deletedAt);1012}10131014const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;10151016export function getIdentities(): SavedIdentity[] {1017  if (!derivedKey) throw new Error("vault locked");1018  const active = entries.filter((e) => !e.deletedAt && e.type === "login");10191020  const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();1021  const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();10221023  for (const entry of active) {1024    const value = entry.username?.trim();1025    if (!value) continue;1026    const map = EMAIL_RE.test(value) ? emailMap : usernameMap;1027    const existing = map.get(value);1028    const domain = extractDomain(entry.url ?? "") ?? "";1029    const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;1030    if (!existing || modifiedAt > existing.lastUsed) {1031      map.set(value, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });1032    } else {1033      map.set(value, { ...existing, count: existing.count + 1 });1034    }1035  }10361037  const toIdentity = (type: "email" | "username") =>1038    ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({1039      value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,1040    });10411042  return [1043    ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),1044    ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),1045  ];1046}10471048export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {1049  if (!derivedKey) throw new Error("vault locked");10501051  const now = Date.now();1052  const added: VaultEntry[] = [];1053  for (const draft of drafts) {1054    try {1055      const sanitized = sanitizeEntryDraft(draft);1056      const nextEntry: VaultEntry = {1057        ...sanitized,1058        id: crypto.randomUUID(),1059        createdAt: now,1060        modifiedAt: now,1061      };1062      entries.push(nextEntry);1063      added.push(nextEntry);1064    } catch {1065      // Skip invalid drafts silently — caller can see diff between input and output length1066    }1067  }10681069  if (added.length > 0) {1070    await persistEntries();1071  }10721073  return added;1074}10751076/**1077 * Restore a set of entries in full fidelity — preserves id, createdAt,1078 * modifiedAt, and every other field unlike `batchAddEntries` which1079 * assigns fresh identity. Used by restore paths where the backup is the1080 * authoritative source of truth. `mode` controls how entries already in1081 * the vault are treated.1082 */1083export async function restoreEntries(1084  incoming: VaultEntry[],1085  mode: "replace" | "merge"1086): Promise<{ added: number; updated: number; skipped: number }> {1087  if (!derivedKey) throw new Error("vault locked");10881089  // A replace with zero incoming entries is almost certainly a caller bug1090  // (e.g. an import that silently dropped everything). Refuse rather than1091  // wipe the vault.1092  if (mode === "replace" && incoming.length === 0) {1093    throw new Error("refuse to replace with empty entry set");1094  }10951096  let added = 0;1097  let updated = 0;1098  let skipped = 0;10991100  if (mode === "replace") {1101    entries = [];1102    for (const entry of incoming) {1103      const normalized = sanitizeRestoredEntry(entry);1104      if (!normalized) {1105        skipped += 1;1106        continue;1107      }1108      entries.push(normalized);1109      added += 1;1110    }1111  } else {1112    const byId = new Map<string, VaultEntry>();1113    for (const e of entries) byId.set(e.id, e);11141115    for (const entry of incoming) {1116      const normalized = sanitizeRestoredEntry(entry);1117      if (!normalized) {1118        skipped += 1;1119        continue;1120      }1121      const existing = byId.get(normalized.id);1122      if (!existing) {1123        entries.push(normalized);1124        added += 1;1125      } else if (normalized.modifiedAt > existing.modifiedAt) {1126        const idx = entries.findIndex((e) => e.id === existing.id);1127        if (idx !== -1) {1128          entries[idx] = normalized;1129          updated += 1;1130        }1131      } else {1132        skipped += 1;1133      }1134    }1135  }11361137  await persistEntries("import");1138  return { added, updated, skipped };1139}11401141/**1142 * Validate + normalise a VaultEntry coming from a backup. Accepts1143 * anything structurally sound; keeps all metadata verbatim. Returns1144 * null for values the live vault shouldn't accept (e.g., missing title).1145 */1146function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {1147  if (!entry || typeof entry !== "object") return null;1148  const title = typeof entry.title === "string" ? entry.title.trim() : "";1149  if (!title) return null;1150  const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();1151  const now = Date.now();1152  const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;1153  const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;11541155  // Migrate legacy passkey shape on import (same logic as on-disk read).1156  // Imports from pre-v2.11.0 vault backups still carry type:"passkey" with1157  // flat fields; bring them into the new shape immediately.1158  const migrated: VaultEntry = migrateLegacyPasskey(1159    {1160      ...entry,1161      id,1162      title,1163      type: entry.type ?? "login",1164      createdAt,1165      modifiedAt,1166    },1167    entry1168  );11691170  // Login entries from backup must carry a password (or be passkey-only,1171  // in which case the passkey sub-object replaces the password requirement).1172  if (1173    migrated.type === "login" &&1174    !migrated.passkey &&1175    typeof migrated.password !== "string"1176  ) {1177    return null;1178  }1179  if (migrated.passkey && !migrated.passkey.credentialId) {1180    return null;1181  }11821183  return migrated;1184}11851186// Soft-deletes every non-deleted entry in one call. The literal string1187// argument is a tripwire against accidental calls — any caller that would1188// wipe the vault has to consciously type "REPLACE_ALL". Do not relax this1189// to a boolean.1190export async function clearVaultEntries(1191  confirmation: "REPLACE_ALL"1192): Promise<void> {1193  if (confirmation !== "REPLACE_ALL") {1194    throw new Error("clearVaultEntries requires explicit confirmation");1195  }1196  if (!derivedKey) throw new Error("vault locked");1197  for (const entry of entries) {1198    if (!entry.deletedAt) {1199      entry.deletedAt = Date.now();1200      entry.modifiedAt = Date.now();1201    }1202  }1203  await persistEntries();1204}12051206export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {1207  if (!derivedKey) throw new Error("vault locked");12081209  const sanitized = sanitizeEntryDraft(entry);1210  const now = Date.now();1211  const nextEntry: VaultEntry = {1212    ...sanitized,1213    id: crypto.randomUUID(),1214    createdAt: now,1215    modifiedAt: now,1216    // Stamp passwordChangedAt at creation so age tracking is accurate from1217    // day one. Non-login entries carry the same stamp harmlessly.1218    passwordChangedAt: sanitized.password ? now : undefined,1219  };12201221  entries.push(nextEntry);1222  await persistEntries();12231224  // Fire-and-forget breach check (only for login entries if breach monitoring is enabled or not set)1225  if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {1226    checkBreach(nextEntry.password).then(async (count) => {1227      if (count > 0) {1228        const idx = entries.findIndex((e) => e.id === nextEntry.id);1229        if (idx !== -1) {1230          entries[idx] = { ...entries[idx], breach: count, modifiedAt: Date.now() };1231          await persistEntries();1232        }1233      }1234    });1235  }12361237  return nextEntry;1238}12391240export async function updateEntry(1241  id: string,1242  patch: Partial<VaultEntry>1243): Promise<void> {1244  if (!derivedKey) throw new Error("vault locked");12451246  const idx = entries.findIndex((entry) => entry.id === id);1247  if (idx === -1 || entries[idx].deletedAt) {1248    throw new Error("entry not found");1249  }12501251  const current = entries[idx];1252  const sanitizedPatch = sanitizeEntryPatch(patch);1253  // Refresh passwordChangedAt only when the password value actually changes —1254  // a metadata-only update (title, tags, etc.) must not reset the age clock1255  // that drives the Pro health rotation recommendation.1256  const passwordChanged =1257    "password" in patch &&1258    typeof sanitizedPatch.password === "string" &&1259    sanitizedPatch.password !== current.password;1260  entries[idx] = {1261    ...current,1262    ...sanitizedPatch,1263    modifiedAt: Date.now(),1264    ...(passwordChanged ? { passwordChangedAt: Date.now() } : {}),1265  };12661267  // A login entry must carry SOMETHING fillable — either a password or a1268  // passkey credential. An empty-password login with no passkey is dead1269  // state. Permit the password-clear when a passkey is attached (that's1270  // the legitimate "drop the password, keep the passkey" path).1271  if (1272    entries[idx].type === "login" &&1273    !entries[idx].password &&1274    !entries[idx].passkey1275  ) {1276    entries[idx] = current;1277    throw new Error("password or passkey required");1278  }12791280  // Card entries must retain their card number1281  if (entries[idx].type === "card" && !entries[idx].cardNumber) {1282    entries[idx] = current;1283    throw new Error("card number is required for card entries");1284  }12851286  await persistEntries();12871288  // Breach check when password changes: clear immediately so old breach doesn't linger,1289  // then async-check the new password and only re-set if it's also found.1290  if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {1291    entries[idx] = { ...entries[idx], breach: undefined };1292    await persistEntries();1293    const password = entries[idx].password;1294    if (password) {1295      checkBreach(password).then(async (count) => {1296        const i = entries.findIndex((e) => e.id === id);1297        if (i !== -1 && count > 0) {1298          entries[i] = { ...entries[i], breach: count, modifiedAt: Date.now() };1299          await persistEntries();1300        }1301      });1302    }1303  }1304}13051306export async function deleteEntry(id: string): Promise<void> {1307  if (!derivedKey) throw new Error("vault locked");13081309  const entry = entries.find((item) => item.id === id);1310  if (!entry || entry.deletedAt) {1311    throw new Error("entry not found");1312  }13131314  entry.deletedAt = Date.now();1315  entry.modifiedAt = Date.now();1316  await persistEntries();1317}13181319export function getDeletedEntries(): VaultEntry[] {1320  if (!derivedKey) return [];1321  return entries.filter((e) => !!e.deletedAt);1322}13231324export async function restoreEntry(id: string): Promise<void> {1325  if (!derivedKey) throw new Error("vault locked");1326  const entry = entries.find((e) => e.id === id && e.deletedAt);1327  if (!entry) throw new Error("deleted entry not found");1328  delete entry.deletedAt;1329  entry.modifiedAt = Date.now();1330  await persistEntries();1331  buildDomainIndexSync(entries);1332}13331334export async function purgeEntry(id: string): Promise<void> {1335  if (!derivedKey) throw new Error("vault locked");1336  const idx = entries.findIndex((e) => e.id === id && e.deletedAt);1337  if (idx === -1) throw new Error("deleted entry not found");1338  entries.splice(idx, 1);1339  await persistEntries();1340}13411342/** Permanently delete entries whose deletedAt is older than retentionMs. 0 = keep forever. */1343export async function purgeExpiredTrash(retentionMs: number): Promise<number> {1344  if (!derivedKey || retentionMs === 0) return 0;1345  const cutoff = Date.now() - retentionMs;1346  const before = entries.length;1347  entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));1348  const purged = before - entries.length;1349  if (purged > 0) await persistEntries();1350  return purged;1351}13521353export function queryDomain(domain: string): VaultEntry[] {1354  return domainIndex.get(domain) ?? [];1355}13561357export function getEntryById(id: string): VaultEntry | undefined {1358  return entries.find((entry) => entry.id === id && !entry.deletedAt);1359}13601361async function persistSlotA(1362  reason: VaultSnapshot["reason"] = "local_save",1363): Promise<StoredVault> {1364  if (!derivedKey) throw new Error("vault locked");13651366  const slotA = await loadSlot(SLOT_A);1367  if (!slotA) throw new Error("missing slot A");13681369  // Snapshot the about-to-be-overwritten state BEFORE we mutate disk. Failures1370  // are swallowed by takeVaultSnapshot — history must never block a save.1371  await takeVaultSnapshot(reason);13721373  const plaintext = encodePayload(entries, duressConfigured);1374  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext);13751376  // Preserve existing recovery escrow fields.1377  const nextSlotA: StoredVault = {1378    ...slotA,1379    nonce,1380    ciphertext,1381    tag,1382    // recovery_salt and recovery_wrapped_root_key are already set from loadSlot1383  };1384  await writeSlot(SLOT_A, nextSlotA);13851386  // When duress is not configured, keep slot B size-matched with slot A by1387  // regenerating its noise. When duress IS configured, leave slot B alone —1388  // we don't have the decoy key to re-encrypt it. This is a known trade-off.1389  if (!duressConfigured) {1390    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));1391  }13921393  return nextSlotA;1394}13951396async function persistSlotB(): Promise<void> {1397  if (!derivedKey) throw new Error("vault locked");13981399  const slotB = await loadSlot(SLOT_B);1400  if (!slotB) throw new Error("missing slot B");14011402  // Decoy plaintext always reports duressConfigured=false — the decoy user1403  // sees a clean slate.1404  const plaintext = encodePayload(entries, false);1405  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext);14061407  await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });1408}14091410async function persistEntries(1411  reason: VaultSnapshot["reason"] = "local_save",1412): Promise<void> {1413  if (!derivedKey) throw new Error("vault locked");14141415  if (vaultMode === "decoy") {1416    await persistSlotB();1417  } else {1418    await persistSlotA(reason);1419  }1420  buildDomainIndexSync(entries);1421}14221423function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {1424  if (!Array.isArray(values)) return undefined;1425  const seen = new Set<string>();1426  const cleaned: string[] = [];1427  for (const value of values) {1428    const trimmed = typeof value === "string" ? value.trim() : "";1429    if (!trimmed) continue;1430    const key = trimmed.toLowerCase();1431    if (seen.has(key)) continue;1432    seen.add(key);1433    cleaned.push(trimmed);1434  }1435  return cleaned.length > 0 ? cleaned : undefined;1436}14371438function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {1439  const title = entry.title.trim();1440  // Accept legacy `type:"passkey"` drafts but rewrite to "login" — the new1441  // model is "any entry, optionally with a passkey sub-object." Imports and1442  // any in-flight callers from before v2.11.0 keep working without throwing.1443  let type: VaultEntry["type"] = entry.type ?? "login";1444  if (type === "passkey") type = "login";14451446  if (!title) throw new Error("title is required");1447  // A login entry needs either a password or a passkey credential to be useful.1448  // Passkey-only entries (passkey present, no password) are valid.1449  if (type === "login" && !entry.password?.trim() && !entry.passkey) {1450    throw new Error("password or passkey required");1451  }1452  if (entry.passkey) {1453    const p = entry.passkey;1454    if (1455      !p.rpId ||1456      !p.credentialId ||1457      !p.publicKeyCose ||1458      !p.userHandle ||1459      !p.userName ||1460      (p.algorithm !== -7 && p.algorithm !== -8)1461    ) {1462      throw new Error("invalid passkey credential");1463    }1464  }1465  if (type === "card") {1466    if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {1467      throw new Error("cardholder name and card number are required");1468    }1469  }14701471  return {1472    type,1473    title,1474    username: type === "login" ? entry.username?.trim() ?? "" : undefined,1475    password: type === "login" ? entry.password : undefined,1476    url: type === "login" ? entry.url?.trim() ?? "" : undefined,1477    additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,1478    totp: type === "login" ? entry.totp?.trim() || undefined : undefined,1479    notes: entry.notes?.trim() || undefined,1480    breach: type === "login" ? entry.breach : undefined,1481    canary: type === "login" ? entry.canary : undefined,1482    tags: entry.tags,1483    passkey: entry.passkey,1484    cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,1485    cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,1486    expMonth: type === "card" ? entry.expMonth?.trim() : undefined,1487    expYear: type === "card" ? entry.expYear?.trim() : undefined,1488    cvc: type === "card" ? entry.cvc?.trim() : undefined,1489    cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,1490    network: type === "card" ? entry.network : undefined,1491    last4: type === "card" ? entry.last4?.trim() : undefined,1492  };1493}14941495function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {1496  const nextPatch: Partial<VaultEntry> = {};14971498  if ("type" in patch) {1499    nextPatch.type = patch.type;1500  }15011502  if ("title" in patch) {1503    const title = patch.title?.trim() ?? "";1504    if (!title) throw new Error("title is required");1505    nextPatch.title = title;1506  }15071508  if ("url" in patch) {1509    nextPatch.url = patch.url?.trim() ?? "";1510  }15111512  if ("additionalUrls" in patch) {1513    const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];1514    const seen = new Set<string>();1515    const cleaned: string[] = [];1516    for (const value of incoming) {1517      const trimmed = typeof value === "string" ? value.trim() : "";1518      if (!trimmed) continue;1519      const key = trimmed.toLowerCase();1520      if (seen.has(key)) continue;1521      seen.add(key);1522      cleaned.push(trimmed);1523    }1524    nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;1525  }15261527  if ("username" in patch) {1528    nextPatch.username = patch.username?.trim() ?? "";1529  }15301531  if ("email" in patch) {1532    nextPatch.email = patch.email?.trim() || undefined;1533  }15341535  if ("password" in patch) {1536    const password = patch.password ?? "";1537    // Allow clearing a password (e.g. on passkey-only entries)1538    nextPatch.password = password || undefined;1539  }15401541  if ("totp" in patch) {1542    nextPatch.totp = patch.totp?.trim() || undefined;1543  }15441545  if ("notes" in patch) {1546    nextPatch.notes = patch.notes?.trim() || undefined;1547  }15481549  if ("breach" in patch) {1550    nextPatch.breach = patch.breach;1551  }15521553  if ("canary" in patch) {1554    nextPatch.canary = patch.canary;1555  }15561557  if ("passkey" in patch) {1558    // Passkey sub-object replaces all the legacy flat passkey fields. A1559    // patch with `passkey: undefined` removes the credential from the entry1560    // (used by "remove passkey" without deleting the whole entry).1561    nextPatch.passkey = patch.passkey;1562  }15631564  if ("tags" in patch) {1565    nextPatch.tags = patch.tags;1566  }15671568  if ("cardholderName" in patch) {1569    nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;1570  }1571  if ("cardNumber" in patch) {1572    const n = patch.cardNumber ?? "";1573    nextPatch.cardNumber = n || undefined;1574  }1575  if ("expMonth" in patch) {1576    nextPatch.expMonth = patch.expMonth?.trim() || undefined;1577  }1578  if ("expYear" in patch) {1579    nextPatch.expYear = patch.expYear?.trim() || undefined;1580  }1581  if ("cvc" in patch) {1582    nextPatch.cvc = patch.cvc?.trim() || undefined;1583  }1584  if ("cardNickname" in patch) {1585    nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;1586  }1587  if ("network" in patch) {1588    nextPatch.network = patch.network;1589  }1590  if ("last4" in patch) {1591    nextPatch.last4 = patch.last4?.trim() || undefined;1592  }15931594  return nextPatch;1595}15961597function normalizeEntry(entry: VaultEntry | LegacyVaultEntry): VaultEntry {1598  const createdAt = "createdAt" in entry ? entry.createdAt : entry.created;1599  const modifiedAt =1600    "modifiedAt" in entry ? entry.modifiedAt : entry.updated;16011602  const base: VaultEntry = {1603    id: entry.id,1604    type: "type" in entry ? entry.type : "login",1605    title: entry.title,1606    username: entry.username,1607    password: entry.password,1608    url: entry.url,1609    totp: entry.totp,1610    notes: entry.notes,1611    breach: entry.breach,1612    canary: "canary" in entry ? entry.canary : undefined,1613    passkey: "passkey" in entry ? entry.passkey : undefined,1614    createdAt,1615    modifiedAt,1616    deletedAt: entry.deletedAt,1617    tags: "tags" in entry ? entry.tags : undefined,1618    cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,1619    cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,1620    expMonth: "expMonth" in entry ? entry.expMonth : undefined,1621    expYear: "expYear" in entry ? entry.expYear : undefined,1622    cvc: "cvc" in entry ? entry.cvc : undefined,1623    cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,1624    network: "network" in entry ? entry.network : undefined,1625    last4: "last4" in entry ? entry.last4 : undefined,1626  };16271628  return migrateLegacyPasskey(base, entry);1629}16301631/**1632 * v2.11.0 read migration. Pre-v2.11.0 passkey entries used `type:"passkey"`1633 * with flat top-level fields (rpId, credentialId, etc.). This converts them1634 * to the new shape — `type:"login"` with a `passkey` sub-object — so all1635 * downstream consumers can rely on the new model. The result is rewritten1636 * to disk on next vault save (hasLegacyShape detects the un-migrated case).1637 */1638function migrateLegacyPasskey(1639  base: VaultEntry,1640  raw: VaultEntry | LegacyVaultEntry1641): VaultEntry {1642  if (base.passkey) return base;1643  const flat = raw as Partial<VaultEntry>;1644  const isPasskeyType = base.type === "passkey";1645  const hasFlatPasskeyFields =1646    typeof flat.rpId === "string" &&1647    typeof flat.credentialId === "string" &&1648    typeof flat.publicKeyCose === "string" &&1649    typeof flat.userHandle === "string" &&1650    typeof flat.userName === "string";1651  if (!isPasskeyType && !hasFlatPasskeyFields) return base;1652  if (!hasFlatPasskeyFields) return base;16531654  const algorithm: -7 | -8 = flat.algorithm === -8 ? -8 : -7;1655  base.passkey = {1656    rpId: flat.rpId!,1657    rpName: flat.rpName ?? flat.rpId!,1658    credentialId: flat.credentialId!,1659    publicKeyCose: flat.publicKeyCose!,1660    privateKeyJwk: flat.privateKeyJwk,1661    userHandle: flat.userHandle!,1662    userName: flat.userName!,1663    userDisplayName: flat.userDisplayName ?? flat.userName!,1664    algorithm,1665    signCount: flat.signCount ?? 0,1666    aaguid: flat.aaguid ?? "",1667    backupEligible: flat.backupEligible === true,1668    backupState: flat.backupState === true,1669    lastUsedAt: flat.lastUsedAt,1670    browser: flat.browser,1671    transports: flat.transports,1672    createdAt: base.createdAt,1673  };1674  // Promote to "login" so the unified Entry view renders. Username gets1675  // populated from the passkey's userName so the entry is searchable in the1676  // existing autofill flow without a separate code path.1677  if (isPasskeyType) base.type = "login";1678  if (!base.username) base.username = flat.userName;1679  if (!base.url) base.url = `https://${flat.rpId}`;1680  return base;1681}168216831684// ---------------------------------------------------------------------------1685// Deduplication1686// ---------------------------------------------------------------------------16871688function entryDupeKey(e: VaultEntry): string {1689  if (e.type === "note") return `note|${e.title.toLowerCase()}`;1690  // Passkey-bearing entries dedupe by the credential's RP + user. Two logins1691  // on different sites that happen to share a username are still distinct;1692  // two passkey credentials for the same RP+user are duplicates regardless1693  // of any login fields they may also carry.1694  if (e.passkey) {1695    return `passkey|${e.passkey.rpId.toLowerCase()}|${e.passkey.userName.toLowerCase()}`;1696  }1697  return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;1698}16991700/** Returns the number of duplicate entries (those that would be removed). */1701export function countDuplicates(): number {1702  const best = new Map<string, VaultEntry>();1703  let dupeCount = 0;1704  for (const e of entries.filter((e) => !e.deletedAt)) {1705    const key = entryDupeKey(e);1706    const existing = best.get(key);1707    if (!existing) {1708      best.set(key, e);1709    } else {1710      dupeCount++;1711      // Keep the more recently modified one in the map1712      if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {1713        best.set(key, e);1714      }1715    }1716  }1717  return dupeCount;1718}17191720/**1721 * Soft-deletes duplicate entries, keeping the most recently modified copy of1722 * each group. Returns the number of entries moved to trash.1723 */1724export async function deduplicateEntries(): Promise<number> {1725  if (!derivedKey) throw new Error("vault locked");1726  // Dedup reshapes slot B permanently under the decoy key, which is1727  // forensically distinguishable from a freshly-seeded decoy vault. Refuse.1728  if (vaultMode === "decoy") {1729    throw new Error("deduplicate disabled in decoy mode");1730  }17311732  const best = new Map<string, VaultEntry>();1733  for (const e of entries.filter((en) => !en.deletedAt)) {1734    const key = entryDupeKey(e);1735    const existing = best.get(key);1736    if (!existing) {1737      best.set(key, e);1738    } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {1739      best.set(key, e);1740    }1741  }17421743  const keepIds = new Set(Array.from(best.values()).map((e) => e.id));1744  const now = Date.now();1745  let removed = 0;1746  entries = entries.map((e) => {1747    if (!e.deletedAt && !keepIds.has(e.id)) {1748      removed++;1749      return { ...e, deletedAt: now };1750    }1751    return e;1752  });17531754  if (removed > 0) await persistEntries();1755  return removed;1756}17571758// ---------------------------------------------------------------------------1759// Vault history — snapshot BEFORE every vault write so the saved blob is1760// what is about to be lost, not what was just written. Capped at 10. The1761// stored blobs are AES-256-GCM ciphertext under the master password, so1762// history adds zero security surface.1763// ---------------------------------------------------------------------------17641765const HISTORY_KEY = "peach_vault_history";1766const HISTORY_MAX = 10;17671768/**1769 * Snapshot the CURRENT on-disk vault state into history. Call this BEFORE1770 * overwriting peach_vault_a so the saved blob captures the about-to-be-lost1771 * state. Identical-to-most-recent blobs are skipped to avoid filling history1772 * with no-op writes.1773 */1774export async function takeVaultSnapshot(1775  reason: VaultSnapshot["reason"],1776): Promise<void> {1777  try {1778    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);1779    const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];1780    const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];17811782    // Nothing to snapshot if the real slot doesn't exist yet (fresh install,1783    // pre-createVault). createVault skips snapshots intentionally — there is1784    // no prior state to preserve.1785    if (!slotA) return;17861787    const vault_a = JSON.stringify(slotA);1788    const vault_b = JSON.stringify(slotB ?? slotA);17891790    // Best-effort entry count: only meaningful when the in-memory state is1791    // unlocked AND in real mode. Decoy mode would leak the decoy entry1792    // count; locked mode has no entries to count. Both fall through to null.1793    let entryCount: number | null = null;1794    if (derivedKey && vaultMode === "real") {1795      try {1796        entryCount = entries.filter((e) => !e.deletedAt).length;1797      } catch {1798        entryCount = null;1799      }1800    }18011802    const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];1803    const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)1804      ? existingRaw1805      : { snapshots: [] };18061807    // Deduplication: if the most recent snapshot has byte-identical blobs,1808    // skip — saves the same vault N times in a row would otherwise burn the1809    // entire history window with no recovery value.1810    const latest = history.snapshots[0];1811    if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {1812      return;1813    }18141815    const snapshot: VaultSnapshot = {1816      id: crypto.randomUUID(),1817      savedAt: Date.now(),1818      reason,1819      vault_a,1820      vault_b,1821      entryCount,1822    };18231824    history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);1825    await chrome.storage.local.set({ [HISTORY_KEY]: history });1826  } catch {1827    // Non-fatal — history must never block a save. A failed snapshot just1828    // means the user loses one rung of the safety ladder for this write.1829  }1830}18311832/** Wipe all vault history. Called by Panic / DESTROY_VAULT. */1833export async function clearVaultHistory(): Promise<void> {1834  try {1835    await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });1836  } catch {1837    // Non-fatal — DESTROY_VAULT also runs storage.local.clear().1838  }1839}18401841/** Read all snapshots, newest first, for the Settings vault history view. */1842export async function getVaultHistory(): Promise<VaultSnapshot[]> {1843  const raw = await chrome.storage.local.get(HISTORY_KEY);1844  const history = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];1845  if (!history || !Array.isArray(history.snapshots)) return [];1846  return history.snapshots;1847}18481849/**1850 * Replace the on-disk vault with the chosen snapshot's blobs and lock the1851 * vault. The current state is itself snapshotted with reason 'restore' first1852 * so the restore is reversible. After this returns, the user must unlock1853 * with the password that matches the restored blob.1854 */1855export async function restoreVaultSnapshot(1856  snapshotId: string,1857): Promise<{ ok: true } | { ok: false; error: string }> {1858  const history = await getVaultHistory();1859  const snapshot = history.find((s) => s.id === snapshotId);1860  if (!snapshot) return { ok: false, error: "snapshot_not_found" };18611862  // Snapshot the about-to-be-replaced current state so the restore is1863  // reversible. takeVaultSnapshot is no-op when the most recent entry is1864  // byte-identical, so a restore-of-a-restore stays clean.1865  await takeVaultSnapshot("restore");18661867  let restoredA: StoredVault;1868  let restoredB: StoredVault;1869  try {1870    restoredA = JSON.parse(snapshot.vault_a) as StoredVault;1871    restoredB = JSON.parse(snapshot.vault_b) as StoredVault;1872  } catch {1873    return { ok: false, error: "snapshot_corrupt" };1874  }18751876  await writeSlot(SLOT_A, restoredA);1877  await writeSlot(SLOT_B, restoredB);18781879  // Lock so the user must prove they can decrypt the restored blob. If they1880  // restored a pre-password-change snapshot they discover it immediately at1881  // the lock screen rather than silently holding an inaccessible vault.1882  lock();18831884  return { ok: true };1885}18861887/**1888 * Change the master password. Re-encrypts slot A with a fresh salt + new1889 * derived key. Slot B (duress or noise) is left untouched when duress is1890 * configured — it uses an independent key derived from the duress password —1891 * and regenerated as noise when duress is not configured.1892 */1893export async function changePassword(1894  currentPassword: string,1895  newPassword: string1896): Promise<boolean> {1897  if (!derivedKey || vaultMode !== "real") return false;18981899  // Verify current password before allowing any change1900  const valid = await verifyMainPassword(currentPassword);1901  if (!valid) return false;19021903  const slotA = await loadSlot(SLOT_A);1904  if (!slotA) return false;19051906  // Derive fresh key from new password + new random salt1907  const newSalt = generateSalt();1908  const newKey = await deriveKey(newPassword, newSalt);19091910  // Re-encrypt the in-memory entries with the new key1911  const plaintext = encodePayload(entries, duressConfigured);1912  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext);19131914  const freshSlotA: StoredVault = {1915    ...slotA,1916    salt: hex(newSalt),1917    nonce,1918    ciphertext,1919    tag,1920  };1921  // Snapshot the OLD-key blob before overwriting it. If the user later1922  // restores from this snapshot they will need the OLD password — the1923  // post-restore lock surfaces that immediately.1924  await takeVaultSnapshot("local_save");1925  await writeSlot(SLOT_A, freshSlotA);19261927  // Swap the in-memory key synchronously before any further await. If we1928  // threw between the Slot A write and this swap, the next persistEntries()1929  // would overwrite Slot A with old-key ciphertext, locking the user out.1930  zeroKey(derivedKey);1931  derivedKey = newKey;19321933  // Rotate the root key so the old recovery words are immediately invalidated.1934  // After this point getRecoveryWords() returns a fresh 12-word set.1935  const {1936    rawRootKey: freshRawKey,1937    recoverySalt: freshSalt,1938    wrappedRootKey: freshWrapped,1939    wrappedNonce: freshNonce,1940    wrappedTag: freshTag,1941  } = await generateAndWrapRootKey();1942  rootKey = unhex(freshRawKey);1943  const slotAfterRekey = await loadSlot(SLOT_A);1944  if (slotAfterRekey) {1945    await writeSlot(SLOT_A, {1946      ...slotAfterRekey,1947      recovery_salt: freshSalt,1948      recovery_wrapped_root_key: freshWrapped,1949      recovery_nonce: freshNonce,1950      recovery_tag: freshTag,1951    });1952  }19531954  // Regenerate noise for slot B when duress is not in use. Runs after the1955  // key swap so a failure here is a disposable noise regeneration, not a1956  // lockout.1957  if (!duressConfigured) {1958    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));1959  }19601961  return true;1962}