vault.ts

75.7 KB · raw

1/**2 * vault.ts — sole owner of vault state and chrome.storage vault keys.3 *4 * Every read/write of `peach_vault_a`, `peach_vault_b`, and `peach_settings`5 * goes through this module. No other file accesses those keys directly.6 * External callers reach vault operations via `messages.ts` — never by7 * importing from here cross-boundary (popup/content must not). Invariants8 * for the two-slot schema, unlock timing, and key/disk atomicity are in9 * Projects.md §3.2–§3.6.10 */1112import { deriveKey, generateSalt } from "../crypto/argon2";13import { extractDomain } from "../shared/domain";14import {15  rootKeyToWords,16  wordsToRootKeyMaterial,17  deriveRecoveryKey,18} from "../shared/recovery-words";19import type {20  AccentColorName,21  LegacyVaultEntry,22  ManualSummonRecord,23  SavedIdentity,24  StoredVault,25  VaultEntry,26  VaultHistory,27  VaultSnapshot,28} from "../shared/types";29import { decrypt, encrypt, zeroKey } from "./aes";30import { clearAutoLock, touchAutoLock } from "./alarms";3132type EntryDraft = Omit<33  VaultEntry,34  "id" | "createdAt" | "modifiedAt" | "deletedAt"35>;3637// Slot-neutral storage keys (v1.4.24+). Both slots always exist; slot B38// either holds the decoy vault (when duress is configured) or random noise39// that looks identical at rest. No external indicator is stored — duress40// configuration is recorded only inside the encrypted payload of slot A.41const SLOT_A = "peach_vault_a";42const SLOT_B = "peach_vault_b";4344// Legacy keys, migrated away on first access.45const LEGACY_MAIN = "peach_vault";46const LEGACY_DECOY = "peach_decoy_vault";47const LEGACY_DURESS_FLAG = "peach_duress";4849// Plaintext is padded to the next multiple of this size before encryption.50// This coarsens ciphertext-length leakage into 1 KiB buckets.51const PAD_BLOCK = 1024;5253let derivedKey: Uint8Array | null = null;54// 32-byte random root key, separate from the derivedKey used for vault encryption.55// The root key is wrapped (encrypted) under the recovery key derived from the56// 12-word phrase. When the user changes their password, only the wrapping changes;57// the root key and recovery words remain stable.58let rootKey: Uint8Array | null = null;59let entries: VaultEntry[] = [];60let domainIndex: Map<string, VaultEntry[]> = new Map();61let vaultMode: "real" | "decoy" = "real";62// Cached post-unlock view of whether the real vault records that duress is63// configured. Only meaningful after a real-mode unlock; for decoy-mode unlock64// this stays false because we never see slot A's plaintext.65let duressConfigured = false;6667let migrationRan = false;6869// ---------------------------------------------------------------------------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  // Each component is stored separately in the vault slot; decode them individually295  // so the nonce is always exactly the 12 bytes from wrappedNonce.296  const nonceRaw = unhex(wrappedNonce);297  const ciphertextRaw = unhex(wrappedRootKey);298  const tagRaw = unhex(wrappedTag);299  // Combine ciphertext and tag for AES-GCM (expects ciphertext||tag).300  // Use explicit ArrayBuffer allocations to satisfy TS BufferSource constraints.301  const nonceU8 = nonceRaw as unknown as Uint8Array<ArrayBuffer>;302  const combined = new Uint8Array(ciphertextRaw.length + tagRaw.length);303  combined.set(ciphertextRaw, 0);304  combined.set(tagRaw, ciphertextRaw.length);305  const raw = await crypto.subtle.decrypt(306    { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },307    recoveryKey,308    combined309  );310  const decryptedHex = new TextDecoder().decode(raw);311  rootKey = unhex(decryptedHex);312}313314/**315 * Re-wrap the cached root key under a new derived key (from the user's new316 * password). Called after password change and after recovery re-key so the317 * same recovery words continue to work with the updated password.318 */319export async function rewrapRootKeyForPassword(320  _newDerivedKey: Uint8Array,321  _newSalt: Uint8Array322): Promise<void> {323  if (!rootKey) throw new Error("root key not set");324  const slotA = await loadSlot(SLOT_A);325  if (!slotA) throw new Error("missing slot A");326  // This build has only recovery-word escrow fields for rootKey. Do not write327  // password-derived wrapping material into recovery_* fields; the vault328  // payload itself is re-encrypted under the new password by the caller.329  // Future pw_root_* fields should be updated here without touching recovery_*.330}331332/**333 * Change the vault encryption to a new derived key (already derived from334 * the user's new password). Used by RECOVER_WITH_WORDS and changePassword.335 * Caller is responsible for key swap and snapshot.336 */337async function reencryptVaultForNewKey(338  newKey: Uint8Array,339  slotA: StoredVault340): Promise<void> {341  const plaintext = encodePayload(entries, duressConfigured);342  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext);343  await writeSlot(SLOT_A, {344    ...slotA,345    nonce,346    ciphertext,347    tag,348  });349}350351/**352 * Full password change with an already-derived key (used after recovery).353 * Unlike changePassword(), this skips re-verification of current password354 * since recovery flow has already validated the user's identity via words.355 */356export async function changePasswordWithNewKey(357  newSalt: Uint8Array,358  newKey: Uint8Array359): Promise<void> {360  const slotA = await loadSlot(SLOT_A);361  if (!slotA) throw new Error("missing slot A");362  // reencryptVaultForNewKey must receive the updated salt so that subsequent363  // UNLOCK calls with the new password can re-derive the correct key.364  await reencryptVaultForNewKey(newKey, { ...slotA, salt: hex(newSalt) });365  if (derivedKey) zeroKey(derivedKey);366  derivedKey = newKey;367  if (!duressConfigured) {368    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));369  }370}371372// ---------------------------------------------------------------------------373// Salt generation --- exported so the RECOVER_WITH_WORDS handler can derive374// a new key after password reset without re-importing the crypto module.375// ---------------------------------------------------------------------------376377export { deriveKey, generateSalt };378379export async function loadSlotA(): Promise<StoredVault | null> {380  return loadSlot(SLOT_A);381}382383/**384 * Re-derive the session root key from the already-derived AES key (keyA from385 * unlock) and the recovery salt stored in slot A. This is the inverse of386 * generateAndWrapRootKey() — both operations use the same HKDF with the same387 * salt and info string, so they cancel out.388 *389 * The derivedKey and rootKey are related by:390 *   derivedKey = Argon2id(password, slotA.salt)   → AES key for vault payload391 *   rootKey    = HKDF-SHA256(recovery_words, recovery_salt)  → wrapped by HKDF392 *393 * Since we only store the wrapped root key and the recovery salt, we can394 * only re-derive rootKey during an active (unlocked) session where we have395 * the derivedKey already. On lock, rootKey is zeroed.396 *397 * For pre-v2.12 vaults that have no recovery_salt, this returns null and398 * the caller must invoke migrateToRecovery() to generate the recovery escrow.399 */400async function deriveRootKeyFromDerivedKey(401  _derivedKey: Uint8Array,402  _recoverySaltHex: string403): Promise<Uint8Array | null> {404  // The root key is stored wrapped under the recovery key derived from the405  // 12-word phrase. It cannot be re-derived from derivedKey alone — that would406  // require knowing the original recovery words. The in-memory rootKey is set407  // during unlock if recovery data is present.408  // This function exists as a potential future path if we ever store an409  // additional derived-key → root-key relationship. Currently rootKey is410  // cached directly during unlock.411  return null;412}413414/**415 * For vaults created before v2.12 (no recovery_salt/recovery_wrapped_root_key),416 * generate the root key, wrap it under the recovery words, and persist the417 * recovery escrow into slot A. The caller must show the recovery words to the418 * user before calling this — once called, those words are the vault's recovery419 * path. This runs once, on the first unlock of an upgraded vault.420 */421export async function migrateToRecovery(): Promise<void> {422  if (!derivedKey || vaultMode !== "real") {423    throw new Error("vault must be unlocked in real mode");424  }425  const slotA = await loadSlot(SLOT_A);426  if (!slotA) throw new Error("missing slot A");427  if (slotA.recovery_salt && slotA.recovery_wrapped_root_key) return; // already done428429  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =430    await generateAndWrapRootKey();431432  rootKey = unhex(rawRootKey);433434  const nextSlotA: StoredVault = {435    ...slotA,436    recovery_salt: recoverySalt,437    recovery_wrapped_root_key: wrappedRootKey,438    recovery_nonce: wrappedNonce,439    recovery_tag: wrappedTag,440  };441  await writeSlot(SLOT_A, nextSlotA);442}443444/**445 * Returns the 12 recovery words for the current session's root key.446 * Must be called while the vault is unlocked. Throws if recovery has not447 * been set up (pre-v2.12 vault that hasn't migrated yet).448 */449export async function getRecoveryWords(): Promise<string[]> {450  if (!rootKey) {451    throw new Error("recovery not set up — vault may need migration");452  }453  return rootKeyToWords(rootKey);454}455456async function loadSlot(key: string): Promise<StoredVault | null> {457  const result = await chrome.storage.local.get(key);458  return (result as Record<string, StoredVault | undefined>)[key] ?? null;459}460461async function writeSlot(key: string, vault: StoredVault): Promise<void> {462  try {463    await chrome.storage.local.set({ [key]: vault });464  } catch (err) {465    throw mapStorageError(err);466  }467}468469/**470 * One-shot migration from the pre-A-2 schema (peach_vault + peach_decoy_vault471 * + peach_duress flag) to the slot-neutral schema (peach_vault_a +472 * peach_vault_b). Runs at most once per session; safe to call repeatedly.473 */474async function ensureMigrated(): Promise<void> {475  if (migrationRan) return;476  migrationRan = true;477478  const keys = [LEGACY_MAIN, LEGACY_DECOY, LEGACY_DURESS_FLAG, SLOT_A, SLOT_B];479  const raw = await chrome.storage.local.get(keys);480  const slotAExists = raw[SLOT_A] !== undefined;481  const slotBExists = raw[SLOT_B] !== undefined;482  const legacyMain = raw[LEGACY_MAIN] as StoredVault | undefined;483  const legacyDecoy = raw[LEGACY_DECOY] as StoredVault | undefined;484485  // Fresh install with nothing in storage — nothing to do; createVault() sets up both slots.486  if (!slotAExists && !legacyMain) return;487488  // Already migrated.489  if (slotAExists && slotBExists && !legacyMain && !legacyDecoy) return;490491  if (legacyMain && !slotAExists) {492    await writeSlot(SLOT_A, legacyMain);493  }494495  // If slot B isn't set, populate it: use legacy decoy when present, else noise.496  if (!slotBExists) {497    const target = (legacyMain ?? raw[SLOT_A]) as StoredVault | undefined;498    if (legacyDecoy) {499      await writeSlot(SLOT_B, legacyDecoy);500    } else if (target) {501      await writeSlot(SLOT_B, generateNoiseBlob(target.ciphertext.length / 2));502    }503  }504505  const toRemove: string[] = [];506  if (legacyMain) toRemove.push(LEGACY_MAIN);507  if (legacyDecoy) toRemove.push(LEGACY_DECOY);508  if (raw[LEGACY_DURESS_FLAG] !== undefined) toRemove.push(LEGACY_DURESS_FLAG);509  if (toRemove.length > 0) {510    await chrome.storage.local.remove(toRemove);511  }512}513514// ---------------------------------------------------------------------------515// Padding + noise helpers516// ---------------------------------------------------------------------------517518/**519 * Pads the plaintext string with trailing spaces so that the encoded byte520 * length is a multiple of PAD_BLOCK. JSON.parse tolerates trailing521 * whitespace after a complete document, so the padding is transparent on522 * decode. Ciphertext length equals plaintext length plus a 16-byte tag.523 */524function padPlaintext(json: string): string {525  const encoded = new TextEncoder().encode(json);526  const target = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);527  const padLen = target - encoded.length;528  return json + " ".repeat(padLen);529}530531/**532 * Produces a StoredVault-shaped record filled with CSPRNG bytes. The533 * ciphertext length matches the given byte count. Because GCM ciphertext is534 * pseudo-random, this blob is indistinguishable at rest from a real535 * encrypted vault without the key.536 *537 * crypto.getRandomValues() caps each call at 65536 bytes (the Web Crypto538 * spec hard limit). Chunk the fill so vaults larger than that — common once539 * the user has dozens of entries or any passkey — don't throw.540 */541const CSPRNG_CHUNK = 65_536;542543function fillRandom(buf: Uint8Array): Uint8Array {544  for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {545    const end = Math.min(offset + CSPRNG_CHUNK, buf.length);546    const chunk = new Uint8Array(end - offset);547    crypto.getRandomValues(chunk);548    buf.set(chunk, offset);549  }550  return buf;551}552553function generateNoiseBlob(ciphertextBytes: number): StoredVault {554  const salt = crypto.getRandomValues(new Uint8Array(16));555  const nonce = crypto.getRandomValues(new Uint8Array(12));556  const cipher = fillRandom(new Uint8Array(ciphertextBytes));557  const tag = crypto.getRandomValues(new Uint8Array(16));558  return {559    version: 1,560    salt: hex(salt),561    nonce: hex(nonce),562    ciphertext: hex(cipher),563    tag: hex(tag),564  };565}566567// ---------------------------------------------------------------------------568// Encrypted plaintext envelope569// ---------------------------------------------------------------------------570571type VaultPayload = {572  entries: VaultEntry[];573  duressConfigured?: boolean;574};575576type DecryptedPayload = {577  entries: VaultEntry[];578  duressConfigured: boolean;579  /**580   * True when at least one entry in the on-disk payload had a legacy shape581   * (pre-v2.11.0 passkey type/flat fields, or pre-A-2 created/updated keys)582   * and got rewritten by normalizeEntry. The unlock path uses this to583   * persist the new shape immediately — without it, the migration would584   * re-run on every unlock and old shape never disappears from disk.585   */586  migratedFromLegacy: boolean;587};588589function encodePayload(entries: VaultEntry[], duress: boolean): string {590  const envelope: VaultPayload = { entries, duressConfigured: duress };591  return padPlaintext(JSON.stringify(envelope));592}593594function rawNeedsMigration(raw: VaultEntry | LegacyVaultEntry): boolean {595  if ("created" in raw || "updated" in raw) return true;596  const flat = raw as Partial<VaultEntry>;597  if (flat.type === "passkey") return true;598  // Flat rpId without a passkey sub-object means pre-v2.11.0 schema.599  if (flat.rpId !== undefined && flat.passkey === undefined) return true;600  return false;601}602603function decodePayload(plain: string): DecryptedPayload {604  const parsed = JSON.parse(plain) as605    | Array<VaultEntry | LegacyVaultEntry>606    | VaultPayload;607608  const rawEntries = Array.isArray(parsed) ? parsed : parsed.entries ?? [];609  const flatMigrationNeeded = rawEntries.some(rawNeedsMigration);610611  const normalized = rawEntries.map(normalizeEntry);612  const { merged } = mergePasskeyOnlyIntoLogins(normalized);613614  if (Array.isArray(parsed)) {615    return {616      entries: normalized,617      duressConfigured: false,618      migratedFromLegacy: true, // pre-A-2 array shape always needs save619    };620  }621622  return {623    entries: normalized,624    duressConfigured: parsed.duressConfigured === true,625    migratedFromLegacy: flatMigrationNeeded || merged,626  };627}628629/**630 * One-time consolidation pass run alongside the legacy passkey migration.631 *632 * Pre-v2.11.0 the Chrome passkey path always created a fresh `type:"passkey"`633 * entry per registration — so users who tested registration multiple times634 * accumulated several passkey-bearing entries for the same RP, and the635 * migration to the unified shape carried that duplication forward. This636 * pass collapses the duplicates:637 *638 *   1. Group passkey-bearing (and not deleted) entries by `passkey.rpId`.639 *   2. Within each group, the most recently-active credential wins (prefer640 *      lastUsedAt, fall back to passkey.createdAt, fall back to modifiedAt).641 *   3. If a NON-passkey login entry exists for that RP (matched by url or642 *      additionalUrls hostname), attach the winning passkey to it and643 *      soft-delete every passkey-bearing entry in the group.644 *   4. Otherwise, soft-delete every loser in the group, keeping the winner645 *      as a passkey-only entry.646 *647 * Soft delete (deletedAt) rather than splice — the trash flow keeps the648 * record around for retention and the user can restore if the heuristic649 * picked wrong. The `merged` flag goes back to decodePayload so the650 * unlock path persists the consolidated shape immediately.651 */652function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {653  let merged = false;654  const now = Date.now();655656  const candidates = entries.filter((e) => !e.deletedAt && e.passkey);657  const byRpId = new Map<string, VaultEntry[]>();658  for (const e of candidates) {659    const rpId = e.passkey!.rpId;660    const list = byRpId.get(rpId);661    if (list) list.push(e);662    else byRpId.set(rpId, [e]);663  }664665  for (const [rpId, group] of byRpId) {666    if (group.length === 0) continue;667    group.sort((a, b) => {668      const aT =669        a.passkey!.lastUsedAt ?? a.passkey!.createdAt ?? a.modifiedAt ?? a.createdAt;670      const bT =671        b.passkey!.lastUsedAt ?? b.passkey!.createdAt ?? b.modifiedAt ?? b.createdAt;672      return bT - aT;673    });674    const winner = group[0]!;675676    // Look for a NON-passkey login entry matching this RP. Use the URL677    // hostname rather than a substring search so a "login.foo.com" entry678    // doesn't accidentally absorb a passkey for "foo.com".679    const loginTarget = entries.find((e) => {680      if (e.deletedAt || e.passkey || e.type !== "login") return false;681      if (e.url && extractDomain(e.url) === rpId) return true;682      for (const extra of e.additionalUrls ?? []) {683        if (extractDomain(extra) === rpId) return true;684      }685      return false;686    });687688    if (loginTarget) {689      loginTarget.passkey = winner.passkey;690      loginTarget.modifiedAt = now;691      for (const dup of group) {692        if (!dup.deletedAt) {693          dup.deletedAt = now;694          dup.modifiedAt = now;695        }696      }697      merged = true;698    } else if (group.length > 1) {699      for (let i = 1; i < group.length; i += 1) {700        const dup = group[i]!;701        if (!dup.deletedAt) {702          dup.deletedAt = now;703          dup.modifiedAt = now;704        }705      }706      merged = true;707    }708  }709710  return { merged };711}712713// Exported solely for `unlockFromCodex` below, which needs to verify a714// supplied passphrase against a slotA blob *without* committing anything to715// storage. Keep this internal otherwise — callers crossing the messages.ts716// boundary should always go through `unlock` / `verifyMainPassword` so the717// constant-time invariants in Projects.md §3.4 are not bypassed.718export async function tryDecryptSlot(719  vault: StoredVault,720  key: Uint8Array721): Promise<DecryptedPayload | null> {722  try {723    const plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag);724    return decodePayload(plain);725  } catch {726    return null;727  }728}729730// ---------------------------------------------------------------------------731// Core operations732// ---------------------------------------------------------------------------733734function buildDomainIndexSync(all: VaultEntry[]): void {735  domainIndex = new Map();736737  for (const entry of all) {738    if (entry.deletedAt) continue;739    if (entry.type === "note" || entry.type === "card") continue;740741    // An entry can match multiple sites via `additionalUrls`. Index each742    // hostname so `queryDomain` returns the entry regardless of which alias743    // the user is currently visiting. Dedupe per-entry so a single entry744    // never appears twice in one bucket.745    const domains = new Set<string>();746    const primary = extractDomain(entry.url ?? "");747    if (primary) domains.add(primary);748    for (const extra of entry.additionalUrls ?? []) {749      const d = extractDomain(extra);750      if (d) domains.add(d);751    }752    if (domains.size === 0) continue;753754    for (const domain of domains) {755      const bucket = domainIndex.get(domain) ?? [];756      bucket.push(entry);757      domainIndex.set(domain, bucket);758    }759  }760}761762export async function createVault(password: string): Promise<void> {763  await ensureMigrated();764765  const salt = generateSalt();766  derivedKey = await deriveKey(password, salt);767  entries = [];768  vaultMode = "real";769  duressConfigured = false;770  buildDomainIndexSync(entries);771772  // Generate and wrap the root key for recovery word escrow.773  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =774    await generateAndWrapRootKey();775  rootKey = unhex(rawRootKey);776777  const plaintext = encodePayload(entries, duressConfigured);778  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext);779780  const slotA: StoredVault = {781    version: 1,782    salt: hex(salt),783    nonce,784    ciphertext,785    tag,786    recovery_salt: recoverySalt,787    recovery_wrapped_root_key: wrappedRootKey,788    recovery_nonce: wrappedNonce,789    recovery_tag: wrappedTag,790  };791  await writeSlot(SLOT_A, slotA);792793  // Matching-size noise blob for slot B, so a fresh install shows two794  // similarly-shaped records regardless of whether duress is ever set up.795  await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));796797  touchAutoLock();798}799800export async function hasVault(): Promise<boolean> {801  await ensureMigrated();802  return (await loadSlot(SLOT_A)) !== null;803}804805/**806 * Returns whether the real vault has recorded that a duress passphrase is807 * configured. Reliable only after a real-mode unlock — before unlock or in808 * decoy mode, returns false because we cannot read slot A's plaintext.809 */810export async function isDuressEnabled(): Promise<boolean> {811  return vaultMode === "real" && duressConfigured;812}813814export async function setupDuress(duressPassword: string): Promise<void> {815  if (!derivedKey || vaultMode !== "real") {816    throw new Error("vault must be unlocked in real mode");817  }818  await ensureMigrated();819820  // Encrypt the decoy payload (empty entries) under the duress key. Pad to821  // at least the current slot A ciphertext size so the two slots look the822  // same at rest at setup time.823  const slotA = await loadSlot(SLOT_A);824  if (!slotA) throw new Error("missing slot A");825826  const decoySalt = generateSalt();827  const decoyKey = await deriveKey(duressPassword, decoySalt);828  try {829    // Pad the decoy plaintext to match slot A's ciphertext length (minus the830    // 16-byte tag) so encrypted sizes align exactly.831    const targetBytes = slotA.ciphertext.length / 2;832    let plaintext = encodePayload([], false);833    const encoded = new TextEncoder().encode(plaintext);834    if (encoded.length < targetBytes) {835      plaintext = plaintext + " ".repeat(targetBytes - encoded.length);836    }837    const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext);838    await writeSlot(SLOT_B, {839      version: 1,840      salt: hex(decoySalt),841      nonce,842      ciphertext,843      tag,844    });845  } finally {846    zeroKey(decoyKey);847  }848849  // Re-encrypt slot A with the duressConfigured flag set to true. No external850  // flag is written — the bit lives inside the encrypted envelope.851  duressConfigured = true;852  await persistSlotA();853}854855export async function disableDuress(): Promise<void> {856  if (!derivedKey || vaultMode !== "real") {857    throw new Error("vault must be unlocked in real mode");858  }859  await ensureMigrated();860861  // Overwrite slot B with fresh noise that matches slot A's size. The slot862  // remains occupied so its mere existence does not signal that duress was863  // ever configured.864  const slotA = await loadSlot(SLOT_A);865  if (slotA) {866    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));867  }868869  duressConfigured = false;870  await persistSlotA();871}872873export async function verifyMainPassword(password: string): Promise<boolean> {874  await ensureMigrated();875  const slotA = await loadSlot(SLOT_A);876  if (!slotA) return false;877  const key = await deriveKey(password, unhex(slotA.salt));878  try {879    return (await tryDecryptSlot(slotA, key)) !== null;880  } finally {881    zeroKey(key);882  }883}884885export async function unlock(password: string): Promise<boolean> {886  await ensureMigrated();887888  // Load both slots in parallel. Both always exist post-migration; the889  // parallel load and the parallel derivation below keep wall-clock time890  // constant regardless of which slot's passphrase (real or decoy) the891  // caller supplied, so a timing side channel cannot distinguish the892  // duress path from the real-unlock path (DUR-002).893  const [slotA, slotB] = await Promise.all([894    loadSlot(SLOT_A),895    loadSlot(SLOT_B),896  ]);897898  // Derive both keys in parallel, unconditionally.899  const [keyA, keyB] = await Promise.all([900    slotA ? deriveKey(password, unhex(slotA.salt)) : Promise.resolve(null),901    slotB ? deriveKey(password, unhex(slotB.salt)) : Promise.resolve(null),902  ]);903904  // Attempt both decrypts in parallel.905  const [payloadA, payloadB] = await Promise.all([906    keyA && slotA ? tryDecryptSlot(slotA, keyA) : Promise.resolve(null),907    keyB && slotB ? tryDecryptSlot(slotB, keyB) : Promise.resolve(null),908  ]);909910  if (payloadA && keyA) {911    derivedKey = keyA;912    vaultMode = "real";913    entries = payloadA.entries;914    duressConfigured = payloadA.duressConfigured;915    buildDomainIndexSync(entries);916    await loadSettings();917    touchAutoLock();918    if (keyB) zeroKey(keyB);919920    // slotA is non-null when payloadA is truthy (keyA was derived from slotA).921    if (slotA) {922      const needsRecoverySetup =923        !slotA.recovery_salt || !slotA.recovery_wrapped_root_key;924      if (!needsRecoverySetup) {925        rootKey = await deriveRootKeyFromDerivedKey(926          keyA,927          slotA.recovery_salt!928        );929      }930    }931932    // If the payload had a pre-v2.11.0 shape (legacy passkey type, flat933    // passkey fields, or pre-A-2 created/updated keys), rewrite it now so934    // the next save uses the new format and migration doesn't re-run forever.935    if (payloadA.migratedFromLegacy) {936      await persistSlotA();937    }938    return true;939  }940941  if (payloadB && keyB) {942    derivedKey = keyB;943    vaultMode = "decoy";944    entries = payloadB.entries;945    duressConfigured = false;946    buildDomainIndexSync(entries);947    await loadSettings();948    touchAutoLock();949    if (keyA) zeroKey(keyA);950    return true;951  }952953  if (keyA) zeroKey(keyA);954  if (keyB) zeroKey(keyB);955  return false;956}957958export function lock(): void {959  if (derivedKey) {960    zeroKey(derivedKey);961    derivedKey = null;962  }963  if (rootKey) {964    rootKey.fill(0);965    rootKey = null;966  }967968  entries = [];969  domainIndex = new Map();970  vaultMode = "real";971  duressConfigured = false;972  clearAutoLock();973}974975export function isUnlocked(): boolean {976  return derivedKey !== null;977}978979// Opens the vault using a pre-derived AES-256 key (skipping Argon2id).980// Used by Android biometric unlock — the key was derived on the native side.981export async function unlockWithKey(982  masterKeyHex: string,983): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {984  try {985    const masterKeyBytes = unhex(masterKeyHex);986    const stored = await loadSlot(SLOT_A);987    if (!stored) return { ok: false, error: "invalid_key" };988    const payload = await tryDecryptSlot(stored, masterKeyBytes);989    if (!payload) return { ok: false, error: "invalid_key" };990991    derivedKey = masterKeyBytes;992    vaultMode = "real";993    entries = payload.entries;994    duressConfigured = payload.duressConfigured;995    buildDomainIndexSync(entries);996    await loadSettings();997    touchAutoLock();998    return { ok: true, entries };999  } catch {1000    return { ok: false, error: "invalid_key" };1001  }1002}10031004/**1005 * Restore the vault from a parsed Peach Codex payload.1006 *1007 * The supplied passphrase is verified against the Codex's slotA *before* any1008 * storage mutation — wrong passphrases return without touching disk. On1009 * success, the current vault state is snapshotted (reason: "restore") so the1010 * user can revert via Settings -> Vault History, then slotA/slotB are written1011 * and `peach_last_modified_at` is set to the Codex's recorded timestamp. A1012 * regular `unlock()` follows so the rest of the SW sees the standard1013 * post-unlock state.1014 *1015 * Intentionally non-Pro-gated — see peach_codex_v2.md "Pro gating". A Codex1016 * printed by a Pro user must always be restorable, even on a free device.1017 *1018 * Timing is not held constant here (in contrast to `unlock`): the Codex flow1019 * is an explicit user action with a known passphrase, not a passive lock1020 * screen, so the duress-vs-real timing side channel does not apply.1021 */1022export async function unlockFromCodex(params: {1023  slotA: string; // JSON string of StoredVault for slot A1024  slotB: string | null; // JSON string of StoredVault for slot B, or null1025  timestamp: number;1026  masterPassphrase: string;1027}): Promise<1028  | { ok: true; entryCount: number }1029  | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" }1030> {1031  let parsedSlotA: StoredVault;1032  let parsedSlotB: StoredVault | null = null;1033  try {1034    parsedSlotA = JSON.parse(params.slotA) as StoredVault;1035    if (params.slotB !== null) {1036      parsedSlotB = JSON.parse(params.slotB) as StoredVault;1037    }1038    // Minimal structural validation — the decrypt step below catches deeper1039    // corruption, but bail early on obviously-bad shapes so we don't reach1040    // storage with junk.1041    if (1042      typeof parsedSlotA?.salt !== "string" ||1043      typeof parsedSlotA?.nonce !== "string" ||1044      typeof parsedSlotA?.ciphertext !== "string" ||1045      typeof parsedSlotA?.tag !== "string"1046    ) {1047      return { ok: false, reason: "invalid_slot_format" };1048    }1049  } catch {1050    return { ok: false, reason: "invalid_slot_format" };1051  }10521053  // Verify the passphrase against the supplied slotA WITHOUT writing anything.1054  // If this fails the on-disk vault is left completely untouched.1055  const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));1056  const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey);1057  if (!trialPayload) {1058    zeroKey(trialKey);1059    return { ok: false, reason: "wrong_passphrase" };1060  }1061  // Drop the trial key; `unlock()` below derives its own copy. Holding two1062  // copies of the master key in memory at once would be a needless surface.1063  zeroKey(trialKey);10641065  // Snapshot the about-to-be-overwritten on-disk state so the user can revert1066  // a mistaken Codex restore via the Vault History UI. Non-fatal if it fails.1067  await takeVaultSnapshot("restore");10681069  await writeSlot(SLOT_A, parsedSlotA);1070  if (parsedSlotB) {1071    await writeSlot(SLOT_B, parsedSlotB);1072  } else {1073    // Slot B must always exist with ciphertext length matching slot A1074    // (Projects.md §3.2). Codex prints may omit slot B (duress wasn't1075    // configured); regenerate noise to satisfy the invariant.1076    await writeSlot(1077      SLOT_B,1078      generateNoiseBlob(parsedSlotA.ciphertext.length / 2),1079    );1080  }1081  await chrome.storage.local.set({1082    peach_last_modified_at: String(params.timestamp),1083  });10841085  // Standard unlock path so domain index, settings, auto-lock, and1086  // recovery-key state all populate exactly as a normal unlock would.1087  const ok = await unlock(params.masterPassphrase);1088  if (!ok) {1089    // Should be unreachable — we just verified the passphrase against the1090    // same slotA we wrote. Treat as wrong_passphrase to keep the contract1091    // simple if some race or storage anomaly intrudes.1092    return { ok: false, reason: "wrong_passphrase" };1093  }1094  return { ok: true, entryCount: getEntries().length };1095}10961097// Returns the current in-memory derived key as a hex string.1098// Used by the biometric enable flow in Settings to store the key in Android Keystore.1099export function getDerivedKeyHex(): string {1100  if (!derivedKey) throw new Error("vault_not_unlocked");1101  return hex(derivedKey);1102}11031104export function getEntries(): VaultEntry[] {1105  if (!derivedKey) throw new Error("vault locked");1106  return entries.filter((entry) => !entry.deletedAt);1107}11081109const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;11101111export function getIdentities(): SavedIdentity[] {1112  if (!derivedKey) throw new Error("vault locked");1113  const active = entries.filter((e) => !e.deletedAt && e.type === "login");11141115  const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();1116  const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();11171118  for (const entry of active) {1119    const value = entry.username?.trim();1120    if (!value) continue;1121    const map = EMAIL_RE.test(value) ? emailMap : usernameMap;1122    const existing = map.get(value);1123    const domain = extractDomain(entry.url ?? "") ?? "";1124    const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;1125    if (!existing || modifiedAt > existing.lastUsed) {1126      map.set(value, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });1127    } else {1128      map.set(value, { ...existing, count: existing.count + 1 });1129    }1130  }11311132  const toIdentity = (type: "email" | "username") =>1133    ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({1134      value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,1135    });11361137  return [1138    ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),1139    ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),1140  ];1141}11421143export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {1144  if (!derivedKey) throw new Error("vault locked");11451146  const now = Date.now();1147  const added: VaultEntry[] = [];1148  for (const draft of drafts) {1149    try {1150      const sanitized = sanitizeEntryDraft(draft);1151      const nextEntry: VaultEntry = {1152        ...sanitized,1153        id: crypto.randomUUID(),1154        createdAt: now,1155        modifiedAt: now,1156      };1157      entries.push(nextEntry);1158      added.push(nextEntry);1159    } catch {1160      // Skip invalid drafts silently — caller can see diff between input and output length1161    }1162  }11631164  if (added.length > 0) {1165    await persistEntries();1166  }11671168  return added;1169}11701171/**1172 * Restore a set of entries in full fidelity — preserves id, createdAt,1173 * modifiedAt, and every other field unlike `batchAddEntries` which1174 * assigns fresh identity. Used by restore paths where the backup is the1175 * authoritative source of truth. `mode` controls how entries already in1176 * the vault are treated.1177 */1178export async function restoreEntries(1179  incoming: VaultEntry[],1180  mode: "replace" | "merge"1181): Promise<{ added: number; updated: number; skipped: number }> {1182  if (!derivedKey) throw new Error("vault locked");11831184  // A replace with zero incoming entries is almost certainly a caller bug1185  // (e.g. an import that silently dropped everything). Refuse rather than1186  // wipe the vault.1187  if (mode === "replace" && incoming.length === 0) {1188    throw new Error("refuse to replace with empty entry set");1189  }11901191  let added = 0;1192  let updated = 0;1193  let skipped = 0;11941195  if (mode === "replace") {1196    entries = [];1197    for (const entry of incoming) {1198      const normalized = sanitizeRestoredEntry(entry);1199      if (!normalized) {1200        skipped += 1;1201        continue;1202      }1203      entries.push(normalized);1204      added += 1;1205    }1206  } else {1207    const byId = new Map<string, VaultEntry>();1208    for (const e of entries) byId.set(e.id, e);12091210    for (const entry of incoming) {1211      const normalized = sanitizeRestoredEntry(entry);1212      if (!normalized) {1213        skipped += 1;1214        continue;1215      }1216      const existing = byId.get(normalized.id);1217      if (!existing) {1218        entries.push(normalized);1219        added += 1;1220      } else if (normalized.modifiedAt > existing.modifiedAt) {1221        const idx = entries.findIndex((e) => e.id === existing.id);1222        if (idx !== -1) {1223          entries[idx] = normalized;1224          updated += 1;1225        }1226      } else {1227        skipped += 1;1228      }1229    }1230  }12311232  await persistEntries("import");1233  return { added, updated, skipped };1234}12351236/**1237 * Validate + normalise a VaultEntry coming from a backup. Accepts1238 * anything structurally sound; keeps all metadata verbatim. Returns1239 * null for values the live vault shouldn't accept (e.g., missing title).1240 */1241function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {1242  if (!entry || typeof entry !== "object") return null;1243  const title = typeof entry.title === "string" ? entry.title.trim() : "";1244  if (!title) return null;1245  const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();1246  const now = Date.now();1247  const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;1248  const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;12491250  // Migrate legacy passkey shape on import (same logic as on-disk read).1251  // Imports from pre-v2.11.0 vault backups still carry type:"passkey" with1252  // flat fields; bring them into the new shape immediately.1253  const migrated: VaultEntry = migrateLegacyPasskey(1254    {1255      ...entry,1256      id,1257      title,1258      type: entry.type ?? "login",1259      createdAt,1260      modifiedAt,1261    },1262    entry1263  );12641265  // Login entries from backup must carry a password (or be passkey-only,1266  // in which case the passkey sub-object replaces the password requirement).1267  if (1268    migrated.type === "login" &&1269    !migrated.passkey &&1270    typeof migrated.password !== "string"1271  ) {1272    return null;1273  }1274  if (migrated.passkey && !migrated.passkey.credentialId) {1275    return null;1276  }12771278  return migrated;1279}12801281// Soft-deletes every non-deleted entry in one call. The literal string1282// argument is a tripwire against accidental calls — any caller that would1283// wipe the vault has to consciously type "REPLACE_ALL". Do not relax this1284// to a boolean.1285export async function clearVaultEntries(1286  confirmation: "REPLACE_ALL"1287): Promise<void> {1288  if (confirmation !== "REPLACE_ALL") {1289    throw new Error("clearVaultEntries requires explicit confirmation");1290  }1291  if (!derivedKey) throw new Error("vault locked");1292  for (const entry of entries) {1293    if (!entry.deletedAt) {1294      entry.deletedAt = Date.now();1295      entry.modifiedAt = Date.now();1296    }1297  }1298  await persistEntries();1299}13001301export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {1302  if (!derivedKey) throw new Error("vault locked");13031304  const sanitized = sanitizeEntryDraft(entry);1305  const now = Date.now();1306  const nextEntry: VaultEntry = {1307    ...sanitized,1308    id: crypto.randomUUID(),1309    createdAt: now,1310    modifiedAt: now,1311    // Stamp passwordChangedAt at creation so age tracking is accurate from1312    // day one. Non-login entries carry the same stamp harmlessly.1313    passwordChangedAt: sanitized.password ? now : undefined,1314  };13151316  entries.push(nextEntry);1317  await persistEntries();13181319  // Fire-and-forget breach check (only for login entries if breach monitoring is enabled or not set)1320  if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {1321    checkBreach(nextEntry.password).then(async (count) => {1322      if (count > 0) {1323        const idx = entries.findIndex((e) => e.id === nextEntry.id);1324        if (idx !== -1) {1325          entries[idx] = { ...entries[idx], breach: count, modifiedAt: Date.now() };1326          await persistEntries();1327        }1328      }1329    });1330  }13311332  return nextEntry;1333}13341335export async function updateEntry(1336  id: string,1337  patch: Partial<VaultEntry>1338): Promise<void> {1339  if (!derivedKey) throw new Error("vault locked");13401341  const idx = entries.findIndex((entry) => entry.id === id);1342  if (idx === -1 || entries[idx].deletedAt) {1343    throw new Error("entry not found");1344  }13451346  const current = entries[idx];1347  const sanitizedPatch = sanitizeEntryPatch(patch);1348  // Refresh passwordChangedAt only when the password value actually changes —1349  // a metadata-only update (title, tags, etc.) must not reset the age clock1350  // that drives the Pro health rotation recommendation.1351  const passwordChanged =1352    "password" in patch &&1353    typeof sanitizedPatch.password === "string" &&1354    sanitizedPatch.password !== current.password;1355  entries[idx] = {1356    ...current,1357    ...sanitizedPatch,1358    modifiedAt: Date.now(),1359    ...(passwordChanged ? { passwordChangedAt: Date.now() } : {}),1360  };13611362  // A login entry must carry SOMETHING fillable — either a password or a1363  // passkey credential. An empty-password login with no passkey is dead1364  // state. Permit the password-clear when a passkey is attached (that's1365  // the legitimate "drop the password, keep the passkey" path).1366  if (1367    entries[idx].type === "login" &&1368    !entries[idx].password &&1369    !entries[idx].passkey1370  ) {1371    entries[idx] = current;1372    throw new Error("password or passkey required");1373  }13741375  // Card entries must retain their card number1376  if (entries[idx].type === "card" && !entries[idx].cardNumber) {1377    entries[idx] = current;1378    throw new Error("card number is required for card entries");1379  }13801381  await persistEntries();13821383  // Breach check when password changes: clear immediately so old breach doesn't linger,1384  // then async-check the new password and only re-set if it's also found.1385  if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {1386    entries[idx] = { ...entries[idx], breach: undefined };1387    await persistEntries();1388    const password = entries[idx].password;1389    if (password) {1390      checkBreach(password).then(async (count) => {1391        const i = entries.findIndex((e) => e.id === id);1392        if (i !== -1 && count > 0) {1393          entries[i] = { ...entries[i], breach: count, modifiedAt: Date.now() };1394          await persistEntries();1395        }1396      });1397    }1398  }1399}14001401export async function deleteEntry(id: string): Promise<void> {1402  if (!derivedKey) throw new Error("vault locked");14031404  const entry = entries.find((item) => item.id === id);1405  if (!entry || entry.deletedAt) {1406    throw new Error("entry not found");1407  }14081409  entry.deletedAt = Date.now();1410  entry.modifiedAt = Date.now();1411  await persistEntries();1412}14131414export function getDeletedEntries(): VaultEntry[] {1415  if (!derivedKey) return [];1416  return entries.filter((e) => !!e.deletedAt);1417}14181419export async function restoreEntry(id: string): Promise<void> {1420  if (!derivedKey) throw new Error("vault locked");1421  const entry = entries.find((e) => e.id === id && e.deletedAt);1422  if (!entry) throw new Error("deleted entry not found");1423  delete entry.deletedAt;1424  entry.modifiedAt = Date.now();1425  await persistEntries();1426  buildDomainIndexSync(entries);1427}14281429export async function purgeEntry(id: string): Promise<void> {1430  if (!derivedKey) throw new Error("vault locked");1431  const idx = entries.findIndex((e) => e.id === id && e.deletedAt);1432  if (idx === -1) throw new Error("deleted entry not found");1433  entries.splice(idx, 1);1434  await persistEntries();1435}14361437/** Permanently delete entries whose deletedAt is older than retentionMs. 0 = keep forever. */1438export async function purgeExpiredTrash(retentionMs: number): Promise<number> {1439  if (!derivedKey || retentionMs === 0) return 0;1440  const cutoff = Date.now() - retentionMs;1441  const before = entries.length;1442  entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));1443  const purged = before - entries.length;1444  if (purged > 0) await persistEntries();1445  return purged;1446}14471448export function queryDomain(domain: string): VaultEntry[] {1449  return domainIndex.get(domain) ?? [];1450}14511452export function getEntryById(id: string): VaultEntry | undefined {1453  return entries.find((entry) => entry.id === id && !entry.deletedAt);1454}14551456async function persistSlotA(1457  reason: VaultSnapshot["reason"] = "local_save",1458): Promise<StoredVault> {1459  if (!derivedKey) throw new Error("vault locked");14601461  const slotA = await loadSlot(SLOT_A);1462  if (!slotA) throw new Error("missing slot A");14631464  // Snapshot the about-to-be-overwritten state BEFORE we mutate disk. Failures1465  // are swallowed by takeVaultSnapshot — history must never block a save.1466  await takeVaultSnapshot(reason);14671468  const plaintext = encodePayload(entries, duressConfigured);1469  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext);14701471  // Preserve existing recovery escrow fields.1472  const nextSlotA: StoredVault = {1473    ...slotA,1474    nonce,1475    ciphertext,1476    tag,1477    // recovery_salt and recovery_wrapped_root_key are already set from loadSlot1478  };1479  await writeSlot(SLOT_A, nextSlotA);14801481  // When duress is not configured, keep slot B size-matched with slot A by1482  // regenerating its noise. When duress IS configured, leave slot B alone —1483  // we don't have the decoy key to re-encrypt it. This is a known trade-off.1484  if (!duressConfigured) {1485    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));1486  }14871488  return nextSlotA;1489}14901491async function persistSlotB(): Promise<void> {1492  if (!derivedKey) throw new Error("vault locked");14931494  const slotB = await loadSlot(SLOT_B);1495  if (!slotB) throw new Error("missing slot B");14961497  // Decoy plaintext always reports duressConfigured=false — the decoy user1498  // sees a clean slate.1499  const plaintext = encodePayload(entries, false);1500  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext);15011502  await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });1503}15041505async function persistEntries(1506  reason: VaultSnapshot["reason"] = "local_save",1507): Promise<void> {1508  if (!derivedKey) throw new Error("vault locked");15091510  if (vaultMode === "decoy") {1511    await persistSlotB();1512  } else {1513    await persistSlotA(reason);1514  }1515  buildDomainIndexSync(entries);1516}15171518function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {1519  if (!Array.isArray(values)) return undefined;1520  const seen = new Set<string>();1521  const cleaned: string[] = [];1522  for (const value of values) {1523    const trimmed = typeof value === "string" ? value.trim() : "";1524    if (!trimmed) continue;1525    const key = trimmed.toLowerCase();1526    if (seen.has(key)) continue;1527    seen.add(key);1528    cleaned.push(trimmed);1529  }1530  return cleaned.length > 0 ? cleaned : undefined;1531}15321533function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {1534  const title = entry.title.trim();1535  // Accept legacy `type:"passkey"` drafts but rewrite to "login" — the new1536  // model is "any entry, optionally with a passkey sub-object." Imports and1537  // any in-flight callers from before v2.11.0 keep working without throwing.1538  let type: VaultEntry["type"] = entry.type ?? "login";1539  if (type === "passkey") type = "login";15401541  if (!title) throw new Error("title is required");1542  // A login entry needs either a password or a passkey credential to be useful.1543  // Passkey-only entries (passkey present, no password) are valid.1544  if (type === "login" && !entry.password?.trim() && !entry.passkey) {1545    throw new Error("password or passkey required");1546  }1547  if (entry.passkey) {1548    const p = entry.passkey;1549    if (1550      !p.rpId ||1551      !p.credentialId ||1552      !p.publicKeyCose ||1553      !p.userHandle ||1554      !p.userName ||1555      (p.algorithm !== -7 && p.algorithm !== -8)1556    ) {1557      throw new Error("invalid passkey credential");1558    }1559  }1560  if (type === "card") {1561    if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {1562      throw new Error("cardholder name and card number are required");1563    }1564  }15651566  return {1567    type,1568    title,1569    username: type === "login" ? entry.username?.trim() ?? "" : undefined,1570    password: type === "login" ? entry.password : undefined,1571    url: type === "login" ? entry.url?.trim() ?? "" : undefined,1572    additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,1573    totp: type === "login" ? entry.totp?.trim() || undefined : undefined,1574    notes: entry.notes?.trim() || undefined,1575    breach: type === "login" ? entry.breach : undefined,1576    canary: type === "login" ? entry.canary : undefined,1577    tags: entry.tags,1578    passkey: entry.passkey,1579    cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,1580    cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,1581    expMonth: type === "card" ? entry.expMonth?.trim() : undefined,1582    expYear: type === "card" ? entry.expYear?.trim() : undefined,1583    cvc: type === "card" ? entry.cvc?.trim() : undefined,1584    cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,1585    network: type === "card" ? entry.network : undefined,1586    last4: type === "card" ? entry.last4?.trim() : undefined,1587  };1588}15891590function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {1591  const nextPatch: Partial<VaultEntry> = {};15921593  if ("type" in patch) {1594    nextPatch.type = patch.type;1595  }15961597  if ("title" in patch) {1598    const title = patch.title?.trim() ?? "";1599    if (!title) throw new Error("title is required");1600    nextPatch.title = title;1601  }16021603  if ("url" in patch) {1604    nextPatch.url = patch.url?.trim() ?? "";1605  }16061607  if ("additionalUrls" in patch) {1608    const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];1609    const seen = new Set<string>();1610    const cleaned: string[] = [];1611    for (const value of incoming) {1612      const trimmed = typeof value === "string" ? value.trim() : "";1613      if (!trimmed) continue;1614      const key = trimmed.toLowerCase();1615      if (seen.has(key)) continue;1616      seen.add(key);1617      cleaned.push(trimmed);1618    }1619    nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;1620  }16211622  if ("username" in patch) {1623    nextPatch.username = patch.username?.trim() ?? "";1624  }16251626  if ("email" in patch) {1627    nextPatch.email = patch.email?.trim() || undefined;1628  }16291630  if ("password" in patch) {1631    const password = patch.password ?? "";1632    // Allow clearing a password (e.g. on passkey-only entries)1633    nextPatch.password = password || undefined;1634  }16351636  if ("totp" in patch) {1637    nextPatch.totp = patch.totp?.trim() || undefined;1638  }16391640  if ("notes" in patch) {1641    nextPatch.notes = patch.notes?.trim() || undefined;1642  }16431644  if ("breach" in patch) {1645    nextPatch.breach = patch.breach;1646  }16471648  if ("canary" in patch) {1649    nextPatch.canary = patch.canary;1650  }16511652  if ("passkey" in patch) {1653    // Passkey sub-object replaces all the legacy flat passkey fields. A1654    // patch with `passkey: undefined` removes the credential from the entry1655    // (used by "remove passkey" without deleting the whole entry).1656    nextPatch.passkey = patch.passkey;1657  }16581659  if ("tags" in patch) {1660    nextPatch.tags = patch.tags;1661  }16621663  if ("cardholderName" in patch) {1664    nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;1665  }1666  if ("cardNumber" in patch) {1667    const n = patch.cardNumber ?? "";1668    nextPatch.cardNumber = n || undefined;1669  }1670  if ("expMonth" in patch) {1671    nextPatch.expMonth = patch.expMonth?.trim() || undefined;1672  }1673  if ("expYear" in patch) {1674    nextPatch.expYear = patch.expYear?.trim() || undefined;1675  }1676  if ("cvc" in patch) {1677    nextPatch.cvc = patch.cvc?.trim() || undefined;1678  }1679  if ("cardNickname" in patch) {1680    nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;1681  }1682  if ("network" in patch) {1683    nextPatch.network = patch.network;1684  }1685  if ("last4" in patch) {1686    nextPatch.last4 = patch.last4?.trim() || undefined;1687  }16881689  return nextPatch;1690}16911692function normalizeEntry(entry: VaultEntry | LegacyVaultEntry): VaultEntry {1693  const createdAt = "createdAt" in entry ? entry.createdAt : entry.created;1694  const modifiedAt =1695    "modifiedAt" in entry ? entry.modifiedAt : entry.updated;16961697  const base: VaultEntry = {1698    id: entry.id,1699    type: "type" in entry ? entry.type : "login",1700    title: entry.title,1701    username: entry.username,1702    password: entry.password,1703    url: entry.url,1704    totp: entry.totp,1705    notes: entry.notes,1706    breach: entry.breach,1707    canary: "canary" in entry ? entry.canary : undefined,1708    passkey: "passkey" in entry ? entry.passkey : undefined,1709    createdAt,1710    modifiedAt,1711    deletedAt: entry.deletedAt,1712    tags: "tags" in entry ? entry.tags : undefined,1713    cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,1714    cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,1715    expMonth: "expMonth" in entry ? entry.expMonth : undefined,1716    expYear: "expYear" in entry ? entry.expYear : undefined,1717    cvc: "cvc" in entry ? entry.cvc : undefined,1718    cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,1719    network: "network" in entry ? entry.network : undefined,1720    last4: "last4" in entry ? entry.last4 : undefined,1721  };17221723  return migrateLegacyPasskey(base, entry);1724}17251726/**1727 * v2.11.0 read migration. Pre-v2.11.0 passkey entries used `type:"passkey"`1728 * with flat top-level fields (rpId, credentialId, etc.). This converts them1729 * to the new shape — `type:"login"` with a `passkey` sub-object — so all1730 * downstream consumers can rely on the new model. The result is rewritten1731 * to disk on next vault save (hasLegacyShape detects the un-migrated case).1732 */1733function migrateLegacyPasskey(1734  base: VaultEntry,1735  raw: VaultEntry | LegacyVaultEntry1736): VaultEntry {1737  if (base.passkey) return base;1738  const flat = raw as Partial<VaultEntry>;1739  const isPasskeyType = base.type === "passkey";1740  const hasFlatPasskeyFields =1741    typeof flat.rpId === "string" &&1742    typeof flat.credentialId === "string" &&1743    typeof flat.publicKeyCose === "string" &&1744    typeof flat.userHandle === "string" &&1745    typeof flat.userName === "string";1746  if (!isPasskeyType && !hasFlatPasskeyFields) return base;1747  if (!hasFlatPasskeyFields) return base;17481749  const algorithm: -7 | -8 = flat.algorithm === -8 ? -8 : -7;1750  base.passkey = {1751    rpId: flat.rpId!,1752    rpName: flat.rpName ?? flat.rpId!,1753    credentialId: flat.credentialId!,1754    publicKeyCose: flat.publicKeyCose!,1755    privateKeyJwk: flat.privateKeyJwk,1756    userHandle: flat.userHandle!,1757    userName: flat.userName!,1758    userDisplayName: flat.userDisplayName ?? flat.userName!,1759    algorithm,1760    signCount: flat.signCount ?? 0,1761    aaguid: flat.aaguid ?? "",1762    backupEligible: flat.backupEligible === true,1763    backupState: flat.backupState === true,1764    lastUsedAt: flat.lastUsedAt,1765    browser: flat.browser,1766    transports: flat.transports,1767    createdAt: base.createdAt,1768  };1769  // Promote to "login" so the unified Entry view renders. Username gets1770  // populated from the passkey's userName so the entry is searchable in the1771  // existing autofill flow without a separate code path.1772  if (isPasskeyType) base.type = "login";1773  if (!base.username) base.username = flat.userName;1774  if (!base.url) base.url = `https://${flat.rpId}`;1775  return base;1776}177717781779// ---------------------------------------------------------------------------1780// Deduplication1781// ---------------------------------------------------------------------------17821783function entryDupeKey(e: VaultEntry): string {1784  if (e.type === "note") return `note|${e.title.toLowerCase()}`;1785  // Passkey-bearing entries dedupe by the credential's RP + user. Two logins1786  // on different sites that happen to share a username are still distinct;1787  // two passkey credentials for the same RP+user are duplicates regardless1788  // of any login fields they may also carry.1789  if (e.passkey) {1790    return `passkey|${e.passkey.rpId.toLowerCase()}|${e.passkey.userName.toLowerCase()}`;1791  }1792  return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;1793}17941795/** Returns the number of duplicate entries (those that would be removed). */1796export function countDuplicates(): number {1797  const best = new Map<string, VaultEntry>();1798  let dupeCount = 0;1799  for (const e of entries.filter((e) => !e.deletedAt)) {1800    const key = entryDupeKey(e);1801    const existing = best.get(key);1802    if (!existing) {1803      best.set(key, e);1804    } else {1805      dupeCount++;1806      // Keep the more recently modified one in the map1807      if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {1808        best.set(key, e);1809      }1810    }1811  }1812  return dupeCount;1813}18141815/**1816 * Soft-deletes duplicate entries, keeping the most recently modified copy of1817 * each group. Returns the number of entries moved to trash.1818 */1819export async function deduplicateEntries(): Promise<number> {1820  if (!derivedKey) throw new Error("vault locked");1821  // Dedup reshapes slot B permanently under the decoy key, which is1822  // forensically distinguishable from a freshly-seeded decoy vault. Refuse.1823  if (vaultMode === "decoy") {1824    throw new Error("deduplicate disabled in decoy mode");1825  }18261827  const best = new Map<string, VaultEntry>();1828  for (const e of entries.filter((en) => !en.deletedAt)) {1829    const key = entryDupeKey(e);1830    const existing = best.get(key);1831    if (!existing) {1832      best.set(key, e);1833    } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {1834      best.set(key, e);1835    }1836  }18371838  const keepIds = new Set(Array.from(best.values()).map((e) => e.id));1839  const now = Date.now();1840  let removed = 0;1841  entries = entries.map((e) => {1842    if (!e.deletedAt && !keepIds.has(e.id)) {1843      removed++;1844      return { ...e, deletedAt: now };1845    }1846    return e;1847  });18481849  if (removed > 0) await persistEntries();1850  return removed;1851}18521853// ---------------------------------------------------------------------------1854// Vault history — snapshot BEFORE every vault write so the saved blob is1855// what is about to be lost, not what was just written. Capped at 10. The1856// stored blobs are AES-256-GCM ciphertext under the master password, so1857// history adds zero security surface.1858// ---------------------------------------------------------------------------18591860const HISTORY_KEY = "peach_vault_history";1861const HISTORY_MAX = 10;18621863/**1864 * Snapshot the CURRENT on-disk vault state into history. Call this BEFORE1865 * overwriting peach_vault_a so the saved blob captures the about-to-be-lost1866 * state. Identical-to-most-recent blobs are skipped to avoid filling history1867 * with no-op writes.1868 */1869export async function takeVaultSnapshot(1870  reason: VaultSnapshot["reason"],1871): Promise<void> {1872  try {1873    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);1874    const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];1875    const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];18761877    // Nothing to snapshot if the real slot doesn't exist yet (fresh install,1878    // pre-createVault). createVault skips snapshots intentionally — there is1879    // no prior state to preserve.1880    if (!slotA) return;18811882    const vault_a = JSON.stringify(slotA);1883    const vault_b = JSON.stringify(slotB ?? slotA);18841885    // Best-effort entry count: only meaningful when the in-memory state is1886    // unlocked AND in real mode. Decoy mode would leak the decoy entry1887    // count; locked mode has no entries to count. Both fall through to null.1888    let entryCount: number | null = null;1889    if (derivedKey && vaultMode === "real") {1890      try {1891        entryCount = entries.filter((e) => !e.deletedAt).length;1892      } catch {1893        entryCount = null;1894      }1895    }18961897    const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];1898    const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)1899      ? existingRaw1900      : { snapshots: [] };19011902    // Deduplication: if the most recent snapshot has byte-identical blobs,1903    // skip — saves the same vault N times in a row would otherwise burn the1904    // entire history window with no recovery value.1905    const latest = history.snapshots[0];1906    if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {1907      return;1908    }19091910    const snapshot: VaultSnapshot = {1911      id: crypto.randomUUID(),1912      savedAt: Date.now(),1913      reason,1914      vault_a,1915      vault_b,1916      entryCount,1917    };19181919    history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);1920    await chrome.storage.local.set({ [HISTORY_KEY]: history });1921  } catch {1922    // Non-fatal — history must never block a save. A failed snapshot just1923    // means the user loses one rung of the safety ladder for this write.1924  }1925}19261927/** Wipe all vault history. Called by Panic / DESTROY_VAULT. */1928export async function clearVaultHistory(): Promise<void> {1929  try {1930    await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });1931  } catch {1932    // Non-fatal — DESTROY_VAULT also runs storage.local.clear().1933  }1934}19351936/** Read all snapshots, newest first, for the Settings vault history view. */1937export async function getVaultHistory(): Promise<VaultSnapshot[]> {1938  const raw = await chrome.storage.local.get(HISTORY_KEY);1939  const history = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];1940  if (!history || !Array.isArray(history.snapshots)) return [];1941  return history.snapshots;1942}19431944/**1945 * Replace the on-disk vault with the chosen snapshot's blobs and lock the1946 * vault. The current state is itself snapshotted with reason 'restore' first1947 * so the restore is reversible. After this returns, the user must unlock1948 * with the password that matches the restored blob.1949 */1950export async function restoreVaultSnapshot(1951  snapshotId: string,1952): Promise<{ ok: true } | { ok: false; error: string }> {1953  const history = await getVaultHistory();1954  const snapshot = history.find((s) => s.id === snapshotId);1955  if (!snapshot) return { ok: false, error: "snapshot_not_found" };19561957  // Snapshot the about-to-be-replaced current state so the restore is1958  // reversible. takeVaultSnapshot is no-op when the most recent entry is1959  // byte-identical, so a restore-of-a-restore stays clean.1960  await takeVaultSnapshot("restore");19611962  let restoredA: StoredVault;1963  let restoredB: StoredVault;1964  try {1965    restoredA = JSON.parse(snapshot.vault_a) as StoredVault;1966    restoredB = JSON.parse(snapshot.vault_b) as StoredVault;1967  } catch {1968    return { ok: false, error: "snapshot_corrupt" };1969  }19701971  await writeSlot(SLOT_A, restoredA);1972  await writeSlot(SLOT_B, restoredB);19731974  // Lock so the user must prove they can decrypt the restored blob. If they1975  // restored a pre-password-change snapshot they discover it immediately at1976  // the lock screen rather than silently holding an inaccessible vault.1977  lock();19781979  return { ok: true };1980}19811982/**1983 * Change the master password. Re-encrypts slot A with a fresh salt + new1984 * derived key. Slot B (duress or noise) is left untouched when duress is1985 * configured — it uses an independent key derived from the duress password —1986 * and regenerated as noise when duress is not configured.1987 */1988export async function changePassword(1989  currentPassword: string,1990  newPassword: string1991): Promise<boolean> {1992  if (!derivedKey || vaultMode !== "real") return false;19931994  // Verify current password before allowing any change1995  const valid = await verifyMainPassword(currentPassword);1996  if (!valid) return false;19971998  const slotA = await loadSlot(SLOT_A);1999  if (!slotA) return false;20002001  // Derive fresh key from new password + new random salt2002  const newSalt = generateSalt();2003  const newKey = await deriveKey(newPassword, newSalt);20042005  // Re-encrypt the in-memory entries with the new key2006  const plaintext = encodePayload(entries, duressConfigured);2007  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext);20082009  const freshSlotA: StoredVault = {2010    ...slotA,2011    salt: hex(newSalt),2012    nonce,2013    ciphertext,2014    tag,2015  };2016  // Snapshot the OLD-key blob before overwriting it. If the user later2017  // restores from this snapshot they will need the OLD password — the2018  // post-restore lock surfaces that immediately.2019  await takeVaultSnapshot("local_save");2020  await writeSlot(SLOT_A, freshSlotA);20212022  // Swap the in-memory key synchronously before any further await. If we2023  // threw between the Slot A write and this swap, the next persistEntries()2024  // would overwrite Slot A with old-key ciphertext, locking the user out.2025  zeroKey(derivedKey);2026  derivedKey = newKey;20272028  // Rotate the root key so the old recovery words are immediately invalidated.2029  // After this point getRecoveryWords() returns a fresh 12-word set.2030  const {2031    rawRootKey: freshRawKey,2032    recoverySalt: freshSalt,2033    wrappedRootKey: freshWrapped,2034    wrappedNonce: freshNonce,2035    wrappedTag: freshTag,2036  } = await generateAndWrapRootKey();2037  rootKey = unhex(freshRawKey);2038  const slotAfterRekey = await loadSlot(SLOT_A);2039  if (slotAfterRekey) {2040    await writeSlot(SLOT_A, {2041      ...slotAfterRekey,2042      recovery_salt: freshSalt,2043      recovery_wrapped_root_key: freshWrapped,2044      recovery_nonce: freshNonce,2045      recovery_tag: freshTag,2046    });2047  }20482049  // Regenerate noise for slot B when duress is not in use. Runs after the2050  // key swap so a failure here is a disposable noise regeneration, not a2051  // lockout.2052  if (!duressConfigured) {2053    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));2054  }20552056  return true;2057}20582059// ---------------------------------------------------------------------------2060// Sync helpers2061// ---------------------------------------------------------------------------20622063export async function getVaultBlobForSync(): Promise<{2064  blob: string;2065  timestamp: number;2066  license?: string;2067} | null> {2068  const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, 'peach_last_modified_at', 'peach_license']);2069  const slotA = (raw as Record<string, unknown>)[SLOT_A];2070  if (!slotA) return null;2071  const slotB = (raw as Record<string, unknown>)[SLOT_B];2072  const blob = JSON.stringify({ a: slotA, b: slotB });2073  const rawTs = (raw as Record<string, unknown>)['peach_last_modified_at'];2074  const timestamp = typeof rawTs === 'string' ? parseInt(rawTs) : 0;2075  const license = (raw as Record<string, unknown>)['peach_license'];2076  return {2077    blob,2078    timestamp,2079    license: typeof license === 'string' ? license : undefined,2080  };2081}20822083export async function applyIncomingVault(2084  blobJson: string,2085  remoteTimestamp: number,2086  remoteLicense?: string,2087): Promise<boolean> {2088  const raw = await chrome.storage.local.get('peach_last_modified_at');2089  const rawTs = (raw as Record<string, unknown>)['peach_last_modified_at'];2090  const localTimestamp = typeof rawTs === 'string' ? parseInt(rawTs) : 0;20912092  if (remoteLicense) {2093    const licenseRaw = await chrome.storage.local.get('peach_license');2094    const existing = (licenseRaw as Record<string, unknown>)['peach_license'];2095    if (!existing) {2096      await chrome.storage.local.set({ peach_license: remoteLicense });2097    }2098  }20992100  if (remoteTimestamp <= localTimestamp) return false;21012102  // Snapshot before overwriting — failure is non-fatal2103  await takeVaultSnapshot('sync_received').catch(() => {});21042105  const { a, b } = JSON.parse(blobJson) as { a: unknown; b?: unknown };2106  await writeSlot(SLOT_A, a as StoredVault);2107  if (b) await writeSlot(SLOT_B, b as StoredVault);2108  await chrome.storage.local.set({2109    peach_last_sync_at: String(Date.now()),2110    peach_last_modified_at: String(remoteTimestamp),2111  });21122113  return true;2114}21152116export async function getSyncIdentity(): Promise<{2117  privateKeyBytes: Uint8Array;2118  publicKeyBytes: Uint8Array;2119  publicKeyHex: string;2120}> {2121  const raw = await chrome.storage.local.get('peach_sync_identity');2122  const stored = (raw as Record<string, unknown>)['peach_sync_identity'];2123  if (typeof stored === 'string') {2124    const { priv, pub } = JSON.parse(stored) as { priv: string; pub: string };2125    const privateKeyBytes = base64DecodeBytes(priv);2126    const publicKeyBytes = base64DecodeBytes(pub);2127    return { privateKeyBytes, publicKeyBytes, publicKeyHex: bytesToHex(publicKeyBytes) };2128  }21292130  // Generate a fresh X25519 keypair and persist it.2131  const { generateKeyPair } = await import('@stablelib/x25519');2132  const keypair = generateKeyPair();2133  await chrome.storage.local.set({2134    peach_sync_identity: JSON.stringify({2135      priv: base64EncodeBytes(keypair.secretKey),2136      pub: base64EncodeBytes(keypair.publicKey),2137    }),2138  });2139  return {2140    privateKeyBytes: keypair.secretKey,2141    publicKeyBytes: keypair.publicKey,2142    publicKeyHex: bytesToHex(keypair.publicKey),2143  };2144}21452146// Re-decrypt vault entries from storage using the current in-memory key.2147// Called after applyIncomingVault so the in-memory state stays consistent2148// with what was just written to storage.2149export async function reloadEntriesAfterSync(): Promise<boolean> {2150  if (!derivedKey) return false;2151  const slotA = await loadSlot(SLOT_A);2152  if (!slotA) return false;2153  try {2154    const payload = await tryDecryptSlot(slotA, derivedKey);2155    if (!payload) return false;2156    entries = payload.entries;2157    buildDomainIndexSync(entries);2158    return true;2159  } catch {2160    return false;2161  }2162}21632164function bytesToHex(bytes: Uint8Array): string {2165  return Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');2166}21672168function base64EncodeBytes(bytes: Uint8Array): string {2169  let binary = '';2170  for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);2171  return btoa(binary);2172}21732174function base64DecodeBytes(b64: string): Uint8Array {2175  const binary = atob(b64);2176  const bytes = new Uint8Array(binary.length);2177  for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);2178  return bytes;2179}