vault.ts

119.2 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  /** Whether this vault has a local PIN unlock wrapper configured. */147  pinEnabled?: boolean;148  /** Whether the lock screen should open on PIN instead of the password. */149  pinPreferred?: boolean;150  /**151   * User overrides for keyboard shortcuts. Keys are ShortcutAction names152   * (see src/shared/shortcuts.ts). Missing actions fall through to153   * DEFAULT_BINDINGS — `getActiveBindings(settings.shortcuts)` is the154   * canonical lookup. Storing only the deltas keeps the vault payload155   * small and lets default updates land for users who never rebind.156   */157  shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;158}159160interface StoredPinWrap {161  version: 1;162  salt: string;163  nonce: string;164  ciphertext: string;165  tag: string;166}167168const PIN_WRAP_STORAGE = "peach_pin_wrap";169const PIN_MIN_LENGTH = 4;170const PIN_MAX_LENGTH = 12;171172let settings: VaultSettings = {};173174export function getSettings(): VaultSettings {175  return settings;176}177178export async function ensureSettingsLoaded(): Promise<VaultSettings> {179  await loadSettings();180  return settings;181}182183export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {184  await loadSettings();185  // LV-7: cheap insurance against prototype pollution if a future caller ever186  // feeds parsed external JSON here (native spread keeps __proto__ an own-187  // property today, but Object.assign-style consumers and JSON revivers have188  // been burned before).189  const safe = Object.fromEntries(190    Object.entries(patch).filter(191      ([k]) => !["__proto__", "constructor", "prototype"].includes(k),192    ),193  ) as Partial<VaultSettings>;194  settings = { ...settings, ...safe };195  await persistSettings();196}197198function isValidPin(pin: string): boolean {199  return new RegExp(`^\\d{${PIN_MIN_LENGTH},${PIN_MAX_LENGTH}}$`).test(pin);200}201202/** Set up a local PIN wrapper after proving the current master password. */203export async function setupPinUnlock(currentPassword: string, pin: string): Promise<boolean> {204  if (!derivedKey || vaultMode !== "real" || !isValidPin(pin)) return false;205  if (!(await verifyMainPassword(currentPassword))) return false;206207  const salt = generateSalt();208  const pinKey = await deriveKey(pin, salt);209  try {210    const wrapped = await encrypt(pinKey, hex(derivedKey), "pin_wrap_v1");211    await chrome.storage.local.set({212      [PIN_WRAP_STORAGE]: { version: 1, salt: hex(salt), ...wrapped } satisfies StoredPinWrap,213    });214    await updateSettings({ pinEnabled: true });215    return true;216  } finally {217    zeroKey(pinKey);218  }219}220221async function clearPinUnlockStorage(): Promise<void> {222  await chrome.storage.local.remove(PIN_WRAP_STORAGE);223  await updateSettings({ pinEnabled: false });224}225226/** Remove the PIN wrapper after proving the current master password. */227export async function disablePinUnlock(currentPassword: string): Promise<boolean> {228  if (!derivedKey || vaultMode !== "real") return false;229  if (!(await verifyMainPassword(currentPassword))) return false;230  await clearPinUnlockStorage();231  return true;232}233234/** Unlock the real vault from its locally stored PIN-wrapped derived key. */235export async function unlockWithPin(pin: string): Promise<boolean> {236  if (!isValidPin(pin)) return false;237  await loadSettings();238  if (!settings.pinEnabled) return false;239240  const stored = (await chrome.storage.local.get(PIN_WRAP_STORAGE))[PIN_WRAP_STORAGE] as241    | StoredPinWrap242    | undefined;243  if (244    !stored ||245    stored.version !== 1 ||246    !stored.salt ||247    !stored.nonce ||248    !stored.ciphertext ||249    !stored.tag250  ) return false;251252  const pinKey = await deriveKey(pin, unhex(stored.salt));253  let unwrappedKey: Uint8Array | null = null;254  try {255    const masterKeyHex = await decrypt(256      pinKey,257      stored.nonce,258      stored.ciphertext,259      stored.tag,260      "pin_wrap_v1",261    );262    if (!/^[0-9a-f]{64}$/.test(masterKeyHex)) return false;263    unwrappedKey = unhex(masterKeyHex);264    const result = await unlockWithKey(masterKeyHex);265    if (!result.ok) return false;266    await saveSessionKey(unwrappedKey, "real");267    return true;268  } catch {269    return false;270  } finally {271    zeroKey(pinKey);272    if (unwrappedKey) zeroKey(unwrappedKey);273  }274}275276async function persistSettings(): Promise<void> {277  try {278    await chrome.storage.local.set({ peach_settings: settings });279  } catch (err) {280    throw mapStorageError(err);281  }282}283284function mapStorageError(err: unknown): Error {285  const message = err instanceof Error ? err.message : String(err);286  if (/QUOTA_BYTES|quota/i.test(message)) {287    return new Error("STORAGE_QUOTA_EXCEEDED");288  }289  return err instanceof Error ? err : new Error(message);290}291292async function loadSettings(): Promise<void> {293  const result = await chrome.storage.local.get("peach_settings");294  settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};295}296297// Fire-and-forget sync trigger after a committed vault write. A failure here298// must never fail the write that caused it.299function fireSyncTrigger(reason: "vault_change"): void {300  void Promise.resolve()301    .then(() => triggerSyncIfReachable({ reason }))302    .catch(() => {303      /* no sync runner registered, or nothing reachable — non-fatal */304    });305}306307let lockedSyncRefreshHook: (() => Promise<void>) | null = null;308let lockedSyncUnlockHook: (() => Promise<void>) | null = null;309310export function setLockedSyncHooks(hooks: {311  refresh: () => Promise<void>;312  afterUnlock: () => Promise<void>;313}): void {314  lockedSyncRefreshHook = hooks.refresh;315  lockedSyncUnlockHook = hooks.afterUnlock;316}317318async function refreshLockedSyncState(): Promise<void> {319  if (vaultMode !== "real" || !rootKey || !lockedSyncRefreshHook) return;320  await lockedSyncRefreshHook().catch((error) => {321    console.warn("[Peach sync] locked spool refresh failed:", error);322  });323}324325// ---------------------------------------------------------------------------326// HIBP breach check (k-anonymity model)327// ---------------------------------------------------------------------------328329export async function checkBreach(password: string): Promise<number> {330  // HIBP k-anonymity API is keyed on SHA-1 prefixes — this is dictated by331  // the public API, not a security choice. Do not migrate to SHA-256 here.332  const encoder = new TextEncoder();333  const hashBuffer = await crypto.subtle.digest("SHA-1", encoder.encode(password));334  const hashHex = Array.from(new Uint8Array(hashBuffer))335    .map((b) => b.toString(16).padStart(2, "0"))336    .join("")337    .toUpperCase();338339  const prefix = hashHex.slice(0, 5);340  const suffix = hashHex.slice(5);341342  try {343    // PCH-02-007: request HIBP response padding so response length does not344    // reveal how many suffixes a queried prefix returned.345    const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`, {346      headers: { "Add-Padding": "true" },347    });348    if (!res.ok) return 0;349    const text = await res.text();350    const match = text.split("\r\n").find((l) => l.startsWith(suffix));351    return match ? parseInt(match.split(":")[1], 10) : 0;352  } catch {353    return 0; // Network unavailable — don't block354  }355}356357export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {358  const fingerprint = await cardFingerprint(last4, expMonth, expYear);359  await loadSettings();360  settings = {361    ...settings,362    declinedCardFingerprints: [...(settings.declinedCardFingerprints ?? []), fingerprint],363  };364  await persistSettings();365}366367export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {368  await loadSettings();369  const fingerprint = await cardFingerprint(last4, expMonth, expYear);370  return (settings.declinedCardFingerprints ?? []).includes(fingerprint);371}372373async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {374  const encoder = new TextEncoder();375  const buf = await crypto.subtle.digest("SHA-256", encoder.encode(`${last4}|${expMonth}|${expYear}`));376  return Array.from(new Uint8Array(buf).slice(0, 8))377    .map((b) => b.toString(16).padStart(2, "0"))378    .join("");379}380381function hex(buf: Uint8Array): string {382  return Array.from(buf)383    .map((b) => b.toString(16).padStart(2, "0"))384    .join("");385}386387function unhex(s: string): Uint8Array {388  const out = new Uint8Array(s.length / 2);389  for (let i = 0; i < s.length; i += 2) {390    out[i / 2] = parseInt(s.slice(i, i + 2), 16);391  }392  return out;393}394395// ---------------------------------------------------------------------------396// Root key generation and recovery word wrapping397// ---------------------------------------------------------------------------398399/**400 * Generate a random 32-byte root key and wrap it (AES-256-GCM) under a key401 * derived from the recovery word material via HKDF-SHA256. The wrapped blob402 * fields are stored in slot A alongside the password-wrapped ciphertext. The403 * root key itself is kept in memory for the session so getRecoveryWords() can404 * encode it without re-deriving.405 *406 * SECURITY MODEL (PCH-01-005): the recovery KEK is derived from the 12-word407 * material, which encodes only rootKey[0..16] (recovery-words.ts). The KEK is thus408 * derived from a PREFIX of the very plaintext it wraps, and effective recovery409 * security is 128-bit (standard for a 12-word phrase), NOT 256-bit. This is safe —410 * unwrapping requires the words, and the GCM ciphertext leaks nothing without them —411 * but it is intentional, not an oversight. A future escrow version wanting 256-bit412 * recovery must derive the words from INDEPENDENT entropy, not from the root key.413 */414async function generateAndWrapRootKey(): Promise<{415  rawRootKey: string; // hex of the plaintext root key — caller stores in rootKey416  recoverySalt: string;417  wrappedRootKey: string;418  wrappedNonce: string;419  wrappedTag: string;420}> {421  const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));422423  // Derive the recovery key from the BIP39 words encoding of the root key.424  const words = await rootKeyToWords(rootKeyBytes);425  const wordMaterial = await wordsToRootKeyMaterial(words);426  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));427  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);428429  // Wrap the root key with the recovery key using AES-256-GCM directly.430  // We hex-encode rootKeyBytes so the plaintext is always valid UTF-8.431  const nonce = crypto.getRandomValues(new Uint8Array(12));432  const encoded = new TextEncoder().encode(hex(rootKeyBytes));433  const raw = await crypto.subtle.encrypt(434    {435      name: "AES-GCM",436      iv: nonce,437      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,438      tagLength: 128,439    },440    recoveryKey,441    encoded442  );443  // WebCrypto returns ciphertext || auth tag concatenated; split them.444  const rawU8 = new Uint8Array(raw);445  const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));446  const tag = hex(rawU8.slice(rawU8.length - 16));447448  return {449    rawRootKey: hex(rootKeyBytes),450    recoverySalt: hex(recoverySalt),451    wrappedRootKey: ciphertext,452    wrappedNonce: hex(nonce),453    wrappedTag: tag,454  };455}456457async function wrapExistingRootKeyForRecovery(rootKeyBytes: Uint8Array): Promise<{458  recoverySalt: string;459  wrappedRootKey: string;460  wrappedNonce: string;461  wrappedTag: string;462}> {463  if (rootKeyBytes.length !== 32) {464    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");465  }466467  const words = await rootKeyToWords(rootKeyBytes);468  const wordMaterial = await wordsToRootKeyMaterial(words);469  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));470  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);471  const nonce = crypto.getRandomValues(new Uint8Array(12));472  const encoded = new TextEncoder().encode(hex(rootKeyBytes));473  const raw = await crypto.subtle.encrypt(474    {475      name: "AES-GCM",476      iv: nonce,477      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,478      tagLength: 128,479    },480    recoveryKey,481    encoded,482  );483  const rawU8 = new Uint8Array(raw);484  return {485    recoverySalt: hex(recoverySalt),486    wrappedRootKey: hex(rawU8.slice(0, rawU8.length - 16)),487    wrappedNonce: hex(nonce),488    wrappedTag: hex(rawU8.slice(rawU8.length - 16)),489  };490}491492/**493 * Unwrap the root key using recovery words. Called during recovery flow when494 * the user provides their 12-word phrase and a new password.495 * Exported for use by the RECOVER_WITH_WORDS message handler.496 */497export async function unwrapRootKeyForRecovery(498  wrappedRootKey: string,499  wrappedNonce: string,500  wrappedTag: string,501  recoverySaltHex: string,502  words: string[]503): Promise<void> {504  const wordMaterial = await wordsToRootKeyMaterial(words);505  const recoverySalt = unhex(recoverySaltHex);506  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);507508  // Decrypt and cache the root key. The root key bytes were hex-encoded before509  // encryption so the ciphertext is valid UTF-8. We inline the AES-GCM decrypt510  // here to avoid passing a CryptoKey to the string-based encrypt/decrypt helpers.511  // Each component is stored separately in the vault slot; decode them individually512  // so the nonce is always exactly the 12 bytes from wrappedNonce.513  const nonceRaw = unhex(wrappedNonce);514  const ciphertextRaw = unhex(wrappedRootKey);515  const tagRaw = unhex(wrappedTag);516  // Combine ciphertext and tag for AES-GCM (expects ciphertext||tag).517  // Use explicit ArrayBuffer allocations to satisfy TS BufferSource constraints.518  const nonceU8 = nonceRaw as unknown as Uint8Array<ArrayBuffer>;519  const combined = new Uint8Array(ciphertextRaw.length + tagRaw.length);520  combined.set(ciphertextRaw, 0);521  combined.set(tagRaw, ciphertextRaw.length);522  const raw = await crypto.subtle.decrypt(523    { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },524    recoveryKey,525    combined526  );527  const decryptedHex = new TextDecoder().decode(raw);528  rootKey = unhex(decryptedHex);529}530531/**532 * Re-wrap the cached root key under a new derived key (from the user's new533 * password). Called after password change and after recovery re-key so the534 * same recovery words continue to work with the updated password — and so535 * subsequent unlocks can rehydrate rootKey via deriveRootKeyFromDerivedKey.536 *537 * recovery_* fields are intentionally not touched: those wrap rootKey under538 * the recovery words, which do not change when the password changes.539 */540export async function rewrapRootKeyForPassword(541  newDerivedKey: Uint8Array,542  _newSalt: Uint8Array543): Promise<void> {544  if (!rootKey) throw new Error("root key not set");545  const slotA = await loadSlot(SLOT_A);546  if (!slotA) throw new Error("missing slot A");547  const pwRoot = await wrapRootKeyForDerivedKey(newDerivedKey, rootKey);548  await writeSlot(SLOT_A, { ...slotA, ...pwRoot });549}550551/**552 * Change the vault encryption to a new derived key (already derived from553 * the user's new password). Used by RECOVER_WITH_WORDS and changePassword.554 * Caller is responsible for key swap and snapshot.555 */556async function reencryptVaultForNewKey(557  newKey: Uint8Array,558  slotA: StoredVault559): Promise<void> {560  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);561  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");562  await writeSlot(SLOT_A, {563    ...slotA,564    nonce,565    ciphertext,566    tag,567  });568}569570/**571 * Full password change with an already-derived key (used after recovery).572 * Unlike changePassword(), this skips re-verification of current password573 * since recovery flow has already validated the user's identity via words.574 */575export async function changePasswordWithNewKey(576  newSalt: Uint8Array,577  newKey: Uint8Array578): Promise<void> {579  const slotA = await loadSlot(SLOT_A);580  if (!slotA) throw new Error("missing slot A");581  // reencryptVaultForNewKey must receive the updated salt so that subsequent582  // UNLOCK calls with the new password can re-derive the correct key.583  await reencryptVaultForNewKey(newKey, { ...slotA, salt: hex(newSalt) });584  if (derivedKey) zeroKey(derivedKey);585  derivedKey = newKey;586  // PCH-01-008: re-escrow the new key (see changePassword). The recovery flow587  // reaches this path, so a post-recovery SW restart would otherwise lock out588  // a user who just reset their password.589  void saveSessionKey(newKey, "real");590  // Refresh pw_root_* under the new key so deriveRootKeyFromDerivedKey works591  // on the next unlock (H2/COR-006). If rootKey is missing — recovery flow592  // should have populated it — fall back silently rather than blowing up the593  // recovery path; migrateToRecovery will rehydrate on the next unlock.594  if (rootKey) {595    const slotAfter = await loadSlot(SLOT_A);596    if (slotAfter) {597      const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);598      await writeSlot(SLOT_A, { ...slotAfter, ...pwRoot });599    }600  }601  if (!duressConfigured) {602    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));603  }604  await clearPinUnlockStorage();605  await stampLocalVaultMutation();606}607608// ---------------------------------------------------------------------------609// Salt generation --- exported so the RECOVER_WITH_WORDS handler can derive610// a new key after password reset without re-importing the crypto module.611// ---------------------------------------------------------------------------612613export { deriveKey, generateSalt };614615export async function loadSlotA(): Promise<StoredVault | null> {616  return loadSlot(SLOT_A);617}618619/**620 * Recover the session root key by AES-GCM-decrypting the pw_root_* fields621 * (a second wrapping of the root key under the password-derived key). This622 * is what makes GET_RECOVERY_WORDS work across lock/unlock cycles without623 * the user re-entering their recovery phrase: the same root key bytes —624 * and therefore the same 12 words — survive every unlock.625 *626 * Returns null when the pw_root fields are absent (pre-v2.12 vault that627 * hasn't been migrated yet) or when decryption fails (wrong derived key,628 * tampered ciphertext). On null the caller should fall through to629 * migrateToRecovery() to populate the fields.630 */631async function deriveRootKeyFromDerivedKey(632  derivedKeyBytes: Uint8Array,633  slotA: StoredVault,634): Promise<Uint8Array | null> {635  if (!slotA.pw_root_ciphertext || !slotA.pw_root_nonce || !slotA.pw_root_tag) {636    return null;637  }638  try {639    const rootHex = await decrypt(640      derivedKeyBytes,641      slotA.pw_root_nonce,642      slotA.pw_root_ciphertext,643      slotA.pw_root_tag,644      "pw_root_v1",645    );646    return unhex(rootHex);647  } catch {648    return null;649  }650}651652// AES-GCM-wrap rootKey under derivedKey for the pw_root_* fields. Returns the653// hex-encoded ciphertext/nonce/tag triple ready to embed in StoredVault.654async function wrapRootKeyForDerivedKey(655  derivedKeyBytes: Uint8Array,656  rootKeyBytes: Uint8Array,657): Promise<{ pw_root_ciphertext: string; pw_root_nonce: string; pw_root_tag: string }> {658  const { nonce, ciphertext, tag } = await encrypt(derivedKeyBytes, hex(rootKeyBytes), "pw_root_v1");659  return {660    pw_root_ciphertext: ciphertext,661    pw_root_nonce: nonce,662    pw_root_tag: tag,663  };664}665666/**667 * For vaults created before v2.12 (no recovery_salt/recovery_wrapped_root_key),668 * generate the root key, wrap it under the recovery words, and persist the669 * recovery escrow into slot A. The caller must show the recovery words to the670 * user before calling this — once called, those words are the vault's recovery671 * path. This runs once, on the first unlock of an upgraded vault.672 */673export async function migrateToRecovery(): Promise<void> {674  if (!derivedKey || vaultMode !== "real") {675    throw new Error("vault must be unlocked in real mode");676  }677  const slotA = await loadSlot(SLOT_A);678  if (!slotA) throw new Error("missing slot A");679  const hasRecoveryEscrow =680    !!slotA.recovery_salt && !!slotA.recovery_wrapped_root_key;681  const hasPwRoot = !!slotA.pw_root_ciphertext && !!slotA.pw_root_nonce;682  if (hasRecoveryEscrow && hasPwRoot) return; // already done683684  // If recovery escrow already exists but pw_root doesn't, we cannot recover685  // the original rootKey without the user's words. The least-surprising path686  // is to rotate to a fresh root key — the user's old recovery words become687  // invalid but we surface peach_recovery_pending so the popup re-presents688  // the words. The unlock-path callers all set that flag.689  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =690    await generateAndWrapRootKey();691  rootKey = unhex(rawRootKey);692693  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);694  const nextSlotA: StoredVault = {695    ...slotA,696    recovery_salt: recoverySalt,697    recovery_wrapped_root_key: wrappedRootKey,698    recovery_nonce: wrappedNonce,699    recovery_tag: wrappedTag,700    ...pwRoot,701  };702  await writeSlot(SLOT_A, nextSlotA);703  await stampLocalVaultMutation();704}705706/**707 * Returns the 12 recovery words for the current session's root key.708 * Must be called while the vault is unlocked. Throws if recovery has not709 * been set up (pre-v2.12 vault that hasn't migrated yet).710 */711export async function getRecoveryWords(): Promise<string[]> {712  if (!rootKey) {713    throw new Error("recovery not set up — vault may need migration");714  }715  return rootKeyToWords(rootKey);716}717718async function loadSlot(key: string): Promise<StoredVault | null> {719  const result = await chrome.storage.local.get(key);720  return (result as Record<string, StoredVault | undefined>)[key] ?? null;721}722723async function writeSlot(key: string, vault: StoredVault): Promise<void> {724  try {725    await chrome.storage.local.set({ [key]: vault });726  } catch (err) {727    throw mapStorageError(err);728  }729}730731/**732 * Roll back a vault that was created by [createVaultFromRootKey] but733 * couldn't be paired (e.g. the subsequent license activation, identity734 * derivation, or paired-device upsert failed). Without this, a failed735 * receiver session leaves behind an empty vault — the user has to736 * re-pair to get a working setup, but the empty vault sits in the way.737 *738 * The call is idempotent: removing keys that aren't there is a no-op.739 */740export async function rollbackAdoptedVault(): Promise<void> {741  lock();742  try {743    await chrome.storage.local.remove([744      SLOT_A,745      SLOT_B,746      "peach_last_modified_at",747    ]);748  } catch (err) {749    throw mapStorageError(err);750  }751}752753async function commitCreatedVaultSlots(slotA: StoredVault, slotB: StoredVault): Promise<void> {754  const raw = await chrome.storage.local.get("peach_last_modified_at");755  const previous = Number(756    (raw as Record<string, unknown>).peach_last_modified_at,757  );758  const next = Math.max(759    Date.now(),760    Number.isFinite(previous) ? previous + 1 : 0,761  );762  try {763    await chrome.storage.local.set({764      [SLOT_A]: slotA,765      [SLOT_B]: slotB,766      peach_last_modified_at: String(next),767    });768  } catch (err) {769    throw mapStorageError(err);770  }771}772773// Monotonic clock for per-entry modifiedAt / deletedAt timestamps. Guards the774// sync layer's last-write-wins merge against wall-clock regressions (NTP step,775// manual clock change, DST glitch): a backwards Date.now() must never produce776// an entry timestamp that's <= the entry's existing modifiedAt, or a genuine777// local edit would lose to a stale remote copy. The returned value is always778// strictly greater than both the entry's current modifiedAt and the previous779// call's result (SEV-2-E).780let lastEntryTimestamp = 0;781function monotonicEntryTimestamp(currentModifiedAt?: number): number {782  const base = Math.max(783    Date.now(),784    (currentModifiedAt ?? 0) + 1,785    lastEntryTimestamp + 1,786  );787  lastEntryTimestamp = base;788  return base;789}790791async function stampLocalVaultMutation(): Promise<void> {792  const raw = await chrome.storage.local.get("peach_last_modified_at");793  const previous = Number(794    (raw as Record<string, unknown>).peach_last_modified_at,795  );796  const next = Math.max(797    Date.now(),798    Number.isFinite(previous) ? previous + 1 : 0,799  );800  await chrome.storage.local.set({801    peach_last_modified_at: String(next),802  });803}804805/**806 * One-shot migration from the pre-A-2 schema (peach_vault + peach_decoy_vault807 * + peach_duress flag) to the slot-neutral schema (peach_vault_a +808 * peach_vault_b). Runs at most once per session; safe to call repeatedly.809 */810async function ensureMigrated(): Promise<void> {811  if (migrationRan) return;812  migrationRan = true;813814  const keys = [LEGACY_MAIN, LEGACY_DECOY, LEGACY_DURESS_FLAG, SLOT_A, SLOT_B];815  const raw = await chrome.storage.local.get(keys);816  const slotAExists = raw[SLOT_A] !== undefined;817  const slotBExists = raw[SLOT_B] !== undefined;818  const legacyMain = raw[LEGACY_MAIN] as StoredVault | undefined;819  const legacyDecoy = raw[LEGACY_DECOY] as StoredVault | undefined;820821  // Fresh install with nothing in storage — nothing to do; createVault() sets up both slots.822  if (!slotAExists && !legacyMain) return;823824  // Already migrated.825  if (slotAExists && slotBExists && !legacyMain && !legacyDecoy) return;826827  let didMigrate = false;828  if (legacyMain && !slotAExists) {829    await writeSlot(SLOT_A, legacyMain);830    didMigrate = true;831  }832833  // If slot B isn't set, populate it: use legacy decoy when present, else noise.834  if (!slotBExists) {835    const target = (legacyMain ?? raw[SLOT_A]) as StoredVault | undefined;836    if (legacyDecoy) {837      await writeSlot(SLOT_B, legacyDecoy);838      didMigrate = true;839    } else if (target) {840      await writeSlot(SLOT_B, generateNoiseBlob(target.ciphertext.length / 2));841      didMigrate = true;842    }843  }844845  const toRemove: string[] = [];846  if (legacyMain) toRemove.push(LEGACY_MAIN);847  if (legacyDecoy) toRemove.push(LEGACY_DECOY);848  if (raw[LEGACY_DURESS_FLAG] !== undefined) toRemove.push(LEGACY_DURESS_FLAG);849  if (toRemove.length > 0) {850    await chrome.storage.local.remove(toRemove);851    didMigrate = true;852  }853  if (didMigrate) {854    await stampLocalVaultMutation();855  }856}857858// ---------------------------------------------------------------------------859// Padding + noise helpers860// ---------------------------------------------------------------------------861862/**863 * Pads the plaintext string with trailing spaces so that the encoded byte864 * length is a multiple of PAD_BLOCK. JSON.parse tolerates trailing865 * whitespace after a complete document, so the padding is transparent on866 * decode. Ciphertext length equals plaintext length plus a 16-byte tag.867 */868function padPlaintext(json: string, minBytes = 0): string {869  const encoded = new TextEncoder().encode(json);870  const bucket = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);871  // minBytes lets the duress path force a fixed ceiling so both slots match.872  const target = Math.max(bucket, minBytes);873  const padLen = target - encoded.length;874  return json + " ".repeat(padLen);875}876877/**878 * Produces a StoredVault-shaped record filled with CSPRNG bytes. The879 * ciphertext length matches the given byte count. Because GCM ciphertext is880 * pseudo-random, this blob is indistinguishable at rest from a real881 * encrypted vault without the key.882 *883 * crypto.getRandomValues() caps each call at 65536 bytes (the Web Crypto884 * spec hard limit). Chunk the fill so vaults larger than that — common once885 * the user has dozens of entries or any passkey — don't throw.886 */887const CSPRNG_CHUNK = 65_536;888889function fillRandom(buf: Uint8Array): Uint8Array {890  for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {891    const end = Math.min(offset + CSPRNG_CHUNK, buf.length);892    const chunk = new Uint8Array(end - offset);893    crypto.getRandomValues(chunk);894    buf.set(chunk, offset);895  }896  return buf;897}898899function generateNoiseBlob(ciphertextBytes: number): StoredVault {900  const salt = crypto.getRandomValues(new Uint8Array(16));901  const nonce = crypto.getRandomValues(new Uint8Array(12));902  const cipher = fillRandom(new Uint8Array(ciphertextBytes));903  const tag = crypto.getRandomValues(new Uint8Array(16));904  return {905    version: 1,906    salt: hex(salt),907    nonce: hex(nonce),908    ciphertext: hex(cipher),909    tag: hex(tag),910  };911}912913// ---------------------------------------------------------------------------914// Encrypted plaintext envelope915// ---------------------------------------------------------------------------916917type VaultPayload = {918  entries: VaultEntry[];919  duressConfigured?: boolean;920};921922type DecryptedPayload = {923  entries: VaultEntry[];924  duressConfigured: boolean;925  /**926   * True when at least one entry in the on-disk payload had a legacy shape927   * (pre-v2.11.0 passkey type/flat fields, or pre-A-2 created/updated keys)928   * and got rewritten by normalizeEntry. The unlock path uses this to929   * persist the new shape immediately — without it, the migration would930   * re-run on every unlock and old shape never disappears from disk.931   */932  migratedFromLegacy: boolean;933};934935function encodePayload(entries: VaultEntry[], duress: boolean, minBytes = 0): string {936  const envelope: VaultPayload = { entries, duressConfigured: duress };937  return padPlaintext(JSON.stringify(envelope), minBytes);938}939940function rawNeedsMigration(raw: VaultEntry | LegacyVaultEntry): boolean {941  if ("created" in raw || "updated" in raw) return true;942  const flat = raw as Partial<VaultEntry>;943  if (flat.type === "passkey") return true;944  // Flat rpId without a passkey sub-object means pre-v2.11.0 schema.945  if (flat.rpId !== undefined && flat.passkey === undefined) return true;946  return false;947}948949function decodePayload(plain: string): DecryptedPayload {950  const parsed = JSON.parse(plain) as951    | Array<VaultEntry | LegacyVaultEntry>952    | VaultPayload;953954  const rawEntries = Array.isArray(parsed) ? parsed : parsed.entries ?? [];955  const flatMigrationNeeded = rawEntries.some(rawNeedsMigration);956957  const normalized = rawEntries.map(normalizeEntry);958  const { merged } = mergePasskeyOnlyIntoLogins(normalized);959960  if (Array.isArray(parsed)) {961    return {962      entries: normalized,963      duressConfigured: false,964      migratedFromLegacy: true, // pre-A-2 array shape always needs save965    };966  }967968  return {969    entries: normalized,970    duressConfigured: parsed.duressConfigured === true,971    migratedFromLegacy: flatMigrationNeeded || merged,972  };973}974975/**976 * One-time consolidation pass run alongside the legacy passkey migration.977 *978 * Pre-v2.11.0 the Chrome passkey path always created a fresh `type:"passkey"`979 * entry per registration — so users who tested registration multiple times980 * accumulated several passkey-bearing entries for the same RP, and the981 * migration to the unified shape carried that duplication forward. This982 * pass collapses the duplicates:983 *984 *   1. Group passkey-bearing (and not deleted) entries by `passkey.rpId`.985 *   2. Within each group, the most recently-active credential wins (prefer986 *      lastUsedAt, fall back to passkey.createdAt, fall back to modifiedAt).987 *   3. If a NON-passkey login entry exists for that RP (matched by url or988 *      additionalUrls hostname), attach the winning passkey to it and989 *      soft-delete every passkey-bearing entry in the group.990 *   4. Otherwise, soft-delete every loser in the group, keeping the winner991 *      as a passkey-only entry.992 *993 * Soft delete (deletedAt) rather than splice — the trash flow keeps the994 * record around for retention and the user can restore if the heuristic995 * picked wrong. The `merged` flag goes back to decodePayload so the996 * unlock path persists the consolidated shape immediately.997 */998function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {999  let merged = false;1000  const now = Date.now();10011002  const candidates = entries.filter((e) => !e.deletedAt && e.passkey);1003  const byRpId = new Map<string, VaultEntry[]>();1004  for (const e of candidates) {1005    const rpId = e.passkey!.rpId;1006    const list = byRpId.get(rpId);1007    if (list) list.push(e);1008    else byRpId.set(rpId, [e]);1009  }10101011  for (const [rpId, group] of byRpId) {1012    if (group.length === 0) continue;1013    group.sort((a, b) => {1014      const aT =1015        a.passkey!.lastUsedAt ?? a.passkey!.createdAt ?? a.modifiedAt ?? a.createdAt;1016      const bT =1017        b.passkey!.lastUsedAt ?? b.passkey!.createdAt ?? b.modifiedAt ?? b.createdAt;1018      return bT - aT;1019    });1020    const winner = group[0]!;10211022    // Look for a NON-passkey login entry matching this RP. Use the URL1023    // hostname rather than a substring search so a "login.foo.com" entry1024    // doesn't accidentally absorb a passkey for "foo.com".1025    const loginTarget = entries.find((e) => {1026      if (e.deletedAt || e.passkey || e.type !== "login") return false;1027      if (e.url && extractDomain(e.url) === rpId) return true;1028      for (const extra of e.additionalUrls ?? []) {1029        if (extractDomain(extra) === rpId) return true;1030      }1031      return false;1032    });10331034    if (loginTarget) {1035      loginTarget.passkey = winner.passkey;1036      // A passkey entry may also carry the site's TOTP seed. Preserve it when1037      // the passkey is consolidated onto an existing login instead of1038      // soft-deleting the only record that held the 2FA configuration.1039      if (!loginTarget.totp && winner.totp) {1040        loginTarget.totp = winner.totp;1041        loginTarget.totpAlgorithm = winner.totpAlgorithm;1042        loginTarget.totpDigits = winner.totpDigits;1043        loginTarget.totpPeriod = winner.totpPeriod;1044      }1045      loginTarget.modifiedAt = now;1046      for (const dup of group) {1047        if (!dup.deletedAt) {1048          dup.deletedAt = now;1049          dup.modifiedAt = now;1050        }1051      }1052      merged = true;1053    } else if (group.length > 1) {1054      for (let i = 1; i < group.length; i += 1) {1055        const dup = group[i]!;1056        if (!dup.deletedAt) {1057          dup.deletedAt = now;1058          dup.modifiedAt = now;1059        }1060      }1061      merged = true;1062    }1063  }10641065  return { merged };1066}10671068// Validates that a `StoredVault` record on disk has the field shape we expect1069// before treating an AES-GCM decrypt success as a clean unlock. AES-GCM only1070// authenticates the static VERSION_BYTE AAD, not the `version` field on the1071// outer record — a corrupted `version: 42` slot still decrypts cleanly. This1072// check surfaces that as `corrupted` (M7/COR-007) so the popup can offer a1073// history-restore path instead of falsely reporting "wrong password".1074function hasValidVaultSchema(v: unknown): v is StoredVault {1075  if (typeof v !== "object" || v === null) return false;1076  const r = v as Record<string, unknown>;1077  return (1078    r.version === 1 &&1079    typeof r.salt === "string" &&1080    typeof r.nonce === "string" &&1081    typeof r.ciphertext === "string" &&1082    typeof r.tag === "string"1083  );1084}10851086export type TryDecryptResult =1087  | { status: "ok"; payload: DecryptedPayload }1088  | { status: "wrong_key" }1089  | { status: "corrupted"; reason: string };10901091// Exported solely for `unlockFromCodex` below, which needs to verify a1092// supplied passphrase against a slotA blob *without* committing anything to1093// storage. Keep this internal otherwise — callers crossing the messages.ts1094// boundary should always go through `unlock` / `verifyMainPassword` so the1095// constant-time invariants in Projects.md §3.4 are not bypassed.1096export async function tryDecryptSlot(1097  vault: StoredVault,1098  key: Uint8Array,1099  aadTag?: string,1100): Promise<DecryptedPayload | null> {1101  const res = await tryDecryptSlotResult(vault, key, aadTag);1102  return res.status === "ok" ? res.payload : null;1103}11041105export async function tryDecryptSlotResult(1106  vault: StoredVault,1107  key: Uint8Array,1108  aadTag?: string,1109): Promise<TryDecryptResult> {1110  if (!hasValidVaultSchema(vault)) {1111    return { status: "corrupted", reason: "invalid_slot_schema" };1112  }1113  let plain: string;1114  try {1115    plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);1116  } catch {1117    return { status: "wrong_key" };1118  }1119  try {1120    const parsed = JSON.parse(plain) as unknown;1121    if (typeof parsed !== "object" || parsed === null) {1122      return { status: "corrupted", reason: "invalid_payload_shape" };1123    }1124    if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {1125      return { status: "corrupted", reason: "invalid_payload_shape" };1126    }1127    return { status: "ok", payload: decodePayload(plain) };1128  } catch {1129    return { status: "corrupted", reason: "invalid_payload_json" };1130  }1131}11321133// ---------------------------------------------------------------------------1134// Core operations1135// ---------------------------------------------------------------------------11361137function buildDomainIndexSync(all: VaultEntry[]): void {1138  domainIndex = new Map();11391140  for (const entry of all) {1141    if (entry.deletedAt) continue;1142    if (entry.type === "note" || entry.type === "card") continue;11431144    // An entry can match multiple sites via `additionalUrls`. Index each1145    // hostname so `queryDomain` returns the entry regardless of which alias1146    // the user is currently visiting. Dedupe per-entry so a single entry1147    // never appears twice in one bucket.1148    const domains = new Set<string>();1149    const primary = extractDomain(entry.url ?? "");1150    if (primary) domains.add(primary);1151    for (const extra of entry.additionalUrls ?? []) {1152      const d = extractDomain(extra);1153      if (d) domains.add(d);1154    }1155    if (domains.size === 0) continue;11561157    for (const domain of domains) {1158      const bucket = domainIndex.get(domain) ?? [];1159      bucket.push(entry);1160      domainIndex.set(domain, bucket);1161    }1162  }1163}11641165export async function createVault(password: string): Promise<void> {1166  await ensureMigrated();11671168  const salt = generateSalt();1169  derivedKey = await deriveKey(password, salt);1170  entries = [];1171  vaultMode = "real";1172  duressConfigured = false;1173  buildDomainIndexSync(entries);11741175  // Generate and wrap the root key for recovery word escrow.1176  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =1177    await generateAndWrapRootKey();1178  rootKey = unhex(rawRootKey);11791180  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);1181  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");11821183  // Second wrapping of rootKey under derivedKey so future unlocks can rehydrate1184  // it without recovery words (H2/COR-006).1185  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);11861187  const slotA: StoredVault = {1188    version: 1,1189    salt: hex(salt),1190    nonce,1191    ciphertext,1192    tag,1193    recovery_salt: recoverySalt,1194    recovery_wrapped_root_key: wrappedRootKey,1195    recovery_nonce: wrappedNonce,1196    recovery_tag: wrappedTag,1197    ...pwRoot,1198  };1199  await writeSlot(SLOT_A, slotA);12001201  // Matching-size noise blob for slot B, so a fresh install shows two1202  // similarly-shaped records regardless of whether duress is ever set up.1203  await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));1204  await stampLocalVaultMutation();12051206  touchAutoLock();1207}12081209/**1210 * Creates a local vault from an existing vault root key received through the1211 * SAS-gated adoption protocol. The password is local to this device; it wraps1212 * the adopted root key at rest and does not need to match the source device.1213 */1214export async function createVaultFromRootKey(1215  password: string,1216  rootKeyHex: string,1217): Promise<{ vaultId: string }> {1218  if (typeof password !== "string" || password.length === 0) {1219    throw new Error("ADOPT_INVALID_PASSWORD");1220  }1221  if (typeof rootKeyHex !== "string" || !/^[0-9a-f]{64}$/.test(rootKeyHex)) {1222    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars");1223  }12241225  const rootKeyBytes = unhex(rootKeyHex);1226  if (rootKeyBytes.length !== 32) {1227    rootKeyBytes.fill(0);1228    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");1229  }12301231  let nextDerivedKey: Uint8Array | null = null;1232  let sessionRootKey: Uint8Array | null = null;1233  try {1234    await ensureMigrated();1235    if ((await loadSlot(SLOT_A)) !== null) {1236      throw new Error("ADOPT_VAULT_ALREADY_EXISTS");1237    }12381239    const nextEntries: VaultEntry[] = [];1240    const nextDuressConfigured = false;1241    const vaultId = await computeVaultId(rootKeyBytes);1242    const salt = generateSalt();1243    nextDerivedKey = await deriveKey(password, salt);1244    const recovery = await wrapExistingRootKeyForRecovery(rootKeyBytes);12451246    sessionRootKey = new Uint8Array(rootKeyBytes);1247    const plaintext = encodePayload(nextEntries, nextDuressConfigured, 0);1248    const { nonce, ciphertext, tag } = await encrypt(nextDerivedKey, plaintext, "slot_a_v1");1249    const pwRoot = await wrapRootKeyForDerivedKey(nextDerivedKey, sessionRootKey);1250    const slotA: StoredVault = {1251      version: 1,1252      salt: hex(salt),1253      nonce,1254      ciphertext,1255      tag,1256      recovery_salt: recovery.recoverySalt,1257      recovery_wrapped_root_key: recovery.wrappedRootKey,1258      recovery_nonce: recovery.wrappedNonce,1259      recovery_tag: recovery.wrappedTag,1260      ...pwRoot,1261    };1262    const slotB = generateNoiseBlob(ciphertext.length / 2);1263    await commitCreatedVaultSlots(slotA, slotB);12641265    const previousDerivedKey = derivedKey;1266    const previousRootKey = rootKey;1267    derivedKey = nextDerivedKey;1268    rootKey = sessionRootKey;1269    nextDerivedKey = null;1270    sessionRootKey = null;1271    entries = nextEntries;1272    vaultMode = "real";1273    duressConfigured = nextDuressConfigured;1274    buildDomainIndexSync(entries);1275    if (previousDerivedKey && previousDerivedKey !== derivedKey) zeroKey(previousDerivedKey);1276    if (previousRootKey && previousRootKey !== rootKey) previousRootKey.fill(0);1277    touchAutoLock();12781279    return { vaultId };1280  } finally {1281    rootKeyBytes.fill(0);1282    if (nextDerivedKey) zeroKey(nextDerivedKey);1283    if (sessionRootKey) sessionRootKey.fill(0);1284  }1285}12861287export async function hasVault(): Promise<boolean> {1288  await ensureMigrated();1289  return (await loadSlot(SLOT_A)) !== null;1290}12911292/**1293 * Returns whether the real vault has recorded that a duress passphrase is1294 * configured. Reliable only after a real-mode unlock — before unlock or in1295 * decoy mode, returns false because we cannot read slot A's plaintext.1296 */1297export async function isDuressEnabled(): Promise<boolean> {1298  return vaultMode === "real" && duressConfigured;1299}13001301export async function setupDuress(duressPassword: string): Promise<void> {1302  if (!derivedKey || vaultMode !== "real") {1303    throw new Error("vault must be unlocked in real mode");1304  }1305  await ensureMigrated();13061307  // Encrypt the decoy payload (empty entries) under the duress key. Pad to1308  // at least the current slot A ciphertext size so the two slots look the1309  // same at rest at setup time.1310  const slotA = await loadSlot(SLOT_A);1311  if (!slotA) throw new Error("missing slot A");13121313  const decoySalt = generateSalt();1314  const decoyKey = await deriveKey(duressPassword, decoySalt);1315  try {1316    // Pad the decoy to the fixed duress ceiling. Slot A is re-encrypted to the1317    // same ceiling by the persistSlotA() call below (duressConfigured is now1318    // true), so both slots are exactly DURESS_SLOT_SIZE+tag at rest and their1319    // lengths cannot reveal that duress is configured (audit MEDIUM).1320    const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);1321    const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");1322    await writeSlot(SLOT_B, {1323      version: 1,1324      salt: hex(decoySalt),1325      nonce,1326      ciphertext,1327      tag,1328    });1329  } finally {1330    zeroKey(decoyKey);1331  }13321333  // Re-encrypt slot A with the duressConfigured flag set to true. No external1334  // flag is written — the bit lives inside the encrypted envelope.1335  duressConfigured = true;1336  await persistSlotA();1337}13381339export async function disableDuress(): Promise<void> {1340  if (!derivedKey || vaultMode !== "real") {1341    throw new Error("vault must be unlocked in real mode");1342  }1343  await ensureMigrated();13441345  // Overwrite slot B with fresh noise that matches slot A's size. The slot1346  // remains occupied so its mere existence does not signal that duress was1347  // ever configured.1348  const slotA = await loadSlot(SLOT_A);1349  if (slotA) {1350    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));1351  }13521353  duressConfigured = false;1354  await persistSlotA();1355}13561357// L14/COR-015: this function intentionally checks slot A (real vault) only.1358// A duress-mode user attempting changePassword is rejected earlier by the1359// vaultMode === 'decoy' check at changePassword. The real-vs-decoy1360// distinction here is by design — duress users cannot rotate the real1361// password by guessing it, and the asymmetry in error timing is acceptable1362// because duress mode is opt-in and the user knows their own decoy key.1363export async function verifyMainPassword(password: string): Promise<boolean> {1364  await ensureMigrated();1365  const slotA = await loadSlot(SLOT_A);1366  if (!slotA) return false;1367  const key = await deriveKey(password, unhex(slotA.salt));1368  try {1369    return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;1370  } finally {1371    zeroKey(key);1372  }1373}13741375export async function unlock(password: string): Promise<boolean> {1376  // LV-1: the normal path NFC-normalizes inside deriveKey. If that fails and1377  // the supplied password is not already in NFC form, the vault may have been1378  // sealed (pre-LV-1) with the raw, un-normalized bytes — retry with those.1379  if (await attemptUnlockWithDerive(password, deriveKey)) return true;13801381  const nfc = password.normalize("NFC");1382  if (password === nfc) return false; // ASCII/NFC password — no legacy form to try13831384  if (await attemptUnlockWithDerive(password, deriveKeyRaw)) {1385    // Heal: re-seal the real slot under the NFC-normalized key so every1386    // future unlock takes the normal path. Only the real vault is re-sealed;1387    // a non-NFC duress password keeps working through this fallback.1388    if (vaultMode === "real") {1389      try {1390        const newSalt = generateSalt();1391        const newKey = await deriveKey(password, newSalt);1392        await changePasswordWithNewKey(newSalt, newKey);1393      } catch (healErr) {1394        console.warn("[Peach] LV-1 NFC heal failed:", healErr);1395      }1396    }1397    return true;1398  }1399  return false;1400}14011402async function attemptUnlockWithDerive(1403  password: string,1404  derive: typeof deriveKey,1405): Promise<boolean> {1406  await ensureMigrated();14071408  // Load both slots in parallel. Both always exist post-migration; the1409  // parallel load and the parallel derivation below keep wall-clock time1410  // constant regardless of which slot's passphrase (real or decoy) the1411  // caller supplied, so a timing side channel cannot distinguish the1412  // duress path from the real-unlock path (DUR-002).1413  const [slotA, slotB] = await Promise.all([1414    loadSlot(SLOT_A),1415    loadSlot(SLOT_B),1416  ]);14171418  // Derive both keys in parallel, unconditionally.1419  const [keyA, keyB] = await Promise.all([1420    slotA ? derive(password, unhex(slotA.salt)) : Promise.resolve(null),1421    slotB ? derive(password, unhex(slotB.salt)) : Promise.resolve(null),1422  ]);14231424  // Attempt both decrypts in parallel. The Result variant lets us distinguish1425  // 'wrong_key' from 'corrupted' so callers can offer a history-restore path1426  // when a slot's schema is invalid even though AES-GCM authenticated (M7).1427  const [resultA, resultB] = await Promise.all([1428    keyA && slotA1429      ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")1430      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1431    keyB && slotB1432      ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")1433      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1434  ]);1435  const payloadA = resultA.status === "ok" ? resultA.payload : null;1436  const payloadB = resultB.status === "ok" ? resultB.payload : null;14371438  if (payloadA && keyA) {1439    derivedKey = keyA;1440    void saveSessionKey(keyA, "real");1441    vaultMode = "real";1442    entries = payloadA.entries;1443    duressConfigured = payloadA.duressConfigured;1444    buildDomainIndexSync(entries);1445    await loadSettings();1446    touchAutoLock();1447    if (keyB) zeroKey(keyB);14481449    // slotA is non-null when payloadA is truthy (keyA was derived from slotA).1450    if (slotA) {1451      const needsRecoverySetup =1452        !slotA.recovery_salt || !slotA.recovery_wrapped_root_key;1453      if (!needsRecoverySetup) {1454        rootKey = await deriveRootKeyFromDerivedKey(keyA, slotA);1455      }1456      // Pre-v2.12 vault, or a vault whose pw_root_* fields haven't been written1457      // yet: generate the recovery escrow and seed pw_root_* so subsequent1458      // unlocks can rehydrate rootKey without the user's recovery words.1459      // Best-effort — a failure here must not block unlock.1460      if (needsRecoverySetup || !rootKey) {1461        try {1462          await migrateToRecovery();1463          if (needsRecoverySetup) {1464            // String "1" matches the popup's existing peach_recovery_pending1465            // check; surfaced so the user re-confirms recovery words after a1466            // legacy-vault unlock (H2/COR-006).1467            await chrome.storage.local.set({ peach_recovery_pending: '1' });1468          }1469        } catch (migrationErr) {1470          console.warn('[Peach] recovery migration failed:', migrationErr);1471        }1472      }1473    }14741475    // If the payload had a pre-v2.11.0 shape (legacy passkey type, flat1476    // passkey fields, or pre-A-2 created/updated keys), rewrite it now so1477    // the next save uses the new format and migration doesn't re-run forever.1478    if (payloadA.migratedFromLegacy) {1479      await persistSlotA();1480    }1481    await lockedSyncUnlockHook?.().catch((error) => {1482      console.warn("[Peach sync] locked inbox drain failed:", error);1483    });1484    return true;1485  }14861487  if (payloadB && keyB) {1488    derivedKey = keyB;1489    void saveSessionKey(keyB, "decoy");1490    vaultMode = "decoy";1491    entries = payloadB.entries;1492    duressConfigured = false;1493    buildDomainIndexSync(entries);1494    await loadSettings();1495    touchAutoLock();1496    if (keyA) zeroKey(keyA);1497    return true;1498  }14991500  if (keyA) zeroKey(keyA);1501  if (keyB) zeroKey(keyB);1502  // Surface corruption (good AES tag, broken schema) distinctly from1503  // wrong-password so the popup can offer history-restore (M7/COR-007).1504  if (resultA.status === "corrupted") {1505    lastUnlockFailureReason = resultA.reason;1506  } else if (resultB.status === "corrupted") {1507    lastUnlockFailureReason = resultB.reason;1508  }1509  return false;1510}15111512// ---------------------------------------------------------------------------1513// MV3 service worker session key — survives SW restarts within a browser session1514// ---------------------------------------------------------------------------15151516// chrome.storage.session is cleared on browser close; survives SW restart.1517// Firefox does not implement it (persistent background script, no restart risk).1518const SESSION_KEY_STORAGE = "peach_session_dk";15191520async function saveSessionKey(key: Uint8Array, mode: "real" | "decoy"): Promise<void> {1521  if (!chrome.storage.session) return;1522  await chrome.storage.session.set({ [SESSION_KEY_STORAGE]: { keyHex: hex(key), mode } });1523}15241525async function clearSessionKey(): Promise<void> {1526  if (!chrome.storage.session) return;1527  await chrome.storage.session.remove(SESSION_KEY_STORAGE);1528}15291530/**1531 * On SW restart, re-derive all in-memory vault state from the session key1532 * stored in chrome.storage.session (set at unlock time, cleared by lock();1533 * also cleared on browser close or when restoration fails).1534 * Returns true if the vault was restored, false if no session key was found.1535 * No-ops if the vault is already unlocked.1536 */1537export async function restoreFromSession(): Promise<boolean> {1538  if (derivedKey !== null) return true;1539  if (!chrome.storage.session) return false;1540  const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);1541  const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;1542  if (!entry?.keyHex) return false;15431544  const key = unhex(entry.keyHex);1545  const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;1546  const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";1547  const slot = await loadSlot(slotKey);1548  if (!slot) { await clearSessionKey(); return false; }15491550  const result = await tryDecryptSlotResult(slot, key, aadTag);1551  if (result.status !== "ok") { await clearSessionKey(); return false; }15521553  derivedKey = key;1554  vaultMode = entry.mode;1555  entries = result.payload.entries;1556  duressConfigured = entry.mode === "real" ? result.payload.duressConfigured : false;1557  buildDomainIndexSync(entries);1558  await loadSettings();1559  touchAutoLock();15601561  // The rootKey is what identity/sync derivations use. deriveRootKeyFromDerivedKey1562  // pulls it from the pw_root_* fields on the slot — set on every createVault +1563  // re-set on every password change (H2/COR-006). The previous gate on1564  // recovery_salt + recovery_wrapped_root_key silently left rootKey unset for1565  // any vault that hadn't been through migrateToRecovery, which broke background1566  // sync: the SW re-woke from the alarm, isUnlocked() was true (the session key1567  // restored derivedKey + entries), but getRootKeyHex() returned null and the1568  // runner returned VAULT_LOCKED. The fix is to always try the pw_root path1569  // when the slot has those fields — the recovery fields are independent.1570  if (entry.mode === "real") {1571    try {1572      rootKey = await deriveRootKeyFromDerivedKey(key, slot);1573    } catch {1574      /* non-fatal — sync identity will still skip on the runner's null-rootKey check */1575    }1576  }15771578  await lockedSyncUnlockHook?.().catch((error) => {1579    console.warn("[Peach sync] locked inbox drain failed:", error);1580  });15811582  return true;1583}15841585export function lock(): void {1586  // A user-initiated lock must be durable across MV3 service-worker restarts.1587  // The SW is idle-killed after ~30s of inactivity, and the popup's next open1588  // wakes a cold SW whose restoreFromSession() reads chrome.storage.session.1589  // If the session key survived lock(), that restore would silently re-unlock1590  // the vault ~a minute after the user locked it — a lock that only held1591  // while the SW happened to stay alive. The background-sync convenience the1592  // session key once bought (sync runner re-waking to a restored vault) is1593  // not worth an unlocked vault the user never asked to unlock; when locked,1594  // sync-runner correctly reports VAULT_LOCKED instead.1595  void clearSessionKey();1596  if (derivedKey) {1597    zeroKey(derivedKey);1598    derivedKey = null;1599  }1600  if (rootKey) {1601    rootKey.fill(0);1602    rootKey = null;1603  }16041605  entries = [];1606  domainIndex = new Map();1607  vaultMode = "real";1608  duressConfigured = false;1609  clearAutoLock();1610}16111612export function isUnlocked(): boolean {1613  return derivedKey !== null;1614}16151616// Opens the vault using a pre-derived AES-256 key (skipping Argon2id).1617// Used by Android biometric unlock — the key was derived on the native side.1618// SECURITY: only reachable via Capacitor native bridge; browser messages.ts never routes here.1619export async function unlockWithKey(1620  masterKeyHex: string,1621): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {1622  try {1623    const masterKeyBytes = unhex(masterKeyHex);1624    const stored = await loadSlot(SLOT_A);1625    if (!stored) return { ok: false, error: "invalid_key" };1626    const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");1627    if (!payload) return { ok: false, error: "invalid_key" };16281629    derivedKey = masterKeyBytes;1630    vaultMode = "real";1631    entries = payload.entries;1632    duressConfigured = payload.duressConfigured;1633    buildDomainIndexSync(entries);1634    await loadSettings();1635    touchAutoLock();16361637    // PCH-01-009: the biometric path skips Argon2id but must still rehydrate the1638    // root key, exactly like attemptUnlockWithDerive and restoreFromSession.1639    // Without it, rootKey stays null after a biometric unlock and sync +1640    // GET_RECOVERY_WORDS report the open vault as locked. Guarded and non-fatal:1641    // a missing/legacy escrow must not fail the unlock itself.1642    if (stored.recovery_salt && stored.recovery_wrapped_root_key) {1643      try {1644        rootKey = await deriveRootKeyFromDerivedKey(masterKeyBytes, stored);1645      } catch { /* non-fatal — unlock still succeeds without rootKey */ }1646    }1647    return { ok: true, entries };1648  } catch {1649    return { ok: false, error: "invalid_key" };1650  }1651}16521653// --- Adoption duress-slot helpers (passthrough, no decrypt) ---16541655/**1656 * Adoption SOURCE helper: returns the sealed slot B as a JSON string when1657 * duress is configured and slot B exists, so the inline snapshot can ship it1658 * to the receiver. Returns null otherwise. Never decrypts.1659 */1660export async function exportDuressSlotForAdoption(): Promise<string | null> {1661  if (!(await isDuressEnabled())) return null;1662  await ensureMigrated();1663  const slotB = await loadSlot(SLOT_B);1664  if (!slotB) return null;1665  return JSON.stringify(slotB);1666}16671668/**1669 * Adoption RECEIVER helper: installs a duress slot received from a source1670 * device. Validates the StoredVault shape (same guard as unlockFromCodex)1671 * and writes it to slot B. Throws on invalid shape so the caller can treat1672 * it as a non-fatal snapshot failure. Never decrypts.1673 */1674export async function installAdoptedDuressSlot(json: string): Promise<void> {1675  let parsed: StoredVault;1676  try {1677    const raw = JSON.parse(json) as unknown;1678    if (!hasValidVaultSchema(raw)) {1679      throw new Error("invalid_duress_slot_shape");1680    }1681    parsed = raw;1682  } catch (err) {1683    if (err instanceof SyntaxError) {1684      throw new Error("invalid_duress_slot_shape");1685    }1686    throw err;1687  }1688  await writeSlot(SLOT_B, parsed);1689}16901691/**1692 * Restore the vault from a parsed Peach Codex payload.1693 *1694 * The supplied passphrase is verified against the Codex's slotA *before* any1695 * storage mutation — wrong passphrases return without touching disk. On1696 * success, the current vault state is snapshotted (reason: "restore") so the1697 * user can revert via Settings -> Vault History, then slotA/slotB are written1698 * and `peach_last_modified_at` is set to the Codex's recorded timestamp. A1699 * regular `unlock()` follows so the rest of the SW sees the standard1700 * post-unlock state.1701 *1702 * Intentionally non-Pro-gated — see peach_codex_v2.md "Pro gating". A Codex1703 * printed by a Pro user must always be restorable, even on a free device.1704 *1705 * Timing is not held constant here (in contrast to `unlock`): the Codex flow1706 * is an explicit user action with a known passphrase, not a passive lock1707 * screen, so the duress-vs-real timing side channel does not apply.1708 */1709export async function unlockFromCodex(params: {1710  slotA: string; // JSON string of StoredVault for slot A1711  slotB: string | null; // JSON string of StoredVault for slot B, or null1712  timestamp: number;1713  masterPassphrase: string;1714}): Promise<1715  | { ok: true; entryCount: number }1716  | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" }1717> {1718  let parsedSlotA: StoredVault;1719  let parsedSlotB: StoredVault | null = null;1720  try {1721    const rawA = JSON.parse(params.slotA) as unknown;1722    if (!hasValidVaultSchema(rawA)) {1723      return { ok: false, reason: "invalid_slot_format" };1724    }1725    parsedSlotA = rawA;1726    if (params.slotB !== null) {1727      const rawB = JSON.parse(params.slotB) as unknown;1728      if (!hasValidVaultSchema(rawB)) {1729        return { ok: false, reason: "invalid_slot_format" };1730      }1731      parsedSlotB = rawB;1732    }1733  } catch {1734    return { ok: false, reason: "invalid_slot_format" };1735  }17361737  // Verify the passphrase against the supplied slotA WITHOUT writing anything.1738  // If this fails the on-disk vault is left completely untouched.1739  const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));1740  const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");1741  if (!trialPayload) {1742    zeroKey(trialKey);1743    return { ok: false, reason: "wrong_passphrase" };1744  }1745  // Drop the trial key; `unlock()` below derives its own copy. Holding two1746  // copies of the master key in memory at once would be a needless surface.1747  zeroKey(trialKey);17481749  // Snapshot the about-to-be-overwritten on-disk state so the user can revert1750  // a mistaken Codex restore via the Vault History UI. Non-fatal if it fails.1751  await takeVaultSnapshot("restore");17521753  await writeSlot(SLOT_A, parsedSlotA);1754  if (parsedSlotB) {1755    await writeSlot(SLOT_B, parsedSlotB);1756  } else {1757    // Slot B must always exist with ciphertext length matching slot A1758    // (Projects.md §3.2). Codex prints may omit slot B (duress wasn't1759    // configured); regenerate noise to satisfy the invariant.1760    await writeSlot(1761      SLOT_B,1762      generateNoiseBlob(parsedSlotA.ciphertext.length / 2),1763    );1764  }1765  await chrome.storage.local.set({1766    peach_last_modified_at: String(params.timestamp),1767  });17681769  // Standard unlock path so domain index, settings, auto-lock, and1770  // recovery-key state all populate exactly as a normal unlock would.1771  const ok = await unlock(params.masterPassphrase);1772  if (!ok) {1773    // Should be unreachable — we just verified the passphrase against the1774    // same slotA we wrote. Treat as wrong_passphrase to keep the contract1775    // simple if some race or storage anomaly intrudes.1776    return { ok: false, reason: "wrong_passphrase" };1777  }1778  return { ok: true, entryCount: getEntries().length };1779}17801781// Returns the current in-memory derived key as a hex string.1782// Used by the biometric enable flow in Settings to store the key in Android Keystore.1783export function getDerivedKeyHex(): string {1784  if (!derivedKey) throw new Error("vault_not_unlocked");1785  return hex(derivedKey);1786}17871788/**1789 * Returns the vault's stable root key as hex, or null when locked / not yet1790 * populated. The root key is random per-vault, generated at creation, escrowed1791 * under the recovery words, and re-wrapped (not regenerated) on every password1792 * change — so it is INVARIANT across password rotation, unlike getDerivedKeyHex.1793 *1794 * This is the correct input for sync identity derivation (vault_id, the Noise1795 * NK static key, the Ed25519 manifest signing key, and per-entry envelope1796 * keys): paired devices keep the same identity and can still decrypt each1797 * other's entries after either side rotates its master password (SEV-2-B).1798 *1799 * Returns null rather than throwing so sync callers degrade to VAULT_LOCKED1800 * instead of crashing; rootKey is populated on every real-mode unlock via1801 * deriveRootKeyFromDerivedKey / migrateToRecovery.1802 */1803export function getRootKeyHex(): string | null {1804  return rootKey ? hex(rootKey) : null;1805}18061807export function getEntries(): VaultEntry[] {1808  if (!derivedKey) throw new Error("vault_locked");1809  return entries.filter((entry) => !entry.deletedAt);1810}18111812const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;18131814export function getIdentities(): SavedIdentity[] {1815  if (!derivedKey) throw new Error("vault_locked");1816  const active = entries.filter((e) => !e.deletedAt && e.type === "login");18171818  const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();1819  const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();18201821  for (const entry of active) {1822    const domain = extractDomain(entry.url ?? "") ?? "";1823    const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;18241825    function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {1826      const existing = map.get(v);1827      if (!existing || modifiedAt > existing.lastUsed) {1828        map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });1829      } else {1830        map.set(v, { ...existing, count: existing.count + 1 });1831      }1832    }18331834    const uVal = entry.username?.trim();1835    if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);18361837    // Also count the dedicated email field — entries created via the inline1838    // popup new-entry form store email here rather than in username.1839    const eVal = entry.email?.trim();1840    if (eVal) tally(emailMap, eVal);1841  }18421843  const toIdentity = (type: "email" | "username") =>1844    ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({1845      value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,1846    });18471848  return [1849    ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),1850    ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),1851  ];1852}18531854export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {1855  if (!derivedKey) throw new Error("vault_locked");18561857  const now = Date.now();1858  const added: VaultEntry[] = [];1859  for (const draft of drafts) {1860    try {1861      const sanitized = sanitizeEntryDraft(draft);1862      const nextEntry: VaultEntry = {1863        ...sanitized,1864        id: crypto.randomUUID(),1865        createdAt: now,1866        modifiedAt: monotonicEntryTimestamp(),1867      };1868      entries.push(nextEntry);1869      added.push(nextEntry);1870    } catch {1871      // Skip invalid drafts silently — caller can see diff between input and output length1872    }1873  }18741875  if (added.length > 0) {1876    await persistEntries();1877  }18781879  return added;1880}18811882/**1883 * Restore a set of entries in full fidelity — preserves id, createdAt,1884 * modifiedAt, and every other field unlike `batchAddEntries` which1885 * assigns fresh identity. Used by restore paths where the backup is the1886 * authoritative source of truth. `mode` controls how entries already in1887 * the vault are treated.1888 */1889export async function restoreEntries(1890  incoming: VaultEntry[],1891  mode: "replace" | "merge"1892): Promise<{ added: number; updated: number; skipped: number }> {1893  if (!derivedKey) throw new Error("vault_locked");18941895  // A replace with zero incoming entries is almost certainly a caller bug1896  // (e.g. an import that silently dropped everything). Refuse rather than1897  // wipe the vault.1898  if (mode === "replace" && incoming.length === 0) {1899    throw new Error("refuse to replace with empty entry set");1900  }19011902  let added = 0;1903  let updated = 0;1904  let skipped = 0;19051906  if (mode === "replace") {1907    entries = [];1908    for (const entry of incoming) {1909      const normalized = sanitizeRestoredEntry(entry);1910      if (!normalized) {1911        skipped += 1;1912        continue;1913      }1914      entries.push(normalized);1915      added += 1;1916    }1917  } else {1918    const byId = new Map<string, VaultEntry>();1919    for (const e of entries) byId.set(e.id, e);19201921    for (const entry of incoming) {1922      const normalized = sanitizeRestoredEntry(entry);1923      if (!normalized) {1924        skipped += 1;1925        continue;1926      }1927      const existing = byId.get(normalized.id);1928      if (!existing) {1929        entries.push(normalized);1930        added += 1;1931      } else if (normalized.modifiedAt > existing.modifiedAt) {1932        const idx = entries.findIndex((e) => e.id === existing.id);1933        if (idx !== -1) {1934          entries[idx] = normalized;1935          updated += 1;1936        }1937      } else {1938        skipped += 1;1939      }1940    }1941  }19421943  await persistEntries("import");1944  return { added, updated, skipped };1945}19461947/**1948 * Validate + normalise a VaultEntry coming from a backup, import, or sync1949 * peer. MV-6: this is a strict field WHITELIST — `normalizeEntry` copies1950 * only known VaultEntry fields (unknown/attacker keys are dropped), and1951 * nested `passkey`/`canary` shapes are rebuilt field-by-field, never1952 * spread. Returns null for values the live vault shouldn't accept.1953 */1954function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {1955  if (!entry || typeof entry !== "object") return null;1956  const title = typeof entry.title === "string" ? entry.title.trim() : "";1957  if (!title) return null;1958  const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();1959  const now = Date.now();1960  const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;1961  const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;19621963  // normalizeEntry whitelists every known VaultEntry field and runs the1964  // same legacy-passkey migration as the on-disk read path — pre-v2.11.01965  // backups with flat passkey fields still import correctly because the1966  // legacy flat fields are themselves whitelisted VaultEntry members.1967  const normalized = normalizeEntry({1968    ...entry,1969    id,1970    title,1971    type: entry.type ?? "login",1972    createdAt,1973    modifiedAt,1974  });19751976  if (normalized.passkey) {1977    normalized.passkey = sanitizePasskey(normalized.passkey);1978  }1979  if (normalized.canary) {1980    normalized.canary = sanitizeCanary(normalized.canary);1981  }1982  // PCH-01-016: bound tags on the restore path too, so both import funnels agree.1983  normalized.tags = sanitizeTags(normalized.tags);19841985  // Login entries from backup must carry a password (or be passkey-only,1986  // in which case the passkey sub-object replaces the password requirement).1987  if (1988    normalized.type === "login" &&1989    !normalized.passkey &&1990    typeof normalized.password !== "string"1991  ) {1992    return null;1993  }1994  if (entry.passkey && !normalized.passkey) {1995    // Entry claimed a passkey but the shape didn't validate — refuse the1996    // whole entry rather than silently importing a credential-less husk.1997    return null;1998  }19992000  return normalized;2001}20022003/**2004 * Rebuild a PasskeyData object from untrusted input, field by field.2005 * Returns undefined when required fields are missing/mistyped — a rogue2006 * passkey credential must not activate via import (MV-6 attack scenario).2007 */2008function sanitizePasskey(pk: unknown): PasskeyData | undefined {2009  if (!pk || typeof pk !== "object") return undefined;2010  const r = pk as Record<string, unknown>;2011  if (2012    typeof r.rpId !== "string" || !r.rpId ||2013    typeof r.credentialId !== "string" || !r.credentialId ||2014    typeof r.publicKeyCose !== "string" ||2015    typeof r.userHandle !== "string" ||2016    typeof r.userName !== "string"2017  ) {2018    return undefined;2019  }2020  return {2021    rpId: r.rpId,2022    rpName: typeof r.rpName === "string" ? r.rpName : r.rpId,2023    credentialId: r.credentialId,2024    publicKeyCose: r.publicKeyCose,2025    privateKeyJwk:2026      r.privateKeyJwk && typeof r.privateKeyJwk === "object"2027        ? (r.privateKeyJwk as JsonWebKey)2028        : undefined,2029    userHandle: r.userHandle,2030    userName: r.userName,2031    userDisplayName:2032      typeof r.userDisplayName === "string" ? r.userDisplayName : r.userName,2033    algorithm: r.algorithm === -8 ? -8 : -7,2034    signCount: typeof r.signCount === "number" ? r.signCount : 0,2035    aaguid: typeof r.aaguid === "string" ? r.aaguid : "",2036    backupEligible: r.backupEligible === true,2037    backupState: r.backupState === true,2038    lastUsedAt: typeof r.lastUsedAt === "number" ? r.lastUsedAt : undefined,2039    browser: r.browser === "chrome" || r.browser === "firefox" ? r.browser : undefined,2040    transports: Array.isArray(r.transports)2041      ? r.transports.filter((t): t is string => typeof t === "string")2042      : undefined,2043    createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),2044  };2045}20462047/**2048 * Rebuild a Canary object from untrusted input. The webhook must be a2049 * well-formed HTTPS URL — a poisoned canary.webhookUrl is a standing2050 * exfiltration endpoint that the canary subsystem will POST entry titles2051 * to (MV-6 attack scenario). Invalid → the canary is dropped, not the2052 * entry. FIRE_CANARY_PING re-validates with the full SSRF guard at fire2053 * time (isAllowedCanaryWebhookUrl), so this import-time check is the2054 * outer of two gates.2055 */2056function sanitizeCanary(c: unknown): Canary | undefined {2057  if (!c || typeof c !== "object") return undefined;2058  const r = c as Record<string, unknown>;2059  if (typeof r.webhookUrl !== "string") return undefined;2060  let url: URL;2061  try {2062    url = new URL(r.webhookUrl);2063  } catch {2064    return undefined;2065  }2066  if (url.protocol !== "https:") return undefined;2067  return {2068    webhookUrl: url.toString(),2069    label: typeof r.label === "string" ? r.label : undefined,2070    lastPinged: typeof r.lastPinged === "number" ? r.lastPinged : undefined,2071    pingCount: typeof r.pingCount === "number" ? r.pingCount : undefined,2072  };2073}20742075/**2076 * MV-6 / PCH-01-016: tags from imported / batch-added entries are untrusted.2077 * Keep only non-empty strings, cap each at 256 chars, and cap the count at 2552078 * (the same per-entry ceiling the export codec enforces, peachPayload.ts).2079 * Non-array or all-invalid input collapses to undefined.2080 */2081function sanitizeTags(tags: unknown): string[] | undefined {2082  if (!Array.isArray(tags)) return undefined;2083  const out: string[] = [];2084  for (const t of tags) {2085    if (typeof t !== "string") continue;2086    const trimmed = t.trim();2087    if (!trimmed) continue;2088    out.push(trimmed.slice(0, 256));2089    if (out.length >= 255) break;2090  }2091  return out.length > 0 ? out : undefined;2092}20932094// Soft-deletes every non-deleted entry in one call. The literal string2095// argument is a tripwire against accidental calls — any caller that would2096// wipe the vault has to consciously type "REPLACE_ALL". Do not relax this2097// to a boolean.2098export async function clearVaultEntries(2099  confirmation: "REPLACE_ALL"2100): Promise<void> {2101  if (confirmation !== "REPLACE_ALL") {2102    throw new Error("clearVaultEntries requires explicit confirmation");2103  }2104  if (!derivedKey) throw new Error("vault_locked");2105  for (const entry of entries) {2106    if (!entry.deletedAt) {2107      const stamp = monotonicEntryTimestamp(entry.modifiedAt);2108      entry.deletedAt = stamp;2109      entry.modifiedAt = stamp;2110    }2111  }2112  await persistEntries();2113}21142115export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {2116  if (!derivedKey) throw new Error("vault_locked");21172118  const sanitized = sanitizeEntryDraft(entry);2119  const now = Date.now();2120  const stamp = monotonicEntryTimestamp();2121  const nextEntry: VaultEntry = {2122    ...sanitized,2123    id: crypto.randomUUID(),2124    createdAt: now,2125    modifiedAt: stamp,2126    // Stamp passwordChangedAt at creation so age tracking is accurate from2127    // day one. Non-login entries carry the same stamp harmlessly.2128    passwordChangedAt: sanitized.password ? stamp : undefined,2129  };21302131  // Clone-and-replace so a failed persist rolls back the in-memory state2132  // (COR-008). Without this, a quota-full or storage error leaves the2133  // module-level `entries` ahead of what's actually on disk.2134  const rollback = entries;2135  entries = [...entries, nextEntry];2136  try {2137    await persistEntries();2138  } catch (err) {2139    entries = rollback;2140    throw err;2141  }21422143  // Fire-and-forget breach check (only for login entries if breach monitoring is enabled or not set)2144  if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {2145    checkBreach(nextEntry.password).then(async (count) => {2146      if (count > 0) {2147        const idx = entries.findIndex((e) => e.id === nextEntry.id);2148        if (idx !== -1) {2149          entries[idx] = { ...entries[idx], breach: count, modifiedAt: monotonicEntryTimestamp(entries[idx].modifiedAt) };2150          await persistEntries();2151        }2152      }2153    });2154  }21552156  fireSyncTrigger("vault_change");21572158  return nextEntry;2159}21602161/**2162 * Run the passkey-merge pass on the live in-memory entries and persist if2163 * anything changed. Called immediately after any passkey registration so that2164 * a same-domain TOTP-only entry already in the vault gets consolidated right2165 * away instead of waiting until the next lock/unlock cycle.2166 */2167export async function consolidatePasskeyEntries(): Promise<void> {2168  if (!derivedKey) return;2169  const { merged } = mergePasskeyOnlyIntoLogins(entries);2170  if (merged) {2171    await persistEntries();2172  }2173}21742175export async function updateEntry(2176  id: string,2177  patch: Partial<VaultEntry>2178): Promise<void> {2179  if (!derivedKey) throw new Error("vault_locked");21802181  const idx = entries.findIndex((entry) => entry.id === id);2182  if (idx === -1 || entries[idx].deletedAt) {2183    throw new Error("entry_not_found");2184  }21852186  const current = entries[idx];2187  const sanitizedPatch = sanitizeEntryPatch(patch);2188  // Refresh passwordChangedAt only when the password value actually changes —2189  // a metadata-only update (title, tags, etc.) must not reset the age clock2190  // that drives the Pro health rotation recommendation.2191  const passwordChanged =2192    "password" in patch &&2193    typeof sanitizedPatch.password === "string" &&2194    sanitizedPatch.password !== current.password;2195  const stamp = monotonicEntryTimestamp(current.modifiedAt);2196  // When the password actually changes, push the outgoing one onto the history2197  // (newest first) so the user can reveal/copy/restore it later. We record the2198  // age it carried (passwordChangedAt, falling back to createdAt) rather than2199  // `now`, so the list reflects when each password was last in effect. Only2200  // capture a non-empty prior value — clearing a password leaves no secret to2201  // keep, and we skip an immediate exact duplicate (e.g. restore-then-restore)2202  // to avoid noise.2203  const priorPassword = current.password;2204  const shouldCapture =2205    passwordChanged &&2206    typeof priorPassword === "string" &&2207    priorPassword.length > 0 &&2208    current.passwordHistory?.[0]?.password !== priorPassword;2209  const nextHistory = shouldCapture2210    ? [2211        { password: priorPassword!, changedAt: current.passwordChangedAt ?? current.createdAt },2212        ...(current.passwordHistory ?? []),2213      ].slice(0, PASSWORD_HISTORY_MAX)2214    : current.passwordHistory;2215  entries[idx] = {2216    ...current,2217    ...sanitizedPatch,2218    modifiedAt: stamp,2219    ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),2220  };2221222222232224  // Card entries must retain their card number2225  if (entries[idx].type === "card" && !entries[idx].cardNumber) {2226    entries[idx] = current;2227    throw new Error("card number is required for card entries");2228  }22292230  // Roll the in-memory entry back to its pre-edit state if the disk write2231  // fails (e.g. storage quota). Without this the module-level `entries` array2232  // would hold an edit that never landed on disk, diverging from the vault2233  // until the next unlock silently reverts it (SEV-3-A). Mirrors addEntry.2234  try {2235    await persistEntries();2236  } catch (err) {2237    entries[idx] = current;2238    throw err;2239  }22402241  // Breach check when password changes: clear immediately so old breach doesn't linger,2242  // then async-check the new password and only re-set if it's also found.2243  if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {2244    entries[idx] = { ...entries[idx], breach: undefined };2245    await persistEntries();2246    const password = entries[idx].password;2247    if (password) {2248      checkBreach(password).then(async (count) => {2249        const i = entries.findIndex((e) => e.id === id);2250        if (i !== -1 && count > 0) {2251          entries[i] = { ...entries[i], breach: count, modifiedAt: monotonicEntryTimestamp(entries[i].modifiedAt) };2252          await persistEntries();2253        }2254      });2255    }2256  }22572258  fireSyncTrigger("vault_change");2259}22602261export async function deleteEntry(id: string): Promise<void> {2262  if (!derivedKey) throw new Error("vault_locked");22632264  const entry = entries.find((item) => item.id === id);2265  if (!entry || entry.deletedAt) {2266    throw new Error("entry_not_found");2267  }22682269  // Tombstone timestamp must be strictly greater than the entry's last2270  // modification so the deletion wins LWW against any in-flight edit, even2271  // under clock skew (SEV-2-E).2272  const previousModifiedAt = entry.modifiedAt;2273  const stamp = monotonicEntryTimestamp(entry.modifiedAt);2274  entry.deletedAt = stamp;2275  entry.modifiedAt = stamp;2276  // Roll the tombstone back if the disk write fails, so a quota error doesn't2277  // leave the entry deleted in memory but alive on disk (SEV-3-A).2278  try {2279    await persistEntries();2280  } catch (err) {2281    delete entry.deletedAt;2282    entry.modifiedAt = previousModifiedAt;2283    throw err;2284  }2285  fireSyncTrigger("vault_change");2286}22872288export function getDeletedEntries(): VaultEntry[] {2289  if (!derivedKey) return [];2290  return entries.filter((e) => !!e.deletedAt);2291}22922293/**2294 * Returns the vault's monotonic version — the `peach_last_modified_at` value2295 * stamped on every user-initiated write. Remote (sync) writes do NOT advance2296 * this version so a sync round never cascades into a second outbound sync.2297 */2298export async function getVaultVersion(): Promise<number> {2299  try {2300    const raw = await chrome.storage.local.get("peach_last_modified_at");2301    const v = (raw as Record<string, unknown>).peach_last_modified_at;2302    if (typeof v === "number") return v;2303    if (typeof v === "string" && v !== "") {2304      const n = Number.parseInt(v, 10);2305      return Number.isFinite(n) ? n : 0;2306    }2307    return 0;2308  } catch {2309    return 0;2310  }2311}23122313/**2314 * Internal write variants — bypass `fireSyncTrigger` so the sync layer can2315 * apply entries without cascading into another outbound sync round.2316 *2317 * INVARIANT: callers must not pass entries whose IDs collide with existing2318 * active (non-deleted) entries unless the intent is an explicit overwrite.2319 * These functions do not validate field-level constraints (password required,2320 * card number required, etc.) — they are trust-the-caller paths for sync and2321 * test harness use only.2322 */2323export async function addEntryDirect(entry: VaultEntry): Promise<void> {2324  if (!derivedKey) throw new Error("vault_locked");2325  entries = [...entries, entry];2326  await persistEntries("sync_received");2327}23282329export async function updateEntryDirect(patch: VaultEntry): Promise<void> {2330  if (!derivedKey) throw new Error("vault_locked");2331  const idx = entries.findIndex((e) => e.id === patch.id);2332  if (idx === -1) throw new Error("entry_not_found");2333  entries[idx] = { ...entries[idx], ...patch };2334  await persistEntries("sync_received");2335}23362337export async function deleteEntryDirect(id: string, deletedAt: number): Promise<void> {2338  if (!derivedKey) throw new Error("vault_locked");2339  const idx = entries.findIndex((e) => e.id === id);2340  if (idx === -1) throw new Error("entry_not_found");2341  entries[idx] = { ...entries[idx], deletedAt, modifiedAt: deletedAt };2342  await persistEntries("sync_received");2343}23442345/**2346 * Apply a batch of remote entries + tombstones from a sync peer.2347 * Last-write-wins by `modifiedAt`; a tombstone supersedes a live entry when2348 * `deletedAt > modifiedAt` on the local side. Mutates `entries` directly and2349 * persists with reason `sync_received` — does NOT fire the sync dispatcher, so2350 * applying a sync round cannot cascade into another outbound sync.2351 *2352 * `applied` counts entries that actually changed local state (new add,2353 * overwrite-by-newer, or new tombstone). `received` is the raw payload size2354 * the caller can surface in the sync result UI.2355 */2356export async function applyMergedRemoteEntries(2357  remoteEntries: VaultEntry[],2358  remoteTombstones: Record<string, number>,2359  _context: { deviceName?: string } = {},2360): Promise<{ received: number; applied: number; conflicts: number }> {2361  // DESIGN: last-write-wins is applied PER-ENTRY, not per-field. If two devices2362  // concurrently edit different fields of the same entry, the one with the2363  // newer modifiedAt wins the whole entry and the other device's field edits2364  // are dropped silently. This is the deliberate trade-off for a simple,2365  // conflict-free merge — per-field CRDT merge is out of scope. Guidance for2366  // users: edit a given entry on one device at a time.2367  if (!derivedKey) throw new Error("vault_locked");23682369  const received = remoteEntries.length + Object.keys(remoteTombstones).length;2370  let applied = 0;2371  let conflicts = 0;23722373  const byId = new Map<string, VaultEntry>();2374  for (const e of entries) byId.set(e.id, e);23752376  const mergeNow = Date.now();23772378  for (const remote of remoteEntries) {2379    const sanitized = sanitizeRestoredEntry(remote);2380    if (!sanitized) continue;2381    // HV-1a: a far-future remote modifiedAt must not permanently pin a2382    // malicious value against honest local edits. Clamp BEFORE any2383    // comparison against local timestamps.2384    sanitized.modifiedAt = clampSyncTimestamp(sanitized.modifiedAt, mergeNow);2385    if (typeof sanitized.deletedAt === "number") {2386      sanitized.deletedAt = clampSyncTimestamp(sanitized.deletedAt, mergeNow);2387    }2388    const tombstoneTs = remoteTombstones[sanitized.id];2389    if (tombstoneTs !== undefined && clampSyncTimestamp(tombstoneTs, mergeNow) >= sanitized.modifiedAt) {2390      continue;2391    }2392    const local = byId.get(sanitized.id);2393    if (!local) {2394      entries.push(sanitized);2395      byId.set(sanitized.id, sanitized);2396      applied += 1;2397    } else if (sanitized.modifiedAt > local.modifiedAt) {2398      const idx = entries.findIndex((e) => e.id === local.id);2399      if (idx !== -1) {2400        entries[idx] = sanitized;2401        byId.set(sanitized.id, sanitized);2402        applied += 1;2403        if (!local.deletedAt) conflicts += 1;2404      }2405    }2406  }24072408  for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2409    if (typeof rawDeletedAt !== "number" || !Number.isFinite(rawDeletedAt)) continue;2410    // HV-1a/1c: clamp the tombstone timestamp before every comparison.2411    const deletedAt = clampSyncTimestamp(rawDeletedAt, mergeNow);2412    const local = byId.get(id);2413    if (!local) continue;2414    if (local.deletedAt && local.deletedAt >= deletedAt) continue;2415    if (deletedAt < local.modifiedAt) continue;2416    const idx = entries.findIndex((e) => e.id === id);2417    if (idx !== -1) {2418      entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };2419      applied += 1;2420    }2421  }24222423  if (applied > 0) {2424    await persistEntries("sync_received");2425    buildDomainIndexSync(entries);2426  }2427  return { received, applied, conflicts };2428}24292430export async function restoreEntry(id: string): Promise<void> {2431  if (!derivedKey) throw new Error("vault_locked");2432  const entry = entries.find((e) => e.id === id && e.deletedAt);2433  if (!entry) throw new Error("deleted entry not found");2434  delete entry.deletedAt;2435  entry.modifiedAt = monotonicEntryTimestamp(entry.modifiedAt);2436  await persistEntries();2437  buildDomainIndexSync(entries);2438}24392440export async function purgeEntry(id: string): Promise<void> {2441  if (!derivedKey) throw new Error("vault_locked");2442  const idx = entries.findIndex((e) => e.id === id && e.deletedAt);2443  if (idx === -1) throw new Error("deleted entry not found");2444  entries.splice(idx, 1);2445  await persistEntries();2446}24472448/** Permanently delete entries whose deletedAt is older than retentionMs. 0 = keep forever. */2449export async function purgeExpiredTrash(retentionMs: number): Promise<number> {2450  if (!derivedKey || retentionMs === 0) return 0;2451  const cutoff = Date.now() - retentionMs;2452  const before = entries.length;2453  entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));2454  const purged = before - entries.length;2455  if (purged > 0) await persistEntries();2456  return purged;2457}24582459export function queryDomain(domain: string): VaultEntry[] {2460  return domainIndex.get(domain) ?? [];2461}24622463export function getEntryById(id: string): VaultEntry | undefined {2464  return entries.find((entry) => entry.id === id && !entry.deletedAt);2465}24662467async function persistSlotA(2468  reason: VaultSnapshot["reason"] = "local_save",2469): Promise<StoredVault> {2470  if (!derivedKey) throw new Error("vault_locked");24712472  const slotA = await loadSlot(SLOT_A);2473  if (!slotA) throw new Error("missing slot A");24742475  // Snapshot the about-to-be-overwritten state BEFORE we mutate disk. Failures2476  // are swallowed by takeVaultSnapshot — history must never block a save.2477  await takeVaultSnapshot(reason);24782479  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);2480  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");24812482  // Preserve existing recovery escrow fields.2483  const nextSlotA: StoredVault = {2484    ...slotA,2485    nonce,2486    ciphertext,2487    tag,2488    // recovery_salt and recovery_wrapped_root_key are already set from loadSlot2489  };2490  await writeSlot(SLOT_A, nextSlotA);24912492  // Slot A (the real vault) is now committed. Wrap every later write so a2493  // mid-persist failure (e.g. a storage error after slot A landed) restores the2494  // prior slot A before rethrowing. Without this, a "failed" save that already2495  // wrote slot A leaves disk ahead of the in-memory rollback in addEntry/2496  // updateEntry/deleteEntry — the entry stays silently on disk and resurfaces2497  // as a duplicate on the next unlock (observed under storage-quota pressure).2498  try {2499    // When duress is not configured, keep slot B size-matched with slot A by2500    // regenerating its noise. When duress IS configured, leave slot B alone —2501    // we don't have the decoy key to re-encrypt it. This is a known trade-off.2502    if (!duressConfigured) {2503      await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));2504    }2505    // Only advance the vault version for locally-originated writes. Entries2506    // applied from a sync peer ("sync_received") must NOT bump the counter —2507    // otherwise applying a remote round makes us look newer than the peer and2508    // triggers a redundant outbound sync, defeating the no-op optimisation2509    // and risking a ping-pong between two devices (SEV-2-C).2510    if (reason !== "sync_received") {2511      await stampLocalVaultMutation();2512    }2513  } catch (err) {2514    // Best-effort restore — the prior slot A is smaller-or-equal, so this write2515    // fits even when the failure was a quota overflow.2516    await writeSlot(SLOT_A, slotA).catch(() => {});2517    throw err;2518  }25192520  return nextSlotA;2521}25222523async function persistSlotB(): Promise<void> {2524  if (!derivedKey) throw new Error("vault_locked");25252526  const slotB = await loadSlot(SLOT_B);2527  if (!slotB) throw new Error("missing slot B");25282529  // Decoy plaintext always reports duressConfigured=false — the decoy user2530  // sees a clean slate. persistSlotB only runs in decoy mode, which only2531  // exists once duress is configured, so pad to the fixed duress ceiling to2532  // keep slot B's length equal to slot A's (audit MEDIUM — deniability).2533  const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);2534  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");25352536  await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });2537  // Symmetric with persistSlotA: if the version stamp fails after the decoy2538  // slot committed, restore the prior slot B so a failed decoy-mode save can't2539  // leave disk ahead of the in-memory rollback.2540  try {2541    await stampLocalVaultMutation();2542  } catch (err) {2543    await writeSlot(SLOT_B, slotB).catch(() => {});2544    throw err;2545  }2546}25472548async function persistEntries(2549  reason: VaultSnapshot["reason"] = "local_save",2550): Promise<void> {2551  if (!derivedKey) throw new Error("vault_locked");25522553  if (vaultMode === "decoy") {2554    await persistSlotB();2555  } else {2556    await persistSlotA(reason);2557  }2558  buildDomainIndexSync(entries);2559  await refreshLockedSyncState();2560}25612562function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {2563  if (!Array.isArray(values)) return undefined;2564  const seen = new Set<string>();2565  const cleaned: string[] = [];2566  for (const value of values) {2567    const trimmed = typeof value === "string" ? value.trim() : "";2568    if (!trimmed) continue;2569    const key = trimmed.toLowerCase();2570    if (seen.has(key)) continue;2571    seen.add(key);2572    cleaned.push(trimmed);2573  }2574  return cleaned.length > 0 ? cleaned : undefined;2575}25762577function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {2578  const title = entry.title.trim();2579  // Accept legacy `type:"passkey"` drafts but rewrite to "login" — the new2580  // model is "any entry, optionally with a passkey sub-object." Imports and2581  // any in-flight callers from before v2.11.0 keep working without throwing.2582  let type: VaultEntry["type"] = entry.type ?? "login";2583  if (type === "passkey") type = "login";25842585  if (!title) throw new Error("title is required");25862587  if (entry.passkey) {2588    const p = entry.passkey;2589    if (2590      !p.rpId ||2591      !p.credentialId ||2592      !p.publicKeyCose ||2593      !p.userHandle ||2594      !p.userName ||2595      (p.algorithm !== -7 && p.algorithm !== -8)2596    ) {2597      throw new Error("invalid passkey credential");2598    }2599  }2600  if (type === "card") {2601    if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {2602      throw new Error("cardholder name and card number are required");2603    }2604  }26052606  return {2607    type,2608    title,2609    username: type === "login" ? entry.username?.trim() ?? "" : undefined,2610    email: type === "login" ? entry.email?.trim() || undefined : undefined,2611    password: type === "login" ? entry.password : undefined,2612    url: type === "login" ? entry.url?.trim() ?? "" : undefined,2613    additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,2614    totp: type === "login" ? entry.totp?.trim() || undefined : undefined,2615    // PCH-01-019: preserve non-default TOTP params through batch-add/import so2616    // they are not silently stripped (they fall back to SHA-1/6/30 when absent).2617    totpAlgorithm: type === "login" ? entry.totpAlgorithm : undefined,2618    totpDigits: type === "login" ? entry.totpDigits : undefined,2619    totpPeriod: type === "login" ? entry.totpPeriod : undefined,2620    notes: entry.notes?.trim() || undefined,2621    breach: type === "login" ? entry.breach : undefined,2622    // PCH-01-016: the batch-add path was bypassing the MV-6 canary/tags2623    // whitelist applied on the RESTORE_ENTRIES path. Run both sanitizers here.2624    canary: type === "login" ? sanitizeCanary(entry.canary) : undefined,2625    tags: sanitizeTags(entry.tags),2626    passkey: entry.passkey,2627    cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,2628    cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,2629    expMonth: type === "card" ? entry.expMonth?.trim() : undefined,2630    expYear: type === "card" ? entry.expYear?.trim() : undefined,2631    cvc: type === "card" ? entry.cvc?.trim() : undefined,2632    cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,2633    network: type === "card" ? entry.network : undefined,2634    last4: type === "card" ? entry.last4?.trim() : undefined,2635  };2636}26372638function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {2639  const nextPatch: Partial<VaultEntry> = {};26402641  if ("type" in patch) {2642    nextPatch.type = patch.type;2643  }26442645  if ("title" in patch) {2646    const title = patch.title?.trim() ?? "";2647    if (!title) throw new Error("title is required");2648    nextPatch.title = title;2649  }26502651  if ("url" in patch) {2652    nextPatch.url = patch.url?.trim() ?? "";2653  }26542655  if ("additionalUrls" in patch) {2656    const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];2657    const seen = new Set<string>();2658    const cleaned: string[] = [];2659    for (const value of incoming) {2660      const trimmed = typeof value === "string" ? value.trim() : "";2661      if (!trimmed) continue;2662      const key = trimmed.toLowerCase();2663      if (seen.has(key)) continue;2664      seen.add(key);2665      cleaned.push(trimmed);2666    }2667    nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;2668  }26692670  if ("username" in patch) {2671    nextPatch.username = patch.username?.trim() ?? "";2672  }26732674  if ("email" in patch) {2675    nextPatch.email = patch.email?.trim() || undefined;2676  }26772678  if ("password" in patch) {2679    const password = patch.password ?? "";2680    // Allow clearing a password (e.g. on passkey-only entries)2681    nextPatch.password = password || undefined;2682  }26832684  if ("totp" in patch) {2685    nextPatch.totp = patch.totp?.trim() || undefined;2686  }26872688  if ("notes" in patch) {2689    nextPatch.notes = patch.notes?.trim() || undefined;2690  }26912692  if ("breach" in patch) {2693    nextPatch.breach = patch.breach;2694  }26952696  if ("canary" in patch) {2697    // PCH-02-001: route update patches through the same canary whitelist used2698    // by add/restore/sync. Invalid shapes drop the canary; `undefined` clears it.2699    nextPatch.canary = patch.canary ? sanitizeCanary(patch.canary) : undefined;2700  }27012702  if ("passkey" in patch) {2703    // Passkey sub-object replaces all the legacy flat passkey fields. A2704    // patch with `passkey: undefined` removes the credential from the entry2705    // (used by "remove passkey" without deleting the whole entry).2706    if (patch.passkey === undefined || patch.passkey === null) {2707      nextPatch.passkey = undefined;2708    } else {2709      const sanitized = sanitizePasskey(patch.passkey);2710      if (!sanitized) throw new Error("invalid passkey credential");2711      nextPatch.passkey = sanitized;2712    }2713  }27142715  if ("tags" in patch) {2716    // PCH-02-001: bound tags exactly like both import funnels.2717    nextPatch.tags = sanitizeTags(patch.tags);2718  }27192720  if ("cardholderName" in patch) {2721    nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;2722  }2723  if ("cardNumber" in patch) {2724    const n = patch.cardNumber ?? "";2725    nextPatch.cardNumber = n || undefined;2726  }2727  if ("expMonth" in patch) {2728    nextPatch.expMonth = patch.expMonth?.trim() || undefined;2729  }2730  if ("expYear" in patch) {2731    nextPatch.expYear = patch.expYear?.trim() || undefined;2732  }2733  if ("cvc" in patch) {2734    nextPatch.cvc = patch.cvc?.trim() || undefined;2735  }2736  if ("cardNickname" in patch) {2737    nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;2738  }2739  if ("network" in patch) {2740    nextPatch.network = patch.network;2741  }2742  if ("last4" in patch) {2743    nextPatch.last4 = patch.last4?.trim() || undefined;2744  }27452746  return nextPatch;2747}27482749function normalizeEntry(entry: VaultEntry | LegacyVaultEntry): VaultEntry {2750  const createdAt = "createdAt" in entry ? entry.createdAt : entry.created;2751  const modifiedAt =2752    "modifiedAt" in entry ? entry.modifiedAt : entry.updated;27532754  const base: VaultEntry = {2755    id: entry.id,2756    type: "type" in entry ? entry.type : "login",2757    title: entry.title,2758    username: entry.username,2759    email: "email" in entry ? entry.email : undefined,2760    password: entry.password,2761    url: entry.url,2762    additionalUrls:2763      "additionalUrls" in entry && Array.isArray(entry.additionalUrls)2764        ? entry.additionalUrls2765        : undefined,2766    totp: entry.totp,2767    // PCH-01-019: carry TOTP params through the normalize/restore path too.2768    totpAlgorithm: entry.totpAlgorithm,2769    totpDigits: entry.totpDigits,2770    totpPeriod: entry.totpPeriod,2771    notes: entry.notes,2772    breach: entry.breach,2773    // Preserve the password-age clock across lock/unlock. Without this the2774    // field is dropped on every decode and the advanced-health "aged password"2775    // signal silently resets to createdAt on each unlock (SEV-2-A).2776    passwordChangedAt:2777      "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,2778    // Preserve past-password history across lock/unlock. normalizeEntry is a2779    // field whitelist, so an unlisted field is silently dropped on every decode2780    // (same class as the passwordChangedAt SEV-2-A above).2781    passwordHistory:2782      "passwordHistory" in entry && Array.isArray(entry.passwordHistory)2783        ? entry.passwordHistory2784        : undefined,2785    canary: "canary" in entry ? entry.canary : undefined,2786    passkey: "passkey" in entry ? entry.passkey : undefined,2787    createdAt,2788    modifiedAt,2789    deletedAt: entry.deletedAt,2790    tags: "tags" in entry ? entry.tags : undefined,2791    cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,2792    cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,2793    expMonth: "expMonth" in entry ? entry.expMonth : undefined,2794    expYear: "expYear" in entry ? entry.expYear : undefined,2795    cvc: "cvc" in entry ? entry.cvc : undefined,2796    cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,2797    network: "network" in entry ? entry.network : undefined,2798    last4: "last4" in entry ? entry.last4 : undefined,2799  };28002801  return migrateLegacyPasskey(base, entry);2802}28032804/**2805 * v2.11.0 read migration. Pre-v2.11.0 passkey entries used `type:"passkey"`2806 * with flat top-level fields (rpId, credentialId, etc.). This converts them2807 * to the new shape — `type:"login"` with a `passkey` sub-object — so all2808 * downstream consumers can rely on the new model. The result is rewritten2809 * to disk on next vault save (hasLegacyShape detects the un-migrated case).2810 */2811function migrateLegacyPasskey(2812  base: VaultEntry,2813  raw: VaultEntry | LegacyVaultEntry2814): VaultEntry {2815  if (base.passkey) return base;2816  const flat = raw as Partial<VaultEntry>;2817  const isPasskeyType = base.type === "passkey";2818  const hasFlatPasskeyFields =2819    typeof flat.rpId === "string" &&2820    typeof flat.credentialId === "string" &&2821    typeof flat.publicKeyCose === "string" &&2822    typeof flat.userHandle === "string" &&2823    typeof flat.userName === "string";2824  if (!isPasskeyType && !hasFlatPasskeyFields) return base;2825  if (!hasFlatPasskeyFields) return base;28262827  const algorithm: -7 | -8 = flat.algorithm === -8 ? -8 : -7;2828  base.passkey = {2829    rpId: flat.rpId!,2830    rpName: flat.rpName ?? flat.rpId!,2831    credentialId: flat.credentialId!,2832    publicKeyCose: flat.publicKeyCose!,2833    privateKeyJwk: flat.privateKeyJwk,2834    userHandle: flat.userHandle!,2835    userName: flat.userName!,2836    userDisplayName: flat.userDisplayName ?? flat.userName!,2837    algorithm,2838    signCount: flat.signCount ?? 0,2839    aaguid: flat.aaguid ?? "",2840    backupEligible: flat.backupEligible === true,2841    backupState: flat.backupState === true,2842    lastUsedAt: flat.lastUsedAt,2843    browser: flat.browser,2844    transports: flat.transports,2845    createdAt: base.createdAt,2846  };2847  // Promote to "login" so the unified Entry view renders. Username gets2848  // populated from the passkey's userName so the entry is searchable in the2849  // existing autofill flow without a separate code path.2850  if (isPasskeyType) base.type = "login";2851  if (!base.username) base.username = flat.userName;2852  if (!base.url) base.url = `https://${flat.rpId}`;2853  return base;2854}285528562857// ---------------------------------------------------------------------------2858// Deduplication2859// ---------------------------------------------------------------------------28602861function entryDupeKey(e: VaultEntry): string {2862  if (e.type === "note") return `note|${e.title.toLowerCase()}`;2863  // Passkey-bearing entries dedupe by the credential's RP + user. Two logins2864  // on different sites that happen to share a username are still distinct;2865  // two passkey credentials for the same RP+user are duplicates regardless2866  // of any login fields they may also carry.2867  if (e.passkey) {2868    return `passkey|${e.passkey.rpId.toLowerCase()}|${e.passkey.userName.toLowerCase()}`;2869  }2870  return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;2871}28722873/** Returns the number of duplicate entries (those that would be removed). */2874export function countDuplicates(): number {2875  const best = new Map<string, VaultEntry>();2876  let dupeCount = 0;2877  for (const e of entries.filter((e) => !e.deletedAt)) {2878    const key = entryDupeKey(e);2879    const existing = best.get(key);2880    if (!existing) {2881      best.set(key, e);2882    } else {2883      dupeCount++;2884      // Keep the more recently modified one in the map2885      if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2886        best.set(key, e);2887      }2888    }2889  }2890  return dupeCount;2891}28922893/**2894 * Soft-deletes duplicate entries, keeping the most recently modified copy of2895 * each group. Returns the number of entries moved to trash.2896 */2897export async function deduplicateEntries(): Promise<number> {2898  if (!derivedKey) throw new Error("vault_locked");2899  // Dedup reshapes slot B permanently under the decoy key, which is2900  // forensically distinguishable from a freshly-seeded decoy vault. Refuse.2901  if (vaultMode === "decoy") {2902    throw new Error("deduplicate disabled in decoy mode");2903  }29042905  const best = new Map<string, VaultEntry>();2906  for (const e of entries.filter((en) => !en.deletedAt)) {2907    const key = entryDupeKey(e);2908    const existing = best.get(key);2909    if (!existing) {2910      best.set(key, e);2911    } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2912      best.set(key, e);2913    }2914  }29152916  const keepIds = new Set(Array.from(best.values()).map((e) => e.id));2917  let removed = 0;2918  entries = entries.map((e) => {2919    if (!e.deletedAt && !keepIds.has(e.id)) {2920      removed++;2921      return { ...e, deletedAt: monotonicEntryTimestamp(e.modifiedAt) };2922    }2923    return e;2924  });29252926  if (removed > 0) await persistEntries();2927  return removed;2928}29292930// ---------------------------------------------------------------------------2931// Vault history — snapshot BEFORE every vault write so the saved blob is2932// what is about to be lost, not what was just written. Capped at 5. The2933// stored blobs are AES-256-GCM ciphertext under the master password, so2934// history adds zero security surface.2935// ---------------------------------------------------------------------------29362937const HISTORY_KEY = "peach_vault_history";2938const HISTORY_MAX = 5;29392940// PCH-01-023: coarsen a live-entry count into a low-resolution bucket so the2941// plaintext snapshot field cannot reveal exact vault size or single-entry change2942// deltas. Buckets widen as the vault grows so absolute leakage stays roughly2943// proportional rather than exact.2944function bucketEntryCount(n: number): number {2945  if (n <= 0) return 0;2946  if (n <= 10) return 10;2947  if (n <= 25) return 25;2948  if (n <= 50) return 50;2949  if (n <= 100) return 100;2950  if (n <= 250) return 250;2951  if (n <= 500) return 500;2952  return Math.ceil(n / 500) * 500;2953}29542955/**2956 * Snapshot the CURRENT on-disk vault state into history. Call this BEFORE2957 * overwriting peach_vault_a so the saved blob captures the about-to-be-lost2958 * state. Identical-to-most-recent blobs are skipped to avoid filling history2959 * with no-op writes.2960 */2961export async function takeVaultSnapshot(2962  reason: VaultSnapshot["reason"],2963): Promise<void> {2964  try {2965    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);2966    const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];2967    const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];29682969    // Nothing to snapshot if the real slot doesn't exist yet (fresh install,2970    // pre-createVault). createVault skips snapshots intentionally — there is2971    // no prior state to preserve.2972    if (!slotA) return;29732974    const vault_a = JSON.stringify(slotA);2975    const vault_b = JSON.stringify(slotB ?? slotA);29762977    // Best-effort entry count: only meaningful when the in-memory state is2978    // unlocked AND in real mode. Decoy mode would leak the decoy entry2979    // count; locked mode has no entries to count. Both fall through to null.2980    // PCH-01-023: store a coarse bucket, not the exact count — chrome.storage2981    // .local sits next to the AES-GCM blobs in plaintext, so an exact count would2982    // leak vault size and per-write deltas (the metadata padding hides this).2983    let entryCount: number | null = null;2984    if (derivedKey && vaultMode === "real") {2985      try {2986        entryCount = bucketEntryCount(entries.filter((e) => !e.deletedAt).length);2987      } catch {2988        entryCount = null;2989      }2990    }29912992    const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];2993    const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)2994      ? existingRaw2995      : { snapshots: [] };29962997    // Deduplication: if the most recent snapshot has byte-identical blobs,2998    // skip — saves the same vault N times in a row would otherwise burn the2999    // entire history window with no recovery value.3000    const latest = history.snapshots[0];3001    if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {3002      return;3003    }30043005    const snapshot: VaultSnapshot = {3006      id: crypto.randomUUID(),3007      savedAt: Date.now(),3008      reason,3009      vault_a,3010      vault_b,3011      entryCount,3012    };30133014    history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);3015    await chrome.storage.local.set({ [HISTORY_KEY]: history });3016  } catch (err) {3017    // Non-fatal — history must never block a save. A failed snapshot just3018    // means the user loses one rung of the safety ladder for this write.3019    // M4/QUA-006: log so the failure is visible; if it looks like a quota3020    // problem, notify the popup so the user can prune history themselves.3021    console.warn('[Peach] takeVaultSnapshot failed:', err);3022    if (String(err).includes('QUOTA') || String(err).includes('quota')) {3023      try {3024        await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });3025      } catch {3026        // popup may be closed; surfaced via console.warn above3027      }3028    }3029  }3030}30313032/** Wipe all vault history. Called by Panic / DESTROY_VAULT. */3033export async function clearVaultHistory(): Promise<void> {3034  try {3035    await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });3036  } catch {3037    // Non-fatal — DESTROY_VAULT also runs storage.local.clear().3038  }3039}30403041/** Read all snapshots, newest first, for the Settings vault history view. */3042export async function getVaultHistory(): Promise<VaultSnapshot[]> {3043  const raw = await chrome.storage.local.get(HISTORY_KEY);3044  const history = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];3045  if (!history || !Array.isArray(history.snapshots)) return [];3046  return history.snapshots;3047}30483049/**3050 * Replace the on-disk vault with the chosen snapshot's blobs and lock the3051 * vault. The current state is itself snapshotted with reason 'restore' first3052 * so the restore is reversible. After this returns, the user must unlock3053 * with the password that matches the restored blob.3054 */3055export async function restoreVaultSnapshot(3056  snapshotId: string,3057): Promise<{ ok: true } | { ok: false; error: string }> {3058  const history = await getVaultHistory();3059  const snapshot = history.find((s) => s.id === snapshotId);3060  if (!snapshot) return { ok: false, error: "snapshot_not_found" };30613062  // Snapshot the about-to-be-replaced current state so the restore is3063  // reversible. takeVaultSnapshot is no-op when the most recent entry is3064  // byte-identical, so a restore-of-a-restore stays clean.3065  await takeVaultSnapshot("restore");30663067  let restoredA: StoredVault;3068  let restoredB: StoredVault;3069  try {3070    restoredA = JSON.parse(snapshot.vault_a) as StoredVault;3071    restoredB = JSON.parse(snapshot.vault_b) as StoredVault;3072  } catch {3073    return { ok: false, error: "snapshot_corrupt" };3074  }30753076  await writeSlot(SLOT_A, restoredA);3077  await writeSlot(SLOT_B, restoredB);3078  await stampLocalVaultMutation();30793080  // Lock so the user must prove they can decrypt the restored blob. If they3081  // restored a pre-password-change snapshot they discover it immediately at3082  // the lock screen rather than silently holding an inaccessible vault.3083  lock();30843085  return { ok: true };3086}30873088/**3089 * Rotate the vault's sync identity by generating a FRESH ROOT KEY and3090 * re-wrapping everything under it (MV-8). Because every sync credential —3091 * vault_id, the Noise static keypair, the Ed25519 manifest signing key,3092 * and the per-entry envelope keys — derives from the root key, rotation3093 * makes a lost/stolen device's retained key material useless. All paired3094 * devices must re-pair afterwards.3095 *3096 * CONSEQUENCE THE UI MUST SURFACE: the 12 recovery words also derive from3097 * the root key, so rotation INVALIDATES the old recovery phrase. The flow3098 * sets peach_recovery_pending so the popup re-presents the new words for3099 * confirmation, same as the migrateToRecovery rotate path.3100 */3101export async function rotateSyncIdentity(): Promise<{ ok: boolean; error?: string }> {3102  if (!derivedKey || vaultMode !== "real") {3103    return { ok: false, error: "vault_locked" };3104  }3105  const slotA = await loadSlot(SLOT_A);3106  if (!slotA) return { ok: false, error: "missing_slot_a" };31073108  // 1. Fresh root key + recovery escrow (new words).3109  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =3110    await generateAndWrapRootKey();31113112  // 2. Re-wrap the new root key under the current password-derived key.3113  const newRootKey = unhex(rawRootKey);3114  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, newRootKey);31153116  // 3. Snapshot, then single atomic slot write — both escrow wrappings of3117  //    the new root key land together (same transactional rule as3118  //    changePassword). Entries are untouched: they are sealed under the3119  //    password-derived key, not the root key.3120  await takeVaultSnapshot("local_save");3121  const nextSlotA: StoredVault = {3122    ...slotA,3123    recovery_salt: recoverySalt,3124    recovery_wrapped_root_key: wrappedRootKey,3125    recovery_nonce: wrappedNonce,3126    recovery_tag: wrappedTag,3127    ...pwRoot,3128  };3129  await writeSlot(SLOT_A, nextSlotA);31303131  // 4. Swap in memory only after disk committed.3132  if (rootKey) zeroKey(rootKey);3133  rootKey = newRootKey;31343135  // 5. Old peers' identities derive from the dead root key — drop them all.3136  await clearPairedDevices();31373138  // 6. Force re-presentation of the NEW recovery words on next popup view.3139  await setRecoveryConfirmPending(); // same flag the create-vault flow uses31403141  await stampLocalVaultMutation();3142  return { ok: true };3143}31443145/**3146 * Change the master password. Re-encrypts slot A with a fresh salt + new3147 * derived key. Slot B (duress or noise) is left untouched when duress is3148 * configured — it uses an independent key derived from the duress password —3149 * and regenerated as noise when duress is not configured.3150 */3151export async function changePassword(3152  currentPassword: string,3153  newPassword: string3154): Promise<boolean> {3155  if (!derivedKey || vaultMode !== "real") return false;31563157  // Verify current password before allowing any change3158  const valid = await verifyMainPassword(currentPassword);3159  if (!valid) return false;31603161  const slotA = await loadSlot(SLOT_A);3162  if (!slotA) return false;3163  if (!rootKey) return false;31643165  // Derive fresh key from new password + new random salt3166  const newSalt = generateSalt();3167  const newKey = await deriveKey(newPassword, newSalt);31683169  // Re-encrypt the in-memory entries with the new key3170  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3171  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");31723173  // Pre-wrap root key under the new derived key. Recovery fields wrap rootKey3174  // under recovery words and remain untouched — recovery phrase keeps working3175  // across password changes (H4/COR-002).3176  const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);31773178  const finalSlotA: StoredVault = {3179    ...slotA,3180    salt: hex(newSalt),3181    nonce,3182    ciphertext,3183    tag,3184    ...pwRoot,3185  };31863187  // Snapshot the OLD-key blob before overwriting it. If the user later3188  // restores from this snapshot they will need the OLD password — the3189  // post-restore lock surfaces that immediately.3190  await takeVaultSnapshot("local_save");31913192  // Single atomic write: ciphertext, salt, and pw_root_* fields all land in3193  // one storage transaction. An SW kill before this point leaves the old3194  // slot intact; after this point everything tied to the new password is3195  // already on disk together (M6/COR-004).3196  await writeSlot(SLOT_A, finalSlotA);31973198  // Swap the in-memory key synchronously before any further await. If we3199  // threw between the Slot A write and this swap, the next persistEntries()3200  // would overwrite Slot A with old-key ciphertext, locking the user out.3201  zeroKey(derivedKey);3202  derivedKey = newKey;32033204  // PCH-01-008: the MV3 session escrow still holds the OLD key. Without this,3205  // the next service-worker restore decrypts the new-key Slot A with the stale3206  // key, fails tryDecryptSlotResult, and silently drops the user to a lock3207  // screen. Re-escrow the new key so restore survives a password change.3208  void saveSessionKey(newKey, "real");32093210  // Regenerate noise for slot B when duress is not in use. Runs after the3211  // key swap so a failure here is a disposable noise regeneration, not a3212  // lockout.3213  if (!duressConfigured) {3214    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3215  }3216  await clearPinUnlockStorage();3217  await stampLocalVaultMutation();32183219  return true;3220}