vault.ts

115.0 KB · raw

1/**2 * vault.ts — sole owner of vault state and chrome.storage vault keys.3 *4 * Every read/write of `peach_vault_a`, `peach_vault_b`, and `peach_settings`5 * goes through this module. No other file accesses those keys directly.6 * External callers reach vault operations via `messages.ts` — never by7 * importing from here cross-boundary (popup/content must not). Invariants8 * for the two-slot schema, unlock timing, and key/disk atomicity are in9 * Projects.md §3.2–§3.6.10 */1112import { deriveKey, deriveKeyRaw, generateSalt } from "../crypto/argon2";13import { extractDomain } from "../shared/domain";14import { clampSyncTimestamp } from "../shared/sync-limits";15import { computeVaultId } from "../shared/sync-identity";16// Static, not `await import()`: runtime import() throws in an MV3 service17// worker. Neither module imports vault.ts back, so there is no cycle to break.18import { triggerSyncIfReachable } from "./sync-trigger";19import { clearPairedDevices } from "./paired-devices";20import {21  rootKeyToWords,22  wordsToRootKeyMaterial,23  deriveRecoveryKey,24} from "../shared/recovery-words";25import type {26  AccentColorName,27  Canary,28  LegacyVaultEntry,29  ManualSummonRecord,30  PasskeyData,31  SavedIdentity,32  StoredVault,33  VaultEntry,34  VaultHistory,35  VaultSnapshot,36} from "../shared/types";37import { decrypt, encrypt, zeroKey } from "./aes";38import { clearAutoLock, touchAutoLock } from "./alarms";39import { setRecoveryConfirmPending } from "./recovery-pending";4041type EntryDraft = Omit<42  VaultEntry,43  "id" | "createdAt" | "modifiedAt" | "deletedAt"44>;4546// Slot-neutral storage keys (v1.4.24+). Both slots always exist; slot B47// either holds the decoy vault (when duress is configured) or random noise48// that looks identical at rest. No external indicator is stored — duress49// configuration is recorded only inside the encrypted payload of slot A.50const SLOT_A = "peach_vault_a";51const SLOT_B = "peach_vault_b";5253// Legacy keys, migrated away on first access.54const LEGACY_MAIN = "peach_vault";55const LEGACY_DECOY = "peach_decoy_vault";56const LEGACY_DURESS_FLAG = "peach_duress";5758// Plaintext is padded to the next multiple of this size before encryption.59// This coarsens ciphertext-length leakage into 1 KiB buckets.60const PAD_BLOCK = 1024;6162// How many past passwords to retain per entry. Generous enough to be useful as63// a recovery aid while bounding the secret material we hold (and the ciphertext64// growth) for an entry whose password is rotated frequently.65const PASSWORD_HISTORY_MAX = 50;6667// When duress is configured, BOTH slots are padded to this fixed ceiling so68// their ciphertext lengths are identical and cannot reveal that a hidden decoy69// vault exists (audit MEDIUM — plausible-deniability leak). 256 KiB comfortably70// holds a very large vault (thousands of entries incl. passkeys). The decoy71// slot can't be re-encrypted on every real-vault save (the real session has no72// decoy key), so a fixed ceiling — rather than size-matching on each write — is73// what keeps the two slots equal. A real vault whose plaintext exceeds this74// would grow past the ceiling and re-expose the bit; that is an extreme,75// documented edge well beyond normal use.76const DURESS_SLOT_SIZE = 262_144;7778let derivedKey: Uint8Array | null = null;79// 32-byte random root key, separate from the derivedKey used for vault encryption.80// The root key is wrapped (encrypted) under the recovery key derived from the81// 12-word phrase. When the user changes their password, only the wrapping changes;82// the root key and recovery words remain stable.83let rootKey: Uint8Array | null = null;84let entries: VaultEntry[] = [];85let domainIndex: Map<string, VaultEntry[]> = new Map();86let vaultMode: "real" | "decoy" = "real";87// Cached post-unlock view of whether the real vault records that duress is88// configured. Only meaningful after a real-mode unlock; for decoy-mode unlock89// this stays false because we never see slot A's plaintext.90let duressConfigured = false;9192let migrationRan = false;9394// Set to a corruption reason during the last unlock() attempt when both slots95// decrypted but failed schema validation. Consumed and cleared by96// consumeLastUnlockFailureReason() so messages.ts can surface vault_corrupted97// distinctly from wrong-password (M7/COR-007).98//99// NOTE: module-level state — if vault.ts is ever moved to a worker context,100// this must be replaced with a structured return value from unlock() or a101// postMessage channel. The signal is invisible across module-instance102// boundaries.103let lastUnlockFailureReason: string | null = null;104105export function consumeLastUnlockFailureReason(): string | null {106  const r = lastUnlockFailureReason;107  lastUnlockFailureReason = null;108  return r;109}110111// ---------------------------------------------------------------------------112// Settings (persisted inside the encrypted vault store as a sidecar key)113// ---------------------------------------------------------------------------114115export type TextSize = "small" | "medium" | "large";116117export interface VaultSettings {118  accentColor?: AccentColorName;119  theme?: "dark" | "light";120  autoLockMinutes?: number;121  clipboardClearSeconds?: number;122  lockOnClose?: boolean;123  breachMonitoring?: boolean;124  passkeyProviderEnabled?: boolean;125  trashRetentionDays?: number;126  manualSummonDomains?: Record<string, ManualSummonRecord>;127  declinedCardFingerprints?: string[];128  /**129   * Text size scale for body copy and entry titles. Stops at "large" by130   * design — XL clips dense screens (Vault, Health) inside the fixed131   * 330×480 popup surface.132   */133  textSize?: TextSize;134  /**135   * When true, all entrance/exit transitions and ambient animations are136   * collapsed to instant. Honoured alongside the user's OS-level137   * `prefers-reduced-motion`.138   */139  reduceMotion?: boolean;140  /**141   * Android-only: when true, the master key is escrowed in AndroidKeyStore142   * and the lock screen offers biometric unlock. Toggled from Settings →143   * Security → Biometrics. Has no effect on desktop builds.144   */145  biometricsEnabled?: boolean;146  /**147   * User overrides for keyboard shortcuts. Keys are ShortcutAction names148   * (see src/shared/shortcuts.ts). Missing actions fall through to149   * DEFAULT_BINDINGS — `getActiveBindings(settings.shortcuts)` is the150   * canonical lookup. Storing only the deltas keeps the vault payload151   * small and lets default updates land for users who never rebind.152   */153  shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;154}155156let settings: VaultSettings = {};157158export function getSettings(): VaultSettings {159  return settings;160}161162export async function ensureSettingsLoaded(): Promise<VaultSettings> {163  await loadSettings();164  return settings;165}166167export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {168  await loadSettings();169  // LV-7: cheap insurance against prototype pollution if a future caller ever170  // feeds parsed external JSON here (native spread keeps __proto__ an own-171  // property today, but Object.assign-style consumers and JSON revivers have172  // been burned before).173  const safe = Object.fromEntries(174    Object.entries(patch).filter(175      ([k]) => !["__proto__", "constructor", "prototype"].includes(k),176    ),177  ) as Partial<VaultSettings>;178  settings = { ...settings, ...safe };179  await persistSettings();180}181182async function persistSettings(): Promise<void> {183  try {184    await chrome.storage.local.set({ peach_settings: settings });185  } catch (err) {186    throw mapStorageError(err);187  }188}189190function mapStorageError(err: unknown): Error {191  const message = err instanceof Error ? err.message : String(err);192  if (/QUOTA_BYTES|quota/i.test(message)) {193    return new Error("STORAGE_QUOTA_EXCEEDED");194  }195  return err instanceof Error ? err : new Error(message);196}197198async function loadSettings(): Promise<void> {199  const result = await chrome.storage.local.get("peach_settings");200  settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};201}202203// Fire-and-forget sync trigger after a committed vault write. A failure here204// must never fail the write that caused it.205function fireSyncTrigger(reason: "vault_change"): void {206  void Promise.resolve()207    .then(() => triggerSyncIfReachable({ reason }))208    .catch(() => {209      /* no sync runner registered, or nothing reachable — non-fatal */210    });211}212213// ---------------------------------------------------------------------------214// HIBP breach check (k-anonymity model)215// ---------------------------------------------------------------------------216217export async function checkBreach(password: string): Promise<number> {218  // HIBP k-anonymity API is keyed on SHA-1 prefixes — this is dictated by219  // the public API, not a security choice. Do not migrate to SHA-256 here.220  const encoder = new TextEncoder();221  const hashBuffer = await crypto.subtle.digest("SHA-1", encoder.encode(password));222  const hashHex = Array.from(new Uint8Array(hashBuffer))223    .map((b) => b.toString(16).padStart(2, "0"))224    .join("")225    .toUpperCase();226227  const prefix = hashHex.slice(0, 5);228  const suffix = hashHex.slice(5);229230  try {231    // PCH-02-007: request HIBP response padding so response length does not232    // reveal how many suffixes a queried prefix returned.233    const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`, {234      headers: { "Add-Padding": "true" },235    });236    if (!res.ok) return 0;237    const text = await res.text();238    const match = text.split("\r\n").find((l) => l.startsWith(suffix));239    return match ? parseInt(match.split(":")[1], 10) : 0;240  } catch {241    return 0; // Network unavailable — don't block242  }243}244245export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {246  const fingerprint = await cardFingerprint(last4, expMonth, expYear);247  await loadSettings();248  settings = {249    ...settings,250    declinedCardFingerprints: [...(settings.declinedCardFingerprints ?? []), fingerprint],251  };252  await persistSettings();253}254255export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {256  await loadSettings();257  const fingerprint = await cardFingerprint(last4, expMonth, expYear);258  return (settings.declinedCardFingerprints ?? []).includes(fingerprint);259}260261async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {262  const encoder = new TextEncoder();263  const buf = await crypto.subtle.digest("SHA-256", encoder.encode(`${last4}|${expMonth}|${expYear}`));264  return Array.from(new Uint8Array(buf).slice(0, 8))265    .map((b) => b.toString(16).padStart(2, "0"))266    .join("");267}268269function hex(buf: Uint8Array): string {270  return Array.from(buf)271    .map((b) => b.toString(16).padStart(2, "0"))272    .join("");273}274275function unhex(s: string): Uint8Array {276  const out = new Uint8Array(s.length / 2);277  for (let i = 0; i < s.length; i += 2) {278    out[i / 2] = parseInt(s.slice(i, i + 2), 16);279  }280  return out;281}282283// ---------------------------------------------------------------------------284// Root key generation and recovery word wrapping285// ---------------------------------------------------------------------------286287/**288 * Generate a random 32-byte root key and wrap it (AES-256-GCM) under a key289 * derived from the recovery word material via HKDF-SHA256. The wrapped blob290 * fields are stored in slot A alongside the password-wrapped ciphertext. The291 * root key itself is kept in memory for the session so getRecoveryWords() can292 * encode it without re-deriving.293 *294 * SECURITY MODEL (PCH-01-005): the recovery KEK is derived from the 12-word295 * material, which encodes only rootKey[0..16] (recovery-words.ts). The KEK is thus296 * derived from a PREFIX of the very plaintext it wraps, and effective recovery297 * security is 128-bit (standard for a 12-word phrase), NOT 256-bit. This is safe —298 * unwrapping requires the words, and the GCM ciphertext leaks nothing without them —299 * but it is intentional, not an oversight. A future escrow version wanting 256-bit300 * recovery must derive the words from INDEPENDENT entropy, not from the root key.301 */302async function generateAndWrapRootKey(): Promise<{303  rawRootKey: string; // hex of the plaintext root key — caller stores in rootKey304  recoverySalt: string;305  wrappedRootKey: string;306  wrappedNonce: string;307  wrappedTag: string;308}> {309  const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));310311  // Derive the recovery key from the BIP39 words encoding of the root key.312  const words = await rootKeyToWords(rootKeyBytes);313  const wordMaterial = await wordsToRootKeyMaterial(words);314  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));315  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);316317  // Wrap the root key with the recovery key using AES-256-GCM directly.318  // We hex-encode rootKeyBytes so the plaintext is always valid UTF-8.319  const nonce = crypto.getRandomValues(new Uint8Array(12));320  const encoded = new TextEncoder().encode(hex(rootKeyBytes));321  const raw = await crypto.subtle.encrypt(322    {323      name: "AES-GCM",324      iv: nonce,325      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,326      tagLength: 128,327    },328    recoveryKey,329    encoded330  );331  // WebCrypto returns ciphertext || auth tag concatenated; split them.332  const rawU8 = new Uint8Array(raw);333  const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));334  const tag = hex(rawU8.slice(rawU8.length - 16));335336  return {337    rawRootKey: hex(rootKeyBytes),338    recoverySalt: hex(recoverySalt),339    wrappedRootKey: ciphertext,340    wrappedNonce: hex(nonce),341    wrappedTag: tag,342  };343}344345async function wrapExistingRootKeyForRecovery(rootKeyBytes: Uint8Array): Promise<{346  recoverySalt: string;347  wrappedRootKey: string;348  wrappedNonce: string;349  wrappedTag: string;350}> {351  if (rootKeyBytes.length !== 32) {352    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");353  }354355  const words = await rootKeyToWords(rootKeyBytes);356  const wordMaterial = await wordsToRootKeyMaterial(words);357  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));358  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);359  const nonce = crypto.getRandomValues(new Uint8Array(12));360  const encoded = new TextEncoder().encode(hex(rootKeyBytes));361  const raw = await crypto.subtle.encrypt(362    {363      name: "AES-GCM",364      iv: nonce,365      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,366      tagLength: 128,367    },368    recoveryKey,369    encoded,370  );371  const rawU8 = new Uint8Array(raw);372  return {373    recoverySalt: hex(recoverySalt),374    wrappedRootKey: hex(rawU8.slice(0, rawU8.length - 16)),375    wrappedNonce: hex(nonce),376    wrappedTag: hex(rawU8.slice(rawU8.length - 16)),377  };378}379380/**381 * Unwrap the root key using recovery words. Called during recovery flow when382 * the user provides their 12-word phrase and a new password.383 * Exported for use by the RECOVER_WITH_WORDS message handler.384 */385export async function unwrapRootKeyForRecovery(386  wrappedRootKey: string,387  wrappedNonce: string,388  wrappedTag: string,389  recoverySaltHex: string,390  words: string[]391): Promise<void> {392  const wordMaterial = await wordsToRootKeyMaterial(words);393  const recoverySalt = unhex(recoverySaltHex);394  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);395396  // Decrypt and cache the root key. The root key bytes were hex-encoded before397  // encryption so the ciphertext is valid UTF-8. We inline the AES-GCM decrypt398  // here to avoid passing a CryptoKey to the string-based encrypt/decrypt helpers.399  // Each component is stored separately in the vault slot; decode them individually400  // so the nonce is always exactly the 12 bytes from wrappedNonce.401  const nonceRaw = unhex(wrappedNonce);402  const ciphertextRaw = unhex(wrappedRootKey);403  const tagRaw = unhex(wrappedTag);404  // Combine ciphertext and tag for AES-GCM (expects ciphertext||tag).405  // Use explicit ArrayBuffer allocations to satisfy TS BufferSource constraints.406  const nonceU8 = nonceRaw as unknown as Uint8Array<ArrayBuffer>;407  const combined = new Uint8Array(ciphertextRaw.length + tagRaw.length);408  combined.set(ciphertextRaw, 0);409  combined.set(tagRaw, ciphertextRaw.length);410  const raw = await crypto.subtle.decrypt(411    { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },412    recoveryKey,413    combined414  );415  const decryptedHex = new TextDecoder().decode(raw);416  rootKey = unhex(decryptedHex);417}418419/**420 * Re-wrap the cached root key under a new derived key (from the user's new421 * password). Called after password change and after recovery re-key so the422 * same recovery words continue to work with the updated password — and so423 * subsequent unlocks can rehydrate rootKey via deriveRootKeyFromDerivedKey.424 *425 * recovery_* fields are intentionally not touched: those wrap rootKey under426 * the recovery words, which do not change when the password changes.427 */428export async function rewrapRootKeyForPassword(429  newDerivedKey: Uint8Array,430  _newSalt: Uint8Array431): Promise<void> {432  if (!rootKey) throw new Error("root key not set");433  const slotA = await loadSlot(SLOT_A);434  if (!slotA) throw new Error("missing slot A");435  const pwRoot = await wrapRootKeyForDerivedKey(newDerivedKey, rootKey);436  await writeSlot(SLOT_A, { ...slotA, ...pwRoot });437}438439/**440 * Change the vault encryption to a new derived key (already derived from441 * the user's new password). Used by RECOVER_WITH_WORDS and changePassword.442 * Caller is responsible for key swap and snapshot.443 */444async function reencryptVaultForNewKey(445  newKey: Uint8Array,446  slotA: StoredVault447): Promise<void> {448  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);449  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");450  await writeSlot(SLOT_A, {451    ...slotA,452    nonce,453    ciphertext,454    tag,455  });456}457458/**459 * Full password change with an already-derived key (used after recovery).460 * Unlike changePassword(), this skips re-verification of current password461 * since recovery flow has already validated the user's identity via words.462 */463export async function changePasswordWithNewKey(464  newSalt: Uint8Array,465  newKey: Uint8Array466): Promise<void> {467  const slotA = await loadSlot(SLOT_A);468  if (!slotA) throw new Error("missing slot A");469  // reencryptVaultForNewKey must receive the updated salt so that subsequent470  // UNLOCK calls with the new password can re-derive the correct key.471  await reencryptVaultForNewKey(newKey, { ...slotA, salt: hex(newSalt) });472  if (derivedKey) zeroKey(derivedKey);473  derivedKey = newKey;474  // PCH-01-008: re-escrow the new key (see changePassword). The recovery flow475  // reaches this path, so a post-recovery SW restart would otherwise lock out476  // a user who just reset their password.477  void saveSessionKey(newKey, "real");478  // Refresh pw_root_* under the new key so deriveRootKeyFromDerivedKey works479  // on the next unlock (H2/COR-006). If rootKey is missing — recovery flow480  // should have populated it — fall back silently rather than blowing up the481  // recovery path; migrateToRecovery will rehydrate on the next unlock.482  if (rootKey) {483    const slotAfter = await loadSlot(SLOT_A);484    if (slotAfter) {485      const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);486      await writeSlot(SLOT_A, { ...slotAfter, ...pwRoot });487    }488  }489  if (!duressConfigured) {490    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));491  }492  await stampLocalVaultMutation();493}494495// ---------------------------------------------------------------------------496// Salt generation --- exported so the RECOVER_WITH_WORDS handler can derive497// a new key after password reset without re-importing the crypto module.498// ---------------------------------------------------------------------------499500export { deriveKey, generateSalt };501502export async function loadSlotA(): Promise<StoredVault | null> {503  return loadSlot(SLOT_A);504}505506/**507 * Recover the session root key by AES-GCM-decrypting the pw_root_* fields508 * (a second wrapping of the root key under the password-derived key). This509 * is what makes GET_RECOVERY_WORDS work across lock/unlock cycles without510 * the user re-entering their recovery phrase: the same root key bytes —511 * and therefore the same 12 words — survive every unlock.512 *513 * Returns null when the pw_root fields are absent (pre-v2.12 vault that514 * hasn't been migrated yet) or when decryption fails (wrong derived key,515 * tampered ciphertext). On null the caller should fall through to516 * migrateToRecovery() to populate the fields.517 */518async function deriveRootKeyFromDerivedKey(519  derivedKeyBytes: Uint8Array,520  slotA: StoredVault,521): Promise<Uint8Array | null> {522  if (!slotA.pw_root_ciphertext || !slotA.pw_root_nonce || !slotA.pw_root_tag) {523    return null;524  }525  try {526    const rootHex = await decrypt(527      derivedKeyBytes,528      slotA.pw_root_nonce,529      slotA.pw_root_ciphertext,530      slotA.pw_root_tag,531      "pw_root_v1",532    );533    return unhex(rootHex);534  } catch {535    return null;536  }537}538539// AES-GCM-wrap rootKey under derivedKey for the pw_root_* fields. Returns the540// hex-encoded ciphertext/nonce/tag triple ready to embed in StoredVault.541async function wrapRootKeyForDerivedKey(542  derivedKeyBytes: Uint8Array,543  rootKeyBytes: Uint8Array,544): Promise<{ pw_root_ciphertext: string; pw_root_nonce: string; pw_root_tag: string }> {545  const { nonce, ciphertext, tag } = await encrypt(derivedKeyBytes, hex(rootKeyBytes), "pw_root_v1");546  return {547    pw_root_ciphertext: ciphertext,548    pw_root_nonce: nonce,549    pw_root_tag: tag,550  };551}552553/**554 * For vaults created before v2.12 (no recovery_salt/recovery_wrapped_root_key),555 * generate the root key, wrap it under the recovery words, and persist the556 * recovery escrow into slot A. The caller must show the recovery words to the557 * user before calling this — once called, those words are the vault's recovery558 * path. This runs once, on the first unlock of an upgraded vault.559 */560export async function migrateToRecovery(): Promise<void> {561  if (!derivedKey || vaultMode !== "real") {562    throw new Error("vault must be unlocked in real mode");563  }564  const slotA = await loadSlot(SLOT_A);565  if (!slotA) throw new Error("missing slot A");566  const hasRecoveryEscrow =567    !!slotA.recovery_salt && !!slotA.recovery_wrapped_root_key;568  const hasPwRoot = !!slotA.pw_root_ciphertext && !!slotA.pw_root_nonce;569  if (hasRecoveryEscrow && hasPwRoot) return; // already done570571  // If recovery escrow already exists but pw_root doesn't, we cannot recover572  // the original rootKey without the user's words. The least-surprising path573  // is to rotate to a fresh root key — the user's old recovery words become574  // invalid but we surface peach_recovery_pending so the popup re-presents575  // the words. The unlock-path callers all set that flag.576  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =577    await generateAndWrapRootKey();578  rootKey = unhex(rawRootKey);579580  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);581  const nextSlotA: StoredVault = {582    ...slotA,583    recovery_salt: recoverySalt,584    recovery_wrapped_root_key: wrappedRootKey,585    recovery_nonce: wrappedNonce,586    recovery_tag: wrappedTag,587    ...pwRoot,588  };589  await writeSlot(SLOT_A, nextSlotA);590  await stampLocalVaultMutation();591}592593/**594 * Returns the 12 recovery words for the current session's root key.595 * Must be called while the vault is unlocked. Throws if recovery has not596 * been set up (pre-v2.12 vault that hasn't migrated yet).597 */598export async function getRecoveryWords(): Promise<string[]> {599  if (!rootKey) {600    throw new Error("recovery not set up — vault may need migration");601  }602  return rootKeyToWords(rootKey);603}604605async function loadSlot(key: string): Promise<StoredVault | null> {606  const result = await chrome.storage.local.get(key);607  return (result as Record<string, StoredVault | undefined>)[key] ?? null;608}609610async function writeSlot(key: string, vault: StoredVault): Promise<void> {611  try {612    await chrome.storage.local.set({ [key]: vault });613  } catch (err) {614    throw mapStorageError(err);615  }616}617618/**619 * Roll back a vault that was created by [createVaultFromRootKey] but620 * couldn't be paired (e.g. the subsequent license activation, identity621 * derivation, or paired-device upsert failed). Without this, a failed622 * receiver session leaves behind an empty vault — the user has to623 * re-pair to get a working setup, but the empty vault sits in the way.624 *625 * The call is idempotent: removing keys that aren't there is a no-op.626 */627export async function rollbackAdoptedVault(): Promise<void> {628  lock();629  try {630    await chrome.storage.local.remove([631      SLOT_A,632      SLOT_B,633      "peach_last_modified_at",634    ]);635  } catch (err) {636    throw mapStorageError(err);637  }638}639640async function commitCreatedVaultSlots(slotA: StoredVault, slotB: StoredVault): Promise<void> {641  const raw = await chrome.storage.local.get("peach_last_modified_at");642  const previous = Number(643    (raw as Record<string, unknown>).peach_last_modified_at,644  );645  const next = Math.max(646    Date.now(),647    Number.isFinite(previous) ? previous + 1 : 0,648  );649  try {650    await chrome.storage.local.set({651      [SLOT_A]: slotA,652      [SLOT_B]: slotB,653      peach_last_modified_at: String(next),654    });655  } catch (err) {656    throw mapStorageError(err);657  }658}659660// Monotonic clock for per-entry modifiedAt / deletedAt timestamps. Guards the661// sync layer's last-write-wins merge against wall-clock regressions (NTP step,662// manual clock change, DST glitch): a backwards Date.now() must never produce663// an entry timestamp that's <= the entry's existing modifiedAt, or a genuine664// local edit would lose to a stale remote copy. The returned value is always665// strictly greater than both the entry's current modifiedAt and the previous666// call's result (SEV-2-E).667let lastEntryTimestamp = 0;668function monotonicEntryTimestamp(currentModifiedAt?: number): number {669  const base = Math.max(670    Date.now(),671    (currentModifiedAt ?? 0) + 1,672    lastEntryTimestamp + 1,673  );674  lastEntryTimestamp = base;675  return base;676}677678async function stampLocalVaultMutation(): Promise<void> {679  const raw = await chrome.storage.local.get("peach_last_modified_at");680  const previous = Number(681    (raw as Record<string, unknown>).peach_last_modified_at,682  );683  const next = Math.max(684    Date.now(),685    Number.isFinite(previous) ? previous + 1 : 0,686  );687  await chrome.storage.local.set({688    peach_last_modified_at: String(next),689  });690}691692/**693 * One-shot migration from the pre-A-2 schema (peach_vault + peach_decoy_vault694 * + peach_duress flag) to the slot-neutral schema (peach_vault_a +695 * peach_vault_b). Runs at most once per session; safe to call repeatedly.696 */697async function ensureMigrated(): Promise<void> {698  if (migrationRan) return;699  migrationRan = true;700701  const keys = [LEGACY_MAIN, LEGACY_DECOY, LEGACY_DURESS_FLAG, SLOT_A, SLOT_B];702  const raw = await chrome.storage.local.get(keys);703  const slotAExists = raw[SLOT_A] !== undefined;704  const slotBExists = raw[SLOT_B] !== undefined;705  const legacyMain = raw[LEGACY_MAIN] as StoredVault | undefined;706  const legacyDecoy = raw[LEGACY_DECOY] as StoredVault | undefined;707708  // Fresh install with nothing in storage — nothing to do; createVault() sets up both slots.709  if (!slotAExists && !legacyMain) return;710711  // Already migrated.712  if (slotAExists && slotBExists && !legacyMain && !legacyDecoy) return;713714  let didMigrate = false;715  if (legacyMain && !slotAExists) {716    await writeSlot(SLOT_A, legacyMain);717    didMigrate = true;718  }719720  // If slot B isn't set, populate it: use legacy decoy when present, else noise.721  if (!slotBExists) {722    const target = (legacyMain ?? raw[SLOT_A]) as StoredVault | undefined;723    if (legacyDecoy) {724      await writeSlot(SLOT_B, legacyDecoy);725      didMigrate = true;726    } else if (target) {727      await writeSlot(SLOT_B, generateNoiseBlob(target.ciphertext.length / 2));728      didMigrate = true;729    }730  }731732  const toRemove: string[] = [];733  if (legacyMain) toRemove.push(LEGACY_MAIN);734  if (legacyDecoy) toRemove.push(LEGACY_DECOY);735  if (raw[LEGACY_DURESS_FLAG] !== undefined) toRemove.push(LEGACY_DURESS_FLAG);736  if (toRemove.length > 0) {737    await chrome.storage.local.remove(toRemove);738    didMigrate = true;739  }740  if (didMigrate) {741    await stampLocalVaultMutation();742  }743}744745// ---------------------------------------------------------------------------746// Padding + noise helpers747// ---------------------------------------------------------------------------748749/**750 * Pads the plaintext string with trailing spaces so that the encoded byte751 * length is a multiple of PAD_BLOCK. JSON.parse tolerates trailing752 * whitespace after a complete document, so the padding is transparent on753 * decode. Ciphertext length equals plaintext length plus a 16-byte tag.754 */755function padPlaintext(json: string, minBytes = 0): string {756  const encoded = new TextEncoder().encode(json);757  const bucket = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);758  // minBytes lets the duress path force a fixed ceiling so both slots match.759  const target = Math.max(bucket, minBytes);760  const padLen = target - encoded.length;761  return json + " ".repeat(padLen);762}763764/**765 * Produces a StoredVault-shaped record filled with CSPRNG bytes. The766 * ciphertext length matches the given byte count. Because GCM ciphertext is767 * pseudo-random, this blob is indistinguishable at rest from a real768 * encrypted vault without the key.769 *770 * crypto.getRandomValues() caps each call at 65536 bytes (the Web Crypto771 * spec hard limit). Chunk the fill so vaults larger than that — common once772 * the user has dozens of entries or any passkey — don't throw.773 */774const CSPRNG_CHUNK = 65_536;775776function fillRandom(buf: Uint8Array): Uint8Array {777  for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {778    const end = Math.min(offset + CSPRNG_CHUNK, buf.length);779    const chunk = new Uint8Array(end - offset);780    crypto.getRandomValues(chunk);781    buf.set(chunk, offset);782  }783  return buf;784}785786function generateNoiseBlob(ciphertextBytes: number): StoredVault {787  const salt = crypto.getRandomValues(new Uint8Array(16));788  const nonce = crypto.getRandomValues(new Uint8Array(12));789  const cipher = fillRandom(new Uint8Array(ciphertextBytes));790  const tag = crypto.getRandomValues(new Uint8Array(16));791  return {792    version: 1,793    salt: hex(salt),794    nonce: hex(nonce),795    ciphertext: hex(cipher),796    tag: hex(tag),797  };798}799800// ---------------------------------------------------------------------------801// Encrypted plaintext envelope802// ---------------------------------------------------------------------------803804type VaultPayload = {805  entries: VaultEntry[];806  duressConfigured?: boolean;807};808809type DecryptedPayload = {810  entries: VaultEntry[];811  duressConfigured: boolean;812  /**813   * True when at least one entry in the on-disk payload had a legacy shape814   * (pre-v2.11.0 passkey type/flat fields, or pre-A-2 created/updated keys)815   * and got rewritten by normalizeEntry. The unlock path uses this to816   * persist the new shape immediately — without it, the migration would817   * re-run on every unlock and old shape never disappears from disk.818   */819  migratedFromLegacy: boolean;820};821822function encodePayload(entries: VaultEntry[], duress: boolean, minBytes = 0): string {823  const envelope: VaultPayload = { entries, duressConfigured: duress };824  return padPlaintext(JSON.stringify(envelope), minBytes);825}826827function rawNeedsMigration(raw: VaultEntry | LegacyVaultEntry): boolean {828  if ("created" in raw || "updated" in raw) return true;829  const flat = raw as Partial<VaultEntry>;830  if (flat.type === "passkey") return true;831  // Flat rpId without a passkey sub-object means pre-v2.11.0 schema.832  if (flat.rpId !== undefined && flat.passkey === undefined) return true;833  return false;834}835836function decodePayload(plain: string): DecryptedPayload {837  const parsed = JSON.parse(plain) as838    | Array<VaultEntry | LegacyVaultEntry>839    | VaultPayload;840841  const rawEntries = Array.isArray(parsed) ? parsed : parsed.entries ?? [];842  const flatMigrationNeeded = rawEntries.some(rawNeedsMigration);843844  const normalized = rawEntries.map(normalizeEntry);845  const { merged } = mergePasskeyOnlyIntoLogins(normalized);846847  if (Array.isArray(parsed)) {848    return {849      entries: normalized,850      duressConfigured: false,851      migratedFromLegacy: true, // pre-A-2 array shape always needs save852    };853  }854855  return {856    entries: normalized,857    duressConfigured: parsed.duressConfigured === true,858    migratedFromLegacy: flatMigrationNeeded || merged,859  };860}861862/**863 * One-time consolidation pass run alongside the legacy passkey migration.864 *865 * Pre-v2.11.0 the Chrome passkey path always created a fresh `type:"passkey"`866 * entry per registration — so users who tested registration multiple times867 * accumulated several passkey-bearing entries for the same RP, and the868 * migration to the unified shape carried that duplication forward. This869 * pass collapses the duplicates:870 *871 *   1. Group passkey-bearing (and not deleted) entries by `passkey.rpId`.872 *   2. Within each group, the most recently-active credential wins (prefer873 *      lastUsedAt, fall back to passkey.createdAt, fall back to modifiedAt).874 *   3. If a NON-passkey login entry exists for that RP (matched by url or875 *      additionalUrls hostname), attach the winning passkey to it and876 *      soft-delete every passkey-bearing entry in the group.877 *   4. Otherwise, soft-delete every loser in the group, keeping the winner878 *      as a passkey-only entry.879 *880 * Soft delete (deletedAt) rather than splice — the trash flow keeps the881 * record around for retention and the user can restore if the heuristic882 * picked wrong. The `merged` flag goes back to decodePayload so the883 * unlock path persists the consolidated shape immediately.884 */885function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {886  let merged = false;887  const now = Date.now();888889  const candidates = entries.filter((e) => !e.deletedAt && e.passkey);890  const byRpId = new Map<string, VaultEntry[]>();891  for (const e of candidates) {892    const rpId = e.passkey!.rpId;893    const list = byRpId.get(rpId);894    if (list) list.push(e);895    else byRpId.set(rpId, [e]);896  }897898  for (const [rpId, group] of byRpId) {899    if (group.length === 0) continue;900    group.sort((a, b) => {901      const aT =902        a.passkey!.lastUsedAt ?? a.passkey!.createdAt ?? a.modifiedAt ?? a.createdAt;903      const bT =904        b.passkey!.lastUsedAt ?? b.passkey!.createdAt ?? b.modifiedAt ?? b.createdAt;905      return bT - aT;906    });907    const winner = group[0]!;908909    // Look for a NON-passkey login entry matching this RP. Use the URL910    // hostname rather than a substring search so a "login.foo.com" entry911    // doesn't accidentally absorb a passkey for "foo.com".912    const loginTarget = entries.find((e) => {913      if (e.deletedAt || e.passkey || e.type !== "login") return false;914      if (e.url && extractDomain(e.url) === rpId) return true;915      for (const extra of e.additionalUrls ?? []) {916        if (extractDomain(extra) === rpId) return true;917      }918      return false;919    });920921    if (loginTarget) {922      loginTarget.passkey = winner.passkey;923      loginTarget.modifiedAt = now;924      for (const dup of group) {925        if (!dup.deletedAt) {926          dup.deletedAt = now;927          dup.modifiedAt = now;928        }929      }930      merged = true;931    } else if (group.length > 1) {932      for (let i = 1; i < group.length; i += 1) {933        const dup = group[i]!;934        if (!dup.deletedAt) {935          dup.deletedAt = now;936          dup.modifiedAt = now;937        }938      }939      merged = true;940    }941  }942943  return { merged };944}945946// Validates that a `StoredVault` record on disk has the field shape we expect947// before treating an AES-GCM decrypt success as a clean unlock. AES-GCM only948// authenticates the static VERSION_BYTE AAD, not the `version` field on the949// outer record — a corrupted `version: 42` slot still decrypts cleanly. This950// check surfaces that as `corrupted` (M7/COR-007) so the popup can offer a951// history-restore path instead of falsely reporting "wrong password".952function hasValidVaultSchema(v: unknown): v is StoredVault {953  if (typeof v !== "object" || v === null) return false;954  const r = v as Record<string, unknown>;955  return (956    r.version === 1 &&957    typeof r.salt === "string" &&958    typeof r.nonce === "string" &&959    typeof r.ciphertext === "string" &&960    typeof r.tag === "string"961  );962}963964export type TryDecryptResult =965  | { status: "ok"; payload: DecryptedPayload }966  | { status: "wrong_key" }967  | { status: "corrupted"; reason: string };968969// Exported solely for `unlockFromCodex` below, which needs to verify a970// supplied passphrase against a slotA blob *without* committing anything to971// storage. Keep this internal otherwise — callers crossing the messages.ts972// boundary should always go through `unlock` / `verifyMainPassword` so the973// constant-time invariants in Projects.md §3.4 are not bypassed.974export async function tryDecryptSlot(975  vault: StoredVault,976  key: Uint8Array,977  aadTag?: string,978): Promise<DecryptedPayload | null> {979  const res = await tryDecryptSlotResult(vault, key, aadTag);980  return res.status === "ok" ? res.payload : null;981}982983export async function tryDecryptSlotResult(984  vault: StoredVault,985  key: Uint8Array,986  aadTag?: string,987): Promise<TryDecryptResult> {988  if (!hasValidVaultSchema(vault)) {989    return { status: "corrupted", reason: "invalid_slot_schema" };990  }991  let plain: string;992  try {993    plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);994  } catch {995    return { status: "wrong_key" };996  }997  try {998    const parsed = JSON.parse(plain) as unknown;999    if (typeof parsed !== "object" || parsed === null) {1000      return { status: "corrupted", reason: "invalid_payload_shape" };1001    }1002    if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {1003      return { status: "corrupted", reason: "invalid_payload_shape" };1004    }1005    return { status: "ok", payload: decodePayload(plain) };1006  } catch {1007    return { status: "corrupted", reason: "invalid_payload_json" };1008  }1009}10101011// ---------------------------------------------------------------------------1012// Core operations1013// ---------------------------------------------------------------------------10141015function buildDomainIndexSync(all: VaultEntry[]): void {1016  domainIndex = new Map();10171018  for (const entry of all) {1019    if (entry.deletedAt) continue;1020    if (entry.type === "note" || entry.type === "card") continue;10211022    // An entry can match multiple sites via `additionalUrls`. Index each1023    // hostname so `queryDomain` returns the entry regardless of which alias1024    // the user is currently visiting. Dedupe per-entry so a single entry1025    // never appears twice in one bucket.1026    const domains = new Set<string>();1027    const primary = extractDomain(entry.url ?? "");1028    if (primary) domains.add(primary);1029    for (const extra of entry.additionalUrls ?? []) {1030      const d = extractDomain(extra);1031      if (d) domains.add(d);1032    }1033    if (domains.size === 0) continue;10341035    for (const domain of domains) {1036      const bucket = domainIndex.get(domain) ?? [];1037      bucket.push(entry);1038      domainIndex.set(domain, bucket);1039    }1040  }1041}10421043export async function createVault(password: string): Promise<void> {1044  await ensureMigrated();10451046  const salt = generateSalt();1047  derivedKey = await deriveKey(password, salt);1048  entries = [];1049  vaultMode = "real";1050  duressConfigured = false;1051  buildDomainIndexSync(entries);10521053  // Generate and wrap the root key for recovery word escrow.1054  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =1055    await generateAndWrapRootKey();1056  rootKey = unhex(rawRootKey);10571058  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);1059  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");10601061  // Second wrapping of rootKey under derivedKey so future unlocks can rehydrate1062  // it without recovery words (H2/COR-006).1063  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);10641065  const slotA: StoredVault = {1066    version: 1,1067    salt: hex(salt),1068    nonce,1069    ciphertext,1070    tag,1071    recovery_salt: recoverySalt,1072    recovery_wrapped_root_key: wrappedRootKey,1073    recovery_nonce: wrappedNonce,1074    recovery_tag: wrappedTag,1075    ...pwRoot,1076  };1077  await writeSlot(SLOT_A, slotA);10781079  // Matching-size noise blob for slot B, so a fresh install shows two1080  // similarly-shaped records regardless of whether duress is ever set up.1081  await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));1082  await stampLocalVaultMutation();10831084  touchAutoLock();1085}10861087/**1088 * Creates a local vault from an existing vault root key received through the1089 * SAS-gated adoption protocol. The password is local to this device; it wraps1090 * the adopted root key at rest and does not need to match the source device.1091 */1092export async function createVaultFromRootKey(1093  password: string,1094  rootKeyHex: string,1095): Promise<{ vaultId: string }> {1096  if (typeof password !== "string" || password.length === 0) {1097    throw new Error("ADOPT_INVALID_PASSWORD");1098  }1099  if (typeof rootKeyHex !== "string" || !/^[0-9a-f]{64}$/.test(rootKeyHex)) {1100    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars");1101  }11021103  const rootKeyBytes = unhex(rootKeyHex);1104  if (rootKeyBytes.length !== 32) {1105    rootKeyBytes.fill(0);1106    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");1107  }11081109  let nextDerivedKey: Uint8Array | null = null;1110  let sessionRootKey: Uint8Array | null = null;1111  try {1112    await ensureMigrated();1113    if ((await loadSlot(SLOT_A)) !== null) {1114      throw new Error("ADOPT_VAULT_ALREADY_EXISTS");1115    }11161117    const nextEntries: VaultEntry[] = [];1118    const nextDuressConfigured = false;1119    const vaultId = await computeVaultId(rootKeyBytes);1120    const salt = generateSalt();1121    nextDerivedKey = await deriveKey(password, salt);1122    const recovery = await wrapExistingRootKeyForRecovery(rootKeyBytes);11231124    sessionRootKey = new Uint8Array(rootKeyBytes);1125    const plaintext = encodePayload(nextEntries, nextDuressConfigured, 0);1126    const { nonce, ciphertext, tag } = await encrypt(nextDerivedKey, plaintext, "slot_a_v1");1127    const pwRoot = await wrapRootKeyForDerivedKey(nextDerivedKey, sessionRootKey);1128    const slotA: StoredVault = {1129      version: 1,1130      salt: hex(salt),1131      nonce,1132      ciphertext,1133      tag,1134      recovery_salt: recovery.recoverySalt,1135      recovery_wrapped_root_key: recovery.wrappedRootKey,1136      recovery_nonce: recovery.wrappedNonce,1137      recovery_tag: recovery.wrappedTag,1138      ...pwRoot,1139    };1140    const slotB = generateNoiseBlob(ciphertext.length / 2);1141    await commitCreatedVaultSlots(slotA, slotB);11421143    const previousDerivedKey = derivedKey;1144    const previousRootKey = rootKey;1145    derivedKey = nextDerivedKey;1146    rootKey = sessionRootKey;1147    nextDerivedKey = null;1148    sessionRootKey = null;1149    entries = nextEntries;1150    vaultMode = "real";1151    duressConfigured = nextDuressConfigured;1152    buildDomainIndexSync(entries);1153    if (previousDerivedKey && previousDerivedKey !== derivedKey) zeroKey(previousDerivedKey);1154    if (previousRootKey && previousRootKey !== rootKey) previousRootKey.fill(0);1155    touchAutoLock();11561157    return { vaultId };1158  } finally {1159    rootKeyBytes.fill(0);1160    if (nextDerivedKey) zeroKey(nextDerivedKey);1161    if (sessionRootKey) sessionRootKey.fill(0);1162  }1163}11641165export async function hasVault(): Promise<boolean> {1166  await ensureMigrated();1167  return (await loadSlot(SLOT_A)) !== null;1168}11691170/**1171 * Returns whether the real vault has recorded that a duress passphrase is1172 * configured. Reliable only after a real-mode unlock — before unlock or in1173 * decoy mode, returns false because we cannot read slot A's plaintext.1174 */1175export async function isDuressEnabled(): Promise<boolean> {1176  return vaultMode === "real" && duressConfigured;1177}11781179export async function setupDuress(duressPassword: string): Promise<void> {1180  if (!derivedKey || vaultMode !== "real") {1181    throw new Error("vault must be unlocked in real mode");1182  }1183  await ensureMigrated();11841185  // Encrypt the decoy payload (empty entries) under the duress key. Pad to1186  // at least the current slot A ciphertext size so the two slots look the1187  // same at rest at setup time.1188  const slotA = await loadSlot(SLOT_A);1189  if (!slotA) throw new Error("missing slot A");11901191  const decoySalt = generateSalt();1192  const decoyKey = await deriveKey(duressPassword, decoySalt);1193  try {1194    // Pad the decoy to the fixed duress ceiling. Slot A is re-encrypted to the1195    // same ceiling by the persistSlotA() call below (duressConfigured is now1196    // true), so both slots are exactly DURESS_SLOT_SIZE+tag at rest and their1197    // lengths cannot reveal that duress is configured (audit MEDIUM).1198    const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);1199    const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");1200    await writeSlot(SLOT_B, {1201      version: 1,1202      salt: hex(decoySalt),1203      nonce,1204      ciphertext,1205      tag,1206    });1207  } finally {1208    zeroKey(decoyKey);1209  }12101211  // Re-encrypt slot A with the duressConfigured flag set to true. No external1212  // flag is written — the bit lives inside the encrypted envelope.1213  duressConfigured = true;1214  await persistSlotA();1215}12161217export async function disableDuress(): Promise<void> {1218  if (!derivedKey || vaultMode !== "real") {1219    throw new Error("vault must be unlocked in real mode");1220  }1221  await ensureMigrated();12221223  // Overwrite slot B with fresh noise that matches slot A's size. The slot1224  // remains occupied so its mere existence does not signal that duress was1225  // ever configured.1226  const slotA = await loadSlot(SLOT_A);1227  if (slotA) {1228    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));1229  }12301231  duressConfigured = false;1232  await persistSlotA();1233}12341235// L14/COR-015: this function intentionally checks slot A (real vault) only.1236// A duress-mode user attempting changePassword is rejected earlier by the1237// vaultMode === 'decoy' check at changePassword. The real-vs-decoy1238// distinction here is by design — duress users cannot rotate the real1239// password by guessing it, and the asymmetry in error timing is acceptable1240// because duress mode is opt-in and the user knows their own decoy key.1241export async function verifyMainPassword(password: string): Promise<boolean> {1242  await ensureMigrated();1243  const slotA = await loadSlot(SLOT_A);1244  if (!slotA) return false;1245  const key = await deriveKey(password, unhex(slotA.salt));1246  try {1247    return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;1248  } finally {1249    zeroKey(key);1250  }1251}12521253export async function unlock(password: string): Promise<boolean> {1254  // LV-1: the normal path NFC-normalizes inside deriveKey. If that fails and1255  // the supplied password is not already in NFC form, the vault may have been1256  // sealed (pre-LV-1) with the raw, un-normalized bytes — retry with those.1257  if (await attemptUnlockWithDerive(password, deriveKey)) return true;12581259  const nfc = password.normalize("NFC");1260  if (password === nfc) return false; // ASCII/NFC password — no legacy form to try12611262  if (await attemptUnlockWithDerive(password, deriveKeyRaw)) {1263    // Heal: re-seal the real slot under the NFC-normalized key so every1264    // future unlock takes the normal path. Only the real vault is re-sealed;1265    // a non-NFC duress password keeps working through this fallback.1266    if (vaultMode === "real") {1267      try {1268        const newSalt = generateSalt();1269        const newKey = await deriveKey(password, newSalt);1270        await changePasswordWithNewKey(newSalt, newKey);1271      } catch (healErr) {1272        console.warn("[Peach] LV-1 NFC heal failed:", healErr);1273      }1274    }1275    return true;1276  }1277  return false;1278}12791280async function attemptUnlockWithDerive(1281  password: string,1282  derive: typeof deriveKey,1283): Promise<boolean> {1284  await ensureMigrated();12851286  // Load both slots in parallel. Both always exist post-migration; the1287  // parallel load and the parallel derivation below keep wall-clock time1288  // constant regardless of which slot's passphrase (real or decoy) the1289  // caller supplied, so a timing side channel cannot distinguish the1290  // duress path from the real-unlock path (DUR-002).1291  const [slotA, slotB] = await Promise.all([1292    loadSlot(SLOT_A),1293    loadSlot(SLOT_B),1294  ]);12951296  // Derive both keys in parallel, unconditionally.1297  const [keyA, keyB] = await Promise.all([1298    slotA ? derive(password, unhex(slotA.salt)) : Promise.resolve(null),1299    slotB ? derive(password, unhex(slotB.salt)) : Promise.resolve(null),1300  ]);13011302  // Attempt both decrypts in parallel. The Result variant lets us distinguish1303  // 'wrong_key' from 'corrupted' so callers can offer a history-restore path1304  // when a slot's schema is invalid even though AES-GCM authenticated (M7).1305  const [resultA, resultB] = await Promise.all([1306    keyA && slotA1307      ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")1308      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1309    keyB && slotB1310      ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")1311      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1312  ]);1313  const payloadA = resultA.status === "ok" ? resultA.payload : null;1314  const payloadB = resultB.status === "ok" ? resultB.payload : null;13151316  if (payloadA && keyA) {1317    derivedKey = keyA;1318    void saveSessionKey(keyA, "real");1319    vaultMode = "real";1320    entries = payloadA.entries;1321    duressConfigured = payloadA.duressConfigured;1322    buildDomainIndexSync(entries);1323    await loadSettings();1324    touchAutoLock();1325    if (keyB) zeroKey(keyB);13261327    // slotA is non-null when payloadA is truthy (keyA was derived from slotA).1328    if (slotA) {1329      const needsRecoverySetup =1330        !slotA.recovery_salt || !slotA.recovery_wrapped_root_key;1331      if (!needsRecoverySetup) {1332        rootKey = await deriveRootKeyFromDerivedKey(keyA, slotA);1333      }1334      // Pre-v2.12 vault, or a vault whose pw_root_* fields haven't been written1335      // yet: generate the recovery escrow and seed pw_root_* so subsequent1336      // unlocks can rehydrate rootKey without the user's recovery words.1337      // Best-effort — a failure here must not block unlock.1338      if (needsRecoverySetup || !rootKey) {1339        try {1340          await migrateToRecovery();1341          if (needsRecoverySetup) {1342            // String "1" matches the popup's existing peach_recovery_pending1343            // check; surfaced so the user re-confirms recovery words after a1344            // legacy-vault unlock (H2/COR-006).1345            await chrome.storage.local.set({ peach_recovery_pending: '1' });1346          }1347        } catch (migrationErr) {1348          console.warn('[Peach] recovery migration failed:', migrationErr);1349        }1350      }1351    }13521353    // If the payload had a pre-v2.11.0 shape (legacy passkey type, flat1354    // passkey fields, or pre-A-2 created/updated keys), rewrite it now so1355    // the next save uses the new format and migration doesn't re-run forever.1356    if (payloadA.migratedFromLegacy) {1357      await persistSlotA();1358    }1359    return true;1360  }13611362  if (payloadB && keyB) {1363    derivedKey = keyB;1364    void saveSessionKey(keyB, "decoy");1365    vaultMode = "decoy";1366    entries = payloadB.entries;1367    duressConfigured = false;1368    buildDomainIndexSync(entries);1369    await loadSettings();1370    touchAutoLock();1371    if (keyA) zeroKey(keyA);1372    return true;1373  }13741375  if (keyA) zeroKey(keyA);1376  if (keyB) zeroKey(keyB);1377  // Surface corruption (good AES tag, broken schema) distinctly from1378  // wrong-password so the popup can offer history-restore (M7/COR-007).1379  if (resultA.status === "corrupted") {1380    lastUnlockFailureReason = resultA.reason;1381  } else if (resultB.status === "corrupted") {1382    lastUnlockFailureReason = resultB.reason;1383  }1384  return false;1385}13861387// ---------------------------------------------------------------------------1388// MV3 service worker session key — survives SW restarts within a browser session1389// ---------------------------------------------------------------------------13901391// chrome.storage.session is cleared on browser close; survives SW restart.1392// Firefox does not implement it (persistent background script, no restart risk).1393const SESSION_KEY_STORAGE = "peach_session_dk";13941395async function saveSessionKey(key: Uint8Array, mode: "real" | "decoy"): Promise<void> {1396  if (!chrome.storage.session) return;1397  await chrome.storage.session.set({ [SESSION_KEY_STORAGE]: { keyHex: hex(key), mode } });1398}13991400async function clearSessionKey(): Promise<void> {1401  if (!chrome.storage.session) return;1402  await chrome.storage.session.remove(SESSION_KEY_STORAGE);1403}14041405/**1406 * On SW restart, re-derive all in-memory vault state from the session key1407 * stored in chrome.storage.session (set at unlock time, cleared on lock).1408 * Returns true if the vault was restored, false if no session key was found.1409 * No-ops if the vault is already unlocked.1410 */1411export async function restoreFromSession(): Promise<boolean> {1412  if (derivedKey !== null) return true;1413  if (!chrome.storage.session) return false;1414  const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);1415  const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;1416  if (!entry?.keyHex) return false;14171418  const key = unhex(entry.keyHex);1419  const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;1420  const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";1421  const slot = await loadSlot(slotKey);1422  if (!slot) { await clearSessionKey(); return false; }14231424  const result = await tryDecryptSlotResult(slot, key, aadTag);1425  if (result.status !== "ok") { await clearSessionKey(); return false; }14261427  derivedKey = key;1428  vaultMode = entry.mode;1429  entries = result.payload.entries;1430  duressConfigured = entry.mode === "real" ? result.payload.duressConfigured : false;1431  buildDomainIndexSync(entries);1432  await loadSettings();1433  touchAutoLock();14341435  // The rootKey is what identity/sync derivations use. deriveRootKeyFromDerivedKey1436  // pulls it from the pw_root_* fields on the slot — set on every createVault +1437  // re-set on every password change (H2/COR-006). The previous gate on1438  // recovery_salt + recovery_wrapped_root_key silently left rootKey unset for1439  // any vault that hadn't been through migrateToRecovery, which broke background1440  // sync: the SW re-woke from the alarm, isUnlocked() was true (the session key1441  // restored derivedKey + entries), but getRootKeyHex() returned null and the1442  // runner returned VAULT_LOCKED. The fix is to always try the pw_root path1443  // when the slot has those fields — the recovery fields are independent.1444  if (entry.mode === "real") {1445    try {1446      rootKey = await deriveRootKeyFromDerivedKey(key, slot);1447    } catch {1448      /* non-fatal — sync identity will still skip on the runner's null-rootKey check */1449    }1450  }14511452  return true;1453}14541455export function lock(): void {1456  // Deliberately does NOT clear the session key. The session key survives1457  // `lock()` so the MV3 service worker can restore the vault from1458  // chrome.storage.session on the next wake — the 10-minute sync alarm, the1459  // post-adoption retry, the post-update alarm. The previous behaviour1460  // (clear on every lock()) broke background sync: any popup close with1461  // lockOnClose=true would `lock()`, which cleared the session key, and1462  // the next SW wake would find no session key and the runner would return1463  // VAULT_LOCKED. The session key's natural lifetime is the browser session1464  // (chrome.storage.session is cleared on browser close), so explicit user1465  // lock + popup close + auto-lock all keep the session key alive and the1466  // expected sync-after-restart flow actually works.1467  if (derivedKey) {1468    zeroKey(derivedKey);1469    derivedKey = null;1470  }1471  if (rootKey) {1472    rootKey.fill(0);1473    rootKey = null;1474  }14751476  entries = [];1477  domainIndex = new Map();1478  vaultMode = "real";1479  duressConfigured = false;1480  clearAutoLock();1481}14821483export function isUnlocked(): boolean {1484  return derivedKey !== null;1485}14861487// Opens the vault using a pre-derived AES-256 key (skipping Argon2id).1488// Used by Android biometric unlock — the key was derived on the native side.1489// SECURITY: only reachable via Capacitor native bridge; browser messages.ts never routes here.1490export async function unlockWithKey(1491  masterKeyHex: string,1492): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {1493  try {1494    const masterKeyBytes = unhex(masterKeyHex);1495    const stored = await loadSlot(SLOT_A);1496    if (!stored) return { ok: false, error: "invalid_key" };1497    const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");1498    if (!payload) return { ok: false, error: "invalid_key" };14991500    derivedKey = masterKeyBytes;1501    vaultMode = "real";1502    entries = payload.entries;1503    duressConfigured = payload.duressConfigured;1504    buildDomainIndexSync(entries);1505    await loadSettings();1506    touchAutoLock();15071508    // PCH-01-009: the biometric path skips Argon2id but must still rehydrate the1509    // root key, exactly like attemptUnlockWithDerive and restoreFromSession.1510    // Without it, rootKey stays null after a biometric unlock and sync +1511    // GET_RECOVERY_WORDS report the open vault as locked. Guarded and non-fatal:1512    // a missing/legacy escrow must not fail the unlock itself.1513    if (stored.recovery_salt && stored.recovery_wrapped_root_key) {1514      try {1515        rootKey = await deriveRootKeyFromDerivedKey(masterKeyBytes, stored);1516      } catch { /* non-fatal — unlock still succeeds without rootKey */ }1517    }1518    return { ok: true, entries };1519  } catch {1520    return { ok: false, error: "invalid_key" };1521  }1522}15231524// --- Adoption duress-slot helpers (passthrough, no decrypt) ---15251526/**1527 * Adoption SOURCE helper: returns the sealed slot B as a JSON string when1528 * duress is configured and slot B exists, so the inline snapshot can ship it1529 * to the receiver. Returns null otherwise. Never decrypts.1530 */1531export async function exportDuressSlotForAdoption(): Promise<string | null> {1532  if (!(await isDuressEnabled())) return null;1533  await ensureMigrated();1534  const slotB = await loadSlot(SLOT_B);1535  if (!slotB) return null;1536  return JSON.stringify(slotB);1537}15381539/**1540 * Adoption RECEIVER helper: installs a duress slot received from a source1541 * device. Validates the StoredVault shape (same guard as unlockFromCodex)1542 * and writes it to slot B. Throws on invalid shape so the caller can treat1543 * it as a non-fatal snapshot failure. Never decrypts.1544 */1545export async function installAdoptedDuressSlot(json: string): Promise<void> {1546  let parsed: StoredVault;1547  try {1548    const raw = JSON.parse(json) as unknown;1549    if (!hasValidVaultSchema(raw)) {1550      throw new Error("invalid_duress_slot_shape");1551    }1552    parsed = raw;1553  } catch (err) {1554    if (err instanceof SyntaxError) {1555      throw new Error("invalid_duress_slot_shape");1556    }1557    throw err;1558  }1559  await writeSlot(SLOT_B, parsed);1560}15611562/**1563 * Restore the vault from a parsed Peach Codex payload.1564 *1565 * The supplied passphrase is verified against the Codex's slotA *before* any1566 * storage mutation — wrong passphrases return without touching disk. On1567 * success, the current vault state is snapshotted (reason: "restore") so the1568 * user can revert via Settings -> Vault History, then slotA/slotB are written1569 * and `peach_last_modified_at` is set to the Codex's recorded timestamp. A1570 * regular `unlock()` follows so the rest of the SW sees the standard1571 * post-unlock state.1572 *1573 * Intentionally non-Pro-gated — see peach_codex_v2.md "Pro gating". A Codex1574 * printed by a Pro user must always be restorable, even on a free device.1575 *1576 * Timing is not held constant here (in contrast to `unlock`): the Codex flow1577 * is an explicit user action with a known passphrase, not a passive lock1578 * screen, so the duress-vs-real timing side channel does not apply.1579 */1580export async function unlockFromCodex(params: {1581  slotA: string; // JSON string of StoredVault for slot A1582  slotB: string | null; // JSON string of StoredVault for slot B, or null1583  timestamp: number;1584  masterPassphrase: string;1585}): Promise<1586  | { ok: true; entryCount: number }1587  | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" }1588> {1589  let parsedSlotA: StoredVault;1590  let parsedSlotB: StoredVault | null = null;1591  try {1592    const rawA = JSON.parse(params.slotA) as unknown;1593    if (!hasValidVaultSchema(rawA)) {1594      return { ok: false, reason: "invalid_slot_format" };1595    }1596    parsedSlotA = rawA;1597    if (params.slotB !== null) {1598      const rawB = JSON.parse(params.slotB) as unknown;1599      if (!hasValidVaultSchema(rawB)) {1600        return { ok: false, reason: "invalid_slot_format" };1601      }1602      parsedSlotB = rawB;1603    }1604  } catch {1605    return { ok: false, reason: "invalid_slot_format" };1606  }16071608  // Verify the passphrase against the supplied slotA WITHOUT writing anything.1609  // If this fails the on-disk vault is left completely untouched.1610  const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));1611  const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");1612  if (!trialPayload) {1613    zeroKey(trialKey);1614    return { ok: false, reason: "wrong_passphrase" };1615  }1616  // Drop the trial key; `unlock()` below derives its own copy. Holding two1617  // copies of the master key in memory at once would be a needless surface.1618  zeroKey(trialKey);16191620  // Snapshot the about-to-be-overwritten on-disk state so the user can revert1621  // a mistaken Codex restore via the Vault History UI. Non-fatal if it fails.1622  await takeVaultSnapshot("restore");16231624  await writeSlot(SLOT_A, parsedSlotA);1625  if (parsedSlotB) {1626    await writeSlot(SLOT_B, parsedSlotB);1627  } else {1628    // Slot B must always exist with ciphertext length matching slot A1629    // (Projects.md §3.2). Codex prints may omit slot B (duress wasn't1630    // configured); regenerate noise to satisfy the invariant.1631    await writeSlot(1632      SLOT_B,1633      generateNoiseBlob(parsedSlotA.ciphertext.length / 2),1634    );1635  }1636  await chrome.storage.local.set({1637    peach_last_modified_at: String(params.timestamp),1638  });16391640  // Standard unlock path so domain index, settings, auto-lock, and1641  // recovery-key state all populate exactly as a normal unlock would.1642  const ok = await unlock(params.masterPassphrase);1643  if (!ok) {1644    // Should be unreachable — we just verified the passphrase against the1645    // same slotA we wrote. Treat as wrong_passphrase to keep the contract1646    // simple if some race or storage anomaly intrudes.1647    return { ok: false, reason: "wrong_passphrase" };1648  }1649  return { ok: true, entryCount: getEntries().length };1650}16511652// Returns the current in-memory derived key as a hex string.1653// Used by the biometric enable flow in Settings to store the key in Android Keystore.1654export function getDerivedKeyHex(): string {1655  if (!derivedKey) throw new Error("vault_not_unlocked");1656  return hex(derivedKey);1657}16581659/**1660 * Returns the vault's stable root key as hex, or null when locked / not yet1661 * populated. The root key is random per-vault, generated at creation, escrowed1662 * under the recovery words, and re-wrapped (not regenerated) on every password1663 * change — so it is INVARIANT across password rotation, unlike getDerivedKeyHex.1664 *1665 * This is the correct input for sync identity derivation (vault_id, the Noise1666 * NK static key, the Ed25519 manifest signing key, and per-entry envelope1667 * keys): paired devices keep the same identity and can still decrypt each1668 * other's entries after either side rotates its master password (SEV-2-B).1669 *1670 * Returns null rather than throwing so sync callers degrade to VAULT_LOCKED1671 * instead of crashing; rootKey is populated on every real-mode unlock via1672 * deriveRootKeyFromDerivedKey / migrateToRecovery.1673 */1674export function getRootKeyHex(): string | null {1675  return rootKey ? hex(rootKey) : null;1676}16771678export function getEntries(): VaultEntry[] {1679  if (!derivedKey) throw new Error("vault_locked");1680  return entries.filter((entry) => !entry.deletedAt);1681}16821683const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;16841685export function getIdentities(): SavedIdentity[] {1686  if (!derivedKey) throw new Error("vault_locked");1687  const active = entries.filter((e) => !e.deletedAt && e.type === "login");16881689  const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();1690  const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();16911692  for (const entry of active) {1693    const domain = extractDomain(entry.url ?? "") ?? "";1694    const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;16951696    function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {1697      const existing = map.get(v);1698      if (!existing || modifiedAt > existing.lastUsed) {1699        map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });1700      } else {1701        map.set(v, { ...existing, count: existing.count + 1 });1702      }1703    }17041705    const uVal = entry.username?.trim();1706    if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);17071708    // Also count the dedicated email field — entries created via the inline1709    // popup new-entry form store email here rather than in username.1710    const eVal = entry.email?.trim();1711    if (eVal) tally(emailMap, eVal);1712  }17131714  const toIdentity = (type: "email" | "username") =>1715    ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({1716      value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,1717    });17181719  return [1720    ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),1721    ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),1722  ];1723}17241725export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {1726  if (!derivedKey) throw new Error("vault_locked");17271728  const now = Date.now();1729  const added: VaultEntry[] = [];1730  for (const draft of drafts) {1731    try {1732      const sanitized = sanitizeEntryDraft(draft);1733      const nextEntry: VaultEntry = {1734        ...sanitized,1735        id: crypto.randomUUID(),1736        createdAt: now,1737        modifiedAt: monotonicEntryTimestamp(),1738      };1739      entries.push(nextEntry);1740      added.push(nextEntry);1741    } catch {1742      // Skip invalid drafts silently — caller can see diff between input and output length1743    }1744  }17451746  if (added.length > 0) {1747    await persistEntries();1748  }17491750  return added;1751}17521753/**1754 * Restore a set of entries in full fidelity — preserves id, createdAt,1755 * modifiedAt, and every other field unlike `batchAddEntries` which1756 * assigns fresh identity. Used by restore paths where the backup is the1757 * authoritative source of truth. `mode` controls how entries already in1758 * the vault are treated.1759 */1760export async function restoreEntries(1761  incoming: VaultEntry[],1762  mode: "replace" | "merge"1763): Promise<{ added: number; updated: number; skipped: number }> {1764  if (!derivedKey) throw new Error("vault_locked");17651766  // A replace with zero incoming entries is almost certainly a caller bug1767  // (e.g. an import that silently dropped everything). Refuse rather than1768  // wipe the vault.1769  if (mode === "replace" && incoming.length === 0) {1770    throw new Error("refuse to replace with empty entry set");1771  }17721773  let added = 0;1774  let updated = 0;1775  let skipped = 0;17761777  if (mode === "replace") {1778    entries = [];1779    for (const entry of incoming) {1780      const normalized = sanitizeRestoredEntry(entry);1781      if (!normalized) {1782        skipped += 1;1783        continue;1784      }1785      entries.push(normalized);1786      added += 1;1787    }1788  } else {1789    const byId = new Map<string, VaultEntry>();1790    for (const e of entries) byId.set(e.id, e);17911792    for (const entry of incoming) {1793      const normalized = sanitizeRestoredEntry(entry);1794      if (!normalized) {1795        skipped += 1;1796        continue;1797      }1798      const existing = byId.get(normalized.id);1799      if (!existing) {1800        entries.push(normalized);1801        added += 1;1802      } else if (normalized.modifiedAt > existing.modifiedAt) {1803        const idx = entries.findIndex((e) => e.id === existing.id);1804        if (idx !== -1) {1805          entries[idx] = normalized;1806          updated += 1;1807        }1808      } else {1809        skipped += 1;1810      }1811    }1812  }18131814  await persistEntries("import");1815  return { added, updated, skipped };1816}18171818/**1819 * Validate + normalise a VaultEntry coming from a backup, import, or sync1820 * peer. MV-6: this is a strict field WHITELIST — `normalizeEntry` copies1821 * only known VaultEntry fields (unknown/attacker keys are dropped), and1822 * nested `passkey`/`canary` shapes are rebuilt field-by-field, never1823 * spread. Returns null for values the live vault shouldn't accept.1824 */1825function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {1826  if (!entry || typeof entry !== "object") return null;1827  const title = typeof entry.title === "string" ? entry.title.trim() : "";1828  if (!title) return null;1829  const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();1830  const now = Date.now();1831  const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;1832  const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;18331834  // normalizeEntry whitelists every known VaultEntry field and runs the1835  // same legacy-passkey migration as the on-disk read path — pre-v2.11.01836  // backups with flat passkey fields still import correctly because the1837  // legacy flat fields are themselves whitelisted VaultEntry members.1838  const normalized = normalizeEntry({1839    ...entry,1840    id,1841    title,1842    type: entry.type ?? "login",1843    createdAt,1844    modifiedAt,1845  });18461847  if (normalized.passkey) {1848    normalized.passkey = sanitizePasskey(normalized.passkey);1849  }1850  if (normalized.canary) {1851    normalized.canary = sanitizeCanary(normalized.canary);1852  }1853  // PCH-01-016: bound tags on the restore path too, so both import funnels agree.1854  normalized.tags = sanitizeTags(normalized.tags);18551856  // Login entries from backup must carry a password (or be passkey-only,1857  // in which case the passkey sub-object replaces the password requirement).1858  if (1859    normalized.type === "login" &&1860    !normalized.passkey &&1861    typeof normalized.password !== "string"1862  ) {1863    return null;1864  }1865  if (entry.passkey && !normalized.passkey) {1866    // Entry claimed a passkey but the shape didn't validate — refuse the1867    // whole entry rather than silently importing a credential-less husk.1868    return null;1869  }18701871  return normalized;1872}18731874/**1875 * Rebuild a PasskeyData object from untrusted input, field by field.1876 * Returns undefined when required fields are missing/mistyped — a rogue1877 * passkey credential must not activate via import (MV-6 attack scenario).1878 */1879function sanitizePasskey(pk: unknown): PasskeyData | undefined {1880  if (!pk || typeof pk !== "object") return undefined;1881  const r = pk as Record<string, unknown>;1882  if (1883    typeof r.rpId !== "string" || !r.rpId ||1884    typeof r.credentialId !== "string" || !r.credentialId ||1885    typeof r.publicKeyCose !== "string" ||1886    typeof r.userHandle !== "string" ||1887    typeof r.userName !== "string"1888  ) {1889    return undefined;1890  }1891  return {1892    rpId: r.rpId,1893    rpName: typeof r.rpName === "string" ? r.rpName : r.rpId,1894    credentialId: r.credentialId,1895    publicKeyCose: r.publicKeyCose,1896    privateKeyJwk:1897      r.privateKeyJwk && typeof r.privateKeyJwk === "object"1898        ? (r.privateKeyJwk as JsonWebKey)1899        : undefined,1900    userHandle: r.userHandle,1901    userName: r.userName,1902    userDisplayName:1903      typeof r.userDisplayName === "string" ? r.userDisplayName : r.userName,1904    algorithm: r.algorithm === -8 ? -8 : -7,1905    signCount: typeof r.signCount === "number" ? r.signCount : 0,1906    aaguid: typeof r.aaguid === "string" ? r.aaguid : "",1907    backupEligible: r.backupEligible === true,1908    backupState: r.backupState === true,1909    lastUsedAt: typeof r.lastUsedAt === "number" ? r.lastUsedAt : undefined,1910    browser: r.browser === "chrome" || r.browser === "firefox" ? r.browser : undefined,1911    transports: Array.isArray(r.transports)1912      ? r.transports.filter((t): t is string => typeof t === "string")1913      : undefined,1914    createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),1915  };1916}19171918/**1919 * Rebuild a Canary object from untrusted input. The webhook must be a1920 * well-formed HTTPS URL — a poisoned canary.webhookUrl is a standing1921 * exfiltration endpoint that the canary subsystem will POST entry titles1922 * to (MV-6 attack scenario). Invalid → the canary is dropped, not the1923 * entry. FIRE_CANARY_PING re-validates with the full SSRF guard at fire1924 * time (isAllowedCanaryWebhookUrl), so this import-time check is the1925 * outer of two gates.1926 */1927function sanitizeCanary(c: unknown): Canary | undefined {1928  if (!c || typeof c !== "object") return undefined;1929  const r = c as Record<string, unknown>;1930  if (typeof r.webhookUrl !== "string") return undefined;1931  let url: URL;1932  try {1933    url = new URL(r.webhookUrl);1934  } catch {1935    return undefined;1936  }1937  if (url.protocol !== "https:") return undefined;1938  return {1939    webhookUrl: url.toString(),1940    label: typeof r.label === "string" ? r.label : undefined,1941    lastPinged: typeof r.lastPinged === "number" ? r.lastPinged : undefined,1942    pingCount: typeof r.pingCount === "number" ? r.pingCount : undefined,1943  };1944}19451946/**1947 * MV-6 / PCH-01-016: tags from imported / batch-added entries are untrusted.1948 * Keep only non-empty strings, cap each at 256 chars, and cap the count at 2551949 * (the same per-entry ceiling the export codec enforces, peachPayload.ts).1950 * Non-array or all-invalid input collapses to undefined.1951 */1952function sanitizeTags(tags: unknown): string[] | undefined {1953  if (!Array.isArray(tags)) return undefined;1954  const out: string[] = [];1955  for (const t of tags) {1956    if (typeof t !== "string") continue;1957    const trimmed = t.trim();1958    if (!trimmed) continue;1959    out.push(trimmed.slice(0, 256));1960    if (out.length >= 255) break;1961  }1962  return out.length > 0 ? out : undefined;1963}19641965// Soft-deletes every non-deleted entry in one call. The literal string1966// argument is a tripwire against accidental calls — any caller that would1967// wipe the vault has to consciously type "REPLACE_ALL". Do not relax this1968// to a boolean.1969export async function clearVaultEntries(1970  confirmation: "REPLACE_ALL"1971): Promise<void> {1972  if (confirmation !== "REPLACE_ALL") {1973    throw new Error("clearVaultEntries requires explicit confirmation");1974  }1975  if (!derivedKey) throw new Error("vault_locked");1976  for (const entry of entries) {1977    if (!entry.deletedAt) {1978      const stamp = monotonicEntryTimestamp(entry.modifiedAt);1979      entry.deletedAt = stamp;1980      entry.modifiedAt = stamp;1981    }1982  }1983  await persistEntries();1984}19851986export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {1987  if (!derivedKey) throw new Error("vault_locked");19881989  const sanitized = sanitizeEntryDraft(entry);1990  const now = Date.now();1991  const stamp = monotonicEntryTimestamp();1992  const nextEntry: VaultEntry = {1993    ...sanitized,1994    id: crypto.randomUUID(),1995    createdAt: now,1996    modifiedAt: stamp,1997    // Stamp passwordChangedAt at creation so age tracking is accurate from1998    // day one. Non-login entries carry the same stamp harmlessly.1999    passwordChangedAt: sanitized.password ? stamp : undefined,2000  };20012002  // Clone-and-replace so a failed persist rolls back the in-memory state2003  // (COR-008). Without this, a quota-full or storage error leaves the2004  // module-level `entries` ahead of what's actually on disk.2005  const rollback = entries;2006  entries = [...entries, nextEntry];2007  try {2008    await persistEntries();2009  } catch (err) {2010    entries = rollback;2011    throw err;2012  }20132014  // Fire-and-forget breach check (only for login entries if breach monitoring is enabled or not set)2015  if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {2016    checkBreach(nextEntry.password).then(async (count) => {2017      if (count > 0) {2018        const idx = entries.findIndex((e) => e.id === nextEntry.id);2019        if (idx !== -1) {2020          entries[idx] = { ...entries[idx], breach: count, modifiedAt: monotonicEntryTimestamp(entries[idx].modifiedAt) };2021          await persistEntries();2022        }2023      }2024    });2025  }20262027  fireSyncTrigger("vault_change");20282029  return nextEntry;2030}20312032/**2033 * Run the passkey-merge pass on the live in-memory entries and persist if2034 * anything changed. Called immediately after any passkey registration so that2035 * a same-domain TOTP-only entry already in the vault gets consolidated right2036 * away instead of waiting until the next lock/unlock cycle.2037 */2038export async function consolidatePasskeyEntries(): Promise<void> {2039  if (!derivedKey) return;2040  const { merged } = mergePasskeyOnlyIntoLogins(entries);2041  if (merged) {2042    await persistEntries();2043  }2044}20452046export async function updateEntry(2047  id: string,2048  patch: Partial<VaultEntry>2049): Promise<void> {2050  if (!derivedKey) throw new Error("vault_locked");20512052  const idx = entries.findIndex((entry) => entry.id === id);2053  if (idx === -1 || entries[idx].deletedAt) {2054    throw new Error("entry_not_found");2055  }20562057  const current = entries[idx];2058  const sanitizedPatch = sanitizeEntryPatch(patch);2059  // Refresh passwordChangedAt only when the password value actually changes —2060  // a metadata-only update (title, tags, etc.) must not reset the age clock2061  // that drives the Pro health rotation recommendation.2062  const passwordChanged =2063    "password" in patch &&2064    typeof sanitizedPatch.password === "string" &&2065    sanitizedPatch.password !== current.password;2066  const stamp = monotonicEntryTimestamp(current.modifiedAt);2067  // When the password actually changes, push the outgoing one onto the history2068  // (newest first) so the user can reveal/copy/restore it later. We record the2069  // age it carried (passwordChangedAt, falling back to createdAt) rather than2070  // `now`, so the list reflects when each password was last in effect. Only2071  // capture a non-empty prior value — clearing a password leaves no secret to2072  // keep, and we skip an immediate exact duplicate (e.g. restore-then-restore)2073  // to avoid noise.2074  const priorPassword = current.password;2075  const shouldCapture =2076    passwordChanged &&2077    typeof priorPassword === "string" &&2078    priorPassword.length > 0 &&2079    current.passwordHistory?.[0]?.password !== priorPassword;2080  const nextHistory = shouldCapture2081    ? [2082        { password: priorPassword!, changedAt: current.passwordChangedAt ?? current.createdAt },2083        ...(current.passwordHistory ?? []),2084      ].slice(0, PASSWORD_HISTORY_MAX)2085    : current.passwordHistory;2086  entries[idx] = {2087    ...current,2088    ...sanitizedPatch,2089    modifiedAt: stamp,2090    ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),2091  };2092209320942095  // Card entries must retain their card number2096  if (entries[idx].type === "card" && !entries[idx].cardNumber) {2097    entries[idx] = current;2098    throw new Error("card number is required for card entries");2099  }21002101  // Roll the in-memory entry back to its pre-edit state if the disk write2102  // fails (e.g. storage quota). Without this the module-level `entries` array2103  // would hold an edit that never landed on disk, diverging from the vault2104  // until the next unlock silently reverts it (SEV-3-A). Mirrors addEntry.2105  try {2106    await persistEntries();2107  } catch (err) {2108    entries[idx] = current;2109    throw err;2110  }21112112  // Breach check when password changes: clear immediately so old breach doesn't linger,2113  // then async-check the new password and only re-set if it's also found.2114  if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {2115    entries[idx] = { ...entries[idx], breach: undefined };2116    await persistEntries();2117    const password = entries[idx].password;2118    if (password) {2119      checkBreach(password).then(async (count) => {2120        const i = entries.findIndex((e) => e.id === id);2121        if (i !== -1 && count > 0) {2122          entries[i] = { ...entries[i], breach: count, modifiedAt: monotonicEntryTimestamp(entries[i].modifiedAt) };2123          await persistEntries();2124        }2125      });2126    }2127  }21282129  fireSyncTrigger("vault_change");2130}21312132export async function deleteEntry(id: string): Promise<void> {2133  if (!derivedKey) throw new Error("vault_locked");21342135  const entry = entries.find((item) => item.id === id);2136  if (!entry || entry.deletedAt) {2137    throw new Error("entry_not_found");2138  }21392140  // Tombstone timestamp must be strictly greater than the entry's last2141  // modification so the deletion wins LWW against any in-flight edit, even2142  // under clock skew (SEV-2-E).2143  const previousModifiedAt = entry.modifiedAt;2144  const stamp = monotonicEntryTimestamp(entry.modifiedAt);2145  entry.deletedAt = stamp;2146  entry.modifiedAt = stamp;2147  // Roll the tombstone back if the disk write fails, so a quota error doesn't2148  // leave the entry deleted in memory but alive on disk (SEV-3-A).2149  try {2150    await persistEntries();2151  } catch (err) {2152    delete entry.deletedAt;2153    entry.modifiedAt = previousModifiedAt;2154    throw err;2155  }2156  fireSyncTrigger("vault_change");2157}21582159export function getDeletedEntries(): VaultEntry[] {2160  if (!derivedKey) return [];2161  return entries.filter((e) => !!e.deletedAt);2162}21632164/**2165 * Returns the vault's monotonic version — the `peach_last_modified_at` value2166 * stamped on every user-initiated write. Remote (sync) writes do NOT advance2167 * this version so a sync round never cascades into a second outbound sync.2168 */2169export async function getVaultVersion(): Promise<number> {2170  try {2171    const raw = await chrome.storage.local.get("peach_last_modified_at");2172    const v = (raw as Record<string, unknown>).peach_last_modified_at;2173    if (typeof v === "number") return v;2174    if (typeof v === "string" && v !== "") {2175      const n = Number.parseInt(v, 10);2176      return Number.isFinite(n) ? n : 0;2177    }2178    return 0;2179  } catch {2180    return 0;2181  }2182}21832184/**2185 * Internal write variants — bypass `fireSyncTrigger` so the sync layer can2186 * apply entries without cascading into another outbound sync round.2187 *2188 * INVARIANT: callers must not pass entries whose IDs collide with existing2189 * active (non-deleted) entries unless the intent is an explicit overwrite.2190 * These functions do not validate field-level constraints (password required,2191 * card number required, etc.) — they are trust-the-caller paths for sync and2192 * test harness use only.2193 */2194export async function addEntryDirect(entry: VaultEntry): Promise<void> {2195  if (!derivedKey) throw new Error("vault_locked");2196  entries = [...entries, entry];2197  await persistEntries("sync_received");2198}21992200export async function updateEntryDirect(patch: VaultEntry): Promise<void> {2201  if (!derivedKey) throw new Error("vault_locked");2202  const idx = entries.findIndex((e) => e.id === patch.id);2203  if (idx === -1) throw new Error("entry_not_found");2204  entries[idx] = { ...entries[idx], ...patch };2205  await persistEntries("sync_received");2206}22072208export async function deleteEntryDirect(id: string, deletedAt: number): Promise<void> {2209  if (!derivedKey) throw new Error("vault_locked");2210  const idx = entries.findIndex((e) => e.id === id);2211  if (idx === -1) throw new Error("entry_not_found");2212  entries[idx] = { ...entries[idx], deletedAt, modifiedAt: deletedAt };2213  await persistEntries("sync_received");2214}22152216/**2217 * Apply a batch of remote entries + tombstones from a sync peer.2218 * Last-write-wins by `modifiedAt`; a tombstone supersedes a live entry when2219 * `deletedAt > modifiedAt` on the local side. Mutates `entries` directly and2220 * persists with reason `sync_received` — does NOT fire the sync dispatcher, so2221 * applying a sync round cannot cascade into another outbound sync.2222 *2223 * `applied` counts entries that actually changed local state (new add,2224 * overwrite-by-newer, or new tombstone). `received` is the raw payload size2225 * the caller can surface in the sync result UI.2226 */2227export async function applyMergedRemoteEntries(2228  remoteEntries: VaultEntry[],2229  remoteTombstones: Record<string, number>,2230  _context: { deviceName?: string } = {},2231): Promise<{ received: number; applied: number; conflicts: number }> {2232  // DESIGN: last-write-wins is applied PER-ENTRY, not per-field. If two devices2233  // concurrently edit different fields of the same entry, the one with the2234  // newer modifiedAt wins the whole entry and the other device's field edits2235  // are dropped silently. This is the deliberate trade-off for a simple,2236  // conflict-free merge — per-field CRDT merge is out of scope. Guidance for2237  // users: edit a given entry on one device at a time.2238  if (!derivedKey) throw new Error("vault_locked");22392240  const received = remoteEntries.length + Object.keys(remoteTombstones).length;2241  let applied = 0;2242  let conflicts = 0;22432244  const byId = new Map<string, VaultEntry>();2245  for (const e of entries) byId.set(e.id, e);22462247  const mergeNow = Date.now();22482249  for (const remote of remoteEntries) {2250    const sanitized = sanitizeRestoredEntry(remote);2251    if (!sanitized) continue;2252    // HV-1a: a far-future remote modifiedAt must not permanently pin a2253    // malicious value against honest local edits. Clamp BEFORE any2254    // comparison against local timestamps.2255    sanitized.modifiedAt = clampSyncTimestamp(sanitized.modifiedAt, mergeNow);2256    if (typeof sanitized.deletedAt === "number") {2257      sanitized.deletedAt = clampSyncTimestamp(sanitized.deletedAt, mergeNow);2258    }2259    const tombstoneTs = remoteTombstones[sanitized.id];2260    if (tombstoneTs !== undefined && clampSyncTimestamp(tombstoneTs, mergeNow) >= sanitized.modifiedAt) {2261      continue;2262    }2263    const local = byId.get(sanitized.id);2264    if (!local) {2265      entries.push(sanitized);2266      byId.set(sanitized.id, sanitized);2267      applied += 1;2268    } else if (sanitized.modifiedAt > local.modifiedAt) {2269      const idx = entries.findIndex((e) => e.id === local.id);2270      if (idx !== -1) {2271        entries[idx] = sanitized;2272        byId.set(sanitized.id, sanitized);2273        applied += 1;2274        if (!local.deletedAt) conflicts += 1;2275      }2276    }2277  }22782279  for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2280    if (typeof rawDeletedAt !== "number" || !Number.isFinite(rawDeletedAt)) continue;2281    // HV-1a/1c: clamp the tombstone timestamp before every comparison.2282    const deletedAt = clampSyncTimestamp(rawDeletedAt, mergeNow);2283    const local = byId.get(id);2284    if (!local) continue;2285    if (local.deletedAt && local.deletedAt >= deletedAt) continue;2286    if (deletedAt < local.modifiedAt) continue;2287    const idx = entries.findIndex((e) => e.id === id);2288    if (idx !== -1) {2289      entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };2290      applied += 1;2291    }2292  }22932294  if (applied > 0) {2295    await persistEntries("sync_received");2296    buildDomainIndexSync(entries);2297  }2298  return { received, applied, conflicts };2299}23002301export async function restoreEntry(id: string): Promise<void> {2302  if (!derivedKey) throw new Error("vault_locked");2303  const entry = entries.find((e) => e.id === id && e.deletedAt);2304  if (!entry) throw new Error("deleted entry not found");2305  delete entry.deletedAt;2306  entry.modifiedAt = monotonicEntryTimestamp(entry.modifiedAt);2307  await persistEntries();2308  buildDomainIndexSync(entries);2309}23102311export async function purgeEntry(id: string): Promise<void> {2312  if (!derivedKey) throw new Error("vault_locked");2313  const idx = entries.findIndex((e) => e.id === id && e.deletedAt);2314  if (idx === -1) throw new Error("deleted entry not found");2315  entries.splice(idx, 1);2316  await persistEntries();2317}23182319/** Permanently delete entries whose deletedAt is older than retentionMs. 0 = keep forever. */2320export async function purgeExpiredTrash(retentionMs: number): Promise<number> {2321  if (!derivedKey || retentionMs === 0) return 0;2322  const cutoff = Date.now() - retentionMs;2323  const before = entries.length;2324  entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));2325  const purged = before - entries.length;2326  if (purged > 0) await persistEntries();2327  return purged;2328}23292330export function queryDomain(domain: string): VaultEntry[] {2331  return domainIndex.get(domain) ?? [];2332}23332334export function getEntryById(id: string): VaultEntry | undefined {2335  return entries.find((entry) => entry.id === id && !entry.deletedAt);2336}23372338async function persistSlotA(2339  reason: VaultSnapshot["reason"] = "local_save",2340): Promise<StoredVault> {2341  if (!derivedKey) throw new Error("vault_locked");23422343  const slotA = await loadSlot(SLOT_A);2344  if (!slotA) throw new Error("missing slot A");23452346  // Snapshot the about-to-be-overwritten state BEFORE we mutate disk. Failures2347  // are swallowed by takeVaultSnapshot — history must never block a save.2348  await takeVaultSnapshot(reason);23492350  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);2351  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");23522353  // Preserve existing recovery escrow fields.2354  const nextSlotA: StoredVault = {2355    ...slotA,2356    nonce,2357    ciphertext,2358    tag,2359    // recovery_salt and recovery_wrapped_root_key are already set from loadSlot2360  };2361  await writeSlot(SLOT_A, nextSlotA);23622363  // Slot A (the real vault) is now committed. Wrap every later write so a2364  // mid-persist failure (e.g. a storage error after slot A landed) restores the2365  // prior slot A before rethrowing. Without this, a "failed" save that already2366  // wrote slot A leaves disk ahead of the in-memory rollback in addEntry/2367  // updateEntry/deleteEntry — the entry stays silently on disk and resurfaces2368  // as a duplicate on the next unlock (observed under storage-quota pressure).2369  try {2370    // When duress is not configured, keep slot B size-matched with slot A by2371    // regenerating its noise. When duress IS configured, leave slot B alone —2372    // we don't have the decoy key to re-encrypt it. This is a known trade-off.2373    if (!duressConfigured) {2374      await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));2375    }2376    // Only advance the vault version for locally-originated writes. Entries2377    // applied from a sync peer ("sync_received") must NOT bump the counter —2378    // otherwise applying a remote round makes us look newer than the peer and2379    // triggers a redundant outbound sync, defeating the no-op optimisation2380    // and risking a ping-pong between two devices (SEV-2-C).2381    if (reason !== "sync_received") {2382      await stampLocalVaultMutation();2383    }2384  } catch (err) {2385    // Best-effort restore — the prior slot A is smaller-or-equal, so this write2386    // fits even when the failure was a quota overflow.2387    await writeSlot(SLOT_A, slotA).catch(() => {});2388    throw err;2389  }23902391  return nextSlotA;2392}23932394async function persistSlotB(): Promise<void> {2395  if (!derivedKey) throw new Error("vault_locked");23962397  const slotB = await loadSlot(SLOT_B);2398  if (!slotB) throw new Error("missing slot B");23992400  // Decoy plaintext always reports duressConfigured=false — the decoy user2401  // sees a clean slate. persistSlotB only runs in decoy mode, which only2402  // exists once duress is configured, so pad to the fixed duress ceiling to2403  // keep slot B's length equal to slot A's (audit MEDIUM — deniability).2404  const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);2405  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");24062407  await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });2408  // Symmetric with persistSlotA: if the version stamp fails after the decoy2409  // slot committed, restore the prior slot B so a failed decoy-mode save can't2410  // leave disk ahead of the in-memory rollback.2411  try {2412    await stampLocalVaultMutation();2413  } catch (err) {2414    await writeSlot(SLOT_B, slotB).catch(() => {});2415    throw err;2416  }2417}24182419async function persistEntries(2420  reason: VaultSnapshot["reason"] = "local_save",2421): Promise<void> {2422  if (!derivedKey) throw new Error("vault_locked");24232424  if (vaultMode === "decoy") {2425    await persistSlotB();2426  } else {2427    await persistSlotA(reason);2428  }2429  buildDomainIndexSync(entries);2430}24312432function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {2433  if (!Array.isArray(values)) return undefined;2434  const seen = new Set<string>();2435  const cleaned: string[] = [];2436  for (const value of values) {2437    const trimmed = typeof value === "string" ? value.trim() : "";2438    if (!trimmed) continue;2439    const key = trimmed.toLowerCase();2440    if (seen.has(key)) continue;2441    seen.add(key);2442    cleaned.push(trimmed);2443  }2444  return cleaned.length > 0 ? cleaned : undefined;2445}24462447function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {2448  const title = entry.title.trim();2449  // Accept legacy `type:"passkey"` drafts but rewrite to "login" — the new2450  // model is "any entry, optionally with a passkey sub-object." Imports and2451  // any in-flight callers from before v2.11.0 keep working without throwing.2452  let type: VaultEntry["type"] = entry.type ?? "login";2453  if (type === "passkey") type = "login";24542455  if (!title) throw new Error("title is required");24562457  if (entry.passkey) {2458    const p = entry.passkey;2459    if (2460      !p.rpId ||2461      !p.credentialId ||2462      !p.publicKeyCose ||2463      !p.userHandle ||2464      !p.userName ||2465      (p.algorithm !== -7 && p.algorithm !== -8)2466    ) {2467      throw new Error("invalid passkey credential");2468    }2469  }2470  if (type === "card") {2471    if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {2472      throw new Error("cardholder name and card number are required");2473    }2474  }24752476  return {2477    type,2478    title,2479    username: type === "login" ? entry.username?.trim() ?? "" : undefined,2480    email: type === "login" ? entry.email?.trim() || undefined : undefined,2481    password: type === "login" ? entry.password : undefined,2482    url: type === "login" ? entry.url?.trim() ?? "" : undefined,2483    additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,2484    totp: type === "login" ? entry.totp?.trim() || undefined : undefined,2485    // PCH-01-019: preserve non-default TOTP params through batch-add/import so2486    // they are not silently stripped (they fall back to SHA-1/6/30 when absent).2487    totpAlgorithm: type === "login" ? entry.totpAlgorithm : undefined,2488    totpDigits: type === "login" ? entry.totpDigits : undefined,2489    totpPeriod: type === "login" ? entry.totpPeriod : undefined,2490    notes: entry.notes?.trim() || undefined,2491    breach: type === "login" ? entry.breach : undefined,2492    // PCH-01-016: the batch-add path was bypassing the MV-6 canary/tags2493    // whitelist applied on the RESTORE_ENTRIES path. Run both sanitizers here.2494    canary: type === "login" ? sanitizeCanary(entry.canary) : undefined,2495    tags: sanitizeTags(entry.tags),2496    passkey: entry.passkey,2497    cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,2498    cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,2499    expMonth: type === "card" ? entry.expMonth?.trim() : undefined,2500    expYear: type === "card" ? entry.expYear?.trim() : undefined,2501    cvc: type === "card" ? entry.cvc?.trim() : undefined,2502    cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,2503    network: type === "card" ? entry.network : undefined,2504    last4: type === "card" ? entry.last4?.trim() : undefined,2505  };2506}25072508function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {2509  const nextPatch: Partial<VaultEntry> = {};25102511  if ("type" in patch) {2512    nextPatch.type = patch.type;2513  }25142515  if ("title" in patch) {2516    const title = patch.title?.trim() ?? "";2517    if (!title) throw new Error("title is required");2518    nextPatch.title = title;2519  }25202521  if ("url" in patch) {2522    nextPatch.url = patch.url?.trim() ?? "";2523  }25242525  if ("additionalUrls" in patch) {2526    const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];2527    const seen = new Set<string>();2528    const cleaned: string[] = [];2529    for (const value of incoming) {2530      const trimmed = typeof value === "string" ? value.trim() : "";2531      if (!trimmed) continue;2532      const key = trimmed.toLowerCase();2533      if (seen.has(key)) continue;2534      seen.add(key);2535      cleaned.push(trimmed);2536    }2537    nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;2538  }25392540  if ("username" in patch) {2541    nextPatch.username = patch.username?.trim() ?? "";2542  }25432544  if ("email" in patch) {2545    nextPatch.email = patch.email?.trim() || undefined;2546  }25472548  if ("password" in patch) {2549    const password = patch.password ?? "";2550    // Allow clearing a password (e.g. on passkey-only entries)2551    nextPatch.password = password || undefined;2552  }25532554  if ("totp" in patch) {2555    nextPatch.totp = patch.totp?.trim() || undefined;2556  }25572558  if ("notes" in patch) {2559    nextPatch.notes = patch.notes?.trim() || undefined;2560  }25612562  if ("breach" in patch) {2563    nextPatch.breach = patch.breach;2564  }25652566  if ("canary" in patch) {2567    // PCH-02-001: route update patches through the same canary whitelist used2568    // by add/restore/sync. Invalid shapes drop the canary; `undefined` clears it.2569    nextPatch.canary = patch.canary ? sanitizeCanary(patch.canary) : undefined;2570  }25712572  if ("passkey" in patch) {2573    // Passkey sub-object replaces all the legacy flat passkey fields. A2574    // patch with `passkey: undefined` removes the credential from the entry2575    // (used by "remove passkey" without deleting the whole entry).2576    if (patch.passkey === undefined || patch.passkey === null) {2577      nextPatch.passkey = undefined;2578    } else {2579      const sanitized = sanitizePasskey(patch.passkey);2580      if (!sanitized) throw new Error("invalid passkey credential");2581      nextPatch.passkey = sanitized;2582    }2583  }25842585  if ("tags" in patch) {2586    // PCH-02-001: bound tags exactly like both import funnels.2587    nextPatch.tags = sanitizeTags(patch.tags);2588  }25892590  if ("cardholderName" in patch) {2591    nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;2592  }2593  if ("cardNumber" in patch) {2594    const n = patch.cardNumber ?? "";2595    nextPatch.cardNumber = n || undefined;2596  }2597  if ("expMonth" in patch) {2598    nextPatch.expMonth = patch.expMonth?.trim() || undefined;2599  }2600  if ("expYear" in patch) {2601    nextPatch.expYear = patch.expYear?.trim() || undefined;2602  }2603  if ("cvc" in patch) {2604    nextPatch.cvc = patch.cvc?.trim() || undefined;2605  }2606  if ("cardNickname" in patch) {2607    nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;2608  }2609  if ("network" in patch) {2610    nextPatch.network = patch.network;2611  }2612  if ("last4" in patch) {2613    nextPatch.last4 = patch.last4?.trim() || undefined;2614  }26152616  return nextPatch;2617}26182619function normalizeEntry(entry: VaultEntry | LegacyVaultEntry): VaultEntry {2620  const createdAt = "createdAt" in entry ? entry.createdAt : entry.created;2621  const modifiedAt =2622    "modifiedAt" in entry ? entry.modifiedAt : entry.updated;26232624  const base: VaultEntry = {2625    id: entry.id,2626    type: "type" in entry ? entry.type : "login",2627    title: entry.title,2628    username: entry.username,2629    email: "email" in entry ? entry.email : undefined,2630    password: entry.password,2631    url: entry.url,2632    additionalUrls:2633      "additionalUrls" in entry && Array.isArray(entry.additionalUrls)2634        ? entry.additionalUrls2635        : undefined,2636    totp: entry.totp,2637    // PCH-01-019: carry TOTP params through the normalize/restore path too.2638    totpAlgorithm: entry.totpAlgorithm,2639    totpDigits: entry.totpDigits,2640    totpPeriod: entry.totpPeriod,2641    notes: entry.notes,2642    breach: entry.breach,2643    // Preserve the password-age clock across lock/unlock. Without this the2644    // field is dropped on every decode and the advanced-health "aged password"2645    // signal silently resets to createdAt on each unlock (SEV-2-A).2646    passwordChangedAt:2647      "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,2648    // Preserve past-password history across lock/unlock. normalizeEntry is a2649    // field whitelist, so an unlisted field is silently dropped on every decode2650    // (same class as the passwordChangedAt SEV-2-A above).2651    passwordHistory:2652      "passwordHistory" in entry && Array.isArray(entry.passwordHistory)2653        ? entry.passwordHistory2654        : undefined,2655    canary: "canary" in entry ? entry.canary : undefined,2656    passkey: "passkey" in entry ? entry.passkey : undefined,2657    createdAt,2658    modifiedAt,2659    deletedAt: entry.deletedAt,2660    tags: "tags" in entry ? entry.tags : undefined,2661    cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,2662    cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,2663    expMonth: "expMonth" in entry ? entry.expMonth : undefined,2664    expYear: "expYear" in entry ? entry.expYear : undefined,2665    cvc: "cvc" in entry ? entry.cvc : undefined,2666    cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,2667    network: "network" in entry ? entry.network : undefined,2668    last4: "last4" in entry ? entry.last4 : undefined,2669  };26702671  return migrateLegacyPasskey(base, entry);2672}26732674/**2675 * v2.11.0 read migration. Pre-v2.11.0 passkey entries used `type:"passkey"`2676 * with flat top-level fields (rpId, credentialId, etc.). This converts them2677 * to the new shape — `type:"login"` with a `passkey` sub-object — so all2678 * downstream consumers can rely on the new model. The result is rewritten2679 * to disk on next vault save (hasLegacyShape detects the un-migrated case).2680 */2681function migrateLegacyPasskey(2682  base: VaultEntry,2683  raw: VaultEntry | LegacyVaultEntry2684): VaultEntry {2685  if (base.passkey) return base;2686  const flat = raw as Partial<VaultEntry>;2687  const isPasskeyType = base.type === "passkey";2688  const hasFlatPasskeyFields =2689    typeof flat.rpId === "string" &&2690    typeof flat.credentialId === "string" &&2691    typeof flat.publicKeyCose === "string" &&2692    typeof flat.userHandle === "string" &&2693    typeof flat.userName === "string";2694  if (!isPasskeyType && !hasFlatPasskeyFields) return base;2695  if (!hasFlatPasskeyFields) return base;26962697  const algorithm: -7 | -8 = flat.algorithm === -8 ? -8 : -7;2698  base.passkey = {2699    rpId: flat.rpId!,2700    rpName: flat.rpName ?? flat.rpId!,2701    credentialId: flat.credentialId!,2702    publicKeyCose: flat.publicKeyCose!,2703    privateKeyJwk: flat.privateKeyJwk,2704    userHandle: flat.userHandle!,2705    userName: flat.userName!,2706    userDisplayName: flat.userDisplayName ?? flat.userName!,2707    algorithm,2708    signCount: flat.signCount ?? 0,2709    aaguid: flat.aaguid ?? "",2710    backupEligible: flat.backupEligible === true,2711    backupState: flat.backupState === true,2712    lastUsedAt: flat.lastUsedAt,2713    browser: flat.browser,2714    transports: flat.transports,2715    createdAt: base.createdAt,2716  };2717  // Promote to "login" so the unified Entry view renders. Username gets2718  // populated from the passkey's userName so the entry is searchable in the2719  // existing autofill flow without a separate code path.2720  if (isPasskeyType) base.type = "login";2721  if (!base.username) base.username = flat.userName;2722  if (!base.url) base.url = `https://${flat.rpId}`;2723  return base;2724}272527262727// ---------------------------------------------------------------------------2728// Deduplication2729// ---------------------------------------------------------------------------27302731function entryDupeKey(e: VaultEntry): string {2732  if (e.type === "note") return `note|${e.title.toLowerCase()}`;2733  // Passkey-bearing entries dedupe by the credential's RP + user. Two logins2734  // on different sites that happen to share a username are still distinct;2735  // two passkey credentials for the same RP+user are duplicates regardless2736  // of any login fields they may also carry.2737  if (e.passkey) {2738    return `passkey|${e.passkey.rpId.toLowerCase()}|${e.passkey.userName.toLowerCase()}`;2739  }2740  return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;2741}27422743/** Returns the number of duplicate entries (those that would be removed). */2744export function countDuplicates(): number {2745  const best = new Map<string, VaultEntry>();2746  let dupeCount = 0;2747  for (const e of entries.filter((e) => !e.deletedAt)) {2748    const key = entryDupeKey(e);2749    const existing = best.get(key);2750    if (!existing) {2751      best.set(key, e);2752    } else {2753      dupeCount++;2754      // Keep the more recently modified one in the map2755      if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2756        best.set(key, e);2757      }2758    }2759  }2760  return dupeCount;2761}27622763/**2764 * Soft-deletes duplicate entries, keeping the most recently modified copy of2765 * each group. Returns the number of entries moved to trash.2766 */2767export async function deduplicateEntries(): Promise<number> {2768  if (!derivedKey) throw new Error("vault_locked");2769  // Dedup reshapes slot B permanently under the decoy key, which is2770  // forensically distinguishable from a freshly-seeded decoy vault. Refuse.2771  if (vaultMode === "decoy") {2772    throw new Error("deduplicate disabled in decoy mode");2773  }27742775  const best = new Map<string, VaultEntry>();2776  for (const e of entries.filter((en) => !en.deletedAt)) {2777    const key = entryDupeKey(e);2778    const existing = best.get(key);2779    if (!existing) {2780      best.set(key, e);2781    } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2782      best.set(key, e);2783    }2784  }27852786  const keepIds = new Set(Array.from(best.values()).map((e) => e.id));2787  let removed = 0;2788  entries = entries.map((e) => {2789    if (!e.deletedAt && !keepIds.has(e.id)) {2790      removed++;2791      return { ...e, deletedAt: monotonicEntryTimestamp(e.modifiedAt) };2792    }2793    return e;2794  });27952796  if (removed > 0) await persistEntries();2797  return removed;2798}27992800// ---------------------------------------------------------------------------2801// Vault history — snapshot BEFORE every vault write so the saved blob is2802// what is about to be lost, not what was just written. Capped at 5. The2803// stored blobs are AES-256-GCM ciphertext under the master password, so2804// history adds zero security surface.2805// ---------------------------------------------------------------------------28062807const HISTORY_KEY = "peach_vault_history";2808const HISTORY_MAX = 5;28092810// PCH-01-023: coarsen a live-entry count into a low-resolution bucket so the2811// plaintext snapshot field cannot reveal exact vault size or single-entry change2812// deltas. Buckets widen as the vault grows so absolute leakage stays roughly2813// proportional rather than exact.2814function bucketEntryCount(n: number): number {2815  if (n <= 0) return 0;2816  if (n <= 10) return 10;2817  if (n <= 25) return 25;2818  if (n <= 50) return 50;2819  if (n <= 100) return 100;2820  if (n <= 250) return 250;2821  if (n <= 500) return 500;2822  return Math.ceil(n / 500) * 500;2823}28242825/**2826 * Snapshot the CURRENT on-disk vault state into history. Call this BEFORE2827 * overwriting peach_vault_a so the saved blob captures the about-to-be-lost2828 * state. Identical-to-most-recent blobs are skipped to avoid filling history2829 * with no-op writes.2830 */2831export async function takeVaultSnapshot(2832  reason: VaultSnapshot["reason"],2833): Promise<void> {2834  try {2835    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);2836    const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];2837    const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];28382839    // Nothing to snapshot if the real slot doesn't exist yet (fresh install,2840    // pre-createVault). createVault skips snapshots intentionally — there is2841    // no prior state to preserve.2842    if (!slotA) return;28432844    const vault_a = JSON.stringify(slotA);2845    const vault_b = JSON.stringify(slotB ?? slotA);28462847    // Best-effort entry count: only meaningful when the in-memory state is2848    // unlocked AND in real mode. Decoy mode would leak the decoy entry2849    // count; locked mode has no entries to count. Both fall through to null.2850    // PCH-01-023: store a coarse bucket, not the exact count — chrome.storage2851    // .local sits next to the AES-GCM blobs in plaintext, so an exact count would2852    // leak vault size and per-write deltas (the metadata padding hides this).2853    let entryCount: number | null = null;2854    if (derivedKey && vaultMode === "real") {2855      try {2856        entryCount = bucketEntryCount(entries.filter((e) => !e.deletedAt).length);2857      } catch {2858        entryCount = null;2859      }2860    }28612862    const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];2863    const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)2864      ? existingRaw2865      : { snapshots: [] };28662867    // Deduplication: if the most recent snapshot has byte-identical blobs,2868    // skip — saves the same vault N times in a row would otherwise burn the2869    // entire history window with no recovery value.2870    const latest = history.snapshots[0];2871    if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {2872      return;2873    }28742875    const snapshot: VaultSnapshot = {2876      id: crypto.randomUUID(),2877      savedAt: Date.now(),2878      reason,2879      vault_a,2880      vault_b,2881      entryCount,2882    };28832884    history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);2885    await chrome.storage.local.set({ [HISTORY_KEY]: history });2886  } catch (err) {2887    // Non-fatal — history must never block a save. A failed snapshot just2888    // means the user loses one rung of the safety ladder for this write.2889    // M4/QUA-006: log so the failure is visible; if it looks like a quota2890    // problem, notify the popup so the user can prune history themselves.2891    console.warn('[Peach] takeVaultSnapshot failed:', err);2892    if (String(err).includes('QUOTA') || String(err).includes('quota')) {2893      try {2894        await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });2895      } catch {2896        // popup may be closed; surfaced via console.warn above2897      }2898    }2899  }2900}29012902/** Wipe all vault history. Called by Panic / DESTROY_VAULT. */2903export async function clearVaultHistory(): Promise<void> {2904  try {2905    await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });2906  } catch {2907    // Non-fatal — DESTROY_VAULT also runs storage.local.clear().2908  }2909}29102911/** Read all snapshots, newest first, for the Settings vault history view. */2912export async function getVaultHistory(): Promise<VaultSnapshot[]> {2913  const raw = await chrome.storage.local.get(HISTORY_KEY);2914  const history = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];2915  if (!history || !Array.isArray(history.snapshots)) return [];2916  return history.snapshots;2917}29182919/**2920 * Replace the on-disk vault with the chosen snapshot's blobs and lock the2921 * vault. The current state is itself snapshotted with reason 'restore' first2922 * so the restore is reversible. After this returns, the user must unlock2923 * with the password that matches the restored blob.2924 */2925export async function restoreVaultSnapshot(2926  snapshotId: string,2927): Promise<{ ok: true } | { ok: false; error: string }> {2928  const history = await getVaultHistory();2929  const snapshot = history.find((s) => s.id === snapshotId);2930  if (!snapshot) return { ok: false, error: "snapshot_not_found" };29312932  // Snapshot the about-to-be-replaced current state so the restore is2933  // reversible. takeVaultSnapshot is no-op when the most recent entry is2934  // byte-identical, so a restore-of-a-restore stays clean.2935  await takeVaultSnapshot("restore");29362937  let restoredA: StoredVault;2938  let restoredB: StoredVault;2939  try {2940    restoredA = JSON.parse(snapshot.vault_a) as StoredVault;2941    restoredB = JSON.parse(snapshot.vault_b) as StoredVault;2942  } catch {2943    return { ok: false, error: "snapshot_corrupt" };2944  }29452946  await writeSlot(SLOT_A, restoredA);2947  await writeSlot(SLOT_B, restoredB);2948  await stampLocalVaultMutation();29492950  // Lock so the user must prove they can decrypt the restored blob. If they2951  // restored a pre-password-change snapshot they discover it immediately at2952  // the lock screen rather than silently holding an inaccessible vault.2953  lock();29542955  return { ok: true };2956}29572958/**2959 * Rotate the vault's sync identity by generating a FRESH ROOT KEY and2960 * re-wrapping everything under it (MV-8). Because every sync credential —2961 * vault_id, the Noise static keypair, the Ed25519 manifest signing key,2962 * and the per-entry envelope keys — derives from the root key, rotation2963 * makes a lost/stolen device's retained key material useless. All paired2964 * devices must re-pair afterwards.2965 *2966 * CONSEQUENCE THE UI MUST SURFACE: the 12 recovery words also derive from2967 * the root key, so rotation INVALIDATES the old recovery phrase. The flow2968 * sets peach_recovery_pending so the popup re-presents the new words for2969 * confirmation, same as the migrateToRecovery rotate path.2970 */2971export async function rotateSyncIdentity(): Promise<{ ok: boolean; error?: string }> {2972  if (!derivedKey || vaultMode !== "real") {2973    return { ok: false, error: "vault_locked" };2974  }2975  const slotA = await loadSlot(SLOT_A);2976  if (!slotA) return { ok: false, error: "missing_slot_a" };29772978  // 1. Fresh root key + recovery escrow (new words).2979  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =2980    await generateAndWrapRootKey();29812982  // 2. Re-wrap the new root key under the current password-derived key.2983  const newRootKey = unhex(rawRootKey);2984  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, newRootKey);29852986  // 3. Snapshot, then single atomic slot write — both escrow wrappings of2987  //    the new root key land together (same transactional rule as2988  //    changePassword). Entries are untouched: they are sealed under the2989  //    password-derived key, not the root key.2990  await takeVaultSnapshot("local_save");2991  const nextSlotA: StoredVault = {2992    ...slotA,2993    recovery_salt: recoverySalt,2994    recovery_wrapped_root_key: wrappedRootKey,2995    recovery_nonce: wrappedNonce,2996    recovery_tag: wrappedTag,2997    ...pwRoot,2998  };2999  await writeSlot(SLOT_A, nextSlotA);30003001  // 4. Swap in memory only after disk committed.3002  if (rootKey) zeroKey(rootKey);3003  rootKey = newRootKey;30043005  // 5. Old peers' identities derive from the dead root key — drop them all.3006  await clearPairedDevices();30073008  // 6. Force re-presentation of the NEW recovery words on next popup view.3009  await setRecoveryConfirmPending(); // same flag the create-vault flow uses30103011  await stampLocalVaultMutation();3012  return { ok: true };3013}30143015/**3016 * Change the master password. Re-encrypts slot A with a fresh salt + new3017 * derived key. Slot B (duress or noise) is left untouched when duress is3018 * configured — it uses an independent key derived from the duress password —3019 * and regenerated as noise when duress is not configured.3020 */3021export async function changePassword(3022  currentPassword: string,3023  newPassword: string3024): Promise<boolean> {3025  if (!derivedKey || vaultMode !== "real") return false;30263027  // Verify current password before allowing any change3028  const valid = await verifyMainPassword(currentPassword);3029  if (!valid) return false;30303031  const slotA = await loadSlot(SLOT_A);3032  if (!slotA) return false;3033  if (!rootKey) return false;30343035  // Derive fresh key from new password + new random salt3036  const newSalt = generateSalt();3037  const newKey = await deriveKey(newPassword, newSalt);30383039  // Re-encrypt the in-memory entries with the new key3040  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3041  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");30423043  // Pre-wrap root key under the new derived key. Recovery fields wrap rootKey3044  // under recovery words and remain untouched — recovery phrase keeps working3045  // across password changes (H4/COR-002).3046  const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);30473048  const finalSlotA: StoredVault = {3049    ...slotA,3050    salt: hex(newSalt),3051    nonce,3052    ciphertext,3053    tag,3054    ...pwRoot,3055  };30563057  // Snapshot the OLD-key blob before overwriting it. If the user later3058  // restores from this snapshot they will need the OLD password — the3059  // post-restore lock surfaces that immediately.3060  await takeVaultSnapshot("local_save");30613062  // Single atomic write: ciphertext, salt, and pw_root_* fields all land in3063  // one storage transaction. An SW kill before this point leaves the old3064  // slot intact; after this point everything tied to the new password is3065  // already on disk together (M6/COR-004).3066  await writeSlot(SLOT_A, finalSlotA);30673068  // Swap the in-memory key synchronously before any further await. If we3069  // threw between the Slot A write and this swap, the next persistEntries()3070  // would overwrite Slot A with old-key ciphertext, locking the user out.3071  zeroKey(derivedKey);3072  derivedKey = newKey;30733074  // PCH-01-008: the MV3 session escrow still holds the OLD key. Without this,3075  // the next service-worker restore decrypts the new-key Slot A with the stale3076  // key, fails tryDecryptSlotResult, and silently drops the user to a lock3077  // screen. Re-escrow the new key so restore survives a password change.3078  void saveSessionKey(newKey, "real");30793080  // Regenerate noise for slot B when duress is not in use. Runs after the3081  // key swap so a failure here is a disposable noise regeneration, not a3082  // lockout.3083  if (!duressConfigured) {3084    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3085  }3086  await stampLocalVaultMutation();30873088  return true;3089}