vault.ts

116.8 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  SavedIdentity,31  StoredVault,32  VaultEntry,33  VaultHistory,34  VaultSnapshot,35} from "../shared/types";36import { decrypt, encrypt, zeroKey } from "./aes";37import { clearAutoLock, touchAutoLock } from "./alarms";38import {39  clearRecoveryConfirmPending,40  setRecoveryConfirmPending,41} from "./recovery-pending";4243type EntryDraft = Omit<44  VaultEntry,45  "id" | "createdAt" | "modifiedAt" | "deletedAt"46>;4748// Slot-neutral storage keys (v1.4.24+). Both slots always exist; slot B49// either holds the decoy vault (when duress is configured) or random noise50// that looks identical at rest. No external indicator is stored — duress51// configuration is recorded only inside the encrypted payload of slot A.52const SLOT_A = "peach_vault_a";53const SLOT_B = "peach_vault_b";5455// Plaintext is padded to the next multiple of this size before encryption.56// This coarsens ciphertext-length leakage into 1 KiB buckets.57const PAD_BLOCK = 1024;5859// How many past passwords to retain per entry. Generous enough to be useful as60// a recovery aid while bounding the secret material we hold (and the ciphertext61// growth) for an entry whose password is rotated frequently.62const PASSWORD_HISTORY_MAX = 50;6364// When duress is configured, BOTH slots are padded to this fixed ceiling so65// their ciphertext lengths are identical and cannot reveal that a hidden decoy66// vault exists (audit MEDIUM — plausible-deniability leak). 256 KiB comfortably67// holds a very large vault (thousands of entries incl. passkeys). The decoy68// slot can't be re-encrypted on every real-vault save (the real session has no69// decoy key), so a fixed ceiling — rather than size-matching on each write — is70// what keeps the two slots equal. A real vault whose plaintext exceeds this71// would grow past the ceiling and re-expose the bit; that is an extreme,72// documented edge well beyond normal use.73const DURESS_SLOT_SIZE = 262_144;7475let derivedKey: Uint8Array | null = null;76// 32-byte random root key, separate from the derivedKey used for vault encryption.77// The root key is wrapped (encrypted) under the recovery key derived from the78// 12-word phrase. When the user changes their password, only the wrapping changes;79// the root key and recovery words remain stable.80let rootKey: Uint8Array | null = null;81let entries: VaultEntry[] = [];82// Tombstones outlive their full entry records so a peer that was offline83// during a purge cannot reintroduce an old ciphertext envelope. This map is84// serialized only inside the encrypted vault payload.85let tombstones = new Map<string, number>();86let domainIndex: Map<string, VaultEntry[]> = new Map();87let vaultMode: "real" | "decoy" = "real";88// Cached post-unlock view of whether the real vault records that duress is89// configured. Only meaningful after a real-mode unlock; for decoy-mode unlock90// this stays false because we never see slot A's plaintext.91let duressConfigured = false;9293// Set to a corruption reason during the last unlock() attempt when both slots94// decrypted but failed schema validation. Consumed and cleared by95// consumeLastUnlockFailureReason() so messages.ts can surface vault_corrupted96// distinctly from wrong-password (M7/COR-007).97//98// NOTE: module-level state — if vault.ts is ever moved to a worker context,99// this must be replaced with a structured return value from unlock() or a100// postMessage channel. The signal is invisible across module-instance101// boundaries.102let lastUnlockFailureReason: string | null = null;103104export function consumeLastUnlockFailureReason(): string | null {105  const r = lastUnlockFailureReason;106  lastUnlockFailureReason = null;107  return r;108}109110// ---------------------------------------------------------------------------111// Settings (persisted inside the encrypted vault store as a sidecar key)112// ---------------------------------------------------------------------------113114export type TextSize = "small" | "medium" | "large";115116export interface VaultSettings {117  accentColor?: AccentColorName;118  theme?: "dark" | "light";119  autoLockMinutes?: number;120  clipboardClearSeconds?: number;121  lockOnClose?: boolean;122  breachMonitoring?: boolean;123  passkeyProviderEnabled?: boolean;124  trashRetentionDays?: number;125  manualSummonDomains?: Record<string, ManualSummonRecord>;126  manualSummonSalt?: string;127  declinedCardFingerprints?: string[];128  cardFingerprintSalt?: string;129130  /** Metadata is bounded because it remains outside the encrypted vault blob. */131  metadataVersion?: 1;132  /**133   * Text size scale for body copy and entry titles. Stops at "large" by134   * design — XL clips dense screens (Vault, Health) inside the fixed135   * 330×480 popup surface.136   */137  textSize?: TextSize;138  /**139   * When true, all entrance/exit transitions and ambient animations are140   * collapsed to instant. Honoured alongside the user's OS-level141   * `prefers-reduced-motion`.142   */143  reduceMotion?: boolean;144  /** Whether this vault has a local PIN unlock wrapper configured. */145  pinEnabled?: boolean;146  /** Whether the lock screen should open on PIN instead of the password. */147  pinPreferred?: boolean;148  /**149   * User overrides for keyboard shortcuts. Keys are ShortcutAction names150   * (see src/shared/shortcuts.ts). Missing actions fall through to151   * DEFAULT_BINDINGS — `getActiveBindings(settings.shortcuts)` is the152   * canonical lookup. Storing only the deltas keeps the vault payload153   * small and lets default updates land for users who never rebind.154   */155  shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;156}157158interface StoredPinWrap {159  version: 1;160  salt: string;161  nonce: string;162  ciphertext: string;163  tag: string;164}165166const PIN_WRAP_STORAGE = "peach_pin_wrap";167const PIN_ATTEMPTS_STORAGE = "peach_pin_attempts";168const PIN_MIN_LENGTH = 4;169const PIN_MAX_LENGTH = 12;170const PIN_MAX_ATTEMPTS = 3;171172let settings: VaultSettings = {};173const CARD_DECLINE_MAX = 256;174const METADATA_SALT_BYTES = 16;175176function randomMetadataSalt(): string {177  return Array.from(crypto.getRandomValues(new Uint8Array(METADATA_SALT_BYTES)))178    .map((byte) => byte.toString(16).padStart(2, "0"))179    .join("");180}181182async function metadataDigest(value: string, salt: string): Promise<string> {183  const bytes = new TextEncoder().encode(`${salt}:${value}`);184  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));185  return Array.from(digest.slice(0, 16)).map((byte) => byte.toString(16).padStart(2, "0")).join("");186}187188let inMemoryPinWrap: StoredPinWrap | null = null;189let inMemoryPinFailedAttempts = 0;190let sessionPinStorageFailed = false;191192export function getSettings(): VaultSettings {193  return settings;194}195196export async function ensureSettingsLoaded(): Promise<VaultSettings> {197  await loadSettings();198  return settings;199}200201export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {202  await loadSettings();203  // LV-7: cheap insurance against prototype pollution if a future caller ever204  // feeds parsed external JSON here (native spread keeps __proto__ an own-205  // property today, but Object.assign-style consumers and JSON revivers have206  // been burned before).207  const safe = Object.fromEntries(208    Object.entries(patch).filter(209      ([k]) => !["__proto__", "constructor", "prototype"].includes(k),210    ),211  ) as Partial<VaultSettings>;212  settings = { ...settings, ...safe };213  await persistSettings();214}215216function isValidPin(pin: string): boolean {217  return new RegExp(`^\\d{${PIN_MIN_LENGTH},${PIN_MAX_LENGTH}}$`).test(pin);218}219220/** Set up a local PIN wrapper after proving the current master password. */221export async function setupPinUnlock(currentPassword: string, pin: string): Promise<boolean> {222  if (!derivedKey || vaultMode !== "real" || !isValidPin(pin)) return false;223  if (!(await verifyMainPassword(currentPassword))) return false;224225  const salt = generateSalt();226  const pinKey = await deriveKey(pin, salt);227  try {228    const wrapped = await encrypt(pinKey, hex(derivedKey), "pin_wrap_v1");229    await savePinWrap({ version: 1, salt: hex(salt), ...wrapped });230    await updateSettings({ pinEnabled: true });231    return true;232  } finally {233    zeroKey(pinKey);234  }235}236237async function clearPinUnlockStorage(): Promise<void> {238  inMemoryPinWrap = null;239  inMemoryPinFailedAttempts = 0;240  sessionPinStorageFailed = false;241  if (chrome.storage.session) {242    await chrome.storage.session.remove([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);243  }244  await updateSettings({ pinEnabled: false });245}246247/** Remove the PIN wrapper after proving the current master password. */248export async function disablePinUnlock(currentPassword: string): Promise<boolean> {249  if (!derivedKey || vaultMode !== "real") return false;250  if (!(await verifyMainPassword(currentPassword))) return false;251  await clearPinUnlockStorage();252  return true;253}254255/** Unlock the real vault from its locally stored PIN-wrapped derived key. */256export async function unlockWithPin(pin: string): Promise<boolean> {257  if (!isValidPin(pin)) return false;258  await loadSettings();259  if (!settings.pinEnabled) return false;260261  const { stored, failedAttempts } = await loadPinState();262  if (failedAttempts >= PIN_MAX_ATTEMPTS) return false;263  if (264    !stored ||265    stored.version !== 1 ||266    !stored.salt ||267    !stored.nonce ||268    !stored.ciphertext ||269    !stored.tag270  ) return false;271272  const pinKey = await deriveKey(pin, unhex(stored.salt));273  let unwrappedKey: Uint8Array | null = null;274  try {275    const masterKeyHex = await decrypt(276      pinKey,277      stored.nonce,278      stored.ciphertext,279      stored.tag,280      "pin_wrap_v1",281    );282    if (!/^[0-9a-f]{64}$/.test(masterKeyHex)) return false;283    unwrappedKey = unhex(masterKeyHex);284    const result = await unlockWithKey(masterKeyHex);285    if (!result.ok) return false;286    await saveSessionKey(unwrappedKey, "real");287    await resetPinFailedAttempts();288    return true;289  } catch {290    await recordPinFailure(failedAttempts + 1);291    return false;292  } finally {293    zeroKey(pinKey);294    if (unwrappedKey) zeroKey(unwrappedKey);295  }296}297298async function savePinWrap(stored: StoredPinWrap): Promise<void> {299  inMemoryPinWrap = stored;300  inMemoryPinFailedAttempts = 0;301  sessionPinStorageFailed = !chrome.storage.session;302  if (!chrome.storage.session) return;303  try {304    await chrome.storage.session.set({ [PIN_WRAP_STORAGE]: stored, [PIN_ATTEMPTS_STORAGE]: 0 });305    sessionPinStorageFailed = false;306  } catch {307    // Firefox fallback: keep the wrapper only in this background context.308    sessionPinStorageFailed = true;309  }310}311312async function loadPinState(): Promise<{313  stored: StoredPinWrap | undefined;314  failedAttempts: number;315}> {316  if (!chrome.storage.session) {317    return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };318  }319  try {320    const result = await chrome.storage.session.get([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);321    return {322      stored: (result[PIN_WRAP_STORAGE] as StoredPinWrap | undefined) ??323        (sessionPinStorageFailed ? inMemoryPinWrap ?? undefined : undefined),324      failedAttempts: typeof result[PIN_ATTEMPTS_STORAGE] === "number"325        ? result[PIN_ATTEMPTS_STORAGE]326        : 0,327    };328  } catch {329    return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };330  }331}332333async function recordPinFailure(failedAttempts: number): Promise<void> {334  inMemoryPinFailedAttempts = Math.min(failedAttempts, PIN_MAX_ATTEMPTS);335  if (!chrome.storage.session) return;336  try {337    await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: inMemoryPinFailedAttempts });338  } catch { /* in-memory counter remains the fallback */ }339}340341async function resetPinFailedAttempts(): Promise<void> {342  inMemoryPinFailedAttempts = 0;343  if (!chrome.storage.session) return;344  try {345    await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: 0 });346  } catch { /* in-memory counter remains the fallback */ }347}348349export async function getPinUnlockStatus(): Promise<{350  configured: boolean;351  available: boolean;352  attemptsRemaining: number;353}> {354  await loadSettings();355  if (!settings.pinEnabled) {356    return { configured: false, available: false, attemptsRemaining: 0 };357  }358  const { stored, failedAttempts } = await loadPinState();359  const available = Boolean(stored) && failedAttempts < PIN_MAX_ATTEMPTS;360  return {361    configured: true,362    available,363    attemptsRemaining: stored ? Math.max(0, PIN_MAX_ATTEMPTS - failedAttempts) : 0,364  };365}366367async function persistSettings(): Promise<void> {368  try {369    const salt = settings.cardFingerprintSalt ?? randomMetadataSalt();370    await chrome.storage.local.set({371      peach_settings: {372        ...settings,373        manualSummonDomains: undefined,374        manualSummonSalt: undefined,375        cardFingerprintSalt: salt,376        declinedCardFingerprints: settings.declinedCardFingerprints ?? [],377        metadataVersion: 1,378      },379    });380  } catch (err) {381    throw mapStorageError(err);382  }383}384385function mapStorageError(err: unknown): Error {386  const message = err instanceof Error ? err.message : String(err);387  if (/QUOTA_BYTES|quota/i.test(message)) {388    return new Error("STORAGE_QUOTA_EXCEEDED");389  }390  return err instanceof Error ? err : new Error(message);391}392393async function loadSettings(): Promise<void> {394  const result = await chrome.storage.local.get("peach_settings");395  settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};396}397398// Fire-and-forget sync trigger after a committed vault write. A failure here399// must never fail the write that caused it.400function fireSyncTrigger(reason: "vault_change"): void {401  void Promise.resolve()402    .then(() => triggerSyncIfReachable({ reason }))403    .catch(() => {404      /* no sync runner registered, or nothing reachable — non-fatal */405    });406}407408let lockedSyncRefreshHook: (() => Promise<void>) | null = null;409let lockedSyncUnlockHook: (() => Promise<void>) | null = null;410411export function setLockedSyncHooks(hooks: {412  refresh: () => Promise<void>;413  afterUnlock: () => Promise<void>;414}): void {415  lockedSyncRefreshHook = hooks.refresh;416  lockedSyncUnlockHook = hooks.afterUnlock;417}418419async function refreshLockedSyncState(): Promise<void> {420  if (vaultMode !== "real" || !rootKey || !lockedSyncRefreshHook) return;421  await lockedSyncRefreshHook().catch((error) => {422    console.warn("[Peach sync] locked spool refresh failed:", error);423  });424}425426// ---------------------------------------------------------------------------427// HIBP breach check (k-anonymity model)428// ---------------------------------------------------------------------------429430export async function checkBreach(password: string): Promise<number> {431  // HIBP k-anonymity API is keyed on SHA-1 prefixes — this is dictated by432  // the public API, not a security choice. Do not migrate to SHA-256 here.433  const encoder = new TextEncoder();434  const hashBuffer = await crypto.subtle.digest("SHA-1", encoder.encode(password));435  const hashHex = Array.from(new Uint8Array(hashBuffer))436    .map((b) => b.toString(16).padStart(2, "0"))437    .join("")438    .toUpperCase();439440  const prefix = hashHex.slice(0, 5);441  const suffix = hashHex.slice(5);442443  try {444    // PCH-02-007: request HIBP response padding so response length does not445    // reveal how many suffixes a queried prefix returned.446    const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`, {447      headers: { "Add-Padding": "true" },448    });449    if (!res.ok) return 0;450    const text = await res.text();451    const match = text.split("\r\n").find((l) => l.startsWith(suffix));452    return match ? parseInt(match.split(":")[1], 10) : 0;453  } catch {454    return 0; // Network unavailable — don't block455  }456}457458export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {459  const fingerprint = await cardFingerprint(last4, expMonth, expYear);460  await loadSettings();461  const salt = settings.cardFingerprintSalt ?? randomMetadataSalt();462  settings = {463    ...settings,464    cardFingerprintSalt: salt,465    declinedCardFingerprints: [466      ...(settings.declinedCardFingerprints ?? []),467      await metadataDigest(fingerprint, salt),468    ].slice(-CARD_DECLINE_MAX),469  };470  await persistSettings();471}472473export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {474  await loadSettings();475  const fingerprint = await cardFingerprint(last4, expMonth, expYear);476  const salt = settings.cardFingerprintSalt;477  if (!salt) return false;478  const candidate = await metadataDigest(fingerprint, salt);479  return (settings.declinedCardFingerprints ?? []).some((stored) => stored === fingerprint || stored === candidate);480}481482async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {483  const encoder = new TextEncoder();484  const buf = await crypto.subtle.digest("SHA-256", encoder.encode(`${last4}|${expMonth}|${expYear}`));485  return Array.from(new Uint8Array(buf).slice(0, 8))486    .map((b) => b.toString(16).padStart(2, "0"))487    .join("");488}489490function hex(buf: Uint8Array): string {491  return Array.from(buf)492    .map((b) => b.toString(16).padStart(2, "0"))493    .join("");494}495496function unhex(s: string): Uint8Array {497  const out = new Uint8Array(s.length / 2);498  for (let i = 0; i < s.length; i += 2) {499    out[i / 2] = parseInt(s.slice(i, i + 2), 16);500  }501  return out;502}503504// ---------------------------------------------------------------------------505// Root key generation and recovery word wrapping506// ---------------------------------------------------------------------------507508/**509 * Generate a random 32-byte root key and wrap it (AES-256-GCM) under a key510 * derived from the recovery word material via HKDF-SHA256. The wrapped blob511 * fields are stored in slot A alongside the password-wrapped ciphertext. The512 * root key itself is kept in memory for the session so getRecoveryWords() can513 * encode it without re-deriving.514 *515 * SECURITY MODEL (PCH-01-005): the recovery KEK is derived from the 12-word516 * material, which encodes only rootKey[0..16] (recovery-words.ts). The KEK is thus517 * derived from a PREFIX of the very plaintext it wraps, and effective recovery518 * security is 128-bit (standard for a 12-word phrase), NOT 256-bit. This is safe —519 * unwrapping requires the words, and the GCM ciphertext leaks nothing without them —520 * but it is intentional, not an oversight. A future escrow version wanting 256-bit521 * recovery must derive the words from INDEPENDENT entropy, not from the root key.522 */523async function generateAndWrapRootKey(): Promise<{524  rawRootKey: string; // hex of the plaintext root key — caller stores in rootKey525  recoverySalt: string;526  wrappedRootKey: string;527  wrappedNonce: string;528  wrappedTag: string;529}> {530  const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));531532  // Derive the recovery key from the BIP39 words encoding of the root key.533  const words = await rootKeyToWords(rootKeyBytes);534  const wordMaterial = await wordsToRootKeyMaterial(words);535  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));536  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);537538  // Wrap the root key with the recovery key using AES-256-GCM directly.539  // We hex-encode rootKeyBytes so the plaintext is always valid UTF-8.540  const nonce = crypto.getRandomValues(new Uint8Array(12));541  const encoded = new TextEncoder().encode(hex(rootKeyBytes));542  const raw = await crypto.subtle.encrypt(543    {544      name: "AES-GCM",545      iv: nonce,546      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,547      tagLength: 128,548    },549    recoveryKey,550    encoded551  );552  // WebCrypto returns ciphertext || auth tag concatenated; split them.553  const rawU8 = new Uint8Array(raw);554  const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));555  const tag = hex(rawU8.slice(rawU8.length - 16));556557  return {558    rawRootKey: hex(rootKeyBytes),559    recoverySalt: hex(recoverySalt),560    wrappedRootKey: ciphertext,561    wrappedNonce: hex(nonce),562    wrappedTag: tag,563  };564}565566async function wrapExistingRootKeyForRecovery(rootKeyBytes: Uint8Array): Promise<{567  recoverySalt: string;568  wrappedRootKey: string;569  wrappedNonce: string;570  wrappedTag: string;571}> {572  if (rootKeyBytes.length !== 32) {573    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");574  }575576  const words = await rootKeyToWords(rootKeyBytes);577  const wordMaterial = await wordsToRootKeyMaterial(words);578  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));579  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);580  const nonce = crypto.getRandomValues(new Uint8Array(12));581  const encoded = new TextEncoder().encode(hex(rootKeyBytes));582  const raw = await crypto.subtle.encrypt(583    {584      name: "AES-GCM",585      iv: nonce,586      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,587      tagLength: 128,588    },589    recoveryKey,590    encoded,591  );592  const rawU8 = new Uint8Array(raw);593  return {594    recoverySalt: hex(recoverySalt),595    wrappedRootKey: hex(rawU8.slice(0, rawU8.length - 16)),596    wrappedNonce: hex(nonce),597    wrappedTag: hex(rawU8.slice(rawU8.length - 16)),598  };599}600601/**602 * Unwrap the root key using recovery words. Called during recovery flow when603 * the user provides their 12-word phrase and a new password.604 * Exported for use by the RECOVER_WITH_WORDS message handler.605 */606export async function unwrapRootKeyForRecovery(607  wrappedRootKey: string,608  wrappedNonce: string,609  wrappedTag: string,610  recoverySaltHex: string,611  words: string[]612): Promise<void> {613  const wordMaterial = await wordsToRootKeyMaterial(words);614  const recoverySalt = unhex(recoverySaltHex);615  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);616617  // Decrypt and cache the root key. The root key bytes were hex-encoded before618  // encryption so the ciphertext is valid UTF-8. We inline the AES-GCM decrypt619  // here to avoid passing a CryptoKey to the string-based encrypt/decrypt helpers.620  // Each component is stored separately in the vault slot; decode them individually621  // so the nonce is always exactly the 12 bytes from wrappedNonce.622  const nonceRaw = unhex(wrappedNonce);623  const ciphertextRaw = unhex(wrappedRootKey);624  const tagRaw = unhex(wrappedTag);625  // Combine ciphertext and tag for AES-GCM (expects ciphertext||tag).626  // Use explicit ArrayBuffer allocations to satisfy TS BufferSource constraints.627  const nonceU8 = nonceRaw as unknown as Uint8Array<ArrayBuffer>;628  const combined = new Uint8Array(ciphertextRaw.length + tagRaw.length);629  combined.set(ciphertextRaw, 0);630  combined.set(tagRaw, ciphertextRaw.length);631  const raw = await crypto.subtle.decrypt(632    { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },633    recoveryKey,634    combined635  );636  const decryptedHex = new TextDecoder().decode(raw);637  rootKey = unhex(decryptedHex);638}639640/**641 * Re-wrap the cached root key under a new derived key (from the user's new642 * password). Called after password change and after recovery re-key so the643 * same recovery words continue to work with the updated password — and so644 * subsequent unlocks can rehydrate rootKey via deriveRootKeyFromDerivedKey.645 *646 * recovery_* fields are intentionally not touched: those wrap rootKey under647 * the recovery words, which do not change when the password changes.648 */649export async function rewrapRootKeyForPassword(650  newDerivedKey: Uint8Array,651  _newSalt: Uint8Array652): Promise<void> {653  if (!rootKey) throw new Error("root key not set");654  const slotA = await loadSlot(SLOT_A);655  if (!slotA) throw new Error("missing slot A");656  const pwRoot = await wrapRootKeyForDerivedKey(newDerivedKey, rootKey);657  await writeSlot(SLOT_A, { ...slotA, ...pwRoot });658}659660/**661 * Change the vault encryption to a new derived key (already derived from662 * the user's new password). Used by RECOVER_WITH_WORDS and changePassword.663 * Caller is responsible for key swap and snapshot.664 */665async function reencryptVaultForNewKey(666  newKey: Uint8Array,667  slotA: StoredVault668): Promise<void> {669  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);670  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");671  await writeSlot(SLOT_A, {672    ...slotA,673    nonce,674    ciphertext,675    tag,676  });677}678679/**680 * Full password change with an already-derived key (used after recovery).681 * Unlike changePassword(), this skips re-verification of current password682 * since recovery flow has already validated the user's identity via words.683 */684export async function changePasswordWithNewKey(685  newSalt: Uint8Array,686  newKey: Uint8Array687): Promise<void> {688  const slotA = await loadSlot(SLOT_A);689  if (!slotA) throw new Error("missing slot A");690  // reencryptVaultForNewKey must receive the updated salt so that subsequent691  // UNLOCK calls with the new password can re-derive the correct key.692  await reencryptVaultForNewKey(newKey, { ...slotA, salt: hex(newSalt) });693  if (derivedKey) zeroKey(derivedKey);694  derivedKey = newKey;695  // PCH-01-008: re-escrow the new key (see changePassword). The recovery flow696  // reaches this path, so a post-recovery SW restart would otherwise lock out697  // a user who just reset their password.698  void saveSessionKey(newKey, "real");699  // Refresh pw_root_* under the new key so deriveRootKeyFromDerivedKey works700  // on the next unlock (H2/COR-006). If rootKey is missing — recovery flow701  // should have populated it — fall back silently rather than blowing up the702  // recovery path; the escrow is already present on every supported vault.703  if (rootKey) {704    const slotAfter = await loadSlot(SLOT_A);705    if (slotAfter) {706      const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);707      await writeSlot(SLOT_A, { ...slotAfter, ...pwRoot });708    }709  }710  if (!duressConfigured) {711    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));712  }713  await clearPinUnlockStorage();714  await stampLocalVaultMutation();715}716717// ---------------------------------------------------------------------------718// Salt generation --- exported so the RECOVER_WITH_WORDS handler can derive719// a new key after password reset without re-importing the crypto module.720// ---------------------------------------------------------------------------721722export { deriveKey, generateSalt };723724export async function loadSlotA(): Promise<StoredVault | null> {725  return loadSlot(SLOT_A);726}727728/**729 * Recover the session root key by AES-GCM-decrypting the pw_root_* fields730 * (a second wrapping of the root key under the password-derived key). This731 * is what makes GET_RECOVERY_WORDS work across lock/unlock cycles without732 * the user re-entering their recovery phrase: the same root key bytes —733 * and therefore the same 12 words — survive every unlock.734 *735 * Returns null when the escrow is absent or decryption fails.736 */737async function deriveRootKeyFromDerivedKey(738  derivedKeyBytes: Uint8Array,739  slotA: StoredVault,740): Promise<Uint8Array | null> {741  if (!slotA.pw_root_ciphertext || !slotA.pw_root_nonce || !slotA.pw_root_tag) {742    return null;743  }744  try {745    const rootHex = await decrypt(746      derivedKeyBytes,747      slotA.pw_root_nonce,748      slotA.pw_root_ciphertext,749      slotA.pw_root_tag,750      "pw_root_v1",751    );752    return unhex(rootHex);753  } catch {754    return null;755  }756}757758// AES-GCM-wrap rootKey under derivedKey for the pw_root_* fields. Returns the759// hex-encoded ciphertext/nonce/tag triple ready to embed in StoredVault.760async function wrapRootKeyForDerivedKey(761  derivedKeyBytes: Uint8Array,762  rootKeyBytes: Uint8Array,763): Promise<{ pw_root_ciphertext: string; pw_root_nonce: string; pw_root_tag: string }> {764  const { nonce, ciphertext, tag } = await encrypt(derivedKeyBytes, hex(rootKeyBytes), "pw_root_v1");765  return {766    pw_root_ciphertext: ciphertext,767    pw_root_nonce: nonce,768    pw_root_tag: tag,769  };770}771772/** Returns the 12 recovery words for the current session's root key. */773export async function getRecoveryWords(): Promise<string[]> {774  if (!rootKey) {775    throw new Error("recovery not set up");776  }777  return rootKeyToWords(rootKey);778}779780async function loadSlot(key: string): Promise<StoredVault | null> {781  const result = await chrome.storage.local.get(key);782  return (result as Record<string, StoredVault | undefined>)[key] ?? null;783}784785async function writeSlot(key: string, vault: StoredVault): Promise<void> {786  try {787    await chrome.storage.local.set({ [key]: vault });788  } catch (err) {789    throw mapStorageError(err);790  }791}792793/**794 * Roll back a vault that was created by [createVaultFromRootKey] but795 * couldn't be paired (e.g. the subsequent license activation, identity796 * derivation, or paired-device upsert failed). Without this, a failed797 * receiver session leaves behind an empty vault — the user has to798 * re-pair to get a working setup, but the empty vault sits in the way.799 *800 * The call is idempotent: removing keys that aren't there is a no-op.801 */802export async function rollbackAdoptedVault(): Promise<void> {803  lock();804  try {805    await chrome.storage.local.remove([806      SLOT_A,807      SLOT_B,808      "peach_last_modified_at",809    ]);810  } catch (err) {811    throw mapStorageError(err);812  }813}814815async function commitCreatedVaultSlots(slotA: StoredVault, slotB: StoredVault): Promise<void> {816  const raw = await chrome.storage.local.get("peach_last_modified_at");817  const previous = Number(818    (raw as Record<string, unknown>).peach_last_modified_at,819  );820  const next = Math.max(821    Date.now(),822    Number.isFinite(previous) ? previous + 1 : 0,823  );824  try {825    await chrome.storage.local.set({826      [SLOT_A]: slotA,827      [SLOT_B]: slotB,828      peach_last_modified_at: String(next),829    });830  } catch (err) {831    throw mapStorageError(err);832  }833}834835// Monotonic clock for per-entry modifiedAt / deletedAt timestamps. Guards the836// sync layer's last-write-wins merge against wall-clock regressions (NTP step,837// manual clock change, DST glitch): a backwards Date.now() must never produce838// an entry timestamp that's <= the entry's existing modifiedAt, or a genuine839// local edit would lose to a stale remote copy. The returned value is always840// strictly greater than both the entry's current modifiedAt and the previous841// call's result (SEV-2-E).842let lastEntryTimestamp = 0;843function monotonicEntryTimestamp(currentModifiedAt?: number): number {844  const base = Math.max(845    Date.now(),846    (currentModifiedAt ?? 0) + 1,847    lastEntryTimestamp + 1,848  );849  lastEntryTimestamp = base;850  return base;851}852853async function stampLocalVaultMutation(): Promise<void> {854  const raw = await chrome.storage.local.get("peach_last_modified_at");855  const previous = Number(856    (raw as Record<string, unknown>).peach_last_modified_at,857  );858  const next = Math.max(859    Date.now(),860    Number.isFinite(previous) ? previous + 1 : 0,861  );862  await chrome.storage.local.set({863    peach_last_modified_at: String(next),864  });865}866867// ---------------------------------------------------------------------------868// Padding + noise helpers869// ---------------------------------------------------------------------------870871/**872 * Pads the plaintext string with trailing spaces so that the encoded byte873 * length is a multiple of PAD_BLOCK. JSON.parse tolerates trailing874 * whitespace after a complete document, so the padding is transparent on875 * decode. Ciphertext length equals plaintext length plus a 16-byte tag.876 */877function padPlaintext(json: string, minBytes = 0): string {878  const encoded = new TextEncoder().encode(json);879  const bucket = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);880  // minBytes lets the duress path force a fixed ceiling so both slots match.881  const target = Math.max(bucket, minBytes);882  const padLen = target - encoded.length;883  return json + " ".repeat(padLen);884}885886/**887 * Produces a StoredVault-shaped record filled with CSPRNG bytes. The888 * ciphertext length matches the given byte count. Because GCM ciphertext is889 * pseudo-random, this blob is indistinguishable at rest from a real890 * encrypted vault without the key.891 *892 * crypto.getRandomValues() caps each call at 65536 bytes (the Web Crypto893 * spec hard limit). Chunk the fill so vaults larger than that — common once894 * the user has dozens of entries or any passkey — don't throw.895 */896const CSPRNG_CHUNK = 65_536;897898function fillRandom(buf: Uint8Array): Uint8Array {899  for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {900    const end = Math.min(offset + CSPRNG_CHUNK, buf.length);901    const chunk = new Uint8Array(end - offset);902    crypto.getRandomValues(chunk);903    buf.set(chunk, offset);904  }905  return buf;906}907908function generateNoiseBlob(ciphertextBytes: number): StoredVault {909  const salt = crypto.getRandomValues(new Uint8Array(16));910  const nonce = crypto.getRandomValues(new Uint8Array(12));911  const cipher = fillRandom(new Uint8Array(ciphertextBytes));912  const tag = crypto.getRandomValues(new Uint8Array(16));913  return {914    version: 1,915    salt: hex(salt),916    nonce: hex(nonce),917    ciphertext: hex(cipher),918    tag: hex(tag),919  };920}921922// ---------------------------------------------------------------------------923// Encrypted plaintext envelope924// ---------------------------------------------------------------------------925926type VaultPayload = {927  entries: VaultEntry[];928  tombstones?: Record<string, number>;929  duressConfigured?: boolean;930};931932type DecryptedPayload = {933  entries: VaultEntry[];934  tombstones: Map<string, number>;935  duressConfigured: boolean;936};937938function encodePayload(entries: VaultEntry[], duress: boolean, minBytes = 0): string {939  const envelope: VaultPayload = {940    entries,941    tombstones: Object.fromEntries(tombstones),942    duressConfigured: duress,943  };944  return padPlaintext(JSON.stringify(envelope), minBytes);945}946947function decodeTombstones(raw: unknown, allEntries: VaultEntry[]): Map<string, number> {948  const result = new Map<string, number>();949  if (raw && typeof raw === "object" && !Array.isArray(raw)) {950    for (const [id, timestamp] of Object.entries(raw as Record<string, unknown>)) {951      if (typeof timestamp === "number" && Number.isFinite(timestamp) && timestamp > 0) {952        result.set(id, timestamp);953      }954    }955  }956  // Older payloads had no ledger. Rebuild the durable portion from any957  // soft-deleted entries before they are eligible for a later purge.958  for (const entry of allEntries) {959    if (typeof entry.deletedAt !== "number" || !Number.isFinite(entry.deletedAt) || entry.deletedAt <= 0) {960      continue;961    }962    if ((result.get(entry.id) ?? 0) < entry.deletedAt) {963      result.set(entry.id, entry.deletedAt);964    }965  }966  return result;967}968969function reconcileTombstones(): void {970  const byId = new Map(entries.map((entry) => [entry.id, entry]));971  for (const [id] of tombstones) {972    if (byId.has(id) && !byId.get(id)?.deletedAt) tombstones.delete(id);973  }974  for (const entry of entries) {975    if (typeof entry.deletedAt === "number" && Number.isFinite(entry.deletedAt) && entry.deletedAt > 0) {976      if ((tombstones.get(entry.id) ?? 0) < entry.deletedAt) {977        tombstones.set(entry.id, entry.deletedAt);978      }979    }980  }981}982983function decodePayload(plain: string): DecryptedPayload {984  const parsed = JSON.parse(plain) as VaultPayload;985  if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.entries)) {986    throw new Error("invalid vault payload");987  }988  const normalized = parsed.entries.map(normalizeEntry);989  return {990    entries: normalized,991    tombstones: decodeTombstones(parsed.tombstones, normalized),992    duressConfigured: parsed.duressConfigured === true,993  };994}995996/**997 * Consolidate duplicate passkey records after registration.998 *999 * Multiple registrations for one RP can leave duplicate passkey records. This1000 * pass collapses the duplicates:1001 *1002 *   1. Group passkey-bearing (and not deleted) entries by `passkey.rpId`.1003 *   2. Within each group, the most recently-active credential wins (prefer1004 *      lastUsedAt, fall back to passkey.createdAt, fall back to modifiedAt).1005 *   3. If a NON-passkey login entry exists for that RP (matched by url or1006 *      additionalUrls hostname), attach the winning passkey to it and1007 *      soft-delete every passkey-bearing entry in the group.1008 *   4. Otherwise, soft-delete every loser in the group, keeping the winner1009 *      as a passkey-only entry.1010 *1011 * Soft delete (deletedAt) rather than splice — the trash flow keeps the1012 * record around for retention and the user can restore if the heuristic1013 * picked wrong. The `merged` flag goes back to decodePayload so the1014 * unlock path persists the consolidated shape immediately.1015 */1016function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {1017  let merged = false;1018  const now = Date.now();10191020  const candidates = entries.filter((e) => !e.deletedAt && e.passkey);1021  const byRpId = new Map<string, VaultEntry[]>();1022  for (const e of candidates) {1023    const rpId = e.passkey!.rpId;1024    const list = byRpId.get(rpId);1025    if (list) list.push(e);1026    else byRpId.set(rpId, [e]);1027  }10281029  for (const [rpId, group] of byRpId) {1030    if (group.length === 0) continue;1031    group.sort((a, b) => {1032      const aT =1033        a.passkey!.lastUsedAt ?? a.passkey!.createdAt ?? a.modifiedAt ?? a.createdAt;1034      const bT =1035        b.passkey!.lastUsedAt ?? b.passkey!.createdAt ?? b.modifiedAt ?? b.createdAt;1036      return bT - aT;1037    });1038    const winner = group[0]!;10391040    // Look for a NON-passkey login entry matching this RP. Use the URL1041    // hostname rather than a substring search so a "login.foo.com" entry1042    // doesn't accidentally absorb a passkey for "foo.com".1043    const loginTarget = entries.find((e) => {1044      if (e.deletedAt || e.passkey || e.type !== "login") return false;1045      if (e.url && extractDomain(e.url) === rpId) return true;1046      for (const extra of e.additionalUrls ?? []) {1047        if (extractDomain(extra) === rpId) return true;1048      }1049      return false;1050    });10511052    if (loginTarget) {1053      loginTarget.passkey = winner.passkey;1054      // A passkey entry may also carry the site's TOTP seed. Preserve it when1055      // the passkey is consolidated onto an existing login instead of1056      // soft-deleting the only record that held the 2FA configuration.1057      if (!loginTarget.totp && winner.totp) {1058        loginTarget.totp = winner.totp;1059        loginTarget.totpAlgorithm = winner.totpAlgorithm;1060        loginTarget.totpDigits = winner.totpDigits;1061        loginTarget.totpPeriod = winner.totpPeriod;1062      }1063      loginTarget.modifiedAt = now;1064      for (const dup of group) {1065        if (!dup.deletedAt) {1066          dup.deletedAt = now;1067          dup.modifiedAt = now;1068        }1069      }1070      merged = true;1071    } else if (group.length > 1) {1072      for (let i = 1; i < group.length; i += 1) {1073        const dup = group[i]!;1074        if (!dup.deletedAt) {1075          dup.deletedAt = now;1076          dup.modifiedAt = now;1077        }1078      }1079      merged = true;1080    }1081  }10821083  return { merged };1084}10851086// Validates that a `StoredVault` record on disk has the field shape we expect1087// before treating an AES-GCM decrypt success as a clean unlock. AES-GCM only1088// authenticates the static VERSION_BYTE AAD, not the `version` field on the1089// outer record — a corrupted `version: 42` slot still decrypts cleanly. This1090// check surfaces that as `corrupted` (M7/COR-007) so the popup can offer a1091// history-restore path instead of falsely reporting "wrong password".1092function hasValidVaultSchema(v: unknown): v is StoredVault {1093  if (typeof v !== "object" || v === null) return false;1094  const r = v as Record<string, unknown>;1095  return (1096    r.version === 1 &&1097    typeof r.salt === "string" &&1098    typeof r.nonce === "string" &&1099    typeof r.ciphertext === "string" &&1100    typeof r.tag === "string"1101  );1102}11031104export type TryDecryptResult =1105  | { status: "ok"; payload: DecryptedPayload }1106  | { status: "wrong_key" }1107  | { status: "corrupted"; reason: string };11081109// Exported solely for `unlockFromCodex` below, which needs to verify a1110// supplied passphrase against a slotA blob *without* committing anything to1111// storage. Keep this internal otherwise — callers crossing the messages.ts1112// boundary should always go through `unlock` / `verifyMainPassword` so the1113// constant-time invariants in Projects.md §3.4 are not bypassed.1114export async function tryDecryptSlot(1115  vault: StoredVault,1116  key: Uint8Array,1117  aadTag?: string,1118): Promise<DecryptedPayload | null> {1119  const res = await tryDecryptSlotResult(vault, key, aadTag);1120  return res.status === "ok" ? res.payload : null;1121}11221123export async function tryDecryptSlotResult(1124  vault: StoredVault,1125  key: Uint8Array,1126  aadTag?: string,1127): Promise<TryDecryptResult> {1128  if (!hasValidVaultSchema(vault)) {1129    return { status: "corrupted", reason: "invalid_slot_schema" };1130  }1131  let plain: string;1132  try {1133    plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);1134  } catch {1135    return { status: "wrong_key" };1136  }1137  try {1138    const parsed = JSON.parse(plain) as unknown;1139    if (typeof parsed !== "object" || parsed === null) {1140      return { status: "corrupted", reason: "invalid_payload_shape" };1141    }1142    if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {1143      return { status: "corrupted", reason: "invalid_payload_shape" };1144    }1145    return { status: "ok", payload: decodePayload(plain) };1146  } catch {1147    return { status: "corrupted", reason: "invalid_payload_json" };1148  }1149}11501151// ---------------------------------------------------------------------------1152// Core operations1153// ---------------------------------------------------------------------------11541155function buildDomainIndexSync(all: VaultEntry[]): void {1156  domainIndex = new Map();11571158  for (const entry of all) {1159    if (entry.deletedAt) continue;1160    if (entry.type === "note" || entry.type === "card") continue;11611162    // An entry can match multiple sites via `additionalUrls`. Index each1163    // hostname so `queryDomain` returns the entry regardless of which alias1164    // the user is currently visiting. Dedupe per-entry so a single entry1165    // never appears twice in one bucket.1166    const domains = new Set<string>();1167    const primary = extractDomain(entry.url ?? "");1168    if (primary) domains.add(primary);1169    for (const extra of entry.additionalUrls ?? []) {1170      const d = extractDomain(extra);1171      if (d) domains.add(d);1172    }1173    if (domains.size === 0) continue;11741175    for (const domain of domains) {1176      const bucket = domainIndex.get(domain) ?? [];1177      bucket.push(entry);1178      domainIndex.set(domain, bucket);1179    }1180  }1181}11821183export async function createVault(password: string): Promise<void> {1184  const salt = generateSalt();1185  derivedKey = await deriveKey(password, salt);1186  entries = [];1187  tombstones = new Map();1188  vaultMode = "real";1189  duressConfigured = false;1190  buildDomainIndexSync(entries);11911192  // Generate and wrap the root key for recovery word escrow.1193  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =1194    await generateAndWrapRootKey();1195  rootKey = unhex(rawRootKey);11961197  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);1198  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");11991200  // Second wrapping of rootKey under derivedKey so future unlocks can rehydrate1201  // it without recovery words (H2/COR-006).1202  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);12031204  const slotA: StoredVault = {1205    version: 1,1206    salt: hex(salt),1207    nonce,1208    ciphertext,1209    tag,1210    recovery_salt: recoverySalt,1211    recovery_wrapped_root_key: wrappedRootKey,1212    recovery_nonce: wrappedNonce,1213    recovery_tag: wrappedTag,1214    ...pwRoot,1215  };1216  await writeSlot(SLOT_A, slotA);12171218  // Matching-size noise blob for slot B, so a fresh install shows two1219  // similarly-shaped records regardless of whether duress is ever set up.1220  await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));1221  await stampLocalVaultMutation();12221223  touchAutoLock();1224}12251226/**1227 * Creates a local vault from an existing vault root key received through the1228 * SAS-gated adoption protocol. The password is local to this device; it wraps1229 * the adopted root key at rest and does not need to match the source device.1230 */1231export async function createVaultFromRootKey(1232  password: string,1233  rootKeyHex: string,1234): Promise<{ vaultId: string }> {1235  if (typeof password !== "string" || password.length === 0) {1236    throw new Error("ADOPT_INVALID_PASSWORD");1237  }1238  if (typeof rootKeyHex !== "string" || !/^[0-9a-f]{64}$/.test(rootKeyHex)) {1239    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars");1240  }12411242  const rootKeyBytes = unhex(rootKeyHex);1243  if (rootKeyBytes.length !== 32) {1244    rootKeyBytes.fill(0);1245    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");1246  }12471248  let nextDerivedKey: Uint8Array | null = null;1249  let sessionRootKey: Uint8Array | null = null;1250  try {1251    if ((await loadSlot(SLOT_A)) !== null) {1252      throw new Error("ADOPT_VAULT_ALREADY_EXISTS");1253    }12541255    const nextEntries: VaultEntry[] = [];1256    const nextDuressConfigured = false;1257    const vaultId = await computeVaultId(rootKeyBytes);1258    const salt = generateSalt();1259    nextDerivedKey = await deriveKey(password, salt);1260    const recovery = await wrapExistingRootKeyForRecovery(rootKeyBytes);12611262    sessionRootKey = new Uint8Array(rootKeyBytes);1263    const plaintext = encodePayload(nextEntries, nextDuressConfigured, 0);1264    const { nonce, ciphertext, tag } = await encrypt(nextDerivedKey, plaintext, "slot_a_v1");1265    const pwRoot = await wrapRootKeyForDerivedKey(nextDerivedKey, sessionRootKey);1266    const slotA: StoredVault = {1267      version: 1,1268      salt: hex(salt),1269      nonce,1270      ciphertext,1271      tag,1272      recovery_salt: recovery.recoverySalt,1273      recovery_wrapped_root_key: recovery.wrappedRootKey,1274      recovery_nonce: recovery.wrappedNonce,1275      recovery_tag: recovery.wrappedTag,1276      ...pwRoot,1277    };1278    const slotB = generateNoiseBlob(ciphertext.length / 2);1279    await commitCreatedVaultSlots(slotA, slotB);12801281    const previousDerivedKey = derivedKey;1282    const previousRootKey = rootKey;1283    derivedKey = nextDerivedKey;1284    rootKey = sessionRootKey;1285    nextDerivedKey = null;1286    sessionRootKey = null;1287    entries = nextEntries;1288    tombstones = new Map();1289    vaultMode = "real";1290    duressConfigured = nextDuressConfigured;1291    buildDomainIndexSync(entries);1292    if (previousDerivedKey && previousDerivedKey !== derivedKey) zeroKey(previousDerivedKey);1293    if (previousRootKey && previousRootKey !== rootKey) previousRootKey.fill(0);1294    touchAutoLock();12951296    return { vaultId };1297  } finally {1298    rootKeyBytes.fill(0);1299    if (nextDerivedKey) zeroKey(nextDerivedKey);1300    if (sessionRootKey) sessionRootKey.fill(0);1301  }1302}13031304export async function hasVault(): Promise<boolean> {1305  return (await loadSlot(SLOT_A)) !== null;1306}13071308/**1309 * Returns whether the real vault has recorded that a duress passphrase is1310 * configured. Reliable only after a real-mode unlock — before unlock or in1311 * decoy mode, returns false because we cannot read slot A's plaintext.1312 */1313export async function isDuressEnabled(): Promise<boolean> {1314  return vaultMode === "real" && duressConfigured;1315}13161317export async function setupDuress(duressPassword: string): Promise<void> {1318  if (!derivedKey || vaultMode !== "real") {1319    throw new Error("vault must be unlocked in real mode");1320  }1321  // Encrypt the decoy payload (empty entries) under the duress key. Pad to1322  // at least the current slot A ciphertext size so the two slots look the1323  // same at rest at setup time.1324  const slotA = await loadSlot(SLOT_A);1325  if (!slotA) throw new Error("missing slot A");13261327  const decoySalt = generateSalt();1328  const decoyKey = await deriveKey(duressPassword, decoySalt);1329  try {1330    // Pad the decoy to the fixed duress ceiling. Slot A is re-encrypted to the1331    // same ceiling by the persistSlotA() call below (duressConfigured is now1332    // true), so both slots are exactly DURESS_SLOT_SIZE+tag at rest and their1333    // lengths cannot reveal that duress is configured (audit MEDIUM).1334    const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);1335    const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");1336    await writeSlot(SLOT_B, {1337      version: 1,1338      salt: hex(decoySalt),1339      nonce,1340      ciphertext,1341      tag,1342    });1343  } finally {1344    zeroKey(decoyKey);1345  }13461347  // Re-encrypt slot A with the duressConfigured flag set to true. No external1348  // flag is written — the bit lives inside the encrypted envelope.1349  duressConfigured = true;1350  await persistSlotA();1351}13521353export async function disableDuress(): Promise<void> {1354  if (!derivedKey || vaultMode !== "real") {1355    throw new Error("vault must be unlocked in real mode");1356  }1357  // Overwrite slot B with fresh noise that matches slot A's size. The slot1358  // remains occupied so its mere existence does not signal that duress was1359  // ever configured.1360  const slotA = await loadSlot(SLOT_A);1361  if (slotA) {1362    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));1363  }13641365  duressConfigured = false;1366  await persistSlotA();1367}13681369// L14/COR-015: this function intentionally checks slot A (real vault) only.1370// A duress-mode user attempting changePassword is rejected earlier by the1371// vaultMode === 'decoy' check at changePassword. The real-vs-decoy1372// distinction here is by design — duress users cannot rotate the real1373// password by guessing it, and the asymmetry in error timing is acceptable1374// because duress mode is opt-in and the user knows their own decoy key.1375export async function verifyMainPassword(password: string): Promise<boolean> {1376  const slotA = await loadSlot(SLOT_A);1377  if (!slotA) return false;1378  const key = await deriveKey(password, unhex(slotA.salt));1379  try {1380    return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;1381  } finally {1382    zeroKey(key);1383  }1384}13851386export async function unlock(password: string): Promise<boolean> {1387  return attemptUnlockWithDerive(password, deriveKey);1388}13891390async function attemptUnlockWithDerive(1391  password: string,1392  derive: typeof deriveKey,1393): Promise<boolean> {1394  // Load both current-format slots in parallel. Both exist on a supported1395  // install; the1396  // parallel load and the parallel derivation below keep wall-clock time1397  // constant regardless of which slot's passphrase (real or decoy) the1398  // caller supplied, so a timing side channel cannot distinguish the1399  // duress path from the real-unlock path (DUR-002).1400  const [slotA, slotB] = await Promise.all([1401    loadSlot(SLOT_A),1402    loadSlot(SLOT_B),1403  ]);14041405  // Derive both keys in parallel, unconditionally.1406  const [keyA, keyB] = await Promise.all([1407    slotA ? derive(password, unhex(slotA.salt)) : Promise.resolve(null),1408    slotB ? derive(password, unhex(slotB.salt)) : Promise.resolve(null),1409  ]);14101411  // Attempt both decrypts in parallel. The Result variant lets us distinguish1412  // 'wrong_key' from 'corrupted' so callers can offer a history-restore path1413  // when a slot's schema is invalid even though AES-GCM authenticated (M7).1414  const [resultA, resultB] = await Promise.all([1415    keyA && slotA1416      ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")1417      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1418    keyB && slotB1419      ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")1420      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1421  ]);1422  const payloadA = resultA.status === "ok" ? resultA.payload : null;1423  const payloadB = resultB.status === "ok" ? resultB.payload : null;14241425  if (payloadA && keyA) {1426    derivedKey = keyA;1427    void saveSessionKey(keyA, "real");1428    vaultMode = "real";1429    entries = payloadA.entries;1430    tombstones = payloadA.tombstones;1431    duressConfigured = payloadA.duressConfigured;1432    buildDomainIndexSync(entries);1433    await loadSettings();1434    touchAutoLock();1435    if (keyB) zeroKey(keyB);14361437    // Current vaults always carry a password-wrapped root key. Older vaults1438    // without this escrow are outside the supported storage format.1439    rootKey = slotA ? await deriveRootKeyFromDerivedKey(keyA, slotA) : null;1440    if (!rootKey) {1441      lock();1442      return false;1443    }14441445    await lockedSyncUnlockHook?.().catch((error) => {1446      console.warn("[Peach sync] locked inbox drain failed:", error);1447    });1448    await resetPinFailedAttempts();1449    return true;1450  }14511452  if (payloadB && keyB) {1453    derivedKey = keyB;1454    void saveSessionKey(keyB, "decoy");1455    vaultMode = "decoy";1456    entries = payloadB.entries;1457    tombstones = payloadB.tombstones;1458    duressConfigured = false;1459    buildDomainIndexSync(entries);1460    await loadSettings();1461    touchAutoLock();1462    if (keyA) zeroKey(keyA);1463    return true;1464  }14651466  if (keyA) zeroKey(keyA);1467  if (keyB) zeroKey(keyB);1468  // Surface corruption (good AES tag, broken schema) distinctly from1469  // wrong-password so the popup can offer history-restore (M7/COR-007).1470  if (resultA.status === "corrupted") {1471    lastUnlockFailureReason = resultA.reason;1472  } else if (resultB.status === "corrupted") {1473    lastUnlockFailureReason = resultB.reason;1474  }1475  return false;1476}14771478// ---------------------------------------------------------------------------1479// MV3 service worker session key — survives SW restarts within a browser session1480// ---------------------------------------------------------------------------14811482// chrome.storage.session is cleared on browser close; survives SW restart.1483// Firefox does not implement it (persistent background script, no restart risk).1484const SESSION_KEY_STORAGE = "peach_session_dk";14851486async function saveSessionKey(key: Uint8Array, mode: "real" | "decoy"): Promise<void> {1487  if (!chrome.storage.session) return;1488  await chrome.storage.session.set({ [SESSION_KEY_STORAGE]: { keyHex: hex(key), mode } });1489}14901491async function clearSessionKey(): Promise<void> {1492  if (!chrome.storage.session) return;1493  await chrome.storage.session.remove(SESSION_KEY_STORAGE);1494}14951496/**1497 * On SW restart, re-derive all in-memory vault state from the session key1498 * stored in chrome.storage.session (set at unlock time, cleared by lock();1499 * also cleared on browser close or when restoration fails).1500 * Returns true if the vault was restored, false if no session key was found.1501 * No-ops if the vault is already unlocked.1502 */1503export async function restoreFromSession(): Promise<boolean> {1504  if (derivedKey !== null) return true;1505  if (!chrome.storage.session) return false;1506  const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);1507  const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;1508  if (!entry?.keyHex) return false;15091510  const key = unhex(entry.keyHex);1511  const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;1512  const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";1513  const slot = await loadSlot(slotKey);1514  if (!slot) { await clearSessionKey(); return false; }15151516  const result = await tryDecryptSlotResult(slot, key, aadTag);1517  if (result.status !== "ok") { await clearSessionKey(); return false; }15181519  derivedKey = key;1520  vaultMode = entry.mode;1521  entries = result.payload.entries;1522  tombstones = result.payload.tombstones;1523  duressConfigured = entry.mode === "real" ? result.payload.duressConfigured : false;1524  buildDomainIndexSync(entries);1525  await loadSettings();1526  touchAutoLock();15271528  // Rehydrate the root key used by sync identity derivation from the password1529  // escrow stored on the current vault format.1530  if (entry.mode === "real") {1531    rootKey = await deriveRootKeyFromDerivedKey(key, slot);1532    if (!rootKey) {1533      lock();1534      return false;1535    }1536  }15371538  await lockedSyncUnlockHook?.().catch((error) => {1539    console.warn("[Peach sync] locked inbox drain failed:", error);1540  });15411542  return true;1543}15441545export function lock(): void {1546  // A user-initiated lock must be durable across MV3 service-worker restarts.1547  // The SW is idle-killed after ~30s of inactivity, and the popup's next open1548  // wakes a cold SW whose restoreFromSession() reads chrome.storage.session.1549  // If the session key survived lock(), that restore would silently re-unlock1550  // the vault ~a minute after the user locked it — a lock that only held1551  // while the SW happened to stay alive. The background-sync convenience the1552  // session key once bought (sync runner re-waking to a restored vault) is1553  // not worth an unlocked vault the user never asked to unlock; when locked,1554  // sync-runner correctly reports VAULT_LOCKED instead.1555  void clearSessionKey();1556  void clearRecoveryConfirmPending();1557  if (derivedKey) {1558    zeroKey(derivedKey);1559    derivedKey = null;1560  }1561  if (rootKey) {1562    rootKey.fill(0);1563    rootKey = null;1564  }15651566  entries = [];1567  tombstones = new Map();1568  domainIndex = new Map();1569  vaultMode = "real";1570  duressConfigured = false;1571  clearAutoLock();1572}15731574export function isUnlocked(): boolean {1575  return derivedKey !== null;1576}15771578// Opens the vault using a pre-derived AES-256 key (skipping Argon2id). The1579// PIN-unlock path unwraps this key from its PIN wrap; the passphrase path1580// always derives from scratch via Argon2id.1581export async function unlockWithKey(1582  masterKeyHex: string,1583): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {1584  try {1585    const masterKeyBytes = unhex(masterKeyHex);1586    const stored = await loadSlot(SLOT_A);1587    if (!stored) return { ok: false, error: "invalid_key" };1588    const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");1589    if (!payload) return { ok: false, error: "invalid_key" };15901591    derivedKey = masterKeyBytes;1592    vaultMode = "real";1593    entries = payload.entries;1594    tombstones = payload.tombstones;1595    duressConfigured = payload.duressConfigured;1596    buildDomainIndexSync(entries);1597    await loadSettings();1598    touchAutoLock();15991600    rootKey = await deriveRootKeyFromDerivedKey(masterKeyBytes, stored);1601    if (!rootKey) {1602      lock();1603      return { ok: false, error: "invalid_key" };1604    }1605    return { ok: true, entries };1606  } catch {1607    return { ok: false, error: "invalid_key" };1608  }1609}16101611// --- Adoption duress-slot helpers (passthrough, no decrypt) ---16121613/**1614 * Adoption SOURCE helper: returns the sealed slot B as a JSON string when1615 * duress is configured and slot B exists, so the inline snapshot can ship it1616 * to the receiver. Returns null otherwise. Never decrypts.1617 */1618export async function exportDuressSlotForAdoption(): Promise<string | null> {1619  if (!(await isDuressEnabled())) return null;1620  const slotB = await loadSlot(SLOT_B);1621  if (!slotB) return null;1622  return JSON.stringify(slotB);1623}16241625/**1626 * Adoption RECEIVER helper: installs a duress slot received from a source1627 * device. Validates the StoredVault shape (same guard as unlockFromCodex)1628 * and writes it to slot B. Throws on invalid shape so the caller can treat1629 * it as a non-fatal snapshot failure. Never decrypts.1630 */1631export async function installAdoptedDuressSlot(json: string): Promise<void> {1632  let parsed: StoredVault;1633  try {1634    const raw = JSON.parse(json) as unknown;1635    if (!hasValidVaultSchema(raw)) {1636      throw new Error("invalid_duress_slot_shape");1637    }1638    parsed = raw;1639  } catch (err) {1640    if (err instanceof SyntaxError) {1641      throw new Error("invalid_duress_slot_shape");1642    }1643    throw err;1644  }1645  await writeSlot(SLOT_B, parsed);1646}16471648/**1649 * Restore the vault from a parsed Peach Codex payload.1650 *1651 * The supplied passphrase is verified against the Codex's slotA *before* any1652 * storage mutation — wrong passphrases return without touching disk. On1653 * success, the current vault state is snapshotted (reason: "restore") so the1654 * user can revert via Settings -> Vault History, then slotA/slotB are written1655 * and `peach_last_modified_at` is set to the Codex's recorded timestamp. A1656 * regular `unlock()` follows so the rest of the SW sees the standard1657 * post-unlock state.1658 *1659 * Intentionally non-Pro-gated — see peach_codex_v2.md "Pro gating". A Codex1660 * printed by a Pro user must always be restorable, even on a free device.1661 *1662 * Timing is not held constant here (in contrast to `unlock`): the Codex flow1663 * is an explicit user action with a known passphrase, not a passive lock1664 * screen, so the duress-vs-real timing side channel does not apply.1665 */1666export async function unlockFromCodex(params: {1667  slotA: string; // JSON string of StoredVault for slot A1668  slotB: string | null; // JSON string of StoredVault for slot B, or null1669  timestamp: number;1670  masterPassphrase: string;1671}): Promise<1672  | { ok: true; entryCount: number }1673  | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" }1674> {1675  let parsedSlotA: StoredVault;1676  let parsedSlotB: StoredVault | null = null;1677  try {1678    const rawA = JSON.parse(params.slotA) as unknown;1679    if (!hasValidVaultSchema(rawA)) {1680      return { ok: false, reason: "invalid_slot_format" };1681    }1682    parsedSlotA = rawA;1683    if (params.slotB !== null) {1684      const rawB = JSON.parse(params.slotB) as unknown;1685      if (!hasValidVaultSchema(rawB)) {1686        return { ok: false, reason: "invalid_slot_format" };1687      }1688      parsedSlotB = rawB;1689    }1690  } catch {1691    return { ok: false, reason: "invalid_slot_format" };1692  }16931694  // Verify the passphrase against the supplied slotA WITHOUT writing anything.1695  // If this fails the on-disk vault is left completely untouched.1696  const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));1697  const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");1698  if (!trialPayload) {1699    zeroKey(trialKey);1700    return { ok: false, reason: "wrong_passphrase" };1701  }1702  // Drop the trial key; `unlock()` below derives its own copy. Holding two1703  // copies of the master key in memory at once would be a needless surface.1704  zeroKey(trialKey);17051706  // Snapshot the about-to-be-overwritten on-disk state so the user can revert1707  // a mistaken Codex restore via the Vault History UI. Non-fatal if it fails.1708  await takeVaultSnapshot("restore");17091710  await writeSlot(SLOT_A, parsedSlotA);1711  if (parsedSlotB) {1712    await writeSlot(SLOT_B, parsedSlotB);1713  } else {1714    // Slot B must always exist with ciphertext length matching slot A1715    // (Projects.md §3.2). Codex prints may omit slot B (duress wasn't1716    // configured); regenerate noise to satisfy the invariant.1717    await writeSlot(1718      SLOT_B,1719      generateNoiseBlob(parsedSlotA.ciphertext.length / 2),1720    );1721  }1722  await chrome.storage.local.set({1723    peach_last_modified_at: String(params.timestamp),1724  });17251726  // Standard unlock path so domain index, settings, auto-lock, and1727  // recovery-key state all populate exactly as a normal unlock would.1728  const ok = await unlock(params.masterPassphrase);1729  if (!ok) {1730    // Should be unreachable — we just verified the passphrase against the1731    // same slotA we wrote. Treat as wrong_passphrase to keep the contract1732    // simple if some race or storage anomaly intrudes.1733    return { ok: false, reason: "wrong_passphrase" };1734  }1735  return { ok: true, entryCount: getEntries().length };1736}17371738// Returns the current in-memory derived key as a hex string. Only the PIN1739// unlock path needs this value, and it reads module state directly; this1740// accessor exists so unlockWithKey's root-key rehydration is testable.1741export /* @testable */ function getDerivedKeyHex(): string {1742  if (!derivedKey) throw new Error("vault_not_unlocked");1743  return hex(derivedKey);1744}17451746/**1747 * Returns the vault's stable root key as hex, or null when locked / not yet1748 * populated. The root key is random per-vault, generated at creation, escrowed1749 * under the recovery words, and re-wrapped (not regenerated) on every password1750 * change — so it is INVARIANT across password rotation, unlike getDerivedKeyHex.1751 *1752 * This is the correct input for sync identity derivation (vault_id, the Noise1753 * NK static key, the Ed25519 manifest signing key, and per-entry envelope1754 * keys): paired devices keep the same identity and can still decrypt each1755 * other's entries after either side rotates its master password (SEV-2-B).1756 *1757 * Returns null rather than throwing so sync callers degrade to VAULT_LOCKED1758 * instead of crashing; rootKey is populated on every supported real-mode1759 * unlock via deriveRootKeyFromDerivedKey.1760 */1761export function getRootKeyHex(): string | null {1762  return rootKey ? hex(rootKey) : null;1763}17641765export function getEntries(): VaultEntry[] {1766  if (!derivedKey) throw new Error("vault_locked");1767  return entries.filter((entry) => !entry.deletedAt);1768}17691770const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;17711772export function getIdentities(): SavedIdentity[] {1773  if (!derivedKey) throw new Error("vault_locked");1774  const active = entries.filter((e) => !e.deletedAt && e.type === "login");17751776  const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();1777  const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();17781779  for (const entry of active) {1780    const domain = extractDomain(entry.url ?? "") ?? "";1781    const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;17821783    function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {1784      const existing = map.get(v);1785      if (!existing || modifiedAt > existing.lastUsed) {1786        map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });1787      } else {1788        map.set(v, { ...existing, count: existing.count + 1 });1789      }1790    }17911792    const uVal = entry.username?.trim();1793    if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);17941795    // Also count the dedicated email field — entries created via the inline1796    // popup new-entry form store email here rather than in username.1797    const eVal = entry.email?.trim();1798    if (eVal) tally(emailMap, eVal);1799  }18001801  const toIdentity = (type: "email" | "username") =>1802    ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({1803      value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,1804    });18051806  return [1807    ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),1808    ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),1809  ];1810}18111812export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {1813  if (!derivedKey) throw new Error("vault_locked");18141815  const now = Date.now();1816  const added: VaultEntry[] = [];1817  for (const draft of drafts) {1818    try {1819      const sanitized = sanitizeEntryDraft(draft);1820      const nextEntry: VaultEntry = {1821        ...sanitized,1822        id: crypto.randomUUID(),1823        createdAt: now,1824        modifiedAt: monotonicEntryTimestamp(),1825      };1826      entries.push(nextEntry);1827      added.push(nextEntry);1828    } catch {1829      // Skip invalid drafts silently — caller can see diff between input and output length1830    }1831  }18321833  if (added.length > 0) {1834    await persistEntries();1835  }18361837  return added;1838}18391840/**1841 * Restore a set of entries in full fidelity — preserves id, createdAt,1842 * modifiedAt, and every other field unlike `batchAddEntries` which1843 * assigns fresh identity. Used by restore paths where the backup is the1844 * authoritative source of truth. `mode` controls how entries already in1845 * the vault are treated.1846 */1847export async function restoreEntries(1848  incoming: VaultEntry[],1849  mode: "replace" | "merge"1850): Promise<{ added: number; updated: number; skipped: number }> {1851  if (!derivedKey) throw new Error("vault_locked");18521853  // A replace with zero incoming entries is almost certainly a caller bug1854  // (e.g. an import that silently dropped everything). Refuse rather than1855  // wipe the vault.1856  if (mode === "replace" && incoming.length === 0) {1857    throw new Error("refuse to replace with empty entry set");1858  }18591860  let added = 0;1861  let updated = 0;1862  let skipped = 0;18631864  if (mode === "replace") {1865    entries = [];1866    for (const entry of incoming) {1867      const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));1868      if (!normalized) {1869        skipped += 1;1870        continue;1871      }1872      entries.push(normalized);1873      if (normalized.deletedAt) {1874        tombstones.set(1875          normalized.id,1876          Math.max(tombstones.get(normalized.id) ?? 0, normalized.deletedAt),1877        );1878      } else {1879        tombstones.delete(normalized.id);1880      }1881      added += 1;1882    }1883  } else {1884    const byId = new Map<string, VaultEntry>();1885    for (const e of entries) byId.set(e.id, e);18861887    for (const entry of incoming) {1888      const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));1889      if (!normalized) {1890        skipped += 1;1891        continue;1892      }1893      const existing = byId.get(normalized.id);1894      if (!existing) {1895        entries.push(normalized);1896        if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);1897        else tombstones.delete(normalized.id);1898        added += 1;1899      } else if (normalized.modifiedAt > existing.modifiedAt) {1900        const idx = entries.findIndex((e) => e.id === existing.id);1901        if (idx !== -1) {1902          entries[idx] = normalized;1903          if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);1904          else tombstones.delete(normalized.id);1905          updated += 1;1906        }1907      } else {1908        skipped += 1;1909      }1910    }1911  }19121913  await persistEntries("import");1914  return { added, updated, skipped };1915}19161917/**1918 * A Peach entry id is a UUID. A restored or imported file carries whatever id1919 * its author used, and no reader bounds it, so one oversized id would ride1920 * into every future sync frame and be rejected there — a permanent, opaque1921 * failure on both platforms, caused by data that was already local.1922 *1923 * The action is mint, not reject: this is the last point where an id is still1924 * ours to choose, so the worst outcome is one duplicate if the same vault is1925 * later restored beside a device still holding the old id. Rejecting would1926 * lose the user's import.1927 *1928 * Deliberately NOT inside sanitizeRestoredEntry, which applyMergedRemoteEntries1929 * also calls. Sync has to adopt a peer's id verbatim — that is the only thing1930 * keeping two devices agreed on which entry they are discussing — so reminting1931 * there would fork identity on every device, on every round.1932 */1933const ENTRY_ID_SHAPE = /^[A-Za-z0-9_-]{1,64}$/;19341935function naturalizeRestoredId(entry: VaultEntry | null): VaultEntry | null {1936  if (!entry || ENTRY_ID_SHAPE.test(entry.id)) return entry;1937  return { ...entry, id: crypto.randomUUID() };1938}19391940/**1941 * Validate + normalise a VaultEntry coming from a backup, import, or sync1942 * peer. MV-6: this is a strict field WHITELIST — `normalizeEntry` copies1943 * only known VaultEntry fields (unknown/attacker keys are dropped), and1944 * nested `passkey`/`canary` shapes are rebuilt field-by-field, never1945 * spread. Returns null for values the live vault shouldn't accept.1946 */1947function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {1948  if (!entry || typeof entry !== "object") return null;1949  const title = typeof entry.title === "string" ? entry.title.trim() : "";1950  if (!title) return null;1951  const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();1952  const now = Date.now();1953  const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;1954  const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;19551956  // normalizeEntry whitelists every known VaultEntry field before the entry1957  // reaches the live vault.1958  const normalized = normalizeEntry({1959    ...entry,1960    id,1961    title,1962    type: entry.type ?? "login",1963    createdAt,1964    modifiedAt,1965  });19661967  if (normalized.passkey) {1968    normalized.passkey = sanitizePasskey(normalized.passkey);1969  }1970  if (normalized.canary) {1971    normalized.canary = sanitizeCanary(normalized.canary);1972  }1973  // PCH-01-016: bound tags on the restore path too, so both import funnels agree.1974  normalized.tags = sanitizeTags(normalized.tags);19751976  // Login entries from backup must carry a password (or be passkey-only,1977  // in which case the passkey sub-object replaces the password requirement).1978  if (1979    normalized.type === "login" &&1980    !normalized.passkey &&1981    typeof normalized.password !== "string"1982  ) {1983    return null;1984  }1985  if (entry.passkey && !normalized.passkey) {1986    // Entry claimed a passkey but the shape didn't validate — refuse the1987    // whole entry rather than silently importing a credential-less husk.1988    return null;1989  }19901991  return normalized;1992}19931994/**1995 * Rebuild a PasskeyData object from untrusted input, field by field.1996 * Returns undefined when required fields are missing/mistyped — a rogue1997 * passkey credential must not activate via import (MV-6 attack scenario).1998 */1999function sanitizePasskey(pk: unknown): PasskeyData | undefined {2000  if (!pk || typeof pk !== "object") return undefined;2001  const r = pk as Record<string, unknown>;2002  if (2003    typeof r.rpId !== "string" || !r.rpId ||2004    typeof r.credentialId !== "string" || !r.credentialId ||2005    typeof r.publicKeyCose !== "string" ||2006    typeof r.userHandle !== "string" ||2007    typeof r.userName !== "string"2008  ) {2009    return undefined;2010  }2011  return {2012    rpId: r.rpId,2013    rpName: typeof r.rpName === "string" ? r.rpName : r.rpId,2014    credentialId: r.credentialId,2015    publicKeyCose: r.publicKeyCose,2016    privateKeyJwk:2017      r.privateKeyJwk && typeof r.privateKeyJwk === "object"2018        ? (r.privateKeyJwk as JsonWebKey)2019        : undefined,2020    userHandle: r.userHandle,2021    userName: r.userName,2022    userDisplayName:2023      typeof r.userDisplayName === "string" ? r.userDisplayName : r.userName,2024    algorithm: r.algorithm === -8 ? -8 : -7,2025    signCount: typeof r.signCount === "number" ? r.signCount : 0,2026    aaguid: typeof r.aaguid === "string" ? r.aaguid : "",2027    backupEligible: r.backupEligible === true,2028    backupState: r.backupState === true,2029    lastUsedAt: typeof r.lastUsedAt === "number" ? r.lastUsedAt : undefined,2030    browser: r.browser === "chrome" || r.browser === "firefox" ? r.browser : undefined,2031    transports: Array.isArray(r.transports)2032      ? r.transports.filter((t): t is string => typeof t === "string")2033      : undefined,2034    createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),2035  };2036}20372038/**2039 * Rebuild a Canary object from untrusted input. The webhook must be a2040 * well-formed HTTPS URL — a poisoned canary.webhookUrl is a standing2041 * exfiltration endpoint that the canary subsystem will POST entry titles2042 * to (MV-6 attack scenario). Invalid → the canary is dropped, not the2043 * entry. FIRE_CANARY_PING re-validates with the full SSRF guard at fire2044 * time (isAllowedCanaryWebhookUrl), so this import-time check is the2045 * outer of two gates.2046 */2047function sanitizeCanary(c: unknown): Canary | undefined {2048  if (!c || typeof c !== "object") return undefined;2049  const r = c as Record<string, unknown>;2050  if (typeof r.webhookUrl !== "string") return undefined;2051  let url: URL;2052  try {2053    url = new URL(r.webhookUrl);2054  } catch {2055    return undefined;2056  }2057  if (url.protocol !== "https:") return undefined;2058  return {2059    webhookUrl: url.toString(),2060    label: typeof r.label === "string" ? r.label : undefined,2061    lastPinged: typeof r.lastPinged === "number" ? r.lastPinged : undefined,2062    pingCount: typeof r.pingCount === "number" ? r.pingCount : undefined,2063  };2064}20652066/**2067 * MV-6 / PCH-01-016: tags from imported / batch-added entries are untrusted.2068 * Keep only non-empty strings, cap each at 256 chars, and cap the count at 2552069 * (the same per-entry ceiling the export codec enforces, peachPayload.ts).2070 * Non-array or all-invalid input collapses to undefined.2071 */2072function sanitizeTags(tags: unknown): string[] | undefined {2073  if (!Array.isArray(tags)) return undefined;2074  const out: string[] = [];2075  for (const t of tags) {2076    if (typeof t !== "string") continue;2077    const trimmed = t.trim();2078    if (!trimmed) continue;2079    out.push(trimmed.slice(0, 256));2080    if (out.length >= 255) break;2081  }2082  return out.length > 0 ? out : undefined;2083}20842085// Soft-deletes every non-deleted entry in one call. The literal string2086// argument is a tripwire against accidental calls — any caller that would2087// wipe the vault has to consciously type "REPLACE_ALL". Do not relax this2088// to a boolean.2089export async function clearVaultEntries(2090  confirmation: "REPLACE_ALL"2091): Promise<void> {2092  if (confirmation !== "REPLACE_ALL") {2093    throw new Error("clearVaultEntries requires explicit confirmation");2094  }2095  if (!derivedKey) throw new Error("vault_locked");2096  for (const entry of entries) {2097    if (!entry.deletedAt) {2098      const stamp = monotonicEntryTimestamp(Math.max(2099        entry.modifiedAt,2100        tombstones.get(entry.id) ?? 0,2101      ));2102      entry.deletedAt = stamp;2103      entry.modifiedAt = stamp;2104      tombstones.set(entry.id, stamp);2105    }2106  }2107  await persistEntries();2108}21092110export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {2111  if (!derivedKey) throw new Error("vault_locked");21122113  const sanitized = sanitizeEntryDraft(entry);2114  const now = Date.now();2115  const stamp = monotonicEntryTimestamp();2116  const nextEntry: VaultEntry = {2117    ...sanitized,2118    id: crypto.randomUUID(),2119    createdAt: now,2120    modifiedAt: stamp,2121    // Stamp passwordChangedAt at creation so age tracking is accurate from2122    // day one. Non-login entries carry the same stamp harmlessly.2123    passwordChangedAt: sanitized.password ? stamp : undefined,2124  };21252126  // Clone-and-replace so a failed persist rolls back the in-memory state2127  // (COR-008). Without this, a quota-full or storage error leaves the2128  // module-level `entries` ahead of what's actually on disk.2129  const rollback = entries;2130  entries = [...entries, nextEntry];2131  try {2132    await persistEntries();2133  } catch (err) {2134    entries = rollback;2135    throw err;2136  }21372138  // Fire-and-forget breach check (only for login entries if breach monitoring is enabled or not set)2139  if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {2140    checkBreach(nextEntry.password).then(async (count) => {2141      if (count > 0) {2142        const idx = entries.findIndex((e) => e.id === nextEntry.id);2143        if (idx !== -1) {2144          entries[idx] = { ...entries[idx], breach: count, modifiedAt: monotonicEntryTimestamp(entries[idx].modifiedAt) };2145          await persistEntries();2146        }2147      }2148    });2149  }21502151  fireSyncTrigger("vault_change");21522153  return nextEntry;2154}21552156/**2157 * Run the passkey-merge pass on the live in-memory entries and persist if2158 * anything changed. Called immediately after any passkey registration so that2159 * a same-domain TOTP-only entry already in the vault gets consolidated right2160 * away instead of waiting until the next lock/unlock cycle.2161 */2162export async function consolidatePasskeyEntries(): Promise<void> {2163  if (!derivedKey) return;2164  const { merged } = mergePasskeyOnlyIntoLogins(entries);2165  if (merged) {2166    await persistEntries();2167  }2168}21692170export async function updateEntry(2171  id: string,2172  patch: Partial<VaultEntry>2173): Promise<void> {2174  if (!derivedKey) throw new Error("vault_locked");21752176  const idx = entries.findIndex((entry) => entry.id === id);2177  if (idx === -1 || entries[idx].deletedAt) {2178    throw new Error("entry_not_found");2179  }21802181  const current = entries[idx];2182  const sanitizedPatch = sanitizeEntryPatch(patch);2183  // Refresh passwordChangedAt only when the password value actually changes —2184  // a metadata-only update (title, tags, etc.) must not reset the age clock2185  // that drives the Pro health rotation recommendation.2186  const passwordChanged =2187    "password" in patch &&2188    typeof sanitizedPatch.password === "string" &&2189    sanitizedPatch.password !== current.password;2190  const stamp = monotonicEntryTimestamp(current.modifiedAt);2191  // When the password actually changes, push the outgoing one onto the history2192  // (newest first) so the user can reveal/copy/restore it later. We record the2193  // age it carried (passwordChangedAt, falling back to createdAt) rather than2194  // `now`, so the list reflects when each password was last in effect. Only2195  // capture a non-empty prior value — clearing a password leaves no secret to2196  // keep, and we skip an immediate exact duplicate (e.g. restore-then-restore)2197  // to avoid noise.2198  const priorPassword = current.password;2199  const shouldCapture =2200    passwordChanged &&2201    typeof priorPassword === "string" &&2202    priorPassword.length > 0 &&2203    current.passwordHistory?.[0]?.password !== priorPassword;2204  const nextHistory = shouldCapture2205    ? [2206        { password: priorPassword!, changedAt: current.passwordChangedAt ?? current.createdAt },2207        ...(current.passwordHistory ?? []),2208      ].slice(0, PASSWORD_HISTORY_MAX)2209    : current.passwordHistory;2210  entries[idx] = {2211    ...current,2212    ...sanitizedPatch,2213    modifiedAt: stamp,2214    ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),2215  };2216221722182219  // Card entries must retain their card number2220  if (entries[idx].type === "card" && !entries[idx].cardNumber) {2221    entries[idx] = current;2222    throw new Error("card number is required for card entries");2223  }22242225  // Roll the in-memory entry back to its pre-edit state if the disk write2226  // fails (e.g. storage quota). Without this the module-level `entries` array2227  // would hold an edit that never landed on disk, diverging from the vault2228  // until the next unlock silently reverts it (SEV-3-A). Mirrors addEntry.2229  try {2230    await persistEntries();2231  } catch (err) {2232    entries[idx] = current;2233    throw err;2234  }22352236  // Breach check when password changes: clear immediately so old breach doesn't linger,2237  // then async-check the new password and only re-set if it's also found.2238  if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {2239    entries[idx] = { ...entries[idx], breach: undefined };2240    await persistEntries();2241    const password = entries[idx].password;2242    if (password) {2243      checkBreach(password).then(async (count) => {2244        const i = entries.findIndex((e) => e.id === id);2245        if (i !== -1 && count > 0) {2246          entries[i] = { ...entries[i], breach: count, modifiedAt: monotonicEntryTimestamp(entries[i].modifiedAt) };2247          await persistEntries();2248        }2249      });2250    }2251  }22522253  fireSyncTrigger("vault_change");2254}22552256export async function deleteEntry(id: string): Promise<void> {2257  if (!derivedKey) throw new Error("vault_locked");22582259  const entry = entries.find((item) => item.id === id);2260  if (!entry || entry.deletedAt) {2261    throw new Error("entry_not_found");2262  }22632264  // Tombstone timestamp must be strictly greater than the entry's last2265  // modification so the deletion wins LWW against any in-flight edit, even2266  // under clock skew (SEV-2-E).2267  const previousModifiedAt = entry.modifiedAt;2268  const previousTombstone = tombstones.get(id);2269  const stamp = monotonicEntryTimestamp(Math.max(entry.modifiedAt, previousTombstone ?? 0));2270  entry.deletedAt = stamp;2271  entry.modifiedAt = stamp;2272  tombstones.set(id, stamp);2273  // Roll the tombstone back if the disk write fails, so a quota error doesn't2274  // leave the entry deleted in memory but alive on disk (SEV-3-A).2275  try {2276    await persistEntries();2277  } catch (err) {2278    delete entry.deletedAt;2279    entry.modifiedAt = previousModifiedAt;2280    if (previousTombstone === undefined) tombstones.delete(id);2281    else tombstones.set(id, previousTombstone);2282    throw err;2283  }2284  fireSyncTrigger("vault_change");2285}22862287export function getDeletedEntries(): VaultEntry[] {2288  if (!derivedKey) return [];2289  return entries.filter((e) => !!e.deletedAt);2290}22912292/** Return all durable deletion timestamps, including purged full entries. */2293export function getTombstoneManifest(): Record<string, number> {2294  if (!derivedKey) return {};2295  return Object.fromEntries(tombstones);2296}22972298/**2299 * Returns the vault's monotonic version — the `peach_last_modified_at` value2300 * stamped on every user-initiated write. Remote (sync) writes do NOT advance2301 * this version so a sync round never cascades into a second outbound sync.2302 */2303export async function getVaultVersion(): Promise<number> {2304  try {2305    const raw = await chrome.storage.local.get("peach_last_modified_at");2306    const v = (raw as Record<string, unknown>).peach_last_modified_at;2307    if (typeof v === "number") return v;2308    if (typeof v === "string" && v !== "") {2309      const n = Number.parseInt(v, 10);2310      return Number.isFinite(n) ? n : 0;2311    }2312    return 0;2313  } catch {2314    return 0;2315  }2316}23172318/**2319 * Apply a batch of remote entries + tombstones from a sync peer.2320 * Last-write-wins by `modifiedAt`; a tombstone supersedes a live entry when2321 * `deletedAt > modifiedAt` on the local side. Mutates `entries` directly and2322 * persists with reason `sync_received` — does NOT fire the sync dispatcher, so2323 * applying a sync round cannot cascade into another outbound sync.2324 *2325 * `applied` counts entries that actually changed local state (new add,2326 * overwrite-by-newer, or new tombstone). `received` is the raw payload size2327 * the caller can surface in the sync result UI.2328 */2329export async function applyMergedRemoteEntries(2330  remoteEntries: VaultEntry[],2331  remoteTombstones: Record<string, number>,2332  _context: { deviceName?: string } = {},2333): Promise<{ received: number; applied: number; conflicts: number }> {2334  // DESIGN: last-write-wins is applied PER-ENTRY, not per-field. If two devices2335  // concurrently edit different fields of the same entry, the one with the2336  // newer modifiedAt wins the whole entry and the other device's field edits2337  // are dropped silently. This is the deliberate trade-off for a simple,2338  // conflict-free merge — per-field CRDT merge is out of scope. Guidance for2339  // users: edit a given entry on one device at a time.2340  if (!derivedKey) throw new Error("vault_locked");23412342  const received = remoteEntries.length + Object.keys(remoteTombstones).length;2343  let applied = 0;2344  let conflicts = 0;23452346  const byId = new Map<string, VaultEntry>();2347  for (const e of entries) byId.set(e.id, e);23482349  const mergeNow = Date.now();2350  const remoteTombstoneTimes = new Map<string, number>();2351  for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2352    if (typeof rawDeletedAt === "number" && Number.isFinite(rawDeletedAt) && rawDeletedAt > 0) {2353      remoteTombstoneTimes.set(id, clampSyncTimestamp(rawDeletedAt, mergeNow));2354    }2355  }23562357  for (const remote of remoteEntries) {2358    const sanitized = sanitizeRestoredEntry(remote);2359    if (!sanitized) continue;2360    // HV-1a: a far-future remote modifiedAt must not permanently pin a2361    // malicious value against honest local edits. Clamp BEFORE any2362    // comparison against local timestamps.2363    sanitized.modifiedAt = clampSyncTimestamp(sanitized.modifiedAt, mergeNow);2364    if (typeof sanitized.deletedAt === "number") {2365      sanitized.deletedAt = clampSyncTimestamp(sanitized.deletedAt, mergeNow);2366    }2367    const remoteTombstoneTs = remoteTombstoneTimes.get(sanitized.id);2368    const localTombstoneTs = tombstones.get(sanitized.id);2369    const tombstoneTs = Math.max(remoteTombstoneTs ?? 0, localTombstoneTs ?? 0);2370    if (tombstoneTs > 0 && tombstoneTs >= sanitized.modifiedAt) {2371      continue;2372    }2373    const local = byId.get(sanitized.id);2374    if (!local) {2375      entries.push(sanitized);2376      byId.set(sanitized.id, sanitized);2377      tombstones.delete(sanitized.id);2378      applied += 1;2379    } else if (sanitized.modifiedAt > local.modifiedAt) {2380      const idx = entries.findIndex((e) => e.id === local.id);2381      if (idx !== -1) {2382        entries[idx] = sanitized;2383        byId.set(sanitized.id, sanitized);2384        tombstones.delete(sanitized.id);2385        applied += 1;2386        if (!local.deletedAt) conflicts += 1;2387      }2388    }2389  }23902391  for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2392    if (typeof rawDeletedAt !== "number" || !Number.isFinite(rawDeletedAt) || rawDeletedAt <= 0) continue;2393    // HV-1a/1c: clamp the tombstone timestamp before every comparison.2394    const deletedAt = remoteTombstoneTimes.get(id)!;2395    const knownTombstone = tombstones.get(id);2396    if (knownTombstone !== undefined && knownTombstone >= deletedAt) continue;2397    const local = byId.get(id);2398    if (!local) {2399      tombstones.set(id, deletedAt);2400      applied += 1;2401      continue;2402    }2403    if (local.deletedAt && local.deletedAt >= deletedAt) continue;2404    if (deletedAt < local.modifiedAt) continue;2405    const idx = entries.findIndex((e) => e.id === id);2406    if (idx !== -1) {2407      entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };2408      tombstones.set(id, deletedAt);2409      applied += 1;2410    }2411  }24122413  if (applied > 0) {2414    await persistEntries("sync_received");2415    buildDomainIndexSync(entries);2416  }2417  return { received, applied, conflicts };2418}24192420export async function restoreEntry(id: string): Promise<void> {2421  if (!derivedKey) throw new Error("vault_locked");2422  const entry = entries.find((e) => e.id === id && e.deletedAt);2423  if (!entry) throw new Error("deleted entry not found");2424  const previousDeletedAt = entry.deletedAt;2425  const previousModifiedAt = entry.modifiedAt;2426  const previousTombstone = tombstones.get(id);2427  delete entry.deletedAt;2428  entry.modifiedAt = monotonicEntryTimestamp(Math.max(2429    entry.modifiedAt,2430    previousTombstone ?? 0,2431  ));2432  tombstones.delete(id);2433  try {2434    await persistEntries();2435  } catch (err) {2436    entry.deletedAt = previousDeletedAt;2437    entry.modifiedAt = previousModifiedAt;2438    if (previousTombstone !== undefined) tombstones.set(id, previousTombstone);2439    throw err;2440  }2441  buildDomainIndexSync(entries);2442}24432444export async function purgeEntry(id: string): Promise<void> {2445  if (!derivedKey) throw new Error("vault_locked");2446  const idx = entries.findIndex((e) => e.id === id && e.deletedAt);2447  if (idx === -1) throw new Error("deleted entry not found");2448  const entry = entries[idx]!;2449  tombstones.set(id, Math.max(tombstones.get(id) ?? 0, entry.deletedAt!));2450  entries.splice(idx, 1);2451  await persistEntries();2452}24532454/** Permanently delete entries whose deletedAt is older than retentionMs. 0 = keep forever. */2455export async function purgeExpiredTrash(retentionMs: number): Promise<number> {2456  if (!derivedKey || retentionMs === 0) return 0;2457  const cutoff = Date.now() - retentionMs;2458  const before = entries.length;2459  for (const entry of entries) {2460    if (entry.deletedAt && entry.deletedAt < cutoff) {2461      tombstones.set(entry.id, Math.max(tombstones.get(entry.id) ?? 0, entry.deletedAt));2462    }2463  }2464  entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));2465  const purged = before - entries.length;2466  if (purged > 0) await persistEntries();2467  return purged;2468}24692470export function queryDomain(domain: string): VaultEntry[] {2471  return domainIndex.get(domain) ?? [];2472}24732474export function getEntryById(id: string): VaultEntry | undefined {2475  return entries.find((entry) => entry.id === id && !entry.deletedAt);2476}24772478async function persistSlotA(2479  reason: VaultSnapshot["reason"] = "local_save",2480): Promise<StoredVault> {2481  if (!derivedKey) throw new Error("vault_locked");24822483  const slotA = await loadSlot(SLOT_A);2484  if (!slotA) throw new Error("missing slot A");24852486  // Snapshot the about-to-be-overwritten state BEFORE we mutate disk. Failures2487  // are swallowed by takeVaultSnapshot — history must never block a save.2488  await takeVaultSnapshot(reason);24892490  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);2491  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");24922493  // Preserve existing recovery escrow fields.2494  const nextSlotA: StoredVault = {2495    ...slotA,2496    nonce,2497    ciphertext,2498    tag,2499    // recovery_salt and recovery_wrapped_root_key are already set from loadSlot2500  };2501  await writeSlot(SLOT_A, nextSlotA);25022503  // Slot A (the real vault) is now committed. Wrap every later write so a2504  // mid-persist failure (e.g. a storage error after slot A landed) restores the2505  // prior slot A before rethrowing. Without this, a "failed" save that already2506  // wrote slot A leaves disk ahead of the in-memory rollback in addEntry/2507  // updateEntry/deleteEntry — the entry stays silently on disk and resurfaces2508  // as a duplicate on the next unlock (observed under storage-quota pressure).2509  try {2510    // When duress is not configured, keep slot B size-matched with slot A by2511    // regenerating its noise. When duress IS configured, leave slot B alone —2512    // we don't have the decoy key to re-encrypt it. This is a known trade-off.2513    if (!duressConfigured) {2514      await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));2515    }2516    // Only advance the vault version for locally-originated writes. Entries2517    // applied from a sync peer ("sync_received") must NOT bump the counter —2518    // otherwise applying a remote round makes us look newer than the peer and2519    // triggers a redundant outbound sync, defeating the no-op optimisation2520    // and risking a ping-pong between two devices (SEV-2-C).2521    if (reason !== "sync_received") {2522      await stampLocalVaultMutation();2523    }2524  } catch (err) {2525    // Best-effort restore — the prior slot A is smaller-or-equal, so this write2526    // fits even when the failure was a quota overflow.2527    await writeSlot(SLOT_A, slotA).catch(() => {});2528    throw err;2529  }25302531  return nextSlotA;2532}25332534async function persistSlotB(): Promise<void> {2535  if (!derivedKey) throw new Error("vault_locked");25362537  const slotB = await loadSlot(SLOT_B);2538  if (!slotB) throw new Error("missing slot B");25392540  // Decoy plaintext always reports duressConfigured=false — the decoy user2541  // sees a clean slate. persistSlotB only runs in decoy mode, which only2542  // exists once duress is configured, so pad to the fixed duress ceiling to2543  // keep slot B's length equal to slot A's (audit MEDIUM — deniability).2544  const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);2545  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");25462547  await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });2548  // Symmetric with persistSlotA: if the version stamp fails after the decoy2549  // slot committed, restore the prior slot B so a failed decoy-mode save can't2550  // leave disk ahead of the in-memory rollback.2551  try {2552    await stampLocalVaultMutation();2553  } catch (err) {2554    await writeSlot(SLOT_B, slotB).catch(() => {});2555    throw err;2556  }2557}25582559async function persistEntries(2560  reason: VaultSnapshot["reason"] = "local_save",2561): Promise<void> {2562  if (!derivedKey) throw new Error("vault_locked");25632564  // Reconcile direct soft-delete callers while restoring the previous map if2565  // storage rejects the save.2566  const previousTombstones = tombstones;2567  tombstones = new Map(tombstones);2568  reconcileTombstones();2569  try {2570    if (vaultMode === "decoy") {2571      await persistSlotB();2572    } else {2573      await persistSlotA(reason);2574    }2575  } catch (err) {2576    tombstones = previousTombstones;2577    throw err;2578  }2579  buildDomainIndexSync(entries);2580  await refreshLockedSyncState();2581}25822583// PB-26-011: drop URLs whose parsed scheme is not http(s) at the storage2584// boundary. Schemeless values (e.g. "github.com") are inert and kept — they2585// pre-date this guard in existing data. Unparseable values are kept: the2586// reviewed render paths never execute them (favicons via _favicon/, domains2587// via tldts); this is defense-in-depth against future sinks.2588function allowHttpUrl(url: string | undefined): string {2589  const trimmed = url?.trim() ?? "";2590  if (!trimmed) return "";2591  try {2592    const parsed = new URL(trimmed);2593    if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return "";2594  } catch {2595    // No scheme to reject.2596  }2597  return trimmed;2598}25992600function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {2601  if (!Array.isArray(values)) return undefined;2602  const seen = new Set<string>();2603  const cleaned: string[] = [];2604  for (const value of values) {2605    const trimmed = typeof value === "string" ? value.trim() : "";2606    if (!trimmed) continue;2607    if (!allowHttpUrl(trimmed)) continue;2608    const key = trimmed.toLowerCase();2609    if (seen.has(key)) continue;2610    seen.add(key);2611    cleaned.push(trimmed);2612  }2613  return cleaned.length > 0 ? cleaned : undefined;2614}26152616function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {2617  const title = entry.title.trim();2618  const type: VaultEntry["type"] = entry.type ?? "login";26192620  if (!title) throw new Error("title is required");26212622  if (entry.passkey) {2623    const p = entry.passkey;2624    if (2625      !p.rpId ||2626      !p.credentialId ||2627      !p.publicKeyCose ||2628      !p.userHandle ||2629      !p.userName ||2630      (p.algorithm !== -7 && p.algorithm !== -8)2631    ) {2632      throw new Error("invalid passkey credential");2633    }2634  }2635  if (type === "card") {2636    if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {2637      throw new Error("cardholder name and card number are required");2638    }2639  }26402641  return {2642    type,2643    title,2644    username: type === "login" ? entry.username?.trim() ?? "" : undefined,2645    email: type === "login" ? entry.email?.trim() || undefined : undefined,2646    password: type === "login" ? entry.password : undefined,2647    url: type === "login" ? allowHttpUrl(entry.url) : undefined,2648    additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,2649    totp: type === "login" ? entry.totp?.trim() || undefined : undefined,2650    // PCH-01-019: preserve non-default TOTP params through batch-add/import so2651    // they are not silently stripped (they fall back to SHA-1/6/30 when absent).2652    totpAlgorithm: type === "login" ? entry.totpAlgorithm : undefined,2653    totpDigits: type === "login" ? entry.totpDigits : undefined,2654    totpPeriod: type === "login" ? entry.totpPeriod : undefined,2655    notes: entry.notes?.trim() || undefined,2656    breach: type === "login" ? entry.breach : undefined,2657    // PCH-01-016: the batch-add path was bypassing the MV-6 canary/tags2658    // whitelist applied on the RESTORE_ENTRIES path. Run both sanitizers here.2659    canary: type === "login" ? sanitizeCanary(entry.canary) : undefined,2660    tags: sanitizeTags(entry.tags),2661    passkey: entry.passkey,2662    cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,2663    cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,2664    expMonth: type === "card" ? entry.expMonth?.trim() : undefined,2665    expYear: type === "card" ? entry.expYear?.trim() : undefined,2666    cvc: type === "card" ? entry.cvc?.trim() : undefined,2667    cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,2668    network: type === "card" ? entry.network : undefined,2669    last4: type === "card" ? entry.last4?.trim() : undefined,2670  };2671}26722673function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {2674  const nextPatch: Partial<VaultEntry> = {};26752676  if ("type" in patch) {2677    nextPatch.type = patch.type;2678  }26792680  if ("title" in patch) {2681    const title = patch.title?.trim() ?? "";2682    if (!title) throw new Error("title is required");2683    nextPatch.title = title;2684  }26852686  if ("url" in patch) {2687    nextPatch.url = allowHttpUrl(patch.url);2688  }26892690  if ("additionalUrls" in patch) {2691    const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];2692    const seen = new Set<string>();2693    const cleaned: string[] = [];2694    for (const value of incoming) {2695      const trimmed = typeof value === "string" ? value.trim() : "";2696      if (!trimmed || !allowHttpUrl(trimmed)) continue;2697      const key = trimmed.toLowerCase();2698      if (seen.has(key)) continue;2699      seen.add(key);2700      cleaned.push(trimmed);2701    }2702    nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;2703  }27042705  if ("username" in patch) {2706    nextPatch.username = patch.username?.trim() ?? "";2707  }27082709  if ("email" in patch) {2710    nextPatch.email = patch.email?.trim() || undefined;2711  }27122713  if ("password" in patch) {2714    const password = patch.password ?? "";2715    // Allow clearing a password (e.g. on passkey-only entries)2716    nextPatch.password = password || undefined;2717  }27182719  if ("totp" in patch) {2720    nextPatch.totp = patch.totp?.trim() || undefined;2721  }27222723  if ("notes" in patch) {2724    nextPatch.notes = patch.notes?.trim() || undefined;2725  }27262727  if ("breach" in patch) {2728    nextPatch.breach = patch.breach;2729  }27302731  if ("canary" in patch) {2732    // PCH-02-001: route update patches through the same canary whitelist used2733    // by add/restore/sync. Invalid shapes drop the canary; `undefined` clears it.2734    nextPatch.canary = patch.canary ? sanitizeCanary(patch.canary) : undefined;2735  }27362737  if ("passkey" in patch) {2738    // A patch with `passkey: undefined` removes the credential from the entry2739    // (used by "remove passkey" without deleting the whole entry).2740    if (patch.passkey === undefined || patch.passkey === null) {2741      nextPatch.passkey = undefined;2742    } else {2743      const sanitized = sanitizePasskey(patch.passkey);2744      if (!sanitized) throw new Error("invalid passkey credential");2745      nextPatch.passkey = sanitized;2746    }2747  }27482749  if ("tags" in patch) {2750    // PCH-02-001: bound tags exactly like both import funnels.2751    nextPatch.tags = sanitizeTags(patch.tags);2752  }27532754  if ("cardholderName" in patch) {2755    nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;2756  }2757  if ("cardNumber" in patch) {2758    const n = patch.cardNumber ?? "";2759    nextPatch.cardNumber = n || undefined;2760  }2761  if ("expMonth" in patch) {2762    nextPatch.expMonth = patch.expMonth?.trim() || undefined;2763  }2764  if ("expYear" in patch) {2765    nextPatch.expYear = patch.expYear?.trim() || undefined;2766  }2767  if ("cvc" in patch) {2768    nextPatch.cvc = patch.cvc?.trim() || undefined;2769  }2770  if ("cardNickname" in patch) {2771    nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;2772  }2773  if ("network" in patch) {2774    nextPatch.network = patch.network;2775  }2776  if ("last4" in patch) {2777    nextPatch.last4 = patch.last4?.trim() || undefined;2778  }27792780  return nextPatch;2781}27822783function normalizeEntry(entry: VaultEntry): VaultEntry {2784  const base: VaultEntry = {2785    id: entry.id,2786    type: entry.type,2787    title: entry.title,2788    username: entry.username,2789    email: entry.email,2790    password: entry.password,2791    url: entry.url,2792    additionalUrls:2793      "additionalUrls" in entry && Array.isArray(entry.additionalUrls)2794        ? entry.additionalUrls2795        : undefined,2796    totp: entry.totp,2797    // PCH-01-019: carry TOTP params through the normalize/restore path too.2798    totpAlgorithm: entry.totpAlgorithm,2799    totpDigits: entry.totpDigits,2800    totpPeriod: entry.totpPeriod,2801    notes: entry.notes,2802    breach: entry.breach,2803    // Preserve the password-age clock across lock/unlock. Without this the2804    // field is dropped on every decode and the advanced-health "aged password"2805    // signal silently resets to createdAt on each unlock (SEV-2-A).2806    passwordChangedAt:2807      "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,2808    // Preserve past-password history across lock/unlock. normalizeEntry is a2809    // field whitelist, so an unlisted field is silently dropped on every decode2810    // (same class as the passwordChangedAt SEV-2-A above).2811    passwordHistory:2812      "passwordHistory" in entry && Array.isArray(entry.passwordHistory)2813        ? entry.passwordHistory2814        : undefined,2815    canary: entry.canary,2816    passkey: entry.passkey,2817    createdAt: entry.createdAt,2818    modifiedAt: entry.modifiedAt,2819    deletedAt: entry.deletedAt,2820    tags: entry.tags,2821    cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,2822    cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,2823    expMonth: "expMonth" in entry ? entry.expMonth : undefined,2824    expYear: "expYear" in entry ? entry.expYear : undefined,2825    cvc: "cvc" in entry ? entry.cvc : undefined,2826    cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,2827    network: "network" in entry ? entry.network : undefined,2828    last4: "last4" in entry ? entry.last4 : undefined,2829  };28302831  return base;2832}283328342835// ---------------------------------------------------------------------------2836// Deduplication2837// ---------------------------------------------------------------------------28382839function entryDupeKey(e: VaultEntry): string {2840  if (e.type === "note") return `note|${e.title.toLowerCase()}`;2841  // Passkey-bearing entries dedupe by the credential's RP + user. Two logins2842  // on different sites that happen to share a username are still distinct;2843  // two passkey credentials for the same RP+user are duplicates regardless2844  // of any login fields they may also carry.2845  if (e.passkey) {2846    return `passkey|${e.passkey.rpId.toLowerCase()}|${e.passkey.userName.toLowerCase()}`;2847  }2848  return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;2849}28502851/** Returns the number of duplicate entries (those that would be removed). */2852export function countDuplicates(): number {2853  const best = new Map<string, VaultEntry>();2854  let dupeCount = 0;2855  for (const e of entries.filter((e) => !e.deletedAt)) {2856    const key = entryDupeKey(e);2857    const existing = best.get(key);2858    if (!existing) {2859      best.set(key, e);2860    } else {2861      dupeCount++;2862      // Keep the more recently modified one in the map2863      if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2864        best.set(key, e);2865      }2866    }2867  }2868  return dupeCount;2869}28702871/**2872 * Soft-deletes duplicate entries, keeping the most recently modified copy of2873 * each group. Returns the number of entries moved to trash.2874 */2875export async function deduplicateEntries(): Promise<number> {2876  if (!derivedKey) throw new Error("vault_locked");2877  // Dedup reshapes slot B permanently under the decoy key, which is2878  // forensically distinguishable from a freshly-seeded decoy vault. Refuse.2879  if (vaultMode === "decoy") {2880    throw new Error("deduplicate disabled in decoy mode");2881  }28822883  const best = new Map<string, VaultEntry>();2884  for (const e of entries.filter((en) => !en.deletedAt)) {2885    const key = entryDupeKey(e);2886    const existing = best.get(key);2887    if (!existing) {2888      best.set(key, e);2889    } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2890      best.set(key, e);2891    }2892  }28932894  const keepIds = new Set(Array.from(best.values()).map((e) => e.id));2895  let removed = 0;2896  entries = entries.map((e) => {2897    if (!e.deletedAt && !keepIds.has(e.id)) {2898      removed++;2899      const deletedAt = monotonicEntryTimestamp(Math.max(2900        e.modifiedAt,2901        tombstones.get(e.id) ?? 0,2902      ));2903      tombstones.set(e.id, deletedAt);2904      return { ...e, deletedAt };2905    }2906    return e;2907  });29082909  if (removed > 0) await persistEntries();2910  return removed;2911}29122913// ---------------------------------------------------------------------------2914// Vault history — snapshot BEFORE every vault write so the saved blob is2915// what is about to be lost, not what was just written. Capped at 5. The2916// stored blobs are AES-256-GCM ciphertext under the master password, so2917// history adds zero security surface.2918// ---------------------------------------------------------------------------29192920const HISTORY_KEY = "peach_vault_history";2921const HISTORY_MAX = 5;29222923// PCH-01-023: coarsen a live-entry count into a low-resolution bucket so the2924// plaintext snapshot field cannot reveal exact vault size or single-entry change2925// deltas. Buckets widen as the vault grows so absolute leakage stays roughly2926// proportional rather than exact.2927function bucketEntryCount(n: number): number {2928  if (n <= 0) return 0;2929  if (n <= 10) return 10;2930  if (n <= 25) return 25;2931  if (n <= 50) return 50;2932  if (n <= 100) return 100;2933  if (n <= 250) return 250;2934  if (n <= 500) return 500;2935  return Math.ceil(n / 500) * 500;2936}29372938/**2939 * Snapshot the CURRENT on-disk vault state into history. Call this BEFORE2940 * overwriting peach_vault_a so the saved blob captures the about-to-be-lost2941 * state. Identical-to-most-recent blobs are skipped to avoid filling history2942 * with no-op writes.2943 */2944export async function takeVaultSnapshot(2945  reason: VaultSnapshot["reason"],2946): Promise<void> {2947  try {2948    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);2949    const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];2950    const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];29512952    // Nothing to snapshot if the real slot doesn't exist yet (fresh install,2953    // pre-createVault). createVault skips snapshots intentionally — there is2954    // no prior state to preserve.2955    if (!slotA) return;29562957    const vault_a = JSON.stringify(slotA);2958    const vault_b = JSON.stringify(slotB ?? slotA);29592960    // Best-effort entry count: only meaningful when the in-memory state is2961    // unlocked AND in real mode. Decoy mode would leak the decoy entry2962    // count; locked mode has no entries to count. Both fall through to null.2963    // PCH-01-023: store a coarse bucket, not the exact count — chrome.storage2964    // .local sits next to the AES-GCM blobs in plaintext, so an exact count would2965    // leak vault size and per-write deltas (the metadata padding hides this).2966    let entryCount: number | null = null;2967    if (derivedKey && vaultMode === "real") {2968      try {2969        entryCount = bucketEntryCount(entries.filter((e) => !e.deletedAt).length);2970      } catch {2971        entryCount = null;2972      }2973    }29742975    const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];2976    const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)2977      ? existingRaw2978      : { snapshots: [] };29792980    // Deduplication: if the most recent snapshot has byte-identical blobs,2981    // skip — saves the same vault N times in a row would otherwise burn the2982    // entire history window with no recovery value.2983    const latest = history.snapshots[0];2984    if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {2985      return;2986    }29872988    const snapshot: VaultSnapshot = {2989      id: crypto.randomUUID(),2990      savedAt: Date.now(),2991      reason,2992      vault_a,2993      vault_b,2994      entryCount,2995    };29962997    history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);2998    await chrome.storage.local.set({ [HISTORY_KEY]: history });2999  } catch (err) {3000    // Non-fatal — history must never block a save. A failed snapshot just3001    // means the user loses one rung of the safety ladder for this write.3002    // M4/QUA-006: log so the failure is visible; if it looks like a quota3003    // problem, notify the popup so the user can prune history themselves.3004    console.warn('[Peach] takeVaultSnapshot failed:', err);3005    if (String(err).includes('QUOTA') || String(err).includes('quota')) {3006      try {3007        await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });3008      } catch {3009        // popup may be closed; surfaced via console.warn above3010      }3011    }3012  }3013}30143015/** Wipe all vault history. Called by Panic / DESTROY_VAULT. */3016export async function clearVaultHistory(): Promise<void> {3017  try {3018    await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });3019  } catch {3020    // Non-fatal — DESTROY_VAULT also runs storage.local.clear().3021  }3022}30233024/** Read all snapshots, newest first, for the Settings vault history view. */3025export async function getVaultHistory(): Promise<VaultSnapshot[]> {3026  const raw = await chrome.storage.local.get(HISTORY_KEY);3027  const history = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];3028  if (!history || !Array.isArray(history.snapshots)) return [];3029  return history.snapshots;3030}30313032/**3033 * Replace the on-disk vault with the chosen snapshot's blobs and lock the3034 * vault. The current state is itself snapshotted with reason 'restore' first3035 * so the restore is reversible. After this returns, the user must unlock3036 * with the password that matches the restored blob.3037 */3038export async function restoreVaultSnapshot(3039  snapshotId: string,3040): Promise<{ ok: true } | { ok: false; error: string }> {3041  const history = await getVaultHistory();3042  const snapshot = history.find((s) => s.id === snapshotId);3043  if (!snapshot) return { ok: false, error: "snapshot_not_found" };30443045  // Snapshot the about-to-be-replaced current state so the restore is3046  // reversible. takeVaultSnapshot is no-op when the most recent entry is3047  // byte-identical, so a restore-of-a-restore stays clean.3048  await takeVaultSnapshot("restore");30493050  let restoredA: StoredVault;3051  let restoredB: StoredVault;3052  try {3053    restoredA = JSON.parse(snapshot.vault_a) as StoredVault;3054    restoredB = JSON.parse(snapshot.vault_b) as StoredVault;3055  } catch {3056    return { ok: false, error: "snapshot_corrupt" };3057  }30583059  await writeSlot(SLOT_A, restoredA);3060  await writeSlot(SLOT_B, restoredB);3061  await stampLocalVaultMutation();30623063  // Lock so the user must prove they can decrypt the restored blob. If they3064  // restored a pre-password-change snapshot they discover it immediately at3065  // the lock screen rather than silently holding an inaccessible vault.3066  lock();30673068  return { ok: true };3069}30703071/**3072 * Rotate the vault's sync identity by generating a FRESH ROOT KEY and3073 * re-wrapping everything under it (MV-8). Because every sync credential —3074 * vault_id, the Noise static keypair, the Ed25519 manifest signing key,3075 * and the per-entry envelope keys — derives from the root key, rotation3076 * makes a lost/stolen device's retained key material useless. All paired3077 * devices must re-pair afterwards.3078 *3079 * CONSEQUENCE THE UI MUST SURFACE: the 12 recovery words also derive from3080 * the root key, so rotation INVALIDATES the old recovery phrase. The flow3081 * sets peach_recovery_pending so the popup re-presents the new words for3082 * confirmation, same as the initial recovery-word confirmation path.3083 */3084export async function rotateSyncIdentity(): Promise<{ ok: boolean; error?: string }> {3085  if (!derivedKey || vaultMode !== "real") {3086    return { ok: false, error: "vault_locked" };3087  }3088  const slotA = await loadSlot(SLOT_A);3089  if (!slotA) return { ok: false, error: "missing_slot_a" };30903091  // 1. Fresh root key + recovery escrow (new words).3092  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =3093    await generateAndWrapRootKey();30943095  // 2. Re-wrap the new root key under the current password-derived key.3096  const newRootKey = unhex(rawRootKey);3097  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, newRootKey);30983099  // 3. Snapshot, then single atomic slot write — both escrow wrappings of3100  //    the new root key land together (same transactional rule as3101  //    changePassword). Entries are untouched: they are sealed under the3102  //    password-derived key, not the root key.3103  await takeVaultSnapshot("local_save");3104  const nextSlotA: StoredVault = {3105    ...slotA,3106    recovery_salt: recoverySalt,3107    recovery_wrapped_root_key: wrappedRootKey,3108    recovery_nonce: wrappedNonce,3109    recovery_tag: wrappedTag,3110    ...pwRoot,3111  };3112  await writeSlot(SLOT_A, nextSlotA);31133114  // 4. Swap in memory only after disk committed.3115  if (rootKey) zeroKey(rootKey);3116  rootKey = newRootKey;31173118  // 5. Old peers' identities derive from the dead root key — drop them all.3119  await clearPairedDevices();31203121  // 6. Force re-presentation of the NEW recovery words on next popup view.3122  await setRecoveryConfirmPending(); // same flag the create-vault flow uses31233124  await stampLocalVaultMutation();3125  return { ok: true };3126}31273128/**3129 * Change the master password. Re-encrypts slot A with a fresh salt + new3130 * derived key. Slot B (duress or noise) is left untouched when duress is3131 * configured — it uses an independent key derived from the duress password —3132 * and regenerated as noise when duress is not configured.3133 */3134export async function changePassword(3135  currentPassword: string,3136  newPassword: string3137): Promise<boolean> {3138  if (!derivedKey || vaultMode !== "real") return false;31393140  // Verify current password before allowing any change3141  const valid = await verifyMainPassword(currentPassword);3142  if (!valid) return false;31433144  const slotA = await loadSlot(SLOT_A);3145  if (!slotA) return false;3146  if (!rootKey) return false;31473148  // Derive fresh key from new password + new random salt3149  const newSalt = generateSalt();3150  const newKey = await deriveKey(newPassword, newSalt);31513152  // Re-encrypt the in-memory entries with the new key3153  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3154  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");31553156  // Pre-wrap root key under the new derived key. Recovery fields wrap rootKey3157  // under recovery words and remain untouched — recovery phrase keeps working3158  // across password changes (H4/COR-002).3159  const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);31603161  const finalSlotA: StoredVault = {3162    ...slotA,3163    salt: hex(newSalt),3164    nonce,3165    ciphertext,3166    tag,3167    ...pwRoot,3168  };31693170  // Snapshot the OLD-key blob before overwriting it. If the user later3171  // restores from this snapshot they will need the OLD password — the3172  // post-restore lock surfaces that immediately.3173  await takeVaultSnapshot("local_save");31743175  // Single atomic write: ciphertext, salt, and pw_root_* fields all land in3176  // one storage transaction. An SW kill before this point leaves the old3177  // slot intact; after this point everything tied to the new password is3178  // already on disk together (M6/COR-004).3179  await writeSlot(SLOT_A, finalSlotA);31803181  // Swap the in-memory key synchronously before any further await. If we3182  // threw between the Slot A write and this swap, the next persistEntries()3183  // would overwrite Slot A with old-key ciphertext, locking the user out.3184  zeroKey(derivedKey);3185  derivedKey = newKey;31863187  // PCH-01-008: the MV3 session escrow still holds the OLD key. Without this,3188  // the next service-worker restore decrypts the new-key Slot A with the stale3189  // key, fails tryDecryptSlotResult, and silently drops the user to a lock3190  // screen. Re-escrow the new key so restore survives a password change.3191  void saveSessionKey(newKey, "real");31923193  // Regenerate noise for slot B when duress is not in use. Runs after the3194  // key swap so a failure here is a disposable noise regeneration, not a3195  // lockout.3196  if (!duressConfigured) {3197    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3198  }3199  await clearPinUnlockStorage();3200  await stampLocalVaultMutation();32013202  return true;3203}