vault.ts

92.3 KB · raw

1/**2 * vault.ts — sole owner of vault state and chrome.storage vault keys.3 *4 * Every read/write of `peach_vault_a`, `peach_vault_b`, and `peach_settings`5 * goes through this module. No other file accesses those keys directly.6 * External callers reach vault operations via `messages.ts` — never by7 * importing from here cross-boundary (popup/content must not). Invariants8 * for the two-slot schema, unlock timing, and key/disk atomicity are in9 * Projects.md §3.2–§3.6.10 */1112import { deriveKey, generateSalt } from "../crypto/argon2";13import { extractDomain } from "../shared/domain";14import {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;5253// When duress is configured, BOTH slots are padded to this fixed ceiling so54// their ciphertext lengths are identical and cannot reveal that a hidden decoy55// vault exists (audit MEDIUM — plausible-deniability leak). 256 KiB comfortably56// holds a very large vault (thousands of entries incl. passkeys). The decoy57// slot can't be re-encrypted on every real-vault save (the real session has no58// decoy key), so a fixed ceiling — rather than size-matching on each write — is59// what keeps the two slots equal. A real vault whose plaintext exceeds this60// would grow past the ceiling and re-expose the bit; that is an extreme,61// documented edge well beyond normal use.62const DURESS_SLOT_SIZE = 262_144;6364let derivedKey: Uint8Array | null = null;65// 32-byte random root key, separate from the derivedKey used for vault encryption.66// The root key is wrapped (encrypted) under the recovery key derived from the67// 12-word phrase. When the user changes their password, only the wrapping changes;68// the root key and recovery words remain stable.69let rootKey: Uint8Array | null = null;70let entries: VaultEntry[] = [];71let domainIndex: Map<string, VaultEntry[]> = new Map();72let vaultMode: "real" | "decoy" = "real";73// Cached post-unlock view of whether the real vault records that duress is74// configured. Only meaningful after a real-mode unlock; for decoy-mode unlock75// this stays false because we never see slot A's plaintext.76let duressConfigured = false;7778let migrationRan = false;7980// Set to a corruption reason during the last unlock() attempt when both slots81// decrypted but failed schema validation. Consumed and cleared by82// consumeLastUnlockFailureReason() so messages.ts can surface vault_corrupted83// distinctly from wrong-password (M7/COR-007).84//85// NOTE: module-level state — if vault.ts is ever moved to a worker context,86// this must be replaced with a structured return value from unlock() or a87// postMessage channel. The signal is invisible across module-instance88// boundaries.89let lastUnlockFailureReason: string | null = null;9091export function consumeLastUnlockFailureReason(): string | null {92  const r = lastUnlockFailureReason;93  lastUnlockFailureReason = null;94  return r;95}9697// ---------------------------------------------------------------------------98// Settings (persisted inside the encrypted vault store as a sidecar key)99// ---------------------------------------------------------------------------100101export type TextSize = "small" | "medium" | "large";102103export interface VaultSettings {104  accentColor?: AccentColorName;105  theme?: "dark" | "light";106  autoLockMinutes?: number;107  clipboardClearSeconds?: number;108  lockOnClose?: boolean;109  breachMonitoring?: boolean;110  passkeyProviderEnabled?: boolean;111  trashRetentionDays?: number;112  manualSummonDomains?: Record<string, ManualSummonRecord>;113  declinedCardFingerprints?: string[];114  /**115   * Text size scale for body copy and entry titles. Stops at "large" by116   * design — XL clips dense screens (Vault, Health) inside the fixed117   * 330×480 popup surface.118   */119  textSize?: TextSize;120  /**121   * When true, all entrance/exit transitions and ambient animations are122   * collapsed to instant. Honoured alongside the user's OS-level123   * `prefers-reduced-motion`.124   */125  reduceMotion?: boolean;126  /**127   * Android-only: when true, the master key is escrowed in AndroidKeyStore128   * and the lock screen offers biometric unlock. Toggled from Settings →129   * Security → Biometrics. Has no effect on desktop builds.130   */131  biometricsEnabled?: boolean;132  /**133   * User overrides for keyboard shortcuts. Keys are ShortcutAction names134   * (see src/shared/shortcuts.ts). Missing actions fall through to135   * DEFAULT_BINDINGS — `getActiveBindings(settings.shortcuts)` is the136   * canonical lookup. Storing only the deltas keeps the vault payload137   * small and lets default updates land for users who never rebind.138   */139  shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;140}141142let settings: VaultSettings = {};143144export function getSettings(): VaultSettings {145  return settings;146}147148export async function ensureSettingsLoaded(): Promise<VaultSettings> {149  await loadSettings();150  return settings;151}152153export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {154  await loadSettings();155  settings = { ...settings, ...patch };156  await persistSettings();157}158159async function persistSettings(): Promise<void> {160  try {161    await chrome.storage.local.set({ peach_settings: settings });162  } catch (err) {163    throw mapStorageError(err);164  }165}166167function mapStorageError(err: unknown): Error {168  const message = err instanceof Error ? err.message : String(err);169  if (/QUOTA_BYTES|quota/i.test(message)) {170    return new Error("STORAGE_QUOTA_EXCEEDED");171  }172  return err instanceof Error ? err : new Error(message);173}174175async function loadSettings(): Promise<void> {176  const result = await chrome.storage.local.get("peach_settings");177  settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};178}179180// Fire-and-forget sync trigger after a committed vault write. Lazy181// dynamic import avoids a circular dependency between vault.ts and182// sync-trigger.ts (the trigger imports paired-devices, which only reads183// storage, but the lazy load also gives us a clean opt-out path in184// tests where sync-trigger has not been initialised).185function fireSyncTrigger(reason: "vault_change"): void {186  void import("./sync-trigger")187    .then((mod) => mod.triggerSyncIfReachable({ reason }))188    .catch(() => {189      /* sync trigger module not available — non-fatal */190    });191}192193// ---------------------------------------------------------------------------194// HIBP breach check (k-anonymity model)195// ---------------------------------------------------------------------------196197export async function checkBreach(password: string): Promise<number> {198  // HIBP k-anonymity API is keyed on SHA-1 prefixes — this is dictated by199  // the public API, not a security choice. Do not migrate to SHA-256 here.200  const encoder = new TextEncoder();201  const hashBuffer = await crypto.subtle.digest("SHA-1", encoder.encode(password));202  const hashHex = Array.from(new Uint8Array(hashBuffer))203    .map((b) => b.toString(16).padStart(2, "0"))204    .join("")205    .toUpperCase();206207  const prefix = hashHex.slice(0, 5);208  const suffix = hashHex.slice(5);209210  try {211    const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`);212    if (!res.ok) return 0;213    const text = await res.text();214    const match = text.split("\r\n").find((l) => l.startsWith(suffix));215    return match ? parseInt(match.split(":")[1], 10) : 0;216  } catch {217    return 0; // Network unavailable — don't block218  }219}220221export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {222  const fingerprint = await cardFingerprint(last4, expMonth, expYear);223  await loadSettings();224  settings = {225    ...settings,226    declinedCardFingerprints: [...(settings.declinedCardFingerprints ?? []), fingerprint],227  };228  await persistSettings();229}230231export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {232  await loadSettings();233  const fingerprint = await cardFingerprint(last4, expMonth, expYear);234  return (settings.declinedCardFingerprints ?? []).includes(fingerprint);235}236237async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {238  const encoder = new TextEncoder();239  const buf = await crypto.subtle.digest("SHA-256", encoder.encode(`${last4}|${expMonth}|${expYear}`));240  return Array.from(new Uint8Array(buf).slice(0, 8))241    .map((b) => b.toString(16).padStart(2, "0"))242    .join("");243}244245function hex(buf: Uint8Array): string {246  return Array.from(buf)247    .map((b) => b.toString(16).padStart(2, "0"))248    .join("");249}250251function unhex(s: string): Uint8Array {252  const out = new Uint8Array(s.length / 2);253  for (let i = 0; i < s.length; i += 2) {254    out[i / 2] = parseInt(s.slice(i, i + 2), 16);255  }256  return out;257}258259// ---------------------------------------------------------------------------260// Root key generation and recovery word wrapping261// ---------------------------------------------------------------------------262263/**264 * Generate a random 32-byte root key and wrap it (AES-256-GCM) under a key265 * derived from the recovery word material via HKDF-SHA256. The wrapped blob266 * fields are stored in slot A alongside the password-wrapped ciphertext. The267 * root key itself is kept in memory for the session so getRecoveryWords() can268 * encode it without re-deriving.269 */270async function generateAndWrapRootKey(): Promise<{271  rawRootKey: string; // hex of the plaintext root key — caller stores in rootKey272  recoverySalt: string;273  wrappedRootKey: string;274  wrappedNonce: string;275  wrappedTag: string;276}> {277  const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));278279  // Derive the recovery key from the BIP39 words encoding of the root key.280  const words = await rootKeyToWords(rootKeyBytes);281  const wordMaterial = await wordsToRootKeyMaterial(words);282  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));283  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);284285  // Wrap the root key with the recovery key using AES-256-GCM directly.286  // We hex-encode rootKeyBytes so the plaintext is always valid UTF-8.287  const nonce = crypto.getRandomValues(new Uint8Array(12));288  const encoded = new TextEncoder().encode(hex(rootKeyBytes));289  const raw = await crypto.subtle.encrypt(290    {291      name: "AES-GCM",292      iv: nonce,293      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,294      tagLength: 128,295    },296    recoveryKey,297    encoded298  );299  // WebCrypto returns ciphertext || auth tag concatenated; split them.300  const rawU8 = new Uint8Array(raw);301  const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));302  const tag = hex(rawU8.slice(rawU8.length - 16));303304  return {305    rawRootKey: hex(rootKeyBytes),306    recoverySalt: hex(recoverySalt),307    wrappedRootKey: ciphertext,308    wrappedNonce: hex(nonce),309    wrappedTag: tag,310  };311}312313/**314 * Unwrap the root key using recovery words. Called during recovery flow when315 * the user provides their 12-word phrase and a new password.316 * Exported for use by the RECOVER_WITH_WORDS message handler.317 */318export async function unwrapRootKeyForRecovery(319  wrappedRootKey: string,320  wrappedNonce: string,321  wrappedTag: string,322  recoverySaltHex: string,323  words: string[]324): Promise<void> {325  const wordMaterial = await wordsToRootKeyMaterial(words);326  const recoverySalt = unhex(recoverySaltHex);327  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);328329  // Decrypt and cache the root key. The root key bytes were hex-encoded before330  // encryption so the ciphertext is valid UTF-8. We inline the AES-GCM decrypt331  // here to avoid passing a CryptoKey to the string-based encrypt/decrypt helpers.332  // Each component is stored separately in the vault slot; decode them individually333  // so the nonce is always exactly the 12 bytes from wrappedNonce.334  const nonceRaw = unhex(wrappedNonce);335  const ciphertextRaw = unhex(wrappedRootKey);336  const tagRaw = unhex(wrappedTag);337  // Combine ciphertext and tag for AES-GCM (expects ciphertext||tag).338  // Use explicit ArrayBuffer allocations to satisfy TS BufferSource constraints.339  const nonceU8 = nonceRaw as unknown as Uint8Array<ArrayBuffer>;340  const combined = new Uint8Array(ciphertextRaw.length + tagRaw.length);341  combined.set(ciphertextRaw, 0);342  combined.set(tagRaw, ciphertextRaw.length);343  const raw = await crypto.subtle.decrypt(344    { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },345    recoveryKey,346    combined347  );348  const decryptedHex = new TextDecoder().decode(raw);349  rootKey = unhex(decryptedHex);350}351352/**353 * Re-wrap the cached root key under a new derived key (from the user's new354 * password). Called after password change and after recovery re-key so the355 * same recovery words continue to work with the updated password — and so356 * subsequent unlocks can rehydrate rootKey via deriveRootKeyFromDerivedKey.357 *358 * recovery_* fields are intentionally not touched: those wrap rootKey under359 * the recovery words, which do not change when the password changes.360 */361export async function rewrapRootKeyForPassword(362  newDerivedKey: Uint8Array,363  _newSalt: Uint8Array364): Promise<void> {365  if (!rootKey) throw new Error("root key not set");366  const slotA = await loadSlot(SLOT_A);367  if (!slotA) throw new Error("missing slot A");368  const pwRoot = await wrapRootKeyForDerivedKey(newDerivedKey, rootKey);369  await writeSlot(SLOT_A, { ...slotA, ...pwRoot });370}371372/**373 * Change the vault encryption to a new derived key (already derived from374 * the user's new password). Used by RECOVER_WITH_WORDS and changePassword.375 * Caller is responsible for key swap and snapshot.376 */377async function reencryptVaultForNewKey(378  newKey: Uint8Array,379  slotA: StoredVault380): Promise<void> {381  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);382  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");383  await writeSlot(SLOT_A, {384    ...slotA,385    nonce,386    ciphertext,387    tag,388  });389}390391/**392 * Full password change with an already-derived key (used after recovery).393 * Unlike changePassword(), this skips re-verification of current password394 * since recovery flow has already validated the user's identity via words.395 */396export async function changePasswordWithNewKey(397  newSalt: Uint8Array,398  newKey: Uint8Array399): Promise<void> {400  const slotA = await loadSlot(SLOT_A);401  if (!slotA) throw new Error("missing slot A");402  // reencryptVaultForNewKey must receive the updated salt so that subsequent403  // UNLOCK calls with the new password can re-derive the correct key.404  await reencryptVaultForNewKey(newKey, { ...slotA, salt: hex(newSalt) });405  if (derivedKey) zeroKey(derivedKey);406  derivedKey = newKey;407  // Refresh pw_root_* under the new key so deriveRootKeyFromDerivedKey works408  // on the next unlock (H2/COR-006). If rootKey is missing — recovery flow409  // should have populated it — fall back silently rather than blowing up the410  // recovery path; migrateToRecovery will rehydrate on the next unlock.411  if (rootKey) {412    const slotAfter = await loadSlot(SLOT_A);413    if (slotAfter) {414      const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);415      await writeSlot(SLOT_A, { ...slotAfter, ...pwRoot });416    }417  }418  if (!duressConfigured) {419    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));420  }421  await stampLocalVaultMutation();422}423424// ---------------------------------------------------------------------------425// Salt generation --- exported so the RECOVER_WITH_WORDS handler can derive426// a new key after password reset without re-importing the crypto module.427// ---------------------------------------------------------------------------428429export { deriveKey, generateSalt };430431export async function loadSlotA(): Promise<StoredVault | null> {432  return loadSlot(SLOT_A);433}434435/**436 * Recover the session root key by AES-GCM-decrypting the pw_root_* fields437 * (a second wrapping of the root key under the password-derived key). This438 * is what makes GET_RECOVERY_WORDS work across lock/unlock cycles without439 * the user re-entering their recovery phrase: the same root key bytes —440 * and therefore the same 12 words — survive every unlock.441 *442 * Returns null when the pw_root fields are absent (pre-v2.12 vault that443 * hasn't been migrated yet) or when decryption fails (wrong derived key,444 * tampered ciphertext). On null the caller should fall through to445 * migrateToRecovery() to populate the fields.446 */447async function deriveRootKeyFromDerivedKey(448  derivedKeyBytes: Uint8Array,449  slotA: StoredVault,450): Promise<Uint8Array | null> {451  if (!slotA.pw_root_ciphertext || !slotA.pw_root_nonce || !slotA.pw_root_tag) {452    return null;453  }454  try {455    const rootHex = await decrypt(456      derivedKeyBytes,457      slotA.pw_root_nonce,458      slotA.pw_root_ciphertext,459      slotA.pw_root_tag,460      "pw_root_v1",461    );462    return unhex(rootHex);463  } catch {464    return null;465  }466}467468// AES-GCM-wrap rootKey under derivedKey for the pw_root_* fields. Returns the469// hex-encoded ciphertext/nonce/tag triple ready to embed in StoredVault.470async function wrapRootKeyForDerivedKey(471  derivedKeyBytes: Uint8Array,472  rootKeyBytes: Uint8Array,473): Promise<{ pw_root_ciphertext: string; pw_root_nonce: string; pw_root_tag: string }> {474  const { nonce, ciphertext, tag } = await encrypt(derivedKeyBytes, hex(rootKeyBytes), "pw_root_v1");475  return {476    pw_root_ciphertext: ciphertext,477    pw_root_nonce: nonce,478    pw_root_tag: tag,479  };480}481482/**483 * For vaults created before v2.12 (no recovery_salt/recovery_wrapped_root_key),484 * generate the root key, wrap it under the recovery words, and persist the485 * recovery escrow into slot A. The caller must show the recovery words to the486 * user before calling this — once called, those words are the vault's recovery487 * path. This runs once, on the first unlock of an upgraded vault.488 */489export async function migrateToRecovery(): Promise<void> {490  if (!derivedKey || vaultMode !== "real") {491    throw new Error("vault must be unlocked in real mode");492  }493  const slotA = await loadSlot(SLOT_A);494  if (!slotA) throw new Error("missing slot A");495  const hasRecoveryEscrow =496    !!slotA.recovery_salt && !!slotA.recovery_wrapped_root_key;497  const hasPwRoot = !!slotA.pw_root_ciphertext && !!slotA.pw_root_nonce;498  if (hasRecoveryEscrow && hasPwRoot) return; // already done499500  // If recovery escrow already exists but pw_root doesn't, we cannot recover501  // the original rootKey without the user's words. The least-surprising path502  // is to rotate to a fresh root key — the user's old recovery words become503  // invalid but we surface peach_recovery_pending so the popup re-presents504  // the words. The unlock-path callers all set that flag.505  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =506    await generateAndWrapRootKey();507  rootKey = unhex(rawRootKey);508509  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);510  const nextSlotA: StoredVault = {511    ...slotA,512    recovery_salt: recoverySalt,513    recovery_wrapped_root_key: wrappedRootKey,514    recovery_nonce: wrappedNonce,515    recovery_tag: wrappedTag,516    ...pwRoot,517  };518  await writeSlot(SLOT_A, nextSlotA);519  await stampLocalVaultMutation();520}521522/**523 * Returns the 12 recovery words for the current session's root key.524 * Must be called while the vault is unlocked. Throws if recovery has not525 * been set up (pre-v2.12 vault that hasn't migrated yet).526 */527export async function getRecoveryWords(): Promise<string[]> {528  if (!rootKey) {529    throw new Error("recovery not set up — vault may need migration");530  }531  return rootKeyToWords(rootKey);532}533534async function loadSlot(key: string): Promise<StoredVault | null> {535  const result = await chrome.storage.local.get(key);536  return (result as Record<string, StoredVault | undefined>)[key] ?? null;537}538539async function writeSlot(key: string, vault: StoredVault): Promise<void> {540  try {541    await chrome.storage.local.set({ [key]: vault });542  } catch (err) {543    throw mapStorageError(err);544  }545}546547// Monotonic clock for per-entry modifiedAt / deletedAt timestamps. Guards the548// sync layer's last-write-wins merge against wall-clock regressions (NTP step,549// manual clock change, DST glitch): a backwards Date.now() must never produce550// an entry timestamp that's <= the entry's existing modifiedAt, or a genuine551// local edit would lose to a stale remote copy. The returned value is always552// strictly greater than both the entry's current modifiedAt and the previous553// call's result (SEV-2-E).554let lastEntryTimestamp = 0;555function monotonicEntryTimestamp(currentModifiedAt?: number): number {556  const base = Math.max(557    Date.now(),558    (currentModifiedAt ?? 0) + 1,559    lastEntryTimestamp + 1,560  );561  lastEntryTimestamp = base;562  return base;563}564565async function stampLocalVaultMutation(): Promise<void> {566  const raw = await chrome.storage.local.get("peach_last_modified_at");567  const previous = Number(568    (raw as Record<string, unknown>).peach_last_modified_at,569  );570  const next = Math.max(571    Date.now(),572    Number.isFinite(previous) ? previous + 1 : 0,573  );574  await chrome.storage.local.set({575    peach_last_modified_at: String(next),576  });577}578579/**580 * One-shot migration from the pre-A-2 schema (peach_vault + peach_decoy_vault581 * + peach_duress flag) to the slot-neutral schema (peach_vault_a +582 * peach_vault_b). Runs at most once per session; safe to call repeatedly.583 */584async function ensureMigrated(): Promise<void> {585  if (migrationRan) return;586  migrationRan = true;587588  const keys = [LEGACY_MAIN, LEGACY_DECOY, LEGACY_DURESS_FLAG, SLOT_A, SLOT_B];589  const raw = await chrome.storage.local.get(keys);590  const slotAExists = raw[SLOT_A] !== undefined;591  const slotBExists = raw[SLOT_B] !== undefined;592  const legacyMain = raw[LEGACY_MAIN] as StoredVault | undefined;593  const legacyDecoy = raw[LEGACY_DECOY] as StoredVault | undefined;594595  // Fresh install with nothing in storage — nothing to do; createVault() sets up both slots.596  if (!slotAExists && !legacyMain) return;597598  // Already migrated.599  if (slotAExists && slotBExists && !legacyMain && !legacyDecoy) return;600601  let didMigrate = false;602  if (legacyMain && !slotAExists) {603    await writeSlot(SLOT_A, legacyMain);604    didMigrate = true;605  }606607  // If slot B isn't set, populate it: use legacy decoy when present, else noise.608  if (!slotBExists) {609    const target = (legacyMain ?? raw[SLOT_A]) as StoredVault | undefined;610    if (legacyDecoy) {611      await writeSlot(SLOT_B, legacyDecoy);612      didMigrate = true;613    } else if (target) {614      await writeSlot(SLOT_B, generateNoiseBlob(target.ciphertext.length / 2));615      didMigrate = true;616    }617  }618619  const toRemove: string[] = [];620  if (legacyMain) toRemove.push(LEGACY_MAIN);621  if (legacyDecoy) toRemove.push(LEGACY_DECOY);622  if (raw[LEGACY_DURESS_FLAG] !== undefined) toRemove.push(LEGACY_DURESS_FLAG);623  if (toRemove.length > 0) {624    await chrome.storage.local.remove(toRemove);625    didMigrate = true;626  }627  if (didMigrate) {628    await stampLocalVaultMutation();629  }630}631632// ---------------------------------------------------------------------------633// Padding + noise helpers634// ---------------------------------------------------------------------------635636/**637 * Pads the plaintext string with trailing spaces so that the encoded byte638 * length is a multiple of PAD_BLOCK. JSON.parse tolerates trailing639 * whitespace after a complete document, so the padding is transparent on640 * decode. Ciphertext length equals plaintext length plus a 16-byte tag.641 */642function padPlaintext(json: string, minBytes = 0): string {643  const encoded = new TextEncoder().encode(json);644  const bucket = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);645  // minBytes lets the duress path force a fixed ceiling so both slots match.646  const target = Math.max(bucket, minBytes);647  const padLen = target - encoded.length;648  return json + " ".repeat(padLen);649}650651/**652 * Produces a StoredVault-shaped record filled with CSPRNG bytes. The653 * ciphertext length matches the given byte count. Because GCM ciphertext is654 * pseudo-random, this blob is indistinguishable at rest from a real655 * encrypted vault without the key.656 *657 * crypto.getRandomValues() caps each call at 65536 bytes (the Web Crypto658 * spec hard limit). Chunk the fill so vaults larger than that — common once659 * the user has dozens of entries or any passkey — don't throw.660 */661const CSPRNG_CHUNK = 65_536;662663function fillRandom(buf: Uint8Array): Uint8Array {664  for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {665    const end = Math.min(offset + CSPRNG_CHUNK, buf.length);666    const chunk = new Uint8Array(end - offset);667    crypto.getRandomValues(chunk);668    buf.set(chunk, offset);669  }670  return buf;671}672673function generateNoiseBlob(ciphertextBytes: number): StoredVault {674  const salt = crypto.getRandomValues(new Uint8Array(16));675  const nonce = crypto.getRandomValues(new Uint8Array(12));676  const cipher = fillRandom(new Uint8Array(ciphertextBytes));677  const tag = crypto.getRandomValues(new Uint8Array(16));678  return {679    version: 1,680    salt: hex(salt),681    nonce: hex(nonce),682    ciphertext: hex(cipher),683    tag: hex(tag),684  };685}686687// ---------------------------------------------------------------------------688// Encrypted plaintext envelope689// ---------------------------------------------------------------------------690691type VaultPayload = {692  entries: VaultEntry[];693  duressConfigured?: boolean;694};695696type DecryptedPayload = {697  entries: VaultEntry[];698  duressConfigured: boolean;699  /**700   * True when at least one entry in the on-disk payload had a legacy shape701   * (pre-v2.11.0 passkey type/flat fields, or pre-A-2 created/updated keys)702   * and got rewritten by normalizeEntry. The unlock path uses this to703   * persist the new shape immediately — without it, the migration would704   * re-run on every unlock and old shape never disappears from disk.705   */706  migratedFromLegacy: boolean;707};708709function encodePayload(entries: VaultEntry[], duress: boolean, minBytes = 0): string {710  const envelope: VaultPayload = { entries, duressConfigured: duress };711  return padPlaintext(JSON.stringify(envelope), minBytes);712}713714function rawNeedsMigration(raw: VaultEntry | LegacyVaultEntry): boolean {715  if ("created" in raw || "updated" in raw) return true;716  const flat = raw as Partial<VaultEntry>;717  if (flat.type === "passkey") return true;718  // Flat rpId without a passkey sub-object means pre-v2.11.0 schema.719  if (flat.rpId !== undefined && flat.passkey === undefined) return true;720  return false;721}722723function decodePayload(plain: string): DecryptedPayload {724  const parsed = JSON.parse(plain) as725    | Array<VaultEntry | LegacyVaultEntry>726    | VaultPayload;727728  const rawEntries = Array.isArray(parsed) ? parsed : parsed.entries ?? [];729  const flatMigrationNeeded = rawEntries.some(rawNeedsMigration);730731  const normalized = rawEntries.map(normalizeEntry);732  const { merged } = mergePasskeyOnlyIntoLogins(normalized);733734  if (Array.isArray(parsed)) {735    return {736      entries: normalized,737      duressConfigured: false,738      migratedFromLegacy: true, // pre-A-2 array shape always needs save739    };740  }741742  return {743    entries: normalized,744    duressConfigured: parsed.duressConfigured === true,745    migratedFromLegacy: flatMigrationNeeded || merged,746  };747}748749/**750 * One-time consolidation pass run alongside the legacy passkey migration.751 *752 * Pre-v2.11.0 the Chrome passkey path always created a fresh `type:"passkey"`753 * entry per registration — so users who tested registration multiple times754 * accumulated several passkey-bearing entries for the same RP, and the755 * migration to the unified shape carried that duplication forward. This756 * pass collapses the duplicates:757 *758 *   1. Group passkey-bearing (and not deleted) entries by `passkey.rpId`.759 *   2. Within each group, the most recently-active credential wins (prefer760 *      lastUsedAt, fall back to passkey.createdAt, fall back to modifiedAt).761 *   3. If a NON-passkey login entry exists for that RP (matched by url or762 *      additionalUrls hostname), attach the winning passkey to it and763 *      soft-delete every passkey-bearing entry in the group.764 *   4. Otherwise, soft-delete every loser in the group, keeping the winner765 *      as a passkey-only entry.766 *767 * Soft delete (deletedAt) rather than splice — the trash flow keeps the768 * record around for retention and the user can restore if the heuristic769 * picked wrong. The `merged` flag goes back to decodePayload so the770 * unlock path persists the consolidated shape immediately.771 */772function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {773  let merged = false;774  const now = Date.now();775776  const candidates = entries.filter((e) => !e.deletedAt && e.passkey);777  const byRpId = new Map<string, VaultEntry[]>();778  for (const e of candidates) {779    const rpId = e.passkey!.rpId;780    const list = byRpId.get(rpId);781    if (list) list.push(e);782    else byRpId.set(rpId, [e]);783  }784785  for (const [rpId, group] of byRpId) {786    if (group.length === 0) continue;787    group.sort((a, b) => {788      const aT =789        a.passkey!.lastUsedAt ?? a.passkey!.createdAt ?? a.modifiedAt ?? a.createdAt;790      const bT =791        b.passkey!.lastUsedAt ?? b.passkey!.createdAt ?? b.modifiedAt ?? b.createdAt;792      return bT - aT;793    });794    const winner = group[0]!;795796    // Look for a NON-passkey login entry matching this RP. Use the URL797    // hostname rather than a substring search so a "login.foo.com" entry798    // doesn't accidentally absorb a passkey for "foo.com".799    const loginTarget = entries.find((e) => {800      if (e.deletedAt || e.passkey || e.type !== "login") return false;801      if (e.url && extractDomain(e.url) === rpId) return true;802      for (const extra of e.additionalUrls ?? []) {803        if (extractDomain(extra) === rpId) return true;804      }805      return false;806    });807808    if (loginTarget) {809      loginTarget.passkey = winner.passkey;810      loginTarget.modifiedAt = now;811      for (const dup of group) {812        if (!dup.deletedAt) {813          dup.deletedAt = now;814          dup.modifiedAt = now;815        }816      }817      merged = true;818    } else if (group.length > 1) {819      for (let i = 1; i < group.length; i += 1) {820        const dup = group[i]!;821        if (!dup.deletedAt) {822          dup.deletedAt = now;823          dup.modifiedAt = now;824        }825      }826      merged = true;827    }828  }829830  return { merged };831}832833// Validates that a `StoredVault` record on disk has the field shape we expect834// before treating an AES-GCM decrypt success as a clean unlock. AES-GCM only835// authenticates the static VERSION_BYTE AAD, not the `version` field on the836// outer record — a corrupted `version: 42` slot still decrypts cleanly. This837// check surfaces that as `corrupted` (M7/COR-007) so the popup can offer a838// history-restore path instead of falsely reporting "wrong password".839function hasValidVaultSchema(v: unknown): v is StoredVault {840  if (typeof v !== "object" || v === null) return false;841  const r = v as Record<string, unknown>;842  return (843    r.version === 1 &&844    typeof r.salt === "string" &&845    typeof r.nonce === "string" &&846    typeof r.ciphertext === "string" &&847    typeof r.tag === "string"848  );849}850851export type TryDecryptResult =852  | { status: "ok"; payload: DecryptedPayload }853  | { status: "wrong_key" }854  | { status: "corrupted"; reason: string };855856// Exported solely for `unlockFromCodex` below, which needs to verify a857// supplied passphrase against a slotA blob *without* committing anything to858// storage. Keep this internal otherwise — callers crossing the messages.ts859// boundary should always go through `unlock` / `verifyMainPassword` so the860// constant-time invariants in Projects.md §3.4 are not bypassed.861export async function tryDecryptSlot(862  vault: StoredVault,863  key: Uint8Array,864  aadTag?: string,865): Promise<DecryptedPayload | null> {866  const res = await tryDecryptSlotResult(vault, key, aadTag);867  return res.status === "ok" ? res.payload : null;868}869870export async function tryDecryptSlotResult(871  vault: StoredVault,872  key: Uint8Array,873  aadTag?: string,874): Promise<TryDecryptResult> {875  if (!hasValidVaultSchema(vault)) {876    return { status: "corrupted", reason: "invalid_slot_schema" };877  }878  let plain: string;879  try {880    plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);881  } catch {882    return { status: "wrong_key" };883  }884  try {885    const parsed = JSON.parse(plain) as unknown;886    if (typeof parsed !== "object" || parsed === null) {887      return { status: "corrupted", reason: "invalid_payload_shape" };888    }889    if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {890      return { status: "corrupted", reason: "invalid_payload_shape" };891    }892    return { status: "ok", payload: decodePayload(plain) };893  } catch {894    return { status: "corrupted", reason: "invalid_payload_json" };895  }896}897898// ---------------------------------------------------------------------------899// Core operations900// ---------------------------------------------------------------------------901902function buildDomainIndexSync(all: VaultEntry[]): void {903  domainIndex = new Map();904905  for (const entry of all) {906    if (entry.deletedAt) continue;907    if (entry.type === "note" || entry.type === "card") continue;908909    // An entry can match multiple sites via `additionalUrls`. Index each910    // hostname so `queryDomain` returns the entry regardless of which alias911    // the user is currently visiting. Dedupe per-entry so a single entry912    // never appears twice in one bucket.913    const domains = new Set<string>();914    const primary = extractDomain(entry.url ?? "");915    if (primary) domains.add(primary);916    for (const extra of entry.additionalUrls ?? []) {917      const d = extractDomain(extra);918      if (d) domains.add(d);919    }920    if (domains.size === 0) continue;921922    for (const domain of domains) {923      const bucket = domainIndex.get(domain) ?? [];924      bucket.push(entry);925      domainIndex.set(domain, bucket);926    }927  }928}929930export async function createVault(password: string): Promise<void> {931  await ensureMigrated();932933  const salt = generateSalt();934  derivedKey = await deriveKey(password, salt);935  entries = [];936  vaultMode = "real";937  duressConfigured = false;938  buildDomainIndexSync(entries);939940  // Generate and wrap the root key for recovery word escrow.941  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =942    await generateAndWrapRootKey();943  rootKey = unhex(rawRootKey);944945  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);946  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");947948  // Second wrapping of rootKey under derivedKey so future unlocks can rehydrate949  // it without recovery words (H2/COR-006).950  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);951952  const slotA: StoredVault = {953    version: 1,954    salt: hex(salt),955    nonce,956    ciphertext,957    tag,958    recovery_salt: recoverySalt,959    recovery_wrapped_root_key: wrappedRootKey,960    recovery_nonce: wrappedNonce,961    recovery_tag: wrappedTag,962    ...pwRoot,963  };964  await writeSlot(SLOT_A, slotA);965966  // Matching-size noise blob for slot B, so a fresh install shows two967  // similarly-shaped records regardless of whether duress is ever set up.968  await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));969  await stampLocalVaultMutation();970971  touchAutoLock();972}973974export async function hasVault(): Promise<boolean> {975  await ensureMigrated();976  return (await loadSlot(SLOT_A)) !== null;977}978979/**980 * Returns whether the real vault has recorded that a duress passphrase is981 * configured. Reliable only after a real-mode unlock — before unlock or in982 * decoy mode, returns false because we cannot read slot A's plaintext.983 */984export async function isDuressEnabled(): Promise<boolean> {985  return vaultMode === "real" && duressConfigured;986}987988export async function setupDuress(duressPassword: string): Promise<void> {989  if (!derivedKey || vaultMode !== "real") {990    throw new Error("vault must be unlocked in real mode");991  }992  await ensureMigrated();993994  // Encrypt the decoy payload (empty entries) under the duress key. Pad to995  // at least the current slot A ciphertext size so the two slots look the996  // same at rest at setup time.997  const slotA = await loadSlot(SLOT_A);998  if (!slotA) throw new Error("missing slot A");9991000  const decoySalt = generateSalt();1001  const decoyKey = await deriveKey(duressPassword, decoySalt);1002  try {1003    // Pad the decoy to the fixed duress ceiling. Slot A is re-encrypted to the1004    // same ceiling by the persistSlotA() call below (duressConfigured is now1005    // true), so both slots are exactly DURESS_SLOT_SIZE+tag at rest and their1006    // lengths cannot reveal that duress is configured (audit MEDIUM).1007    const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);1008    const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");1009    await writeSlot(SLOT_B, {1010      version: 1,1011      salt: hex(decoySalt),1012      nonce,1013      ciphertext,1014      tag,1015    });1016  } finally {1017    zeroKey(decoyKey);1018  }10191020  // Re-encrypt slot A with the duressConfigured flag set to true. No external1021  // flag is written — the bit lives inside the encrypted envelope.1022  duressConfigured = true;1023  await persistSlotA();1024}10251026export async function disableDuress(): Promise<void> {1027  if (!derivedKey || vaultMode !== "real") {1028    throw new Error("vault must be unlocked in real mode");1029  }1030  await ensureMigrated();10311032  // Overwrite slot B with fresh noise that matches slot A's size. The slot1033  // remains occupied so its mere existence does not signal that duress was1034  // ever configured.1035  const slotA = await loadSlot(SLOT_A);1036  if (slotA) {1037    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));1038  }10391040  duressConfigured = false;1041  await persistSlotA();1042}10431044// L14/COR-015: this function intentionally checks slot A (real vault) only.1045// A duress-mode user attempting changePassword is rejected earlier by the1046// vaultMode === 'decoy' check at changePassword. The real-vs-decoy1047// distinction here is by design — duress users cannot rotate the real1048// password by guessing it, and the asymmetry in error timing is acceptable1049// because duress mode is opt-in and the user knows their own decoy key.1050export async function verifyMainPassword(password: string): Promise<boolean> {1051  await ensureMigrated();1052  const slotA = await loadSlot(SLOT_A);1053  if (!slotA) return false;1054  const key = await deriveKey(password, unhex(slotA.salt));1055  try {1056    return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;1057  } finally {1058    zeroKey(key);1059  }1060}10611062export async function unlock(password: string): Promise<boolean> {1063  await ensureMigrated();10641065  // Load both slots in parallel. Both always exist post-migration; the1066  // parallel load and the parallel derivation below keep wall-clock time1067  // constant regardless of which slot's passphrase (real or decoy) the1068  // caller supplied, so a timing side channel cannot distinguish the1069  // duress path from the real-unlock path (DUR-002).1070  const [slotA, slotB] = await Promise.all([1071    loadSlot(SLOT_A),1072    loadSlot(SLOT_B),1073  ]);10741075  // Derive both keys in parallel, unconditionally.1076  const [keyA, keyB] = await Promise.all([1077    slotA ? deriveKey(password, unhex(slotA.salt)) : Promise.resolve(null),1078    slotB ? deriveKey(password, unhex(slotB.salt)) : Promise.resolve(null),1079  ]);10801081  // Attempt both decrypts in parallel. The Result variant lets us distinguish1082  // 'wrong_key' from 'corrupted' so callers can offer a history-restore path1083  // when a slot's schema is invalid even though AES-GCM authenticated (M7).1084  const [resultA, resultB] = await Promise.all([1085    keyA && slotA1086      ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")1087      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1088    keyB && slotB1089      ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")1090      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1091  ]);1092  const payloadA = resultA.status === "ok" ? resultA.payload : null;1093  const payloadB = resultB.status === "ok" ? resultB.payload : null;10941095  if (payloadA && keyA) {1096    derivedKey = keyA;1097    void saveSessionKey(keyA, "real");1098    vaultMode = "real";1099    entries = payloadA.entries;1100    duressConfigured = payloadA.duressConfigured;1101    buildDomainIndexSync(entries);1102    await loadSettings();1103    touchAutoLock();1104    if (keyB) zeroKey(keyB);11051106    // slotA is non-null when payloadA is truthy (keyA was derived from slotA).1107    if (slotA) {1108      const needsRecoverySetup =1109        !slotA.recovery_salt || !slotA.recovery_wrapped_root_key;1110      if (!needsRecoverySetup) {1111        rootKey = await deriveRootKeyFromDerivedKey(keyA, slotA);1112      }1113      // Pre-v2.12 vault, or a vault whose pw_root_* fields haven't been written1114      // yet: generate the recovery escrow and seed pw_root_* so subsequent1115      // unlocks can rehydrate rootKey without the user's recovery words.1116      // Best-effort — a failure here must not block unlock.1117      if (needsRecoverySetup || !rootKey) {1118        try {1119          await migrateToRecovery();1120          if (needsRecoverySetup) {1121            // String "1" matches the popup's existing peach_recovery_pending1122            // check; surfaced so the user re-confirms recovery words after a1123            // legacy-vault unlock (H2/COR-006).1124            await chrome.storage.local.set({ peach_recovery_pending: '1' });1125          }1126        } catch (migrationErr) {1127          console.warn('[Peach] recovery migration failed:', migrationErr);1128        }1129      }1130    }11311132    // If the payload had a pre-v2.11.0 shape (legacy passkey type, flat1133    // passkey fields, or pre-A-2 created/updated keys), rewrite it now so1134    // the next save uses the new format and migration doesn't re-run forever.1135    if (payloadA.migratedFromLegacy) {1136      await persistSlotA();1137    }1138    return true;1139  }11401141  if (payloadB && keyB) {1142    derivedKey = keyB;1143    void saveSessionKey(keyB, "decoy");1144    vaultMode = "decoy";1145    entries = payloadB.entries;1146    duressConfigured = false;1147    buildDomainIndexSync(entries);1148    await loadSettings();1149    touchAutoLock();1150    if (keyA) zeroKey(keyA);1151    return true;1152  }11531154  if (keyA) zeroKey(keyA);1155  if (keyB) zeroKey(keyB);1156  // Surface corruption (good AES tag, broken schema) distinctly from1157  // wrong-password so the popup can offer history-restore (M7/COR-007).1158  if (resultA.status === "corrupted") {1159    lastUnlockFailureReason = resultA.reason;1160  } else if (resultB.status === "corrupted") {1161    lastUnlockFailureReason = resultB.reason;1162  }1163  return false;1164}11651166// ---------------------------------------------------------------------------1167// MV3 service worker session key — survives SW restarts within a browser session1168// ---------------------------------------------------------------------------11691170// chrome.storage.session is cleared on browser close; survives SW restart.1171// Firefox does not implement it (persistent background script, no restart risk).1172const SESSION_KEY_STORAGE = "peach_session_dk";11731174async function saveSessionKey(key: Uint8Array, mode: "real" | "decoy"): Promise<void> {1175  if (!chrome.storage.session) return;1176  await chrome.storage.session.set({ [SESSION_KEY_STORAGE]: { keyHex: hex(key), mode } });1177}11781179async function clearSessionKey(): Promise<void> {1180  if (!chrome.storage.session) return;1181  await chrome.storage.session.remove(SESSION_KEY_STORAGE);1182}11831184/**1185 * On SW restart, re-derive all in-memory vault state from the session key1186 * stored in chrome.storage.session (set at unlock time, cleared on lock).1187 * Returns true if the vault was restored, false if no session key was found.1188 * No-ops if the vault is already unlocked.1189 */1190export async function restoreFromSession(): Promise<boolean> {1191  if (derivedKey !== null) return true;1192  if (!chrome.storage.session) return false;1193  const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);1194  const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;1195  if (!entry?.keyHex) return false;11961197  const key = unhex(entry.keyHex);1198  const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;1199  const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";1200  const slot = await loadSlot(slotKey);1201  if (!slot) { await clearSessionKey(); return false; }12021203  const result = await tryDecryptSlotResult(slot, key, aadTag);1204  if (result.status !== "ok") { await clearSessionKey(); return false; }12051206  derivedKey = key;1207  vaultMode = entry.mode;1208  entries = result.payload.entries;1209  duressConfigured = entry.mode === "real" ? result.payload.duressConfigured : false;1210  buildDomainIndexSync(entries);1211  await loadSettings();1212  touchAutoLock();12131214  if (entry.mode === "real" && slot.recovery_salt && slot.recovery_wrapped_root_key) {1215    try { rootKey = await deriveRootKeyFromDerivedKey(key, slot); } catch { /* non-fatal */ }1216  }12171218  return true;1219}12201221export function lock(): void {1222  void clearSessionKey();1223  if (derivedKey) {1224    zeroKey(derivedKey);1225    derivedKey = null;1226  }1227  if (rootKey) {1228    rootKey.fill(0);1229    rootKey = null;1230  }12311232  entries = [];1233  domainIndex = new Map();1234  vaultMode = "real";1235  duressConfigured = false;1236  clearAutoLock();1237}12381239export function isUnlocked(): boolean {1240  return derivedKey !== null;1241}12421243// Opens the vault using a pre-derived AES-256 key (skipping Argon2id).1244// Used by Android biometric unlock — the key was derived on the native side.1245export async function unlockWithKey(1246  masterKeyHex: string,1247): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {1248  try {1249    const masterKeyBytes = unhex(masterKeyHex);1250    const stored = await loadSlot(SLOT_A);1251    if (!stored) return { ok: false, error: "invalid_key" };1252    const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");1253    if (!payload) return { ok: false, error: "invalid_key" };12541255    derivedKey = masterKeyBytes;1256    vaultMode = "real";1257    entries = payload.entries;1258    duressConfigured = payload.duressConfigured;1259    buildDomainIndexSync(entries);1260    await loadSettings();1261    touchAutoLock();1262    return { ok: true, entries };1263  } catch {1264    return { ok: false, error: "invalid_key" };1265  }1266}12671268/**1269 * Restore the vault from a parsed Peach Codex payload.1270 *1271 * The supplied passphrase is verified against the Codex's slotA *before* any1272 * storage mutation — wrong passphrases return without touching disk. On1273 * success, the current vault state is snapshotted (reason: "restore") so the1274 * user can revert via Settings -> Vault History, then slotA/slotB are written1275 * and `peach_last_modified_at` is set to the Codex's recorded timestamp. A1276 * regular `unlock()` follows so the rest of the SW sees the standard1277 * post-unlock state.1278 *1279 * Intentionally non-Pro-gated — see peach_codex_v2.md "Pro gating". A Codex1280 * printed by a Pro user must always be restorable, even on a free device.1281 *1282 * Timing is not held constant here (in contrast to `unlock`): the Codex flow1283 * is an explicit user action with a known passphrase, not a passive lock1284 * screen, so the duress-vs-real timing side channel does not apply.1285 */1286export async function unlockFromCodex(params: {1287  slotA: string; // JSON string of StoredVault for slot A1288  slotB: string | null; // JSON string of StoredVault for slot B, or null1289  timestamp: number;1290  masterPassphrase: string;1291}): Promise<1292  | { ok: true; entryCount: number }1293  | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" }1294> {1295  let parsedSlotA: StoredVault;1296  let parsedSlotB: StoredVault | null = null;1297  try {1298    const rawA = JSON.parse(params.slotA) as unknown;1299    if (!hasValidVaultSchema(rawA)) {1300      return { ok: false, reason: "invalid_slot_format" };1301    }1302    parsedSlotA = rawA;1303    if (params.slotB !== null) {1304      const rawB = JSON.parse(params.slotB) as unknown;1305      if (!hasValidVaultSchema(rawB)) {1306        return { ok: false, reason: "invalid_slot_format" };1307      }1308      parsedSlotB = rawB;1309    }1310  } catch {1311    return { ok: false, reason: "invalid_slot_format" };1312  }13131314  // Verify the passphrase against the supplied slotA WITHOUT writing anything.1315  // If this fails the on-disk vault is left completely untouched.1316  const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));1317  const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");1318  if (!trialPayload) {1319    zeroKey(trialKey);1320    return { ok: false, reason: "wrong_passphrase" };1321  }1322  // Drop the trial key; `unlock()` below derives its own copy. Holding two1323  // copies of the master key in memory at once would be a needless surface.1324  zeroKey(trialKey);13251326  // Snapshot the about-to-be-overwritten on-disk state so the user can revert1327  // a mistaken Codex restore via the Vault History UI. Non-fatal if it fails.1328  await takeVaultSnapshot("restore");13291330  await writeSlot(SLOT_A, parsedSlotA);1331  if (parsedSlotB) {1332    await writeSlot(SLOT_B, parsedSlotB);1333  } else {1334    // Slot B must always exist with ciphertext length matching slot A1335    // (Projects.md §3.2). Codex prints may omit slot B (duress wasn't1336    // configured); regenerate noise to satisfy the invariant.1337    await writeSlot(1338      SLOT_B,1339      generateNoiseBlob(parsedSlotA.ciphertext.length / 2),1340    );1341  }1342  await chrome.storage.local.set({1343    peach_last_modified_at: String(params.timestamp),1344  });13451346  // Standard unlock path so domain index, settings, auto-lock, and1347  // recovery-key state all populate exactly as a normal unlock would.1348  const ok = await unlock(params.masterPassphrase);1349  if (!ok) {1350    // Should be unreachable — we just verified the passphrase against the1351    // same slotA we wrote. Treat as wrong_passphrase to keep the contract1352    // simple if some race or storage anomaly intrudes.1353    return { ok: false, reason: "wrong_passphrase" };1354  }1355  return { ok: true, entryCount: getEntries().length };1356}13571358// Returns the current in-memory derived key as a hex string.1359// Used by the biometric enable flow in Settings to store the key in Android Keystore.1360export function getDerivedKeyHex(): string {1361  if (!derivedKey) throw new Error("vault_not_unlocked");1362  return hex(derivedKey);1363}13641365/**1366 * Returns the vault's stable root key as hex, or null when locked / not yet1367 * populated. The root key is random per-vault, generated at creation, escrowed1368 * under the recovery words, and re-wrapped (not regenerated) on every password1369 * change — so it is INVARIANT across password rotation, unlike getDerivedKeyHex.1370 *1371 * This is the correct input for sync identity derivation (vault_id, the Noise1372 * XX static key, the Ed25519 manifest signing key, and per-entry envelope1373 * keys): paired devices keep the same identity and can still decrypt each1374 * other's entries after either side rotates its master password (SEV-2-B).1375 *1376 * Returns null rather than throwing so sync callers degrade to VAULT_LOCKED1377 * instead of crashing; rootKey is populated on every real-mode unlock via1378 * deriveRootKeyFromDerivedKey / migrateToRecovery.1379 */1380export function getRootKeyHex(): string | null {1381  return rootKey ? hex(rootKey) : null;1382}13831384export function getEntries(): VaultEntry[] {1385  if (!derivedKey) throw new Error("vault_locked");1386  return entries.filter((entry) => !entry.deletedAt);1387}13881389const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;13901391export function getIdentities(): SavedIdentity[] {1392  if (!derivedKey) throw new Error("vault_locked");1393  const active = entries.filter((e) => !e.deletedAt && e.type === "login");13941395  const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();1396  const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();13971398  for (const entry of active) {1399    const domain = extractDomain(entry.url ?? "") ?? "";1400    const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;14011402    function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {1403      const existing = map.get(v);1404      if (!existing || modifiedAt > existing.lastUsed) {1405        map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });1406      } else {1407        map.set(v, { ...existing, count: existing.count + 1 });1408      }1409    }14101411    const uVal = entry.username?.trim();1412    if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);14131414    // Also count the dedicated email field — entries created via the inline1415    // popup new-entry form store email here rather than in username.1416    const eVal = entry.email?.trim();1417    if (eVal) tally(emailMap, eVal);1418  }14191420  const toIdentity = (type: "email" | "username") =>1421    ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({1422      value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,1423    });14241425  return [1426    ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),1427    ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),1428  ];1429}14301431export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {1432  if (!derivedKey) throw new Error("vault_locked");14331434  const now = Date.now();1435  const added: VaultEntry[] = [];1436  for (const draft of drafts) {1437    try {1438      const sanitized = sanitizeEntryDraft(draft);1439      const nextEntry: VaultEntry = {1440        ...sanitized,1441        id: crypto.randomUUID(),1442        createdAt: now,1443        modifiedAt: monotonicEntryTimestamp(),1444      };1445      entries.push(nextEntry);1446      added.push(nextEntry);1447    } catch {1448      // Skip invalid drafts silently — caller can see diff between input and output length1449    }1450  }14511452  if (added.length > 0) {1453    await persistEntries();1454  }14551456  return added;1457}14581459/**1460 * Restore a set of entries in full fidelity — preserves id, createdAt,1461 * modifiedAt, and every other field unlike `batchAddEntries` which1462 * assigns fresh identity. Used by restore paths where the backup is the1463 * authoritative source of truth. `mode` controls how entries already in1464 * the vault are treated.1465 */1466export async function restoreEntries(1467  incoming: VaultEntry[],1468  mode: "replace" | "merge"1469): Promise<{ added: number; updated: number; skipped: number }> {1470  if (!derivedKey) throw new Error("vault_locked");14711472  // A replace with zero incoming entries is almost certainly a caller bug1473  // (e.g. an import that silently dropped everything). Refuse rather than1474  // wipe the vault.1475  if (mode === "replace" && incoming.length === 0) {1476    throw new Error("refuse to replace with empty entry set");1477  }14781479  let added = 0;1480  let updated = 0;1481  let skipped = 0;14821483  if (mode === "replace") {1484    entries = [];1485    for (const entry of incoming) {1486      const normalized = sanitizeRestoredEntry(entry);1487      if (!normalized) {1488        skipped += 1;1489        continue;1490      }1491      entries.push(normalized);1492      added += 1;1493    }1494  } else {1495    const byId = new Map<string, VaultEntry>();1496    for (const e of entries) byId.set(e.id, e);14971498    for (const entry of incoming) {1499      const normalized = sanitizeRestoredEntry(entry);1500      if (!normalized) {1501        skipped += 1;1502        continue;1503      }1504      const existing = byId.get(normalized.id);1505      if (!existing) {1506        entries.push(normalized);1507        added += 1;1508      } else if (normalized.modifiedAt > existing.modifiedAt) {1509        const idx = entries.findIndex((e) => e.id === existing.id);1510        if (idx !== -1) {1511          entries[idx] = normalized;1512          updated += 1;1513        }1514      } else {1515        skipped += 1;1516      }1517    }1518  }15191520  await persistEntries("import");1521  return { added, updated, skipped };1522}15231524/**1525 * Validate + normalise a VaultEntry coming from a backup. Accepts1526 * anything structurally sound; keeps all metadata verbatim. Returns1527 * null for values the live vault shouldn't accept (e.g., missing title).1528 */1529function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {1530  if (!entry || typeof entry !== "object") return null;1531  const title = typeof entry.title === "string" ? entry.title.trim() : "";1532  if (!title) return null;1533  const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();1534  const now = Date.now();1535  const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;1536  const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;15371538  // Migrate legacy passkey shape on import (same logic as on-disk read).1539  // Imports from pre-v2.11.0 vault backups still carry type:"passkey" with1540  // flat fields; bring them into the new shape immediately.1541  const migrated: VaultEntry = migrateLegacyPasskey(1542    {1543      ...entry,1544      id,1545      title,1546      type: entry.type ?? "login",1547      createdAt,1548      modifiedAt,1549    },1550    entry1551  );15521553  // Login entries from backup must carry a password (or be passkey-only,1554  // in which case the passkey sub-object replaces the password requirement).1555  if (1556    migrated.type === "login" &&1557    !migrated.passkey &&1558    typeof migrated.password !== "string"1559  ) {1560    return null;1561  }1562  if (migrated.passkey && !migrated.passkey.credentialId) {1563    return null;1564  }15651566  return migrated;1567}15681569// Soft-deletes every non-deleted entry in one call. The literal string1570// argument is a tripwire against accidental calls — any caller that would1571// wipe the vault has to consciously type "REPLACE_ALL". Do not relax this1572// to a boolean.1573export async function clearVaultEntries(1574  confirmation: "REPLACE_ALL"1575): Promise<void> {1576  if (confirmation !== "REPLACE_ALL") {1577    throw new Error("clearVaultEntries requires explicit confirmation");1578  }1579  if (!derivedKey) throw new Error("vault_locked");1580  for (const entry of entries) {1581    if (!entry.deletedAt) {1582      const stamp = monotonicEntryTimestamp(entry.modifiedAt);1583      entry.deletedAt = stamp;1584      entry.modifiedAt = stamp;1585    }1586  }1587  await persistEntries();1588}15891590export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {1591  if (!derivedKey) throw new Error("vault_locked");15921593  const sanitized = sanitizeEntryDraft(entry);1594  const now = Date.now();1595  const stamp = monotonicEntryTimestamp();1596  const nextEntry: VaultEntry = {1597    ...sanitized,1598    id: crypto.randomUUID(),1599    createdAt: now,1600    modifiedAt: stamp,1601    // Stamp passwordChangedAt at creation so age tracking is accurate from1602    // day one. Non-login entries carry the same stamp harmlessly.1603    passwordChangedAt: sanitized.password ? stamp : undefined,1604  };16051606  // Clone-and-replace so a failed persist rolls back the in-memory state1607  // (COR-008). Without this, a quota-full or storage error leaves the1608  // module-level `entries` ahead of what's actually on disk.1609  const rollback = entries;1610  entries = [...entries, nextEntry];1611  try {1612    await persistEntries();1613  } catch (err) {1614    entries = rollback;1615    throw err;1616  }16171618  // Fire-and-forget breach check (only for login entries if breach monitoring is enabled or not set)1619  if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {1620    checkBreach(nextEntry.password).then(async (count) => {1621      if (count > 0) {1622        const idx = entries.findIndex((e) => e.id === nextEntry.id);1623        if (idx !== -1) {1624          entries[idx] = { ...entries[idx], breach: count, modifiedAt: monotonicEntryTimestamp(entries[idx].modifiedAt) };1625          await persistEntries();1626        }1627      }1628    });1629  }16301631  fireSyncTrigger("vault_change");16321633  return nextEntry;1634}16351636export async function updateEntry(1637  id: string,1638  patch: Partial<VaultEntry>1639): Promise<void> {1640  if (!derivedKey) throw new Error("vault_locked");16411642  const idx = entries.findIndex((entry) => entry.id === id);1643  if (idx === -1 || entries[idx].deletedAt) {1644    throw new Error("entry_not_found");1645  }16461647  const current = entries[idx];1648  const sanitizedPatch = sanitizeEntryPatch(patch);1649  // Refresh passwordChangedAt only when the password value actually changes —1650  // a metadata-only update (title, tags, etc.) must not reset the age clock1651  // that drives the Pro health rotation recommendation.1652  const passwordChanged =1653    "password" in patch &&1654    typeof sanitizedPatch.password === "string" &&1655    sanitizedPatch.password !== current.password;1656  const stamp = monotonicEntryTimestamp(current.modifiedAt);1657  entries[idx] = {1658    ...current,1659    ...sanitizedPatch,1660    modifiedAt: stamp,1661    ...(passwordChanged ? { passwordChangedAt: stamp } : {}),1662  };1663166416651666  // Card entries must retain their card number1667  if (entries[idx].type === "card" && !entries[idx].cardNumber) {1668    entries[idx] = current;1669    throw new Error("card number is required for card entries");1670  }16711672  // Roll the in-memory entry back to its pre-edit state if the disk write1673  // fails (e.g. storage quota). Without this the module-level `entries` array1674  // would hold an edit that never landed on disk, diverging from the vault1675  // until the next unlock silently reverts it (SEV-3-A). Mirrors addEntry.1676  try {1677    await persistEntries();1678  } catch (err) {1679    entries[idx] = current;1680    throw err;1681  }16821683  // Breach check when password changes: clear immediately so old breach doesn't linger,1684  // then async-check the new password and only re-set if it's also found.1685  if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {1686    entries[idx] = { ...entries[idx], breach: undefined };1687    await persistEntries();1688    const password = entries[idx].password;1689    if (password) {1690      checkBreach(password).then(async (count) => {1691        const i = entries.findIndex((e) => e.id === id);1692        if (i !== -1 && count > 0) {1693          entries[i] = { ...entries[i], breach: count, modifiedAt: monotonicEntryTimestamp(entries[i].modifiedAt) };1694          await persistEntries();1695        }1696      });1697    }1698  }16991700  fireSyncTrigger("vault_change");1701}17021703export async function deleteEntry(id: string): Promise<void> {1704  if (!derivedKey) throw new Error("vault_locked");17051706  const entry = entries.find((item) => item.id === id);1707  if (!entry || entry.deletedAt) {1708    throw new Error("entry_not_found");1709  }17101711  // Tombstone timestamp must be strictly greater than the entry's last1712  // modification so the deletion wins LWW against any in-flight edit, even1713  // under clock skew (SEV-2-E).1714  const previousModifiedAt = entry.modifiedAt;1715  const stamp = monotonicEntryTimestamp(entry.modifiedAt);1716  entry.deletedAt = stamp;1717  entry.modifiedAt = stamp;1718  // Roll the tombstone back if the disk write fails, so a quota error doesn't1719  // leave the entry deleted in memory but alive on disk (SEV-3-A).1720  try {1721    await persistEntries();1722  } catch (err) {1723    delete entry.deletedAt;1724    entry.modifiedAt = previousModifiedAt;1725    throw err;1726  }1727  fireSyncTrigger("vault_change");1728}17291730export function getDeletedEntries(): VaultEntry[] {1731  if (!derivedKey) return [];1732  return entries.filter((e) => !!e.deletedAt);1733}17341735/**1736 * Returns the vault's monotonic version — the `peach_last_modified_at` value1737 * stamped on every user-initiated write. Remote (sync) writes do NOT advance1738 * this version so a sync round never cascades into a second outbound sync.1739 */1740export async function getVaultVersion(): Promise<number> {1741  try {1742    const raw = await chrome.storage.local.get("peach_last_modified_at");1743    const v = (raw as Record<string, unknown>).peach_last_modified_at;1744    if (typeof v === "number") return v;1745    if (typeof v === "string" && v !== "") {1746      const n = Number.parseInt(v, 10);1747      return Number.isFinite(n) ? n : 0;1748    }1749    return 0;1750  } catch {1751    return 0;1752  }1753}17541755/**1756 * Internal write variants — bypass `fireSyncTrigger` so the sync layer can1757 * apply entries without cascading into another outbound sync round.1758 *1759 * INVARIANT: callers must not pass entries whose IDs collide with existing1760 * active (non-deleted) entries unless the intent is an explicit overwrite.1761 * These functions do not validate field-level constraints (password required,1762 * card number required, etc.) — they are trust-the-caller paths for sync and1763 * test harness use only.1764 */1765export async function addEntryDirect(entry: VaultEntry): Promise<void> {1766  if (!derivedKey) throw new Error("vault_locked");1767  entries = [...entries, entry];1768  await persistEntries("sync_received");1769}17701771export async function updateEntryDirect(patch: VaultEntry): Promise<void> {1772  if (!derivedKey) throw new Error("vault_locked");1773  const idx = entries.findIndex((e) => e.id === patch.id);1774  if (idx === -1) throw new Error("entry_not_found");1775  entries[idx] = { ...entries[idx], ...patch };1776  await persistEntries("sync_received");1777}17781779export async function deleteEntryDirect(id: string, deletedAt: number): Promise<void> {1780  if (!derivedKey) throw new Error("vault_locked");1781  const idx = entries.findIndex((e) => e.id === id);1782  if (idx === -1) throw new Error("entry_not_found");1783  entries[idx] = { ...entries[idx], deletedAt, modifiedAt: deletedAt };1784  await persistEntries("sync_received");1785}17861787/**1788 * Apply a batch of remote entries + tombstones from a chirp-sync peer.1789 * Last-write-wins by `modifiedAt`; a tombstone supersedes a live entry when1790 * `deletedAt > modifiedAt` on the local side. Mutates `entries` directly and1791 * persists with reason `sync_received` — does NOT fire the sync dispatcher, so1792 * applying a sync round cannot cascade into another outbound sync.1793 *1794 * `applied` counts entries that actually changed local state (new add,1795 * overwrite-by-newer, or new tombstone). `received` is the raw payload size1796 * the caller can surface in the sync result UI.1797 */1798export async function applyMergedRemoteEntries(1799  remoteEntries: VaultEntry[],1800  remoteTombstones: Record<string, number>,1801): Promise<{ received: number; applied: number; conflicts: number }> {1802  // DESIGN: last-write-wins is applied PER-ENTRY, not per-field. If two devices1803  // concurrently edit different fields of the same entry, the one with the1804  // newer modifiedAt wins the whole entry and the other device's field edits1805  // are dropped silently. This is the deliberate trade-off for a simple,1806  // conflict-free merge — per-field CRDT merge is out of scope. Guidance for1807  // users: edit a given entry on one device at a time.1808  if (!derivedKey) throw new Error("vault_locked");18091810  const received = remoteEntries.length + Object.keys(remoteTombstones).length;1811  let applied = 0;1812  let conflicts = 0;18131814  const byId = new Map<string, VaultEntry>();1815  for (const e of entries) byId.set(e.id, e);18161817  for (const remote of remoteEntries) {1818    const sanitized = sanitizeRestoredEntry(remote);1819    if (!sanitized) continue;1820    const tombstoneTs = remoteTombstones[sanitized.id];1821    if (tombstoneTs !== undefined && tombstoneTs >= sanitized.modifiedAt) {1822      continue;1823    }1824    const local = byId.get(sanitized.id);1825    if (!local) {1826      entries.push(sanitized);1827      byId.set(sanitized.id, sanitized);1828      applied += 1;1829    } else if (sanitized.modifiedAt > local.modifiedAt) {1830      const idx = entries.findIndex((e) => e.id === local.id);1831      if (idx !== -1) {1832        entries[idx] = sanitized;1833        byId.set(sanitized.id, sanitized);1834        applied += 1;1835        if (!local.deletedAt) conflicts += 1;1836      }1837    }1838  }18391840  for (const [id, deletedAt] of Object.entries(remoteTombstones)) {1841    if (typeof deletedAt !== "number" || !Number.isFinite(deletedAt)) continue;1842    const local = byId.get(id);1843    if (!local) continue;1844    if (local.deletedAt && local.deletedAt >= deletedAt) continue;1845    if (deletedAt < local.modifiedAt) continue;1846    const idx = entries.findIndex((e) => e.id === id);1847    if (idx !== -1) {1848      entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };1849      applied += 1;1850    }1851  }18521853  if (applied > 0) {1854    await persistEntries("sync_received");1855    buildDomainIndexSync(entries);1856  }1857  return { received, applied, conflicts };1858}18591860export async function restoreEntry(id: string): Promise<void> {1861  if (!derivedKey) throw new Error("vault_locked");1862  const entry = entries.find((e) => e.id === id && e.deletedAt);1863  if (!entry) throw new Error("deleted entry not found");1864  delete entry.deletedAt;1865  entry.modifiedAt = monotonicEntryTimestamp(entry.modifiedAt);1866  await persistEntries();1867  buildDomainIndexSync(entries);1868}18691870export async function purgeEntry(id: string): Promise<void> {1871  if (!derivedKey) throw new Error("vault_locked");1872  const idx = entries.findIndex((e) => e.id === id && e.deletedAt);1873  if (idx === -1) throw new Error("deleted entry not found");1874  entries.splice(idx, 1);1875  await persistEntries();1876}18771878/** Permanently delete entries whose deletedAt is older than retentionMs. 0 = keep forever. */1879export async function purgeExpiredTrash(retentionMs: number): Promise<number> {1880  if (!derivedKey || retentionMs === 0) return 0;1881  const cutoff = Date.now() - retentionMs;1882  const before = entries.length;1883  entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));1884  const purged = before - entries.length;1885  if (purged > 0) await persistEntries();1886  return purged;1887}18881889export function queryDomain(domain: string): VaultEntry[] {1890  return domainIndex.get(domain) ?? [];1891}18921893export function getEntryById(id: string): VaultEntry | undefined {1894  return entries.find((entry) => entry.id === id && !entry.deletedAt);1895}18961897async function persistSlotA(1898  reason: VaultSnapshot["reason"] = "local_save",1899): Promise<StoredVault> {1900  if (!derivedKey) throw new Error("vault_locked");19011902  const slotA = await loadSlot(SLOT_A);1903  if (!slotA) throw new Error("missing slot A");19041905  // Snapshot the about-to-be-overwritten state BEFORE we mutate disk. Failures1906  // are swallowed by takeVaultSnapshot — history must never block a save.1907  await takeVaultSnapshot(reason);19081909  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);1910  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");19111912  // Preserve existing recovery escrow fields.1913  const nextSlotA: StoredVault = {1914    ...slotA,1915    nonce,1916    ciphertext,1917    tag,1918    // recovery_salt and recovery_wrapped_root_key are already set from loadSlot1919  };1920  await writeSlot(SLOT_A, nextSlotA);19211922  // Slot A (the real vault) is now committed. Wrap every later write so a1923  // mid-persist failure (e.g. a storage error after slot A landed) restores the1924  // prior slot A before rethrowing. Without this, a "failed" save that already1925  // wrote slot A leaves disk ahead of the in-memory rollback in addEntry/1926  // updateEntry/deleteEntry — the entry stays silently on disk and resurfaces1927  // as a duplicate on the next unlock (observed under storage-quota pressure).1928  try {1929    // When duress is not configured, keep slot B size-matched with slot A by1930    // regenerating its noise. When duress IS configured, leave slot B alone —1931    // we don't have the decoy key to re-encrypt it. This is a known trade-off.1932    if (!duressConfigured) {1933      await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));1934    }1935    // Only advance the vault version for locally-originated writes. Entries1936    // applied from a sync peer ("sync_received") must NOT bump the counter —1937    // otherwise applying a remote round makes us look newer than the peer and1938    // triggers a redundant outbound sync, defeating the no-op optimisation1939    // and risking a ping-pong between two devices (SEV-2-C).1940    if (reason !== "sync_received") {1941      await stampLocalVaultMutation();1942    }1943  } catch (err) {1944    // Best-effort restore — the prior slot A is smaller-or-equal, so this write1945    // fits even when the failure was a quota overflow.1946    await writeSlot(SLOT_A, slotA).catch(() => {});1947    throw err;1948  }19491950  return nextSlotA;1951}19521953async function persistSlotB(): Promise<void> {1954  if (!derivedKey) throw new Error("vault_locked");19551956  const slotB = await loadSlot(SLOT_B);1957  if (!slotB) throw new Error("missing slot B");19581959  // Decoy plaintext always reports duressConfigured=false — the decoy user1960  // sees a clean slate. persistSlotB only runs in decoy mode, which only1961  // exists once duress is configured, so pad to the fixed duress ceiling to1962  // keep slot B's length equal to slot A's (audit MEDIUM — deniability).1963  const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);1964  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");19651966  await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });1967  // Symmetric with persistSlotA: if the version stamp fails after the decoy1968  // slot committed, restore the prior slot B so a failed decoy-mode save can't1969  // leave disk ahead of the in-memory rollback.1970  try {1971    await stampLocalVaultMutation();1972  } catch (err) {1973    await writeSlot(SLOT_B, slotB).catch(() => {});1974    throw err;1975  }1976}19771978async function persistEntries(1979  reason: VaultSnapshot["reason"] = "local_save",1980): Promise<void> {1981  if (!derivedKey) throw new Error("vault_locked");19821983  if (vaultMode === "decoy") {1984    await persistSlotB();1985  } else {1986    await persistSlotA(reason);1987  }1988  buildDomainIndexSync(entries);1989}19901991function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {1992  if (!Array.isArray(values)) return undefined;1993  const seen = new Set<string>();1994  const cleaned: string[] = [];1995  for (const value of values) {1996    const trimmed = typeof value === "string" ? value.trim() : "";1997    if (!trimmed) continue;1998    const key = trimmed.toLowerCase();1999    if (seen.has(key)) continue;2000    seen.add(key);2001    cleaned.push(trimmed);2002  }2003  return cleaned.length > 0 ? cleaned : undefined;2004}20052006function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {2007  const title = entry.title.trim();2008  // Accept legacy `type:"passkey"` drafts but rewrite to "login" — the new2009  // model is "any entry, optionally with a passkey sub-object." Imports and2010  // any in-flight callers from before v2.11.0 keep working without throwing.2011  let type: VaultEntry["type"] = entry.type ?? "login";2012  if (type === "passkey") type = "login";20132014  if (!title) throw new Error("title is required");20152016  if (entry.passkey) {2017    const p = entry.passkey;2018    if (2019      !p.rpId ||2020      !p.credentialId ||2021      !p.publicKeyCose ||2022      !p.userHandle ||2023      !p.userName ||2024      (p.algorithm !== -7 && p.algorithm !== -8)2025    ) {2026      throw new Error("invalid passkey credential");2027    }2028  }2029  if (type === "card") {2030    if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {2031      throw new Error("cardholder name and card number are required");2032    }2033  }20342035  return {2036    type,2037    title,2038    username: type === "login" ? entry.username?.trim() ?? "" : undefined,2039    email: type === "login" ? entry.email?.trim() || undefined : undefined,2040    password: type === "login" ? entry.password : undefined,2041    url: type === "login" ? entry.url?.trim() ?? "" : undefined,2042    additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,2043    totp: type === "login" ? entry.totp?.trim() || undefined : undefined,2044    notes: entry.notes?.trim() || undefined,2045    breach: type === "login" ? entry.breach : undefined,2046    canary: type === "login" ? entry.canary : undefined,2047    tags: entry.tags,2048    passkey: entry.passkey,2049    cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,2050    cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,2051    expMonth: type === "card" ? entry.expMonth?.trim() : undefined,2052    expYear: type === "card" ? entry.expYear?.trim() : undefined,2053    cvc: type === "card" ? entry.cvc?.trim() : undefined,2054    cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,2055    network: type === "card" ? entry.network : undefined,2056    last4: type === "card" ? entry.last4?.trim() : undefined,2057  };2058}20592060function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {2061  const nextPatch: Partial<VaultEntry> = {};20622063  if ("type" in patch) {2064    nextPatch.type = patch.type;2065  }20662067  if ("title" in patch) {2068    const title = patch.title?.trim() ?? "";2069    if (!title) throw new Error("title is required");2070    nextPatch.title = title;2071  }20722073  if ("url" in patch) {2074    nextPatch.url = patch.url?.trim() ?? "";2075  }20762077  if ("additionalUrls" in patch) {2078    const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];2079    const seen = new Set<string>();2080    const cleaned: string[] = [];2081    for (const value of incoming) {2082      const trimmed = typeof value === "string" ? value.trim() : "";2083      if (!trimmed) continue;2084      const key = trimmed.toLowerCase();2085      if (seen.has(key)) continue;2086      seen.add(key);2087      cleaned.push(trimmed);2088    }2089    nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;2090  }20912092  if ("username" in patch) {2093    nextPatch.username = patch.username?.trim() ?? "";2094  }20952096  if ("email" in patch) {2097    nextPatch.email = patch.email?.trim() || undefined;2098  }20992100  if ("password" in patch) {2101    const password = patch.password ?? "";2102    // Allow clearing a password (e.g. on passkey-only entries)2103    nextPatch.password = password || undefined;2104  }21052106  if ("totp" in patch) {2107    nextPatch.totp = patch.totp?.trim() || undefined;2108  }21092110  if ("notes" in patch) {2111    nextPatch.notes = patch.notes?.trim() || undefined;2112  }21132114  if ("breach" in patch) {2115    nextPatch.breach = patch.breach;2116  }21172118  if ("canary" in patch) {2119    nextPatch.canary = patch.canary;2120  }21212122  if ("passkey" in patch) {2123    // Passkey sub-object replaces all the legacy flat passkey fields. A2124    // patch with `passkey: undefined` removes the credential from the entry2125    // (used by "remove passkey" without deleting the whole entry).2126    nextPatch.passkey = patch.passkey;2127  }21282129  if ("tags" in patch) {2130    nextPatch.tags = patch.tags;2131  }21322133  if ("cardholderName" in patch) {2134    nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;2135  }2136  if ("cardNumber" in patch) {2137    const n = patch.cardNumber ?? "";2138    nextPatch.cardNumber = n || undefined;2139  }2140  if ("expMonth" in patch) {2141    nextPatch.expMonth = patch.expMonth?.trim() || undefined;2142  }2143  if ("expYear" in patch) {2144    nextPatch.expYear = patch.expYear?.trim() || undefined;2145  }2146  if ("cvc" in patch) {2147    nextPatch.cvc = patch.cvc?.trim() || undefined;2148  }2149  if ("cardNickname" in patch) {2150    nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;2151  }2152  if ("network" in patch) {2153    nextPatch.network = patch.network;2154  }2155  if ("last4" in patch) {2156    nextPatch.last4 = patch.last4?.trim() || undefined;2157  }21582159  return nextPatch;2160}21612162function normalizeEntry(entry: VaultEntry | LegacyVaultEntry): VaultEntry {2163  const createdAt = "createdAt" in entry ? entry.createdAt : entry.created;2164  const modifiedAt =2165    "modifiedAt" in entry ? entry.modifiedAt : entry.updated;21662167  const base: VaultEntry = {2168    id: entry.id,2169    type: "type" in entry ? entry.type : "login",2170    title: entry.title,2171    username: entry.username,2172    email: "email" in entry ? entry.email : undefined,2173    password: entry.password,2174    url: entry.url,2175    additionalUrls:2176      "additionalUrls" in entry && Array.isArray(entry.additionalUrls)2177        ? entry.additionalUrls2178        : undefined,2179    totp: entry.totp,2180    notes: entry.notes,2181    breach: entry.breach,2182    // Preserve the password-age clock across lock/unlock. Without this the2183    // field is dropped on every decode and the advanced-health "aged password"2184    // signal silently resets to createdAt on each unlock (SEV-2-A).2185    passwordChangedAt:2186      "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,2187    canary: "canary" in entry ? entry.canary : undefined,2188    passkey: "passkey" in entry ? entry.passkey : undefined,2189    createdAt,2190    modifiedAt,2191    deletedAt: entry.deletedAt,2192    tags: "tags" in entry ? entry.tags : undefined,2193    cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,2194    cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,2195    expMonth: "expMonth" in entry ? entry.expMonth : undefined,2196    expYear: "expYear" in entry ? entry.expYear : undefined,2197    cvc: "cvc" in entry ? entry.cvc : undefined,2198    cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,2199    network: "network" in entry ? entry.network : undefined,2200    last4: "last4" in entry ? entry.last4 : undefined,2201  };22022203  return migrateLegacyPasskey(base, entry);2204}22052206/**2207 * v2.11.0 read migration. Pre-v2.11.0 passkey entries used `type:"passkey"`2208 * with flat top-level fields (rpId, credentialId, etc.). This converts them2209 * to the new shape — `type:"login"` with a `passkey` sub-object — so all2210 * downstream consumers can rely on the new model. The result is rewritten2211 * to disk on next vault save (hasLegacyShape detects the un-migrated case).2212 */2213function migrateLegacyPasskey(2214  base: VaultEntry,2215  raw: VaultEntry | LegacyVaultEntry2216): VaultEntry {2217  if (base.passkey) return base;2218  const flat = raw as Partial<VaultEntry>;2219  const isPasskeyType = base.type === "passkey";2220  const hasFlatPasskeyFields =2221    typeof flat.rpId === "string" &&2222    typeof flat.credentialId === "string" &&2223    typeof flat.publicKeyCose === "string" &&2224    typeof flat.userHandle === "string" &&2225    typeof flat.userName === "string";2226  if (!isPasskeyType && !hasFlatPasskeyFields) return base;2227  if (!hasFlatPasskeyFields) return base;22282229  const algorithm: -7 | -8 = flat.algorithm === -8 ? -8 : -7;2230  base.passkey = {2231    rpId: flat.rpId!,2232    rpName: flat.rpName ?? flat.rpId!,2233    credentialId: flat.credentialId!,2234    publicKeyCose: flat.publicKeyCose!,2235    privateKeyJwk: flat.privateKeyJwk,2236    userHandle: flat.userHandle!,2237    userName: flat.userName!,2238    userDisplayName: flat.userDisplayName ?? flat.userName!,2239    algorithm,2240    signCount: flat.signCount ?? 0,2241    aaguid: flat.aaguid ?? "",2242    backupEligible: flat.backupEligible === true,2243    backupState: flat.backupState === true,2244    lastUsedAt: flat.lastUsedAt,2245    browser: flat.browser,2246    transports: flat.transports,2247    createdAt: base.createdAt,2248  };2249  // Promote to "login" so the unified Entry view renders. Username gets2250  // populated from the passkey's userName so the entry is searchable in the2251  // existing autofill flow without a separate code path.2252  if (isPasskeyType) base.type = "login";2253  if (!base.username) base.username = flat.userName;2254  if (!base.url) base.url = `https://${flat.rpId}`;2255  return base;2256}225722582259// ---------------------------------------------------------------------------2260// Deduplication2261// ---------------------------------------------------------------------------22622263function entryDupeKey(e: VaultEntry): string {2264  if (e.type === "note") return `note|${e.title.toLowerCase()}`;2265  // Passkey-bearing entries dedupe by the credential's RP + user. Two logins2266  // on different sites that happen to share a username are still distinct;2267  // two passkey credentials for the same RP+user are duplicates regardless2268  // of any login fields they may also carry.2269  if (e.passkey) {2270    return `passkey|${e.passkey.rpId.toLowerCase()}|${e.passkey.userName.toLowerCase()}`;2271  }2272  return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;2273}22742275/** Returns the number of duplicate entries (those that would be removed). */2276export function countDuplicates(): number {2277  const best = new Map<string, VaultEntry>();2278  let dupeCount = 0;2279  for (const e of entries.filter((e) => !e.deletedAt)) {2280    const key = entryDupeKey(e);2281    const existing = best.get(key);2282    if (!existing) {2283      best.set(key, e);2284    } else {2285      dupeCount++;2286      // Keep the more recently modified one in the map2287      if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2288        best.set(key, e);2289      }2290    }2291  }2292  return dupeCount;2293}22942295/**2296 * Soft-deletes duplicate entries, keeping the most recently modified copy of2297 * each group. Returns the number of entries moved to trash.2298 */2299export async function deduplicateEntries(): Promise<number> {2300  if (!derivedKey) throw new Error("vault_locked");2301  // Dedup reshapes slot B permanently under the decoy key, which is2302  // forensically distinguishable from a freshly-seeded decoy vault. Refuse.2303  if (vaultMode === "decoy") {2304    throw new Error("deduplicate disabled in decoy mode");2305  }23062307  const best = new Map<string, VaultEntry>();2308  for (const e of entries.filter((en) => !en.deletedAt)) {2309    const key = entryDupeKey(e);2310    const existing = best.get(key);2311    if (!existing) {2312      best.set(key, e);2313    } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2314      best.set(key, e);2315    }2316  }23172318  const keepIds = new Set(Array.from(best.values()).map((e) => e.id));2319  let removed = 0;2320  entries = entries.map((e) => {2321    if (!e.deletedAt && !keepIds.has(e.id)) {2322      removed++;2323      return { ...e, deletedAt: monotonicEntryTimestamp(e.modifiedAt) };2324    }2325    return e;2326  });23272328  if (removed > 0) await persistEntries();2329  return removed;2330}23312332// ---------------------------------------------------------------------------2333// Vault history — snapshot BEFORE every vault write so the saved blob is2334// what is about to be lost, not what was just written. Capped at 5. The2335// stored blobs are AES-256-GCM ciphertext under the master password, so2336// history adds zero security surface.2337// ---------------------------------------------------------------------------23382339const HISTORY_KEY = "peach_vault_history";2340const HISTORY_MAX = 5;23412342/**2343 * Snapshot the CURRENT on-disk vault state into history. Call this BEFORE2344 * overwriting peach_vault_a so the saved blob captures the about-to-be-lost2345 * state. Identical-to-most-recent blobs are skipped to avoid filling history2346 * with no-op writes.2347 */2348export async function takeVaultSnapshot(2349  reason: VaultSnapshot["reason"],2350): Promise<void> {2351  try {2352    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);2353    const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];2354    const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];23552356    // Nothing to snapshot if the real slot doesn't exist yet (fresh install,2357    // pre-createVault). createVault skips snapshots intentionally — there is2358    // no prior state to preserve.2359    if (!slotA) return;23602361    const vault_a = JSON.stringify(slotA);2362    const vault_b = JSON.stringify(slotB ?? slotA);23632364    // Best-effort entry count: only meaningful when the in-memory state is2365    // unlocked AND in real mode. Decoy mode would leak the decoy entry2366    // count; locked mode has no entries to count. Both fall through to null.2367    let entryCount: number | null = null;2368    if (derivedKey && vaultMode === "real") {2369      try {2370        entryCount = entries.filter((e) => !e.deletedAt).length;2371      } catch {2372        entryCount = null;2373      }2374    }23752376    const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];2377    const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)2378      ? existingRaw2379      : { snapshots: [] };23802381    // Deduplication: if the most recent snapshot has byte-identical blobs,2382    // skip — saves the same vault N times in a row would otherwise burn the2383    // entire history window with no recovery value.2384    const latest = history.snapshots[0];2385    if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {2386      return;2387    }23882389    const snapshot: VaultSnapshot = {2390      id: crypto.randomUUID(),2391      savedAt: Date.now(),2392      reason,2393      vault_a,2394      vault_b,2395      entryCount,2396    };23972398    history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);2399    await chrome.storage.local.set({ [HISTORY_KEY]: history });2400  } catch (err) {2401    // Non-fatal — history must never block a save. A failed snapshot just2402    // means the user loses one rung of the safety ladder for this write.2403    // M4/QUA-006: log so the failure is visible; if it looks like a quota2404    // problem, notify the popup so the user can prune history themselves.2405    console.warn('[Peach] takeVaultSnapshot failed:', err);2406    if (String(err).includes('QUOTA') || String(err).includes('quota')) {2407      try {2408        await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });2409      } catch {2410        // popup may be closed; surfaced via console.warn above2411      }2412    }2413  }2414}24152416/** Wipe all vault history. Called by Panic / DESTROY_VAULT. */2417export async function clearVaultHistory(): Promise<void> {2418  try {2419    await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });2420  } catch {2421    // Non-fatal — DESTROY_VAULT also runs storage.local.clear().2422  }2423}24242425/** Read all snapshots, newest first, for the Settings vault history view. */2426export async function getVaultHistory(): Promise<VaultSnapshot[]> {2427  const raw = await chrome.storage.local.get(HISTORY_KEY);2428  const history = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];2429  if (!history || !Array.isArray(history.snapshots)) return [];2430  return history.snapshots;2431}24322433/**2434 * Replace the on-disk vault with the chosen snapshot's blobs and lock the2435 * vault. The current state is itself snapshotted with reason 'restore' first2436 * so the restore is reversible. After this returns, the user must unlock2437 * with the password that matches the restored blob.2438 */2439export async function restoreVaultSnapshot(2440  snapshotId: string,2441): Promise<{ ok: true } | { ok: false; error: string }> {2442  const history = await getVaultHistory();2443  const snapshot = history.find((s) => s.id === snapshotId);2444  if (!snapshot) return { ok: false, error: "snapshot_not_found" };24452446  // Snapshot the about-to-be-replaced current state so the restore is2447  // reversible. takeVaultSnapshot is no-op when the most recent entry is2448  // byte-identical, so a restore-of-a-restore stays clean.2449  await takeVaultSnapshot("restore");24502451  let restoredA: StoredVault;2452  let restoredB: StoredVault;2453  try {2454    restoredA = JSON.parse(snapshot.vault_a) as StoredVault;2455    restoredB = JSON.parse(snapshot.vault_b) as StoredVault;2456  } catch {2457    return { ok: false, error: "snapshot_corrupt" };2458  }24592460  await writeSlot(SLOT_A, restoredA);2461  await writeSlot(SLOT_B, restoredB);2462  await stampLocalVaultMutation();24632464  // Lock so the user must prove they can decrypt the restored blob. If they2465  // restored a pre-password-change snapshot they discover it immediately at2466  // the lock screen rather than silently holding an inaccessible vault.2467  lock();24682469  return { ok: true };2470}24712472/**2473 * Change the master password. Re-encrypts slot A with a fresh salt + new2474 * derived key. Slot B (duress or noise) is left untouched when duress is2475 * configured — it uses an independent key derived from the duress password —2476 * and regenerated as noise when duress is not configured.2477 */2478export async function changePassword(2479  currentPassword: string,2480  newPassword: string2481): Promise<boolean> {2482  if (!derivedKey || vaultMode !== "real") return false;24832484  // Verify current password before allowing any change2485  const valid = await verifyMainPassword(currentPassword);2486  if (!valid) return false;24872488  const slotA = await loadSlot(SLOT_A);2489  if (!slotA) return false;2490  if (!rootKey) return false;24912492  // Derive fresh key from new password + new random salt2493  const newSalt = generateSalt();2494  const newKey = await deriveKey(newPassword, newSalt);24952496  // Re-encrypt the in-memory entries with the new key2497  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);2498  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");24992500  // Pre-wrap root key under the new derived key. Recovery fields wrap rootKey2501  // under recovery words and remain untouched — recovery phrase keeps working2502  // across password changes (H4/COR-002).2503  const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);25042505  const finalSlotA: StoredVault = {2506    ...slotA,2507    salt: hex(newSalt),2508    nonce,2509    ciphertext,2510    tag,2511    ...pwRoot,2512  };25132514  // Snapshot the OLD-key blob before overwriting it. If the user later2515  // restores from this snapshot they will need the OLD password — the2516  // post-restore lock surfaces that immediately.2517  await takeVaultSnapshot("local_save");25182519  // Single atomic write: ciphertext, salt, and pw_root_* fields all land in2520  // one storage transaction. An SW kill before this point leaves the old2521  // slot intact; after this point everything tied to the new password is2522  // already on disk together (M6/COR-004).2523  await writeSlot(SLOT_A, finalSlotA);25242525  // Swap the in-memory key synchronously before any further await. If we2526  // threw between the Slot A write and this swap, the next persistEntries()2527  // would overwrite Slot A with old-key ciphertext, locking the user out.2528  zeroKey(derivedKey);2529  derivedKey = newKey;25302531  // Regenerate noise for slot B when duress is not in use. Runs after the2532  // key swap so a failure here is a disposable noise regeneration, not a2533  // lockout.2534  if (!duressConfigured) {2535    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));2536  }2537  await stampLocalVaultMutation();25382539  return true;2540}