vault.ts

107.5 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 { recordSyncAlerts, type SyncAlert } from "./sync-alerts";16import {17  rootKeyToWords,18  wordsToRootKeyMaterial,19  deriveRecoveryKey,20} from "../shared/recovery-words";21import type {22  AccentColorName,23  Canary,24  LegacyVaultEntry,25  ManualSummonRecord,26  PasskeyData,27  SavedIdentity,28  StoredVault,29  VaultEntry,30  VaultHistory,31  VaultSnapshot,32} from "../shared/types";33import { decrypt, encrypt, zeroKey } from "./aes";34import { clearAutoLock, touchAutoLock } from "./alarms";35import { setRecoveryConfirmPending } from "./recovery-pending";3637type EntryDraft = Omit<38  VaultEntry,39  "id" | "createdAt" | "modifiedAt" | "deletedAt"40>;4142// Slot-neutral storage keys (v1.4.24+). Both slots always exist; slot B43// either holds the decoy vault (when duress is configured) or random noise44// that looks identical at rest. No external indicator is stored — duress45// configuration is recorded only inside the encrypted payload of slot A.46const SLOT_A = "peach_vault_a";47const SLOT_B = "peach_vault_b";4849// Legacy keys, migrated away on first access.50const LEGACY_MAIN = "peach_vault";51const LEGACY_DECOY = "peach_decoy_vault";52const LEGACY_DURESS_FLAG = "peach_duress";5354// Plaintext is padded to the next multiple of this size before encryption.55// This coarsens ciphertext-length leakage into 1 KiB buckets.56const PAD_BLOCK = 1024;5758// How many past passwords to retain per entry. Generous enough to be useful as59// a recovery aid while bounding the secret material we hold (and the ciphertext60// growth) for an entry whose password is rotated frequently.61const PASSWORD_HISTORY_MAX = 50;6263// When duress is configured, BOTH slots are padded to this fixed ceiling so64// their ciphertext lengths are identical and cannot reveal that a hidden decoy65// vault exists (audit MEDIUM — plausible-deniability leak). 256 KiB comfortably66// holds a very large vault (thousands of entries incl. passkeys). The decoy67// slot can't be re-encrypted on every real-vault save (the real session has no68// decoy key), so a fixed ceiling — rather than size-matching on each write — is69// what keeps the two slots equal. A real vault whose plaintext exceeds this70// would grow past the ceiling and re-expose the bit; that is an extreme,71// documented edge well beyond normal use.72const DURESS_SLOT_SIZE = 262_144;7374let derivedKey: Uint8Array | null = null;75// 32-byte random root key, separate from the derivedKey used for vault encryption.76// The root key is wrapped (encrypted) under the recovery key derived from the77// 12-word phrase. When the user changes their password, only the wrapping changes;78// the root key and recovery words remain stable.79let rootKey: Uint8Array | null = null;80let entries: VaultEntry[] = [];81let domainIndex: Map<string, VaultEntry[]> = new Map();82let vaultMode: "real" | "decoy" = "real";83// Cached post-unlock view of whether the real vault records that duress is84// configured. Only meaningful after a real-mode unlock; for decoy-mode unlock85// this stays false because we never see slot A's plaintext.86let duressConfigured = false;8788let migrationRan = false;8990// Set to a corruption reason during the last unlock() attempt when both slots91// decrypted but failed schema validation. Consumed and cleared by92// consumeLastUnlockFailureReason() so messages.ts can surface vault_corrupted93// distinctly from wrong-password (M7/COR-007).94//95// NOTE: module-level state — if vault.ts is ever moved to a worker context,96// this must be replaced with a structured return value from unlock() or a97// postMessage channel. The signal is invisible across module-instance98// boundaries.99let lastUnlockFailureReason: string | null = null;100101export function consumeLastUnlockFailureReason(): string | null {102  const r = lastUnlockFailureReason;103  lastUnlockFailureReason = null;104  return r;105}106107// ---------------------------------------------------------------------------108// Settings (persisted inside the encrypted vault store as a sidecar key)109// ---------------------------------------------------------------------------110111export type TextSize = "small" | "medium" | "large";112113export interface VaultSettings {114  accentColor?: AccentColorName;115  theme?: "dark" | "light";116  autoLockMinutes?: number;117  clipboardClearSeconds?: number;118  lockOnClose?: boolean;119  breachMonitoring?: boolean;120  passkeyProviderEnabled?: boolean;121  trashRetentionDays?: number;122  manualSummonDomains?: Record<string, ManualSummonRecord>;123  declinedCardFingerprints?: string[];124  /**125   * Text size scale for body copy and entry titles. Stops at "large" by126   * design — XL clips dense screens (Vault, Health) inside the fixed127   * 330×480 popup surface.128   */129  textSize?: TextSize;130  /**131   * When true, all entrance/exit transitions and ambient animations are132   * collapsed to instant. Honoured alongside the user's OS-level133   * `prefers-reduced-motion`.134   */135  reduceMotion?: boolean;136  /**137   * Android-only: when true, the master key is escrowed in AndroidKeyStore138   * and the lock screen offers biometric unlock. Toggled from Settings →139   * Security → Biometrics. Has no effect on desktop builds.140   */141  biometricsEnabled?: boolean;142  /**143   * User overrides for keyboard shortcuts. Keys are ShortcutAction names144   * (see src/shared/shortcuts.ts). Missing actions fall through to145   * DEFAULT_BINDINGS — `getActiveBindings(settings.shortcuts)` is the146   * canonical lookup. Storing only the deltas keeps the vault payload147   * small and lets default updates land for users who never rebind.148   */149  shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;150}151152let settings: VaultSettings = {};153154export function getSettings(): VaultSettings {155  return settings;156}157158export async function ensureSettingsLoaded(): Promise<VaultSettings> {159  await loadSettings();160  return settings;161}162163export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {164  await loadSettings();165  // LV-7: cheap insurance against prototype pollution if a future caller ever166  // feeds parsed external JSON here (native spread keeps __proto__ an own-167  // property today, but Object.assign-style consumers and JSON revivers have168  // been burned before).169  const safe = Object.fromEntries(170    Object.entries(patch).filter(171      ([k]) => !["__proto__", "constructor", "prototype"].includes(k),172    ),173  ) as Partial<VaultSettings>;174  settings = { ...settings, ...safe };175  await persistSettings();176}177178async function persistSettings(): Promise<void> {179  try {180    await chrome.storage.local.set({ peach_settings: settings });181  } catch (err) {182    throw mapStorageError(err);183  }184}185186function mapStorageError(err: unknown): Error {187  const message = err instanceof Error ? err.message : String(err);188  if (/QUOTA_BYTES|quota/i.test(message)) {189    return new Error("STORAGE_QUOTA_EXCEEDED");190  }191  return err instanceof Error ? err : new Error(message);192}193194async function loadSettings(): Promise<void> {195  const result = await chrome.storage.local.get("peach_settings");196  settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};197}198199// Fire-and-forget sync trigger after a committed vault write. Lazy200// dynamic import avoids a circular dependency between vault.ts and201// sync-trigger.ts (the trigger imports paired-devices, which only reads202// storage, but the lazy load also gives us a clean opt-out path in203// tests where sync-trigger has not been initialised).204function fireSyncTrigger(reason: "vault_change"): void {205  void import("./sync-trigger")206    .then((mod) => mod.triggerSyncIfReachable({ reason }))207    .catch(() => {208      /* sync trigger module not available — non-fatal */209    });210}211212// ---------------------------------------------------------------------------213// HIBP breach check (k-anonymity model)214// ---------------------------------------------------------------------------215216export async function checkBreach(password: string): Promise<number> {217  // HIBP k-anonymity API is keyed on SHA-1 prefixes — this is dictated by218  // the public API, not a security choice. Do not migrate to SHA-256 here.219  const encoder = new TextEncoder();220  const hashBuffer = await crypto.subtle.digest("SHA-1", encoder.encode(password));221  const hashHex = Array.from(new Uint8Array(hashBuffer))222    .map((b) => b.toString(16).padStart(2, "0"))223    .join("")224    .toUpperCase();225226  const prefix = hashHex.slice(0, 5);227  const suffix = hashHex.slice(5);228229  try {230    const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`);231    if (!res.ok) return 0;232    const text = await res.text();233    const match = text.split("\r\n").find((l) => l.startsWith(suffix));234    return match ? parseInt(match.split(":")[1], 10) : 0;235  } catch {236    return 0; // Network unavailable — don't block237  }238}239240export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {241  const fingerprint = await cardFingerprint(last4, expMonth, expYear);242  await loadSettings();243  settings = {244    ...settings,245    declinedCardFingerprints: [...(settings.declinedCardFingerprints ?? []), fingerprint],246  };247  await persistSettings();248}249250export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {251  await loadSettings();252  const fingerprint = await cardFingerprint(last4, expMonth, expYear);253  return (settings.declinedCardFingerprints ?? []).includes(fingerprint);254}255256async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {257  const encoder = new TextEncoder();258  const buf = await crypto.subtle.digest("SHA-256", encoder.encode(`${last4}|${expMonth}|${expYear}`));259  return Array.from(new Uint8Array(buf).slice(0, 8))260    .map((b) => b.toString(16).padStart(2, "0"))261    .join("");262}263264function hex(buf: Uint8Array): string {265  return Array.from(buf)266    .map((b) => b.toString(16).padStart(2, "0"))267    .join("");268}269270function unhex(s: string): Uint8Array {271  const out = new Uint8Array(s.length / 2);272  for (let i = 0; i < s.length; i += 2) {273    out[i / 2] = parseInt(s.slice(i, i + 2), 16);274  }275  return out;276}277278// ---------------------------------------------------------------------------279// Root key generation and recovery word wrapping280// ---------------------------------------------------------------------------281282/**283 * Generate a random 32-byte root key and wrap it (AES-256-GCM) under a key284 * derived from the recovery word material via HKDF-SHA256. The wrapped blob285 * fields are stored in slot A alongside the password-wrapped ciphertext. The286 * root key itself is kept in memory for the session so getRecoveryWords() can287 * encode it without re-deriving.288 *289 * SECURITY MODEL (PCH-01-005): the recovery KEK is derived from the 12-word290 * material, which encodes only rootKey[0..16] (recovery-words.ts). The KEK is thus291 * derived from a PREFIX of the very plaintext it wraps, and effective recovery292 * security is 128-bit (standard for a 12-word phrase), NOT 256-bit. This is safe —293 * unwrapping requires the words, and the GCM ciphertext leaks nothing without them —294 * but it is intentional, not an oversight. A future escrow version wanting 256-bit295 * recovery must derive the words from INDEPENDENT entropy, not from the root key.296 */297async function generateAndWrapRootKey(): Promise<{298  rawRootKey: string; // hex of the plaintext root key — caller stores in rootKey299  recoverySalt: string;300  wrappedRootKey: string;301  wrappedNonce: string;302  wrappedTag: string;303}> {304  const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));305306  // Derive the recovery key from the BIP39 words encoding of the root key.307  const words = await rootKeyToWords(rootKeyBytes);308  const wordMaterial = await wordsToRootKeyMaterial(words);309  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));310  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);311312  // Wrap the root key with the recovery key using AES-256-GCM directly.313  // We hex-encode rootKeyBytes so the plaintext is always valid UTF-8.314  const nonce = crypto.getRandomValues(new Uint8Array(12));315  const encoded = new TextEncoder().encode(hex(rootKeyBytes));316  const raw = await crypto.subtle.encrypt(317    {318      name: "AES-GCM",319      iv: nonce,320      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,321      tagLength: 128,322    },323    recoveryKey,324    encoded325  );326  // WebCrypto returns ciphertext || auth tag concatenated; split them.327  const rawU8 = new Uint8Array(raw);328  const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));329  const tag = hex(rawU8.slice(rawU8.length - 16));330331  return {332    rawRootKey: hex(rootKeyBytes),333    recoverySalt: hex(recoverySalt),334    wrappedRootKey: ciphertext,335    wrappedNonce: hex(nonce),336    wrappedTag: tag,337  };338}339340/**341 * Unwrap the root key using recovery words. Called during recovery flow when342 * the user provides their 12-word phrase and a new password.343 * Exported for use by the RECOVER_WITH_WORDS message handler.344 */345export async function unwrapRootKeyForRecovery(346  wrappedRootKey: string,347  wrappedNonce: string,348  wrappedTag: string,349  recoverySaltHex: string,350  words: string[]351): Promise<void> {352  const wordMaterial = await wordsToRootKeyMaterial(words);353  const recoverySalt = unhex(recoverySaltHex);354  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);355356  // Decrypt and cache the root key. The root key bytes were hex-encoded before357  // encryption so the ciphertext is valid UTF-8. We inline the AES-GCM decrypt358  // here to avoid passing a CryptoKey to the string-based encrypt/decrypt helpers.359  // Each component is stored separately in the vault slot; decode them individually360  // so the nonce is always exactly the 12 bytes from wrappedNonce.361  const nonceRaw = unhex(wrappedNonce);362  const ciphertextRaw = unhex(wrappedRootKey);363  const tagRaw = unhex(wrappedTag);364  // Combine ciphertext and tag for AES-GCM (expects ciphertext||tag).365  // Use explicit ArrayBuffer allocations to satisfy TS BufferSource constraints.366  const nonceU8 = nonceRaw as unknown as Uint8Array<ArrayBuffer>;367  const combined = new Uint8Array(ciphertextRaw.length + tagRaw.length);368  combined.set(ciphertextRaw, 0);369  combined.set(tagRaw, ciphertextRaw.length);370  const raw = await crypto.subtle.decrypt(371    { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },372    recoveryKey,373    combined374  );375  const decryptedHex = new TextDecoder().decode(raw);376  rootKey = unhex(decryptedHex);377}378379/**380 * Re-wrap the cached root key under a new derived key (from the user's new381 * password). Called after password change and after recovery re-key so the382 * same recovery words continue to work with the updated password — and so383 * subsequent unlocks can rehydrate rootKey via deriveRootKeyFromDerivedKey.384 *385 * recovery_* fields are intentionally not touched: those wrap rootKey under386 * the recovery words, which do not change when the password changes.387 */388export async function rewrapRootKeyForPassword(389  newDerivedKey: Uint8Array,390  _newSalt: Uint8Array391): Promise<void> {392  if (!rootKey) throw new Error("root key not set");393  const slotA = await loadSlot(SLOT_A);394  if (!slotA) throw new Error("missing slot A");395  const pwRoot = await wrapRootKeyForDerivedKey(newDerivedKey, rootKey);396  await writeSlot(SLOT_A, { ...slotA, ...pwRoot });397}398399/**400 * Change the vault encryption to a new derived key (already derived from401 * the user's new password). Used by RECOVER_WITH_WORDS and changePassword.402 * Caller is responsible for key swap and snapshot.403 */404async function reencryptVaultForNewKey(405  newKey: Uint8Array,406  slotA: StoredVault407): Promise<void> {408  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);409  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");410  await writeSlot(SLOT_A, {411    ...slotA,412    nonce,413    ciphertext,414    tag,415  });416}417418/**419 * Full password change with an already-derived key (used after recovery).420 * Unlike changePassword(), this skips re-verification of current password421 * since recovery flow has already validated the user's identity via words.422 */423export async function changePasswordWithNewKey(424  newSalt: Uint8Array,425  newKey: Uint8Array426): Promise<void> {427  const slotA = await loadSlot(SLOT_A);428  if (!slotA) throw new Error("missing slot A");429  // reencryptVaultForNewKey must receive the updated salt so that subsequent430  // UNLOCK calls with the new password can re-derive the correct key.431  await reencryptVaultForNewKey(newKey, { ...slotA, salt: hex(newSalt) });432  if (derivedKey) zeroKey(derivedKey);433  derivedKey = newKey;434  // PCH-01-008: re-escrow the new key (see changePassword). The recovery flow435  // reaches this path, so a post-recovery SW restart would otherwise lock out436  // a user who just reset their password.437  void saveSessionKey(newKey, "real");438  // Refresh pw_root_* under the new key so deriveRootKeyFromDerivedKey works439  // on the next unlock (H2/COR-006). If rootKey is missing — recovery flow440  // should have populated it — fall back silently rather than blowing up the441  // recovery path; migrateToRecovery will rehydrate on the next unlock.442  if (rootKey) {443    const slotAfter = await loadSlot(SLOT_A);444    if (slotAfter) {445      const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);446      await writeSlot(SLOT_A, { ...slotAfter, ...pwRoot });447    }448  }449  if (!duressConfigured) {450    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));451  }452  await stampLocalVaultMutation();453}454455// ---------------------------------------------------------------------------456// Salt generation --- exported so the RECOVER_WITH_WORDS handler can derive457// a new key after password reset without re-importing the crypto module.458// ---------------------------------------------------------------------------459460export { deriveKey, generateSalt };461462export async function loadSlotA(): Promise<StoredVault | null> {463  return loadSlot(SLOT_A);464}465466/**467 * Recover the session root key by AES-GCM-decrypting the pw_root_* fields468 * (a second wrapping of the root key under the password-derived key). This469 * is what makes GET_RECOVERY_WORDS work across lock/unlock cycles without470 * the user re-entering their recovery phrase: the same root key bytes —471 * and therefore the same 12 words — survive every unlock.472 *473 * Returns null when the pw_root fields are absent (pre-v2.12 vault that474 * hasn't been migrated yet) or when decryption fails (wrong derived key,475 * tampered ciphertext). On null the caller should fall through to476 * migrateToRecovery() to populate the fields.477 */478async function deriveRootKeyFromDerivedKey(479  derivedKeyBytes: Uint8Array,480  slotA: StoredVault,481): Promise<Uint8Array | null> {482  if (!slotA.pw_root_ciphertext || !slotA.pw_root_nonce || !slotA.pw_root_tag) {483    return null;484  }485  try {486    const rootHex = await decrypt(487      derivedKeyBytes,488      slotA.pw_root_nonce,489      slotA.pw_root_ciphertext,490      slotA.pw_root_tag,491      "pw_root_v1",492    );493    return unhex(rootHex);494  } catch {495    return null;496  }497}498499// AES-GCM-wrap rootKey under derivedKey for the pw_root_* fields. Returns the500// hex-encoded ciphertext/nonce/tag triple ready to embed in StoredVault.501async function wrapRootKeyForDerivedKey(502  derivedKeyBytes: Uint8Array,503  rootKeyBytes: Uint8Array,504): Promise<{ pw_root_ciphertext: string; pw_root_nonce: string; pw_root_tag: string }> {505  const { nonce, ciphertext, tag } = await encrypt(derivedKeyBytes, hex(rootKeyBytes), "pw_root_v1");506  return {507    pw_root_ciphertext: ciphertext,508    pw_root_nonce: nonce,509    pw_root_tag: tag,510  };511}512513/**514 * For vaults created before v2.12 (no recovery_salt/recovery_wrapped_root_key),515 * generate the root key, wrap it under the recovery words, and persist the516 * recovery escrow into slot A. The caller must show the recovery words to the517 * user before calling this — once called, those words are the vault's recovery518 * path. This runs once, on the first unlock of an upgraded vault.519 */520export async function migrateToRecovery(): Promise<void> {521  if (!derivedKey || vaultMode !== "real") {522    throw new Error("vault must be unlocked in real mode");523  }524  const slotA = await loadSlot(SLOT_A);525  if (!slotA) throw new Error("missing slot A");526  const hasRecoveryEscrow =527    !!slotA.recovery_salt && !!slotA.recovery_wrapped_root_key;528  const hasPwRoot = !!slotA.pw_root_ciphertext && !!slotA.pw_root_nonce;529  if (hasRecoveryEscrow && hasPwRoot) return; // already done530531  // If recovery escrow already exists but pw_root doesn't, we cannot recover532  // the original rootKey without the user's words. The least-surprising path533  // is to rotate to a fresh root key — the user's old recovery words become534  // invalid but we surface peach_recovery_pending so the popup re-presents535  // the words. The unlock-path callers all set that flag.536  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =537    await generateAndWrapRootKey();538  rootKey = unhex(rawRootKey);539540  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);541  const nextSlotA: StoredVault = {542    ...slotA,543    recovery_salt: recoverySalt,544    recovery_wrapped_root_key: wrappedRootKey,545    recovery_nonce: wrappedNonce,546    recovery_tag: wrappedTag,547    ...pwRoot,548  };549  await writeSlot(SLOT_A, nextSlotA);550  await stampLocalVaultMutation();551}552553/**554 * Returns the 12 recovery words for the current session's root key.555 * Must be called while the vault is unlocked. Throws if recovery has not556 * been set up (pre-v2.12 vault that hasn't migrated yet).557 */558export async function getRecoveryWords(): Promise<string[]> {559  if (!rootKey) {560    throw new Error("recovery not set up — vault may need migration");561  }562  return rootKeyToWords(rootKey);563}564565async function loadSlot(key: string): Promise<StoredVault | null> {566  const result = await chrome.storage.local.get(key);567  return (result as Record<string, StoredVault | undefined>)[key] ?? null;568}569570async function writeSlot(key: string, vault: StoredVault): Promise<void> {571  try {572    await chrome.storage.local.set({ [key]: vault });573  } catch (err) {574    throw mapStorageError(err);575  }576}577578// Monotonic clock for per-entry modifiedAt / deletedAt timestamps. Guards the579// sync layer's last-write-wins merge against wall-clock regressions (NTP step,580// manual clock change, DST glitch): a backwards Date.now() must never produce581// an entry timestamp that's <= the entry's existing modifiedAt, or a genuine582// local edit would lose to a stale remote copy. The returned value is always583// strictly greater than both the entry's current modifiedAt and the previous584// call's result (SEV-2-E).585let lastEntryTimestamp = 0;586function monotonicEntryTimestamp(currentModifiedAt?: number): number {587  const base = Math.max(588    Date.now(),589    (currentModifiedAt ?? 0) + 1,590    lastEntryTimestamp + 1,591  );592  lastEntryTimestamp = base;593  return base;594}595596async function stampLocalVaultMutation(): Promise<void> {597  const raw = await chrome.storage.local.get("peach_last_modified_at");598  const previous = Number(599    (raw as Record<string, unknown>).peach_last_modified_at,600  );601  const next = Math.max(602    Date.now(),603    Number.isFinite(previous) ? previous + 1 : 0,604  );605  await chrome.storage.local.set({606    peach_last_modified_at: String(next),607  });608}609610/**611 * One-shot migration from the pre-A-2 schema (peach_vault + peach_decoy_vault612 * + peach_duress flag) to the slot-neutral schema (peach_vault_a +613 * peach_vault_b). Runs at most once per session; safe to call repeatedly.614 */615async function ensureMigrated(): Promise<void> {616  if (migrationRan) return;617  migrationRan = true;618619  const keys = [LEGACY_MAIN, LEGACY_DECOY, LEGACY_DURESS_FLAG, SLOT_A, SLOT_B];620  const raw = await chrome.storage.local.get(keys);621  const slotAExists = raw[SLOT_A] !== undefined;622  const slotBExists = raw[SLOT_B] !== undefined;623  const legacyMain = raw[LEGACY_MAIN] as StoredVault | undefined;624  const legacyDecoy = raw[LEGACY_DECOY] as StoredVault | undefined;625626  // Fresh install with nothing in storage — nothing to do; createVault() sets up both slots.627  if (!slotAExists && !legacyMain) return;628629  // Already migrated.630  if (slotAExists && slotBExists && !legacyMain && !legacyDecoy) return;631632  let didMigrate = false;633  if (legacyMain && !slotAExists) {634    await writeSlot(SLOT_A, legacyMain);635    didMigrate = true;636  }637638  // If slot B isn't set, populate it: use legacy decoy when present, else noise.639  if (!slotBExists) {640    const target = (legacyMain ?? raw[SLOT_A]) as StoredVault | undefined;641    if (legacyDecoy) {642      await writeSlot(SLOT_B, legacyDecoy);643      didMigrate = true;644    } else if (target) {645      await writeSlot(SLOT_B, generateNoiseBlob(target.ciphertext.length / 2));646      didMigrate = true;647    }648  }649650  const toRemove: string[] = [];651  if (legacyMain) toRemove.push(LEGACY_MAIN);652  if (legacyDecoy) toRemove.push(LEGACY_DECOY);653  if (raw[LEGACY_DURESS_FLAG] !== undefined) toRemove.push(LEGACY_DURESS_FLAG);654  if (toRemove.length > 0) {655    await chrome.storage.local.remove(toRemove);656    didMigrate = true;657  }658  if (didMigrate) {659    await stampLocalVaultMutation();660  }661}662663// ---------------------------------------------------------------------------664// Padding + noise helpers665// ---------------------------------------------------------------------------666667/**668 * Pads the plaintext string with trailing spaces so that the encoded byte669 * length is a multiple of PAD_BLOCK. JSON.parse tolerates trailing670 * whitespace after a complete document, so the padding is transparent on671 * decode. Ciphertext length equals plaintext length plus a 16-byte tag.672 */673function padPlaintext(json: string, minBytes = 0): string {674  const encoded = new TextEncoder().encode(json);675  const bucket = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);676  // minBytes lets the duress path force a fixed ceiling so both slots match.677  const target = Math.max(bucket, minBytes);678  const padLen = target - encoded.length;679  return json + " ".repeat(padLen);680}681682/**683 * Produces a StoredVault-shaped record filled with CSPRNG bytes. The684 * ciphertext length matches the given byte count. Because GCM ciphertext is685 * pseudo-random, this blob is indistinguishable at rest from a real686 * encrypted vault without the key.687 *688 * crypto.getRandomValues() caps each call at 65536 bytes (the Web Crypto689 * spec hard limit). Chunk the fill so vaults larger than that — common once690 * the user has dozens of entries or any passkey — don't throw.691 */692const CSPRNG_CHUNK = 65_536;693694function fillRandom(buf: Uint8Array): Uint8Array {695  for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {696    const end = Math.min(offset + CSPRNG_CHUNK, buf.length);697    const chunk = new Uint8Array(end - offset);698    crypto.getRandomValues(chunk);699    buf.set(chunk, offset);700  }701  return buf;702}703704function generateNoiseBlob(ciphertextBytes: number): StoredVault {705  const salt = crypto.getRandomValues(new Uint8Array(16));706  const nonce = crypto.getRandomValues(new Uint8Array(12));707  const cipher = fillRandom(new Uint8Array(ciphertextBytes));708  const tag = crypto.getRandomValues(new Uint8Array(16));709  return {710    version: 1,711    salt: hex(salt),712    nonce: hex(nonce),713    ciphertext: hex(cipher),714    tag: hex(tag),715  };716}717718// ---------------------------------------------------------------------------719// Encrypted plaintext envelope720// ---------------------------------------------------------------------------721722type VaultPayload = {723  entries: VaultEntry[];724  duressConfigured?: boolean;725};726727type DecryptedPayload = {728  entries: VaultEntry[];729  duressConfigured: boolean;730  /**731   * True when at least one entry in the on-disk payload had a legacy shape732   * (pre-v2.11.0 passkey type/flat fields, or pre-A-2 created/updated keys)733   * and got rewritten by normalizeEntry. The unlock path uses this to734   * persist the new shape immediately — without it, the migration would735   * re-run on every unlock and old shape never disappears from disk.736   */737  migratedFromLegacy: boolean;738};739740function encodePayload(entries: VaultEntry[], duress: boolean, minBytes = 0): string {741  const envelope: VaultPayload = { entries, duressConfigured: duress };742  return padPlaintext(JSON.stringify(envelope), minBytes);743}744745function rawNeedsMigration(raw: VaultEntry | LegacyVaultEntry): boolean {746  if ("created" in raw || "updated" in raw) return true;747  const flat = raw as Partial<VaultEntry>;748  if (flat.type === "passkey") return true;749  // Flat rpId without a passkey sub-object means pre-v2.11.0 schema.750  if (flat.rpId !== undefined && flat.passkey === undefined) return true;751  return false;752}753754function decodePayload(plain: string): DecryptedPayload {755  const parsed = JSON.parse(plain) as756    | Array<VaultEntry | LegacyVaultEntry>757    | VaultPayload;758759  const rawEntries = Array.isArray(parsed) ? parsed : parsed.entries ?? [];760  const flatMigrationNeeded = rawEntries.some(rawNeedsMigration);761762  const normalized = rawEntries.map(normalizeEntry);763  const { merged } = mergePasskeyOnlyIntoLogins(normalized);764765  if (Array.isArray(parsed)) {766    return {767      entries: normalized,768      duressConfigured: false,769      migratedFromLegacy: true, // pre-A-2 array shape always needs save770    };771  }772773  return {774    entries: normalized,775    duressConfigured: parsed.duressConfigured === true,776    migratedFromLegacy: flatMigrationNeeded || merged,777  };778}779780/**781 * One-time consolidation pass run alongside the legacy passkey migration.782 *783 * Pre-v2.11.0 the Chrome passkey path always created a fresh `type:"passkey"`784 * entry per registration — so users who tested registration multiple times785 * accumulated several passkey-bearing entries for the same RP, and the786 * migration to the unified shape carried that duplication forward. This787 * pass collapses the duplicates:788 *789 *   1. Group passkey-bearing (and not deleted) entries by `passkey.rpId`.790 *   2. Within each group, the most recently-active credential wins (prefer791 *      lastUsedAt, fall back to passkey.createdAt, fall back to modifiedAt).792 *   3. If a NON-passkey login entry exists for that RP (matched by url or793 *      additionalUrls hostname), attach the winning passkey to it and794 *      soft-delete every passkey-bearing entry in the group.795 *   4. Otherwise, soft-delete every loser in the group, keeping the winner796 *      as a passkey-only entry.797 *798 * Soft delete (deletedAt) rather than splice — the trash flow keeps the799 * record around for retention and the user can restore if the heuristic800 * picked wrong. The `merged` flag goes back to decodePayload so the801 * unlock path persists the consolidated shape immediately.802 */803function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {804  let merged = false;805  const now = Date.now();806807  const candidates = entries.filter((e) => !e.deletedAt && e.passkey);808  const byRpId = new Map<string, VaultEntry[]>();809  for (const e of candidates) {810    const rpId = e.passkey!.rpId;811    const list = byRpId.get(rpId);812    if (list) list.push(e);813    else byRpId.set(rpId, [e]);814  }815816  for (const [rpId, group] of byRpId) {817    if (group.length === 0) continue;818    group.sort((a, b) => {819      const aT =820        a.passkey!.lastUsedAt ?? a.passkey!.createdAt ?? a.modifiedAt ?? a.createdAt;821      const bT =822        b.passkey!.lastUsedAt ?? b.passkey!.createdAt ?? b.modifiedAt ?? b.createdAt;823      return bT - aT;824    });825    const winner = group[0]!;826827    // Look for a NON-passkey login entry matching this RP. Use the URL828    // hostname rather than a substring search so a "login.foo.com" entry829    // doesn't accidentally absorb a passkey for "foo.com".830    const loginTarget = entries.find((e) => {831      if (e.deletedAt || e.passkey || e.type !== "login") return false;832      if (e.url && extractDomain(e.url) === rpId) return true;833      for (const extra of e.additionalUrls ?? []) {834        if (extractDomain(extra) === rpId) return true;835      }836      return false;837    });838839    if (loginTarget) {840      loginTarget.passkey = winner.passkey;841      loginTarget.modifiedAt = now;842      for (const dup of group) {843        if (!dup.deletedAt) {844          dup.deletedAt = now;845          dup.modifiedAt = now;846        }847      }848      merged = true;849    } else if (group.length > 1) {850      for (let i = 1; i < group.length; i += 1) {851        const dup = group[i]!;852        if (!dup.deletedAt) {853          dup.deletedAt = now;854          dup.modifiedAt = now;855        }856      }857      merged = true;858    }859  }860861  return { merged };862}863864// Validates that a `StoredVault` record on disk has the field shape we expect865// before treating an AES-GCM decrypt success as a clean unlock. AES-GCM only866// authenticates the static VERSION_BYTE AAD, not the `version` field on the867// outer record — a corrupted `version: 42` slot still decrypts cleanly. This868// check surfaces that as `corrupted` (M7/COR-007) so the popup can offer a869// history-restore path instead of falsely reporting "wrong password".870function hasValidVaultSchema(v: unknown): v is StoredVault {871  if (typeof v !== "object" || v === null) return false;872  const r = v as Record<string, unknown>;873  return (874    r.version === 1 &&875    typeof r.salt === "string" &&876    typeof r.nonce === "string" &&877    typeof r.ciphertext === "string" &&878    typeof r.tag === "string"879  );880}881882export type TryDecryptResult =883  | { status: "ok"; payload: DecryptedPayload }884  | { status: "wrong_key" }885  | { status: "corrupted"; reason: string };886887// Exported solely for `unlockFromCodex` below, which needs to verify a888// supplied passphrase against a slotA blob *without* committing anything to889// storage. Keep this internal otherwise — callers crossing the messages.ts890// boundary should always go through `unlock` / `verifyMainPassword` so the891// constant-time invariants in Projects.md §3.4 are not bypassed.892export async function tryDecryptSlot(893  vault: StoredVault,894  key: Uint8Array,895  aadTag?: string,896): Promise<DecryptedPayload | null> {897  const res = await tryDecryptSlotResult(vault, key, aadTag);898  return res.status === "ok" ? res.payload : null;899}900901export async function tryDecryptSlotResult(902  vault: StoredVault,903  key: Uint8Array,904  aadTag?: string,905): Promise<TryDecryptResult> {906  if (!hasValidVaultSchema(vault)) {907    return { status: "corrupted", reason: "invalid_slot_schema" };908  }909  let plain: string;910  try {911    plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);912  } catch {913    return { status: "wrong_key" };914  }915  try {916    const parsed = JSON.parse(plain) as unknown;917    if (typeof parsed !== "object" || parsed === null) {918      return { status: "corrupted", reason: "invalid_payload_shape" };919    }920    if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {921      return { status: "corrupted", reason: "invalid_payload_shape" };922    }923    return { status: "ok", payload: decodePayload(plain) };924  } catch {925    return { status: "corrupted", reason: "invalid_payload_json" };926  }927}928929// ---------------------------------------------------------------------------930// Core operations931// ---------------------------------------------------------------------------932933function buildDomainIndexSync(all: VaultEntry[]): void {934  domainIndex = new Map();935936  for (const entry of all) {937    if (entry.deletedAt) continue;938    if (entry.type === "note" || entry.type === "card") continue;939940    // An entry can match multiple sites via `additionalUrls`. Index each941    // hostname so `queryDomain` returns the entry regardless of which alias942    // the user is currently visiting. Dedupe per-entry so a single entry943    // never appears twice in one bucket.944    const domains = new Set<string>();945    const primary = extractDomain(entry.url ?? "");946    if (primary) domains.add(primary);947    for (const extra of entry.additionalUrls ?? []) {948      const d = extractDomain(extra);949      if (d) domains.add(d);950    }951    if (domains.size === 0) continue;952953    for (const domain of domains) {954      const bucket = domainIndex.get(domain) ?? [];955      bucket.push(entry);956      domainIndex.set(domain, bucket);957    }958  }959}960961export async function createVault(password: string): Promise<void> {962  await ensureMigrated();963964  const salt = generateSalt();965  derivedKey = await deriveKey(password, salt);966  entries = [];967  vaultMode = "real";968  duressConfigured = false;969  buildDomainIndexSync(entries);970971  // Generate and wrap the root key for recovery word escrow.972  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =973    await generateAndWrapRootKey();974  rootKey = unhex(rawRootKey);975976  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);977  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");978979  // Second wrapping of rootKey under derivedKey so future unlocks can rehydrate980  // it without recovery words (H2/COR-006).981  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);982983  const slotA: StoredVault = {984    version: 1,985    salt: hex(salt),986    nonce,987    ciphertext,988    tag,989    recovery_salt: recoverySalt,990    recovery_wrapped_root_key: wrappedRootKey,991    recovery_nonce: wrappedNonce,992    recovery_tag: wrappedTag,993    ...pwRoot,994  };995  await writeSlot(SLOT_A, slotA);996997  // Matching-size noise blob for slot B, so a fresh install shows two998  // similarly-shaped records regardless of whether duress is ever set up.999  await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));1000  await stampLocalVaultMutation();10011002  touchAutoLock();1003}10041005export async function hasVault(): Promise<boolean> {1006  await ensureMigrated();1007  return (await loadSlot(SLOT_A)) !== null;1008}10091010/**1011 * Returns whether the real vault has recorded that a duress passphrase is1012 * configured. Reliable only after a real-mode unlock — before unlock or in1013 * decoy mode, returns false because we cannot read slot A's plaintext.1014 */1015export async function isDuressEnabled(): Promise<boolean> {1016  return vaultMode === "real" && duressConfigured;1017}10181019export async function setupDuress(duressPassword: string): Promise<void> {1020  if (!derivedKey || vaultMode !== "real") {1021    throw new Error("vault must be unlocked in real mode");1022  }1023  await ensureMigrated();10241025  // Encrypt the decoy payload (empty entries) under the duress key. Pad to1026  // at least the current slot A ciphertext size so the two slots look the1027  // same at rest at setup time.1028  const slotA = await loadSlot(SLOT_A);1029  if (!slotA) throw new Error("missing slot A");10301031  const decoySalt = generateSalt();1032  const decoyKey = await deriveKey(duressPassword, decoySalt);1033  try {1034    // Pad the decoy to the fixed duress ceiling. Slot A is re-encrypted to the1035    // same ceiling by the persistSlotA() call below (duressConfigured is now1036    // true), so both slots are exactly DURESS_SLOT_SIZE+tag at rest and their1037    // lengths cannot reveal that duress is configured (audit MEDIUM).1038    const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);1039    const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");1040    await writeSlot(SLOT_B, {1041      version: 1,1042      salt: hex(decoySalt),1043      nonce,1044      ciphertext,1045      tag,1046    });1047  } finally {1048    zeroKey(decoyKey);1049  }10501051  // Re-encrypt slot A with the duressConfigured flag set to true. No external1052  // flag is written — the bit lives inside the encrypted envelope.1053  duressConfigured = true;1054  await persistSlotA();1055}10561057export async function disableDuress(): Promise<void> {1058  if (!derivedKey || vaultMode !== "real") {1059    throw new Error("vault must be unlocked in real mode");1060  }1061  await ensureMigrated();10621063  // Overwrite slot B with fresh noise that matches slot A's size. The slot1064  // remains occupied so its mere existence does not signal that duress was1065  // ever configured.1066  const slotA = await loadSlot(SLOT_A);1067  if (slotA) {1068    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));1069  }10701071  duressConfigured = false;1072  await persistSlotA();1073}10741075// L14/COR-015: this function intentionally checks slot A (real vault) only.1076// A duress-mode user attempting changePassword is rejected earlier by the1077// vaultMode === 'decoy' check at changePassword. The real-vs-decoy1078// distinction here is by design — duress users cannot rotate the real1079// password by guessing it, and the asymmetry in error timing is acceptable1080// because duress mode is opt-in and the user knows their own decoy key.1081export async function verifyMainPassword(password: string): Promise<boolean> {1082  await ensureMigrated();1083  const slotA = await loadSlot(SLOT_A);1084  if (!slotA) return false;1085  const key = await deriveKey(password, unhex(slotA.salt));1086  try {1087    return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;1088  } finally {1089    zeroKey(key);1090  }1091}10921093export async function unlock(password: string): Promise<boolean> {1094  // LV-1: the normal path NFC-normalizes inside deriveKey. If that fails and1095  // the supplied password is not already in NFC form, the vault may have been1096  // sealed (pre-LV-1) with the raw, un-normalized bytes — retry with those.1097  if (await attemptUnlockWithDerive(password, deriveKey)) return true;10981099  const nfc = password.normalize("NFC");1100  if (password === nfc) return false; // ASCII/NFC password — no legacy form to try11011102  if (await attemptUnlockWithDerive(password, deriveKeyRaw)) {1103    // Heal: re-seal the real slot under the NFC-normalized key so every1104    // future unlock takes the normal path. Only the real vault is re-sealed;1105    // a non-NFC duress password keeps working through this fallback.1106    if (vaultMode === "real") {1107      try {1108        const newSalt = generateSalt();1109        const newKey = await deriveKey(password, newSalt);1110        await changePasswordWithNewKey(newSalt, newKey);1111      } catch (healErr) {1112        console.warn("[Peach] LV-1 NFC heal failed:", healErr);1113      }1114    }1115    return true;1116  }1117  return false;1118}11191120async function attemptUnlockWithDerive(1121  password: string,1122  derive: typeof deriveKey,1123): Promise<boolean> {1124  await ensureMigrated();11251126  // Load both slots in parallel. Both always exist post-migration; the1127  // parallel load and the parallel derivation below keep wall-clock time1128  // constant regardless of which slot's passphrase (real or decoy) the1129  // caller supplied, so a timing side channel cannot distinguish the1130  // duress path from the real-unlock path (DUR-002).1131  const [slotA, slotB] = await Promise.all([1132    loadSlot(SLOT_A),1133    loadSlot(SLOT_B),1134  ]);11351136  // Derive both keys in parallel, unconditionally.1137  const [keyA, keyB] = await Promise.all([1138    slotA ? derive(password, unhex(slotA.salt)) : Promise.resolve(null),1139    slotB ? derive(password, unhex(slotB.salt)) : Promise.resolve(null),1140  ]);11411142  // Attempt both decrypts in parallel. The Result variant lets us distinguish1143  // 'wrong_key' from 'corrupted' so callers can offer a history-restore path1144  // when a slot's schema is invalid even though AES-GCM authenticated (M7).1145  const [resultA, resultB] = await Promise.all([1146    keyA && slotA1147      ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")1148      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1149    keyB && slotB1150      ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")1151      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1152  ]);1153  const payloadA = resultA.status === "ok" ? resultA.payload : null;1154  const payloadB = resultB.status === "ok" ? resultB.payload : null;11551156  if (payloadA && keyA) {1157    derivedKey = keyA;1158    void saveSessionKey(keyA, "real");1159    vaultMode = "real";1160    entries = payloadA.entries;1161    duressConfigured = payloadA.duressConfigured;1162    buildDomainIndexSync(entries);1163    await loadSettings();1164    touchAutoLock();1165    if (keyB) zeroKey(keyB);11661167    // slotA is non-null when payloadA is truthy (keyA was derived from slotA).1168    if (slotA) {1169      const needsRecoverySetup =1170        !slotA.recovery_salt || !slotA.recovery_wrapped_root_key;1171      if (!needsRecoverySetup) {1172        rootKey = await deriveRootKeyFromDerivedKey(keyA, slotA);1173      }1174      // Pre-v2.12 vault, or a vault whose pw_root_* fields haven't been written1175      // yet: generate the recovery escrow and seed pw_root_* so subsequent1176      // unlocks can rehydrate rootKey without the user's recovery words.1177      // Best-effort — a failure here must not block unlock.1178      if (needsRecoverySetup || !rootKey) {1179        try {1180          await migrateToRecovery();1181          if (needsRecoverySetup) {1182            // String "1" matches the popup's existing peach_recovery_pending1183            // check; surfaced so the user re-confirms recovery words after a1184            // legacy-vault unlock (H2/COR-006).1185            await chrome.storage.local.set({ peach_recovery_pending: '1' });1186          }1187        } catch (migrationErr) {1188          console.warn('[Peach] recovery migration failed:', migrationErr);1189        }1190      }1191    }11921193    // If the payload had a pre-v2.11.0 shape (legacy passkey type, flat1194    // passkey fields, or pre-A-2 created/updated keys), rewrite it now so1195    // the next save uses the new format and migration doesn't re-run forever.1196    if (payloadA.migratedFromLegacy) {1197      await persistSlotA();1198    }1199    return true;1200  }12011202  if (payloadB && keyB) {1203    derivedKey = keyB;1204    void saveSessionKey(keyB, "decoy");1205    vaultMode = "decoy";1206    entries = payloadB.entries;1207    duressConfigured = false;1208    buildDomainIndexSync(entries);1209    await loadSettings();1210    touchAutoLock();1211    if (keyA) zeroKey(keyA);1212    return true;1213  }12141215  if (keyA) zeroKey(keyA);1216  if (keyB) zeroKey(keyB);1217  // Surface corruption (good AES tag, broken schema) distinctly from1218  // wrong-password so the popup can offer history-restore (M7/COR-007).1219  if (resultA.status === "corrupted") {1220    lastUnlockFailureReason = resultA.reason;1221  } else if (resultB.status === "corrupted") {1222    lastUnlockFailureReason = resultB.reason;1223  }1224  return false;1225}12261227// ---------------------------------------------------------------------------1228// MV3 service worker session key — survives SW restarts within a browser session1229// ---------------------------------------------------------------------------12301231// chrome.storage.session is cleared on browser close; survives SW restart.1232// Firefox does not implement it (persistent background script, no restart risk).1233const SESSION_KEY_STORAGE = "peach_session_dk";12341235async function saveSessionKey(key: Uint8Array, mode: "real" | "decoy"): Promise<void> {1236  if (!chrome.storage.session) return;1237  await chrome.storage.session.set({ [SESSION_KEY_STORAGE]: { keyHex: hex(key), mode } });1238}12391240async function clearSessionKey(): Promise<void> {1241  if (!chrome.storage.session) return;1242  await chrome.storage.session.remove(SESSION_KEY_STORAGE);1243}12441245/**1246 * On SW restart, re-derive all in-memory vault state from the session key1247 * stored in chrome.storage.session (set at unlock time, cleared on lock).1248 * Returns true if the vault was restored, false if no session key was found.1249 * No-ops if the vault is already unlocked.1250 */1251export async function restoreFromSession(): Promise<boolean> {1252  if (derivedKey !== null) return true;1253  if (!chrome.storage.session) return false;1254  const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);1255  const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;1256  if (!entry?.keyHex) return false;12571258  const key = unhex(entry.keyHex);1259  const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;1260  const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";1261  const slot = await loadSlot(slotKey);1262  if (!slot) { await clearSessionKey(); return false; }12631264  const result = await tryDecryptSlotResult(slot, key, aadTag);1265  if (result.status !== "ok") { await clearSessionKey(); return false; }12661267  derivedKey = key;1268  vaultMode = entry.mode;1269  entries = result.payload.entries;1270  duressConfigured = entry.mode === "real" ? result.payload.duressConfigured : false;1271  buildDomainIndexSync(entries);1272  await loadSettings();1273  touchAutoLock();12741275  if (entry.mode === "real" && slot.recovery_salt && slot.recovery_wrapped_root_key) {1276    try { rootKey = await deriveRootKeyFromDerivedKey(key, slot); } catch { /* non-fatal */ }1277  }12781279  return true;1280}12811282export function lock(): void {1283  void clearSessionKey();1284  if (derivedKey) {1285    zeroKey(derivedKey);1286    derivedKey = null;1287  }1288  if (rootKey) {1289    rootKey.fill(0);1290    rootKey = null;1291  }12921293  entries = [];1294  domainIndex = new Map();1295  vaultMode = "real";1296  duressConfigured = false;1297  clearAutoLock();1298}12991300export function isUnlocked(): boolean {1301  return derivedKey !== null;1302}13031304// Opens the vault using a pre-derived AES-256 key (skipping Argon2id).1305// Used by Android biometric unlock — the key was derived on the native side.1306export async function unlockWithKey(1307  masterKeyHex: string,1308): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {1309  try {1310    const masterKeyBytes = unhex(masterKeyHex);1311    const stored = await loadSlot(SLOT_A);1312    if (!stored) return { ok: false, error: "invalid_key" };1313    const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");1314    if (!payload) return { ok: false, error: "invalid_key" };13151316    derivedKey = masterKeyBytes;1317    vaultMode = "real";1318    entries = payload.entries;1319    duressConfigured = payload.duressConfigured;1320    buildDomainIndexSync(entries);1321    await loadSettings();1322    touchAutoLock();13231324    // PCH-01-009: the biometric path skips Argon2id but must still rehydrate the1325    // root key, exactly like attemptUnlockWithDerive and restoreFromSession.1326    // Without it, rootKey stays null after a biometric unlock and chirp sync +1327    // GET_RECOVERY_WORDS report the open vault as locked. Guarded and non-fatal:1328    // a missing/legacy escrow must not fail the unlock itself.1329    if (stored.recovery_salt && stored.recovery_wrapped_root_key) {1330      try {1331        rootKey = await deriveRootKeyFromDerivedKey(masterKeyBytes, stored);1332      } catch { /* non-fatal — unlock still succeeds without rootKey */ }1333    }1334    return { ok: true, entries };1335  } catch {1336    return { ok: false, error: "invalid_key" };1337  }1338}13391340/**1341 * Restore the vault from a parsed Peach Codex payload.1342 *1343 * The supplied passphrase is verified against the Codex's slotA *before* any1344 * storage mutation — wrong passphrases return without touching disk. On1345 * success, the current vault state is snapshotted (reason: "restore") so the1346 * user can revert via Settings -> Vault History, then slotA/slotB are written1347 * and `peach_last_modified_at` is set to the Codex's recorded timestamp. A1348 * regular `unlock()` follows so the rest of the SW sees the standard1349 * post-unlock state.1350 *1351 * Intentionally non-Pro-gated — see peach_codex_v2.md "Pro gating". A Codex1352 * printed by a Pro user must always be restorable, even on a free device.1353 *1354 * Timing is not held constant here (in contrast to `unlock`): the Codex flow1355 * is an explicit user action with a known passphrase, not a passive lock1356 * screen, so the duress-vs-real timing side channel does not apply.1357 */1358export async function unlockFromCodex(params: {1359  slotA: string; // JSON string of StoredVault for slot A1360  slotB: string | null; // JSON string of StoredVault for slot B, or null1361  timestamp: number;1362  masterPassphrase: string;1363}): Promise<1364  | { ok: true; entryCount: number }1365  | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" }1366> {1367  let parsedSlotA: StoredVault;1368  let parsedSlotB: StoredVault | null = null;1369  try {1370    const rawA = JSON.parse(params.slotA) as unknown;1371    if (!hasValidVaultSchema(rawA)) {1372      return { ok: false, reason: "invalid_slot_format" };1373    }1374    parsedSlotA = rawA;1375    if (params.slotB !== null) {1376      const rawB = JSON.parse(params.slotB) as unknown;1377      if (!hasValidVaultSchema(rawB)) {1378        return { ok: false, reason: "invalid_slot_format" };1379      }1380      parsedSlotB = rawB;1381    }1382  } catch {1383    return { ok: false, reason: "invalid_slot_format" };1384  }13851386  // Verify the passphrase against the supplied slotA WITHOUT writing anything.1387  // If this fails the on-disk vault is left completely untouched.1388  const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));1389  const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");1390  if (!trialPayload) {1391    zeroKey(trialKey);1392    return { ok: false, reason: "wrong_passphrase" };1393  }1394  // Drop the trial key; `unlock()` below derives its own copy. Holding two1395  // copies of the master key in memory at once would be a needless surface.1396  zeroKey(trialKey);13971398  // Snapshot the about-to-be-overwritten on-disk state so the user can revert1399  // a mistaken Codex restore via the Vault History UI. Non-fatal if it fails.1400  await takeVaultSnapshot("restore");14011402  await writeSlot(SLOT_A, parsedSlotA);1403  if (parsedSlotB) {1404    await writeSlot(SLOT_B, parsedSlotB);1405  } else {1406    // Slot B must always exist with ciphertext length matching slot A1407    // (Projects.md §3.2). Codex prints may omit slot B (duress wasn't1408    // configured); regenerate noise to satisfy the invariant.1409    await writeSlot(1410      SLOT_B,1411      generateNoiseBlob(parsedSlotA.ciphertext.length / 2),1412    );1413  }1414  await chrome.storage.local.set({1415    peach_last_modified_at: String(params.timestamp),1416  });14171418  // Standard unlock path so domain index, settings, auto-lock, and1419  // recovery-key state all populate exactly as a normal unlock would.1420  const ok = await unlock(params.masterPassphrase);1421  if (!ok) {1422    // Should be unreachable — we just verified the passphrase against the1423    // same slotA we wrote. Treat as wrong_passphrase to keep the contract1424    // simple if some race or storage anomaly intrudes.1425    return { ok: false, reason: "wrong_passphrase" };1426  }1427  return { ok: true, entryCount: getEntries().length };1428}14291430// Returns the current in-memory derived key as a hex string.1431// Used by the biometric enable flow in Settings to store the key in Android Keystore.1432export function getDerivedKeyHex(): string {1433  if (!derivedKey) throw new Error("vault_not_unlocked");1434  return hex(derivedKey);1435}14361437/**1438 * Returns the vault's stable root key as hex, or null when locked / not yet1439 * populated. The root key is random per-vault, generated at creation, escrowed1440 * under the recovery words, and re-wrapped (not regenerated) on every password1441 * change — so it is INVARIANT across password rotation, unlike getDerivedKeyHex.1442 *1443 * This is the correct input for sync identity derivation (vault_id, the Noise1444 * XX static key, the Ed25519 manifest signing key, and per-entry envelope1445 * keys): paired devices keep the same identity and can still decrypt each1446 * other's entries after either side rotates its master password (SEV-2-B).1447 *1448 * Returns null rather than throwing so sync callers degrade to VAULT_LOCKED1449 * instead of crashing; rootKey is populated on every real-mode unlock via1450 * deriveRootKeyFromDerivedKey / migrateToRecovery.1451 */1452export function getRootKeyHex(): string | null {1453  return rootKey ? hex(rootKey) : null;1454}14551456export function getEntries(): VaultEntry[] {1457  if (!derivedKey) throw new Error("vault_locked");1458  return entries.filter((entry) => !entry.deletedAt);1459}14601461const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;14621463export function getIdentities(): SavedIdentity[] {1464  if (!derivedKey) throw new Error("vault_locked");1465  const active = entries.filter((e) => !e.deletedAt && e.type === "login");14661467  const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();1468  const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();14691470  for (const entry of active) {1471    const domain = extractDomain(entry.url ?? "") ?? "";1472    const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;14731474    function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {1475      const existing = map.get(v);1476      if (!existing || modifiedAt > existing.lastUsed) {1477        map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });1478      } else {1479        map.set(v, { ...existing, count: existing.count + 1 });1480      }1481    }14821483    const uVal = entry.username?.trim();1484    if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);14851486    // Also count the dedicated email field — entries created via the inline1487    // popup new-entry form store email here rather than in username.1488    const eVal = entry.email?.trim();1489    if (eVal) tally(emailMap, eVal);1490  }14911492  const toIdentity = (type: "email" | "username") =>1493    ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({1494      value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,1495    });14961497  return [1498    ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),1499    ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),1500  ];1501}15021503export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {1504  if (!derivedKey) throw new Error("vault_locked");15051506  const now = Date.now();1507  const added: VaultEntry[] = [];1508  for (const draft of drafts) {1509    try {1510      const sanitized = sanitizeEntryDraft(draft);1511      const nextEntry: VaultEntry = {1512        ...sanitized,1513        id: crypto.randomUUID(),1514        createdAt: now,1515        modifiedAt: monotonicEntryTimestamp(),1516      };1517      entries.push(nextEntry);1518      added.push(nextEntry);1519    } catch {1520      // Skip invalid drafts silently — caller can see diff between input and output length1521    }1522  }15231524  if (added.length > 0) {1525    await persistEntries();1526  }15271528  return added;1529}15301531/**1532 * Restore a set of entries in full fidelity — preserves id, createdAt,1533 * modifiedAt, and every other field unlike `batchAddEntries` which1534 * assigns fresh identity. Used by restore paths where the backup is the1535 * authoritative source of truth. `mode` controls how entries already in1536 * the vault are treated.1537 */1538export async function restoreEntries(1539  incoming: VaultEntry[],1540  mode: "replace" | "merge"1541): Promise<{ added: number; updated: number; skipped: number }> {1542  if (!derivedKey) throw new Error("vault_locked");15431544  // A replace with zero incoming entries is almost certainly a caller bug1545  // (e.g. an import that silently dropped everything). Refuse rather than1546  // wipe the vault.1547  if (mode === "replace" && incoming.length === 0) {1548    throw new Error("refuse to replace with empty entry set");1549  }15501551  let added = 0;1552  let updated = 0;1553  let skipped = 0;15541555  if (mode === "replace") {1556    entries = [];1557    for (const entry of incoming) {1558      const normalized = sanitizeRestoredEntry(entry);1559      if (!normalized) {1560        skipped += 1;1561        continue;1562      }1563      entries.push(normalized);1564      added += 1;1565    }1566  } else {1567    const byId = new Map<string, VaultEntry>();1568    for (const e of entries) byId.set(e.id, e);15691570    for (const entry of incoming) {1571      const normalized = sanitizeRestoredEntry(entry);1572      if (!normalized) {1573        skipped += 1;1574        continue;1575      }1576      const existing = byId.get(normalized.id);1577      if (!existing) {1578        entries.push(normalized);1579        added += 1;1580      } else if (normalized.modifiedAt > existing.modifiedAt) {1581        const idx = entries.findIndex((e) => e.id === existing.id);1582        if (idx !== -1) {1583          entries[idx] = normalized;1584          updated += 1;1585        }1586      } else {1587        skipped += 1;1588      }1589    }1590  }15911592  await persistEntries("import");1593  return { added, updated, skipped };1594}15951596/**1597 * Validate + normalise a VaultEntry coming from a backup, import, or sync1598 * peer. MV-6: this is a strict field WHITELIST — `normalizeEntry` copies1599 * only known VaultEntry fields (unknown/attacker keys are dropped), and1600 * nested `passkey`/`canary` shapes are rebuilt field-by-field, never1601 * spread. Returns null for values the live vault shouldn't accept.1602 */1603function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {1604  if (!entry || typeof entry !== "object") return null;1605  const title = typeof entry.title === "string" ? entry.title.trim() : "";1606  if (!title) return null;1607  const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();1608  const now = Date.now();1609  const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;1610  const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;16111612  // normalizeEntry whitelists every known VaultEntry field and runs the1613  // same legacy-passkey migration as the on-disk read path — pre-v2.11.01614  // backups with flat passkey fields still import correctly because the1615  // legacy flat fields are themselves whitelisted VaultEntry members.1616  const normalized = normalizeEntry({1617    ...entry,1618    id,1619    title,1620    type: entry.type ?? "login",1621    createdAt,1622    modifiedAt,1623  });16241625  if (normalized.passkey) {1626    normalized.passkey = sanitizePasskey(normalized.passkey);1627  }1628  if (normalized.canary) {1629    normalized.canary = sanitizeCanary(normalized.canary);1630  }1631  // PCH-01-016: bound tags on the restore path too, so both import funnels agree.1632  normalized.tags = sanitizeTags(normalized.tags);16331634  // Login entries from backup must carry a password (or be passkey-only,1635  // in which case the passkey sub-object replaces the password requirement).1636  if (1637    normalized.type === "login" &&1638    !normalized.passkey &&1639    typeof normalized.password !== "string"1640  ) {1641    return null;1642  }1643  if (entry.passkey && !normalized.passkey) {1644    // Entry claimed a passkey but the shape didn't validate — refuse the1645    // whole entry rather than silently importing a credential-less husk.1646    return null;1647  }16481649  return normalized;1650}16511652/**1653 * Rebuild a PasskeyData object from untrusted input, field by field.1654 * Returns undefined when required fields are missing/mistyped — a rogue1655 * passkey credential must not activate via import (MV-6 attack scenario).1656 */1657function sanitizePasskey(pk: unknown): PasskeyData | undefined {1658  if (!pk || typeof pk !== "object") return undefined;1659  const r = pk as Record<string, unknown>;1660  if (1661    typeof r.rpId !== "string" || !r.rpId ||1662    typeof r.credentialId !== "string" || !r.credentialId ||1663    typeof r.publicKeyCose !== "string" ||1664    typeof r.userHandle !== "string" ||1665    typeof r.userName !== "string"1666  ) {1667    return undefined;1668  }1669  return {1670    rpId: r.rpId,1671    rpName: typeof r.rpName === "string" ? r.rpName : r.rpId,1672    credentialId: r.credentialId,1673    publicKeyCose: r.publicKeyCose,1674    privateKeyJwk:1675      r.privateKeyJwk && typeof r.privateKeyJwk === "object"1676        ? (r.privateKeyJwk as JsonWebKey)1677        : undefined,1678    userHandle: r.userHandle,1679    userName: r.userName,1680    userDisplayName:1681      typeof r.userDisplayName === "string" ? r.userDisplayName : r.userName,1682    algorithm: r.algorithm === -8 ? -8 : -7,1683    signCount: typeof r.signCount === "number" ? r.signCount : 0,1684    aaguid: typeof r.aaguid === "string" ? r.aaguid : "",1685    backupEligible: r.backupEligible === true,1686    backupState: r.backupState === true,1687    lastUsedAt: typeof r.lastUsedAt === "number" ? r.lastUsedAt : undefined,1688    browser: r.browser === "chrome" || r.browser === "firefox" ? r.browser : undefined,1689    transports: Array.isArray(r.transports)1690      ? r.transports.filter((t): t is string => typeof t === "string")1691      : undefined,1692    createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),1693  };1694}16951696/**1697 * Rebuild a Canary object from untrusted input. The webhook must be a1698 * well-formed HTTPS URL — a poisoned canary.webhookUrl is a standing1699 * exfiltration endpoint that the canary subsystem will POST entry titles1700 * to (MV-6 attack scenario). Invalid → the canary is dropped, not the1701 * entry. FIRE_CANARY_PING re-validates with the full SSRF guard at fire1702 * time (isAllowedCanaryWebhookUrl), so this import-time check is the1703 * outer of two gates.1704 */1705function sanitizeCanary(c: unknown): Canary | undefined {1706  if (!c || typeof c !== "object") return undefined;1707  const r = c as Record<string, unknown>;1708  if (typeof r.webhookUrl !== "string") return undefined;1709  let url: URL;1710  try {1711    url = new URL(r.webhookUrl);1712  } catch {1713    return undefined;1714  }1715  if (url.protocol !== "https:") return undefined;1716  return {1717    webhookUrl: url.toString(),1718    label: typeof r.label === "string" ? r.label : undefined,1719    lastPinged: typeof r.lastPinged === "number" ? r.lastPinged : undefined,1720    pingCount: typeof r.pingCount === "number" ? r.pingCount : undefined,1721  };1722}17231724/**1725 * MV-6 / PCH-01-016: tags from imported / batch-added entries are untrusted.1726 * Keep only non-empty strings, cap each at 256 chars, and cap the count at 2551727 * (the same per-entry ceiling the export codec enforces, peachPayload.ts).1728 * Non-array or all-invalid input collapses to undefined.1729 */1730function sanitizeTags(tags: unknown): string[] | undefined {1731  if (!Array.isArray(tags)) return undefined;1732  const out: string[] = [];1733  for (const t of tags) {1734    if (typeof t !== "string") continue;1735    const trimmed = t.trim();1736    if (!trimmed) continue;1737    out.push(trimmed.slice(0, 256));1738    if (out.length >= 255) break;1739  }1740  return out.length > 0 ? out : undefined;1741}17421743// Soft-deletes every non-deleted entry in one call. The literal string1744// argument is a tripwire against accidental calls — any caller that would1745// wipe the vault has to consciously type "REPLACE_ALL". Do not relax this1746// to a boolean.1747export async function clearVaultEntries(1748  confirmation: "REPLACE_ALL"1749): Promise<void> {1750  if (confirmation !== "REPLACE_ALL") {1751    throw new Error("clearVaultEntries requires explicit confirmation");1752  }1753  if (!derivedKey) throw new Error("vault_locked");1754  for (const entry of entries) {1755    if (!entry.deletedAt) {1756      const stamp = monotonicEntryTimestamp(entry.modifiedAt);1757      entry.deletedAt = stamp;1758      entry.modifiedAt = stamp;1759    }1760  }1761  await persistEntries();1762}17631764export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {1765  if (!derivedKey) throw new Error("vault_locked");17661767  const sanitized = sanitizeEntryDraft(entry);1768  const now = Date.now();1769  const stamp = monotonicEntryTimestamp();1770  const nextEntry: VaultEntry = {1771    ...sanitized,1772    id: crypto.randomUUID(),1773    createdAt: now,1774    modifiedAt: stamp,1775    // Stamp passwordChangedAt at creation so age tracking is accurate from1776    // day one. Non-login entries carry the same stamp harmlessly.1777    passwordChangedAt: sanitized.password ? stamp : undefined,1778  };17791780  // Clone-and-replace so a failed persist rolls back the in-memory state1781  // (COR-008). Without this, a quota-full or storage error leaves the1782  // module-level `entries` ahead of what's actually on disk.1783  const rollback = entries;1784  entries = [...entries, nextEntry];1785  try {1786    await persistEntries();1787  } catch (err) {1788    entries = rollback;1789    throw err;1790  }17911792  // Fire-and-forget breach check (only for login entries if breach monitoring is enabled or not set)1793  if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {1794    checkBreach(nextEntry.password).then(async (count) => {1795      if (count > 0) {1796        const idx = entries.findIndex((e) => e.id === nextEntry.id);1797        if (idx !== -1) {1798          entries[idx] = { ...entries[idx], breach: count, modifiedAt: monotonicEntryTimestamp(entries[idx].modifiedAt) };1799          await persistEntries();1800        }1801      }1802    });1803  }18041805  fireSyncTrigger("vault_change");18061807  return nextEntry;1808}18091810/**1811 * Run the passkey-merge pass on the live in-memory entries and persist if1812 * anything changed. Called immediately after any passkey registration so that1813 * a same-domain TOTP-only entry already in the vault gets consolidated right1814 * away instead of waiting until the next lock/unlock cycle.1815 */1816export async function consolidatePasskeyEntries(): Promise<void> {1817  if (!derivedKey) return;1818  const { merged } = mergePasskeyOnlyIntoLogins(entries);1819  if (merged) {1820    await persistEntries();1821  }1822}18231824export async function updateEntry(1825  id: string,1826  patch: Partial<VaultEntry>1827): Promise<void> {1828  if (!derivedKey) throw new Error("vault_locked");18291830  const idx = entries.findIndex((entry) => entry.id === id);1831  if (idx === -1 || entries[idx].deletedAt) {1832    throw new Error("entry_not_found");1833  }18341835  const current = entries[idx];1836  const sanitizedPatch = sanitizeEntryPatch(patch);1837  // Refresh passwordChangedAt only when the password value actually changes —1838  // a metadata-only update (title, tags, etc.) must not reset the age clock1839  // that drives the Pro health rotation recommendation.1840  const passwordChanged =1841    "password" in patch &&1842    typeof sanitizedPatch.password === "string" &&1843    sanitizedPatch.password !== current.password;1844  const stamp = monotonicEntryTimestamp(current.modifiedAt);1845  // When the password actually changes, push the outgoing one onto the history1846  // (newest first) so the user can reveal/copy/restore it later. We record the1847  // age it carried (passwordChangedAt, falling back to createdAt) rather than1848  // `now`, so the list reflects when each password was last in effect. Only1849  // capture a non-empty prior value — clearing a password leaves no secret to1850  // keep, and we skip an immediate exact duplicate (e.g. restore-then-restore)1851  // to avoid noise.1852  const priorPassword = current.password;1853  const shouldCapture =1854    passwordChanged &&1855    typeof priorPassword === "string" &&1856    priorPassword.length > 0 &&1857    current.passwordHistory?.[0]?.password !== priorPassword;1858  const nextHistory = shouldCapture1859    ? [1860        { password: priorPassword!, changedAt: current.passwordChangedAt ?? current.createdAt },1861        ...(current.passwordHistory ?? []),1862      ].slice(0, PASSWORD_HISTORY_MAX)1863    : current.passwordHistory;1864  entries[idx] = {1865    ...current,1866    ...sanitizedPatch,1867    modifiedAt: stamp,1868    ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),1869  };1870187118721873  // Card entries must retain their card number1874  if (entries[idx].type === "card" && !entries[idx].cardNumber) {1875    entries[idx] = current;1876    throw new Error("card number is required for card entries");1877  }18781879  // Roll the in-memory entry back to its pre-edit state if the disk write1880  // fails (e.g. storage quota). Without this the module-level `entries` array1881  // would hold an edit that never landed on disk, diverging from the vault1882  // until the next unlock silently reverts it (SEV-3-A). Mirrors addEntry.1883  try {1884    await persistEntries();1885  } catch (err) {1886    entries[idx] = current;1887    throw err;1888  }18891890  // Breach check when password changes: clear immediately so old breach doesn't linger,1891  // then async-check the new password and only re-set if it's also found.1892  if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {1893    entries[idx] = { ...entries[idx], breach: undefined };1894    await persistEntries();1895    const password = entries[idx].password;1896    if (password) {1897      checkBreach(password).then(async (count) => {1898        const i = entries.findIndex((e) => e.id === id);1899        if (i !== -1 && count > 0) {1900          entries[i] = { ...entries[i], breach: count, modifiedAt: monotonicEntryTimestamp(entries[i].modifiedAt) };1901          await persistEntries();1902        }1903      });1904    }1905  }19061907  fireSyncTrigger("vault_change");1908}19091910export async function deleteEntry(id: string): Promise<void> {1911  if (!derivedKey) throw new Error("vault_locked");19121913  const entry = entries.find((item) => item.id === id);1914  if (!entry || entry.deletedAt) {1915    throw new Error("entry_not_found");1916  }19171918  // Tombstone timestamp must be strictly greater than the entry's last1919  // modification so the deletion wins LWW against any in-flight edit, even1920  // under clock skew (SEV-2-E).1921  const previousModifiedAt = entry.modifiedAt;1922  const stamp = monotonicEntryTimestamp(entry.modifiedAt);1923  entry.deletedAt = stamp;1924  entry.modifiedAt = stamp;1925  // Roll the tombstone back if the disk write fails, so a quota error doesn't1926  // leave the entry deleted in memory but alive on disk (SEV-3-A).1927  try {1928    await persistEntries();1929  } catch (err) {1930    delete entry.deletedAt;1931    entry.modifiedAt = previousModifiedAt;1932    throw err;1933  }1934  fireSyncTrigger("vault_change");1935}19361937export function getDeletedEntries(): VaultEntry[] {1938  if (!derivedKey) return [];1939  return entries.filter((e) => !!e.deletedAt);1940}19411942/**1943 * Returns the vault's monotonic version — the `peach_last_modified_at` value1944 * stamped on every user-initiated write. Remote (sync) writes do NOT advance1945 * this version so a sync round never cascades into a second outbound sync.1946 */1947export async function getVaultVersion(): Promise<number> {1948  try {1949    const raw = await chrome.storage.local.get("peach_last_modified_at");1950    const v = (raw as Record<string, unknown>).peach_last_modified_at;1951    if (typeof v === "number") return v;1952    if (typeof v === "string" && v !== "") {1953      const n = Number.parseInt(v, 10);1954      return Number.isFinite(n) ? n : 0;1955    }1956    return 0;1957  } catch {1958    return 0;1959  }1960}19611962/**1963 * Internal write variants — bypass `fireSyncTrigger` so the sync layer can1964 * apply entries without cascading into another outbound sync round.1965 *1966 * INVARIANT: callers must not pass entries whose IDs collide with existing1967 * active (non-deleted) entries unless the intent is an explicit overwrite.1968 * These functions do not validate field-level constraints (password required,1969 * card number required, etc.) — they are trust-the-caller paths for sync and1970 * test harness use only.1971 */1972export async function addEntryDirect(entry: VaultEntry): Promise<void> {1973  if (!derivedKey) throw new Error("vault_locked");1974  entries = [...entries, entry];1975  await persistEntries("sync_received");1976}19771978export async function updateEntryDirect(patch: VaultEntry): Promise<void> {1979  if (!derivedKey) throw new Error("vault_locked");1980  const idx = entries.findIndex((e) => e.id === patch.id);1981  if (idx === -1) throw new Error("entry_not_found");1982  entries[idx] = { ...entries[idx], ...patch };1983  await persistEntries("sync_received");1984}19851986export async function deleteEntryDirect(id: string, deletedAt: number): Promise<void> {1987  if (!derivedKey) throw new Error("vault_locked");1988  const idx = entries.findIndex((e) => e.id === id);1989  if (idx === -1) throw new Error("entry_not_found");1990  entries[idx] = { ...entries[idx], deletedAt, modifiedAt: deletedAt };1991  await persistEntries("sync_received");1992}19931994/**1995 * Apply a batch of remote entries + tombstones from a chirp-sync peer.1996 * Last-write-wins by `modifiedAt`; a tombstone supersedes a live entry when1997 * `deletedAt > modifiedAt` on the local side. Mutates `entries` directly and1998 * persists with reason `sync_received` — does NOT fire the sync dispatcher, so1999 * applying a sync round cannot cascade into another outbound sync.2000 *2001 * `applied` counts entries that actually changed local state (new add,2002 * overwrite-by-newer, or new tombstone). `received` is the raw payload size2003 * the caller can surface in the sync result UI.2004 */2005export async function applyMergedRemoteEntries(2006  remoteEntries: VaultEntry[],2007  remoteTombstones: Record<string, number>,2008  context: { deviceName?: string } = {},2009): Promise<{ received: number; applied: number; conflicts: number }> {2010  // DESIGN: last-write-wins is applied PER-ENTRY, not per-field. If two devices2011  // concurrently edit different fields of the same entry, the one with the2012  // newer modifiedAt wins the whole entry and the other device's field edits2013  // are dropped silently. This is the deliberate trade-off for a simple,2014  // conflict-free merge — per-field CRDT merge is out of scope. Guidance for2015  // users: edit a given entry on one device at a time.2016  if (!derivedKey) throw new Error("vault_locked");20172018  const received = remoteEntries.length + Object.keys(remoteTombstones).length;2019  let applied = 0;2020  let conflicts = 0;20212022  const byId = new Map<string, VaultEntry>();2023  for (const e of entries) byId.set(e.id, e);20242025  const alerts: SyncAlert[] = [];2026  const deviceName = context.deviceName ?? "paired device";2027  const mergeNow = Date.now();20282029  for (const remote of remoteEntries) {2030    const sanitized = sanitizeRestoredEntry(remote);2031    if (!sanitized) continue;2032    // HV-1a: a far-future remote modifiedAt must not permanently pin a2033    // malicious value against honest local edits. Clamp BEFORE any2034    // comparison against local timestamps.2035    sanitized.modifiedAt = clampSyncTimestamp(sanitized.modifiedAt, mergeNow);2036    if (typeof sanitized.deletedAt === "number") {2037      sanitized.deletedAt = clampSyncTimestamp(sanitized.deletedAt, mergeNow);2038    }2039    const tombstoneTs = remoteTombstones[sanitized.id];2040    if (tombstoneTs !== undefined && clampSyncTimestamp(tombstoneTs, mergeNow) >= sanitized.modifiedAt) {2041      continue;2042    }2043    const local = byId.get(sanitized.id);2044    if (!local) {2045      entries.push(sanitized);2046      byId.set(sanitized.id, sanitized);2047      applied += 1;2048    } else if (sanitized.modifiedAt > local.modifiedAt) {2049      const idx = entries.findIndex((e) => e.id === local.id);2050      if (idx !== -1) {2051        // HV-1b: surface remote password REPLACEMENTS (existing id, password2052        // differs) so a compromised peer can't silently rewrite credentials.2053        if (2054          !local.deletedAt &&2055          typeof sanitized.password === "string" &&2056          typeof local.password === "string" &&2057          sanitized.password !== local.password2058        ) {2059          alerts.push({2060            type: "REMOTE_PASSWORD_CHANGE",2061            entryId: sanitized.id,2062            entryTitle: sanitized.title,2063            deviceName,2064            timestamp: mergeNow,2065          });2066        }2067        entries[idx] = sanitized;2068        byId.set(sanitized.id, sanitized);2069        applied += 1;2070        if (!local.deletedAt) conflicts += 1;2071      }2072    }2073  }20742075  for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2076    if (typeof rawDeletedAt !== "number" || !Number.isFinite(rawDeletedAt)) continue;2077    // HV-1a/1c: clamp the tombstone timestamp before every comparison.2078    const deletedAt = clampSyncTimestamp(rawDeletedAt, mergeNow);2079    const local = byId.get(id);2080    if (!local) continue;2081    if (local.deletedAt && local.deletedAt >= deletedAt) continue;2082    if (deletedAt < local.modifiedAt) continue;2083    const idx = entries.findIndex((e) => e.id === id);2084    if (idx !== -1) {2085      // HV-1b: surface remote deletes of live local entries.2086      if (!local.deletedAt) {2087        alerts.push({2088          type: "REMOTE_DELETE",2089          entryId: id,2090          entryTitle: local.title,2091          deviceName,2092          timestamp: mergeNow,2093        });2094      }2095      entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };2096      applied += 1;2097    }2098  }20992100  if (applied > 0) {2101    await persistEntries("sync_received");2102    buildDomainIndexSync(entries);2103  }2104  // Queued after the merge committed — an alert must describe a mutation2105  // that actually landed. recordSyncAlerts never throws.2106  await recordSyncAlerts(alerts);2107  return { received, applied, conflicts };2108}21092110export async function restoreEntry(id: string): Promise<void> {2111  if (!derivedKey) throw new Error("vault_locked");2112  const entry = entries.find((e) => e.id === id && e.deletedAt);2113  if (!entry) throw new Error("deleted entry not found");2114  delete entry.deletedAt;2115  entry.modifiedAt = monotonicEntryTimestamp(entry.modifiedAt);2116  await persistEntries();2117  buildDomainIndexSync(entries);2118}21192120export async function purgeEntry(id: string): Promise<void> {2121  if (!derivedKey) throw new Error("vault_locked");2122  const idx = entries.findIndex((e) => e.id === id && e.deletedAt);2123  if (idx === -1) throw new Error("deleted entry not found");2124  entries.splice(idx, 1);2125  await persistEntries();2126}21272128/** Permanently delete entries whose deletedAt is older than retentionMs. 0 = keep forever. */2129export async function purgeExpiredTrash(retentionMs: number): Promise<number> {2130  if (!derivedKey || retentionMs === 0) return 0;2131  const cutoff = Date.now() - retentionMs;2132  const before = entries.length;2133  entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));2134  const purged = before - entries.length;2135  if (purged > 0) await persistEntries();2136  return purged;2137}21382139export function queryDomain(domain: string): VaultEntry[] {2140  return domainIndex.get(domain) ?? [];2141}21422143export function getEntryById(id: string): VaultEntry | undefined {2144  return entries.find((entry) => entry.id === id && !entry.deletedAt);2145}21462147async function persistSlotA(2148  reason: VaultSnapshot["reason"] = "local_save",2149): Promise<StoredVault> {2150  if (!derivedKey) throw new Error("vault_locked");21512152  const slotA = await loadSlot(SLOT_A);2153  if (!slotA) throw new Error("missing slot A");21542155  // Snapshot the about-to-be-overwritten state BEFORE we mutate disk. Failures2156  // are swallowed by takeVaultSnapshot — history must never block a save.2157  await takeVaultSnapshot(reason);21582159  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);2160  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");21612162  // Preserve existing recovery escrow fields.2163  const nextSlotA: StoredVault = {2164    ...slotA,2165    nonce,2166    ciphertext,2167    tag,2168    // recovery_salt and recovery_wrapped_root_key are already set from loadSlot2169  };2170  await writeSlot(SLOT_A, nextSlotA);21712172  // Slot A (the real vault) is now committed. Wrap every later write so a2173  // mid-persist failure (e.g. a storage error after slot A landed) restores the2174  // prior slot A before rethrowing. Without this, a "failed" save that already2175  // wrote slot A leaves disk ahead of the in-memory rollback in addEntry/2176  // updateEntry/deleteEntry — the entry stays silently on disk and resurfaces2177  // as a duplicate on the next unlock (observed under storage-quota pressure).2178  try {2179    // When duress is not configured, keep slot B size-matched with slot A by2180    // regenerating its noise. When duress IS configured, leave slot B alone —2181    // we don't have the decoy key to re-encrypt it. This is a known trade-off.2182    if (!duressConfigured) {2183      await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));2184    }2185    // Only advance the vault version for locally-originated writes. Entries2186    // applied from a sync peer ("sync_received") must NOT bump the counter —2187    // otherwise applying a remote round makes us look newer than the peer and2188    // triggers a redundant outbound sync, defeating the no-op optimisation2189    // and risking a ping-pong between two devices (SEV-2-C).2190    if (reason !== "sync_received") {2191      await stampLocalVaultMutation();2192    }2193  } catch (err) {2194    // Best-effort restore — the prior slot A is smaller-or-equal, so this write2195    // fits even when the failure was a quota overflow.2196    await writeSlot(SLOT_A, slotA).catch(() => {});2197    throw err;2198  }21992200  return nextSlotA;2201}22022203async function persistSlotB(): Promise<void> {2204  if (!derivedKey) throw new Error("vault_locked");22052206  const slotB = await loadSlot(SLOT_B);2207  if (!slotB) throw new Error("missing slot B");22082209  // Decoy plaintext always reports duressConfigured=false — the decoy user2210  // sees a clean slate. persistSlotB only runs in decoy mode, which only2211  // exists once duress is configured, so pad to the fixed duress ceiling to2212  // keep slot B's length equal to slot A's (audit MEDIUM — deniability).2213  const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);2214  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");22152216  await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });2217  // Symmetric with persistSlotA: if the version stamp fails after the decoy2218  // slot committed, restore the prior slot B so a failed decoy-mode save can't2219  // leave disk ahead of the in-memory rollback.2220  try {2221    await stampLocalVaultMutation();2222  } catch (err) {2223    await writeSlot(SLOT_B, slotB).catch(() => {});2224    throw err;2225  }2226}22272228async function persistEntries(2229  reason: VaultSnapshot["reason"] = "local_save",2230): Promise<void> {2231  if (!derivedKey) throw new Error("vault_locked");22322233  if (vaultMode === "decoy") {2234    await persistSlotB();2235  } else {2236    await persistSlotA(reason);2237  }2238  buildDomainIndexSync(entries);2239}22402241function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {2242  if (!Array.isArray(values)) return undefined;2243  const seen = new Set<string>();2244  const cleaned: string[] = [];2245  for (const value of values) {2246    const trimmed = typeof value === "string" ? value.trim() : "";2247    if (!trimmed) continue;2248    const key = trimmed.toLowerCase();2249    if (seen.has(key)) continue;2250    seen.add(key);2251    cleaned.push(trimmed);2252  }2253  return cleaned.length > 0 ? cleaned : undefined;2254}22552256function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {2257  const title = entry.title.trim();2258  // Accept legacy `type:"passkey"` drafts but rewrite to "login" — the new2259  // model is "any entry, optionally with a passkey sub-object." Imports and2260  // any in-flight callers from before v2.11.0 keep working without throwing.2261  let type: VaultEntry["type"] = entry.type ?? "login";2262  if (type === "passkey") type = "login";22632264  if (!title) throw new Error("title is required");22652266  if (entry.passkey) {2267    const p = entry.passkey;2268    if (2269      !p.rpId ||2270      !p.credentialId ||2271      !p.publicKeyCose ||2272      !p.userHandle ||2273      !p.userName ||2274      (p.algorithm !== -7 && p.algorithm !== -8)2275    ) {2276      throw new Error("invalid passkey credential");2277    }2278  }2279  if (type === "card") {2280    if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {2281      throw new Error("cardholder name and card number are required");2282    }2283  }22842285  return {2286    type,2287    title,2288    username: type === "login" ? entry.username?.trim() ?? "" : undefined,2289    email: type === "login" ? entry.email?.trim() || undefined : undefined,2290    password: type === "login" ? entry.password : undefined,2291    url: type === "login" ? entry.url?.trim() ?? "" : undefined,2292    additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,2293    totp: type === "login" ? entry.totp?.trim() || undefined : undefined,2294    // PCH-01-019: preserve non-default TOTP params through batch-add/import so2295    // they are not silently stripped (they fall back to SHA-1/6/30 when absent).2296    totpAlgorithm: type === "login" ? entry.totpAlgorithm : undefined,2297    totpDigits: type === "login" ? entry.totpDigits : undefined,2298    totpPeriod: type === "login" ? entry.totpPeriod : undefined,2299    notes: entry.notes?.trim() || undefined,2300    breach: type === "login" ? entry.breach : undefined,2301    // PCH-01-016: the batch-add path was bypassing the MV-6 canary/tags2302    // whitelist applied on the RESTORE_ENTRIES path. Run both sanitizers here.2303    canary: type === "login" ? sanitizeCanary(entry.canary) : undefined,2304    tags: sanitizeTags(entry.tags),2305    passkey: entry.passkey,2306    cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,2307    cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,2308    expMonth: type === "card" ? entry.expMonth?.trim() : undefined,2309    expYear: type === "card" ? entry.expYear?.trim() : undefined,2310    cvc: type === "card" ? entry.cvc?.trim() : undefined,2311    cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,2312    network: type === "card" ? entry.network : undefined,2313    last4: type === "card" ? entry.last4?.trim() : undefined,2314  };2315}23162317function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {2318  const nextPatch: Partial<VaultEntry> = {};23192320  if ("type" in patch) {2321    nextPatch.type = patch.type;2322  }23232324  if ("title" in patch) {2325    const title = patch.title?.trim() ?? "";2326    if (!title) throw new Error("title is required");2327    nextPatch.title = title;2328  }23292330  if ("url" in patch) {2331    nextPatch.url = patch.url?.trim() ?? "";2332  }23332334  if ("additionalUrls" in patch) {2335    const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];2336    const seen = new Set<string>();2337    const cleaned: string[] = [];2338    for (const value of incoming) {2339      const trimmed = typeof value === "string" ? value.trim() : "";2340      if (!trimmed) continue;2341      const key = trimmed.toLowerCase();2342      if (seen.has(key)) continue;2343      seen.add(key);2344      cleaned.push(trimmed);2345    }2346    nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;2347  }23482349  if ("username" in patch) {2350    nextPatch.username = patch.username?.trim() ?? "";2351  }23522353  if ("email" in patch) {2354    nextPatch.email = patch.email?.trim() || undefined;2355  }23562357  if ("password" in patch) {2358    const password = patch.password ?? "";2359    // Allow clearing a password (e.g. on passkey-only entries)2360    nextPatch.password = password || undefined;2361  }23622363  if ("totp" in patch) {2364    nextPatch.totp = patch.totp?.trim() || undefined;2365  }23662367  if ("notes" in patch) {2368    nextPatch.notes = patch.notes?.trim() || undefined;2369  }23702371  if ("breach" in patch) {2372    nextPatch.breach = patch.breach;2373  }23742375  if ("canary" in patch) {2376    nextPatch.canary = patch.canary;2377  }23782379  if ("passkey" in patch) {2380    // Passkey sub-object replaces all the legacy flat passkey fields. A2381    // patch with `passkey: undefined` removes the credential from the entry2382    // (used by "remove passkey" without deleting the whole entry).2383    nextPatch.passkey = patch.passkey;2384  }23852386  if ("tags" in patch) {2387    nextPatch.tags = patch.tags;2388  }23892390  if ("cardholderName" in patch) {2391    nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;2392  }2393  if ("cardNumber" in patch) {2394    const n = patch.cardNumber ?? "";2395    nextPatch.cardNumber = n || undefined;2396  }2397  if ("expMonth" in patch) {2398    nextPatch.expMonth = patch.expMonth?.trim() || undefined;2399  }2400  if ("expYear" in patch) {2401    nextPatch.expYear = patch.expYear?.trim() || undefined;2402  }2403  if ("cvc" in patch) {2404    nextPatch.cvc = patch.cvc?.trim() || undefined;2405  }2406  if ("cardNickname" in patch) {2407    nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;2408  }2409  if ("network" in patch) {2410    nextPatch.network = patch.network;2411  }2412  if ("last4" in patch) {2413    nextPatch.last4 = patch.last4?.trim() || undefined;2414  }24152416  return nextPatch;2417}24182419function normalizeEntry(entry: VaultEntry | LegacyVaultEntry): VaultEntry {2420  const createdAt = "createdAt" in entry ? entry.createdAt : entry.created;2421  const modifiedAt =2422    "modifiedAt" in entry ? entry.modifiedAt : entry.updated;24232424  const base: VaultEntry = {2425    id: entry.id,2426    type: "type" in entry ? entry.type : "login",2427    title: entry.title,2428    username: entry.username,2429    email: "email" in entry ? entry.email : undefined,2430    password: entry.password,2431    url: entry.url,2432    additionalUrls:2433      "additionalUrls" in entry && Array.isArray(entry.additionalUrls)2434        ? entry.additionalUrls2435        : undefined,2436    totp: entry.totp,2437    // PCH-01-019: carry TOTP params through the normalize/restore path too.2438    totpAlgorithm: entry.totpAlgorithm,2439    totpDigits: entry.totpDigits,2440    totpPeriod: entry.totpPeriod,2441    notes: entry.notes,2442    breach: entry.breach,2443    // Preserve the password-age clock across lock/unlock. Without this the2444    // field is dropped on every decode and the advanced-health "aged password"2445    // signal silently resets to createdAt on each unlock (SEV-2-A).2446    passwordChangedAt:2447      "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,2448    // Preserve past-password history across lock/unlock. normalizeEntry is a2449    // field whitelist, so an unlisted field is silently dropped on every decode2450    // (same class as the passwordChangedAt SEV-2-A above).2451    passwordHistory:2452      "passwordHistory" in entry && Array.isArray(entry.passwordHistory)2453        ? entry.passwordHistory2454        : undefined,2455    canary: "canary" in entry ? entry.canary : undefined,2456    passkey: "passkey" in entry ? entry.passkey : undefined,2457    createdAt,2458    modifiedAt,2459    deletedAt: entry.deletedAt,2460    tags: "tags" in entry ? entry.tags : undefined,2461    cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,2462    cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,2463    expMonth: "expMonth" in entry ? entry.expMonth : undefined,2464    expYear: "expYear" in entry ? entry.expYear : undefined,2465    cvc: "cvc" in entry ? entry.cvc : undefined,2466    cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,2467    network: "network" in entry ? entry.network : undefined,2468    last4: "last4" in entry ? entry.last4 : undefined,2469  };24702471  return migrateLegacyPasskey(base, entry);2472}24732474/**2475 * v2.11.0 read migration. Pre-v2.11.0 passkey entries used `type:"passkey"`2476 * with flat top-level fields (rpId, credentialId, etc.). This converts them2477 * to the new shape — `type:"login"` with a `passkey` sub-object — so all2478 * downstream consumers can rely on the new model. The result is rewritten2479 * to disk on next vault save (hasLegacyShape detects the un-migrated case).2480 */2481function migrateLegacyPasskey(2482  base: VaultEntry,2483  raw: VaultEntry | LegacyVaultEntry2484): VaultEntry {2485  if (base.passkey) return base;2486  const flat = raw as Partial<VaultEntry>;2487  const isPasskeyType = base.type === "passkey";2488  const hasFlatPasskeyFields =2489    typeof flat.rpId === "string" &&2490    typeof flat.credentialId === "string" &&2491    typeof flat.publicKeyCose === "string" &&2492    typeof flat.userHandle === "string" &&2493    typeof flat.userName === "string";2494  if (!isPasskeyType && !hasFlatPasskeyFields) return base;2495  if (!hasFlatPasskeyFields) return base;24962497  const algorithm: -7 | -8 = flat.algorithm === -8 ? -8 : -7;2498  base.passkey = {2499    rpId: flat.rpId!,2500    rpName: flat.rpName ?? flat.rpId!,2501    credentialId: flat.credentialId!,2502    publicKeyCose: flat.publicKeyCose!,2503    privateKeyJwk: flat.privateKeyJwk,2504    userHandle: flat.userHandle!,2505    userName: flat.userName!,2506    userDisplayName: flat.userDisplayName ?? flat.userName!,2507    algorithm,2508    signCount: flat.signCount ?? 0,2509    aaguid: flat.aaguid ?? "",2510    backupEligible: flat.backupEligible === true,2511    backupState: flat.backupState === true,2512    lastUsedAt: flat.lastUsedAt,2513    browser: flat.browser,2514    transports: flat.transports,2515    createdAt: base.createdAt,2516  };2517  // Promote to "login" so the unified Entry view renders. Username gets2518  // populated from the passkey's userName so the entry is searchable in the2519  // existing autofill flow without a separate code path.2520  if (isPasskeyType) base.type = "login";2521  if (!base.username) base.username = flat.userName;2522  if (!base.url) base.url = `https://${flat.rpId}`;2523  return base;2524}252525262527// ---------------------------------------------------------------------------2528// Deduplication2529// ---------------------------------------------------------------------------25302531function entryDupeKey(e: VaultEntry): string {2532  if (e.type === "note") return `note|${e.title.toLowerCase()}`;2533  // Passkey-bearing entries dedupe by the credential's RP + user. Two logins2534  // on different sites that happen to share a username are still distinct;2535  // two passkey credentials for the same RP+user are duplicates regardless2536  // of any login fields they may also carry.2537  if (e.passkey) {2538    return `passkey|${e.passkey.rpId.toLowerCase()}|${e.passkey.userName.toLowerCase()}`;2539  }2540  return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;2541}25422543/** Returns the number of duplicate entries (those that would be removed). */2544export function countDuplicates(): number {2545  const best = new Map<string, VaultEntry>();2546  let dupeCount = 0;2547  for (const e of entries.filter((e) => !e.deletedAt)) {2548    const key = entryDupeKey(e);2549    const existing = best.get(key);2550    if (!existing) {2551      best.set(key, e);2552    } else {2553      dupeCount++;2554      // Keep the more recently modified one in the map2555      if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2556        best.set(key, e);2557      }2558    }2559  }2560  return dupeCount;2561}25622563/**2564 * Soft-deletes duplicate entries, keeping the most recently modified copy of2565 * each group. Returns the number of entries moved to trash.2566 */2567export async function deduplicateEntries(): Promise<number> {2568  if (!derivedKey) throw new Error("vault_locked");2569  // Dedup reshapes slot B permanently under the decoy key, which is2570  // forensically distinguishable from a freshly-seeded decoy vault. Refuse.2571  if (vaultMode === "decoy") {2572    throw new Error("deduplicate disabled in decoy mode");2573  }25742575  const best = new Map<string, VaultEntry>();2576  for (const e of entries.filter((en) => !en.deletedAt)) {2577    const key = entryDupeKey(e);2578    const existing = best.get(key);2579    if (!existing) {2580      best.set(key, e);2581    } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2582      best.set(key, e);2583    }2584  }25852586  const keepIds = new Set(Array.from(best.values()).map((e) => e.id));2587  let removed = 0;2588  entries = entries.map((e) => {2589    if (!e.deletedAt && !keepIds.has(e.id)) {2590      removed++;2591      return { ...e, deletedAt: monotonicEntryTimestamp(e.modifiedAt) };2592    }2593    return e;2594  });25952596  if (removed > 0) await persistEntries();2597  return removed;2598}25992600// ---------------------------------------------------------------------------2601// Vault history — snapshot BEFORE every vault write so the saved blob is2602// what is about to be lost, not what was just written. Capped at 5. The2603// stored blobs are AES-256-GCM ciphertext under the master password, so2604// history adds zero security surface.2605// ---------------------------------------------------------------------------26062607const HISTORY_KEY = "peach_vault_history";2608const HISTORY_MAX = 5;26092610// PCH-01-023: coarsen a live-entry count into a low-resolution bucket so the2611// plaintext snapshot field cannot reveal exact vault size or single-entry change2612// deltas. Buckets widen as the vault grows so absolute leakage stays roughly2613// proportional rather than exact.2614function bucketEntryCount(n: number): number {2615  if (n <= 0) return 0;2616  if (n <= 10) return 10;2617  if (n <= 25) return 25;2618  if (n <= 50) return 50;2619  if (n <= 100) return 100;2620  if (n <= 250) return 250;2621  if (n <= 500) return 500;2622  return Math.ceil(n / 500) * 500;2623}26242625/**2626 * Snapshot the CURRENT on-disk vault state into history. Call this BEFORE2627 * overwriting peach_vault_a so the saved blob captures the about-to-be-lost2628 * state. Identical-to-most-recent blobs are skipped to avoid filling history2629 * with no-op writes.2630 */2631export async function takeVaultSnapshot(2632  reason: VaultSnapshot["reason"],2633): Promise<void> {2634  try {2635    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);2636    const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];2637    const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];26382639    // Nothing to snapshot if the real slot doesn't exist yet (fresh install,2640    // pre-createVault). createVault skips snapshots intentionally — there is2641    // no prior state to preserve.2642    if (!slotA) return;26432644    const vault_a = JSON.stringify(slotA);2645    const vault_b = JSON.stringify(slotB ?? slotA);26462647    // Best-effort entry count: only meaningful when the in-memory state is2648    // unlocked AND in real mode. Decoy mode would leak the decoy entry2649    // count; locked mode has no entries to count. Both fall through to null.2650    // PCH-01-023: store a coarse bucket, not the exact count — chrome.storage2651    // .local sits next to the AES-GCM blobs in plaintext, so an exact count would2652    // leak vault size and per-write deltas (the metadata padding hides this).2653    let entryCount: number | null = null;2654    if (derivedKey && vaultMode === "real") {2655      try {2656        entryCount = bucketEntryCount(entries.filter((e) => !e.deletedAt).length);2657      } catch {2658        entryCount = null;2659      }2660    }26612662    const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];2663    const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)2664      ? existingRaw2665      : { snapshots: [] };26662667    // Deduplication: if the most recent snapshot has byte-identical blobs,2668    // skip — saves the same vault N times in a row would otherwise burn the2669    // entire history window with no recovery value.2670    const latest = history.snapshots[0];2671    if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {2672      return;2673    }26742675    const snapshot: VaultSnapshot = {2676      id: crypto.randomUUID(),2677      savedAt: Date.now(),2678      reason,2679      vault_a,2680      vault_b,2681      entryCount,2682    };26832684    history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);2685    await chrome.storage.local.set({ [HISTORY_KEY]: history });2686  } catch (err) {2687    // Non-fatal — history must never block a save. A failed snapshot just2688    // means the user loses one rung of the safety ladder for this write.2689    // M4/QUA-006: log so the failure is visible; if it looks like a quota2690    // problem, notify the popup so the user can prune history themselves.2691    console.warn('[Peach] takeVaultSnapshot failed:', err);2692    if (String(err).includes('QUOTA') || String(err).includes('quota')) {2693      try {2694        await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });2695      } catch {2696        // popup may be closed; surfaced via console.warn above2697      }2698    }2699  }2700}27012702/** Wipe all vault history. Called by Panic / DESTROY_VAULT. */2703export async function clearVaultHistory(): Promise<void> {2704  try {2705    await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });2706  } catch {2707    // Non-fatal — DESTROY_VAULT also runs storage.local.clear().2708  }2709}27102711/** Read all snapshots, newest first, for the Settings vault history view. */2712export async function getVaultHistory(): Promise<VaultSnapshot[]> {2713  const raw = await chrome.storage.local.get(HISTORY_KEY);2714  const history = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];2715  if (!history || !Array.isArray(history.snapshots)) return [];2716  return history.snapshots;2717}27182719/**2720 * Replace the on-disk vault with the chosen snapshot's blobs and lock the2721 * vault. The current state is itself snapshotted with reason 'restore' first2722 * so the restore is reversible. After this returns, the user must unlock2723 * with the password that matches the restored blob.2724 */2725export async function restoreVaultSnapshot(2726  snapshotId: string,2727): Promise<{ ok: true } | { ok: false; error: string }> {2728  const history = await getVaultHistory();2729  const snapshot = history.find((s) => s.id === snapshotId);2730  if (!snapshot) return { ok: false, error: "snapshot_not_found" };27312732  // Snapshot the about-to-be-replaced current state so the restore is2733  // reversible. takeVaultSnapshot is no-op when the most recent entry is2734  // byte-identical, so a restore-of-a-restore stays clean.2735  await takeVaultSnapshot("restore");27362737  let restoredA: StoredVault;2738  let restoredB: StoredVault;2739  try {2740    restoredA = JSON.parse(snapshot.vault_a) as StoredVault;2741    restoredB = JSON.parse(snapshot.vault_b) as StoredVault;2742  } catch {2743    return { ok: false, error: "snapshot_corrupt" };2744  }27452746  await writeSlot(SLOT_A, restoredA);2747  await writeSlot(SLOT_B, restoredB);2748  await stampLocalVaultMutation();27492750  // Lock so the user must prove they can decrypt the restored blob. If they2751  // restored a pre-password-change snapshot they discover it immediately at2752  // the lock screen rather than silently holding an inaccessible vault.2753  lock();27542755  return { ok: true };2756}27572758/**2759 * Rotate the vault's sync identity by generating a FRESH ROOT KEY and2760 * re-wrapping everything under it (MV-8). Because every sync credential —2761 * vault_id, the Noise XX static keypair, the Ed25519 manifest signing key,2762 * and the per-entry envelope keys — derives from the root key, rotation2763 * makes a lost/stolen device's retained key material useless. All paired2764 * devices must re-pair afterwards.2765 *2766 * CONSEQUENCE THE UI MUST SURFACE: the 12 recovery words also derive from2767 * the root key, so rotation INVALIDATES the old recovery phrase. The flow2768 * sets peach_recovery_pending so the popup re-presents the new words for2769 * confirmation, same as the migrateToRecovery rotate path.2770 */2771export async function rotateSyncIdentity(): Promise<{ ok: boolean; error?: string }> {2772  if (!derivedKey || vaultMode !== "real") {2773    return { ok: false, error: "vault_locked" };2774  }2775  const slotA = await loadSlot(SLOT_A);2776  if (!slotA) return { ok: false, error: "missing_slot_a" };27772778  // 1. Fresh root key + recovery escrow (new words).2779  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =2780    await generateAndWrapRootKey();27812782  // 2. Re-wrap the new root key under the current password-derived key.2783  const newRootKey = unhex(rawRootKey);2784  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, newRootKey);27852786  // 3. Snapshot, then single atomic slot write — both escrow wrappings of2787  //    the new root key land together (same transactional rule as2788  //    changePassword). Entries are untouched: they are sealed under the2789  //    password-derived key, not the root key.2790  await takeVaultSnapshot("local_save");2791  const nextSlotA: StoredVault = {2792    ...slotA,2793    recovery_salt: recoverySalt,2794    recovery_wrapped_root_key: wrappedRootKey,2795    recovery_nonce: wrappedNonce,2796    recovery_tag: wrappedTag,2797    ...pwRoot,2798  };2799  await writeSlot(SLOT_A, nextSlotA);28002801  // 4. Swap in memory only after disk committed.2802  if (rootKey) zeroKey(rootKey);2803  rootKey = newRootKey;28042805  // 5. Old peers' identities derive from the dead root key — drop them all.2806  const { clearPairedDevices } = await import("./paired-devices");2807  await clearPairedDevices();28082809  // 6. Force re-presentation of the NEW recovery words on next popup view.2810  await setRecoveryConfirmPending(); // same flag the create-vault flow uses28112812  await stampLocalVaultMutation();2813  return { ok: true };2814}28152816/**2817 * Change the master password. Re-encrypts slot A with a fresh salt + new2818 * derived key. Slot B (duress or noise) is left untouched when duress is2819 * configured — it uses an independent key derived from the duress password —2820 * and regenerated as noise when duress is not configured.2821 */2822export async function changePassword(2823  currentPassword: string,2824  newPassword: string2825): Promise<boolean> {2826  if (!derivedKey || vaultMode !== "real") return false;28272828  // Verify current password before allowing any change2829  const valid = await verifyMainPassword(currentPassword);2830  if (!valid) return false;28312832  const slotA = await loadSlot(SLOT_A);2833  if (!slotA) return false;2834  if (!rootKey) return false;28352836  // Derive fresh key from new password + new random salt2837  const newSalt = generateSalt();2838  const newKey = await deriveKey(newPassword, newSalt);28392840  // Re-encrypt the in-memory entries with the new key2841  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);2842  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");28432844  // Pre-wrap root key under the new derived key. Recovery fields wrap rootKey2845  // under recovery words and remain untouched — recovery phrase keeps working2846  // across password changes (H4/COR-002).2847  const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);28482849  const finalSlotA: StoredVault = {2850    ...slotA,2851    salt: hex(newSalt),2852    nonce,2853    ciphertext,2854    tag,2855    ...pwRoot,2856  };28572858  // Snapshot the OLD-key blob before overwriting it. If the user later2859  // restores from this snapshot they will need the OLD password — the2860  // post-restore lock surfaces that immediately.2861  await takeVaultSnapshot("local_save");28622863  // Single atomic write: ciphertext, salt, and pw_root_* fields all land in2864  // one storage transaction. An SW kill before this point leaves the old2865  // slot intact; after this point everything tied to the new password is2866  // already on disk together (M6/COR-004).2867  await writeSlot(SLOT_A, finalSlotA);28682869  // Swap the in-memory key synchronously before any further await. If we2870  // threw between the Slot A write and this swap, the next persistEntries()2871  // would overwrite Slot A with old-key ciphertext, locking the user out.2872  zeroKey(derivedKey);2873  derivedKey = newKey;28742875  // PCH-01-008: the MV3 session escrow still holds the OLD key. Without this,2876  // the next service-worker restore decrypts the new-key Slot A with the stale2877  // key, fails tryDecryptSlotResult, and silently drops the user to a lock2878  // screen. Re-escrow the new key so restore survives a password change.2879  void saveSessionKey(newKey, "real");28802881  // Regenerate noise for slot B when duress is not in use. Runs after the2882  // key swap so a failure here is a disposable noise regeneration, not a2883  // lockout.2884  if (!duressConfigured) {2885    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));2886  }2887  await stampLocalVaultMutation();28882889  return true;2890}