vault.ts

138.3 KB · raw

1/**2 * vault.ts — sole owner of vault state and chrome.storage vault keys.3 *4 * Every read/write of `peach_vault_a`, `peach_vault_b`, and `peach_settings`5 * goes through this module. No other file accesses those keys directly.6 * External callers reach vault operations via `messages.ts` — never by7 * importing from here cross-boundary (popup/content must not). Invariants8 * for the two-slot schema, unlock timing, and key/disk atomicity are in9 * Projects.md §3.2–§3.6.10 */1112import { deriveKey, generateSalt } from "../crypto/argon2";13import { extractDomain } from "../shared/domain";14import { 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  ManualSummonRecord,29  PasskeyData,30  RecoveryResult,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";40import {41  clearPairSecrets,42  dropSessionCache,43  reconcilePairSecrets,44  setSessionAllowed,45} from "./pair-secrets";4647type EntryDraft = Omit<48  VaultEntry,49  "id" | "createdAt" | "modifiedAt" | "deletedAt"50>;5152// Slot-neutral storage keys (v1.4.24+). Both slots always exist; slot B53// either holds the decoy vault (when duress is configured) or random noise54// that looks identical at rest. No external indicator is stored — duress55// configuration is recorded only inside the encrypted payload of slot A.56const SLOT_A = "peach_vault_a";57const SLOT_B = "peach_vault_b";5859// Plaintext is padded to the next multiple of this size before encryption.60// This coarsens ciphertext-length leakage into 1 KiB buckets.61const PAD_BLOCK = 1024;6263// How many past passwords to retain per entry. Generous enough to be useful as64// a recovery aid while bounding the secret material we hold (and the ciphertext65// growth) for an entry whose password is rotated frequently.66const PASSWORD_HISTORY_MAX = 50;6768// When duress is configured, BOTH slots are padded to this fixed ceiling so69// their ciphertext lengths are identical and cannot reveal that a hidden decoy70// vault exists (audit MEDIUM — plausible-deniability leak). 256 KiB comfortably71// holds a very large vault (thousands of entries incl. passkeys). The decoy72// slot can't be re-encrypted on every real-vault save (the real session has no73// decoy key), so a fixed ceiling — rather than size-matching on each write — is74// what keeps the two slots equal. A real vault whose plaintext exceeds this75// would grow past the ceiling and re-expose the bit; that is an extreme,76// documented edge well beyond normal use.77const DURESS_SLOT_SIZE = 262_144;7879let derivedKey: Uint8Array | null = null;80// 32-byte random root key, separate from the derivedKey used for vault encryption.81// The root key is wrapped (encrypted) under the recovery key derived from the82// 12-word phrase. When the user changes their password, only the wrapping changes;83// the root key and recovery words remain stable.84let rootKey: Uint8Array | null = null;85let recoveryInFlight = false;86let recoverySettled: Promise<void> = Promise.resolve();87let vaultRemovalsInFlight = 0;88let vaultWritesInFlight = 0;89let vaultCreatesInFlight = 0;90let vaultReplacementInFlight = false;91let entries: VaultEntry[] = [];92// Tombstones outlive their full entry records so a peer that was offline93// during a purge cannot reintroduce an old ciphertext envelope. This map is94// serialized only inside the encrypted vault payload.95let tombstones = new Map<string, number>();96let domainIndex: Map<string, VaultEntry[]> = new Map();97let vaultMode: "real" | "decoy" = "real";98// Cached post-unlock view of whether the real vault records that duress is99// configured. Only meaningful after a real-mode unlock; for decoy-mode unlock100// this stays false because we never see slot A's plaintext.101let duressConfigured = false;102103// Set to a corruption reason during the last unlock() attempt when both slots104// decrypted but failed schema validation. Consumed and cleared by105// consumeLastUnlockFailureReason() so messages.ts can surface vault_corrupted106// distinctly from wrong-password (M7/COR-007).107//108// NOTE: module-level state — if vault.ts is ever moved to a worker context,109// this must be replaced with a structured return value from unlock() or a110// postMessage channel. The signal is invisible across module-instance111// boundaries.112let lastUnlockFailureReason: string | null = null;113114export function consumeLastUnlockFailureReason(): string | null {115  const r = lastUnlockFailureReason;116  lastUnlockFailureReason = null;117  return r;118}119120// ---------------------------------------------------------------------------121// Settings (persisted inside the encrypted vault store as a sidecar key)122// ---------------------------------------------------------------------------123124export type TextSize = "small" | "medium" | "large";125126export interface VaultSettings {127  accentColor?: AccentColorName;128  theme?: "dark" | "light";129  autoLockMinutes?: number;130  clipboardClearSeconds?: number;131  lockOnClose?: boolean;132  breachMonitoring?: boolean;133  passkeyProviderEnabled?: boolean;134  trashRetentionDays?: number;135  manualSummonDomains?: Record<string, ManualSummonRecord>;136  manualSummonSalt?: string;137  declinedCardFingerprints?: string[];138139  /** Metadata is bounded because it remains outside the encrypted vault blob. */140  metadataVersion?: 1;141  /**142   * Text size scale for body copy and entry titles. Stops at "large" by143   * design — XL clips dense screens (Vault, Health) inside the fixed144   * 330×480 popup surface.145   */146  textSize?: TextSize;147  /**148   * When true, all entrance/exit transitions and ambient animations are149   * collapsed to instant. Honoured alongside the user's OS-level150   * `prefers-reduced-motion`.151   */152  reduceMotion?: boolean;153  /** Require an unlock after a worker restart before locked Sync resumes. */154  lockedSyncRequiresUnlock?: boolean;155  /** Whether this vault has a local PIN unlock wrapper configured. */156  pinEnabled?: boolean;157  /** Whether the lock screen should open on PIN instead of the password. */158  pinPreferred?: boolean;159  /**160   * User overrides for keyboard shortcuts. Keys are ShortcutAction names161   * (see src/shared/shortcuts.ts). Missing actions fall through to162   * DEFAULT_BINDINGS — `getActiveBindings(settings.shortcuts)` is the163   * canonical lookup. Storing only the deltas keeps the vault payload164   * small and lets default updates land for users who never rebind.165   */166  shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;167}168169interface StoredPinWrap {170  version: 1;171  salt: string;172  nonce: string;173  ciphertext: string;174  tag: string;175}176177const PIN_WRAP_STORAGE = "peach_pin_wrap";178const PIN_ATTEMPTS_STORAGE = "peach_pin_attempts";179const PIN_MIN_LENGTH = 4;180const PIN_MAX_LENGTH = 12;181const PIN_MAX_ATTEMPTS = 3;182183let settings: VaultSettings = {};184const CARD_DECLINE_MAX = 256;185/** Hex length of a keyed card-decline digest. Legacy records are 16 hex. */186const CARD_DECLINE_DIGEST_HEX = 32;187188async function metadataDigest(value: string, key: string): Promise<string> {189  const bytes = new TextEncoder().encode(`${key}:${value}`);190  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));191  return Array.from(digest.slice(0, 16)).map((byte) => byte.toString(16).padStart(2, "0")).join("");192}193194let inMemoryPinWrap: StoredPinWrap | null = null;195let inMemoryPinFailedAttempts = 0;196let sessionPinStorageFailed = false;197198export function getSettings(): VaultSettings {199  return settings;200}201202export async function ensureSettingsLoaded(): Promise<VaultSettings> {203  await loadSettings();204  return settings;205}206207export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {208  await loadSettings();209  // LV-7: cheap insurance against prototype pollution if a future caller ever210  // feeds parsed external JSON here (native spread keeps __proto__ an own-211  // property today, but Object.assign-style consumers and JSON revivers have212  // been burned before).213  const safe = Object.fromEntries(214    Object.entries(patch).filter(215      ([k]) => !["__proto__", "constructor", "prototype"].includes(k),216    ),217  ) as Partial<VaultSettings>;218  settings = { ...settings, ...safe };219  await persistSettings();220}221222function isValidPin(pin: string): boolean {223  return new RegExp(`^\\d{${PIN_MIN_LENGTH},${PIN_MAX_LENGTH}}$`).test(pin);224}225226/** Set up a local PIN wrapper after proving the current master password. */227export async function setupPinUnlock(currentPassword: string, pin: string): Promise<boolean> {228  if (!derivedKey || vaultMode !== "real" || !isValidPin(pin)) return false;229  if (!(await verifyMainPassword(currentPassword))) return false;230231  const salt = generateSalt();232  const pinKey = await deriveKey(pin, salt);233  try {234    const wrapped = await encrypt(pinKey, hex(derivedKey), "pin_wrap_v1");235    await savePinWrap({ version: 1, salt: hex(salt), ...wrapped });236    await updateSettings({ pinEnabled: true });237    return true;238  } finally {239    zeroKey(pinKey);240  }241}242243async function clearPinUnlockStorage(): Promise<void> {244  inMemoryPinWrap = null;245  inMemoryPinFailedAttempts = 0;246  sessionPinStorageFailed = false;247  if (chrome.storage.session) {248    await chrome.storage.session.remove([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);249  }250  await updateSettings({ pinEnabled: false });251}252253/** Remove the PIN wrapper after proving the current master password. */254export async function disablePinUnlock(currentPassword: string): Promise<boolean> {255  if (!derivedKey || vaultMode !== "real") return false;256  if (!(await verifyMainPassword(currentPassword))) return false;257  await clearPinUnlockStorage();258  return true;259}260261/** Unlock the real vault from its locally stored PIN-wrapped derived key. */262export async function unlockWithPin(pin: string): Promise<boolean> {263  if (recoveryInFlight || vaultRemovalsInFlight) return false;264  if (!isValidPin(pin)) return false;265  await loadSettings();266  if (!settings.pinEnabled) return false;267268  const { stored, failedAttempts } = await loadPinState();269  if (failedAttempts >= PIN_MAX_ATTEMPTS) return false;270  if (271    !stored ||272    stored.version !== 1 ||273    !stored.salt ||274    !stored.nonce ||275    !stored.ciphertext ||276    !stored.tag277  ) return false;278279  const pinKey = await deriveKey(pin, unhex(stored.salt));280  let unwrappedKey: Uint8Array | null = null;281  try {282    const masterKeyHex = await decrypt(283      pinKey,284      stored.nonce,285      stored.ciphertext,286      stored.tag,287      "pin_wrap_v1",288    );289    if (!/^[0-9a-f]{64}$/.test(masterKeyHex)) return false;290    unwrappedKey = unhex(masterKeyHex);291    const result = await unlockWithKey(masterKeyHex);292    if (!result.ok) return false;293    await resetPinFailedAttempts();294    return true;295  } catch {296    await recordPinFailure(failedAttempts + 1);297    return false;298  } finally {299    zeroKey(pinKey);300    if (unwrappedKey) zeroKey(unwrappedKey);301  }302}303304async function savePinWrap(stored: StoredPinWrap): Promise<void> {305  inMemoryPinWrap = stored;306  inMemoryPinFailedAttempts = 0;307  sessionPinStorageFailed = !chrome.storage.session;308  if (!chrome.storage.session) return;309  try {310    await chrome.storage.session.set({ [PIN_WRAP_STORAGE]: stored, [PIN_ATTEMPTS_STORAGE]: 0 });311    sessionPinStorageFailed = false;312  } catch {313    // Firefox fallback: keep the wrapper only in this background context.314    sessionPinStorageFailed = true;315  }316}317318async function loadPinState(): Promise<{319  stored: StoredPinWrap | undefined;320  failedAttempts: number;321}> {322  if (!chrome.storage.session) {323    return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };324  }325  try {326    const result = await chrome.storage.session.get([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);327    return {328      stored: (result[PIN_WRAP_STORAGE] as StoredPinWrap | undefined) ??329        (sessionPinStorageFailed ? inMemoryPinWrap ?? undefined : undefined),330      failedAttempts: typeof result[PIN_ATTEMPTS_STORAGE] === "number"331        ? result[PIN_ATTEMPTS_STORAGE]332        : 0,333    };334  } catch {335    return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };336  }337}338339async function recordPinFailure(failedAttempts: number): Promise<void> {340  inMemoryPinFailedAttempts = Math.min(failedAttempts, PIN_MAX_ATTEMPTS);341  if (!chrome.storage.session) return;342  try {343    await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: inMemoryPinFailedAttempts });344  } catch { /* in-memory counter remains the fallback */ }345}346347async function resetPinFailedAttempts(): Promise<void> {348  inMemoryPinFailedAttempts = 0;349  if (!chrome.storage.session) return;350  try {351    await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: 0 });352  } catch { /* in-memory counter remains the fallback */ }353}354355export async function getPinUnlockStatus(): Promise<{356  configured: boolean;357  available: boolean;358  attemptsRemaining: number;359}> {360  await loadSettings();361  if (!settings.pinEnabled) {362    return { configured: false, available: false, attemptsRemaining: 0 };363  }364  const { stored, failedAttempts } = await loadPinState();365  const available = Boolean(stored) && failedAttempts < PIN_MAX_ATTEMPTS;366  return {367    configured: true,368    available,369    attemptsRemaining: stored ? Math.max(0, PIN_MAX_ATTEMPTS - failedAttempts) : 0,370  };371}372373async function persistSettings(): Promise<void> {374  try {375    await chrome.storage.local.set({376      peach_settings: {377        ...settings,378        manualSummonDomains: undefined,379        manualSummonSalt: undefined,380        cardFingerprintSalt: undefined,381        declinedCardFingerprints: settings.declinedCardFingerprints ?? [],382        metadataVersion: 1,383      },384    });385  } catch (err) {386    throw mapStorageError(err);387  }388}389390function mapStorageError(err: unknown): Error {391  const message = err instanceof Error ? err.message : String(err);392  if (/QUOTA_BYTES|quota/i.test(message)) {393    return new Error("STORAGE_QUOTA_EXCEEDED");394  }395  return err instanceof Error ? err : new Error(message);396}397398async function loadSettings(): Promise<void> {399  const result = await chrome.storage.local.get("peach_settings");400  settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};401}402403// Fire-and-forget sync trigger after a committed vault write. A failure here404// must never fail the write that caused it.405function fireSyncTrigger(reason: "vault_change"): void {406  void Promise.resolve()407    .then(() => triggerSyncIfReachable({ reason }))408    .catch(() => {409      /* no sync runner registered, or nothing reachable — non-fatal */410    });411}412export function lockedSyncRequiresUnlock(): boolean {413  return settings.lockedSyncRequiresUnlock === true;414}415416let lockedSyncRefreshHook: (() => Promise<void>) | null = null;417let lockedSyncUnlockHook: (() => Promise<void>) | null = null;418let decoySyncTeardownHook: (() => void) | null = null;419export type IdentityHooks = {420  /** Drop the cached identity: the session is no longer a real unlocked one. */421  onSessionEnded: () => Promise<void>;422  /** Re-wrap the identity under the keys now in force, after a vault key swap. */423  onKeysRotated: () => Promise<void>;424  /** Promote a pre-vault identity once a vault exists, given the password that created it. */425  onVaultCreated: (password: string) => Promise<void>;426};427428let identityHooks: IdentityHooks | null = null;429430export function setIdentityHooks(hooks: IdentityHooks): void {431  identityHooks = hooks;432}433434async function notifyIdentitySessionEnded(): Promise<void> {435  await identityHooks?.onSessionEnded().catch((error) => {436    console.warn("[Peach] local identity cache clear failed:", error);437  });438}439440async function notifyIdentityKeysRotated(): Promise<void> {441  await identityHooks?.onKeysRotated().catch((error) => {442    console.warn("[Peach] local identity re-wrap failed:", error);443  });444}445446export type SealedBox = { nonce: string; ciphertext: string; tag: string };447export type IdentityKeyEnvelope = {448  root?: SealedBox;449  local?: SealedBox;450  pending?: SealedBox;451  pendingSalt?: string;452};453454export function setLockedSyncHooks(hooks: {455  refresh: () => Promise<void>;456  afterUnlock: () => Promise<void>;457  onDecoy?: () => void;458}): void {459  lockedSyncRefreshHook = hooks.refresh;460  lockedSyncUnlockHook = hooks.afterUnlock;461  decoySyncTeardownHook = hooks.onDecoy ?? null;462}463464async function refreshLockedSyncState(): Promise<void> {465  if (vaultMode !== "real" || !rootKey || !lockedSyncRefreshHook) return;466  await lockedSyncRefreshHook().catch((error) => {467    console.warn("[Peach sync] locked spool refresh failed:", error);468  });469}470471// ---------------------------------------------------------------------------472// HIBP breach check (k-anonymity model)473// ---------------------------------------------------------------------------474475export async function checkBreach(password: string): Promise<number> {476  // HIBP k-anonymity API is keyed on SHA-1 prefixes — this is dictated by477  // the public API, not a security choice. Do not migrate to SHA-256 here.478  const encoder = new TextEncoder();479  const hashBuffer = await crypto.subtle.digest("SHA-1", encoder.encode(password));480  const hashHex = Array.from(new Uint8Array(hashBuffer))481    .map((b) => b.toString(16).padStart(2, "0"))482    .join("")483    .toUpperCase();484485  const prefix = hashHex.slice(0, 5);486  const suffix = hashHex.slice(5);487488  try {489    // PCH-02-007: request HIBP response padding so response length does not490    // reveal how many suffixes a queried prefix returned.491    const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`, {492      headers: { "Add-Padding": "true" },493    });494    if (!res.ok) return 0;495    const text = await res.text();496    const match = text.split("\r\n").find((l) => l.startsWith(suffix));497    return match ? parseInt(match.split(":")[1], 10) : 0;498  } catch {499    return 0; // Network unavailable — don't block500  }501}502503export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {504  // Unreachable from the message layer, which gates on isUnlocked first.505  const key = await cardDeclineKey();506  if (!key) return;507  const fingerprint = await cardFingerprint(last4, expMonth, expYear);508  await loadSettings();509  settings = {510    ...settings,511    declinedCardFingerprints: [512      // Legacy records predate the keyed digest and are silently dropped here:513      // they are 16 hex characters rather than 32, and are no longer accepted.514      ...(settings.declinedCardFingerprints ?? []).filter(515        (stored) => stored.length === CARD_DECLINE_DIGEST_HEX,516      ),517      await metadataDigest(fingerprint, key),518    ].slice(-CARD_DECLINE_MAX),519  };520  await persistSettings();521}522523export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {524  await loadSettings();525  const key = await cardDeclineKey();526  if (!key) return false;527  const fingerprint = await cardFingerprint(last4, expMonth, expYear);528  const candidate = await metadataDigest(fingerprint, key);529  return (settings.declinedCardFingerprints ?? []).some(530    (stored) => stored.length === CARD_DECLINE_DIGEST_HEX && stored === candidate,531  );532}533534/**535 * Keying material for the declined-card digest, derived from the vault root536 * key so it is available only while unlocked and never written to storage.537 *538 * PB-26-108: the previous scheme stored a random salt beside the records. A539 * salt defeats precomputed tables, not an attacker holding the file — the540 * candidate space here is ~10^4 last-four values x 12 months x a few years, so541 * a stored salt left the card's last four and expiry recoverable offline in542 * seconds. `peach_settings` is unencrypted and directly readable by a content543 * script on Firefox, so the key has to live outside storage entirely.544 */545async function cardDeclineKey(): Promise<string | null> {546  const root = getRootKeyHex();547  if (!root) return null;548  const digest = new Uint8Array(549    await crypto.subtle.digest(550      "SHA-256",551      new TextEncoder().encode(`peach-card-decline-v1:${root}`),552    ),553  );554  return hex(digest);555}556557async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {558  const encoder = new TextEncoder();559  const buf = await crypto.subtle.digest("SHA-256", encoder.encode(`${last4}|${expMonth}|${expYear}`));560  return Array.from(new Uint8Array(buf).slice(0, 8))561    .map((b) => b.toString(16).padStart(2, "0"))562    .join("");563}564565function hex(buf: Uint8Array): string {566  return Array.from(buf)567    .map((b) => b.toString(16).padStart(2, "0"))568    .join("");569}570571function unhex(s: string): Uint8Array {572  const out = new Uint8Array(s.length / 2);573  for (let i = 0; i < s.length; i += 2) {574    out[i / 2] = parseInt(s.slice(i, i + 2), 16);575  }576  return out;577}578579// ---------------------------------------------------------------------------580// Root key generation and recovery word wrapping581// ---------------------------------------------------------------------------582583/**584 * Generate a random 32-byte root key and wrap it (AES-256-GCM) under a key585 * derived from the recovery word material via HKDF-SHA256. The wrapped blob586 * fields are stored in slot A alongside the password-wrapped ciphertext. The587 * root key itself is kept in memory for the session so getRecoveryWords() can588 * encode it without re-deriving.589 *590 * SECURITY MODEL (PCH-01-005): the recovery KEK is derived from the 12-word591 * material, which encodes only rootKey[0..16] (recovery-words.ts). The KEK is thus592 * derived from a PREFIX of the very plaintext it wraps, and effective recovery593 * security is 128-bit (standard for a 12-word phrase), NOT 256-bit. This is safe —594 * unwrapping requires the words, and the GCM ciphertext leaks nothing without them —595 * but it is intentional, not an oversight. A future escrow version wanting 256-bit596 * recovery must derive the words from INDEPENDENT entropy, not from the root key.597 */598async function generateAndWrapRootKey(): Promise<{599  rawRootKey: string; // hex of the plaintext root key — caller stores in rootKey600  recoverySalt: string;601  wrappedRootKey: string;602  wrappedNonce: string;603  wrappedTag: string;604}> {605  const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));606607  // Derive the recovery key from the BIP39 words encoding of the root key.608  const words = await rootKeyToWords(rootKeyBytes);609  const wordMaterial = await wordsToRootKeyMaterial(words);610  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));611  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);612613  // Wrap the root key with the recovery key using AES-256-GCM directly.614  // We hex-encode rootKeyBytes so the plaintext is always valid UTF-8.615  const nonce = crypto.getRandomValues(new Uint8Array(12));616  const encoded = new TextEncoder().encode(hex(rootKeyBytes));617  const raw = await crypto.subtle.encrypt(618    {619      name: "AES-GCM",620      iv: nonce,621      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,622      tagLength: 128,623    },624    recoveryKey,625    encoded626  );627  // WebCrypto returns ciphertext || auth tag concatenated; split them.628  const rawU8 = new Uint8Array(raw);629  const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));630  const tag = hex(rawU8.slice(rawU8.length - 16));631632  return {633    rawRootKey: hex(rootKeyBytes),634    recoverySalt: hex(recoverySalt),635    wrappedRootKey: ciphertext,636    wrappedNonce: hex(nonce),637    wrappedTag: tag,638  };639}640641async function wrapExistingRootKeyForRecovery(rootKeyBytes: Uint8Array): Promise<{642  recoverySalt: string;643  wrappedRootKey: string;644  wrappedNonce: string;645  wrappedTag: string;646}> {647  if (rootKeyBytes.length !== 32) {648    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");649  }650651  const words = await rootKeyToWords(rootKeyBytes);652  const wordMaterial = await wordsToRootKeyMaterial(words);653  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));654  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);655  const nonce = crypto.getRandomValues(new Uint8Array(12));656  const encoded = new TextEncoder().encode(hex(rootKeyBytes));657  const raw = await crypto.subtle.encrypt(658    {659      name: "AES-GCM",660      iv: nonce,661      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,662      tagLength: 128,663    },664    recoveryKey,665    encoded,666  );667  const rawU8 = new Uint8Array(raw);668  return {669    recoverySalt: hex(recoverySalt),670    wrappedRootKey: hex(rawU8.slice(0, rawU8.length - 16)),671    wrappedNonce: hex(nonce),672    wrappedTag: hex(rawU8.slice(rawU8.length - 16)),673  };674}675676/**677 * Unwrap the root key using recovery words. Called during recovery flow when678 * the user provides their 12-word phrase and a new password.679 */680async function unwrapRootKeyForRecovery(681  wrappedRootKey: string,682  wrappedNonce: string,683  wrappedTag: string,684  recoverySaltHex: string,685  words: string[]686): Promise<Uint8Array> {687  const wordMaterial = await wordsToRootKeyMaterial(words);688  const recoverySalt = unhex(recoverySaltHex);689  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);690691  // The root key bytes were hex-encoded before692  // encryption so the ciphertext is valid UTF-8. We inline the AES-GCM decrypt693  // here to avoid passing a CryptoKey to the string-based encrypt/decrypt helpers.694  // Each component is stored separately in the vault slot; decode them individually695  // so the nonce is always exactly the 12 bytes from wrappedNonce.696  const nonceRaw = unhex(wrappedNonce);697  const ciphertextRaw = unhex(wrappedRootKey);698  const tagRaw = unhex(wrappedTag);699  // Combine ciphertext and tag for AES-GCM (expects ciphertext||tag).700  // Use explicit ArrayBuffer allocations to satisfy TS BufferSource constraints.701  const nonceU8 = nonceRaw as unknown as Uint8Array<ArrayBuffer>;702  const combined = new Uint8Array(ciphertextRaw.length + tagRaw.length);703  combined.set(ciphertextRaw, 0);704  combined.set(tagRaw, ciphertextRaw.length);705  const raw = await crypto.subtle.decrypt(706    { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },707    recoveryKey,708    combined709  );710  const decryptedHex = new TextDecoder().decode(raw);711  const recovered = unhex(decryptedHex);712  if (recovered.length !== 32) { zeroKey(recovered); throw new Error("invalid_recovery_words"); }713  return recovered;714}715716/// Recover a locked real vault without publishing keys before its stored payload authenticates.717export async function recoverWithWords(words: string[], newPassword: string): Promise<RecoveryResult> {718  if (recoveryInFlight || derivedKey) throw new Error("recovery_requires_lock");719  if (vaultWritesInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");720  recoveryInFlight = true;721  let settle!: () => void;722  recoverySettled = new Promise<void>((resolve) => { settle = resolve; });723  const epoch = ++vaultEpoch;724  const check = () => {725    if (epoch !== vaultEpoch || derivedKey) throw new Error("vault_locked");726  };727  let recoveredRoot: Uint8Array | null = null;728  let oldKey: Uint8Array | null = null;729  let newKey: Uint8Array | null = null;730  let committed = false;731  try {732    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);733    check();734    const slot = raw[SLOT_A] as StoredVault | undefined;735    if (!slot) throw new Error("no_vault");736    if (!slot.recovery_salt || !slot.recovery_wrapped_root_key) throw new Error("recovery_not_setup");737    try {738      recoveredRoot = await unwrapRootKeyForRecovery(slot.recovery_wrapped_root_key,739        slot.recovery_nonce ?? "", slot.recovery_tag ?? "", slot.recovery_salt, words);740    } catch {741      throw new Error("invalid_recovery_words");742    }743    check();744    if (!slot.recovery_vault_key) throw new Error("recovery_requires_password_unlock");745    oldKey = await openSealedKey(recoveredRoot, slot.recovery_vault_key, "recovery_vault_key_v1");746    check();747    if (!oldKey) throw new Error("recovery_data_unavailable");748    const result = await tryDecryptSlotResult(slot, oldKey, "slot_a_v1");749    check();750    if (result.status !== "ok") throw new Error("recovery_data_unavailable");751    const payload = result.payload;752    await loadSettings();753    check();754    const salt = generateSalt();755    newKey = await deriveKey(newPassword, salt);756    check();757    // Preserve the authenticated plaintext, including fields unknown to this build.758    const plaintext = await decrypt(oldKey, slot.nonce, slot.ciphertext, slot.tag, "slot_a_v1");759    const encrypted = await encrypt(newKey, plaintext, "slot_a_v1");760    const pwRoot = await wrapRootKeyForDerivedKey(newKey, recoveredRoot);761    const recoveryVaultKey = await encrypt(recoveredRoot, hex(newKey), "recovery_vault_key_v1");762    check();763    const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);764    check();765    if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");766    const history = raw[HISTORY_KEY] as VaultHistory | undefined;767    const snapshot: VaultSnapshot = {768      id: crypto.randomUUID(), savedAt: Date.now(), reason: "local_save",769      vault_a: JSON.stringify(slot), vault_b: JSON.stringify(raw[SLOT_B] ?? slot), entryCount: null,770    };771    const previousStamp = Number(raw.peach_last_modified_at);772    const nextSlot: StoredVault = { ...slot, ...encrypted, ...pwRoot,773      salt: hex(salt), recovery_vault_key: recoveryVaultKey };774    // One storage transaction keeps the rollback snapshot and all new-key fields together.775    await chrome.storage.local.set({776      [SLOT_A]: nextSlot,777      [HISTORY_KEY]: { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) },778      peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previousStamp) ? previousStamp + 1 : 0)),779    });780    committed = true;781    check();782    derivedKey = newKey;783    rootKey = recoveredRoot;784    newKey = null;785    recoveredRoot = null;786    entries = payload.entries;787    tombstones = payload.tombstones;788    duressConfigured = payload.duressConfigured;789    vaultMode = "real";790    buildDomainIndexSync(entries);791    await saveSessionKey(derivedKey, "real", epoch);792    if (epoch !== vaultEpoch) throw new Error("vault_locked");793    await identityHooks?.onKeysRotated();794    if (epoch !== vaultEpoch) throw new Error("vault_locked");795    await reconcilePairSecrets(rootKey);796    if (epoch !== vaultEpoch) throw new Error("vault_locked");797    await clearPinUnlockStorage();798    if (epoch !== vaultEpoch) throw new Error("vault_locked");799    touchAutoLock();800    return { committed: true, unlocked: true };801  } catch (error) {802    if (committed) {803      console.warn("[Peach] recovery password saved; unlock required:", error);804      if (derivedKey && epoch === vaultEpoch) {805        try { await lock(); }806        catch (lockError) { console.warn("[Peach] recovery session cleanup failed:", lockError); }807      }808      return { committed: true, unlocked: false };809    }810    if (derivedKey && epoch === vaultEpoch) await lock();811    throw error;812  } finally {813    if (oldKey) zeroKey(oldKey);814    if (newKey) zeroKey(newKey);815    if (recoveredRoot) zeroKey(recoveredRoot);816    recoveryInFlight = false;817    settle();818  }819}820821/// Cancel recovery and finish its issued storage write before removing vault data.822export async function withVaultRemoval<T>(remove: () => Promise<T>): Promise<T> {823  vaultRemovalsInFlight++;824  try {825    await lock();826    await recoverySettled;827    return await remove();828  } finally {829    vaultRemovalsInFlight--;830  }831}832833/**834 * Recover the session root key by AES-GCM-decrypting the pw_root_* fields835 * (a second wrapping of the root key under the password-derived key). This836 * is what makes GET_RECOVERY_WORDS work across lock/unlock cycles without837 * the user re-entering their recovery phrase: the same root key bytes —838 * and therefore the same 12 words — survive every unlock.839 *840 * Returns null when the escrow is absent or decryption fails.841 */842async function deriveRootKeyFromDerivedKey(843  derivedKeyBytes: Uint8Array,844  slotA: StoredVault,845): Promise<Uint8Array | null> {846  if (!slotA.pw_root_ciphertext || !slotA.pw_root_nonce || !slotA.pw_root_tag) {847    return null;848  }849  try {850    const rootHex = await decrypt(851      derivedKeyBytes,852      slotA.pw_root_nonce,853      slotA.pw_root_ciphertext,854      slotA.pw_root_tag,855      "pw_root_v1",856    );857    return unhex(rootHex);858  } catch {859    return null;860  }861}862863export async function sealIdentityKeyUnderVault(ik: Uint8Array): Promise<IdentityKeyEnvelope> {864  if (vaultMode !== "real" || !rootKey || !derivedKey) throw new Error("vault_locked");865  // The root wrap survives password change and recovery-words re-key; the866  // local wrap is available during normal unlock. Pending is only pre-vault.867  const [root, local] = await Promise.all([868    encrypt(rootKey, hex(ik), "peach-local-identity-ik-root-v1"),869    encrypt(derivedKey, hex(ik), "peach-local-identity-ik-local-v1"),870  ]);871  return { root, local };872}873874export async function sealIdentityKeyPreVault(875  password: string,876  ik: Uint8Array,877): Promise<IdentityKeyEnvelope> {878  const salt = generateSalt();879  const key = await deriveKey(password, salt);880  try {881    const pending = await encrypt(key, hex(ik), "peach-local-identity-ik-pending-v1");882    return { pending, pendingSalt: hex(salt) };883  } finally {884    zeroKey(key);885  }886}887888/**889 * Open the identity key with any wrapping key that is currently available:890 * the live vault-unlock key, then the vault root key, then the pre-vault891 * password. Each attempt is awaited only after the previous one fails, so a892 * successful early unwrap never leaves a later decrypt rejection unobserved,893 * and the pre-vault Argon2id is not paid when a vault key already opens the894 * envelope.895 */896export async function openIdentityKey(897  env: IdentityKeyEnvelope,898  password?: string,899): Promise<Uint8Array | null> {900  if (env.local && derivedKey) {901    const ik = await openSealedKey(derivedKey, env.local, "peach-local-identity-ik-local-v1");902    if (ik) return ik;903  }904  if (env.root && rootKey) {905    const ik = await openSealedKey(rootKey, env.root, "peach-local-identity-ik-root-v1");906    if (ik) return ik;907  }908  if (!env.pending || !env.pendingSalt || password === undefined) return null;909  let key: Uint8Array;910  try {911    const salt = unhex(env.pendingSalt);912    key = await deriveKey(password, salt);913    salt.fill(0);914  } catch {915    return null;916  }917  try {918    return await openSealedKey(key, env.pending, "peach-local-identity-ik-pending-v1");919  } finally {920    zeroKey(key);921  }922}923924/** Decrypt a sealed 32-byte key; null for a wrong key, a bad shape, or corrupt bytes. */925async function openSealedKey(926  key: Uint8Array,927  box: SealedBox,928  info: string,929): Promise<Uint8Array | null> {930  try {931    const value = unhex(await decrypt(key, box.nonce, box.ciphertext, box.tag, info));932    if (value.length === 32) return value;933    value.fill(0);934    return null;935  } catch {936    return null;937  }938}939940// AES-GCM-wrap rootKey under derivedKey for the pw_root_* fields. Returns the941// hex-encoded ciphertext/nonce/tag triple ready to embed in StoredVault.942async function wrapRootKeyForDerivedKey(943  derivedKeyBytes: Uint8Array,944  rootKeyBytes: Uint8Array,945): Promise<{ pw_root_ciphertext: string; pw_root_nonce: string; pw_root_tag: string }> {946  const { nonce, ciphertext, tag } = await encrypt(derivedKeyBytes, hex(rootKeyBytes), "pw_root_v1");947  return {948    pw_root_ciphertext: ciphertext,949    pw_root_nonce: nonce,950    pw_root_tag: tag,951  };952}953954/** Returns the 12 recovery words for the current session's root key. */955export async function getRecoveryWords(): Promise<string[]> {956  if (!rootKey) {957    throw new Error("recovery not set up");958  }959  return rootKeyToWords(rootKey);960}961962async function loadSlot(key: string): Promise<StoredVault | null> {963  const result = await chrome.storage.local.get(key);964  return (result as Record<string, StoredVault | undefined>)[key] ?? null;965}966967async function writeSlot(key: string, vault: StoredVault): Promise<void> {968  if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");969  vaultWritesInFlight++;970  try {971    await chrome.storage.local.set({ [key]: vault });972  } catch (err) {973    throw mapStorageError(err);974  } finally {975    vaultWritesInFlight--;976  }977}978979/**980 * Roll back a vault that was created by [createVaultFromRootKey] but981 * couldn't be paired (e.g. the subsequent license activation, identity982 * derivation, or paired-device upsert failed). Without this, a failed983 * receiver session leaves behind an empty vault — the user has to984 * re-pair to get a working setup, but the empty vault sits in the way.985 *986 * The call is idempotent: removing keys that aren't there is a no-op.987 */988export async function rollbackAdoptedVault(): Promise<void> {989  await withVaultRemoval(async () => {990    try {991      await chrome.storage.local.remove([992        SLOT_A,993        SLOT_B,994        "peach_last_modified_at",995      ]);996    } catch (err) {997      throw mapStorageError(err);998    }999  });1000}10011002async function commitCreatedVaultSlots(slotA: StoredVault, slotB: StoredVault): Promise<void> {1003  if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1004  vaultWritesInFlight++;1005  try {1006    const raw = await chrome.storage.local.get("peach_last_modified_at");1007    const previous = Number(1008      (raw as Record<string, unknown>).peach_last_modified_at,1009    );1010    const next = Math.max(1011      Date.now(),1012      Number.isFinite(previous) ? previous + 1 : 0,1013    );1014    try {1015      if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1016      await chrome.storage.local.set({1017        [SLOT_A]: slotA,1018        [SLOT_B]: slotB,1019        peach_last_modified_at: String(next),1020      });1021    } catch (err) {1022      throw mapStorageError(err);1023    }1024  } finally {1025    vaultWritesInFlight--;1026  }1027}10281029// Monotonic clock for per-entry modifiedAt / deletedAt timestamps. Guards the1030// sync layer's last-write-wins merge against wall-clock regressions (NTP step,1031// manual clock change, DST glitch): a backwards Date.now() must never produce1032// an entry timestamp that's <= the entry's existing modifiedAt, or a genuine1033// local edit would lose to a stale remote copy. The returned value is always1034// strictly greater than both the entry's current modifiedAt and the previous1035// call's result (SEV-2-E).1036let lastEntryTimestamp = 0;1037function monotonicEntryTimestamp(currentModifiedAt?: number): number {1038  const base = Math.max(1039    Date.now(),1040    (currentModifiedAt ?? 0) + 1,1041    lastEntryTimestamp + 1,1042  );1043  lastEntryTimestamp = base;1044  return base;1045}10461047async function stampLocalVaultMutation(): Promise<void> {1048  const raw = await chrome.storage.local.get("peach_last_modified_at");1049  const previous = Number(1050    (raw as Record<string, unknown>).peach_last_modified_at,1051  );1052  const next = Math.max(1053    Date.now(),1054    Number.isFinite(previous) ? previous + 1 : 0,1055  );1056  await chrome.storage.local.set({1057    peach_last_modified_at: String(next),1058  });1059}10601061// ---------------------------------------------------------------------------1062// Padding + noise helpers1063// ---------------------------------------------------------------------------10641065/**1066 * Pads the plaintext string with trailing spaces so that the encoded byte1067 * length is a multiple of PAD_BLOCK. JSON.parse tolerates trailing1068 * whitespace after a complete document, so the padding is transparent on1069 * decode. Ciphertext length equals plaintext length plus a 16-byte tag.1070 */1071function padPlaintext(json: string, minBytes = 0): string {1072  const encoded = new TextEncoder().encode(json);1073  const bucket = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);1074  // minBytes lets the duress path force a fixed ceiling so both slots match.1075  const target = Math.max(bucket, minBytes);1076  const padLen = target - encoded.length;1077  return json + " ".repeat(padLen);1078}10791080/**1081 * Produces a StoredVault-shaped record filled with CSPRNG bytes. The1082 * ciphertext length matches the given byte count. Because GCM ciphertext is1083 * pseudo-random, this blob is indistinguishable at rest from a real1084 * encrypted vault without the key.1085 *1086 * crypto.getRandomValues() caps each call at 65536 bytes (the Web Crypto1087 * spec hard limit). Chunk the fill so vaults larger than that — common once1088 * the user has dozens of entries or any passkey — don't throw.1089 */1090const CSPRNG_CHUNK = 65_536;10911092function fillRandom(buf: Uint8Array): Uint8Array {1093  for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {1094    const end = Math.min(offset + CSPRNG_CHUNK, buf.length);1095    const chunk = new Uint8Array(end - offset);1096    crypto.getRandomValues(chunk);1097    buf.set(chunk, offset);1098  }1099  return buf;1100}11011102function generateNoiseBlob(ciphertextBytes: number): StoredVault {1103  const salt = crypto.getRandomValues(new Uint8Array(16));1104  const nonce = crypto.getRandomValues(new Uint8Array(12));1105  const cipher = fillRandom(new Uint8Array(ciphertextBytes));1106  const tag = crypto.getRandomValues(new Uint8Array(16));1107  return {1108    version: 1,1109    salt: hex(salt),1110    nonce: hex(nonce),1111    ciphertext: hex(cipher),1112    tag: hex(tag),1113  };1114}11151116// ---------------------------------------------------------------------------1117// Encrypted plaintext envelope1118// ---------------------------------------------------------------------------11191120type VaultPayload = {1121  entries: VaultEntry[];1122  tombstones?: Record<string, number>;1123  duressConfigured?: boolean;1124};11251126type DecryptedPayload = {1127  entries: VaultEntry[];1128  tombstones: Map<string, number>;1129  duressConfigured: boolean;1130};11311132function encodePayload(entries: VaultEntry[], duress: boolean, minBytes = 0): string {1133  const envelope: VaultPayload = {1134    entries,1135    tombstones: Object.fromEntries(tombstones),1136    duressConfigured: duress,1137  };1138  return padPlaintext(JSON.stringify(envelope), minBytes);1139}11401141function decodeTombstones(raw: unknown, allEntries: VaultEntry[]): Map<string, number> {1142  const result = new Map<string, number>();1143  if (raw && typeof raw === "object" && !Array.isArray(raw)) {1144    for (const [id, timestamp] of Object.entries(raw as Record<string, unknown>)) {1145      if (typeof timestamp === "number" && Number.isFinite(timestamp) && timestamp > 0) {1146        result.set(id, timestamp);1147      }1148    }1149  }1150  // Older payloads had no ledger. Rebuild the durable portion from any1151  // soft-deleted entries before they are eligible for a later purge.1152  for (const entry of allEntries) {1153    if (typeof entry.deletedAt !== "number" || !Number.isFinite(entry.deletedAt) || entry.deletedAt <= 0) {1154      continue;1155    }1156    if ((result.get(entry.id) ?? 0) < entry.deletedAt) {1157      result.set(entry.id, entry.deletedAt);1158    }1159  }1160  return result;1161}11621163function reconcileTombstones(): void {1164  const byId = new Map(entries.map((entry) => [entry.id, entry]));1165  for (const [id] of tombstones) {1166    if (byId.has(id) && !byId.get(id)?.deletedAt) tombstones.delete(id);1167  }1168  for (const entry of entries) {1169    if (typeof entry.deletedAt === "number" && Number.isFinite(entry.deletedAt) && entry.deletedAt > 0) {1170      if ((tombstones.get(entry.id) ?? 0) < entry.deletedAt) {1171        tombstones.set(entry.id, entry.deletedAt);1172      }1173    }1174  }1175}11761177function decodePayload(plain: string): DecryptedPayload {1178  const parsed = JSON.parse(plain) as VaultPayload;1179  if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.entries)) {1180    throw new Error("invalid vault payload");1181  }1182  const normalized = parsed.entries.map(normalizeEntry);1183  return {1184    entries: normalized,1185    tombstones: decodeTombstones(parsed.tombstones, normalized),1186    duressConfigured: parsed.duressConfigured === true,1187  };1188}11891190/**1191 * Consolidate duplicate passkey records after registration.1192 *1193 * Multiple registrations for one RP can leave duplicate passkey records. This1194 * pass collapses the duplicates:1195 *1196 *   1. Group passkey-bearing (and not deleted) entries by `passkey.rpId`.1197 *   2. Within each group, the most recently-active credential wins (prefer1198 *      lastUsedAt, fall back to passkey.createdAt, fall back to modifiedAt).1199 *   3. If a NON-passkey login entry exists for that RP (matched by url or1200 *      additionalUrls hostname), attach the winning passkey to it and1201 *      soft-delete every passkey-bearing entry in the group.1202 *   4. Otherwise, soft-delete every loser in the group, keeping the winner1203 *      as a passkey-only entry.1204 *1205 * Soft delete (deletedAt) rather than splice — the trash flow keeps the1206 * record around for retention and the user can restore if the heuristic1207 * picked wrong. The `merged` flag goes back to decodePayload so the1208 * unlock path persists the consolidated shape immediately.1209 */1210function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {1211  let merged = false;1212  const now = Date.now();12131214  const candidates = entries.filter((e) => !e.deletedAt && e.passkey);1215  const byRpId = new Map<string, VaultEntry[]>();1216  for (const e of candidates) {1217    const rpId = e.passkey!.rpId;1218    const list = byRpId.get(rpId);1219    if (list) list.push(e);1220    else byRpId.set(rpId, [e]);1221  }12221223  for (const [rpId, group] of byRpId) {1224    if (group.length === 0) continue;1225    group.sort((a, b) => {1226      const aT =1227        a.passkey!.lastUsedAt ?? a.passkey!.createdAt ?? a.modifiedAt ?? a.createdAt;1228      const bT =1229        b.passkey!.lastUsedAt ?? b.passkey!.createdAt ?? b.modifiedAt ?? b.createdAt;1230      return bT - aT;1231    });1232    const winner = group[0]!;12331234    // Look for a NON-passkey login entry matching this RP. Use the URL1235    // hostname rather than a substring search so a "login.foo.com" entry1236    // doesn't accidentally absorb a passkey for "foo.com".1237    const loginTarget = entries.find((e) => {1238      if (e.deletedAt || e.passkey || e.type !== "login") return false;1239      if (e.url && extractDomain(e.url) === rpId) return true;1240      for (const extra of e.additionalUrls ?? []) {1241        if (extractDomain(extra) === rpId) return true;1242      }1243      return false;1244    });12451246    if (loginTarget) {1247      loginTarget.passkey = winner.passkey;1248      // A passkey entry may also carry the site's TOTP seed. Preserve it when1249      // the passkey is consolidated onto an existing login instead of1250      // soft-deleting the only record that held the 2FA configuration.1251      if (!loginTarget.totp && winner.totp) {1252        loginTarget.totp = winner.totp;1253        loginTarget.totpAlgorithm = winner.totpAlgorithm;1254        loginTarget.totpDigits = winner.totpDigits;1255        loginTarget.totpPeriod = winner.totpPeriod;1256      }1257      loginTarget.modifiedAt = now;1258      for (const dup of group) {1259        if (!dup.deletedAt) {1260          dup.deletedAt = now;1261          dup.modifiedAt = now;1262        }1263      }1264      merged = true;1265    } else if (group.length > 1) {1266      for (let i = 1; i < group.length; i += 1) {1267        const dup = group[i]!;1268        if (!dup.deletedAt) {1269          dup.deletedAt = now;1270          dup.modifiedAt = now;1271        }1272      }1273      merged = true;1274    }1275  }12761277  return { merged };1278}12791280// Validates that a `StoredVault` record on disk has the field shape we expect1281// before treating an AES-GCM decrypt success as a clean unlock. AES-GCM only1282// authenticates the static VERSION_BYTE AAD, not the `version` field on the1283// outer record — a corrupted `version: 42` slot still decrypts cleanly. This1284// check surfaces that as `corrupted` (M7/COR-007) so the popup can offer a1285// history-restore path instead of falsely reporting "wrong password".1286function hasValidVaultSchema(v: unknown): v is StoredVault {1287  if (typeof v !== "object" || v === null) return false;1288  const r = v as Record<string, unknown>;1289  return (1290    r.version === 1 &&1291    typeof r.salt === "string" &&1292    typeof r.nonce === "string" &&1293    typeof r.ciphertext === "string" &&1294    typeof r.tag === "string"1295  );1296}1297const MAX_HISTORY_BLOB_BYTES = 1_024 * 1_024;12981299function hasValidHistorySlot(value: unknown): value is StoredVault {1300  if (!hasValidVaultSchema(value)) return false;1301  return /^[0-9a-f]{32}$/i.test(value.salt) &&1302    /^[0-9a-f]{24}$/i.test(value.nonce) &&1303    /^[0-9a-f]+$/i.test(value.ciphertext) &&1304    value.ciphertext.length % 2 === 0 &&1305    value.ciphertext.length / 2 <= MAX_HISTORY_BLOB_BYTES &&1306    /^[0-9a-f]{32}$/i.test(value.tag);1307}13081309function parseHistorySlot(value: string): StoredVault | null {1310  try {1311    const parsed: unknown = JSON.parse(value);1312    return hasValidHistorySlot(parsed) ? parsed : null;1313  } catch {1314    return null;1315  }1316}13171318function isHistoryRecord(value: unknown): value is VaultSnapshot {1319  if (typeof value !== "object" || value === null) return false;1320  const record = value as Record<string, unknown>;1321  return typeof record.id === "string" && record.id.length > 0 && record.id.length <= 128 &&1322    typeof record.savedAt === "number" && Number.isFinite(record.savedAt) &&1323    typeof record.reason === "string" &&1324    typeof record.vault_a === "string" && record.vault_a.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1325    typeof record.vault_b === "string" && record.vault_b.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1326    (record.entryCount === null || typeof record.entryCount === "number");1327}13281329function sanitizeHistory(value: unknown): VaultSnapshot[] {1330  if (typeof value !== "object" || value === null) return [];1331  if (!("snapshots" in value) || !Array.isArray(value.snapshots)) return [];1332  return value.snapshots.filter(isHistoryRecord).slice(0, HISTORY_MAX);1333}13341335export type TryDecryptResult =1336  | { status: "ok"; payload: DecryptedPayload }1337  | { status: "wrong_key" }1338  | { status: "corrupted"; reason: string };13391340// Exported solely for `unlockFromCodex` below, which needs to verify a1341// supplied passphrase against a slotA blob *without* committing anything to1342// storage. Keep this internal otherwise — callers crossing the messages.ts1343// boundary should always go through `unlock` / `verifyMainPassword` so the1344// constant-time invariants in Projects.md §3.4 are not bypassed.1345export async function tryDecryptSlot(1346  vault: StoredVault,1347  key: Uint8Array,1348  aadTag?: string,1349): Promise<DecryptedPayload | null> {1350  const res = await tryDecryptSlotResult(vault, key, aadTag);1351  return res.status === "ok" ? res.payload : null;1352}13531354export async function tryDecryptSlotResult(1355  vault: StoredVault,1356  key: Uint8Array,1357  aadTag?: string,1358): Promise<TryDecryptResult> {1359  if (!hasValidVaultSchema(vault)) {1360    return { status: "corrupted", reason: "invalid_slot_schema" };1361  }1362  let plain: string;1363  try {1364    plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);1365  } catch {1366    return { status: "wrong_key" };1367  }1368  try {1369    const parsed = JSON.parse(plain) as unknown;1370    if (typeof parsed !== "object" || parsed === null) {1371      return { status: "corrupted", reason: "invalid_payload_shape" };1372    }1373    if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {1374      return { status: "corrupted", reason: "invalid_payload_shape" };1375    }1376    return { status: "ok", payload: decodePayload(plain) };1377  } catch {1378    return { status: "corrupted", reason: "invalid_payload_json" };1379  }1380}13811382// ---------------------------------------------------------------------------1383// Core operations1384// ---------------------------------------------------------------------------13851386function buildDomainIndexSync(all: VaultEntry[]): void {1387  domainIndex = new Map();13881389  for (const entry of all) {1390    if (entry.deletedAt) continue;1391    if (entry.type === "note" || entry.type === "card") continue;13921393    // An entry can match multiple sites via `additionalUrls`. Index each1394    // hostname so `queryDomain` returns the entry regardless of which alias1395    // the user is currently visiting. Dedupe per-entry so a single entry1396    // never appears twice in one bucket.1397    const domains = new Set<string>();1398    const primary = extractDomain(entry.url ?? "");1399    if (primary) domains.add(primary);1400    for (const extra of entry.additionalUrls ?? []) {1401      const d = extractDomain(extra);1402      if (d) domains.add(d);1403    }1404    if (domains.size === 0) continue;14051406    for (const domain of domains) {1407      const bucket = domainIndex.get(domain) ?? [];1408      bucket.push(entry);1409      domainIndex.set(domain, bucket);1410    }1411  }1412}14131414export async function createVault(password: string): Promise<void> {1415  if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1416  vaultCreatesInFlight++;1417  try {1418    const epoch = vaultEpoch;1419    const salt = generateSalt();1420    const key = await deriveKey(password, salt);1421    if (epoch !== vaultEpoch) { zeroKey(key); throw new Error("vault_changed"); }1422    if (recoveryInFlight || vaultRemovalsInFlight) { zeroKey(key); throw new Error("recovery_in_progress"); }1423    derivedKey = key;1424    entries = [];1425    tombstones = new Map();1426    vaultMode = "real";1427    duressConfigured = false;1428    buildDomainIndexSync(entries);14291430    // Generate and wrap the root key for recovery word escrow.1431    const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =1432      await generateAndWrapRootKey();1433    if (epoch !== vaultEpoch) throw new Error("vault_changed");1434    rootKey = unhex(rawRootKey);14351436    const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);1437    const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");14381439    // Second wrapping of rootKey under derivedKey so future unlocks can rehydrate1440    // it without recovery words (H2/COR-006).1441    const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);14421443    const slotA: StoredVault = {1444      recovery_vault_key: await encrypt(rootKey, hex(derivedKey), "recovery_vault_key_v1"),1445      version: 1,1446      salt: hex(salt),1447      nonce,1448      ciphertext,1449      tag,1450      recovery_salt: recoverySalt,1451      recovery_wrapped_root_key: wrappedRootKey,1452      recovery_nonce: wrappedNonce,1453      recovery_tag: wrappedTag,1454      ...pwRoot,1455    };1456    if (epoch !== vaultEpoch) throw new Error("vault_changed");1457    await writeSlot(SLOT_A, slotA);14581459    // Matching-size noise blob for slot B, so a fresh install shows two1460    // similarly-shaped records regardless of whether duress is ever set up.1461    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));1462    await stampLocalVaultMutation();14631464    // An identity created while this install had no vault was sealed under the1465    // password alone; the vault keys exist now, so re-seal it under them.1466    await identityHooks?.onVaultCreated(password).catch((error) => {1467      console.warn("[Peach] local identity promotion failed:", error);1468    });14691470    touchAutoLock();1471  } finally {1472    vaultCreatesInFlight--;1473  }1474}14751476/**1477 * Creates a local vault from an existing vault root key received through the1478 * SAS-gated adoption protocol. The password is local to this device; it wraps1479 * the adopted root key at rest and does not need to match the source device.1480 */1481export async function createVaultFromRootKey(1482  password: string,1483  rootKeyHex: string,1484): Promise<{ vaultId: string }> {1485  if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1486  if (typeof password !== "string" || password.length === 0) {1487    throw new Error("ADOPT_INVALID_PASSWORD");1488  }1489  if (typeof rootKeyHex !== "string" || !/^[0-9a-f]{64}$/.test(rootKeyHex)) {1490    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars");1491  }14921493  const rootKeyBytes = unhex(rootKeyHex);1494  if (rootKeyBytes.length !== 32) {1495    rootKeyBytes.fill(0);1496    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");1497  }14981499  let nextDerivedKey: Uint8Array | null = null;1500  let sessionRootKey: Uint8Array | null = null;1501  try {1502    if ((await loadSlot(SLOT_A)) !== null) {1503      throw new Error("ADOPT_VAULT_ALREADY_EXISTS");1504    }15051506    const nextEntries: VaultEntry[] = [];1507    const nextDuressConfigured = false;1508    const vaultId = await computeVaultId(rootKeyBytes);1509    const salt = generateSalt();1510    nextDerivedKey = await deriveKey(password, salt);1511    const recovery = await wrapExistingRootKeyForRecovery(rootKeyBytes);15121513    sessionRootKey = new Uint8Array(rootKeyBytes);1514    const plaintext = encodePayload(nextEntries, nextDuressConfigured, 0);1515    const { nonce, ciphertext, tag } = await encrypt(nextDerivedKey, plaintext, "slot_a_v1");1516    const pwRoot = await wrapRootKeyForDerivedKey(nextDerivedKey, sessionRootKey);1517    const slotA: StoredVault = {1518      recovery_vault_key: await encrypt(sessionRootKey, hex(nextDerivedKey), "recovery_vault_key_v1"),1519      version: 1,1520      salt: hex(salt),1521      nonce,1522      ciphertext,1523      tag,1524      recovery_salt: recovery.recoverySalt,1525      recovery_wrapped_root_key: recovery.wrappedRootKey,1526      recovery_nonce: recovery.wrappedNonce,1527      recovery_tag: recovery.wrappedTag,1528      ...pwRoot,1529    };1530    const slotB = generateNoiseBlob(ciphertext.length / 2);1531    await commitCreatedVaultSlots(slotA, slotB);15321533    const previousDerivedKey = derivedKey;1534    const previousRootKey = rootKey;1535    derivedKey = nextDerivedKey;1536    rootKey = sessionRootKey;1537    nextDerivedKey = null;1538    sessionRootKey = null;1539    entries = nextEntries;1540    tombstones = new Map();1541    vaultMode = "real";1542    duressConfigured = nextDuressConfigured;1543    buildDomainIndexSync(entries);1544    if (previousDerivedKey && previousDerivedKey !== derivedKey) zeroKey(previousDerivedKey);1545    if (previousRootKey && previousRootKey !== rootKey) previousRootKey.fill(0);1546    touchAutoLock();15471548    // The receiver's identity was minted before this vault existed (adoption v21549    // needs it in its first frame), so re-seal it under the vault keys now.1550    await identityHooks?.onVaultCreated(password).catch((error) => {1551      console.warn("[Peach] local identity promotion failed:", error);1552    });15531554    return { vaultId };1555  } finally {1556    rootKeyBytes.fill(0);1557    if (nextDerivedKey) zeroKey(nextDerivedKey);1558    if (sessionRootKey) sessionRootKey.fill(0);1559  }1560}15611562export async function hasVault(): Promise<boolean> {1563  return (await loadSlot(SLOT_A)) !== null;1564}15651566/**1567 * Returns whether the real vault has recorded that a duress passphrase is1568 * configured. Reliable only after a real-mode unlock — before unlock or in1569 * decoy mode, returns false because we cannot read slot A's plaintext.1570 */1571export async function isDuressEnabled(): Promise<boolean> {1572  return vaultMode === "real" && duressConfigured;1573}15741575export async function setupDuress(duressPassword: string): Promise<void> {1576  if (!derivedKey || vaultMode !== "real") {1577    throw new Error("vault must be unlocked in real mode");1578  }1579  // Encrypt the decoy payload (empty entries) under the duress key. Pad to1580  // at least the current slot A ciphertext size so the two slots look the1581  // same at rest at setup time.1582  const slotA = await loadSlot(SLOT_A);1583  if (!slotA) throw new Error("missing slot A");15841585  const decoySalt = generateSalt();1586  const decoyKey = await deriveKey(duressPassword, decoySalt);1587  try {1588    // Pad the decoy to the fixed duress ceiling. Slot A is re-encrypted to the1589    // same ceiling by the persistSlotA() call below (duressConfigured is now1590    // true), so both slots are exactly DURESS_SLOT_SIZE+tag at rest and their1591    // lengths cannot reveal that duress is configured (audit MEDIUM).1592    const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);1593    const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");1594    await writeSlot(SLOT_B, {1595      version: 1,1596      salt: hex(decoySalt),1597      nonce,1598      ciphertext,1599      tag,1600    });1601  } finally {1602    zeroKey(decoyKey);1603  }16041605  // Re-encrypt slot A with the duressConfigured flag set to true. No external1606  // flag is written — the bit lives inside the encrypted envelope.1607  duressConfigured = true;1608  await persistSlotA();1609}16101611export async function disableDuress(): Promise<void> {1612  if (!derivedKey || vaultMode !== "real") {1613    throw new Error("vault must be unlocked in real mode");1614  }1615  // Overwrite slot B with fresh noise that matches slot A's size. The slot1616  // remains occupied so its mere existence does not signal that duress was1617  // ever configured.1618  const slotA = await loadSlot(SLOT_A);1619  if (slotA) {1620    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));1621  }16221623  duressConfigured = false;1624  await persistSlotA();1625}16261627// L14/COR-015: this function intentionally checks slot A (real vault) only.1628// A duress-mode user attempting changePassword is rejected earlier by the1629// vaultMode === 'decoy' check at changePassword. The real-vs-decoy1630// distinction here is by design — duress users cannot rotate the real1631// password by guessing it, and the asymmetry in error timing is acceptable1632// because duress mode is opt-in and the user knows their own decoy key.1633export async function verifyMainPassword(password: string): Promise<boolean> {1634  const slotA = await loadSlot(SLOT_A);1635  if (!slotA) return false;1636  const key = await deriveKey(password, unhex(slotA.salt));1637  try {1638    return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;1639  } finally {1640    zeroKey(key);1641  }1642}16431644export async function unlock(password: string): Promise<boolean> {1645  return attemptUnlockWithDerive(password, deriveKey);1646}16471648async function attemptUnlockWithDerive(1649  password: string,1650  derive: typeof deriveKey,1651): Promise<boolean> {1652  if (recoveryInFlight || vaultRemovalsInFlight) return false;1653  const epoch = vaultEpoch;1654  const stale = () => epoch !== vaultEpoch;1655  // Load both current-format slots in parallel. Both exist on a supported1656  // install; the1657  // parallel load and the parallel derivation below keep wall-clock time1658  // constant regardless of which slot's passphrase (real or decoy) the1659  // caller supplied, so a timing side channel cannot distinguish the1660  // duress path from the real-unlock path (DUR-002).1661  const [slotA, slotB] = await Promise.all([1662    loadSlot(SLOT_A),1663    loadSlot(SLOT_B),1664  ]);16651666  // Derive both keys in parallel, unconditionally.1667  const [keyA, keyB] = await Promise.all([1668    slotA ? derive(password, unhex(slotA.salt)) : Promise.resolve(null),1669    slotB ? derive(password, unhex(slotB.salt)) : Promise.resolve(null),1670  ]);16711672  // Attempt both decrypts in parallel. The Result variant lets us distinguish1673  // 'wrong_key' from 'corrupted' so callers can offer a history-restore path1674  // when a slot's schema is invalid even though AES-GCM authenticated (M7).1675  const [resultA, resultB] = await Promise.all([1676    keyA && slotA1677      ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")1678      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1679    keyB && slotB1680      ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")1681      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1682  ]);1683  const payloadA = resultA.status === "ok" ? resultA.payload : null;1684  const payloadB = resultB.status === "ok" ? resultB.payload : null;16851686  if (stale()) {1687    if (keyA) zeroKey(keyA);1688    if (keyB) zeroKey(keyB);1689    return false;1690  }16911692  if (payloadA && keyA) {1693    if (stale()) {1694      zeroKey(keyA);1695      if (keyB) zeroKey(keyB);1696      return false;1697    }1698    derivedKey = keyA;1699    vaultMode = "real";1700    entries = payloadA.entries;1701    tombstones = payloadA.tombstones;1702    duressConfigured = payloadA.duressConfigured;1703    buildDomainIndexSync(entries);1704    await loadSettings();1705    if (stale()) {1706      await lock();1707      return false;1708    }1709    touchAutoLock();1710    if (keyB) zeroKey(keyB);17111712    // Current vaults always carry a password-wrapped root key. Older vaults1713    // without this escrow are outside the supported storage format.1714    rootKey = slotA ? await deriveRootKeyFromDerivedKey(keyA, slotA) : null;1715    if (!rootKey) {1716      await lock();1717      return false;1718    }17191720    // Repair missing or stale escrow only after a real password authenticates the slot.1721    if (slotA) {1722      const escrowed = slotA.recovery_vault_key1723        ? await openSealedKey(rootKey, slotA.recovery_vault_key, "recovery_vault_key_v1") : null;1724      const matches = escrowed !== null && escrowed.every((byte, i) => byte === keyA[i]);1725      if (escrowed) zeroKey(escrowed);1726      if (stale()) { await lock(); return false; }1727      if (!matches) {1728        try {1729          const recoveryVaultKey = await encrypt(rootKey, hex(keyA), "recovery_vault_key_v1");1730          if (stale()) { await lock(); return false; }1731          await writeSlot(SLOT_A, { ...slotA, recovery_vault_key: recoveryVaultKey });1732          if (stale()) { await lock(); return false; }1733        } catch (error) {1734          await lock();1735          throw error;1736        }1737      }1738    }17391740    // PB-26-213: adopt legacy plaintext pair secrets into the encrypted1741    // record and refresh the trusted-session operational copy.1742    await reconcilePairSecrets(rootKey);1743    if (stale()) {1744      await lock();1745      return false;1746    }1747    await lockedSyncUnlockHook?.().catch((error) => {1748      console.warn("[Peach sync] locked inbox drain failed:", error);1749    });1750    if (stale()) {1751      await lock();1752      return false;1753    }1754    await resetPinFailedAttempts();1755    if (stale()) {1756      await lock();1757      return false;1758    }1759    await saveSessionKey(keyA, "real", epoch);1760    if (stale()) return false;1761    return true;1762  }17631764  if (payloadB && keyB) {1765    if (stale()) {1766      zeroKey(keyB);1767      if (keyA) zeroKey(keyA);1768      return false;1769    }1770    derivedKey = keyB;1771    vaultMode = "decoy";1772    decoySyncTeardownHook?.();1773    // A duress session must not retain the real vault's root key. It gates the1774    // recovery words, the sync identity, and the root wrap of the local device1775    // identity, so leaving it live would expose all three in duress mode.1776    if (rootKey) {1777      rootKey.fill(0);1778      rootKey = null;1779    }1780    entries = payloadB.entries;1781    tombstones = payloadB.tombstones;1782    duressConfigured = false;1783    buildDomainIndexSync(entries);1784    await loadSettings();1785    touchAutoLock();1786    if (keyA) zeroKey(keyA);1787    // PB-26-213: a duress session must never serve the real pair-secret map.1788    await dropSessionCache();1789    // Nor the real device identity: a duress session is not a real one.1790    await notifyIdentitySessionEnded();1791    if (stale()) {1792      await lock();1793      return false;1794    }1795    await saveSessionKey(keyB, "decoy", epoch);1796    if (stale()) return false;1797    return true;1798  }17991800  if (keyA) zeroKey(keyA);1801  if (keyB) zeroKey(keyB);1802  // Surface corruption (good AES tag, broken schema) distinctly from1803  // wrong-password so the popup can offer history-restore (M7/COR-007).1804  if (resultA.status === "corrupted") {1805    lastUnlockFailureReason = resultA.reason;1806  } else if (resultB.status === "corrupted") {1807    lastUnlockFailureReason = resultB.reason;1808  }1809  return false;1810}18111812// ---------------------------------------------------------------------------1813// MV3 service worker session key — survives SW restarts within a browser session1814// ---------------------------------------------------------------------------18151816// chrome.storage.session is cleared on browser close; survives SW restart.1817// Firefox does not implement it (persistent background script, no restart risk).1818const SESSION_KEY_STORAGE = "peach_session_dk";18191820// Order writes and removals so lock's awaited removal is a barrier after1821// every escrow write that started before it.1822let sessionKeyMutation = Promise.resolve();18231824function mutateSessionKey(mutation: () => Promise<void>): Promise<void> {1825  const task = sessionKeyMutation.then(mutation, mutation);1826  sessionKeyMutation = task.catch(() => undefined);1827  return task;1828}18291830// PB-26-203: the session-key escrow may only operate where startup positively1831// established trusted-only session storage. Defaults to available so direct1832// vault imports (tests, non-entry bootstraps) keep working; entry.ts applies1833// the real hardening result before the first restore.1834let sessionEscrowAvailable = true;18351836/**1837 * Apply the storage-hardening result at startup. When the trusted-only1838 * session state cannot be established, any stored session key is removed and1839 * the escrow stays off: the user unlocks again after a worker restart1840 * instead of trusting an unproven boundary.1841 */1842export async function applyStorageHardening(sessionEscrow: boolean): Promise<void> {1843  setSessionAllowed(sessionEscrow);1844  if (sessionEscrow) return;1845  sessionEscrowAvailable = false;1846  await clearSessionKey();1847}18481849async function saveSessionKey(1850  key: Uint8Array,1851  mode: "real" | "decoy",1852  expectedEpoch = vaultEpoch,1853): Promise<void> {1854  const session = chrome.storage.session;1855  if (!session || !sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;1856  const stored = { keyHex: hex(key), mode };1857  await mutateSessionKey(async () => {1858    if (!sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;1859    await session.set({ [SESSION_KEY_STORAGE]: stored });1860  });1861}18621863async function clearSessionKey(): Promise<void> {1864  const session = chrome.storage.session;1865  if (!session) return;1866  await mutateSessionKey(() => session.remove(SESSION_KEY_STORAGE));1867}18681869// A lock that only holds while the service worker stays alive is no lock at1870// all: a cold worker's restoreFromSession() would find the surviving session1871// key and silently re-unlock ~a minute after the user locked. So lock()1872// bumps this epoch synchronously at entry and zeroes keys/indexes before any1873// await; a restore that started earlier sees the mismatch after its next1874// await and aborts instead of publishing.1875let vaultEpoch = 0;18761877// One in-flight restore shared by concurrent callers: storage is read once1878// and the locked-sync unlock hook runs once.1879let restoreInFlight: Promise<boolean> | null = null;18801881/**1882 * On SW restart, re-derive all in-memory vault state from the session key1883 * stored in chrome.storage.session (set at unlock time, cleared by lock();1884 * also cleared on browser close or when restoration fails).1885 * Returns true if the vault was restored, false if no session key was found.1886 * No-ops if the vault is already unlocked.1887 */1888export async function restoreFromSession(): Promise<boolean> {1889  if (recoveryInFlight || vaultRemovalsInFlight) return false;1890  if (derivedKey !== null) return true;1891  if (restoreInFlight) return restoreInFlight;1892  const task = restoreFromSessionInner();1893  restoreInFlight = task;1894  try {1895    return await task;1896  } finally {1897    restoreInFlight = null;1898  }1899}19001901async function restoreFromSessionInner(): Promise<boolean> {1902  const epoch = vaultEpoch;1903  const stale = () => epoch !== vaultEpoch;1904  if (derivedKey !== null) return true;1905  if (!sessionEscrowAvailable) return false;1906  if (!chrome.storage.session) return false;1907  const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);1908  if (stale()) return false;1909  const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;1910  if (!entry?.keyHex) return false;19111912  const key = unhex(entry.keyHex);1913  const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;1914  const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";1915  const slot = await loadSlot(slotKey);1916  if (stale()) { zeroKey(key); return false; }1917  if (!slot) { await clearSessionKey(); return false; }19181919  const result = await tryDecryptSlotResult(slot, key, aadTag);1920  if (stale()) { zeroKey(key); return false; }1921  if (result.status !== "ok") { await clearSessionKey(); return false; }19221923  // Decrypted payload stays in locals until the final epoch-checked commit1924  // below; nothing observable is published before then.1925  const payload = result.payload;1926  await loadSettings();1927  if (stale()) { zeroKey(key); return false; }19281929  // Rehydrate the root key used by sync identity derivation from the password1930  // escrow stored on the current vault format.1931  let freshRoot: Uint8Array | null = null;1932  if (entry.mode === "real") {1933    freshRoot = await deriveRootKeyFromDerivedKey(key, slot);1934    if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }1935    if (!freshRoot) {1936      await lock();1937      return false;1938    }1939  }19401941  if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }1942  if (freshRoot) {1943    // PB-26-213: encrypted pair-secret record + session copy, before publish.1944    await reconcilePairSecrets(freshRoot);1945    if (stale()) { zeroKey(key); zeroKey(freshRoot); return false; }1946  } else {1947    // PB-26-213: a duress restore must never serve the real pair-secret map.1948    await dropSessionCache();1949    // Nor the real device identity.1950    await notifyIdentitySessionEnded();1951    if (stale()) { zeroKey(key); return false; }1952  }1953  derivedKey = key;1954  vaultMode = entry.mode;1955  if (entry.mode === "decoy") decoySyncTeardownHook?.();1956  entries = payload.entries;1957  tombstones = payload.tombstones;1958  duressConfigured = entry.mode === "real" ? payload.duressConfigured : false;1959  if (freshRoot) rootKey = freshRoot;1960  buildDomainIndexSync(entries);1961  touchAutoLock();19621963  await lockedSyncUnlockHook?.().catch((error) => {1964    console.warn("[Peach sync] locked inbox drain failed:", error);1965  });1966  if (stale()) return false;19671968  return true;1969}19701971export async function lock(): Promise<void> {1972  // A user-initiated lock must be durable across MV3 service-worker restarts.1973  // The SW is idle-killed after ~30s of inactivity, and the popup's next open1974  // wakes a cold SW whose restoreFromSession() reads chrome.storage.session.1975  // If the session key survived lock(), that restore would silently re-unlock1976  // the vault ~a minute after the user locked it — a lock that only held1977  // while the SW happened to stay alive. The background-sync convenience the1978  // session key once bought (sync runner re-waking to a restored vault) is1979  // not worth an unlocked vault the user never asked to unlock; when locked,1980  // sync-runner correctly reports VAULT_LOCKED instead.1981  vaultEpoch++;1982  if (derivedKey) {1983    zeroKey(derivedKey);1984    derivedKey = null;1985  }1986  if (rootKey) {1987    rootKey.fill(0);1988    rootKey = null;1989  }19901991  entries = [];1992  tombstones = new Map();1993  domainIndex = new Map();1994  vaultMode = "real";1995  duressConfigured = false;1996  clearAutoLock();1997  await clearSessionKey();1998  // The decrypted identity is session state as well, so a locked vault must not1999  // leave one behind; clear it after the in-memory state is gone.2000  await notifyIdentitySessionEnded();2001}20022003export function isUnlocked(): boolean {2004  return derivedKey !== null;2005}2006/** True only while the active session is unlocked through the decoy slot. */2007export function isDecoyMode(): boolean {2008  return derivedKey !== null && vaultMode === "decoy";2009}20102011// Opens the vault using a pre-derived AES-256 key (skipping Argon2id). The2012// PIN-unlock path unwraps this key from its PIN wrap; the passphrase path2013// always derives from scratch via Argon2id.2014export async function unlockWithKey(2015  masterKeyHex: string,2016): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {2017  if (recoveryInFlight || vaultRemovalsInFlight) return { ok: false, error: "recovery_in_progress" };2018  const epoch = vaultEpoch;2019  const stale = () => epoch !== vaultEpoch;2020  let masterKeyBytes: Uint8Array | null = null;2021  try {2022    masterKeyBytes = unhex(masterKeyHex);2023    const stored = await loadSlot(SLOT_A);2024    if (!stored) return { ok: false, error: "invalid_key" };2025    const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");2026    if (!payload || stale()) {2027      zeroKey(masterKeyBytes);2028      return { ok: false, error: "invalid_key" };2029    }20302031    derivedKey = masterKeyBytes;2032    vaultMode = "real";2033    entries = payload.entries;2034    tombstones = payload.tombstones;2035    duressConfigured = payload.duressConfigured;2036    buildDomainIndexSync(entries);2037    await loadSettings();2038    touchAutoLock();20392040    rootKey = await deriveRootKeyFromDerivedKey(masterKeyBytes, stored);2041    if (!rootKey) {2042      await lock();2043      return { ok: false, error: "invalid_key" };2044    }2045    await reconcilePairSecrets(rootKey);2046    if (stale()) {2047      await lock();2048      return { ok: false, error: "invalid_key" };2049    }2050    await saveSessionKey(masterKeyBytes, "real", epoch);2051    if (stale()) return { ok: false, error: "invalid_key" };2052    return { ok: true, entries };2053  } catch {2054    if (masterKeyBytes && derivedKey !== masterKeyBytes) zeroKey(masterKeyBytes);2055    return { ok: false, error: "invalid_key" };2056  }2057}20582059// --- Adoption duress-slot helpers (passthrough, no decrypt) ---20602061/**2062 * Adoption SOURCE helper: returns the sealed slot B as a JSON string when2063 * duress is configured and slot B exists, so the inline snapshot can ship it2064 * to the receiver. Returns null otherwise. Never decrypts.2065 */2066export async function exportDuressSlotForAdoption(): Promise<string | null> {2067  if (!(await isDuressEnabled())) return null;2068  const slotB = await loadSlot(SLOT_B);2069  if (!slotB) return null;2070  return JSON.stringify(slotB);2071}20722073/**2074 * Adoption RECEIVER helper: installs a duress slot received from a source2075 * device. Validates the StoredVault shape (same guard as unlockFromCodex)2076 * and writes it to slot B. Throws on invalid shape so the caller can treat2077 * it as a non-fatal snapshot failure. Never decrypts.2078 */2079export async function installAdoptedDuressSlot(json: string): Promise<void> {2080  let parsed: StoredVault;2081  try {2082    const raw = JSON.parse(json) as unknown;2083    if (!hasValidVaultSchema(raw)) {2084      throw new Error("invalid_duress_slot_shape");2085    }2086    parsed = raw;2087  } catch (err) {2088    if (err instanceof SyntaxError) {2089      throw new Error("invalid_duress_slot_shape");2090    }2091    throw err;2092  }2093  await writeSlot(SLOT_B, parsed);2094}20952096/**2097 * Restore the vault from a parsed Peach Codex payload.2098 *2099 * The supplied passphrase is verified against the Codex's slotA *before* any2100 * storage mutation — wrong passphrases return without touching disk. On2101 * success, the current vault state is snapshotted (reason: "restore") so the2102 * user can revert via Settings -> Vault History, then slotA/slotB are written2103 * and `peach_last_modified_at` is set to the Codex's recorded timestamp. A2104 * regular `unlock()` follows so the rest of the SW sees the standard2105 * post-unlock state.2106 *2107 * Intentionally non-Pro-gated — see peach_codex_v2.md "Pro gating". A Codex2108 * printed by a Pro user must always be restorable, even on a free device.2109 *2110 * Timing is not held constant here (in contrast to `unlock`): the Codex flow2111 * is an explicit user action with a known passphrase, not a passive lock2112 * screen, so the duress-vs-real timing side channel does not apply.2113 */2114export async function unlockFromCodex(params: {2115  slotA: string; // JSON string of StoredVault for slot A2116  slotB: string | null; // JSON string of StoredVault for slot B, or null2117  timestamp: number;2118  masterPassphrase: string;2119}): Promise<2120  | { ok: true; entryCount: number }2121  | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" | "missing_root_escrow" }2122> {2123  if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight) throw new Error("vault_changed");2124  vaultReplacementInFlight = true;2125  try {2126    let parsedSlotA: StoredVault;2127    let parsedSlotB: StoredVault | null = null;2128    try {2129      const rawA = JSON.parse(params.slotA) as unknown;2130      if (!hasValidVaultSchema(rawA)) {2131        return { ok: false, reason: "invalid_slot_format" };2132      }2133      parsedSlotA = rawA;2134      if (params.slotB !== null) {2135        const rawB = JSON.parse(params.slotB) as unknown;2136        if (!hasValidVaultSchema(rawB)) {2137          return { ok: false, reason: "invalid_slot_format" };2138        }2139        parsedSlotB = rawB;2140      }2141    } catch {2142      return { ok: false, reason: "invalid_slot_format" };2143    }21442145    // Verify the passphrase and the password-wrapped root escrow against the2146    // staged Slot A WITHOUT writing anything. Payload decoding is part of the2147    // trial decrypt, so unlock() cannot be the first place these checks run.2148    const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));2149    const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");2150    if (!trialPayload) {2151      zeroKey(trialKey);2152      return { ok: false, reason: "wrong_passphrase" };2153    }2154    const hasEscrow =2155      !!parsedSlotA.pw_root_ciphertext && !!parsedSlotA.pw_root_nonce && !!parsedSlotA.pw_root_tag;2156    if (!hasEscrow) {2157      zeroKey(trialKey);2158      return { ok: false, reason: "missing_root_escrow" };2159    }2160    const stagedRootKey = await deriveRootKeyFromDerivedKey(trialKey, parsedSlotA);2161    if (!stagedRootKey) {2162      zeroKey(trialKey);2163      return { ok: false, reason: "wrong_passphrase" };2164    }2165    zeroKey(stagedRootKey);2166    zeroKey(trialKey);21672168    // Stage the complete candidate pair in memory before touching storage.2169    const stagedSlotB = parsedSlotB ?? generateNoiseBlob(parsedSlotA.ciphertext.length / 2);21702171    // Drop the trial key; `unlock()` below derives its own copy. Holding two2172    // copies of the master key in memory at once would be a needless surface.21732174    // Snapshot the about-to-be-overwritten on-disk state so the user can revert2175    // a mistaken Codex restore via the Vault History UI. Non-fatal if it fails.2176    await takeVaultSnapshot("restore");2177    const previousSlotA = await loadSlot(SLOT_A);2178    const previousSlotB = await loadSlot(SLOT_B);2179    let slotACommitted = false;2180    let slotBCommitted = false;2181    try {2182      await writeSlot(SLOT_A, parsedSlotA);2183      slotACommitted = true;2184      await writeSlot(SLOT_B, stagedSlotB);2185      slotBCommitted = true;2186      await chrome.storage.local.set({2187        peach_last_modified_at: String(params.timestamp),2188      });2189    } catch (err) {2190      if (slotBCommitted && previousSlotB) await writeSlot(SLOT_B, previousSlotB);2191      if (slotACommitted && previousSlotA) await writeSlot(SLOT_A, previousSlotA);2192      throw err;2193    }21942195    // Standard unlock path so domain index, settings, auto-lock, and2196    // recovery-key state all populate exactly as a normal unlock would.2197    const ok = await unlock(params.masterPassphrase);2198    if (!ok) {2199      // Should be unreachable — the staged candidate passed the same checks.2200      return { ok: false, reason: "wrong_passphrase" };2201    }2202    return { ok: true, entryCount: getEntries().length };2203  } finally {2204    vaultReplacementInFlight = false;2205  }2206}22072208// Returns the current in-memory derived key as a hex string. Only the PIN2209// unlock path needs this value, and it reads module state directly; this2210// accessor exists so unlockWithKey's root-key rehydration is testable.2211export /* @testable */ function getDerivedKeyHex(): string {2212  if (!derivedKey) throw new Error("vault_not_unlocked");2213  return hex(derivedKey);2214}22152216/**2217 * Returns the vault's stable root key as hex, or null when locked / not yet2218 * populated. The root key is random per-vault, generated at creation, escrowed2219 * under the recovery words, and re-wrapped (not regenerated) on every password2220 * change — so it is INVARIANT across password rotation, unlike getDerivedKeyHex.2221 *2222 * This is the correct input for sync identity derivation (vault_id, the Noise2223 * NK static key, the Ed25519 manifest signing key, and per-entry envelope2224 * keys): paired devices keep the same identity and can still decrypt each2225 * other's entries after either side rotates its master password (SEV-2-B).2226 *2227 * Returns null rather than throwing so sync callers degrade to VAULT_LOCKED2228 * instead of crashing; rootKey is populated on every supported real-mode2229 * unlock via deriveRootKeyFromDerivedKey.2230 */2231export function getRootKeyHex(): string | null {2232  return rootKey ? hex(rootKey) : null;2233}22342235export function getEntries(): VaultEntry[] {2236  if (!derivedKey) throw new Error("vault_locked");2237  return entries.filter((entry) => !entry.deletedAt);2238}22392240const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;22412242export function getIdentities(): SavedIdentity[] {2243  if (!derivedKey) throw new Error("vault_locked");2244  const active = entries.filter((e) => !e.deletedAt && e.type === "login");22452246  const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();2247  const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();22482249  for (const entry of active) {2250    const domain = extractDomain(entry.url ?? "") ?? "";2251    const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;22522253    function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {2254      const existing = map.get(v);2255      if (!existing || modifiedAt > existing.lastUsed) {2256        map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });2257      } else {2258        map.set(v, { ...existing, count: existing.count + 1 });2259      }2260    }22612262    const uVal = entry.username?.trim();2263    if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);22642265    // Also count the dedicated email field — entries created via the inline2266    // popup new-entry form store email here rather than in username.2267    const eVal = entry.email?.trim();2268    if (eVal) tally(emailMap, eVal);2269  }22702271  const toIdentity = (type: "email" | "username") =>2272    ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({2273      value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,2274    });22752276  return [2277    ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),2278    ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),2279  ];2280}22812282export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {2283  if (!derivedKey) throw new Error("vault_locked");22842285  const now = Date.now();2286  const added: VaultEntry[] = [];2287  for (const draft of drafts) {2288    try {2289      const sanitized = sanitizeEntryDraft(draft);2290      const nextEntry: VaultEntry = {2291        ...sanitized,2292        id: crypto.randomUUID(),2293        createdAt: now,2294        modifiedAt: monotonicEntryTimestamp(),2295      };2296      entries.push(nextEntry);2297      added.push(nextEntry);2298    } catch {2299      // Skip invalid drafts silently — caller can see diff between input and output length2300    }2301  }23022303  if (added.length > 0) {2304    await persistEntries();2305  }23062307  return added;2308}23092310/**2311 * Restore a set of entries in full fidelity — preserves id, createdAt,2312 * modifiedAt, and every other field unlike `batchAddEntries` which2313 * assigns fresh identity. Used by restore paths where the backup is the2314 * authoritative source of truth. `mode` controls how entries already in2315 * the vault are treated.2316 */2317export async function restoreEntries(2318  incoming: VaultEntry[],2319  mode: "replace" | "merge"2320): Promise<{ added: number; updated: number; skipped: number }> {2321  if (!derivedKey) throw new Error("vault_locked");23222323  // A replace with zero incoming entries is almost certainly a caller bug2324  // (e.g. an import that silently dropped everything). Refuse rather than2325  // wipe the vault.2326  if (mode === "replace" && incoming.length === 0) {2327    throw new Error("refuse to replace with empty entry set");2328  }23292330  let added = 0;2331  let updated = 0;2332  let skipped = 0;23332334  if (mode === "replace") {2335    entries = [];2336    for (const entry of incoming) {2337      const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2338      if (!normalized) {2339        skipped += 1;2340        continue;2341      }2342      entries.push(normalized);2343      if (normalized.deletedAt) {2344        tombstones.set(2345          normalized.id,2346          Math.max(tombstones.get(normalized.id) ?? 0, normalized.deletedAt),2347        );2348      } else {2349        tombstones.delete(normalized.id);2350      }2351      added += 1;2352    }2353  } else {2354    const byId = new Map<string, VaultEntry>();2355    for (const e of entries) byId.set(e.id, e);23562357    for (const entry of incoming) {2358      const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2359      if (!normalized) {2360        skipped += 1;2361        continue;2362      }2363      const existing = byId.get(normalized.id);2364      if (!existing) {2365        entries.push(normalized);2366        if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2367        else tombstones.delete(normalized.id);2368        added += 1;2369      } else if (normalized.modifiedAt > existing.modifiedAt) {2370        const idx = entries.findIndex((e) => e.id === existing.id);2371        if (idx !== -1) {2372          entries[idx] = normalized;2373          if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2374          else tombstones.delete(normalized.id);2375          updated += 1;2376        }2377      } else {2378        skipped += 1;2379      }2380    }2381  }23822383  await persistEntries("import");2384  return { added, updated, skipped };2385}23862387/**2388 * A Peach entry id is a UUID. A restored or imported file carries whatever id2389 * its author used, and no reader bounds it, so one oversized id would ride2390 * into every future sync frame and be rejected there — a permanent, opaque2391 * failure on both platforms, caused by data that was already local.2392 *2393 * The action is mint, not reject: this is the last point where an id is still2394 * ours to choose, so the worst outcome is one duplicate if the same vault is2395 * later restored beside a device still holding the old id. Rejecting would2396 * lose the user's import.2397 *2398 * Deliberately NOT inside sanitizeRestoredEntry, which applyMergedRemoteEntries2399 * also calls. Sync has to adopt a peer's id verbatim — that is the only thing2400 * keeping two devices agreed on which entry they are discussing — so reminting2401 * there would fork identity on every device, on every round.2402 */2403const ENTRY_ID_SHAPE = /^[A-Za-z0-9_-]{1,64}$/;24042405function naturalizeRestoredId(entry: VaultEntry | null): VaultEntry | null {2406  if (!entry || ENTRY_ID_SHAPE.test(entry.id)) return entry;2407  return { ...entry, id: crypto.randomUUID() };2408}24092410/**2411 * Validate + normalise a VaultEntry coming from a backup, import, or sync2412 * peer. MV-6: this is a strict field WHITELIST — `normalizeEntry` copies2413 * only known VaultEntry fields (unknown/attacker keys are dropped), and2414 * nested `passkey`/`canary` shapes are rebuilt field-by-field, never2415 * spread. Returns null for values the live vault shouldn't accept.2416 */2417function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {2418  if (!entry || typeof entry !== "object") return null;2419  const title = typeof entry.title === "string" ? entry.title.trim() : "";2420  if (!title) return null;2421  const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();2422  const now = Date.now();2423  const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;2424  const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;24252426  // normalizeEntry whitelists every known VaultEntry field before the entry2427  // reaches the live vault.2428  const normalized = normalizeEntry({2429    ...entry,2430    id,2431    title,2432    type: entry.type ?? "login",2433    createdAt,2434    modifiedAt,2435  });24362437  if (normalized.passkey) {2438    normalized.passkey = sanitizePasskey(normalized.passkey);2439  }2440  if (normalized.canary) {2441    normalized.canary = sanitizeCanary(normalized.canary);2442  }2443  // PCH-01-016: bound tags on the restore path too, so both import funnels agree.2444  normalized.tags = sanitizeTags(normalized.tags);24452446  // Login entries from backup must carry a password (or be passkey-only,2447  // in which case the passkey sub-object replaces the password requirement).2448  if (2449    normalized.type === "login" &&2450    !normalized.passkey &&2451    typeof normalized.password !== "string"2452  ) {2453    return null;2454  }2455  if (entry.passkey && !normalized.passkey) {2456    // Entry claimed a passkey but the shape didn't validate — refuse the2457    // whole entry rather than silently importing a credential-less husk.2458    return null;2459  }24602461  return normalized;2462}24632464/**2465 * Rebuild a PasskeyData object from untrusted input, field by field.2466 * Returns undefined when required fields are missing/mistyped — a rogue2467 * passkey credential must not activate via import (MV-6 attack scenario).2468 */2469function sanitizePasskey(pk: unknown): PasskeyData | undefined {2470  if (!pk || typeof pk !== "object") return undefined;2471  const r = pk as Record<string, unknown>;2472  if (2473    typeof r.rpId !== "string" || !r.rpId ||2474    typeof r.credentialId !== "string" || !r.credentialId ||2475    typeof r.publicKeyCose !== "string" ||2476    typeof r.userHandle !== "string" ||2477    typeof r.userName !== "string"2478  ) {2479    return undefined;2480  }2481  return {2482    rpId: r.rpId,2483    rpName: typeof r.rpName === "string" ? r.rpName : r.rpId,2484    credentialId: r.credentialId,2485    publicKeyCose: r.publicKeyCose,2486    privateKeyJwk:2487      r.privateKeyJwk && typeof r.privateKeyJwk === "object"2488        ? (r.privateKeyJwk as JsonWebKey)2489        : undefined,2490    userHandle: r.userHandle,2491    userName: r.userName,2492    userDisplayName:2493      typeof r.userDisplayName === "string" ? r.userDisplayName : r.userName,2494    algorithm: r.algorithm === -8 ? -8 : -7,2495    signCount: typeof r.signCount === "number" ? r.signCount : 0,2496    aaguid: typeof r.aaguid === "string" ? r.aaguid : "",2497    backupEligible: r.backupEligible === true,2498    backupState: r.backupState === true,2499    lastUsedAt: typeof r.lastUsedAt === "number" ? r.lastUsedAt : undefined,2500    browser: r.browser === "chrome" || r.browser === "firefox" ? r.browser : undefined,2501    transports: Array.isArray(r.transports)2502      ? r.transports.filter((t): t is string => typeof t === "string")2503      : undefined,2504    createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),2505  };2506}25072508/**2509 * Rebuild a Canary object from untrusted input. The webhook must be a2510 * well-formed HTTPS URL — a poisoned canary.webhookUrl is a standing2511 * exfiltration endpoint that the canary subsystem will POST entry titles2512 * to (MV-6 attack scenario). Invalid → the canary is dropped, not the2513 * entry. FIRE_CANARY_PING re-validates with the full SSRF guard at fire2514 * time (isAllowedCanaryWebhookUrl), so this import-time check is the2515 * outer of two gates.2516 */2517function sanitizeCanary(c: unknown): Canary | undefined {2518  if (!c || typeof c !== "object") return undefined;2519  const r = c as Record<string, unknown>;2520  if (typeof r.webhookUrl !== "string") return undefined;2521  let url: URL;2522  try {2523    url = new URL(r.webhookUrl);2524  } catch {2525    return undefined;2526  }2527  if (url.protocol !== "https:") return undefined;2528  return {2529    webhookUrl: url.toString(),2530    label: typeof r.label === "string" ? r.label : undefined,2531    lastPinged: typeof r.lastPinged === "number" ? r.lastPinged : undefined,2532    pingCount: typeof r.pingCount === "number" ? r.pingCount : undefined,2533  };2534}25352536/**2537 * MV-6 / PCH-01-016: tags from imported / batch-added entries are untrusted.2538 * Keep only non-empty strings, cap each at 256 chars, and cap the count at 2552539 * (the same per-entry ceiling the export codec enforces, peachPayload.ts).2540 * Non-array or all-invalid input collapses to undefined.2541 */2542function sanitizeTags(tags: unknown): string[] | undefined {2543  if (!Array.isArray(tags)) return undefined;2544  const out: string[] = [];2545  for (const t of tags) {2546    if (typeof t !== "string") continue;2547    const trimmed = t.trim();2548    if (!trimmed) continue;2549    out.push(trimmed.slice(0, 256));2550    if (out.length >= 255) break;2551  }2552  return out.length > 0 ? out : undefined;2553}25542555// Soft-deletes every non-deleted entry in one call. The literal string2556// argument is a tripwire against accidental calls — any caller that would2557// wipe the vault has to consciously type "REPLACE_ALL". Do not relax this2558// to a boolean.2559export async function clearVaultEntries(2560  confirmation: "REPLACE_ALL"2561): Promise<void> {2562  if (confirmation !== "REPLACE_ALL") {2563    throw new Error("clearVaultEntries requires explicit confirmation");2564  }2565  if (!derivedKey) throw new Error("vault_locked");2566  for (const entry of entries) {2567    if (!entry.deletedAt) {2568      const stamp = monotonicEntryTimestamp(Math.max(2569        entry.modifiedAt,2570        tombstones.get(entry.id) ?? 0,2571      ));2572      entry.deletedAt = stamp;2573      entry.modifiedAt = stamp;2574      tombstones.set(entry.id, stamp);2575    }2576  }2577  await persistEntries();2578}25792580export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {2581  if (!derivedKey) throw new Error("vault_locked");25822583  const sanitized = sanitizeEntryDraft(entry);2584  const now = Date.now();2585  const stamp = monotonicEntryTimestamp();2586  const nextEntry: VaultEntry = {2587    ...sanitized,2588    id: crypto.randomUUID(),2589    createdAt: now,2590    modifiedAt: stamp,2591    // Stamp passwordChangedAt at creation so age tracking is accurate from2592    // day one. Non-login entries carry the same stamp harmlessly.2593    passwordChangedAt: sanitized.password ? stamp : undefined,2594  };25952596  // Clone-and-replace so a failed persist rolls back the in-memory state2597  // (COR-008). Without this, a quota-full or storage error leaves the2598  // module-level `entries` ahead of what's actually on disk.2599  const rollback = entries;2600  entries = [...entries, nextEntry];2601  try {2602    await persistEntries();2603  } catch (err) {2604    entries = rollback;2605    throw err;2606  }26072608  // Fire-and-forget breach check (only for login entries if breach monitoring is enabled or not set)2609  if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {2610    checkBreach(nextEntry.password).then(async (count) => {2611      if (count > 0) {2612        const idx = entries.findIndex((e) => e.id === nextEntry.id);2613        if (idx !== -1) {2614          entries[idx] = { ...entries[idx], breach: count, modifiedAt: monotonicEntryTimestamp(entries[idx].modifiedAt) };2615          await persistEntries();2616        }2617      }2618    });2619  }26202621  fireSyncTrigger("vault_change");26222623  return nextEntry;2624}26252626/**2627 * Run the passkey-merge pass on the live in-memory entries and persist if2628 * anything changed. Called immediately after any passkey registration so that2629 * a same-domain TOTP-only entry already in the vault gets consolidated right2630 * away instead of waiting until the next lock/unlock cycle.2631 */2632export async function consolidatePasskeyEntries(): Promise<void> {2633  if (!derivedKey) return;2634  const { merged } = mergePasskeyOnlyIntoLogins(entries);2635  if (merged) {2636    await persistEntries();2637  }2638}26392640export async function updateEntry(2641  id: string,2642  patch: Partial<VaultEntry>2643): Promise<void> {2644  if (!derivedKey) throw new Error("vault_locked");26452646  const idx = entries.findIndex((entry) => entry.id === id);2647  if (idx === -1 || entries[idx].deletedAt) {2648    throw new Error("entry_not_found");2649  }26502651  const current = entries[idx];2652  const sanitizedPatch = sanitizeEntryPatch(patch);2653  // Refresh passwordChangedAt only when the password value actually changes —2654  // a metadata-only update (title, tags, etc.) must not reset the age clock2655  // that drives the Pro health rotation recommendation.2656  const passwordChanged =2657    "password" in patch &&2658    typeof sanitizedPatch.password === "string" &&2659    sanitizedPatch.password !== current.password;2660  const stamp = monotonicEntryTimestamp(current.modifiedAt);2661  // When the password actually changes, push the outgoing one onto the history2662  // (newest first) so the user can reveal/copy/restore it later. We record the2663  // age it carried (passwordChangedAt, falling back to createdAt) rather than2664  // `now`, so the list reflects when each password was last in effect. Only2665  // capture a non-empty prior value — clearing a password leaves no secret to2666  // keep, and we skip an immediate exact duplicate (e.g. restore-then-restore)2667  // to avoid noise.2668  const priorPassword = current.password;2669  const shouldCapture =2670    passwordChanged &&2671    typeof priorPassword === "string" &&2672    priorPassword.length > 0 &&2673    current.passwordHistory?.[0]?.password !== priorPassword;2674  const nextHistory = shouldCapture2675    ? [2676        { password: priorPassword!, changedAt: current.passwordChangedAt ?? current.createdAt },2677        ...(current.passwordHistory ?? []),2678      ].slice(0, PASSWORD_HISTORY_MAX)2679    : current.passwordHistory;2680  entries[idx] = {2681    ...current,2682    ...sanitizedPatch,2683    modifiedAt: stamp,2684    ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),2685  };2686268726882689  // Card entries must retain their card number2690  if (entries[idx].type === "card" && !entries[idx].cardNumber) {2691    entries[idx] = current;2692    throw new Error("card number is required for card entries");2693  }26942695  // Roll the in-memory entry back to its pre-edit state if the disk write2696  // fails (e.g. storage quota). Without this the module-level `entries` array2697  // would hold an edit that never landed on disk, diverging from the vault2698  // until the next unlock silently reverts it (SEV-3-A). Mirrors addEntry.2699  try {2700    await persistEntries();2701  } catch (err) {2702    entries[idx] = current;2703    throw err;2704  }27052706  // Breach check when password changes: clear immediately so old breach doesn't linger,2707  // then async-check the new password and only re-set if it's also found.2708  if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {2709    entries[idx] = { ...entries[idx], breach: undefined };2710    await persistEntries();2711    const password = entries[idx].password;2712    if (password) {2713      checkBreach(password).then(async (count) => {2714        const i = entries.findIndex((e) => e.id === id);2715        if (i !== -1 && count > 0) {2716          entries[i] = { ...entries[i], breach: count, modifiedAt: monotonicEntryTimestamp(entries[i].modifiedAt) };2717          await persistEntries();2718        }2719      });2720    }2721  }27222723  fireSyncTrigger("vault_change");2724}27252726export async function deleteEntry(id: string): Promise<void> {2727  if (!derivedKey) throw new Error("vault_locked");27282729  const entry = entries.find((item) => item.id === id);2730  if (!entry || entry.deletedAt) {2731    throw new Error("entry_not_found");2732  }27332734  // Tombstone timestamp must be strictly greater than the entry's last2735  // modification so the deletion wins LWW against any in-flight edit, even2736  // under clock skew (SEV-2-E).2737  const previousModifiedAt = entry.modifiedAt;2738  const previousTombstone = tombstones.get(id);2739  const stamp = monotonicEntryTimestamp(Math.max(entry.modifiedAt, previousTombstone ?? 0));2740  entry.deletedAt = stamp;2741  entry.modifiedAt = stamp;2742  tombstones.set(id, stamp);2743  // Roll the tombstone back if the disk write fails, so a quota error doesn't2744  // leave the entry deleted in memory but alive on disk (SEV-3-A).2745  try {2746    await persistEntries();2747  } catch (err) {2748    delete entry.deletedAt;2749    entry.modifiedAt = previousModifiedAt;2750    if (previousTombstone === undefined) tombstones.delete(id);2751    else tombstones.set(id, previousTombstone);2752    throw err;2753  }2754  fireSyncTrigger("vault_change");2755}27562757export function getDeletedEntries(): VaultEntry[] {2758  if (!derivedKey) return [];2759  return entries.filter((e) => !!e.deletedAt);2760}27612762/** Return all durable deletion timestamps, including purged full entries. */2763export function getTombstoneManifest(): Record<string, number> {2764  if (!derivedKey) return {};2765  return Object.fromEntries(tombstones);2766}27672768/**2769 * Returns the vault's monotonic version — the `peach_last_modified_at` value2770 * stamped on every user-initiated write. Remote (sync) writes do NOT advance2771 * this version so a sync round never cascades into a second outbound sync.2772 */2773export async function getVaultVersion(): Promise<number> {2774  try {2775    const raw = await chrome.storage.local.get("peach_last_modified_at");2776    const v = (raw as Record<string, unknown>).peach_last_modified_at;2777    if (typeof v === "number") return v;2778    if (typeof v === "string" && v !== "") {2779      const n = Number.parseInt(v, 10);2780      return Number.isFinite(n) ? n : 0;2781    }2782    return 0;2783  } catch {2784    return 0;2785  }2786}27872788/**2789 * Apply a batch of remote entries + tombstones from a sync peer.2790 * Last-write-wins by `modifiedAt`; a tombstone supersedes a live entry when2791 * `deletedAt > modifiedAt` on the local side. Mutates `entries` directly and2792 * persists with reason `sync_received` — does NOT fire the sync dispatcher, so2793 * applying a sync round cannot cascade into another outbound sync.2794 *2795 * `applied` counts entries that actually changed local state (new add,2796 * overwrite-by-newer, or new tombstone). `received` is the raw payload size2797 * the caller can surface in the sync result UI.2798 */2799export async function applyMergedRemoteEntries(2800  remoteEntries: VaultEntry[],2801  remoteTombstones: Record<string, number>,2802): Promise<{ received: number; applied: number; conflicts: number }> {2803  // DESIGN: last-write-wins is applied PER-ENTRY, not per-field. If two devices2804  // concurrently edit different fields of the same entry, the one with the2805  // newer modifiedAt wins the whole entry and the other device's field edits2806  // are dropped silently. This is the deliberate trade-off for a simple,2807  // conflict-free merge — per-field CRDT merge is out of scope. Guidance for2808  // users: edit a given entry on one device at a time.2809  if (!derivedKey || vaultMode === "decoy") throw new Error("vault_locked");28102811  const received = remoteEntries.length + Object.keys(remoteTombstones).length;2812  let applied = 0;2813  let conflicts = 0;28142815  const byId = new Map<string, VaultEntry>();2816  for (const e of entries) byId.set(e.id, e);28172818  const mergeNow = Date.now();2819  const remoteTombstoneTimes = new Map<string, number>();2820  for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2821    if (typeof rawDeletedAt === "number" && Number.isFinite(rawDeletedAt) && rawDeletedAt > 0) {2822      remoteTombstoneTimes.set(id, clampSyncTimestamp(rawDeletedAt, mergeNow));2823    }2824  }28252826  for (const remote of remoteEntries) {2827    const sanitized = sanitizeRestoredEntry(remote);2828    if (!sanitized) continue;2829    // HV-1a: a far-future remote modifiedAt must not permanently pin a2830    // malicious value against honest local edits. Clamp BEFORE any2831    // comparison against local timestamps.2832    sanitized.modifiedAt = clampSyncTimestamp(sanitized.modifiedAt, mergeNow);2833    if (typeof sanitized.deletedAt === "number") {2834      sanitized.deletedAt = clampSyncTimestamp(sanitized.deletedAt, mergeNow);2835    }2836    const remoteTombstoneTs = remoteTombstoneTimes.get(sanitized.id);2837    const localTombstoneTs = tombstones.get(sanitized.id);2838    const tombstoneTs = Math.max(remoteTombstoneTs ?? 0, localTombstoneTs ?? 0);2839    if (tombstoneTs > 0 && tombstoneTs >= sanitized.modifiedAt) {2840      continue;2841    }2842    const local = byId.get(sanitized.id);2843    if (!local) {2844      entries.push(sanitized);2845      byId.set(sanitized.id, sanitized);2846      tombstones.delete(sanitized.id);2847      applied += 1;2848    } else if (sanitized.modifiedAt > local.modifiedAt) {2849      const idx = entries.findIndex((e) => e.id === local.id);2850      if (idx !== -1) {2851        entries[idx] = sanitized;2852        byId.set(sanitized.id, sanitized);2853        tombstones.delete(sanitized.id);2854        applied += 1;2855        if (!local.deletedAt) conflicts += 1;2856      }2857    }2858  }28592860  for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2861    if (typeof rawDeletedAt !== "number" || !Number.isFinite(rawDeletedAt) || rawDeletedAt <= 0) continue;2862    // HV-1a/1c: clamp the tombstone timestamp before every comparison.2863    const deletedAt = remoteTombstoneTimes.get(id)!;2864    const knownTombstone = tombstones.get(id);2865    if (knownTombstone !== undefined && knownTombstone >= deletedAt) continue;2866    const local = byId.get(id);2867    if (!local) {2868      tombstones.set(id, deletedAt);2869      applied += 1;2870      continue;2871    }2872    if (local.deletedAt && local.deletedAt >= deletedAt) continue;2873    if (deletedAt < local.modifiedAt) continue;2874    const idx = entries.findIndex((e) => e.id === id);2875    if (idx !== -1) {2876      entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };2877      tombstones.set(id, deletedAt);2878      applied += 1;2879    }2880  }28812882  if (applied > 0 && vaultMode === "real") {2883    await persistEntries("sync_received");2884    buildDomainIndexSync(entries);2885    // An open popup holds the entries it loaded at mount and polls nothing, so2886    // a background round (the relay listener responding to a peer's push, or the2887    // alarm-driven dial) otherwise lands silently and the user sees stale data2888    // until they reopen. Best-effort: no popup listening is the normal case.2889    try {2890      void chrome.runtime2891        .sendMessage({ type: "VAULT_ENTRIES_CHANGED" })2892        .catch(() => undefined);2893    } catch {2894      // messaging unavailable2895    }2896  }2897  return { received, applied, conflicts };2898}28992900export async function restoreEntry(id: string): Promise<void> {2901  if (!derivedKey) throw new Error("vault_locked");2902  const entry = entries.find((e) => e.id === id && e.deletedAt);2903  if (!entry) throw new Error("deleted entry not found");2904  const previousDeletedAt = entry.deletedAt;2905  const previousModifiedAt = entry.modifiedAt;2906  const previousTombstone = tombstones.get(id);2907  delete entry.deletedAt;2908  entry.modifiedAt = monotonicEntryTimestamp(Math.max(2909    entry.modifiedAt,2910    previousTombstone ?? 0,2911  ));2912  tombstones.delete(id);2913  try {2914    await persistEntries();2915  } catch (err) {2916    entry.deletedAt = previousDeletedAt;2917    entry.modifiedAt = previousModifiedAt;2918    if (previousTombstone !== undefined) tombstones.set(id, previousTombstone);2919    throw err;2920  }2921  buildDomainIndexSync(entries);2922}29232924export async function purgeEntry(id: string): Promise<void> {2925  if (!derivedKey) throw new Error("vault_locked");2926  const idx = entries.findIndex((e) => e.id === id && e.deletedAt);2927  if (idx === -1) throw new Error("deleted entry not found");2928  const entry = entries[idx]!;2929  tombstones.set(id, Math.max(tombstones.get(id) ?? 0, entry.deletedAt!));2930  entries.splice(idx, 1);2931  await persistEntries();2932}29332934/** Permanently delete entries whose deletedAt is older than retentionMs. 0 = keep forever. */2935export async function purgeExpiredTrash(retentionMs: number): Promise<number> {2936  if (!derivedKey || retentionMs === 0) return 0;2937  const cutoff = Date.now() - retentionMs;2938  const before = entries.length;2939  for (const entry of entries) {2940    if (entry.deletedAt && entry.deletedAt < cutoff) {2941      tombstones.set(entry.id, Math.max(tombstones.get(entry.id) ?? 0, entry.deletedAt));2942    }2943  }2944  entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));2945  const purged = before - entries.length;2946  if (purged > 0) await persistEntries();2947  return purged;2948}29492950export function queryDomain(domain: string): VaultEntry[] {2951  return domainIndex.get(domain) ?? [];2952}29532954export function getEntryById(id: string): VaultEntry | undefined {2955  return entries.find((entry) => entry.id === id && !entry.deletedAt);2956}29572958async function persistSlotA(2959  reason: VaultSnapshot["reason"] = "local_save",2960): Promise<StoredVault> {2961  if (!derivedKey) throw new Error("vault_locked");2962  const epoch = vaultEpoch;2963  const throwIfStale = () => {2964    if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");2965  };29662967  const slotA = await loadSlot(SLOT_A);2968  throwIfStale();2969  if (!slotA) throw new Error("missing slot A");29702971  // Snapshot the about-to-be-overwritten state BEFORE we mutate disk. Failures2972  // are swallowed by takeVaultSnapshot — history must never block a save.2973  await takeVaultSnapshot(reason);2974  throwIfStale();29752976  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);2977  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");2978  throwIfStale();29792980  // Preserve existing recovery escrow fields.2981  const nextSlotA: StoredVault = {2982    ...slotA,2983    nonce,2984    ciphertext,2985    tag,2986    // recovery_salt and recovery_wrapped_root_key are already set from loadSlot2987  };29882989  // Slot A (the real vault) is now committed. Wrap every later write so a2990  // mid-persist failure (e.g. a storage error after slot A landed) restores the2991  // prior slot A before rethrowing. Without this, a "failed" save that already2992  // wrote slot A leaves disk ahead of the in-memory rollback in addEntry/2993  // updateEntry/deleteEntry — the entry stays silently on disk and resurfaces2994  // as a duplicate on the next unlock (observed under storage-quota pressure).2995  let slotACommitted = false;2996  try {2997    throwIfStale();2998    await writeSlot(SLOT_A, nextSlotA);2999    slotACommitted = true;3000    throwIfStale();30013002    // When duress is not configured, keep slot B size-matched with slot A by3003    // regenerating its noise. When duress IS configured, leave slot B alone —3004    // we don't have the decoy key to re-encrypt it. This is a known trade-off.3005    if (!duressConfigured) {3006      throwIfStale();3007      await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3008      throwIfStale();3009    }3010    // Only advance the vault version for locally-originated writes. Entries3011    // applied from a sync peer ("sync_received") must NOT bump the counter —3012    // otherwise applying a remote round makes us look newer than the peer and3013    // triggers a redundant outbound sync, defeating the no-op optimisation3014    // and risking a ping-pong between two devices (SEV-2-C).3015    if (reason !== "sync_received") {3016      throwIfStale();3017      await stampLocalVaultMutation();3018      throwIfStale();3019    }3020  } catch (err) {3021    // Best-effort restore — the prior slot A is smaller-or-equal, so this write3022    // fits even when the failure was a quota overflow.3023    if (slotACommitted) await writeSlot(SLOT_A, slotA).catch(() => {});3024    if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3025    throw err;3026  }30273028  return nextSlotA;3029}30303031async function persistSlotB(): Promise<void> {3032  if (!derivedKey) throw new Error("vault_locked");30333034  const slotB = await loadSlot(SLOT_B);3035  if (!slotB) throw new Error("missing slot B");30363037  // Decoy plaintext always reports duressConfigured=false — the decoy user3038  // sees a clean slate. persistSlotB only runs in decoy mode, which only3039  // exists once duress is configured, so pad to the fixed duress ceiling to3040  // keep slot B's length equal to slot A's (audit MEDIUM — deniability).3041  const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);3042  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");30433044  await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });3045  // Symmetric with persistSlotA: if the version stamp fails after the decoy3046  // slot committed, restore the prior slot B so a failed decoy-mode save can't3047  // leave disk ahead of the in-memory rollback.3048  try {3049    await stampLocalVaultMutation();3050  } catch (err) {3051    await writeSlot(SLOT_B, slotB).catch(() => {});3052    throw err;3053  }3054}30553056async function persistEntries(3057  reason: VaultSnapshot["reason"] = "local_save",3058): Promise<void> {3059  if (!derivedKey) throw new Error("vault_locked");30603061  // Reconcile direct soft-delete callers while restoring the previous map if3062  // storage rejects the save.3063  const previousTombstones = tombstones;3064  tombstones = new Map(tombstones);3065  reconcileTombstones();3066  try {3067    if (vaultMode === "decoy") {3068      await persistSlotB();3069    } else {3070      await persistSlotA(reason);3071    }3072  } catch (err) {3073    tombstones = previousTombstones;3074    throw err;3075  }3076  buildDomainIndexSync(entries);3077  await refreshLockedSyncState();3078}30793080// PB-26-011: drop URLs whose parsed scheme is not http(s) at the storage3081// boundary. Schemeless values (e.g. "github.com") are inert and kept — they3082// pre-date this guard in existing data. Unparseable values are kept: the3083// reviewed render paths never execute them (favicons via _favicon/, domains3084// via tldts); this is defense-in-depth against future sinks.3085function allowHttpUrl(url: string | undefined): string {3086  const trimmed = url?.trim() ?? "";3087  if (!trimmed) return "";3088  try {3089    const parsed = new URL(trimmed);3090    if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return "";3091  } catch {3092    // No scheme to reject.3093  }3094  return trimmed;3095}30963097function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {3098  if (!Array.isArray(values)) return undefined;3099  const seen = new Set<string>();3100  const cleaned: string[] = [];3101  for (const value of values) {3102    const trimmed = typeof value === "string" ? value.trim() : "";3103    if (!trimmed) continue;3104    if (!allowHttpUrl(trimmed)) continue;3105    const key = trimmed.toLowerCase();3106    if (seen.has(key)) continue;3107    seen.add(key);3108    cleaned.push(trimmed);3109  }3110  return cleaned.length > 0 ? cleaned : undefined;3111}31123113function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {3114  const title = entry.title.trim();3115  const type: VaultEntry["type"] = entry.type ?? "login";31163117  if (!title) throw new Error("title is required");31183119  if (entry.passkey) {3120    const p = entry.passkey;3121    if (3122      !p.rpId ||3123      !p.credentialId ||3124      !p.publicKeyCose ||3125      !p.userHandle ||3126      !p.userName ||3127      (p.algorithm !== -7 && p.algorithm !== -8)3128    ) {3129      throw new Error("invalid passkey credential");3130    }3131  }3132  if (type === "card") {3133    if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {3134      throw new Error("cardholder name and card number are required");3135    }3136  }31373138  return {3139    type,3140    title,3141    username: type === "login" ? entry.username?.trim() ?? "" : undefined,3142    email: type === "login" ? entry.email?.trim() || undefined : undefined,3143    password: type === "login" ? entry.password : undefined,3144    url: type === "login" ? allowHttpUrl(entry.url) : undefined,3145    additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,3146    totp: type === "login" ? entry.totp?.trim() || undefined : undefined,3147    // PCH-01-019: preserve non-default TOTP params through batch-add/import so3148    // they are not silently stripped (they fall back to SHA-1/6/30 when absent).3149    totpAlgorithm: type === "login" ? entry.totpAlgorithm : undefined,3150    totpDigits: type === "login" ? entry.totpDigits : undefined,3151    totpPeriod: type === "login" ? entry.totpPeriod : undefined,3152    notes: entry.notes?.trim() || undefined,3153    breach: type === "login" ? entry.breach : undefined,3154    // PCH-01-016: the batch-add path was bypassing the MV-6 canary/tags3155    // whitelist applied on the RESTORE_ENTRIES path. Run both sanitizers here.3156    canary: type === "login" ? sanitizeCanary(entry.canary) : undefined,3157    tags: sanitizeTags(entry.tags),3158    passkey: entry.passkey,3159    cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,3160    cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,3161    expMonth: type === "card" ? entry.expMonth?.trim() : undefined,3162    expYear: type === "card" ? entry.expYear?.trim() : undefined,3163    cvc: type === "card" ? entry.cvc?.trim() : undefined,3164    cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,3165    network: type === "card" ? entry.network : undefined,3166    last4: type === "card" ? entry.last4?.trim() : undefined,3167  };3168}31693170function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {3171  const nextPatch: Partial<VaultEntry> = {};31723173  if ("type" in patch) {3174    nextPatch.type = patch.type;3175  }31763177  if ("title" in patch) {3178    const title = patch.title?.trim() ?? "";3179    if (!title) throw new Error("title is required");3180    nextPatch.title = title;3181  }31823183  if ("url" in patch) {3184    nextPatch.url = allowHttpUrl(patch.url);3185  }31863187  if ("additionalUrls" in patch) {3188    const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];3189    const seen = new Set<string>();3190    const cleaned: string[] = [];3191    for (const value of incoming) {3192      const trimmed = typeof value === "string" ? value.trim() : "";3193      if (!trimmed || !allowHttpUrl(trimmed)) continue;3194      const key = trimmed.toLowerCase();3195      if (seen.has(key)) continue;3196      seen.add(key);3197      cleaned.push(trimmed);3198    }3199    nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;3200  }32013202  if ("username" in patch) {3203    nextPatch.username = patch.username?.trim() ?? "";3204  }32053206  if ("email" in patch) {3207    nextPatch.email = patch.email?.trim() || undefined;3208  }32093210  if ("password" in patch) {3211    const password = patch.password ?? "";3212    // Allow clearing a password (e.g. on passkey-only entries)3213    nextPatch.password = password || undefined;3214  }32153216  if ("totp" in patch) {3217    nextPatch.totp = patch.totp?.trim() || undefined;3218  }32193220  if ("totpAlgorithm" in patch) {3221    nextPatch.totpAlgorithm = patch.totpAlgorithm;3222  }32233224  if ("totpDigits" in patch) {3225    nextPatch.totpDigits = patch.totpDigits;3226  }32273228  if ("totpPeriod" in patch) {3229    nextPatch.totpPeriod = patch.totpPeriod;3230  }32313232  if ("notes" in patch) {3233    nextPatch.notes = patch.notes?.trim() || undefined;3234  }32353236  if ("breach" in patch) {3237    nextPatch.breach = patch.breach;3238  }32393240  if ("canary" in patch) {3241    // PCH-02-001: route update patches through the same canary whitelist used3242    // by add/restore/sync. Invalid shapes drop the canary; `undefined` clears it.3243    nextPatch.canary = patch.canary ? sanitizeCanary(patch.canary) : undefined;3244  }32453246  if ("passkey" in patch) {3247    // A patch with `passkey: undefined` removes the credential from the entry3248    // (used by "remove passkey" without deleting the whole entry).3249    if (patch.passkey === undefined || patch.passkey === null) {3250      nextPatch.passkey = undefined;3251    } else {3252      const sanitized = sanitizePasskey(patch.passkey);3253      if (!sanitized) throw new Error("invalid passkey credential");3254      nextPatch.passkey = sanitized;3255    }3256  }32573258  if ("tags" in patch) {3259    // PCH-02-001: bound tags exactly like both import funnels.3260    nextPatch.tags = sanitizeTags(patch.tags);3261  }32623263  if ("cardholderName" in patch) {3264    nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;3265  }3266  if ("cardNumber" in patch) {3267    const n = patch.cardNumber ?? "";3268    nextPatch.cardNumber = n || undefined;3269  }3270  if ("expMonth" in patch) {3271    nextPatch.expMonth = patch.expMonth?.trim() || undefined;3272  }3273  if ("expYear" in patch) {3274    nextPatch.expYear = patch.expYear?.trim() || undefined;3275  }3276  if ("cvc" in patch) {3277    nextPatch.cvc = patch.cvc?.trim() || undefined;3278  }3279  if ("cardNickname" in patch) {3280    nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;3281  }3282  if ("network" in patch) {3283    nextPatch.network = patch.network;3284  }3285  if ("last4" in patch) {3286    nextPatch.last4 = patch.last4?.trim() || undefined;3287  }32883289  return nextPatch;3290}32913292function normalizeEntry(entry: VaultEntry): VaultEntry {3293  const base: VaultEntry = {3294    id: entry.id,3295    type: entry.type,3296    title: entry.title,3297    username: entry.username,3298    email: entry.email,3299    password: entry.password,3300    url: entry.url,3301    additionalUrls:3302      "additionalUrls" in entry && Array.isArray(entry.additionalUrls)3303        ? entry.additionalUrls3304        : undefined,3305    totp: entry.totp,3306    // PCH-01-019: carry TOTP params through the normalize/restore path too.3307    totpAlgorithm: entry.totpAlgorithm,3308    totpDigits: entry.totpDigits,3309    totpPeriod: entry.totpPeriod,3310    notes: entry.notes,3311    breach: entry.breach,3312    // Preserve the password-age clock across lock/unlock. Without this the3313    // field is dropped on every decode and the advanced-health "aged password"3314    // signal silently resets to createdAt on each unlock (SEV-2-A).3315    passwordChangedAt:3316      "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,3317    // Preserve past-password history across lock/unlock. normalizeEntry is a3318    // field whitelist, so an unlisted field is silently dropped on every decode3319    // (same class as the passwordChangedAt SEV-2-A above).3320    passwordHistory:3321      "passwordHistory" in entry && Array.isArray(entry.passwordHistory)3322        ? entry.passwordHistory3323        : undefined,3324    canary: entry.canary,3325    passkey: entry.passkey,3326    createdAt: entry.createdAt,3327    modifiedAt: entry.modifiedAt,3328    deletedAt: entry.deletedAt,3329    tags: entry.tags,3330    cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,3331    cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,3332    expMonth: "expMonth" in entry ? entry.expMonth : undefined,3333    expYear: "expYear" in entry ? entry.expYear : undefined,3334    cvc: "cvc" in entry ? entry.cvc : undefined,3335    cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,3336    network: "network" in entry ? entry.network : undefined,3337    last4: "last4" in entry ? entry.last4 : undefined,3338  };33393340  return base;3341}334233433344// ---------------------------------------------------------------------------3345// Deduplication3346// ---------------------------------------------------------------------------33473348function entryDupeKey(e: VaultEntry): string {3349  if (e.type === "note") return `note|${e.title.toLowerCase()}`;3350  // Passkey-bearing entries dedupe by the credential's RP + user. Two logins3351  // on different sites that happen to share a username are still distinct;3352  // two passkey credentials for the same RP+user are duplicates regardless3353  // of any login fields they may also carry.3354  if (e.passkey) {3355    return `passkey|${e.passkey.rpId.toLowerCase()}|${e.passkey.userName.toLowerCase()}`;3356  }3357  return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;3358}33593360/** Returns the number of duplicate entries (those that would be removed). */3361export function countDuplicates(): number {3362  const best = new Map<string, VaultEntry>();3363  let dupeCount = 0;3364  for (const e of entries.filter((e) => !e.deletedAt)) {3365    const key = entryDupeKey(e);3366    const existing = best.get(key);3367    if (!existing) {3368      best.set(key, e);3369    } else {3370      dupeCount++;3371      // Keep the more recently modified one in the map3372      if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3373        best.set(key, e);3374      }3375    }3376  }3377  return dupeCount;3378}33793380/**3381 * Soft-deletes duplicate entries, keeping the most recently modified copy of3382 * each group. Returns the number of entries moved to trash.3383 */3384export async function deduplicateEntries(): Promise<number> {3385  if (!derivedKey) throw new Error("vault_locked");3386  // Dedup reshapes slot B permanently under the decoy key, which is3387  // forensically distinguishable from a freshly-seeded decoy vault. Refuse.3388  if (vaultMode === "decoy") {3389    throw new Error("deduplicate disabled in decoy mode");3390  }33913392  const best = new Map<string, VaultEntry>();3393  for (const e of entries.filter((en) => !en.deletedAt)) {3394    const key = entryDupeKey(e);3395    const existing = best.get(key);3396    if (!existing) {3397      best.set(key, e);3398    } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3399      best.set(key, e);3400    }3401  }34023403  const keepIds = new Set(Array.from(best.values()).map((e) => e.id));3404  let removed = 0;3405  entries = entries.map((e) => {3406    if (!e.deletedAt && !keepIds.has(e.id)) {3407      removed++;3408      const deletedAt = monotonicEntryTimestamp(Math.max(3409        e.modifiedAt,3410        tombstones.get(e.id) ?? 0,3411      ));3412      tombstones.set(e.id, deletedAt);3413      return { ...e, deletedAt };3414    }3415    return e;3416  });34173418  if (removed > 0) await persistEntries();3419  return removed;3420}34213422// ---------------------------------------------------------------------------3423// Vault history — snapshot BEFORE every vault write so the saved blob is3424// what is about to be lost, not what was just written. Capped at 5. The3425// stored blobs are AES-256-GCM ciphertext under the master password, so3426// history adds zero security surface.3427// ---------------------------------------------------------------------------34283429const HISTORY_KEY = "peach_vault_history";3430const HISTORY_MAX = 5;34313432// PCH-01-023: coarsen a live-entry count into a low-resolution bucket so the3433// plaintext snapshot field cannot reveal exact vault size or single-entry change3434// deltas. Buckets widen as the vault grows so absolute leakage stays roughly3435// proportional rather than exact.3436function bucketEntryCount(n: number): number {3437  if (n <= 0) return 0;3438  if (n <= 10) return 10;3439  if (n <= 25) return 25;3440  if (n <= 50) return 50;3441  if (n <= 100) return 100;3442  if (n <= 250) return 250;3443  if (n <= 500) return 500;3444  return Math.ceil(n / 500) * 500;3445}34463447/**3448 * Snapshot the CURRENT on-disk vault state into history. Call this BEFORE3449 * overwriting peach_vault_a so the saved blob captures the about-to-be-lost3450 * state. Identical-to-most-recent blobs are skipped to avoid filling history3451 * with no-op writes.3452 */3453export async function takeVaultSnapshot(3454  reason: VaultSnapshot["reason"],3455): Promise<void> {3456  if (recoveryInFlight) return;3457  // The history store is real-mode state by construction, so it must not be3458  // written from a decoy session either. The guard lives here rather than only3459  // at the call sites so the invariant survives a new caller (PB-26-915).3460  if (vaultMode === "decoy") return;3461  try {3462    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);3463    const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];3464    const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];34653466    // Nothing to snapshot if the real slot doesn't exist yet (fresh install,3467    // pre-createVault). createVault skips snapshots intentionally — there is3468    // no prior state to preserve.3469    if (!slotA) return;34703471    const vault_a = JSON.stringify(slotA);3472    const vault_b = JSON.stringify(slotB ?? slotA);34733474    // Best-effort entry count: only meaningful when the in-memory state is3475    // unlocked AND in real mode. Decoy mode would leak the decoy entry3476    // count; locked mode has no entries to count. Both fall through to null.3477    // PCH-01-023: store a coarse bucket, not the exact count — chrome.storage3478    // .local sits next to the AES-GCM blobs in plaintext, so an exact count would3479    // leak vault size and per-write deltas (the metadata padding hides this).3480    let entryCount: number | null = null;3481    if (derivedKey && vaultMode === "real") {3482      try {3483        entryCount = bucketEntryCount(entries.filter((e) => !e.deletedAt).length);3484      } catch {3485        entryCount = null;3486      }3487    }34883489    const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];3490    const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)3491      ? existingRaw3492      : { snapshots: [] };34933494    // Deduplication: if the most recent snapshot has byte-identical blobs,3495    // skip — saves the same vault N times in a row would otherwise burn the3496    // entire history window with no recovery value.3497    const latest = history.snapshots[0];3498    if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {3499      return;3500    }35013502    const snapshot: VaultSnapshot = {3503      id: crypto.randomUUID(),3504      savedAt: Date.now(),3505      reason,3506      vault_a,3507      vault_b,3508      entryCount,3509    };35103511    history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);3512    if (recoveryInFlight) return;3513    await chrome.storage.local.set({ [HISTORY_KEY]: history });3514  } catch (err) {3515    // Non-fatal — history must never block a save. A failed snapshot just3516    // means the user loses one rung of the safety ladder for this write.3517    // M4/QUA-006: log so the failure is visible; if it looks like a quota3518    // problem, notify the popup so the user can prune history themselves.3519    console.warn('[Peach] takeVaultSnapshot failed:', err);3520    if (String(err).includes('QUOTA') || String(err).includes('quota')) {3521      try {3522        await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });3523      } catch {3524        // popup may be closed; surfaced via console.warn above3525      }3526    }3527  }3528}35293530/** Wipe all vault history. Called by Panic / DESTROY_VAULT. */3531export async function clearVaultHistory(): Promise<void> {3532  if (recoveryInFlight) throw new Error("recovery_in_progress");3533  try {3534    await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });3535  } catch {3536    // Non-fatal — DESTROY_VAULT also runs storage.local.clear().3537  }3538}35393540/** Read all snapshots, newest first, for the Settings vault history view. */3541export async function getVaultHistory(): Promise<VaultSnapshot[]> {3542  if (vaultMode === "decoy") return [];3543  const raw = await chrome.storage.local.get(HISTORY_KEY);3544  const value = (raw as Record<string, unknown>)[HISTORY_KEY];3545  return sanitizeHistory(value);3546}35473548/**3549 * Replace the on-disk vault with the chosen snapshot's blobs and lock the3550 * vault. The current state is itself snapshotted before replacement.3551 */3552export async function restoreVaultSnapshot(3553  snapshotId: string,3554): Promise<{ ok: true } | { ok: false; error: string }> {3555  if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight) return { ok: false, error: "vault_changed" };3556  vaultReplacementInFlight = true;3557  try {3558    if (vaultMode === "decoy") return { ok: false, error: "vault_locked" };3559    const history = await getVaultHistory();3560    const snapshot = history.find((s) => s.id === snapshotId);3561    if (!snapshot) return { ok: false, error: "snapshot_not_found" };35623563    const restoredA = parseHistorySlot(snapshot.vault_a);3564    const restoredB = parseHistorySlot(snapshot.vault_b);3565    if (!restoredA || !restoredB) return { ok: false, error: "snapshot_corrupt" };35663567    await takeVaultSnapshot("restore");3568    const current = await chrome.storage.local.get([SLOT_A, SLOT_B]);3569    const previousA = (current as Record<string, unknown>)[SLOT_A];3570    const previousB = (current as Record<string, unknown>)[SLOT_B];3571    try {3572      if (recoveryInFlight || vaultRemovalsInFlight) return { ok: false, error: "recovery_in_progress" };3573      await chrome.storage.local.set({ [SLOT_A]: restoredA, [SLOT_B]: restoredB });3574      await stampLocalVaultMutation();3575    } catch {3576      try {3577        await chrome.storage.local.set({ [SLOT_A]: previousA, [SLOT_B]: previousB });3578      } catch {3579        // Preserve the restore failure if storage cannot complete the rollback.3580      }3581      return { ok: false, error: "snapshot_corrupt" };3582    }35833584    await lock();3585    return { ok: true };3586  } finally {3587    vaultReplacementInFlight = false;3588  }3589}35903591/**3592 * Rotate the vault's sync identity by generating a FRESH ROOT KEY and3593 * re-wrapping everything under it (MV-8). Because every sync credential —3594 * vault_id, the Noise static keypair, the Ed25519 manifest signing key,3595 * and the per-entry envelope keys — derives from the root key, rotation3596 * makes a lost/stolen device's retained key material useless. All paired3597 * devices must re-pair afterwards.3598 *3599 * CONSEQUENCE THE UI MUST SURFACE: the 12 recovery words also derive from3600 * the root key, so rotation INVALIDATES the old recovery phrase. The flow3601 * sets peach_recovery_pending so the popup re-presents the new words for3602 * confirmation, same as the initial recovery-word confirmation path.3603 */3604export async function rotateSyncIdentity(): Promise<{ ok: boolean; error?: string }> {3605  if (!derivedKey || vaultMode !== "real") {3606    return { ok: false, error: "vault_locked" };3607  }3608  const slotA = await loadSlot(SLOT_A);3609  if (!slotA) return { ok: false, error: "missing_slot_a" };36103611  // 1. Fresh root key + recovery escrow (new words).3612  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =3613    await generateAndWrapRootKey();36143615  // 2. Re-wrap the new root key under the current password-derived key.3616  const newRootKey = unhex(rawRootKey);3617  const recoveryVaultKey = await encrypt(newRootKey, hex(derivedKey), "recovery_vault_key_v1");3618  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, newRootKey);36193620  // 3. Snapshot, then single atomic slot write — both escrow wrappings of3621  //    the new root key land together (same transactional rule as3622  //    changePassword). Entries are untouched: they are sealed under the3623  //    password-derived key, not the root key.3624  await takeVaultSnapshot("local_save");3625  const nextSlotA: StoredVault = {3626    ...slotA,3627    recovery_vault_key: recoveryVaultKey,3628    recovery_salt: recoverySalt,3629    recovery_wrapped_root_key: wrappedRootKey,3630    recovery_nonce: wrappedNonce,3631    recovery_tag: wrappedTag,3632    ...pwRoot,3633  };3634  await writeSlot(SLOT_A, nextSlotA);36353636  // 4. Swap in memory only after disk committed.3637  if (rootKey) zeroKey(rootKey);3638  rootKey = newRootKey;36393640  // 4b. The identity's root wrap was encrypted under the dead root. Without3641  //     this the identity survives only until the unlock key also changes.3642  await notifyIdentityKeysRotated();36433644  // 5. Old peers' identities derive from the dead root key — drop them all,3645  // with their rendezvous secrets (PB-26-213: rotation clears the map, so3646  // there is nothing to rewrap under the new key).3647  await clearPairedDevices();3648  await clearPairSecrets();36493650  // 6. Force re-presentation of the NEW recovery words on next popup view.3651  await setRecoveryConfirmPending(); // same flag the create-vault flow uses36523653  await stampLocalVaultMutation();3654  return { ok: true };3655}36563657/**3658 * Change the master password. Re-encrypts slot A with a fresh salt + new3659 * derived key. Slot B (duress or noise) is left untouched when duress is3660 * configured — it uses an independent key derived from the duress password —3661 * and regenerated as noise when duress is not configured.3662 */3663export async function changePassword(3664  currentPassword: string,3665  newPassword: string3666): Promise<boolean> {3667  const epoch = vaultEpoch;3668  const stale = () => epoch !== vaultEpoch;3669  if (!derivedKey || vaultMode !== "real") return false;36703671  // Verify current password before allowing any change3672  const valid = await verifyMainPassword(currentPassword);3673  if (!valid) return false;36743675  const slotA = await loadSlot(SLOT_A);3676  if (!slotA) return false;3677  if (!rootKey) return false;36783679  // Derive fresh key from new password + new random salt3680  const newSalt = generateSalt();3681  const newKey = await deriveKey(newPassword, newSalt);3682  if (stale()) {3683    zeroKey(newKey);3684    return false;3685  }36863687  // Re-encrypt the in-memory entries with the new key3688  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3689  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");36903691  // Pre-wrap root key under the new derived key. Recovery fields wrap rootKey3692  // under recovery words and remain untouched — recovery phrase keeps working3693  // across password changes (H4/COR-002).3694  const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);36953696  const recoveryVaultKey = await encrypt(rootKey, hex(newKey), "recovery_vault_key_v1");3697  const finalSlotA: StoredVault = {3698    ...slotA,3699    recovery_vault_key: recoveryVaultKey,3700    salt: hex(newSalt),3701    nonce,3702    ciphertext,3703    tag,3704    ...pwRoot,3705  };37063707  // Snapshot the OLD-key blob before overwriting it. If the user later3708  // restores from this snapshot they will need the OLD password — the3709  // post-restore lock surfaces that immediately.3710  await takeVaultSnapshot("local_save");37113712  // Single atomic write: ciphertext, salt, and pw_root_* fields all land in3713  // one storage transaction. An SW kill before this point leaves the old3714  // slot intact; after this point everything tied to the new password is3715  // already on disk together (M6/COR-004).3716  await writeSlot(SLOT_A, finalSlotA);3717  if (stale()) {3718    zeroKey(newKey);3719    return false;3720  }37213722  // Swap the in-memory key synchronously before any further await. If we3723  // threw between the Slot A write and this swap, the next persistEntries()3724  // would overwrite Slot A with old-key ciphertext, locking the user out.3725  zeroKey(derivedKey);3726  derivedKey = newKey;37273728  // PCH-01-008: the MV3 session escrow still holds the OLD key. Without this,3729  // the next service-worker restore decrypts the new-key Slot A with the stale3730  // key, fails tryDecryptSlotResult, and silently drops the user to a lock3731  // screen. Re-escrow the new key so restore survives a password change.3732  if (stale()) {3733    await lock();3734    return false;3735  }3736  await saveSessionKey(newKey, "real", epoch);3737  if (stale()) return false;37383739  // The identity envelope holds one wrap per recovering key. Swapping the3740  // unlock key kills the local wrap, so re-wrap now or the next key swap3741  // orphans the identity -- and until then the old password still opens it.3742  await notifyIdentityKeysRotated();3743  if (stale()) return false;37443745  // Regenerate noise for slot B when duress is not in use. Runs after the3746  // key swap so a failure here is a disposable noise regeneration, not a3747  // lockout.3748  if (!duressConfigured) {3749    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3750  }3751  await clearPinUnlockStorage();3752  await stampLocalVaultMutation();37533754  return true;3755}