vault.ts

122.4 KB · raw

1/**2 * vault.ts — sole owner of vault state and chrome.storage vault keys.3 *4 * Every read/write of `peach_vault_a`, `peach_vault_b`, and `peach_settings`5 * goes through this module. No other file accesses those keys directly.6 * External callers reach vault operations via `messages.ts` — never by7 * importing from here cross-boundary (popup/content must not). Invariants8 * for the two-slot schema, unlock timing, and key/disk atomicity are in9 * Projects.md §3.2–§3.6.10 */1112import { deriveKey, deriveKeyRaw, generateSalt } from "../crypto/argon2";13import { extractDomain } from "../shared/domain";14import { clampSyncTimestamp } from "../shared/sync-limits";15import { computeVaultId } from "../shared/sync-identity";16// Static, not `await import()`: runtime import() throws in an MV3 service17// worker. Neither module imports vault.ts back, so there is no cycle to break.18import { triggerSyncIfReachable } from "./sync-trigger";19import { clearPairedDevices } from "./paired-devices";20import {21  rootKeyToWords,22  wordsToRootKeyMaterial,23  deriveRecoveryKey,24} from "../shared/recovery-words";25import type {26  AccentColorName,27  Canary,28  LegacyVaultEntry,29  ManualSummonRecord,30  PasskeyData,31  SavedIdentity,32  StoredVault,33  VaultEntry,34  VaultHistory,35  VaultSnapshot,36} from "../shared/types";37import { decrypt, encrypt, zeroKey } from "./aes";38import { clearAutoLock, touchAutoLock } from "./alarms";39import { setRecoveryConfirmPending } from "./recovery-pending";4041type EntryDraft = Omit<42  VaultEntry,43  "id" | "createdAt" | "modifiedAt" | "deletedAt"44>;4546// Slot-neutral storage keys (v1.4.24+). Both slots always exist; slot B47// either holds the decoy vault (when duress is configured) or random noise48// that looks identical at rest. No external indicator is stored — duress49// configuration is recorded only inside the encrypted payload of slot A.50const SLOT_A = "peach_vault_a";51const SLOT_B = "peach_vault_b";5253// Legacy keys, migrated away on first access.54const LEGACY_MAIN = "peach_vault";55const LEGACY_DECOY = "peach_decoy_vault";56const LEGACY_DURESS_FLAG = "peach_duress";5758// Plaintext is padded to the next multiple of this size before encryption.59// This coarsens ciphertext-length leakage into 1 KiB buckets.60const PAD_BLOCK = 1024;6162// How many past passwords to retain per entry. Generous enough to be useful as63// a recovery aid while bounding the secret material we hold (and the ciphertext64// growth) for an entry whose password is rotated frequently.65const PASSWORD_HISTORY_MAX = 50;6667// When duress is configured, BOTH slots are padded to this fixed ceiling so68// their ciphertext lengths are identical and cannot reveal that a hidden decoy69// vault exists (audit MEDIUM — plausible-deniability leak). 256 KiB comfortably70// holds a very large vault (thousands of entries incl. passkeys). The decoy71// slot can't be re-encrypted on every real-vault save (the real session has no72// decoy key), so a fixed ceiling — rather than size-matching on each write — is73// what keeps the two slots equal. A real vault whose plaintext exceeds this74// would grow past the ceiling and re-expose the bit; that is an extreme,75// documented edge well beyond normal use.76const DURESS_SLOT_SIZE = 262_144;7778let derivedKey: Uint8Array | null = null;79// 32-byte random root key, separate from the derivedKey used for vault encryption.80// The root key is wrapped (encrypted) under the recovery key derived from the81// 12-word phrase. When the user changes their password, only the wrapping changes;82// the root key and recovery words remain stable.83let rootKey: Uint8Array | null = null;84let entries: VaultEntry[] = [];85// Tombstones outlive their full entry records so a peer that was offline86// during a purge cannot reintroduce an old ciphertext envelope. This map is87// serialized only inside the encrypted vault payload.88let tombstones = new Map<string, number>();89let domainIndex: Map<string, VaultEntry[]> = new Map();90let vaultMode: "real" | "decoy" = "real";91// Cached post-unlock view of whether the real vault records that duress is92// configured. Only meaningful after a real-mode unlock; for decoy-mode unlock93// this stays false because we never see slot A's plaintext.94let duressConfigured = false;9596let migrationRan = false;9798// Set to a corruption reason during the last unlock() attempt when both slots99// decrypted but failed schema validation. Consumed and cleared by100// consumeLastUnlockFailureReason() so messages.ts can surface vault_corrupted101// distinctly from wrong-password (M7/COR-007).102//103// NOTE: module-level state — if vault.ts is ever moved to a worker context,104// this must be replaced with a structured return value from unlock() or a105// postMessage channel. The signal is invisible across module-instance106// boundaries.107let lastUnlockFailureReason: string | null = null;108109export function consumeLastUnlockFailureReason(): string | null {110  const r = lastUnlockFailureReason;111  lastUnlockFailureReason = null;112  return r;113}114115// ---------------------------------------------------------------------------116// Settings (persisted inside the encrypted vault store as a sidecar key)117// ---------------------------------------------------------------------------118119export type TextSize = "small" | "medium" | "large";120121export interface VaultSettings {122  accentColor?: AccentColorName;123  theme?: "dark" | "light";124  autoLockMinutes?: number;125  clipboardClearSeconds?: number;126  lockOnClose?: boolean;127  breachMonitoring?: boolean;128  passkeyProviderEnabled?: boolean;129  trashRetentionDays?: number;130  manualSummonDomains?: Record<string, ManualSummonRecord>;131  declinedCardFingerprints?: string[];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_MIN_LENGTH = 4;168const PIN_MAX_LENGTH = 12;169170let settings: VaultSettings = {};171172export function getSettings(): VaultSettings {173  return settings;174}175176export async function ensureSettingsLoaded(): Promise<VaultSettings> {177  await loadSettings();178  return settings;179}180181export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {182  await loadSettings();183  // LV-7: cheap insurance against prototype pollution if a future caller ever184  // feeds parsed external JSON here (native spread keeps __proto__ an own-185  // property today, but Object.assign-style consumers and JSON revivers have186  // been burned before).187  const safe = Object.fromEntries(188    Object.entries(patch).filter(189      ([k]) => !["__proto__", "constructor", "prototype"].includes(k),190    ),191  ) as Partial<VaultSettings>;192  settings = { ...settings, ...safe };193  await persistSettings();194}195196function isValidPin(pin: string): boolean {197  return new RegExp(`^\\d{${PIN_MIN_LENGTH},${PIN_MAX_LENGTH}}$`).test(pin);198}199200/** Set up a local PIN wrapper after proving the current master password. */201export async function setupPinUnlock(currentPassword: string, pin: string): Promise<boolean> {202  if (!derivedKey || vaultMode !== "real" || !isValidPin(pin)) return false;203  if (!(await verifyMainPassword(currentPassword))) return false;204205  const salt = generateSalt();206  const pinKey = await deriveKey(pin, salt);207  try {208    const wrapped = await encrypt(pinKey, hex(derivedKey), "pin_wrap_v1");209    await chrome.storage.local.set({210      [PIN_WRAP_STORAGE]: { version: 1, salt: hex(salt), ...wrapped } satisfies StoredPinWrap,211    });212    await updateSettings({ pinEnabled: true });213    return true;214  } finally {215    zeroKey(pinKey);216  }217}218219async function clearPinUnlockStorage(): Promise<void> {220  await chrome.storage.local.remove(PIN_WRAP_STORAGE);221  await updateSettings({ pinEnabled: false });222}223224/** Remove the PIN wrapper after proving the current master password. */225export async function disablePinUnlock(currentPassword: string): Promise<boolean> {226  if (!derivedKey || vaultMode !== "real") return false;227  if (!(await verifyMainPassword(currentPassword))) return false;228  await clearPinUnlockStorage();229  return true;230}231232/** Unlock the real vault from its locally stored PIN-wrapped derived key. */233export async function unlockWithPin(pin: string): Promise<boolean> {234  if (!isValidPin(pin)) return false;235  await loadSettings();236  if (!settings.pinEnabled) return false;237238  const stored = (await chrome.storage.local.get(PIN_WRAP_STORAGE))[PIN_WRAP_STORAGE] as239    | StoredPinWrap240    | undefined;241  if (242    !stored ||243    stored.version !== 1 ||244    !stored.salt ||245    !stored.nonce ||246    !stored.ciphertext ||247    !stored.tag248  ) return false;249250  const pinKey = await deriveKey(pin, unhex(stored.salt));251  let unwrappedKey: Uint8Array | null = null;252  try {253    const masterKeyHex = await decrypt(254      pinKey,255      stored.nonce,256      stored.ciphertext,257      stored.tag,258      "pin_wrap_v1",259    );260    if (!/^[0-9a-f]{64}$/.test(masterKeyHex)) return false;261    unwrappedKey = unhex(masterKeyHex);262    const result = await unlockWithKey(masterKeyHex);263    if (!result.ok) return false;264    await saveSessionKey(unwrappedKey, "real");265    return true;266  } catch {267    return false;268  } finally {269    zeroKey(pinKey);270    if (unwrappedKey) zeroKey(unwrappedKey);271  }272}273274async function persistSettings(): Promise<void> {275  try {276    await chrome.storage.local.set({ peach_settings: settings });277  } catch (err) {278    throw mapStorageError(err);279  }280}281282function mapStorageError(err: unknown): Error {283  const message = err instanceof Error ? err.message : String(err);284  if (/QUOTA_BYTES|quota/i.test(message)) {285    return new Error("STORAGE_QUOTA_EXCEEDED");286  }287  return err instanceof Error ? err : new Error(message);288}289290async function loadSettings(): Promise<void> {291  const result = await chrome.storage.local.get("peach_settings");292  settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};293}294295// Fire-and-forget sync trigger after a committed vault write. A failure here296// must never fail the write that caused it.297function fireSyncTrigger(reason: "vault_change"): void {298  void Promise.resolve()299    .then(() => triggerSyncIfReachable({ reason }))300    .catch(() => {301      /* no sync runner registered, or nothing reachable — non-fatal */302    });303}304305let lockedSyncRefreshHook: (() => Promise<void>) | null = null;306let lockedSyncUnlockHook: (() => Promise<void>) | null = null;307308export function setLockedSyncHooks(hooks: {309  refresh: () => Promise<void>;310  afterUnlock: () => Promise<void>;311}): void {312  lockedSyncRefreshHook = hooks.refresh;313  lockedSyncUnlockHook = hooks.afterUnlock;314}315316async function refreshLockedSyncState(): Promise<void> {317  if (vaultMode !== "real" || !rootKey || !lockedSyncRefreshHook) return;318  await lockedSyncRefreshHook().catch((error) => {319    console.warn("[Peach sync] locked spool refresh failed:", error);320  });321}322323// ---------------------------------------------------------------------------324// HIBP breach check (k-anonymity model)325// ---------------------------------------------------------------------------326327export async function checkBreach(password: string): Promise<number> {328  // HIBP k-anonymity API is keyed on SHA-1 prefixes — this is dictated by329  // the public API, not a security choice. Do not migrate to SHA-256 here.330  const encoder = new TextEncoder();331  const hashBuffer = await crypto.subtle.digest("SHA-1", encoder.encode(password));332  const hashHex = Array.from(new Uint8Array(hashBuffer))333    .map((b) => b.toString(16).padStart(2, "0"))334    .join("")335    .toUpperCase();336337  const prefix = hashHex.slice(0, 5);338  const suffix = hashHex.slice(5);339340  try {341    // PCH-02-007: request HIBP response padding so response length does not342    // reveal how many suffixes a queried prefix returned.343    const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`, {344      headers: { "Add-Padding": "true" },345    });346    if (!res.ok) return 0;347    const text = await res.text();348    const match = text.split("\r\n").find((l) => l.startsWith(suffix));349    return match ? parseInt(match.split(":")[1], 10) : 0;350  } catch {351    return 0; // Network unavailable — don't block352  }353}354355export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {356  const fingerprint = await cardFingerprint(last4, expMonth, expYear);357  await loadSettings();358  settings = {359    ...settings,360    declinedCardFingerprints: [...(settings.declinedCardFingerprints ?? []), fingerprint],361  };362  await persistSettings();363}364365export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {366  await loadSettings();367  const fingerprint = await cardFingerprint(last4, expMonth, expYear);368  return (settings.declinedCardFingerprints ?? []).includes(fingerprint);369}370371async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {372  const encoder = new TextEncoder();373  const buf = await crypto.subtle.digest("SHA-256", encoder.encode(`${last4}|${expMonth}|${expYear}`));374  return Array.from(new Uint8Array(buf).slice(0, 8))375    .map((b) => b.toString(16).padStart(2, "0"))376    .join("");377}378379function hex(buf: Uint8Array): string {380  return Array.from(buf)381    .map((b) => b.toString(16).padStart(2, "0"))382    .join("");383}384385function unhex(s: string): Uint8Array {386  const out = new Uint8Array(s.length / 2);387  for (let i = 0; i < s.length; i += 2) {388    out[i / 2] = parseInt(s.slice(i, i + 2), 16);389  }390  return out;391}392393// ---------------------------------------------------------------------------394// Root key generation and recovery word wrapping395// ---------------------------------------------------------------------------396397/**398 * Generate a random 32-byte root key and wrap it (AES-256-GCM) under a key399 * derived from the recovery word material via HKDF-SHA256. The wrapped blob400 * fields are stored in slot A alongside the password-wrapped ciphertext. The401 * root key itself is kept in memory for the session so getRecoveryWords() can402 * encode it without re-deriving.403 *404 * SECURITY MODEL (PCH-01-005): the recovery KEK is derived from the 12-word405 * material, which encodes only rootKey[0..16] (recovery-words.ts). The KEK is thus406 * derived from a PREFIX of the very plaintext it wraps, and effective recovery407 * security is 128-bit (standard for a 12-word phrase), NOT 256-bit. This is safe —408 * unwrapping requires the words, and the GCM ciphertext leaks nothing without them —409 * but it is intentional, not an oversight. A future escrow version wanting 256-bit410 * recovery must derive the words from INDEPENDENT entropy, not from the root key.411 */412async function generateAndWrapRootKey(): Promise<{413  rawRootKey: string; // hex of the plaintext root key — caller stores in rootKey414  recoverySalt: string;415  wrappedRootKey: string;416  wrappedNonce: string;417  wrappedTag: string;418}> {419  const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));420421  // Derive the recovery key from the BIP39 words encoding of the root key.422  const words = await rootKeyToWords(rootKeyBytes);423  const wordMaterial = await wordsToRootKeyMaterial(words);424  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));425  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);426427  // Wrap the root key with the recovery key using AES-256-GCM directly.428  // We hex-encode rootKeyBytes so the plaintext is always valid UTF-8.429  const nonce = crypto.getRandomValues(new Uint8Array(12));430  const encoded = new TextEncoder().encode(hex(rootKeyBytes));431  const raw = await crypto.subtle.encrypt(432    {433      name: "AES-GCM",434      iv: nonce,435      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,436      tagLength: 128,437    },438    recoveryKey,439    encoded440  );441  // WebCrypto returns ciphertext || auth tag concatenated; split them.442  const rawU8 = new Uint8Array(raw);443  const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));444  const tag = hex(rawU8.slice(rawU8.length - 16));445446  return {447    rawRootKey: hex(rootKeyBytes),448    recoverySalt: hex(recoverySalt),449    wrappedRootKey: ciphertext,450    wrappedNonce: hex(nonce),451    wrappedTag: tag,452  };453}454455async function wrapExistingRootKeyForRecovery(rootKeyBytes: Uint8Array): Promise<{456  recoverySalt: string;457  wrappedRootKey: string;458  wrappedNonce: string;459  wrappedTag: string;460}> {461  if (rootKeyBytes.length !== 32) {462    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");463  }464465  const words = await rootKeyToWords(rootKeyBytes);466  const wordMaterial = await wordsToRootKeyMaterial(words);467  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));468  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);469  const nonce = crypto.getRandomValues(new Uint8Array(12));470  const encoded = new TextEncoder().encode(hex(rootKeyBytes));471  const raw = await crypto.subtle.encrypt(472    {473      name: "AES-GCM",474      iv: nonce,475      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,476      tagLength: 128,477    },478    recoveryKey,479    encoded,480  );481  const rawU8 = new Uint8Array(raw);482  return {483    recoverySalt: hex(recoverySalt),484    wrappedRootKey: hex(rawU8.slice(0, rawU8.length - 16)),485    wrappedNonce: hex(nonce),486    wrappedTag: hex(rawU8.slice(rawU8.length - 16)),487  };488}489490/**491 * Unwrap the root key using recovery words. Called during recovery flow when492 * the user provides their 12-word phrase and a new password.493 * Exported for use by the RECOVER_WITH_WORDS message handler.494 */495export async function unwrapRootKeyForRecovery(496  wrappedRootKey: string,497  wrappedNonce: string,498  wrappedTag: string,499  recoverySaltHex: string,500  words: string[]501): Promise<void> {502  const wordMaterial = await wordsToRootKeyMaterial(words);503  const recoverySalt = unhex(recoverySaltHex);504  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);505506  // Decrypt and cache the root key. The root key bytes were hex-encoded before507  // encryption so the ciphertext is valid UTF-8. We inline the AES-GCM decrypt508  // here to avoid passing a CryptoKey to the string-based encrypt/decrypt helpers.509  // Each component is stored separately in the vault slot; decode them individually510  // so the nonce is always exactly the 12 bytes from wrappedNonce.511  const nonceRaw = unhex(wrappedNonce);512  const ciphertextRaw = unhex(wrappedRootKey);513  const tagRaw = unhex(wrappedTag);514  // Combine ciphertext and tag for AES-GCM (expects ciphertext||tag).515  // Use explicit ArrayBuffer allocations to satisfy TS BufferSource constraints.516  const nonceU8 = nonceRaw as unknown as Uint8Array<ArrayBuffer>;517  const combined = new Uint8Array(ciphertextRaw.length + tagRaw.length);518  combined.set(ciphertextRaw, 0);519  combined.set(tagRaw, ciphertextRaw.length);520  const raw = await crypto.subtle.decrypt(521    { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },522    recoveryKey,523    combined524  );525  const decryptedHex = new TextDecoder().decode(raw);526  rootKey = unhex(decryptedHex);527}528529/**530 * Re-wrap the cached root key under a new derived key (from the user's new531 * password). Called after password change and after recovery re-key so the532 * same recovery words continue to work with the updated password — and so533 * subsequent unlocks can rehydrate rootKey via deriveRootKeyFromDerivedKey.534 *535 * recovery_* fields are intentionally not touched: those wrap rootKey under536 * the recovery words, which do not change when the password changes.537 */538export async function rewrapRootKeyForPassword(539  newDerivedKey: Uint8Array,540  _newSalt: Uint8Array541): Promise<void> {542  if (!rootKey) throw new Error("root key not set");543  const slotA = await loadSlot(SLOT_A);544  if (!slotA) throw new Error("missing slot A");545  const pwRoot = await wrapRootKeyForDerivedKey(newDerivedKey, rootKey);546  await writeSlot(SLOT_A, { ...slotA, ...pwRoot });547}548549/**550 * Change the vault encryption to a new derived key (already derived from551 * the user's new password). Used by RECOVER_WITH_WORDS and changePassword.552 * Caller is responsible for key swap and snapshot.553 */554async function reencryptVaultForNewKey(555  newKey: Uint8Array,556  slotA: StoredVault557): Promise<void> {558  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);559  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");560  await writeSlot(SLOT_A, {561    ...slotA,562    nonce,563    ciphertext,564    tag,565  });566}567568/**569 * Full password change with an already-derived key (used after recovery).570 * Unlike changePassword(), this skips re-verification of current password571 * since recovery flow has already validated the user's identity via words.572 */573export async function changePasswordWithNewKey(574  newSalt: Uint8Array,575  newKey: Uint8Array576): Promise<void> {577  const slotA = await loadSlot(SLOT_A);578  if (!slotA) throw new Error("missing slot A");579  // reencryptVaultForNewKey must receive the updated salt so that subsequent580  // UNLOCK calls with the new password can re-derive the correct key.581  await reencryptVaultForNewKey(newKey, { ...slotA, salt: hex(newSalt) });582  if (derivedKey) zeroKey(derivedKey);583  derivedKey = newKey;584  // PCH-01-008: re-escrow the new key (see changePassword). The recovery flow585  // reaches this path, so a post-recovery SW restart would otherwise lock out586  // a user who just reset their password.587  void saveSessionKey(newKey, "real");588  // Refresh pw_root_* under the new key so deriveRootKeyFromDerivedKey works589  // on the next unlock (H2/COR-006). If rootKey is missing — recovery flow590  // should have populated it — fall back silently rather than blowing up the591  // recovery path; migrateToRecovery will rehydrate on the next unlock.592  if (rootKey) {593    const slotAfter = await loadSlot(SLOT_A);594    if (slotAfter) {595      const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);596      await writeSlot(SLOT_A, { ...slotAfter, ...pwRoot });597    }598  }599  if (!duressConfigured) {600    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));601  }602  await clearPinUnlockStorage();603  await stampLocalVaultMutation();604}605606// ---------------------------------------------------------------------------607// Salt generation --- exported so the RECOVER_WITH_WORDS handler can derive608// a new key after password reset without re-importing the crypto module.609// ---------------------------------------------------------------------------610611export { deriveKey, generateSalt };612613export async function loadSlotA(): Promise<StoredVault | null> {614  return loadSlot(SLOT_A);615}616617/**618 * Recover the session root key by AES-GCM-decrypting the pw_root_* fields619 * (a second wrapping of the root key under the password-derived key). This620 * is what makes GET_RECOVERY_WORDS work across lock/unlock cycles without621 * the user re-entering their recovery phrase: the same root key bytes —622 * and therefore the same 12 words — survive every unlock.623 *624 * Returns null when the pw_root fields are absent (pre-v2.12 vault that625 * hasn't been migrated yet) or when decryption fails (wrong derived key,626 * tampered ciphertext). On null the caller should fall through to627 * migrateToRecovery() to populate the fields.628 */629async function deriveRootKeyFromDerivedKey(630  derivedKeyBytes: Uint8Array,631  slotA: StoredVault,632): Promise<Uint8Array | null> {633  if (!slotA.pw_root_ciphertext || !slotA.pw_root_nonce || !slotA.pw_root_tag) {634    return null;635  }636  try {637    const rootHex = await decrypt(638      derivedKeyBytes,639      slotA.pw_root_nonce,640      slotA.pw_root_ciphertext,641      slotA.pw_root_tag,642      "pw_root_v1",643    );644    return unhex(rootHex);645  } catch {646    return null;647  }648}649650// AES-GCM-wrap rootKey under derivedKey for the pw_root_* fields. Returns the651// hex-encoded ciphertext/nonce/tag triple ready to embed in StoredVault.652async function wrapRootKeyForDerivedKey(653  derivedKeyBytes: Uint8Array,654  rootKeyBytes: Uint8Array,655): Promise<{ pw_root_ciphertext: string; pw_root_nonce: string; pw_root_tag: string }> {656  const { nonce, ciphertext, tag } = await encrypt(derivedKeyBytes, hex(rootKeyBytes), "pw_root_v1");657  return {658    pw_root_ciphertext: ciphertext,659    pw_root_nonce: nonce,660    pw_root_tag: tag,661  };662}663664/**665 * For vaults created before v2.12 (no recovery_salt/recovery_wrapped_root_key),666 * generate the root key, wrap it under the recovery words, and persist the667 * recovery escrow into slot A. The caller must show the recovery words to the668 * user before calling this — once called, those words are the vault's recovery669 * path. This runs once, on the first unlock of an upgraded vault.670 */671export async function migrateToRecovery(): Promise<void> {672  if (!derivedKey || vaultMode !== "real") {673    throw new Error("vault must be unlocked in real mode");674  }675  const slotA = await loadSlot(SLOT_A);676  if (!slotA) throw new Error("missing slot A");677  const hasRecoveryEscrow =678    !!slotA.recovery_salt && !!slotA.recovery_wrapped_root_key;679  const hasPwRoot = !!slotA.pw_root_ciphertext && !!slotA.pw_root_nonce;680  if (hasRecoveryEscrow && hasPwRoot) return; // already done681682  // If recovery escrow already exists but pw_root doesn't, we cannot recover683  // the original rootKey without the user's words. The least-surprising path684  // is to rotate to a fresh root key — the user's old recovery words become685  // invalid but we surface peach_recovery_pending so the popup re-presents686  // the words. The unlock-path callers all set that flag.687  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =688    await generateAndWrapRootKey();689  rootKey = unhex(rawRootKey);690691  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);692  const nextSlotA: StoredVault = {693    ...slotA,694    recovery_salt: recoverySalt,695    recovery_wrapped_root_key: wrappedRootKey,696    recovery_nonce: wrappedNonce,697    recovery_tag: wrappedTag,698    ...pwRoot,699  };700  await writeSlot(SLOT_A, nextSlotA);701  await stampLocalVaultMutation();702}703704/**705 * Returns the 12 recovery words for the current session's root key.706 * Must be called while the vault is unlocked. Throws if recovery has not707 * been set up (pre-v2.12 vault that hasn't migrated yet).708 */709export async function getRecoveryWords(): Promise<string[]> {710  if (!rootKey) {711    throw new Error("recovery not set up — vault may need migration");712  }713  return rootKeyToWords(rootKey);714}715716async function loadSlot(key: string): Promise<StoredVault | null> {717  const result = await chrome.storage.local.get(key);718  return (result as Record<string, StoredVault | undefined>)[key] ?? null;719}720721async function writeSlot(key: string, vault: StoredVault): Promise<void> {722  try {723    await chrome.storage.local.set({ [key]: vault });724  } catch (err) {725    throw mapStorageError(err);726  }727}728729/**730 * Roll back a vault that was created by [createVaultFromRootKey] but731 * couldn't be paired (e.g. the subsequent license activation, identity732 * derivation, or paired-device upsert failed). Without this, a failed733 * receiver session leaves behind an empty vault — the user has to734 * re-pair to get a working setup, but the empty vault sits in the way.735 *736 * The call is idempotent: removing keys that aren't there is a no-op.737 */738export async function rollbackAdoptedVault(): Promise<void> {739  lock();740  try {741    await chrome.storage.local.remove([742      SLOT_A,743      SLOT_B,744      "peach_last_modified_at",745    ]);746  } catch (err) {747    throw mapStorageError(err);748  }749}750751async function commitCreatedVaultSlots(slotA: StoredVault, slotB: StoredVault): Promise<void> {752  const raw = await chrome.storage.local.get("peach_last_modified_at");753  const previous = Number(754    (raw as Record<string, unknown>).peach_last_modified_at,755  );756  const next = Math.max(757    Date.now(),758    Number.isFinite(previous) ? previous + 1 : 0,759  );760  try {761    await chrome.storage.local.set({762      [SLOT_A]: slotA,763      [SLOT_B]: slotB,764      peach_last_modified_at: String(next),765    });766  } catch (err) {767    throw mapStorageError(err);768  }769}770771// Monotonic clock for per-entry modifiedAt / deletedAt timestamps. Guards the772// sync layer's last-write-wins merge against wall-clock regressions (NTP step,773// manual clock change, DST glitch): a backwards Date.now() must never produce774// an entry timestamp that's <= the entry's existing modifiedAt, or a genuine775// local edit would lose to a stale remote copy. The returned value is always776// strictly greater than both the entry's current modifiedAt and the previous777// call's result (SEV-2-E).778let lastEntryTimestamp = 0;779function monotonicEntryTimestamp(currentModifiedAt?: number): number {780  const base = Math.max(781    Date.now(),782    (currentModifiedAt ?? 0) + 1,783    lastEntryTimestamp + 1,784  );785  lastEntryTimestamp = base;786  return base;787}788789async function stampLocalVaultMutation(): Promise<void> {790  const raw = await chrome.storage.local.get("peach_last_modified_at");791  const previous = Number(792    (raw as Record<string, unknown>).peach_last_modified_at,793  );794  const next = Math.max(795    Date.now(),796    Number.isFinite(previous) ? previous + 1 : 0,797  );798  await chrome.storage.local.set({799    peach_last_modified_at: String(next),800  });801}802803/**804 * One-shot migration from the pre-A-2 schema (peach_vault + peach_decoy_vault805 * + peach_duress flag) to the slot-neutral schema (peach_vault_a +806 * peach_vault_b). Runs at most once per session; safe to call repeatedly.807 */808async function ensureMigrated(): Promise<void> {809  if (migrationRan) return;810  migrationRan = true;811812  const keys = [LEGACY_MAIN, LEGACY_DECOY, LEGACY_DURESS_FLAG, SLOT_A, SLOT_B];813  const raw = await chrome.storage.local.get(keys);814  const slotAExists = raw[SLOT_A] !== undefined;815  const slotBExists = raw[SLOT_B] !== undefined;816  const legacyMain = raw[LEGACY_MAIN] as StoredVault | undefined;817  const legacyDecoy = raw[LEGACY_DECOY] as StoredVault | undefined;818819  // Fresh install with nothing in storage — nothing to do; createVault() sets up both slots.820  if (!slotAExists && !legacyMain) return;821822  // Already migrated.823  if (slotAExists && slotBExists && !legacyMain && !legacyDecoy) return;824825  let didMigrate = false;826  if (legacyMain && !slotAExists) {827    await writeSlot(SLOT_A, legacyMain);828    didMigrate = true;829  }830831  // If slot B isn't set, populate it: use legacy decoy when present, else noise.832  if (!slotBExists) {833    const target = (legacyMain ?? raw[SLOT_A]) as StoredVault | undefined;834    if (legacyDecoy) {835      await writeSlot(SLOT_B, legacyDecoy);836      didMigrate = true;837    } else if (target) {838      await writeSlot(SLOT_B, generateNoiseBlob(target.ciphertext.length / 2));839      didMigrate = true;840    }841  }842843  const toRemove: string[] = [];844  if (legacyMain) toRemove.push(LEGACY_MAIN);845  if (legacyDecoy) toRemove.push(LEGACY_DECOY);846  if (raw[LEGACY_DURESS_FLAG] !== undefined) toRemove.push(LEGACY_DURESS_FLAG);847  if (toRemove.length > 0) {848    await chrome.storage.local.remove(toRemove);849    didMigrate = true;850  }851  if (didMigrate) {852    await stampLocalVaultMutation();853  }854}855856// ---------------------------------------------------------------------------857// Padding + noise helpers858// ---------------------------------------------------------------------------859860/**861 * Pads the plaintext string with trailing spaces so that the encoded byte862 * length is a multiple of PAD_BLOCK. JSON.parse tolerates trailing863 * whitespace after a complete document, so the padding is transparent on864 * decode. Ciphertext length equals plaintext length plus a 16-byte tag.865 */866function padPlaintext(json: string, minBytes = 0): string {867  const encoded = new TextEncoder().encode(json);868  const bucket = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);869  // minBytes lets the duress path force a fixed ceiling so both slots match.870  const target = Math.max(bucket, minBytes);871  const padLen = target - encoded.length;872  return json + " ".repeat(padLen);873}874875/**876 * Produces a StoredVault-shaped record filled with CSPRNG bytes. The877 * ciphertext length matches the given byte count. Because GCM ciphertext is878 * pseudo-random, this blob is indistinguishable at rest from a real879 * encrypted vault without the key.880 *881 * crypto.getRandomValues() caps each call at 65536 bytes (the Web Crypto882 * spec hard limit). Chunk the fill so vaults larger than that — common once883 * the user has dozens of entries or any passkey — don't throw.884 */885const CSPRNG_CHUNK = 65_536;886887function fillRandom(buf: Uint8Array): Uint8Array {888  for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {889    const end = Math.min(offset + CSPRNG_CHUNK, buf.length);890    const chunk = new Uint8Array(end - offset);891    crypto.getRandomValues(chunk);892    buf.set(chunk, offset);893  }894  return buf;895}896897function generateNoiseBlob(ciphertextBytes: number): StoredVault {898  const salt = crypto.getRandomValues(new Uint8Array(16));899  const nonce = crypto.getRandomValues(new Uint8Array(12));900  const cipher = fillRandom(new Uint8Array(ciphertextBytes));901  const tag = crypto.getRandomValues(new Uint8Array(16));902  return {903    version: 1,904    salt: hex(salt),905    nonce: hex(nonce),906    ciphertext: hex(cipher),907    tag: hex(tag),908  };909}910911// ---------------------------------------------------------------------------912// Encrypted plaintext envelope913// ---------------------------------------------------------------------------914915type VaultPayload = {916  entries: VaultEntry[];917  tombstones?: Record<string, number>;918  duressConfigured?: boolean;919};920921type DecryptedPayload = {922  entries: VaultEntry[];923  tombstones: Map<string, number>;924  duressConfigured: boolean;925  /**926   * True when the on-disk payload needs a one-time rewrite: either an entry927   * had a legacy shape or the payload predates the tombstone ledger. The928   * unlock path persists the normalized shape immediately.929   */930  migratedFromLegacy: boolean;931};932933function encodePayload(entries: VaultEntry[], duress: boolean, minBytes = 0): string {934  const envelope: VaultPayload = {935    entries,936    tombstones: Object.fromEntries(tombstones),937    duressConfigured: duress,938  };939  return padPlaintext(JSON.stringify(envelope), minBytes);940}941942function decodeTombstones(raw: unknown, allEntries: VaultEntry[]): Map<string, number> {943  const result = new Map<string, number>();944  if (raw && typeof raw === "object" && !Array.isArray(raw)) {945    for (const [id, timestamp] of Object.entries(raw as Record<string, unknown>)) {946      if (typeof timestamp === "number" && Number.isFinite(timestamp) && timestamp > 0) {947        result.set(id, timestamp);948      }949    }950  }951  // Older payloads had no ledger. Rebuild the durable portion from any952  // soft-deleted entries before they are eligible for a later purge.953  for (const entry of allEntries) {954    if (typeof entry.deletedAt !== "number" || !Number.isFinite(entry.deletedAt) || entry.deletedAt <= 0) {955      continue;956    }957    if ((result.get(entry.id) ?? 0) < entry.deletedAt) {958      result.set(entry.id, entry.deletedAt);959    }960  }961  return result;962}963964function reconcileTombstones(): void {965  const byId = new Map(entries.map((entry) => [entry.id, entry]));966  for (const [id] of tombstones) {967    if (byId.has(id) && !byId.get(id)?.deletedAt) tombstones.delete(id);968  }969  for (const entry of entries) {970    if (typeof entry.deletedAt === "number" && Number.isFinite(entry.deletedAt) && entry.deletedAt > 0) {971      if ((tombstones.get(entry.id) ?? 0) < entry.deletedAt) {972        tombstones.set(entry.id, entry.deletedAt);973      }974    }975  }976}977978function rawNeedsMigration(raw: VaultEntry | LegacyVaultEntry): boolean {979  if ("created" in raw || "updated" in raw) return true;980  const flat = raw as Partial<VaultEntry>;981  if (flat.type === "passkey") return true;982  // Flat rpId without a passkey sub-object means pre-v2.11.0 schema.983  if (flat.rpId !== undefined && flat.passkey === undefined) return true;984  return false;985}986987function decodePayload(plain: string): DecryptedPayload {988  const parsed = JSON.parse(plain) as989    | Array<VaultEntry | LegacyVaultEntry>990    | VaultPayload;991992  const rawEntries = Array.isArray(parsed) ? parsed : parsed.entries ?? [];993  const flatMigrationNeeded = rawEntries.some(rawNeedsMigration);994995  const normalized = rawEntries.map(normalizeEntry);996  const { merged } = mergePasskeyOnlyIntoLogins(normalized);997  const decodedTombstones = decodeTombstones(998    Array.isArray(parsed) ? undefined : parsed.tombstones,999    normalized,1000  );10011002  if (Array.isArray(parsed)) {1003    return {1004      entries: normalized,1005      tombstones: decodedTombstones,1006      duressConfigured: false,1007      migratedFromLegacy: true, // pre-A-2 array shape always needs save1008    };1009  }10101011  return {1012    entries: normalized,1013    tombstones: decodedTombstones,1014    duressConfigured: parsed.duressConfigured === true,1015    migratedFromLegacy:1016      flatMigrationNeeded || merged || !Object.hasOwn(parsed, "tombstones"),1017  };1018}10191020/**1021 * One-time consolidation pass run alongside the legacy passkey migration.1022 *1023 * Pre-v2.11.0 the Chrome passkey path always created a fresh `type:"passkey"`1024 * entry per registration — so users who tested registration multiple times1025 * accumulated several passkey-bearing entries for the same RP, and the1026 * migration to the unified shape carried that duplication forward. This1027 * pass collapses the duplicates:1028 *1029 *   1. Group passkey-bearing (and not deleted) entries by `passkey.rpId`.1030 *   2. Within each group, the most recently-active credential wins (prefer1031 *      lastUsedAt, fall back to passkey.createdAt, fall back to modifiedAt).1032 *   3. If a NON-passkey login entry exists for that RP (matched by url or1033 *      additionalUrls hostname), attach the winning passkey to it and1034 *      soft-delete every passkey-bearing entry in the group.1035 *   4. Otherwise, soft-delete every loser in the group, keeping the winner1036 *      as a passkey-only entry.1037 *1038 * Soft delete (deletedAt) rather than splice — the trash flow keeps the1039 * record around for retention and the user can restore if the heuristic1040 * picked wrong. The `merged` flag goes back to decodePayload so the1041 * unlock path persists the consolidated shape immediately.1042 */1043function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {1044  let merged = false;1045  const now = Date.now();10461047  const candidates = entries.filter((e) => !e.deletedAt && e.passkey);1048  const byRpId = new Map<string, VaultEntry[]>();1049  for (const e of candidates) {1050    const rpId = e.passkey!.rpId;1051    const list = byRpId.get(rpId);1052    if (list) list.push(e);1053    else byRpId.set(rpId, [e]);1054  }10551056  for (const [rpId, group] of byRpId) {1057    if (group.length === 0) continue;1058    group.sort((a, b) => {1059      const aT =1060        a.passkey!.lastUsedAt ?? a.passkey!.createdAt ?? a.modifiedAt ?? a.createdAt;1061      const bT =1062        b.passkey!.lastUsedAt ?? b.passkey!.createdAt ?? b.modifiedAt ?? b.createdAt;1063      return bT - aT;1064    });1065    const winner = group[0]!;10661067    // Look for a NON-passkey login entry matching this RP. Use the URL1068    // hostname rather than a substring search so a "login.foo.com" entry1069    // doesn't accidentally absorb a passkey for "foo.com".1070    const loginTarget = entries.find((e) => {1071      if (e.deletedAt || e.passkey || e.type !== "login") return false;1072      if (e.url && extractDomain(e.url) === rpId) return true;1073      for (const extra of e.additionalUrls ?? []) {1074        if (extractDomain(extra) === rpId) return true;1075      }1076      return false;1077    });10781079    if (loginTarget) {1080      loginTarget.passkey = winner.passkey;1081      // A passkey entry may also carry the site's TOTP seed. Preserve it when1082      // the passkey is consolidated onto an existing login instead of1083      // soft-deleting the only record that held the 2FA configuration.1084      if (!loginTarget.totp && winner.totp) {1085        loginTarget.totp = winner.totp;1086        loginTarget.totpAlgorithm = winner.totpAlgorithm;1087        loginTarget.totpDigits = winner.totpDigits;1088        loginTarget.totpPeriod = winner.totpPeriod;1089      }1090      loginTarget.modifiedAt = now;1091      for (const dup of group) {1092        if (!dup.deletedAt) {1093          dup.deletedAt = now;1094          dup.modifiedAt = now;1095        }1096      }1097      merged = true;1098    } else if (group.length > 1) {1099      for (let i = 1; i < group.length; i += 1) {1100        const dup = group[i]!;1101        if (!dup.deletedAt) {1102          dup.deletedAt = now;1103          dup.modifiedAt = now;1104        }1105      }1106      merged = true;1107    }1108  }11091110  return { merged };1111}11121113// Validates that a `StoredVault` record on disk has the field shape we expect1114// before treating an AES-GCM decrypt success as a clean unlock. AES-GCM only1115// authenticates the static VERSION_BYTE AAD, not the `version` field on the1116// outer record — a corrupted `version: 42` slot still decrypts cleanly. This1117// check surfaces that as `corrupted` (M7/COR-007) so the popup can offer a1118// history-restore path instead of falsely reporting "wrong password".1119function hasValidVaultSchema(v: unknown): v is StoredVault {1120  if (typeof v !== "object" || v === null) return false;1121  const r = v as Record<string, unknown>;1122  return (1123    r.version === 1 &&1124    typeof r.salt === "string" &&1125    typeof r.nonce === "string" &&1126    typeof r.ciphertext === "string" &&1127    typeof r.tag === "string"1128  );1129}11301131export type TryDecryptResult =1132  | { status: "ok"; payload: DecryptedPayload }1133  | { status: "wrong_key" }1134  | { status: "corrupted"; reason: string };11351136// Exported solely for `unlockFromCodex` below, which needs to verify a1137// supplied passphrase against a slotA blob *without* committing anything to1138// storage. Keep this internal otherwise — callers crossing the messages.ts1139// boundary should always go through `unlock` / `verifyMainPassword` so the1140// constant-time invariants in Projects.md §3.4 are not bypassed.1141export async function tryDecryptSlot(1142  vault: StoredVault,1143  key: Uint8Array,1144  aadTag?: string,1145): Promise<DecryptedPayload | null> {1146  const res = await tryDecryptSlotResult(vault, key, aadTag);1147  return res.status === "ok" ? res.payload : null;1148}11491150export async function tryDecryptSlotResult(1151  vault: StoredVault,1152  key: Uint8Array,1153  aadTag?: string,1154): Promise<TryDecryptResult> {1155  if (!hasValidVaultSchema(vault)) {1156    return { status: "corrupted", reason: "invalid_slot_schema" };1157  }1158  let plain: string;1159  try {1160    plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);1161  } catch {1162    return { status: "wrong_key" };1163  }1164  try {1165    const parsed = JSON.parse(plain) as unknown;1166    if (typeof parsed !== "object" || parsed === null) {1167      return { status: "corrupted", reason: "invalid_payload_shape" };1168    }1169    if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {1170      return { status: "corrupted", reason: "invalid_payload_shape" };1171    }1172    return { status: "ok", payload: decodePayload(plain) };1173  } catch {1174    return { status: "corrupted", reason: "invalid_payload_json" };1175  }1176}11771178// ---------------------------------------------------------------------------1179// Core operations1180// ---------------------------------------------------------------------------11811182function buildDomainIndexSync(all: VaultEntry[]): void {1183  domainIndex = new Map();11841185  for (const entry of all) {1186    if (entry.deletedAt) continue;1187    if (entry.type === "note" || entry.type === "card") continue;11881189    // An entry can match multiple sites via `additionalUrls`. Index each1190    // hostname so `queryDomain` returns the entry regardless of which alias1191    // the user is currently visiting. Dedupe per-entry so a single entry1192    // never appears twice in one bucket.1193    const domains = new Set<string>();1194    const primary = extractDomain(entry.url ?? "");1195    if (primary) domains.add(primary);1196    for (const extra of entry.additionalUrls ?? []) {1197      const d = extractDomain(extra);1198      if (d) domains.add(d);1199    }1200    if (domains.size === 0) continue;12011202    for (const domain of domains) {1203      const bucket = domainIndex.get(domain) ?? [];1204      bucket.push(entry);1205      domainIndex.set(domain, bucket);1206    }1207  }1208}12091210export async function createVault(password: string): Promise<void> {1211  await ensureMigrated();12121213  const salt = generateSalt();1214  derivedKey = await deriveKey(password, salt);1215  entries = [];1216  tombstones = new Map();1217  vaultMode = "real";1218  duressConfigured = false;1219  buildDomainIndexSync(entries);12201221  // Generate and wrap the root key for recovery word escrow.1222  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =1223    await generateAndWrapRootKey();1224  rootKey = unhex(rawRootKey);12251226  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);1227  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");12281229  // Second wrapping of rootKey under derivedKey so future unlocks can rehydrate1230  // it without recovery words (H2/COR-006).1231  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);12321233  const slotA: StoredVault = {1234    version: 1,1235    salt: hex(salt),1236    nonce,1237    ciphertext,1238    tag,1239    recovery_salt: recoverySalt,1240    recovery_wrapped_root_key: wrappedRootKey,1241    recovery_nonce: wrappedNonce,1242    recovery_tag: wrappedTag,1243    ...pwRoot,1244  };1245  await writeSlot(SLOT_A, slotA);12461247  // Matching-size noise blob for slot B, so a fresh install shows two1248  // similarly-shaped records regardless of whether duress is ever set up.1249  await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));1250  await stampLocalVaultMutation();12511252  touchAutoLock();1253}12541255/**1256 * Creates a local vault from an existing vault root key received through the1257 * SAS-gated adoption protocol. The password is local to this device; it wraps1258 * the adopted root key at rest and does not need to match the source device.1259 */1260export async function createVaultFromRootKey(1261  password: string,1262  rootKeyHex: string,1263): Promise<{ vaultId: string }> {1264  if (typeof password !== "string" || password.length === 0) {1265    throw new Error("ADOPT_INVALID_PASSWORD");1266  }1267  if (typeof rootKeyHex !== "string" || !/^[0-9a-f]{64}$/.test(rootKeyHex)) {1268    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars");1269  }12701271  const rootKeyBytes = unhex(rootKeyHex);1272  if (rootKeyBytes.length !== 32) {1273    rootKeyBytes.fill(0);1274    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");1275  }12761277  let nextDerivedKey: Uint8Array | null = null;1278  let sessionRootKey: Uint8Array | null = null;1279  try {1280    await ensureMigrated();1281    if ((await loadSlot(SLOT_A)) !== null) {1282      throw new Error("ADOPT_VAULT_ALREADY_EXISTS");1283    }12841285    const nextEntries: VaultEntry[] = [];1286    const nextDuressConfigured = false;1287    const vaultId = await computeVaultId(rootKeyBytes);1288    const salt = generateSalt();1289    nextDerivedKey = await deriveKey(password, salt);1290    const recovery = await wrapExistingRootKeyForRecovery(rootKeyBytes);12911292    sessionRootKey = new Uint8Array(rootKeyBytes);1293    const plaintext = encodePayload(nextEntries, nextDuressConfigured, 0);1294    const { nonce, ciphertext, tag } = await encrypt(nextDerivedKey, plaintext, "slot_a_v1");1295    const pwRoot = await wrapRootKeyForDerivedKey(nextDerivedKey, sessionRootKey);1296    const slotA: StoredVault = {1297      version: 1,1298      salt: hex(salt),1299      nonce,1300      ciphertext,1301      tag,1302      recovery_salt: recovery.recoverySalt,1303      recovery_wrapped_root_key: recovery.wrappedRootKey,1304      recovery_nonce: recovery.wrappedNonce,1305      recovery_tag: recovery.wrappedTag,1306      ...pwRoot,1307    };1308    const slotB = generateNoiseBlob(ciphertext.length / 2);1309    await commitCreatedVaultSlots(slotA, slotB);13101311    const previousDerivedKey = derivedKey;1312    const previousRootKey = rootKey;1313    derivedKey = nextDerivedKey;1314    rootKey = sessionRootKey;1315    nextDerivedKey = null;1316    sessionRootKey = null;1317    entries = nextEntries;1318    tombstones = new Map();1319    vaultMode = "real";1320    duressConfigured = nextDuressConfigured;1321    buildDomainIndexSync(entries);1322    if (previousDerivedKey && previousDerivedKey !== derivedKey) zeroKey(previousDerivedKey);1323    if (previousRootKey && previousRootKey !== rootKey) previousRootKey.fill(0);1324    touchAutoLock();13251326    return { vaultId };1327  } finally {1328    rootKeyBytes.fill(0);1329    if (nextDerivedKey) zeroKey(nextDerivedKey);1330    if (sessionRootKey) sessionRootKey.fill(0);1331  }1332}13331334export async function hasVault(): Promise<boolean> {1335  await ensureMigrated();1336  return (await loadSlot(SLOT_A)) !== null;1337}13381339/**1340 * Returns whether the real vault has recorded that a duress passphrase is1341 * configured. Reliable only after a real-mode unlock — before unlock or in1342 * decoy mode, returns false because we cannot read slot A's plaintext.1343 */1344export async function isDuressEnabled(): Promise<boolean> {1345  return vaultMode === "real" && duressConfigured;1346}13471348export async function setupDuress(duressPassword: string): Promise<void> {1349  if (!derivedKey || vaultMode !== "real") {1350    throw new Error("vault must be unlocked in real mode");1351  }1352  await ensureMigrated();13531354  // Encrypt the decoy payload (empty entries) under the duress key. Pad to1355  // at least the current slot A ciphertext size so the two slots look the1356  // same at rest at setup time.1357  const slotA = await loadSlot(SLOT_A);1358  if (!slotA) throw new Error("missing slot A");13591360  const decoySalt = generateSalt();1361  const decoyKey = await deriveKey(duressPassword, decoySalt);1362  try {1363    // Pad the decoy to the fixed duress ceiling. Slot A is re-encrypted to the1364    // same ceiling by the persistSlotA() call below (duressConfigured is now1365    // true), so both slots are exactly DURESS_SLOT_SIZE+tag at rest and their1366    // lengths cannot reveal that duress is configured (audit MEDIUM).1367    const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);1368    const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");1369    await writeSlot(SLOT_B, {1370      version: 1,1371      salt: hex(decoySalt),1372      nonce,1373      ciphertext,1374      tag,1375    });1376  } finally {1377    zeroKey(decoyKey);1378  }13791380  // Re-encrypt slot A with the duressConfigured flag set to true. No external1381  // flag is written — the bit lives inside the encrypted envelope.1382  duressConfigured = true;1383  await persistSlotA();1384}13851386export async function disableDuress(): Promise<void> {1387  if (!derivedKey || vaultMode !== "real") {1388    throw new Error("vault must be unlocked in real mode");1389  }1390  await ensureMigrated();13911392  // Overwrite slot B with fresh noise that matches slot A's size. The slot1393  // remains occupied so its mere existence does not signal that duress was1394  // ever configured.1395  const slotA = await loadSlot(SLOT_A);1396  if (slotA) {1397    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));1398  }13991400  duressConfigured = false;1401  await persistSlotA();1402}14031404// L14/COR-015: this function intentionally checks slot A (real vault) only.1405// A duress-mode user attempting changePassword is rejected earlier by the1406// vaultMode === 'decoy' check at changePassword. The real-vs-decoy1407// distinction here is by design — duress users cannot rotate the real1408// password by guessing it, and the asymmetry in error timing is acceptable1409// because duress mode is opt-in and the user knows their own decoy key.1410export async function verifyMainPassword(password: string): Promise<boolean> {1411  await ensureMigrated();1412  const slotA = await loadSlot(SLOT_A);1413  if (!slotA) return false;1414  const key = await deriveKey(password, unhex(slotA.salt));1415  try {1416    return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;1417  } finally {1418    zeroKey(key);1419  }1420}14211422export async function unlock(password: string): Promise<boolean> {1423  // LV-1: the normal path NFC-normalizes inside deriveKey. If that fails and1424  // the supplied password is not already in NFC form, the vault may have been1425  // sealed (pre-LV-1) with the raw, un-normalized bytes — retry with those.1426  if (await attemptUnlockWithDerive(password, deriveKey)) return true;14271428  const nfc = password.normalize("NFC");1429  if (password === nfc) return false; // ASCII/NFC password — no legacy form to try14301431  if (await attemptUnlockWithDerive(password, deriveKeyRaw)) {1432    // Heal: re-seal the real slot under the NFC-normalized key so every1433    // future unlock takes the normal path. Only the real vault is re-sealed;1434    // a non-NFC duress password keeps working through this fallback.1435    if (vaultMode === "real") {1436      try {1437        const newSalt = generateSalt();1438        const newKey = await deriveKey(password, newSalt);1439        await changePasswordWithNewKey(newSalt, newKey);1440      } catch (healErr) {1441        console.warn("[Peach] LV-1 NFC heal failed:", healErr);1442      }1443    }1444    return true;1445  }1446  return false;1447}14481449async function attemptUnlockWithDerive(1450  password: string,1451  derive: typeof deriveKey,1452): Promise<boolean> {1453  await ensureMigrated();14541455  // Load both slots in parallel. Both always exist post-migration; the1456  // parallel load and the parallel derivation below keep wall-clock time1457  // constant regardless of which slot's passphrase (real or decoy) the1458  // caller supplied, so a timing side channel cannot distinguish the1459  // duress path from the real-unlock path (DUR-002).1460  const [slotA, slotB] = await Promise.all([1461    loadSlot(SLOT_A),1462    loadSlot(SLOT_B),1463  ]);14641465  // Derive both keys in parallel, unconditionally.1466  const [keyA, keyB] = await Promise.all([1467    slotA ? derive(password, unhex(slotA.salt)) : Promise.resolve(null),1468    slotB ? derive(password, unhex(slotB.salt)) : Promise.resolve(null),1469  ]);14701471  // Attempt both decrypts in parallel. The Result variant lets us distinguish1472  // 'wrong_key' from 'corrupted' so callers can offer a history-restore path1473  // when a slot's schema is invalid even though AES-GCM authenticated (M7).1474  const [resultA, resultB] = await Promise.all([1475    keyA && slotA1476      ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")1477      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1478    keyB && slotB1479      ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")1480      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1481  ]);1482  const payloadA = resultA.status === "ok" ? resultA.payload : null;1483  const payloadB = resultB.status === "ok" ? resultB.payload : null;14841485  if (payloadA && keyA) {1486    derivedKey = keyA;1487    void saveSessionKey(keyA, "real");1488    vaultMode = "real";1489    entries = payloadA.entries;1490    tombstones = payloadA.tombstones;1491    duressConfigured = payloadA.duressConfigured;1492    buildDomainIndexSync(entries);1493    await loadSettings();1494    touchAutoLock();1495    if (keyB) zeroKey(keyB);14961497    // slotA is non-null when payloadA is truthy (keyA was derived from slotA).1498    if (slotA) {1499      const needsRecoverySetup =1500        !slotA.recovery_salt || !slotA.recovery_wrapped_root_key;1501      if (!needsRecoverySetup) {1502        rootKey = await deriveRootKeyFromDerivedKey(keyA, slotA);1503      }1504      // Pre-v2.12 vault, or a vault whose pw_root_* fields haven't been written1505      // yet: generate the recovery escrow and seed pw_root_* so subsequent1506      // unlocks can rehydrate rootKey without the user's recovery words.1507      // Best-effort — a failure here must not block unlock.1508      if (needsRecoverySetup || !rootKey) {1509        try {1510          await migrateToRecovery();1511          if (needsRecoverySetup) {1512            // String "1" matches the popup's existing peach_recovery_pending1513            // check; surfaced so the user re-confirms recovery words after a1514            // legacy-vault unlock (H2/COR-006).1515            await chrome.storage.local.set({ peach_recovery_pending: '1' });1516          }1517        } catch (migrationErr) {1518          console.warn('[Peach] recovery migration failed:', migrationErr);1519        }1520      }1521    }15221523    // If the payload had a pre-v2.11.0 shape (legacy passkey type, flat1524    // passkey fields, or pre-A-2 created/updated keys), rewrite it now so1525    // the next save uses the new format and migration doesn't re-run forever.1526    if (payloadA.migratedFromLegacy) {1527      await persistSlotA();1528    }1529    await lockedSyncUnlockHook?.().catch((error) => {1530      console.warn("[Peach sync] locked inbox drain failed:", error);1531    });1532    return true;1533  }15341535  if (payloadB && keyB) {1536    derivedKey = keyB;1537    void saveSessionKey(keyB, "decoy");1538    vaultMode = "decoy";1539    entries = payloadB.entries;1540    tombstones = payloadB.tombstones;1541    duressConfigured = false;1542    buildDomainIndexSync(entries);1543    await loadSettings();1544    touchAutoLock();1545    if (keyA) zeroKey(keyA);1546    return true;1547  }15481549  if (keyA) zeroKey(keyA);1550  if (keyB) zeroKey(keyB);1551  // Surface corruption (good AES tag, broken schema) distinctly from1552  // wrong-password so the popup can offer history-restore (M7/COR-007).1553  if (resultA.status === "corrupted") {1554    lastUnlockFailureReason = resultA.reason;1555  } else if (resultB.status === "corrupted") {1556    lastUnlockFailureReason = resultB.reason;1557  }1558  return false;1559}15601561// ---------------------------------------------------------------------------1562// MV3 service worker session key — survives SW restarts within a browser session1563// ---------------------------------------------------------------------------15641565// chrome.storage.session is cleared on browser close; survives SW restart.1566// Firefox does not implement it (persistent background script, no restart risk).1567const SESSION_KEY_STORAGE = "peach_session_dk";15681569async function saveSessionKey(key: Uint8Array, mode: "real" | "decoy"): Promise<void> {1570  if (!chrome.storage.session) return;1571  await chrome.storage.session.set({ [SESSION_KEY_STORAGE]: { keyHex: hex(key), mode } });1572}15731574async function clearSessionKey(): Promise<void> {1575  if (!chrome.storage.session) return;1576  await chrome.storage.session.remove(SESSION_KEY_STORAGE);1577}15781579/**1580 * On SW restart, re-derive all in-memory vault state from the session key1581 * stored in chrome.storage.session (set at unlock time, cleared by lock();1582 * also cleared on browser close or when restoration fails).1583 * Returns true if the vault was restored, false if no session key was found.1584 * No-ops if the vault is already unlocked.1585 */1586export async function restoreFromSession(): Promise<boolean> {1587  if (derivedKey !== null) return true;1588  if (!chrome.storage.session) return false;1589  const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);1590  const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;1591  if (!entry?.keyHex) return false;15921593  const key = unhex(entry.keyHex);1594  const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;1595  const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";1596  const slot = await loadSlot(slotKey);1597  if (!slot) { await clearSessionKey(); return false; }15981599  const result = await tryDecryptSlotResult(slot, key, aadTag);1600  if (result.status !== "ok") { await clearSessionKey(); return false; }16011602  derivedKey = key;1603  vaultMode = entry.mode;1604  entries = result.payload.entries;1605  tombstones = result.payload.tombstones;1606  duressConfigured = entry.mode === "real" ? result.payload.duressConfigured : false;1607  buildDomainIndexSync(entries);1608  await loadSettings();1609  touchAutoLock();16101611  // The rootKey is what identity/sync derivations use. deriveRootKeyFromDerivedKey1612  // pulls it from the pw_root_* fields on the slot — set on every createVault +1613  // re-set on every password change (H2/COR-006). The previous gate on1614  // recovery_salt + recovery_wrapped_root_key silently left rootKey unset for1615  // any vault that hadn't been through migrateToRecovery, which broke background1616  // sync: the SW re-woke from the alarm, isUnlocked() was true (the session key1617  // restored derivedKey + entries), but getRootKeyHex() returned null and the1618  // runner returned VAULT_LOCKED. The fix is to always try the pw_root path1619  // when the slot has those fields — the recovery fields are independent.1620  if (entry.mode === "real") {1621    try {1622      rootKey = await deriveRootKeyFromDerivedKey(key, slot);1623    } catch {1624      /* non-fatal — sync identity will still skip on the runner's null-rootKey check */1625    }1626  }16271628  await lockedSyncUnlockHook?.().catch((error) => {1629    console.warn("[Peach sync] locked inbox drain failed:", error);1630  });16311632  return true;1633}16341635export function lock(): void {1636  // A user-initiated lock must be durable across MV3 service-worker restarts.1637  // The SW is idle-killed after ~30s of inactivity, and the popup's next open1638  // wakes a cold SW whose restoreFromSession() reads chrome.storage.session.1639  // If the session key survived lock(), that restore would silently re-unlock1640  // the vault ~a minute after the user locked it — a lock that only held1641  // while the SW happened to stay alive. The background-sync convenience the1642  // session key once bought (sync runner re-waking to a restored vault) is1643  // not worth an unlocked vault the user never asked to unlock; when locked,1644  // sync-runner correctly reports VAULT_LOCKED instead.1645  void clearSessionKey();1646  if (derivedKey) {1647    zeroKey(derivedKey);1648    derivedKey = null;1649  }1650  if (rootKey) {1651    rootKey.fill(0);1652    rootKey = null;1653  }16541655  entries = [];1656  tombstones = new Map();1657  domainIndex = new Map();1658  vaultMode = "real";1659  duressConfigured = false;1660  clearAutoLock();1661}16621663export function isUnlocked(): boolean {1664  return derivedKey !== null;1665}16661667// Opens the vault using a pre-derived AES-256 key (skipping Argon2id). The1668// PIN-unlock path unwraps this key from its PIN wrap; the passphrase path1669// always derives from scratch via Argon2id.1670export async function unlockWithKey(1671  masterKeyHex: string,1672): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {1673  try {1674    const masterKeyBytes = unhex(masterKeyHex);1675    const stored = await loadSlot(SLOT_A);1676    if (!stored) return { ok: false, error: "invalid_key" };1677    const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");1678    if (!payload) return { ok: false, error: "invalid_key" };16791680    derivedKey = masterKeyBytes;1681    vaultMode = "real";1682    entries = payload.entries;1683    tombstones = payload.tombstones;1684    duressConfigured = payload.duressConfigured;1685    buildDomainIndexSync(entries);1686    await loadSettings();1687    touchAutoLock();16881689    // PCH-01-009: the biometric path skips Argon2id but must still rehydrate the1690    // root key, exactly like attemptUnlockWithDerive and restoreFromSession.1691    // Without it, rootKey stays null after a biometric unlock and sync +1692    // GET_RECOVERY_WORDS report the open vault as locked. Guarded and non-fatal:1693    // a missing/legacy escrow must not fail the unlock itself.1694    if (stored.recovery_salt && stored.recovery_wrapped_root_key) {1695      try {1696        rootKey = await deriveRootKeyFromDerivedKey(masterKeyBytes, stored);1697      } catch { /* non-fatal — unlock still succeeds without rootKey */ }1698    }1699    return { ok: true, entries };1700  } catch {1701    return { ok: false, error: "invalid_key" };1702  }1703}17041705// --- Adoption duress-slot helpers (passthrough, no decrypt) ---17061707/**1708 * Adoption SOURCE helper: returns the sealed slot B as a JSON string when1709 * duress is configured and slot B exists, so the inline snapshot can ship it1710 * to the receiver. Returns null otherwise. Never decrypts.1711 */1712export async function exportDuressSlotForAdoption(): Promise<string | null> {1713  if (!(await isDuressEnabled())) return null;1714  await ensureMigrated();1715  const slotB = await loadSlot(SLOT_B);1716  if (!slotB) return null;1717  return JSON.stringify(slotB);1718}17191720/**1721 * Adoption RECEIVER helper: installs a duress slot received from a source1722 * device. Validates the StoredVault shape (same guard as unlockFromCodex)1723 * and writes it to slot B. Throws on invalid shape so the caller can treat1724 * it as a non-fatal snapshot failure. Never decrypts.1725 */1726export async function installAdoptedDuressSlot(json: string): Promise<void> {1727  let parsed: StoredVault;1728  try {1729    const raw = JSON.parse(json) as unknown;1730    if (!hasValidVaultSchema(raw)) {1731      throw new Error("invalid_duress_slot_shape");1732    }1733    parsed = raw;1734  } catch (err) {1735    if (err instanceof SyntaxError) {1736      throw new Error("invalid_duress_slot_shape");1737    }1738    throw err;1739  }1740  await writeSlot(SLOT_B, parsed);1741}17421743/**1744 * Restore the vault from a parsed Peach Codex payload.1745 *1746 * The supplied passphrase is verified against the Codex's slotA *before* any1747 * storage mutation — wrong passphrases return without touching disk. On1748 * success, the current vault state is snapshotted (reason: "restore") so the1749 * user can revert via Settings -> Vault History, then slotA/slotB are written1750 * and `peach_last_modified_at` is set to the Codex's recorded timestamp. A1751 * regular `unlock()` follows so the rest of the SW sees the standard1752 * post-unlock state.1753 *1754 * Intentionally non-Pro-gated — see peach_codex_v2.md "Pro gating". A Codex1755 * printed by a Pro user must always be restorable, even on a free device.1756 *1757 * Timing is not held constant here (in contrast to `unlock`): the Codex flow1758 * is an explicit user action with a known passphrase, not a passive lock1759 * screen, so the duress-vs-real timing side channel does not apply.1760 */1761export async function unlockFromCodex(params: {1762  slotA: string; // JSON string of StoredVault for slot A1763  slotB: string | null; // JSON string of StoredVault for slot B, or null1764  timestamp: number;1765  masterPassphrase: string;1766}): Promise<1767  | { ok: true; entryCount: number }1768  | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" }1769> {1770  let parsedSlotA: StoredVault;1771  let parsedSlotB: StoredVault | null = null;1772  try {1773    const rawA = JSON.parse(params.slotA) as unknown;1774    if (!hasValidVaultSchema(rawA)) {1775      return { ok: false, reason: "invalid_slot_format" };1776    }1777    parsedSlotA = rawA;1778    if (params.slotB !== null) {1779      const rawB = JSON.parse(params.slotB) as unknown;1780      if (!hasValidVaultSchema(rawB)) {1781        return { ok: false, reason: "invalid_slot_format" };1782      }1783      parsedSlotB = rawB;1784    }1785  } catch {1786    return { ok: false, reason: "invalid_slot_format" };1787  }17881789  // Verify the passphrase against the supplied slotA WITHOUT writing anything.1790  // If this fails the on-disk vault is left completely untouched.1791  const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));1792  const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");1793  if (!trialPayload) {1794    zeroKey(trialKey);1795    return { ok: false, reason: "wrong_passphrase" };1796  }1797  // Drop the trial key; `unlock()` below derives its own copy. Holding two1798  // copies of the master key in memory at once would be a needless surface.1799  zeroKey(trialKey);18001801  // Snapshot the about-to-be-overwritten on-disk state so the user can revert1802  // a mistaken Codex restore via the Vault History UI. Non-fatal if it fails.1803  await takeVaultSnapshot("restore");18041805  await writeSlot(SLOT_A, parsedSlotA);1806  if (parsedSlotB) {1807    await writeSlot(SLOT_B, parsedSlotB);1808  } else {1809    // Slot B must always exist with ciphertext length matching slot A1810    // (Projects.md §3.2). Codex prints may omit slot B (duress wasn't1811    // configured); regenerate noise to satisfy the invariant.1812    await writeSlot(1813      SLOT_B,1814      generateNoiseBlob(parsedSlotA.ciphertext.length / 2),1815    );1816  }1817  await chrome.storage.local.set({1818    peach_last_modified_at: String(params.timestamp),1819  });18201821  // Standard unlock path so domain index, settings, auto-lock, and1822  // recovery-key state all populate exactly as a normal unlock would.1823  const ok = await unlock(params.masterPassphrase);1824  if (!ok) {1825    // Should be unreachable — we just verified the passphrase against the1826    // same slotA we wrote. Treat as wrong_passphrase to keep the contract1827    // simple if some race or storage anomaly intrudes.1828    return { ok: false, reason: "wrong_passphrase" };1829  }1830  return { ok: true, entryCount: getEntries().length };1831}18321833// Returns the current in-memory derived key as a hex string. Only the PIN1834// unlock path needs this value, and it reads module state directly; this1835// accessor exists so unlockWithKey's root-key rehydration is testable.1836export /* @testable */ function getDerivedKeyHex(): string {1837  if (!derivedKey) throw new Error("vault_not_unlocked");1838  return hex(derivedKey);1839}18401841/**1842 * Returns the vault's stable root key as hex, or null when locked / not yet1843 * populated. The root key is random per-vault, generated at creation, escrowed1844 * under the recovery words, and re-wrapped (not regenerated) on every password1845 * change — so it is INVARIANT across password rotation, unlike getDerivedKeyHex.1846 *1847 * This is the correct input for sync identity derivation (vault_id, the Noise1848 * NK static key, the Ed25519 manifest signing key, and per-entry envelope1849 * keys): paired devices keep the same identity and can still decrypt each1850 * other's entries after either side rotates its master password (SEV-2-B).1851 *1852 * Returns null rather than throwing so sync callers degrade to VAULT_LOCKED1853 * instead of crashing; rootKey is populated on every real-mode unlock via1854 * deriveRootKeyFromDerivedKey / migrateToRecovery.1855 */1856export function getRootKeyHex(): string | null {1857  return rootKey ? hex(rootKey) : null;1858}18591860export function getEntries(): VaultEntry[] {1861  if (!derivedKey) throw new Error("vault_locked");1862  return entries.filter((entry) => !entry.deletedAt);1863}18641865const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;18661867export function getIdentities(): SavedIdentity[] {1868  if (!derivedKey) throw new Error("vault_locked");1869  const active = entries.filter((e) => !e.deletedAt && e.type === "login");18701871  const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();1872  const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();18731874  for (const entry of active) {1875    const domain = extractDomain(entry.url ?? "") ?? "";1876    const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;18771878    function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {1879      const existing = map.get(v);1880      if (!existing || modifiedAt > existing.lastUsed) {1881        map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });1882      } else {1883        map.set(v, { ...existing, count: existing.count + 1 });1884      }1885    }18861887    const uVal = entry.username?.trim();1888    if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);18891890    // Also count the dedicated email field — entries created via the inline1891    // popup new-entry form store email here rather than in username.1892    const eVal = entry.email?.trim();1893    if (eVal) tally(emailMap, eVal);1894  }18951896  const toIdentity = (type: "email" | "username") =>1897    ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({1898      value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,1899    });19001901  return [1902    ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),1903    ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),1904  ];1905}19061907export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {1908  if (!derivedKey) throw new Error("vault_locked");19091910  const now = Date.now();1911  const added: VaultEntry[] = [];1912  for (const draft of drafts) {1913    try {1914      const sanitized = sanitizeEntryDraft(draft);1915      const nextEntry: VaultEntry = {1916        ...sanitized,1917        id: crypto.randomUUID(),1918        createdAt: now,1919        modifiedAt: monotonicEntryTimestamp(),1920      };1921      entries.push(nextEntry);1922      added.push(nextEntry);1923    } catch {1924      // Skip invalid drafts silently — caller can see diff between input and output length1925    }1926  }19271928  if (added.length > 0) {1929    await persistEntries();1930  }19311932  return added;1933}19341935/**1936 * Restore a set of entries in full fidelity — preserves id, createdAt,1937 * modifiedAt, and every other field unlike `batchAddEntries` which1938 * assigns fresh identity. Used by restore paths where the backup is the1939 * authoritative source of truth. `mode` controls how entries already in1940 * the vault are treated.1941 */1942export async function restoreEntries(1943  incoming: VaultEntry[],1944  mode: "replace" | "merge"1945): Promise<{ added: number; updated: number; skipped: number }> {1946  if (!derivedKey) throw new Error("vault_locked");19471948  // A replace with zero incoming entries is almost certainly a caller bug1949  // (e.g. an import that silently dropped everything). Refuse rather than1950  // wipe the vault.1951  if (mode === "replace" && incoming.length === 0) {1952    throw new Error("refuse to replace with empty entry set");1953  }19541955  let added = 0;1956  let updated = 0;1957  let skipped = 0;19581959  if (mode === "replace") {1960    entries = [];1961    tombstones = new Map();1962    for (const entry of incoming) {1963      const normalized = sanitizeRestoredEntry(entry);1964      if (!normalized) {1965        skipped += 1;1966        continue;1967      }1968      entries.push(normalized);1969      if (normalized.deletedAt) {1970        tombstones.set(normalized.id, normalized.deletedAt);1971      }1972      added += 1;1973    }1974  } else {1975    const byId = new Map<string, VaultEntry>();1976    for (const e of entries) byId.set(e.id, e);19771978    for (const entry of incoming) {1979      const normalized = sanitizeRestoredEntry(entry);1980      if (!normalized) {1981        skipped += 1;1982        continue;1983      }1984      const existing = byId.get(normalized.id);1985      if (!existing) {1986        entries.push(normalized);1987        if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);1988        else tombstones.delete(normalized.id);1989        added += 1;1990      } else if (normalized.modifiedAt > existing.modifiedAt) {1991        const idx = entries.findIndex((e) => e.id === existing.id);1992        if (idx !== -1) {1993          entries[idx] = normalized;1994          if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);1995          else tombstones.delete(normalized.id);1996          updated += 1;1997        }1998      } else {1999        skipped += 1;2000      }2001    }2002  }20032004  await persistEntries("import");2005  return { added, updated, skipped };2006}20072008/**2009 * Validate + normalise a VaultEntry coming from a backup, import, or sync2010 * peer. MV-6: this is a strict field WHITELIST — `normalizeEntry` copies2011 * only known VaultEntry fields (unknown/attacker keys are dropped), and2012 * nested `passkey`/`canary` shapes are rebuilt field-by-field, never2013 * spread. Returns null for values the live vault shouldn't accept.2014 */2015function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {2016  if (!entry || typeof entry !== "object") return null;2017  const title = typeof entry.title === "string" ? entry.title.trim() : "";2018  if (!title) return null;2019  const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();2020  const now = Date.now();2021  const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;2022  const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;20232024  // normalizeEntry whitelists every known VaultEntry field and runs the2025  // same legacy-passkey migration as the on-disk read path — pre-v2.11.02026  // backups with flat passkey fields still import correctly because the2027  // legacy flat fields are themselves whitelisted VaultEntry members.2028  const normalized = normalizeEntry({2029    ...entry,2030    id,2031    title,2032    type: entry.type ?? "login",2033    createdAt,2034    modifiedAt,2035  });20362037  if (normalized.passkey) {2038    normalized.passkey = sanitizePasskey(normalized.passkey);2039  }2040  if (normalized.canary) {2041    normalized.canary = sanitizeCanary(normalized.canary);2042  }2043  // PCH-01-016: bound tags on the restore path too, so both import funnels agree.2044  normalized.tags = sanitizeTags(normalized.tags);20452046  // Login entries from backup must carry a password (or be passkey-only,2047  // in which case the passkey sub-object replaces the password requirement).2048  if (2049    normalized.type === "login" &&2050    !normalized.passkey &&2051    typeof normalized.password !== "string"2052  ) {2053    return null;2054  }2055  if (entry.passkey && !normalized.passkey) {2056    // Entry claimed a passkey but the shape didn't validate — refuse the2057    // whole entry rather than silently importing a credential-less husk.2058    return null;2059  }20602061  return normalized;2062}20632064/**2065 * Rebuild a PasskeyData object from untrusted input, field by field.2066 * Returns undefined when required fields are missing/mistyped — a rogue2067 * passkey credential must not activate via import (MV-6 attack scenario).2068 */2069function sanitizePasskey(pk: unknown): PasskeyData | undefined {2070  if (!pk || typeof pk !== "object") return undefined;2071  const r = pk as Record<string, unknown>;2072  if (2073    typeof r.rpId !== "string" || !r.rpId ||2074    typeof r.credentialId !== "string" || !r.credentialId ||2075    typeof r.publicKeyCose !== "string" ||2076    typeof r.userHandle !== "string" ||2077    typeof r.userName !== "string"2078  ) {2079    return undefined;2080  }2081  return {2082    rpId: r.rpId,2083    rpName: typeof r.rpName === "string" ? r.rpName : r.rpId,2084    credentialId: r.credentialId,2085    publicKeyCose: r.publicKeyCose,2086    privateKeyJwk:2087      r.privateKeyJwk && typeof r.privateKeyJwk === "object"2088        ? (r.privateKeyJwk as JsonWebKey)2089        : undefined,2090    userHandle: r.userHandle,2091    userName: r.userName,2092    userDisplayName:2093      typeof r.userDisplayName === "string" ? r.userDisplayName : r.userName,2094    algorithm: r.algorithm === -8 ? -8 : -7,2095    signCount: typeof r.signCount === "number" ? r.signCount : 0,2096    aaguid: typeof r.aaguid === "string" ? r.aaguid : "",2097    backupEligible: r.backupEligible === true,2098    backupState: r.backupState === true,2099    lastUsedAt: typeof r.lastUsedAt === "number" ? r.lastUsedAt : undefined,2100    browser: r.browser === "chrome" || r.browser === "firefox" ? r.browser : undefined,2101    transports: Array.isArray(r.transports)2102      ? r.transports.filter((t): t is string => typeof t === "string")2103      : undefined,2104    createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),2105  };2106}21072108/**2109 * Rebuild a Canary object from untrusted input. The webhook must be a2110 * well-formed HTTPS URL — a poisoned canary.webhookUrl is a standing2111 * exfiltration endpoint that the canary subsystem will POST entry titles2112 * to (MV-6 attack scenario). Invalid → the canary is dropped, not the2113 * entry. FIRE_CANARY_PING re-validates with the full SSRF guard at fire2114 * time (isAllowedCanaryWebhookUrl), so this import-time check is the2115 * outer of two gates.2116 */2117function sanitizeCanary(c: unknown): Canary | undefined {2118  if (!c || typeof c !== "object") return undefined;2119  const r = c as Record<string, unknown>;2120  if (typeof r.webhookUrl !== "string") return undefined;2121  let url: URL;2122  try {2123    url = new URL(r.webhookUrl);2124  } catch {2125    return undefined;2126  }2127  if (url.protocol !== "https:") return undefined;2128  return {2129    webhookUrl: url.toString(),2130    label: typeof r.label === "string" ? r.label : undefined,2131    lastPinged: typeof r.lastPinged === "number" ? r.lastPinged : undefined,2132    pingCount: typeof r.pingCount === "number" ? r.pingCount : undefined,2133  };2134}21352136/**2137 * MV-6 / PCH-01-016: tags from imported / batch-added entries are untrusted.2138 * Keep only non-empty strings, cap each at 256 chars, and cap the count at 2552139 * (the same per-entry ceiling the export codec enforces, peachPayload.ts).2140 * Non-array or all-invalid input collapses to undefined.2141 */2142function sanitizeTags(tags: unknown): string[] | undefined {2143  if (!Array.isArray(tags)) return undefined;2144  const out: string[] = [];2145  for (const t of tags) {2146    if (typeof t !== "string") continue;2147    const trimmed = t.trim();2148    if (!trimmed) continue;2149    out.push(trimmed.slice(0, 256));2150    if (out.length >= 255) break;2151  }2152  return out.length > 0 ? out : undefined;2153}21542155// Soft-deletes every non-deleted entry in one call. The literal string2156// argument is a tripwire against accidental calls — any caller that would2157// wipe the vault has to consciously type "REPLACE_ALL". Do not relax this2158// to a boolean.2159export async function clearVaultEntries(2160  confirmation: "REPLACE_ALL"2161): Promise<void> {2162  if (confirmation !== "REPLACE_ALL") {2163    throw new Error("clearVaultEntries requires explicit confirmation");2164  }2165  if (!derivedKey) throw new Error("vault_locked");2166  for (const entry of entries) {2167    if (!entry.deletedAt) {2168      const stamp = monotonicEntryTimestamp(Math.max(2169        entry.modifiedAt,2170        tombstones.get(entry.id) ?? 0,2171      ));2172      entry.deletedAt = stamp;2173      entry.modifiedAt = stamp;2174      tombstones.set(entry.id, stamp);2175    }2176  }2177  await persistEntries();2178}21792180export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {2181  if (!derivedKey) throw new Error("vault_locked");21822183  const sanitized = sanitizeEntryDraft(entry);2184  const now = Date.now();2185  const stamp = monotonicEntryTimestamp();2186  const nextEntry: VaultEntry = {2187    ...sanitized,2188    id: crypto.randomUUID(),2189    createdAt: now,2190    modifiedAt: stamp,2191    // Stamp passwordChangedAt at creation so age tracking is accurate from2192    // day one. Non-login entries carry the same stamp harmlessly.2193    passwordChangedAt: sanitized.password ? stamp : undefined,2194  };21952196  // Clone-and-replace so a failed persist rolls back the in-memory state2197  // (COR-008). Without this, a quota-full or storage error leaves the2198  // module-level `entries` ahead of what's actually on disk.2199  const rollback = entries;2200  entries = [...entries, nextEntry];2201  try {2202    await persistEntries();2203  } catch (err) {2204    entries = rollback;2205    throw err;2206  }22072208  // Fire-and-forget breach check (only for login entries if breach monitoring is enabled or not set)2209  if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {2210    checkBreach(nextEntry.password).then(async (count) => {2211      if (count > 0) {2212        const idx = entries.findIndex((e) => e.id === nextEntry.id);2213        if (idx !== -1) {2214          entries[idx] = { ...entries[idx], breach: count, modifiedAt: monotonicEntryTimestamp(entries[idx].modifiedAt) };2215          await persistEntries();2216        }2217      }2218    });2219  }22202221  fireSyncTrigger("vault_change");22222223  return nextEntry;2224}22252226/**2227 * Run the passkey-merge pass on the live in-memory entries and persist if2228 * anything changed. Called immediately after any passkey registration so that2229 * a same-domain TOTP-only entry already in the vault gets consolidated right2230 * away instead of waiting until the next lock/unlock cycle.2231 */2232export async function consolidatePasskeyEntries(): Promise<void> {2233  if (!derivedKey) return;2234  const { merged } = mergePasskeyOnlyIntoLogins(entries);2235  if (merged) {2236    await persistEntries();2237  }2238}22392240export async function updateEntry(2241  id: string,2242  patch: Partial<VaultEntry>2243): Promise<void> {2244  if (!derivedKey) throw new Error("vault_locked");22452246  const idx = entries.findIndex((entry) => entry.id === id);2247  if (idx === -1 || entries[idx].deletedAt) {2248    throw new Error("entry_not_found");2249  }22502251  const current = entries[idx];2252  const sanitizedPatch = sanitizeEntryPatch(patch);2253  // Refresh passwordChangedAt only when the password value actually changes —2254  // a metadata-only update (title, tags, etc.) must not reset the age clock2255  // that drives the Pro health rotation recommendation.2256  const passwordChanged =2257    "password" in patch &&2258    typeof sanitizedPatch.password === "string" &&2259    sanitizedPatch.password !== current.password;2260  const stamp = monotonicEntryTimestamp(current.modifiedAt);2261  // When the password actually changes, push the outgoing one onto the history2262  // (newest first) so the user can reveal/copy/restore it later. We record the2263  // age it carried (passwordChangedAt, falling back to createdAt) rather than2264  // `now`, so the list reflects when each password was last in effect. Only2265  // capture a non-empty prior value — clearing a password leaves no secret to2266  // keep, and we skip an immediate exact duplicate (e.g. restore-then-restore)2267  // to avoid noise.2268  const priorPassword = current.password;2269  const shouldCapture =2270    passwordChanged &&2271    typeof priorPassword === "string" &&2272    priorPassword.length > 0 &&2273    current.passwordHistory?.[0]?.password !== priorPassword;2274  const nextHistory = shouldCapture2275    ? [2276        { password: priorPassword!, changedAt: current.passwordChangedAt ?? current.createdAt },2277        ...(current.passwordHistory ?? []),2278      ].slice(0, PASSWORD_HISTORY_MAX)2279    : current.passwordHistory;2280  entries[idx] = {2281    ...current,2282    ...sanitizedPatch,2283    modifiedAt: stamp,2284    ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),2285  };2286228722882289  // Card entries must retain their card number2290  if (entries[idx].type === "card" && !entries[idx].cardNumber) {2291    entries[idx] = current;2292    throw new Error("card number is required for card entries");2293  }22942295  // Roll the in-memory entry back to its pre-edit state if the disk write2296  // fails (e.g. storage quota). Without this the module-level `entries` array2297  // would hold an edit that never landed on disk, diverging from the vault2298  // until the next unlock silently reverts it (SEV-3-A). Mirrors addEntry.2299  try {2300    await persistEntries();2301  } catch (err) {2302    entries[idx] = current;2303    throw err;2304  }23052306  // Breach check when password changes: clear immediately so old breach doesn't linger,2307  // then async-check the new password and only re-set if it's also found.2308  if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {2309    entries[idx] = { ...entries[idx], breach: undefined };2310    await persistEntries();2311    const password = entries[idx].password;2312    if (password) {2313      checkBreach(password).then(async (count) => {2314        const i = entries.findIndex((e) => e.id === id);2315        if (i !== -1 && count > 0) {2316          entries[i] = { ...entries[i], breach: count, modifiedAt: monotonicEntryTimestamp(entries[i].modifiedAt) };2317          await persistEntries();2318        }2319      });2320    }2321  }23222323  fireSyncTrigger("vault_change");2324}23252326export async function deleteEntry(id: string): Promise<void> {2327  if (!derivedKey) throw new Error("vault_locked");23282329  const entry = entries.find((item) => item.id === id);2330  if (!entry || entry.deletedAt) {2331    throw new Error("entry_not_found");2332  }23332334  // Tombstone timestamp must be strictly greater than the entry's last2335  // modification so the deletion wins LWW against any in-flight edit, even2336  // under clock skew (SEV-2-E).2337  const previousModifiedAt = entry.modifiedAt;2338  const previousTombstone = tombstones.get(id);2339  const stamp = monotonicEntryTimestamp(Math.max(entry.modifiedAt, previousTombstone ?? 0));2340  entry.deletedAt = stamp;2341  entry.modifiedAt = stamp;2342  tombstones.set(id, stamp);2343  // Roll the tombstone back if the disk write fails, so a quota error doesn't2344  // leave the entry deleted in memory but alive on disk (SEV-3-A).2345  try {2346    await persistEntries();2347  } catch (err) {2348    delete entry.deletedAt;2349    entry.modifiedAt = previousModifiedAt;2350    if (previousTombstone === undefined) tombstones.delete(id);2351    else tombstones.set(id, previousTombstone);2352    throw err;2353  }2354  fireSyncTrigger("vault_change");2355}23562357export function getDeletedEntries(): VaultEntry[] {2358  if (!derivedKey) return [];2359  return entries.filter((e) => !!e.deletedAt);2360}23612362/** Return all durable deletion timestamps, including purged full entries. */2363export function getTombstoneManifest(): Record<string, number> {2364  if (!derivedKey) return {};2365  return Object.fromEntries(tombstones);2366}23672368/**2369 * Returns the vault's monotonic version — the `peach_last_modified_at` value2370 * stamped on every user-initiated write. Remote (sync) writes do NOT advance2371 * this version so a sync round never cascades into a second outbound sync.2372 */2373export async function getVaultVersion(): Promise<number> {2374  try {2375    const raw = await chrome.storage.local.get("peach_last_modified_at");2376    const v = (raw as Record<string, unknown>).peach_last_modified_at;2377    if (typeof v === "number") return v;2378    if (typeof v === "string" && v !== "") {2379      const n = Number.parseInt(v, 10);2380      return Number.isFinite(n) ? n : 0;2381    }2382    return 0;2383  } catch {2384    return 0;2385  }2386}23872388/**2389 * Apply a batch of remote entries + tombstones from a sync peer.2390 * Last-write-wins by `modifiedAt`; a tombstone supersedes a live entry when2391 * `deletedAt > modifiedAt` on the local side. Mutates `entries` directly and2392 * persists with reason `sync_received` — does NOT fire the sync dispatcher, so2393 * applying a sync round cannot cascade into another outbound sync.2394 *2395 * `applied` counts entries that actually changed local state (new add,2396 * overwrite-by-newer, or new tombstone). `received` is the raw payload size2397 * the caller can surface in the sync result UI.2398 */2399export async function applyMergedRemoteEntries(2400  remoteEntries: VaultEntry[],2401  remoteTombstones: Record<string, number>,2402  _context: { deviceName?: string } = {},2403): Promise<{ received: number; applied: number; conflicts: number }> {2404  // DESIGN: last-write-wins is applied PER-ENTRY, not per-field. If two devices2405  // concurrently edit different fields of the same entry, the one with the2406  // newer modifiedAt wins the whole entry and the other device's field edits2407  // are dropped silently. This is the deliberate trade-off for a simple,2408  // conflict-free merge — per-field CRDT merge is out of scope. Guidance for2409  // users: edit a given entry on one device at a time.2410  if (!derivedKey) throw new Error("vault_locked");24112412  const received = remoteEntries.length + Object.keys(remoteTombstones).length;2413  let applied = 0;2414  let conflicts = 0;24152416  const byId = new Map<string, VaultEntry>();2417  for (const e of entries) byId.set(e.id, e);24182419  const mergeNow = Date.now();2420  const remoteTombstoneTimes = new Map<string, number>();2421  for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2422    if (typeof rawDeletedAt === "number" && Number.isFinite(rawDeletedAt) && rawDeletedAt > 0) {2423      remoteTombstoneTimes.set(id, clampSyncTimestamp(rawDeletedAt, mergeNow));2424    }2425  }24262427  for (const remote of remoteEntries) {2428    const sanitized = sanitizeRestoredEntry(remote);2429    if (!sanitized) continue;2430    // HV-1a: a far-future remote modifiedAt must not permanently pin a2431    // malicious value against honest local edits. Clamp BEFORE any2432    // comparison against local timestamps.2433    sanitized.modifiedAt = clampSyncTimestamp(sanitized.modifiedAt, mergeNow);2434    if (typeof sanitized.deletedAt === "number") {2435      sanitized.deletedAt = clampSyncTimestamp(sanitized.deletedAt, mergeNow);2436    }2437    const remoteTombstoneTs = remoteTombstoneTimes.get(sanitized.id);2438    const localTombstoneTs = tombstones.get(sanitized.id);2439    const tombstoneTs = Math.max(remoteTombstoneTs ?? 0, localTombstoneTs ?? 0);2440    if (tombstoneTs > 0 && tombstoneTs >= sanitized.modifiedAt) {2441      continue;2442    }2443    const local = byId.get(sanitized.id);2444    if (!local) {2445      entries.push(sanitized);2446      byId.set(sanitized.id, sanitized);2447      tombstones.delete(sanitized.id);2448      applied += 1;2449    } else if (sanitized.modifiedAt > local.modifiedAt) {2450      const idx = entries.findIndex((e) => e.id === local.id);2451      if (idx !== -1) {2452        entries[idx] = sanitized;2453        byId.set(sanitized.id, sanitized);2454        tombstones.delete(sanitized.id);2455        applied += 1;2456        if (!local.deletedAt) conflicts += 1;2457      }2458    }2459  }24602461  for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2462    if (typeof rawDeletedAt !== "number" || !Number.isFinite(rawDeletedAt) || rawDeletedAt <= 0) continue;2463    // HV-1a/1c: clamp the tombstone timestamp before every comparison.2464    const deletedAt = remoteTombstoneTimes.get(id)!;2465    const knownTombstone = tombstones.get(id);2466    if (knownTombstone !== undefined && knownTombstone >= deletedAt) continue;2467    const local = byId.get(id);2468    if (!local) {2469      tombstones.set(id, deletedAt);2470      applied += 1;2471      continue;2472    }2473    if (local.deletedAt && local.deletedAt >= deletedAt) continue;2474    if (deletedAt < local.modifiedAt) continue;2475    const idx = entries.findIndex((e) => e.id === id);2476    if (idx !== -1) {2477      entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };2478      tombstones.set(id, deletedAt);2479      applied += 1;2480    }2481  }24822483  if (applied > 0) {2484    await persistEntries("sync_received");2485    buildDomainIndexSync(entries);2486  }2487  return { received, applied, conflicts };2488}24892490export async function restoreEntry(id: string): Promise<void> {2491  if (!derivedKey) throw new Error("vault_locked");2492  const entry = entries.find((e) => e.id === id && e.deletedAt);2493  if (!entry) throw new Error("deleted entry not found");2494  const previousDeletedAt = entry.deletedAt;2495  const previousModifiedAt = entry.modifiedAt;2496  const previousTombstone = tombstones.get(id);2497  delete entry.deletedAt;2498  entry.modifiedAt = monotonicEntryTimestamp(Math.max(2499    entry.modifiedAt,2500    previousTombstone ?? 0,2501  ));2502  tombstones.delete(id);2503  try {2504    await persistEntries();2505  } catch (err) {2506    entry.deletedAt = previousDeletedAt;2507    entry.modifiedAt = previousModifiedAt;2508    if (previousTombstone !== undefined) tombstones.set(id, previousTombstone);2509    throw err;2510  }2511  buildDomainIndexSync(entries);2512}25132514export async function purgeEntry(id: string): Promise<void> {2515  if (!derivedKey) throw new Error("vault_locked");2516  const idx = entries.findIndex((e) => e.id === id && e.deletedAt);2517  if (idx === -1) throw new Error("deleted entry not found");2518  const entry = entries[idx]!;2519  tombstones.set(id, Math.max(tombstones.get(id) ?? 0, entry.deletedAt!));2520  entries.splice(idx, 1);2521  await persistEntries();2522}25232524/** Permanently delete entries whose deletedAt is older than retentionMs. 0 = keep forever. */2525export async function purgeExpiredTrash(retentionMs: number): Promise<number> {2526  if (!derivedKey || retentionMs === 0) return 0;2527  const cutoff = Date.now() - retentionMs;2528  const before = entries.length;2529  for (const entry of entries) {2530    if (entry.deletedAt && entry.deletedAt < cutoff) {2531      tombstones.set(entry.id, Math.max(tombstones.get(entry.id) ?? 0, entry.deletedAt));2532    }2533  }2534  entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));2535  const purged = before - entries.length;2536  if (purged > 0) await persistEntries();2537  return purged;2538}25392540export function queryDomain(domain: string): VaultEntry[] {2541  return domainIndex.get(domain) ?? [];2542}25432544export function getEntryById(id: string): VaultEntry | undefined {2545  return entries.find((entry) => entry.id === id && !entry.deletedAt);2546}25472548async function persistSlotA(2549  reason: VaultSnapshot["reason"] = "local_save",2550): Promise<StoredVault> {2551  if (!derivedKey) throw new Error("vault_locked");25522553  const slotA = await loadSlot(SLOT_A);2554  if (!slotA) throw new Error("missing slot A");25552556  // Snapshot the about-to-be-overwritten state BEFORE we mutate disk. Failures2557  // are swallowed by takeVaultSnapshot — history must never block a save.2558  await takeVaultSnapshot(reason);25592560  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);2561  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");25622563  // Preserve existing recovery escrow fields.2564  const nextSlotA: StoredVault = {2565    ...slotA,2566    nonce,2567    ciphertext,2568    tag,2569    // recovery_salt and recovery_wrapped_root_key are already set from loadSlot2570  };2571  await writeSlot(SLOT_A, nextSlotA);25722573  // Slot A (the real vault) is now committed. Wrap every later write so a2574  // mid-persist failure (e.g. a storage error after slot A landed) restores the2575  // prior slot A before rethrowing. Without this, a "failed" save that already2576  // wrote slot A leaves disk ahead of the in-memory rollback in addEntry/2577  // updateEntry/deleteEntry — the entry stays silently on disk and resurfaces2578  // as a duplicate on the next unlock (observed under storage-quota pressure).2579  try {2580    // When duress is not configured, keep slot B size-matched with slot A by2581    // regenerating its noise. When duress IS configured, leave slot B alone —2582    // we don't have the decoy key to re-encrypt it. This is a known trade-off.2583    if (!duressConfigured) {2584      await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));2585    }2586    // Only advance the vault version for locally-originated writes. Entries2587    // applied from a sync peer ("sync_received") must NOT bump the counter —2588    // otherwise applying a remote round makes us look newer than the peer and2589    // triggers a redundant outbound sync, defeating the no-op optimisation2590    // and risking a ping-pong between two devices (SEV-2-C).2591    if (reason !== "sync_received") {2592      await stampLocalVaultMutation();2593    }2594  } catch (err) {2595    // Best-effort restore — the prior slot A is smaller-or-equal, so this write2596    // fits even when the failure was a quota overflow.2597    await writeSlot(SLOT_A, slotA).catch(() => {});2598    throw err;2599  }26002601  return nextSlotA;2602}26032604async function persistSlotB(): Promise<void> {2605  if (!derivedKey) throw new Error("vault_locked");26062607  const slotB = await loadSlot(SLOT_B);2608  if (!slotB) throw new Error("missing slot B");26092610  // Decoy plaintext always reports duressConfigured=false — the decoy user2611  // sees a clean slate. persistSlotB only runs in decoy mode, which only2612  // exists once duress is configured, so pad to the fixed duress ceiling to2613  // keep slot B's length equal to slot A's (audit MEDIUM — deniability).2614  const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);2615  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");26162617  await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });2618  // Symmetric with persistSlotA: if the version stamp fails after the decoy2619  // slot committed, restore the prior slot B so a failed decoy-mode save can't2620  // leave disk ahead of the in-memory rollback.2621  try {2622    await stampLocalVaultMutation();2623  } catch (err) {2624    await writeSlot(SLOT_B, slotB).catch(() => {});2625    throw err;2626  }2627}26282629async function persistEntries(2630  reason: VaultSnapshot["reason"] = "local_save",2631): Promise<void> {2632  if (!derivedKey) throw new Error("vault_locked");26332634  // Reconcile direct soft-delete callers (clear/deduplicate and legacy2635  // migration) while restoring the previous map if storage rejects the save.2636  const previousTombstones = tombstones;2637  tombstones = new Map(tombstones);2638  reconcileTombstones();2639  try {2640    if (vaultMode === "decoy") {2641      await persistSlotB();2642    } else {2643      await persistSlotA(reason);2644    }2645  } catch (err) {2646    tombstones = previousTombstones;2647    throw err;2648  }2649  buildDomainIndexSync(entries);2650  await refreshLockedSyncState();2651}26522653function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {2654  if (!Array.isArray(values)) return undefined;2655  const seen = new Set<string>();2656  const cleaned: string[] = [];2657  for (const value of values) {2658    const trimmed = typeof value === "string" ? value.trim() : "";2659    if (!trimmed) continue;2660    const key = trimmed.toLowerCase();2661    if (seen.has(key)) continue;2662    seen.add(key);2663    cleaned.push(trimmed);2664  }2665  return cleaned.length > 0 ? cleaned : undefined;2666}26672668function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {2669  const title = entry.title.trim();2670  // Accept legacy `type:"passkey"` drafts but rewrite to "login" — the new2671  // model is "any entry, optionally with a passkey sub-object." Imports and2672  // any in-flight callers from before v2.11.0 keep working without throwing.2673  let type: VaultEntry["type"] = entry.type ?? "login";2674  if (type === "passkey") type = "login";26752676  if (!title) throw new Error("title is required");26772678  if (entry.passkey) {2679    const p = entry.passkey;2680    if (2681      !p.rpId ||2682      !p.credentialId ||2683      !p.publicKeyCose ||2684      !p.userHandle ||2685      !p.userName ||2686      (p.algorithm !== -7 && p.algorithm !== -8)2687    ) {2688      throw new Error("invalid passkey credential");2689    }2690  }2691  if (type === "card") {2692    if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {2693      throw new Error("cardholder name and card number are required");2694    }2695  }26962697  return {2698    type,2699    title,2700    username: type === "login" ? entry.username?.trim() ?? "" : undefined,2701    email: type === "login" ? entry.email?.trim() || undefined : undefined,2702    password: type === "login" ? entry.password : undefined,2703    url: type === "login" ? entry.url?.trim() ?? "" : undefined,2704    additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,2705    totp: type === "login" ? entry.totp?.trim() || undefined : undefined,2706    // PCH-01-019: preserve non-default TOTP params through batch-add/import so2707    // they are not silently stripped (they fall back to SHA-1/6/30 when absent).2708    totpAlgorithm: type === "login" ? entry.totpAlgorithm : undefined,2709    totpDigits: type === "login" ? entry.totpDigits : undefined,2710    totpPeriod: type === "login" ? entry.totpPeriod : undefined,2711    notes: entry.notes?.trim() || undefined,2712    breach: type === "login" ? entry.breach : undefined,2713    // PCH-01-016: the batch-add path was bypassing the MV-6 canary/tags2714    // whitelist applied on the RESTORE_ENTRIES path. Run both sanitizers here.2715    canary: type === "login" ? sanitizeCanary(entry.canary) : undefined,2716    tags: sanitizeTags(entry.tags),2717    passkey: entry.passkey,2718    cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,2719    cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,2720    expMonth: type === "card" ? entry.expMonth?.trim() : undefined,2721    expYear: type === "card" ? entry.expYear?.trim() : undefined,2722    cvc: type === "card" ? entry.cvc?.trim() : undefined,2723    cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,2724    network: type === "card" ? entry.network : undefined,2725    last4: type === "card" ? entry.last4?.trim() : undefined,2726  };2727}27282729function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {2730  const nextPatch: Partial<VaultEntry> = {};27312732  if ("type" in patch) {2733    nextPatch.type = patch.type;2734  }27352736  if ("title" in patch) {2737    const title = patch.title?.trim() ?? "";2738    if (!title) throw new Error("title is required");2739    nextPatch.title = title;2740  }27412742  if ("url" in patch) {2743    nextPatch.url = patch.url?.trim() ?? "";2744  }27452746  if ("additionalUrls" in patch) {2747    const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];2748    const seen = new Set<string>();2749    const cleaned: string[] = [];2750    for (const value of incoming) {2751      const trimmed = typeof value === "string" ? value.trim() : "";2752      if (!trimmed) continue;2753      const key = trimmed.toLowerCase();2754      if (seen.has(key)) continue;2755      seen.add(key);2756      cleaned.push(trimmed);2757    }2758    nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;2759  }27602761  if ("username" in patch) {2762    nextPatch.username = patch.username?.trim() ?? "";2763  }27642765  if ("email" in patch) {2766    nextPatch.email = patch.email?.trim() || undefined;2767  }27682769  if ("password" in patch) {2770    const password = patch.password ?? "";2771    // Allow clearing a password (e.g. on passkey-only entries)2772    nextPatch.password = password || undefined;2773  }27742775  if ("totp" in patch) {2776    nextPatch.totp = patch.totp?.trim() || undefined;2777  }27782779  if ("notes" in patch) {2780    nextPatch.notes = patch.notes?.trim() || undefined;2781  }27822783  if ("breach" in patch) {2784    nextPatch.breach = patch.breach;2785  }27862787  if ("canary" in patch) {2788    // PCH-02-001: route update patches through the same canary whitelist used2789    // by add/restore/sync. Invalid shapes drop the canary; `undefined` clears it.2790    nextPatch.canary = patch.canary ? sanitizeCanary(patch.canary) : undefined;2791  }27922793  if ("passkey" in patch) {2794    // Passkey sub-object replaces all the legacy flat passkey fields. A2795    // patch with `passkey: undefined` removes the credential from the entry2796    // (used by "remove passkey" without deleting the whole entry).2797    if (patch.passkey === undefined || patch.passkey === null) {2798      nextPatch.passkey = undefined;2799    } else {2800      const sanitized = sanitizePasskey(patch.passkey);2801      if (!sanitized) throw new Error("invalid passkey credential");2802      nextPatch.passkey = sanitized;2803    }2804  }28052806  if ("tags" in patch) {2807    // PCH-02-001: bound tags exactly like both import funnels.2808    nextPatch.tags = sanitizeTags(patch.tags);2809  }28102811  if ("cardholderName" in patch) {2812    nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;2813  }2814  if ("cardNumber" in patch) {2815    const n = patch.cardNumber ?? "";2816    nextPatch.cardNumber = n || undefined;2817  }2818  if ("expMonth" in patch) {2819    nextPatch.expMonth = patch.expMonth?.trim() || undefined;2820  }2821  if ("expYear" in patch) {2822    nextPatch.expYear = patch.expYear?.trim() || undefined;2823  }2824  if ("cvc" in patch) {2825    nextPatch.cvc = patch.cvc?.trim() || undefined;2826  }2827  if ("cardNickname" in patch) {2828    nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;2829  }2830  if ("network" in patch) {2831    nextPatch.network = patch.network;2832  }2833  if ("last4" in patch) {2834    nextPatch.last4 = patch.last4?.trim() || undefined;2835  }28362837  return nextPatch;2838}28392840function normalizeEntry(entry: VaultEntry | LegacyVaultEntry): VaultEntry {2841  const createdAt = "createdAt" in entry ? entry.createdAt : entry.created;2842  const modifiedAt =2843    "modifiedAt" in entry ? entry.modifiedAt : entry.updated;28442845  const base: VaultEntry = {2846    id: entry.id,2847    type: "type" in entry ? entry.type : "login",2848    title: entry.title,2849    username: entry.username,2850    email: "email" in entry ? entry.email : undefined,2851    password: entry.password,2852    url: entry.url,2853    additionalUrls:2854      "additionalUrls" in entry && Array.isArray(entry.additionalUrls)2855        ? entry.additionalUrls2856        : undefined,2857    totp: entry.totp,2858    // PCH-01-019: carry TOTP params through the normalize/restore path too.2859    totpAlgorithm: entry.totpAlgorithm,2860    totpDigits: entry.totpDigits,2861    totpPeriod: entry.totpPeriod,2862    notes: entry.notes,2863    breach: entry.breach,2864    // Preserve the password-age clock across lock/unlock. Without this the2865    // field is dropped on every decode and the advanced-health "aged password"2866    // signal silently resets to createdAt on each unlock (SEV-2-A).2867    passwordChangedAt:2868      "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,2869    // Preserve past-password history across lock/unlock. normalizeEntry is a2870    // field whitelist, so an unlisted field is silently dropped on every decode2871    // (same class as the passwordChangedAt SEV-2-A above).2872    passwordHistory:2873      "passwordHistory" in entry && Array.isArray(entry.passwordHistory)2874        ? entry.passwordHistory2875        : undefined,2876    canary: "canary" in entry ? entry.canary : undefined,2877    passkey: "passkey" in entry ? entry.passkey : undefined,2878    createdAt,2879    modifiedAt,2880    deletedAt: entry.deletedAt,2881    tags: "tags" in entry ? entry.tags : undefined,2882    cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,2883    cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,2884    expMonth: "expMonth" in entry ? entry.expMonth : undefined,2885    expYear: "expYear" in entry ? entry.expYear : undefined,2886    cvc: "cvc" in entry ? entry.cvc : undefined,2887    cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,2888    network: "network" in entry ? entry.network : undefined,2889    last4: "last4" in entry ? entry.last4 : undefined,2890  };28912892  return migrateLegacyPasskey(base, entry);2893}28942895/**2896 * v2.11.0 read migration. Pre-v2.11.0 passkey entries used `type:"passkey"`2897 * with flat top-level fields (rpId, credentialId, etc.). This converts them2898 * to the new shape — `type:"login"` with a `passkey` sub-object — so all2899 * downstream consumers can rely on the new model. The result is rewritten2900 * to disk on next vault save (hasLegacyShape detects the un-migrated case).2901 */2902function migrateLegacyPasskey(2903  base: VaultEntry,2904  raw: VaultEntry | LegacyVaultEntry2905): VaultEntry {2906  if (base.passkey) return base;2907  const flat = raw as Partial<VaultEntry>;2908  const isPasskeyType = base.type === "passkey";2909  const hasFlatPasskeyFields =2910    typeof flat.rpId === "string" &&2911    typeof flat.credentialId === "string" &&2912    typeof flat.publicKeyCose === "string" &&2913    typeof flat.userHandle === "string" &&2914    typeof flat.userName === "string";2915  if (!isPasskeyType && !hasFlatPasskeyFields) return base;2916  if (!hasFlatPasskeyFields) return base;29172918  const algorithm: -7 | -8 = flat.algorithm === -8 ? -8 : -7;2919  base.passkey = {2920    rpId: flat.rpId!,2921    rpName: flat.rpName ?? flat.rpId!,2922    credentialId: flat.credentialId!,2923    publicKeyCose: flat.publicKeyCose!,2924    privateKeyJwk: flat.privateKeyJwk,2925    userHandle: flat.userHandle!,2926    userName: flat.userName!,2927    userDisplayName: flat.userDisplayName ?? flat.userName!,2928    algorithm,2929    signCount: flat.signCount ?? 0,2930    aaguid: flat.aaguid ?? "",2931    backupEligible: flat.backupEligible === true,2932    backupState: flat.backupState === true,2933    lastUsedAt: flat.lastUsedAt,2934    browser: flat.browser,2935    transports: flat.transports,2936    createdAt: base.createdAt,2937  };2938  // Promote to "login" so the unified Entry view renders. Username gets2939  // populated from the passkey's userName so the entry is searchable in the2940  // existing autofill flow without a separate code path.2941  if (isPasskeyType) base.type = "login";2942  if (!base.username) base.username = flat.userName;2943  if (!base.url) base.url = `https://${flat.rpId}`;2944  return base;2945}294629472948// ---------------------------------------------------------------------------2949// Deduplication2950// ---------------------------------------------------------------------------29512952function entryDupeKey(e: VaultEntry): string {2953  if (e.type === "note") return `note|${e.title.toLowerCase()}`;2954  // Passkey-bearing entries dedupe by the credential's RP + user. Two logins2955  // on different sites that happen to share a username are still distinct;2956  // two passkey credentials for the same RP+user are duplicates regardless2957  // of any login fields they may also carry.2958  if (e.passkey) {2959    return `passkey|${e.passkey.rpId.toLowerCase()}|${e.passkey.userName.toLowerCase()}`;2960  }2961  return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;2962}29632964/** Returns the number of duplicate entries (those that would be removed). */2965export function countDuplicates(): number {2966  const best = new Map<string, VaultEntry>();2967  let dupeCount = 0;2968  for (const e of entries.filter((e) => !e.deletedAt)) {2969    const key = entryDupeKey(e);2970    const existing = best.get(key);2971    if (!existing) {2972      best.set(key, e);2973    } else {2974      dupeCount++;2975      // Keep the more recently modified one in the map2976      if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2977        best.set(key, e);2978      }2979    }2980  }2981  return dupeCount;2982}29832984/**2985 * Soft-deletes duplicate entries, keeping the most recently modified copy of2986 * each group. Returns the number of entries moved to trash.2987 */2988export async function deduplicateEntries(): Promise<number> {2989  if (!derivedKey) throw new Error("vault_locked");2990  // Dedup reshapes slot B permanently under the decoy key, which is2991  // forensically distinguishable from a freshly-seeded decoy vault. Refuse.2992  if (vaultMode === "decoy") {2993    throw new Error("deduplicate disabled in decoy mode");2994  }29952996  const best = new Map<string, VaultEntry>();2997  for (const e of entries.filter((en) => !en.deletedAt)) {2998    const key = entryDupeKey(e);2999    const existing = best.get(key);3000    if (!existing) {3001      best.set(key, e);3002    } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3003      best.set(key, e);3004    }3005  }30063007  const keepIds = new Set(Array.from(best.values()).map((e) => e.id));3008  let removed = 0;3009  entries = entries.map((e) => {3010    if (!e.deletedAt && !keepIds.has(e.id)) {3011      removed++;3012      const deletedAt = monotonicEntryTimestamp(Math.max(3013        e.modifiedAt,3014        tombstones.get(e.id) ?? 0,3015      ));3016      tombstones.set(e.id, deletedAt);3017      return { ...e, deletedAt };3018    }3019    return e;3020  });30213022  if (removed > 0) await persistEntries();3023  return removed;3024}30253026// ---------------------------------------------------------------------------3027// Vault history — snapshot BEFORE every vault write so the saved blob is3028// what is about to be lost, not what was just written. Capped at 5. The3029// stored blobs are AES-256-GCM ciphertext under the master password, so3030// history adds zero security surface.3031// ---------------------------------------------------------------------------30323033const HISTORY_KEY = "peach_vault_history";3034const HISTORY_MAX = 5;30353036// PCH-01-023: coarsen a live-entry count into a low-resolution bucket so the3037// plaintext snapshot field cannot reveal exact vault size or single-entry change3038// deltas. Buckets widen as the vault grows so absolute leakage stays roughly3039// proportional rather than exact.3040function bucketEntryCount(n: number): number {3041  if (n <= 0) return 0;3042  if (n <= 10) return 10;3043  if (n <= 25) return 25;3044  if (n <= 50) return 50;3045  if (n <= 100) return 100;3046  if (n <= 250) return 250;3047  if (n <= 500) return 500;3048  return Math.ceil(n / 500) * 500;3049}30503051/**3052 * Snapshot the CURRENT on-disk vault state into history. Call this BEFORE3053 * overwriting peach_vault_a so the saved blob captures the about-to-be-lost3054 * state. Identical-to-most-recent blobs are skipped to avoid filling history3055 * with no-op writes.3056 */3057export async function takeVaultSnapshot(3058  reason: VaultSnapshot["reason"],3059): Promise<void> {3060  try {3061    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);3062    const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];3063    const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];30643065    // Nothing to snapshot if the real slot doesn't exist yet (fresh install,3066    // pre-createVault). createVault skips snapshots intentionally — there is3067    // no prior state to preserve.3068    if (!slotA) return;30693070    const vault_a = JSON.stringify(slotA);3071    const vault_b = JSON.stringify(slotB ?? slotA);30723073    // Best-effort entry count: only meaningful when the in-memory state is3074    // unlocked AND in real mode. Decoy mode would leak the decoy entry3075    // count; locked mode has no entries to count. Both fall through to null.3076    // PCH-01-023: store a coarse bucket, not the exact count — chrome.storage3077    // .local sits next to the AES-GCM blobs in plaintext, so an exact count would3078    // leak vault size and per-write deltas (the metadata padding hides this).3079    let entryCount: number | null = null;3080    if (derivedKey && vaultMode === "real") {3081      try {3082        entryCount = bucketEntryCount(entries.filter((e) => !e.deletedAt).length);3083      } catch {3084        entryCount = null;3085      }3086    }30873088    const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];3089    const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)3090      ? existingRaw3091      : { snapshots: [] };30923093    // Deduplication: if the most recent snapshot has byte-identical blobs,3094    // skip — saves the same vault N times in a row would otherwise burn the3095    // entire history window with no recovery value.3096    const latest = history.snapshots[0];3097    if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {3098      return;3099    }31003101    const snapshot: VaultSnapshot = {3102      id: crypto.randomUUID(),3103      savedAt: Date.now(),3104      reason,3105      vault_a,3106      vault_b,3107      entryCount,3108    };31093110    history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);3111    await chrome.storage.local.set({ [HISTORY_KEY]: history });3112  } catch (err) {3113    // Non-fatal — history must never block a save. A failed snapshot just3114    // means the user loses one rung of the safety ladder for this write.3115    // M4/QUA-006: log so the failure is visible; if it looks like a quota3116    // problem, notify the popup so the user can prune history themselves.3117    console.warn('[Peach] takeVaultSnapshot failed:', err);3118    if (String(err).includes('QUOTA') || String(err).includes('quota')) {3119      try {3120        await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });3121      } catch {3122        // popup may be closed; surfaced via console.warn above3123      }3124    }3125  }3126}31273128/** Wipe all vault history. Called by Panic / DESTROY_VAULT. */3129export async function clearVaultHistory(): Promise<void> {3130  try {3131    await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });3132  } catch {3133    // Non-fatal — DESTROY_VAULT also runs storage.local.clear().3134  }3135}31363137/** Read all snapshots, newest first, for the Settings vault history view. */3138export async function getVaultHistory(): Promise<VaultSnapshot[]> {3139  const raw = await chrome.storage.local.get(HISTORY_KEY);3140  const history = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];3141  if (!history || !Array.isArray(history.snapshots)) return [];3142  return history.snapshots;3143}31443145/**3146 * Replace the on-disk vault with the chosen snapshot's blobs and lock the3147 * vault. The current state is itself snapshotted with reason 'restore' first3148 * so the restore is reversible. After this returns, the user must unlock3149 * with the password that matches the restored blob.3150 */3151export async function restoreVaultSnapshot(3152  snapshotId: string,3153): Promise<{ ok: true } | { ok: false; error: string }> {3154  const history = await getVaultHistory();3155  const snapshot = history.find((s) => s.id === snapshotId);3156  if (!snapshot) return { ok: false, error: "snapshot_not_found" };31573158  // Snapshot the about-to-be-replaced current state so the restore is3159  // reversible. takeVaultSnapshot is no-op when the most recent entry is3160  // byte-identical, so a restore-of-a-restore stays clean.3161  await takeVaultSnapshot("restore");31623163  let restoredA: StoredVault;3164  let restoredB: StoredVault;3165  try {3166    restoredA = JSON.parse(snapshot.vault_a) as StoredVault;3167    restoredB = JSON.parse(snapshot.vault_b) as StoredVault;3168  } catch {3169    return { ok: false, error: "snapshot_corrupt" };3170  }31713172  await writeSlot(SLOT_A, restoredA);3173  await writeSlot(SLOT_B, restoredB);3174  await stampLocalVaultMutation();31753176  // Lock so the user must prove they can decrypt the restored blob. If they3177  // restored a pre-password-change snapshot they discover it immediately at3178  // the lock screen rather than silently holding an inaccessible vault.3179  lock();31803181  return { ok: true };3182}31833184/**3185 * Rotate the vault's sync identity by generating a FRESH ROOT KEY and3186 * re-wrapping everything under it (MV-8). Because every sync credential —3187 * vault_id, the Noise static keypair, the Ed25519 manifest signing key,3188 * and the per-entry envelope keys — derives from the root key, rotation3189 * makes a lost/stolen device's retained key material useless. All paired3190 * devices must re-pair afterwards.3191 *3192 * CONSEQUENCE THE UI MUST SURFACE: the 12 recovery words also derive from3193 * the root key, so rotation INVALIDATES the old recovery phrase. The flow3194 * sets peach_recovery_pending so the popup re-presents the new words for3195 * confirmation, same as the migrateToRecovery rotate path.3196 */3197export async function rotateSyncIdentity(): Promise<{ ok: boolean; error?: string }> {3198  if (!derivedKey || vaultMode !== "real") {3199    return { ok: false, error: "vault_locked" };3200  }3201  const slotA = await loadSlot(SLOT_A);3202  if (!slotA) return { ok: false, error: "missing_slot_a" };32033204  // 1. Fresh root key + recovery escrow (new words).3205  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =3206    await generateAndWrapRootKey();32073208  // 2. Re-wrap the new root key under the current password-derived key.3209  const newRootKey = unhex(rawRootKey);3210  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, newRootKey);32113212  // 3. Snapshot, then single atomic slot write — both escrow wrappings of3213  //    the new root key land together (same transactional rule as3214  //    changePassword). Entries are untouched: they are sealed under the3215  //    password-derived key, not the root key.3216  await takeVaultSnapshot("local_save");3217  const nextSlotA: StoredVault = {3218    ...slotA,3219    recovery_salt: recoverySalt,3220    recovery_wrapped_root_key: wrappedRootKey,3221    recovery_nonce: wrappedNonce,3222    recovery_tag: wrappedTag,3223    ...pwRoot,3224  };3225  await writeSlot(SLOT_A, nextSlotA);32263227  // 4. Swap in memory only after disk committed.3228  if (rootKey) zeroKey(rootKey);3229  rootKey = newRootKey;32303231  // 5. Old peers' identities derive from the dead root key — drop them all.3232  await clearPairedDevices();32333234  // 6. Force re-presentation of the NEW recovery words on next popup view.3235  await setRecoveryConfirmPending(); // same flag the create-vault flow uses32363237  await stampLocalVaultMutation();3238  return { ok: true };3239}32403241/**3242 * Change the master password. Re-encrypts slot A with a fresh salt + new3243 * derived key. Slot B (duress or noise) is left untouched when duress is3244 * configured — it uses an independent key derived from the duress password —3245 * and regenerated as noise when duress is not configured.3246 */3247export async function changePassword(3248  currentPassword: string,3249  newPassword: string3250): Promise<boolean> {3251  if (!derivedKey || vaultMode !== "real") return false;32523253  // Verify current password before allowing any change3254  const valid = await verifyMainPassword(currentPassword);3255  if (!valid) return false;32563257  const slotA = await loadSlot(SLOT_A);3258  if (!slotA) return false;3259  if (!rootKey) return false;32603261  // Derive fresh key from new password + new random salt3262  const newSalt = generateSalt();3263  const newKey = await deriveKey(newPassword, newSalt);32643265  // Re-encrypt the in-memory entries with the new key3266  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3267  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");32683269  // Pre-wrap root key under the new derived key. Recovery fields wrap rootKey3270  // under recovery words and remain untouched — recovery phrase keeps working3271  // across password changes (H4/COR-002).3272  const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);32733274  const finalSlotA: StoredVault = {3275    ...slotA,3276    salt: hex(newSalt),3277    nonce,3278    ciphertext,3279    tag,3280    ...pwRoot,3281  };32823283  // Snapshot the OLD-key blob before overwriting it. If the user later3284  // restores from this snapshot they will need the OLD password — the3285  // post-restore lock surfaces that immediately.3286  await takeVaultSnapshot("local_save");32873288  // Single atomic write: ciphertext, salt, and pw_root_* fields all land in3289  // one storage transaction. An SW kill before this point leaves the old3290  // slot intact; after this point everything tied to the new password is3291  // already on disk together (M6/COR-004).3292  await writeSlot(SLOT_A, finalSlotA);32933294  // Swap the in-memory key synchronously before any further await. If we3295  // threw between the Slot A write and this swap, the next persistEntries()3296  // would overwrite Slot A with old-key ciphertext, locking the user out.3297  zeroKey(derivedKey);3298  derivedKey = newKey;32993300  // PCH-01-008: the MV3 session escrow still holds the OLD key. Without this,3301  // the next service-worker restore decrypts the new-key Slot A with the stale3302  // key, fails tryDecryptSlotResult, and silently drops the user to a lock3303  // screen. Re-escrow the new key so restore survives a password change.3304  void saveSessionKey(newKey, "real");33053306  // Regenerate noise for slot B when duress is not in use. Runs after the3307  // key swap so a failure here is a disposable noise regeneration, not a3308  // lockout.3309  if (!duressConfigured) {3310    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3311  }3312  await clearPinUnlockStorage();3313  await stampLocalVaultMutation();33143315  return true;3316}