vault.ts

111.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 { computeVaultId } from "../shared/sync-identity";16// Static, not `await import()`: runtime import() throws in an MV3 service17// worker. Neither module imports vault.ts back, so there is no cycle to break.18import { triggerSyncIfReachable } from "./sync-trigger";19import { clearPairedDevices } from "./paired-devices";20import {21  rootKeyToWords,22  wordsToRootKeyMaterial,23  deriveRecoveryKey,24} from "../shared/recovery-words";25import type {26  AccentColorName,27  Canary,28  LegacyVaultEntry,29  ManualSummonRecord,30  PasskeyData,31  SavedIdentity,32  StoredVault,33  VaultEntry,34  VaultHistory,35  VaultSnapshot,36} from "../shared/types";37import { decrypt, encrypt, zeroKey } from "./aes";38import { clearAutoLock, touchAutoLock } from "./alarms";39import { setRecoveryConfirmPending } from "./recovery-pending";4041type EntryDraft = Omit<42  VaultEntry,43  "id" | "createdAt" | "modifiedAt" | "deletedAt"44>;4546// Slot-neutral storage keys (v1.4.24+). Both slots always exist; slot B47// either holds the decoy vault (when duress is configured) or random noise48// that looks identical at rest. No external indicator is stored — duress49// configuration is recorded only inside the encrypted payload of slot A.50const SLOT_A = "peach_vault_a";51const SLOT_B = "peach_vault_b";5253// Legacy keys, migrated away on first access.54const LEGACY_MAIN = "peach_vault";55const LEGACY_DECOY = "peach_decoy_vault";56const LEGACY_DURESS_FLAG = "peach_duress";5758// Plaintext is padded to the next multiple of this size before encryption.59// This coarsens ciphertext-length leakage into 1 KiB buckets.60const PAD_BLOCK = 1024;6162// How many past passwords to retain per entry. Generous enough to be useful as63// a recovery aid while bounding the secret material we hold (and the ciphertext64// growth) for an entry whose password is rotated frequently.65const PASSWORD_HISTORY_MAX = 50;6667// When duress is configured, BOTH slots are padded to this fixed ceiling so68// their ciphertext lengths are identical and cannot reveal that a hidden decoy69// vault exists (audit MEDIUM — plausible-deniability leak). 256 KiB comfortably70// holds a very large vault (thousands of entries incl. passkeys). The decoy71// slot can't be re-encrypted on every real-vault save (the real session has no72// decoy key), so a fixed ceiling — rather than size-matching on each write — is73// what keeps the two slots equal. A real vault whose plaintext exceeds this74// would grow past the ceiling and re-expose the bit; that is an extreme,75// documented edge well beyond normal use.76const DURESS_SLOT_SIZE = 262_144;7778let derivedKey: Uint8Array | null = null;79// 32-byte random root key, separate from the derivedKey used for vault encryption.80// The root key is wrapped (encrypted) under the recovery key derived from the81// 12-word phrase. When the user changes their password, only the wrapping changes;82// the root key and recovery words remain stable.83let rootKey: Uint8Array | null = null;84let entries: VaultEntry[] = [];85let domainIndex: Map<string, VaultEntry[]> = new Map();86let vaultMode: "real" | "decoy" = "real";87// Cached post-unlock view of whether the real vault records that duress is88// configured. Only meaningful after a real-mode unlock; for decoy-mode unlock89// this stays false because we never see slot A's plaintext.90let duressConfigured = false;9192let migrationRan = false;9394// Set to a corruption reason during the last unlock() attempt when both slots95// decrypted but failed schema validation. Consumed and cleared by96// consumeLastUnlockFailureReason() so messages.ts can surface vault_corrupted97// distinctly from wrong-password (M7/COR-007).98//99// NOTE: module-level state — if vault.ts is ever moved to a worker context,100// this must be replaced with a structured return value from unlock() or a101// postMessage channel. The signal is invisible across module-instance102// boundaries.103let lastUnlockFailureReason: string | null = null;104105export function consumeLastUnlockFailureReason(): string | null {106  const r = lastUnlockFailureReason;107  lastUnlockFailureReason = null;108  return r;109}110111// ---------------------------------------------------------------------------112// Settings (persisted inside the encrypted vault store as a sidecar key)113// ---------------------------------------------------------------------------114115export type TextSize = "small" | "medium" | "large";116117export interface VaultSettings {118  accentColor?: AccentColorName;119  theme?: "dark" | "light";120  autoLockMinutes?: number;121  clipboardClearSeconds?: number;122  lockOnClose?: boolean;123  breachMonitoring?: boolean;124  passkeyProviderEnabled?: boolean;125  trashRetentionDays?: number;126  manualSummonDomains?: Record<string, ManualSummonRecord>;127  declinedCardFingerprints?: string[];128  /**129   * Text size scale for body copy and entry titles. Stops at "large" by130   * design — XL clips dense screens (Vault, Health) inside the fixed131   * 330×480 popup surface.132   */133  textSize?: TextSize;134  /**135   * When true, all entrance/exit transitions and ambient animations are136   * collapsed to instant. Honoured alongside the user's OS-level137   * `prefers-reduced-motion`.138   */139  reduceMotion?: boolean;140  /**141   * Android-only: when true, the master key is escrowed in AndroidKeyStore142   * and the lock screen offers biometric unlock. Toggled from Settings →143   * Security → Biometrics. Has no effect on desktop builds.144   */145  biometricsEnabled?: boolean;146  /**147   * User overrides for keyboard shortcuts. Keys are ShortcutAction names148   * (see src/shared/shortcuts.ts). Missing actions fall through to149   * DEFAULT_BINDINGS — `getActiveBindings(settings.shortcuts)` is the150   * canonical lookup. Storing only the deltas keeps the vault payload151   * small and lets default updates land for users who never rebind.152   */153  shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;154}155156let settings: VaultSettings = {};157158export function getSettings(): VaultSettings {159  return settings;160}161162export async function ensureSettingsLoaded(): Promise<VaultSettings> {163  await loadSettings();164  return settings;165}166167export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {168  await loadSettings();169  // LV-7: cheap insurance against prototype pollution if a future caller ever170  // feeds parsed external JSON here (native spread keeps __proto__ an own-171  // property today, but Object.assign-style consumers and JSON revivers have172  // been burned before).173  const safe = Object.fromEntries(174    Object.entries(patch).filter(175      ([k]) => !["__proto__", "constructor", "prototype"].includes(k),176    ),177  ) as Partial<VaultSettings>;178  settings = { ...settings, ...safe };179  await persistSettings();180}181182async function persistSettings(): Promise<void> {183  try {184    await chrome.storage.local.set({ peach_settings: settings });185  } catch (err) {186    throw mapStorageError(err);187  }188}189190function mapStorageError(err: unknown): Error {191  const message = err instanceof Error ? err.message : String(err);192  if (/QUOTA_BYTES|quota/i.test(message)) {193    return new Error("STORAGE_QUOTA_EXCEEDED");194  }195  return err instanceof Error ? err : new Error(message);196}197198async function loadSettings(): Promise<void> {199  const result = await chrome.storage.local.get("peach_settings");200  settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};201}202203// Fire-and-forget sync trigger after a committed vault write. A failure here204// must never fail the write that caused it.205function fireSyncTrigger(reason: "vault_change"): void {206  void Promise.resolve()207    .then(() => triggerSyncIfReachable({ reason }))208    .catch(() => {209      /* no sync runner registered, or nothing reachable — non-fatal */210    });211}212213// ---------------------------------------------------------------------------214// HIBP breach check (k-anonymity model)215// ---------------------------------------------------------------------------216217export async function checkBreach(password: string): Promise<number> {218  // HIBP k-anonymity API is keyed on SHA-1 prefixes — this is dictated by219  // the public API, not a security choice. Do not migrate to SHA-256 here.220  const encoder = new TextEncoder();221  const hashBuffer = await crypto.subtle.digest("SHA-1", encoder.encode(password));222  const hashHex = Array.from(new Uint8Array(hashBuffer))223    .map((b) => b.toString(16).padStart(2, "0"))224    .join("")225    .toUpperCase();226227  const prefix = hashHex.slice(0, 5);228  const suffix = hashHex.slice(5);229230  try {231    // PCH-02-007: request HIBP response padding so response length does not232    // reveal how many suffixes a queried prefix returned.233    const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`, {234      headers: { "Add-Padding": "true" },235    });236    if (!res.ok) return 0;237    const text = await res.text();238    const match = text.split("\r\n").find((l) => l.startsWith(suffix));239    return match ? parseInt(match.split(":")[1], 10) : 0;240  } catch {241    return 0; // Network unavailable — don't block242  }243}244245export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {246  const fingerprint = await cardFingerprint(last4, expMonth, expYear);247  await loadSettings();248  settings = {249    ...settings,250    declinedCardFingerprints: [...(settings.declinedCardFingerprints ?? []), fingerprint],251  };252  await persistSettings();253}254255export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {256  await loadSettings();257  const fingerprint = await cardFingerprint(last4, expMonth, expYear);258  return (settings.declinedCardFingerprints ?? []).includes(fingerprint);259}260261async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {262  const encoder = new TextEncoder();263  const buf = await crypto.subtle.digest("SHA-256", encoder.encode(`${last4}|${expMonth}|${expYear}`));264  return Array.from(new Uint8Array(buf).slice(0, 8))265    .map((b) => b.toString(16).padStart(2, "0"))266    .join("");267}268269function hex(buf: Uint8Array): string {270  return Array.from(buf)271    .map((b) => b.toString(16).padStart(2, "0"))272    .join("");273}274275function unhex(s: string): Uint8Array {276  const out = new Uint8Array(s.length / 2);277  for (let i = 0; i < s.length; i += 2) {278    out[i / 2] = parseInt(s.slice(i, i + 2), 16);279  }280  return out;281}282283// ---------------------------------------------------------------------------284// Root key generation and recovery word wrapping285// ---------------------------------------------------------------------------286287/**288 * Generate a random 32-byte root key and wrap it (AES-256-GCM) under a key289 * derived from the recovery word material via HKDF-SHA256. The wrapped blob290 * fields are stored in slot A alongside the password-wrapped ciphertext. The291 * root key itself is kept in memory for the session so getRecoveryWords() can292 * encode it without re-deriving.293 *294 * SECURITY MODEL (PCH-01-005): the recovery KEK is derived from the 12-word295 * material, which encodes only rootKey[0..16] (recovery-words.ts). The KEK is thus296 * derived from a PREFIX of the very plaintext it wraps, and effective recovery297 * security is 128-bit (standard for a 12-word phrase), NOT 256-bit. This is safe —298 * unwrapping requires the words, and the GCM ciphertext leaks nothing without them —299 * but it is intentional, not an oversight. A future escrow version wanting 256-bit300 * recovery must derive the words from INDEPENDENT entropy, not from the root key.301 */302async function generateAndWrapRootKey(): Promise<{303  rawRootKey: string; // hex of the plaintext root key — caller stores in rootKey304  recoverySalt: string;305  wrappedRootKey: string;306  wrappedNonce: string;307  wrappedTag: string;308}> {309  const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));310311  // Derive the recovery key from the BIP39 words encoding of the root key.312  const words = await rootKeyToWords(rootKeyBytes);313  const wordMaterial = await wordsToRootKeyMaterial(words);314  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));315  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);316317  // Wrap the root key with the recovery key using AES-256-GCM directly.318  // We hex-encode rootKeyBytes so the plaintext is always valid UTF-8.319  const nonce = crypto.getRandomValues(new Uint8Array(12));320  const encoded = new TextEncoder().encode(hex(rootKeyBytes));321  const raw = await crypto.subtle.encrypt(322    {323      name: "AES-GCM",324      iv: nonce,325      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,326      tagLength: 128,327    },328    recoveryKey,329    encoded330  );331  // WebCrypto returns ciphertext || auth tag concatenated; split them.332  const rawU8 = new Uint8Array(raw);333  const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));334  const tag = hex(rawU8.slice(rawU8.length - 16));335336  return {337    rawRootKey: hex(rootKeyBytes),338    recoverySalt: hex(recoverySalt),339    wrappedRootKey: ciphertext,340    wrappedNonce: hex(nonce),341    wrappedTag: tag,342  };343}344345async function wrapExistingRootKeyForRecovery(rootKeyBytes: Uint8Array): Promise<{346  recoverySalt: string;347  wrappedRootKey: string;348  wrappedNonce: string;349  wrappedTag: string;350}> {351  if (rootKeyBytes.length !== 32) {352    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");353  }354355  const words = await rootKeyToWords(rootKeyBytes);356  const wordMaterial = await wordsToRootKeyMaterial(words);357  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));358  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);359  const nonce = crypto.getRandomValues(new Uint8Array(12));360  const encoded = new TextEncoder().encode(hex(rootKeyBytes));361  const raw = await crypto.subtle.encrypt(362    {363      name: "AES-GCM",364      iv: nonce,365      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,366      tagLength: 128,367    },368    recoveryKey,369    encoded,370  );371  const rawU8 = new Uint8Array(raw);372  return {373    recoverySalt: hex(recoverySalt),374    wrappedRootKey: hex(rawU8.slice(0, rawU8.length - 16)),375    wrappedNonce: hex(nonce),376    wrappedTag: hex(rawU8.slice(rawU8.length - 16)),377  };378}379380/**381 * Unwrap the root key using recovery words. Called during recovery flow when382 * the user provides their 12-word phrase and a new password.383 * Exported for use by the RECOVER_WITH_WORDS message handler.384 */385export async function unwrapRootKeyForRecovery(386  wrappedRootKey: string,387  wrappedNonce: string,388  wrappedTag: string,389  recoverySaltHex: string,390  words: string[]391): Promise<void> {392  const wordMaterial = await wordsToRootKeyMaterial(words);393  const recoverySalt = unhex(recoverySaltHex);394  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);395396  // Decrypt and cache the root key. The root key bytes were hex-encoded before397  // encryption so the ciphertext is valid UTF-8. We inline the AES-GCM decrypt398  // here to avoid passing a CryptoKey to the string-based encrypt/decrypt helpers.399  // Each component is stored separately in the vault slot; decode them individually400  // so the nonce is always exactly the 12 bytes from wrappedNonce.401  const nonceRaw = unhex(wrappedNonce);402  const ciphertextRaw = unhex(wrappedRootKey);403  const tagRaw = unhex(wrappedTag);404  // Combine ciphertext and tag for AES-GCM (expects ciphertext||tag).405  // Use explicit ArrayBuffer allocations to satisfy TS BufferSource constraints.406  const nonceU8 = nonceRaw as unknown as Uint8Array<ArrayBuffer>;407  const combined = new Uint8Array(ciphertextRaw.length + tagRaw.length);408  combined.set(ciphertextRaw, 0);409  combined.set(tagRaw, ciphertextRaw.length);410  const raw = await crypto.subtle.decrypt(411    { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },412    recoveryKey,413    combined414  );415  const decryptedHex = new TextDecoder().decode(raw);416  rootKey = unhex(decryptedHex);417}418419/**420 * Re-wrap the cached root key under a new derived key (from the user's new421 * password). Called after password change and after recovery re-key so the422 * same recovery words continue to work with the updated password — and so423 * subsequent unlocks can rehydrate rootKey via deriveRootKeyFromDerivedKey.424 *425 * recovery_* fields are intentionally not touched: those wrap rootKey under426 * the recovery words, which do not change when the password changes.427 */428export async function rewrapRootKeyForPassword(429  newDerivedKey: Uint8Array,430  _newSalt: Uint8Array431): Promise<void> {432  if (!rootKey) throw new Error("root key not set");433  const slotA = await loadSlot(SLOT_A);434  if (!slotA) throw new Error("missing slot A");435  const pwRoot = await wrapRootKeyForDerivedKey(newDerivedKey, rootKey);436  await writeSlot(SLOT_A, { ...slotA, ...pwRoot });437}438439/**440 * Change the vault encryption to a new derived key (already derived from441 * the user's new password). Used by RECOVER_WITH_WORDS and changePassword.442 * Caller is responsible for key swap and snapshot.443 */444async function reencryptVaultForNewKey(445  newKey: Uint8Array,446  slotA: StoredVault447): Promise<void> {448  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);449  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");450  await writeSlot(SLOT_A, {451    ...slotA,452    nonce,453    ciphertext,454    tag,455  });456}457458/**459 * Full password change with an already-derived key (used after recovery).460 * Unlike changePassword(), this skips re-verification of current password461 * since recovery flow has already validated the user's identity via words.462 */463export async function changePasswordWithNewKey(464  newSalt: Uint8Array,465  newKey: Uint8Array466): Promise<void> {467  const slotA = await loadSlot(SLOT_A);468  if (!slotA) throw new Error("missing slot A");469  // reencryptVaultForNewKey must receive the updated salt so that subsequent470  // UNLOCK calls with the new password can re-derive the correct key.471  await reencryptVaultForNewKey(newKey, { ...slotA, salt: hex(newSalt) });472  if (derivedKey) zeroKey(derivedKey);473  derivedKey = newKey;474  // PCH-01-008: re-escrow the new key (see changePassword). The recovery flow475  // reaches this path, so a post-recovery SW restart would otherwise lock out476  // a user who just reset their password.477  void saveSessionKey(newKey, "real");478  // Refresh pw_root_* under the new key so deriveRootKeyFromDerivedKey works479  // on the next unlock (H2/COR-006). If rootKey is missing — recovery flow480  // should have populated it — fall back silently rather than blowing up the481  // recovery path; migrateToRecovery will rehydrate on the next unlock.482  if (rootKey) {483    const slotAfter = await loadSlot(SLOT_A);484    if (slotAfter) {485      const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);486      await writeSlot(SLOT_A, { ...slotAfter, ...pwRoot });487    }488  }489  if (!duressConfigured) {490    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));491  }492  await stampLocalVaultMutation();493}494495// ---------------------------------------------------------------------------496// Salt generation --- exported so the RECOVER_WITH_WORDS handler can derive497// a new key after password reset without re-importing the crypto module.498// ---------------------------------------------------------------------------499500export { deriveKey, generateSalt };501502export async function loadSlotA(): Promise<StoredVault | null> {503  return loadSlot(SLOT_A);504}505506/**507 * Recover the session root key by AES-GCM-decrypting the pw_root_* fields508 * (a second wrapping of the root key under the password-derived key). This509 * is what makes GET_RECOVERY_WORDS work across lock/unlock cycles without510 * the user re-entering their recovery phrase: the same root key bytes —511 * and therefore the same 12 words — survive every unlock.512 *513 * Returns null when the pw_root fields are absent (pre-v2.12 vault that514 * hasn't been migrated yet) or when decryption fails (wrong derived key,515 * tampered ciphertext). On null the caller should fall through to516 * migrateToRecovery() to populate the fields.517 */518async function deriveRootKeyFromDerivedKey(519  derivedKeyBytes: Uint8Array,520  slotA: StoredVault,521): Promise<Uint8Array | null> {522  if (!slotA.pw_root_ciphertext || !slotA.pw_root_nonce || !slotA.pw_root_tag) {523    return null;524  }525  try {526    const rootHex = await decrypt(527      derivedKeyBytes,528      slotA.pw_root_nonce,529      slotA.pw_root_ciphertext,530      slotA.pw_root_tag,531      "pw_root_v1",532    );533    return unhex(rootHex);534  } catch {535    return null;536  }537}538539// AES-GCM-wrap rootKey under derivedKey for the pw_root_* fields. Returns the540// hex-encoded ciphertext/nonce/tag triple ready to embed in StoredVault.541async function wrapRootKeyForDerivedKey(542  derivedKeyBytes: Uint8Array,543  rootKeyBytes: Uint8Array,544): Promise<{ pw_root_ciphertext: string; pw_root_nonce: string; pw_root_tag: string }> {545  const { nonce, ciphertext, tag } = await encrypt(derivedKeyBytes, hex(rootKeyBytes), "pw_root_v1");546  return {547    pw_root_ciphertext: ciphertext,548    pw_root_nonce: nonce,549    pw_root_tag: tag,550  };551}552553/**554 * For vaults created before v2.12 (no recovery_salt/recovery_wrapped_root_key),555 * generate the root key, wrap it under the recovery words, and persist the556 * recovery escrow into slot A. The caller must show the recovery words to the557 * user before calling this — once called, those words are the vault's recovery558 * path. This runs once, on the first unlock of an upgraded vault.559 */560export async function migrateToRecovery(): Promise<void> {561  if (!derivedKey || vaultMode !== "real") {562    throw new Error("vault must be unlocked in real mode");563  }564  const slotA = await loadSlot(SLOT_A);565  if (!slotA) throw new Error("missing slot A");566  const hasRecoveryEscrow =567    !!slotA.recovery_salt && !!slotA.recovery_wrapped_root_key;568  const hasPwRoot = !!slotA.pw_root_ciphertext && !!slotA.pw_root_nonce;569  if (hasRecoveryEscrow && hasPwRoot) return; // already done570571  // If recovery escrow already exists but pw_root doesn't, we cannot recover572  // the original rootKey without the user's words. The least-surprising path573  // is to rotate to a fresh root key — the user's old recovery words become574  // invalid but we surface peach_recovery_pending so the popup re-presents575  // the words. The unlock-path callers all set that flag.576  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =577    await generateAndWrapRootKey();578  rootKey = unhex(rawRootKey);579580  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);581  const nextSlotA: StoredVault = {582    ...slotA,583    recovery_salt: recoverySalt,584    recovery_wrapped_root_key: wrappedRootKey,585    recovery_nonce: wrappedNonce,586    recovery_tag: wrappedTag,587    ...pwRoot,588  };589  await writeSlot(SLOT_A, nextSlotA);590  await stampLocalVaultMutation();591}592593/**594 * Returns the 12 recovery words for the current session's root key.595 * Must be called while the vault is unlocked. Throws if recovery has not596 * been set up (pre-v2.12 vault that hasn't migrated yet).597 */598export async function getRecoveryWords(): Promise<string[]> {599  if (!rootKey) {600    throw new Error("recovery not set up — vault may need migration");601  }602  return rootKeyToWords(rootKey);603}604605async function loadSlot(key: string): Promise<StoredVault | null> {606  const result = await chrome.storage.local.get(key);607  return (result as Record<string, StoredVault | undefined>)[key] ?? null;608}609610async function writeSlot(key: string, vault: StoredVault): Promise<void> {611  try {612    await chrome.storage.local.set({ [key]: vault });613  } catch (err) {614    throw mapStorageError(err);615  }616}617618async function commitCreatedVaultSlots(slotA: StoredVault, slotB: StoredVault): Promise<void> {619  const raw = await chrome.storage.local.get("peach_last_modified_at");620  const previous = Number(621    (raw as Record<string, unknown>).peach_last_modified_at,622  );623  const next = Math.max(624    Date.now(),625    Number.isFinite(previous) ? previous + 1 : 0,626  );627  try {628    await chrome.storage.local.set({629      [SLOT_A]: slotA,630      [SLOT_B]: slotB,631      peach_last_modified_at: String(next),632    });633  } catch (err) {634    throw mapStorageError(err);635  }636}637638// Monotonic clock for per-entry modifiedAt / deletedAt timestamps. Guards the639// sync layer's last-write-wins merge against wall-clock regressions (NTP step,640// manual clock change, DST glitch): a backwards Date.now() must never produce641// an entry timestamp that's <= the entry's existing modifiedAt, or a genuine642// local edit would lose to a stale remote copy. The returned value is always643// strictly greater than both the entry's current modifiedAt and the previous644// call's result (SEV-2-E).645let lastEntryTimestamp = 0;646function monotonicEntryTimestamp(currentModifiedAt?: number): number {647  const base = Math.max(648    Date.now(),649    (currentModifiedAt ?? 0) + 1,650    lastEntryTimestamp + 1,651  );652  lastEntryTimestamp = base;653  return base;654}655656async function stampLocalVaultMutation(): Promise<void> {657  const raw = await chrome.storage.local.get("peach_last_modified_at");658  const previous = Number(659    (raw as Record<string, unknown>).peach_last_modified_at,660  );661  const next = Math.max(662    Date.now(),663    Number.isFinite(previous) ? previous + 1 : 0,664  );665  await chrome.storage.local.set({666    peach_last_modified_at: String(next),667  });668}669670/**671 * One-shot migration from the pre-A-2 schema (peach_vault + peach_decoy_vault672 * + peach_duress flag) to the slot-neutral schema (peach_vault_a +673 * peach_vault_b). Runs at most once per session; safe to call repeatedly.674 */675async function ensureMigrated(): Promise<void> {676  if (migrationRan) return;677  migrationRan = true;678679  const keys = [LEGACY_MAIN, LEGACY_DECOY, LEGACY_DURESS_FLAG, SLOT_A, SLOT_B];680  const raw = await chrome.storage.local.get(keys);681  const slotAExists = raw[SLOT_A] !== undefined;682  const slotBExists = raw[SLOT_B] !== undefined;683  const legacyMain = raw[LEGACY_MAIN] as StoredVault | undefined;684  const legacyDecoy = raw[LEGACY_DECOY] as StoredVault | undefined;685686  // Fresh install with nothing in storage — nothing to do; createVault() sets up both slots.687  if (!slotAExists && !legacyMain) return;688689  // Already migrated.690  if (slotAExists && slotBExists && !legacyMain && !legacyDecoy) return;691692  let didMigrate = false;693  if (legacyMain && !slotAExists) {694    await writeSlot(SLOT_A, legacyMain);695    didMigrate = true;696  }697698  // If slot B isn't set, populate it: use legacy decoy when present, else noise.699  if (!slotBExists) {700    const target = (legacyMain ?? raw[SLOT_A]) as StoredVault | undefined;701    if (legacyDecoy) {702      await writeSlot(SLOT_B, legacyDecoy);703      didMigrate = true;704    } else if (target) {705      await writeSlot(SLOT_B, generateNoiseBlob(target.ciphertext.length / 2));706      didMigrate = true;707    }708  }709710  const toRemove: string[] = [];711  if (legacyMain) toRemove.push(LEGACY_MAIN);712  if (legacyDecoy) toRemove.push(LEGACY_DECOY);713  if (raw[LEGACY_DURESS_FLAG] !== undefined) toRemove.push(LEGACY_DURESS_FLAG);714  if (toRemove.length > 0) {715    await chrome.storage.local.remove(toRemove);716    didMigrate = true;717  }718  if (didMigrate) {719    await stampLocalVaultMutation();720  }721}722723// ---------------------------------------------------------------------------724// Padding + noise helpers725// ---------------------------------------------------------------------------726727/**728 * Pads the plaintext string with trailing spaces so that the encoded byte729 * length is a multiple of PAD_BLOCK. JSON.parse tolerates trailing730 * whitespace after a complete document, so the padding is transparent on731 * decode. Ciphertext length equals plaintext length plus a 16-byte tag.732 */733function padPlaintext(json: string, minBytes = 0): string {734  const encoded = new TextEncoder().encode(json);735  const bucket = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);736  // minBytes lets the duress path force a fixed ceiling so both slots match.737  const target = Math.max(bucket, minBytes);738  const padLen = target - encoded.length;739  return json + " ".repeat(padLen);740}741742/**743 * Produces a StoredVault-shaped record filled with CSPRNG bytes. The744 * ciphertext length matches the given byte count. Because GCM ciphertext is745 * pseudo-random, this blob is indistinguishable at rest from a real746 * encrypted vault without the key.747 *748 * crypto.getRandomValues() caps each call at 65536 bytes (the Web Crypto749 * spec hard limit). Chunk the fill so vaults larger than that — common once750 * the user has dozens of entries or any passkey — don't throw.751 */752const CSPRNG_CHUNK = 65_536;753754function fillRandom(buf: Uint8Array): Uint8Array {755  for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {756    const end = Math.min(offset + CSPRNG_CHUNK, buf.length);757    const chunk = new Uint8Array(end - offset);758    crypto.getRandomValues(chunk);759    buf.set(chunk, offset);760  }761  return buf;762}763764function generateNoiseBlob(ciphertextBytes: number): StoredVault {765  const salt = crypto.getRandomValues(new Uint8Array(16));766  const nonce = crypto.getRandomValues(new Uint8Array(12));767  const cipher = fillRandom(new Uint8Array(ciphertextBytes));768  const tag = crypto.getRandomValues(new Uint8Array(16));769  return {770    version: 1,771    salt: hex(salt),772    nonce: hex(nonce),773    ciphertext: hex(cipher),774    tag: hex(tag),775  };776}777778// ---------------------------------------------------------------------------779// Encrypted plaintext envelope780// ---------------------------------------------------------------------------781782type VaultPayload = {783  entries: VaultEntry[];784  duressConfigured?: boolean;785};786787type DecryptedPayload = {788  entries: VaultEntry[];789  duressConfigured: boolean;790  /**791   * True when at least one entry in the on-disk payload had a legacy shape792   * (pre-v2.11.0 passkey type/flat fields, or pre-A-2 created/updated keys)793   * and got rewritten by normalizeEntry. The unlock path uses this to794   * persist the new shape immediately — without it, the migration would795   * re-run on every unlock and old shape never disappears from disk.796   */797  migratedFromLegacy: boolean;798};799800function encodePayload(entries: VaultEntry[], duress: boolean, minBytes = 0): string {801  const envelope: VaultPayload = { entries, duressConfigured: duress };802  return padPlaintext(JSON.stringify(envelope), minBytes);803}804805function rawNeedsMigration(raw: VaultEntry | LegacyVaultEntry): boolean {806  if ("created" in raw || "updated" in raw) return true;807  const flat = raw as Partial<VaultEntry>;808  if (flat.type === "passkey") return true;809  // Flat rpId without a passkey sub-object means pre-v2.11.0 schema.810  if (flat.rpId !== undefined && flat.passkey === undefined) return true;811  return false;812}813814function decodePayload(plain: string): DecryptedPayload {815  const parsed = JSON.parse(plain) as816    | Array<VaultEntry | LegacyVaultEntry>817    | VaultPayload;818819  const rawEntries = Array.isArray(parsed) ? parsed : parsed.entries ?? [];820  const flatMigrationNeeded = rawEntries.some(rawNeedsMigration);821822  const normalized = rawEntries.map(normalizeEntry);823  const { merged } = mergePasskeyOnlyIntoLogins(normalized);824825  if (Array.isArray(parsed)) {826    return {827      entries: normalized,828      duressConfigured: false,829      migratedFromLegacy: true, // pre-A-2 array shape always needs save830    };831  }832833  return {834    entries: normalized,835    duressConfigured: parsed.duressConfigured === true,836    migratedFromLegacy: flatMigrationNeeded || merged,837  };838}839840/**841 * One-time consolidation pass run alongside the legacy passkey migration.842 *843 * Pre-v2.11.0 the Chrome passkey path always created a fresh `type:"passkey"`844 * entry per registration — so users who tested registration multiple times845 * accumulated several passkey-bearing entries for the same RP, and the846 * migration to the unified shape carried that duplication forward. This847 * pass collapses the duplicates:848 *849 *   1. Group passkey-bearing (and not deleted) entries by `passkey.rpId`.850 *   2. Within each group, the most recently-active credential wins (prefer851 *      lastUsedAt, fall back to passkey.createdAt, fall back to modifiedAt).852 *   3. If a NON-passkey login entry exists for that RP (matched by url or853 *      additionalUrls hostname), attach the winning passkey to it and854 *      soft-delete every passkey-bearing entry in the group.855 *   4. Otherwise, soft-delete every loser in the group, keeping the winner856 *      as a passkey-only entry.857 *858 * Soft delete (deletedAt) rather than splice — the trash flow keeps the859 * record around for retention and the user can restore if the heuristic860 * picked wrong. The `merged` flag goes back to decodePayload so the861 * unlock path persists the consolidated shape immediately.862 */863function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {864  let merged = false;865  const now = Date.now();866867  const candidates = entries.filter((e) => !e.deletedAt && e.passkey);868  const byRpId = new Map<string, VaultEntry[]>();869  for (const e of candidates) {870    const rpId = e.passkey!.rpId;871    const list = byRpId.get(rpId);872    if (list) list.push(e);873    else byRpId.set(rpId, [e]);874  }875876  for (const [rpId, group] of byRpId) {877    if (group.length === 0) continue;878    group.sort((a, b) => {879      const aT =880        a.passkey!.lastUsedAt ?? a.passkey!.createdAt ?? a.modifiedAt ?? a.createdAt;881      const bT =882        b.passkey!.lastUsedAt ?? b.passkey!.createdAt ?? b.modifiedAt ?? b.createdAt;883      return bT - aT;884    });885    const winner = group[0]!;886887    // Look for a NON-passkey login entry matching this RP. Use the URL888    // hostname rather than a substring search so a "login.foo.com" entry889    // doesn't accidentally absorb a passkey for "foo.com".890    const loginTarget = entries.find((e) => {891      if (e.deletedAt || e.passkey || e.type !== "login") return false;892      if (e.url && extractDomain(e.url) === rpId) return true;893      for (const extra of e.additionalUrls ?? []) {894        if (extractDomain(extra) === rpId) return true;895      }896      return false;897    });898899    if (loginTarget) {900      loginTarget.passkey = winner.passkey;901      loginTarget.modifiedAt = now;902      for (const dup of group) {903        if (!dup.deletedAt) {904          dup.deletedAt = now;905          dup.modifiedAt = now;906        }907      }908      merged = true;909    } else if (group.length > 1) {910      for (let i = 1; i < group.length; i += 1) {911        const dup = group[i]!;912        if (!dup.deletedAt) {913          dup.deletedAt = now;914          dup.modifiedAt = now;915        }916      }917      merged = true;918    }919  }920921  return { merged };922}923924// Validates that a `StoredVault` record on disk has the field shape we expect925// before treating an AES-GCM decrypt success as a clean unlock. AES-GCM only926// authenticates the static VERSION_BYTE AAD, not the `version` field on the927// outer record — a corrupted `version: 42` slot still decrypts cleanly. This928// check surfaces that as `corrupted` (M7/COR-007) so the popup can offer a929// history-restore path instead of falsely reporting "wrong password".930function hasValidVaultSchema(v: unknown): v is StoredVault {931  if (typeof v !== "object" || v === null) return false;932  const r = v as Record<string, unknown>;933  return (934    r.version === 1 &&935    typeof r.salt === "string" &&936    typeof r.nonce === "string" &&937    typeof r.ciphertext === "string" &&938    typeof r.tag === "string"939  );940}941942export type TryDecryptResult =943  | { status: "ok"; payload: DecryptedPayload }944  | { status: "wrong_key" }945  | { status: "corrupted"; reason: string };946947// Exported solely for `unlockFromCodex` below, which needs to verify a948// supplied passphrase against a slotA blob *without* committing anything to949// storage. Keep this internal otherwise — callers crossing the messages.ts950// boundary should always go through `unlock` / `verifyMainPassword` so the951// constant-time invariants in Projects.md §3.4 are not bypassed.952export async function tryDecryptSlot(953  vault: StoredVault,954  key: Uint8Array,955  aadTag?: string,956): Promise<DecryptedPayload | null> {957  const res = await tryDecryptSlotResult(vault, key, aadTag);958  return res.status === "ok" ? res.payload : null;959}960961export async function tryDecryptSlotResult(962  vault: StoredVault,963  key: Uint8Array,964  aadTag?: string,965): Promise<TryDecryptResult> {966  if (!hasValidVaultSchema(vault)) {967    return { status: "corrupted", reason: "invalid_slot_schema" };968  }969  let plain: string;970  try {971    plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);972  } catch {973    return { status: "wrong_key" };974  }975  try {976    const parsed = JSON.parse(plain) as unknown;977    if (typeof parsed !== "object" || parsed === null) {978      return { status: "corrupted", reason: "invalid_payload_shape" };979    }980    if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {981      return { status: "corrupted", reason: "invalid_payload_shape" };982    }983    return { status: "ok", payload: decodePayload(plain) };984  } catch {985    return { status: "corrupted", reason: "invalid_payload_json" };986  }987}988989// ---------------------------------------------------------------------------990// Core operations991// ---------------------------------------------------------------------------992993function buildDomainIndexSync(all: VaultEntry[]): void {994  domainIndex = new Map();995996  for (const entry of all) {997    if (entry.deletedAt) continue;998    if (entry.type === "note" || entry.type === "card") continue;9991000    // An entry can match multiple sites via `additionalUrls`. Index each1001    // hostname so `queryDomain` returns the entry regardless of which alias1002    // the user is currently visiting. Dedupe per-entry so a single entry1003    // never appears twice in one bucket.1004    const domains = new Set<string>();1005    const primary = extractDomain(entry.url ?? "");1006    if (primary) domains.add(primary);1007    for (const extra of entry.additionalUrls ?? []) {1008      const d = extractDomain(extra);1009      if (d) domains.add(d);1010    }1011    if (domains.size === 0) continue;10121013    for (const domain of domains) {1014      const bucket = domainIndex.get(domain) ?? [];1015      bucket.push(entry);1016      domainIndex.set(domain, bucket);1017    }1018  }1019}10201021export async function createVault(password: string): Promise<void> {1022  await ensureMigrated();10231024  const salt = generateSalt();1025  derivedKey = await deriveKey(password, salt);1026  entries = [];1027  vaultMode = "real";1028  duressConfigured = false;1029  buildDomainIndexSync(entries);10301031  // Generate and wrap the root key for recovery word escrow.1032  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =1033    await generateAndWrapRootKey();1034  rootKey = unhex(rawRootKey);10351036  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);1037  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");10381039  // Second wrapping of rootKey under derivedKey so future unlocks can rehydrate1040  // it without recovery words (H2/COR-006).1041  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, rootKey);10421043  const slotA: StoredVault = {1044    version: 1,1045    salt: hex(salt),1046    nonce,1047    ciphertext,1048    tag,1049    recovery_salt: recoverySalt,1050    recovery_wrapped_root_key: wrappedRootKey,1051    recovery_nonce: wrappedNonce,1052    recovery_tag: wrappedTag,1053    ...pwRoot,1054  };1055  await writeSlot(SLOT_A, slotA);10561057  // Matching-size noise blob for slot B, so a fresh install shows two1058  // similarly-shaped records regardless of whether duress is ever set up.1059  await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));1060  await stampLocalVaultMutation();10611062  touchAutoLock();1063}10641065/**1066 * Creates a local vault from an existing vault root key received through the1067 * SAS-gated adoption protocol. The password is local to this device; it wraps1068 * the adopted root key at rest and does not need to match the source device.1069 */1070export async function createVaultFromRootKey(1071  password: string,1072  rootKeyHex: string,1073): Promise<{ vaultId: string }> {1074  if (typeof password !== "string" || password.length === 0) {1075    throw new Error("ADOPT_INVALID_PASSWORD");1076  }1077  if (typeof rootKeyHex !== "string" || !/^[0-9a-f]{64}$/.test(rootKeyHex)) {1078    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars");1079  }10801081  const rootKeyBytes = unhex(rootKeyHex);1082  if (rootKeyBytes.length !== 32) {1083    rootKeyBytes.fill(0);1084    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");1085  }10861087  let nextDerivedKey: Uint8Array | null = null;1088  let sessionRootKey: Uint8Array | null = null;1089  try {1090    await ensureMigrated();1091    if ((await loadSlot(SLOT_A)) !== null) {1092      throw new Error("ADOPT_VAULT_ALREADY_EXISTS");1093    }10941095    const nextEntries: VaultEntry[] = [];1096    const nextDuressConfigured = false;1097    const vaultId = await computeVaultId(rootKeyBytes);1098    const salt = generateSalt();1099    nextDerivedKey = await deriveKey(password, salt);1100    const recovery = await wrapExistingRootKeyForRecovery(rootKeyBytes);11011102    sessionRootKey = new Uint8Array(rootKeyBytes);1103    const plaintext = encodePayload(nextEntries, nextDuressConfigured, 0);1104    const { nonce, ciphertext, tag } = await encrypt(nextDerivedKey, plaintext, "slot_a_v1");1105    const pwRoot = await wrapRootKeyForDerivedKey(nextDerivedKey, sessionRootKey);1106    const slotA: StoredVault = {1107      version: 1,1108      salt: hex(salt),1109      nonce,1110      ciphertext,1111      tag,1112      recovery_salt: recovery.recoverySalt,1113      recovery_wrapped_root_key: recovery.wrappedRootKey,1114      recovery_nonce: recovery.wrappedNonce,1115      recovery_tag: recovery.wrappedTag,1116      ...pwRoot,1117    };1118    const slotB = generateNoiseBlob(ciphertext.length / 2);1119    await commitCreatedVaultSlots(slotA, slotB);11201121    const previousDerivedKey = derivedKey;1122    const previousRootKey = rootKey;1123    derivedKey = nextDerivedKey;1124    rootKey = sessionRootKey;1125    nextDerivedKey = null;1126    sessionRootKey = null;1127    entries = nextEntries;1128    vaultMode = "real";1129    duressConfigured = nextDuressConfigured;1130    buildDomainIndexSync(entries);1131    if (previousDerivedKey && previousDerivedKey !== derivedKey) zeroKey(previousDerivedKey);1132    if (previousRootKey && previousRootKey !== rootKey) previousRootKey.fill(0);1133    touchAutoLock();11341135    return { vaultId };1136  } finally {1137    rootKeyBytes.fill(0);1138    if (nextDerivedKey) zeroKey(nextDerivedKey);1139    if (sessionRootKey) sessionRootKey.fill(0);1140  }1141}11421143export async function hasVault(): Promise<boolean> {1144  await ensureMigrated();1145  return (await loadSlot(SLOT_A)) !== null;1146}11471148/**1149 * Returns whether the real vault has recorded that a duress passphrase is1150 * configured. Reliable only after a real-mode unlock — before unlock or in1151 * decoy mode, returns false because we cannot read slot A's plaintext.1152 */1153export async function isDuressEnabled(): Promise<boolean> {1154  return vaultMode === "real" && duressConfigured;1155}11561157export async function setupDuress(duressPassword: string): Promise<void> {1158  if (!derivedKey || vaultMode !== "real") {1159    throw new Error("vault must be unlocked in real mode");1160  }1161  await ensureMigrated();11621163  // Encrypt the decoy payload (empty entries) under the duress key. Pad to1164  // at least the current slot A ciphertext size so the two slots look the1165  // same at rest at setup time.1166  const slotA = await loadSlot(SLOT_A);1167  if (!slotA) throw new Error("missing slot A");11681169  const decoySalt = generateSalt();1170  const decoyKey = await deriveKey(duressPassword, decoySalt);1171  try {1172    // Pad the decoy to the fixed duress ceiling. Slot A is re-encrypted to the1173    // same ceiling by the persistSlotA() call below (duressConfigured is now1174    // true), so both slots are exactly DURESS_SLOT_SIZE+tag at rest and their1175    // lengths cannot reveal that duress is configured (audit MEDIUM).1176    const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);1177    const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");1178    await writeSlot(SLOT_B, {1179      version: 1,1180      salt: hex(decoySalt),1181      nonce,1182      ciphertext,1183      tag,1184    });1185  } finally {1186    zeroKey(decoyKey);1187  }11881189  // Re-encrypt slot A with the duressConfigured flag set to true. No external1190  // flag is written — the bit lives inside the encrypted envelope.1191  duressConfigured = true;1192  await persistSlotA();1193}11941195export async function disableDuress(): Promise<void> {1196  if (!derivedKey || vaultMode !== "real") {1197    throw new Error("vault must be unlocked in real mode");1198  }1199  await ensureMigrated();12001201  // Overwrite slot B with fresh noise that matches slot A's size. The slot1202  // remains occupied so its mere existence does not signal that duress was1203  // ever configured.1204  const slotA = await loadSlot(SLOT_A);1205  if (slotA) {1206    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));1207  }12081209  duressConfigured = false;1210  await persistSlotA();1211}12121213// L14/COR-015: this function intentionally checks slot A (real vault) only.1214// A duress-mode user attempting changePassword is rejected earlier by the1215// vaultMode === 'decoy' check at changePassword. The real-vs-decoy1216// distinction here is by design — duress users cannot rotate the real1217// password by guessing it, and the asymmetry in error timing is acceptable1218// because duress mode is opt-in and the user knows their own decoy key.1219export async function verifyMainPassword(password: string): Promise<boolean> {1220  await ensureMigrated();1221  const slotA = await loadSlot(SLOT_A);1222  if (!slotA) return false;1223  const key = await deriveKey(password, unhex(slotA.salt));1224  try {1225    return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;1226  } finally {1227    zeroKey(key);1228  }1229}12301231export async function unlock(password: string): Promise<boolean> {1232  // LV-1: the normal path NFC-normalizes inside deriveKey. If that fails and1233  // the supplied password is not already in NFC form, the vault may have been1234  // sealed (pre-LV-1) with the raw, un-normalized bytes — retry with those.1235  if (await attemptUnlockWithDerive(password, deriveKey)) return true;12361237  const nfc = password.normalize("NFC");1238  if (password === nfc) return false; // ASCII/NFC password — no legacy form to try12391240  if (await attemptUnlockWithDerive(password, deriveKeyRaw)) {1241    // Heal: re-seal the real slot under the NFC-normalized key so every1242    // future unlock takes the normal path. Only the real vault is re-sealed;1243    // a non-NFC duress password keeps working through this fallback.1244    if (vaultMode === "real") {1245      try {1246        const newSalt = generateSalt();1247        const newKey = await deriveKey(password, newSalt);1248        await changePasswordWithNewKey(newSalt, newKey);1249      } catch (healErr) {1250        console.warn("[Peach] LV-1 NFC heal failed:", healErr);1251      }1252    }1253    return true;1254  }1255  return false;1256}12571258async function attemptUnlockWithDerive(1259  password: string,1260  derive: typeof deriveKey,1261): Promise<boolean> {1262  await ensureMigrated();12631264  // Load both slots in parallel. Both always exist post-migration; the1265  // parallel load and the parallel derivation below keep wall-clock time1266  // constant regardless of which slot's passphrase (real or decoy) the1267  // caller supplied, so a timing side channel cannot distinguish the1268  // duress path from the real-unlock path (DUR-002).1269  const [slotA, slotB] = await Promise.all([1270    loadSlot(SLOT_A),1271    loadSlot(SLOT_B),1272  ]);12731274  // Derive both keys in parallel, unconditionally.1275  const [keyA, keyB] = await Promise.all([1276    slotA ? derive(password, unhex(slotA.salt)) : Promise.resolve(null),1277    slotB ? derive(password, unhex(slotB.salt)) : Promise.resolve(null),1278  ]);12791280  // Attempt both decrypts in parallel. The Result variant lets us distinguish1281  // 'wrong_key' from 'corrupted' so callers can offer a history-restore path1282  // when a slot's schema is invalid even though AES-GCM authenticated (M7).1283  const [resultA, resultB] = await Promise.all([1284    keyA && slotA1285      ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")1286      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1287    keyB && slotB1288      ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")1289      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1290  ]);1291  const payloadA = resultA.status === "ok" ? resultA.payload : null;1292  const payloadB = resultB.status === "ok" ? resultB.payload : null;12931294  if (payloadA && keyA) {1295    derivedKey = keyA;1296    void saveSessionKey(keyA, "real");1297    vaultMode = "real";1298    entries = payloadA.entries;1299    duressConfigured = payloadA.duressConfigured;1300    buildDomainIndexSync(entries);1301    await loadSettings();1302    touchAutoLock();1303    if (keyB) zeroKey(keyB);13041305    // slotA is non-null when payloadA is truthy (keyA was derived from slotA).1306    if (slotA) {1307      const needsRecoverySetup =1308        !slotA.recovery_salt || !slotA.recovery_wrapped_root_key;1309      if (!needsRecoverySetup) {1310        rootKey = await deriveRootKeyFromDerivedKey(keyA, slotA);1311      }1312      // Pre-v2.12 vault, or a vault whose pw_root_* fields haven't been written1313      // yet: generate the recovery escrow and seed pw_root_* so subsequent1314      // unlocks can rehydrate rootKey without the user's recovery words.1315      // Best-effort — a failure here must not block unlock.1316      if (needsRecoverySetup || !rootKey) {1317        try {1318          await migrateToRecovery();1319          if (needsRecoverySetup) {1320            // String "1" matches the popup's existing peach_recovery_pending1321            // check; surfaced so the user re-confirms recovery words after a1322            // legacy-vault unlock (H2/COR-006).1323            await chrome.storage.local.set({ peach_recovery_pending: '1' });1324          }1325        } catch (migrationErr) {1326          console.warn('[Peach] recovery migration failed:', migrationErr);1327        }1328      }1329    }13301331    // If the payload had a pre-v2.11.0 shape (legacy passkey type, flat1332    // passkey fields, or pre-A-2 created/updated keys), rewrite it now so1333    // the next save uses the new format and migration doesn't re-run forever.1334    if (payloadA.migratedFromLegacy) {1335      await persistSlotA();1336    }1337    return true;1338  }13391340  if (payloadB && keyB) {1341    derivedKey = keyB;1342    void saveSessionKey(keyB, "decoy");1343    vaultMode = "decoy";1344    entries = payloadB.entries;1345    duressConfigured = false;1346    buildDomainIndexSync(entries);1347    await loadSettings();1348    touchAutoLock();1349    if (keyA) zeroKey(keyA);1350    return true;1351  }13521353  if (keyA) zeroKey(keyA);1354  if (keyB) zeroKey(keyB);1355  // Surface corruption (good AES tag, broken schema) distinctly from1356  // wrong-password so the popup can offer history-restore (M7/COR-007).1357  if (resultA.status === "corrupted") {1358    lastUnlockFailureReason = resultA.reason;1359  } else if (resultB.status === "corrupted") {1360    lastUnlockFailureReason = resultB.reason;1361  }1362  return false;1363}13641365// ---------------------------------------------------------------------------1366// MV3 service worker session key — survives SW restarts within a browser session1367// ---------------------------------------------------------------------------13681369// chrome.storage.session is cleared on browser close; survives SW restart.1370// Firefox does not implement it (persistent background script, no restart risk).1371const SESSION_KEY_STORAGE = "peach_session_dk";13721373async function saveSessionKey(key: Uint8Array, mode: "real" | "decoy"): Promise<void> {1374  if (!chrome.storage.session) return;1375  await chrome.storage.session.set({ [SESSION_KEY_STORAGE]: { keyHex: hex(key), mode } });1376}13771378async function clearSessionKey(): Promise<void> {1379  if (!chrome.storage.session) return;1380  await chrome.storage.session.remove(SESSION_KEY_STORAGE);1381}13821383/**1384 * On SW restart, re-derive all in-memory vault state from the session key1385 * stored in chrome.storage.session (set at unlock time, cleared on lock).1386 * Returns true if the vault was restored, false if no session key was found.1387 * No-ops if the vault is already unlocked.1388 */1389export async function restoreFromSession(): Promise<boolean> {1390  if (derivedKey !== null) return true;1391  if (!chrome.storage.session) return false;1392  const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);1393  const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;1394  if (!entry?.keyHex) return false;13951396  const key = unhex(entry.keyHex);1397  const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;1398  const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";1399  const slot = await loadSlot(slotKey);1400  if (!slot) { await clearSessionKey(); return false; }14011402  const result = await tryDecryptSlotResult(slot, key, aadTag);1403  if (result.status !== "ok") { await clearSessionKey(); return false; }14041405  derivedKey = key;1406  vaultMode = entry.mode;1407  entries = result.payload.entries;1408  duressConfigured = entry.mode === "real" ? result.payload.duressConfigured : false;1409  buildDomainIndexSync(entries);1410  await loadSettings();1411  touchAutoLock();14121413  if (entry.mode === "real" && slot.recovery_salt && slot.recovery_wrapped_root_key) {1414    try { rootKey = await deriveRootKeyFromDerivedKey(key, slot); } catch { /* non-fatal */ }1415  }14161417  return true;1418}14191420export function lock(): void {1421  void clearSessionKey();1422  if (derivedKey) {1423    zeroKey(derivedKey);1424    derivedKey = null;1425  }1426  if (rootKey) {1427    rootKey.fill(0);1428    rootKey = null;1429  }14301431  entries = [];1432  domainIndex = new Map();1433  vaultMode = "real";1434  duressConfigured = false;1435  clearAutoLock();1436}14371438export function isUnlocked(): boolean {1439  return derivedKey !== null;1440}14411442// Opens the vault using a pre-derived AES-256 key (skipping Argon2id).1443// Used by Android biometric unlock — the key was derived on the native side.1444export async function unlockWithKey(1445  masterKeyHex: string,1446): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {1447  try {1448    const masterKeyBytes = unhex(masterKeyHex);1449    const stored = await loadSlot(SLOT_A);1450    if (!stored) return { ok: false, error: "invalid_key" };1451    const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");1452    if (!payload) return { ok: false, error: "invalid_key" };14531454    derivedKey = masterKeyBytes;1455    vaultMode = "real";1456    entries = payload.entries;1457    duressConfigured = payload.duressConfigured;1458    buildDomainIndexSync(entries);1459    await loadSettings();1460    touchAutoLock();14611462    // PCH-01-009: the biometric path skips Argon2id but must still rehydrate the1463    // root key, exactly like attemptUnlockWithDerive and restoreFromSession.1464    // Without it, rootKey stays null after a biometric unlock and sync +1465    // GET_RECOVERY_WORDS report the open vault as locked. Guarded and non-fatal:1466    // a missing/legacy escrow must not fail the unlock itself.1467    if (stored.recovery_salt && stored.recovery_wrapped_root_key) {1468      try {1469        rootKey = await deriveRootKeyFromDerivedKey(masterKeyBytes, stored);1470      } catch { /* non-fatal — unlock still succeeds without rootKey */ }1471    }1472    return { ok: true, entries };1473  } catch {1474    return { ok: false, error: "invalid_key" };1475  }1476}14771478/**1479 * Restore the vault from a parsed Peach Codex payload.1480 *1481 * The supplied passphrase is verified against the Codex's slotA *before* any1482 * storage mutation — wrong passphrases return without touching disk. On1483 * success, the current vault state is snapshotted (reason: "restore") so the1484 * user can revert via Settings -> Vault History, then slotA/slotB are written1485 * and `peach_last_modified_at` is set to the Codex's recorded timestamp. A1486 * regular `unlock()` follows so the rest of the SW sees the standard1487 * post-unlock state.1488 *1489 * Intentionally non-Pro-gated — see peach_codex_v2.md "Pro gating". A Codex1490 * printed by a Pro user must always be restorable, even on a free device.1491 *1492 * Timing is not held constant here (in contrast to `unlock`): the Codex flow1493 * is an explicit user action with a known passphrase, not a passive lock1494 * screen, so the duress-vs-real timing side channel does not apply.1495 */1496export async function unlockFromCodex(params: {1497  slotA: string; // JSON string of StoredVault for slot A1498  slotB: string | null; // JSON string of StoredVault for slot B, or null1499  timestamp: number;1500  masterPassphrase: string;1501}): Promise<1502  | { ok: true; entryCount: number }1503  | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" }1504> {1505  let parsedSlotA: StoredVault;1506  let parsedSlotB: StoredVault | null = null;1507  try {1508    const rawA = JSON.parse(params.slotA) as unknown;1509    if (!hasValidVaultSchema(rawA)) {1510      return { ok: false, reason: "invalid_slot_format" };1511    }1512    parsedSlotA = rawA;1513    if (params.slotB !== null) {1514      const rawB = JSON.parse(params.slotB) as unknown;1515      if (!hasValidVaultSchema(rawB)) {1516        return { ok: false, reason: "invalid_slot_format" };1517      }1518      parsedSlotB = rawB;1519    }1520  } catch {1521    return { ok: false, reason: "invalid_slot_format" };1522  }15231524  // Verify the passphrase against the supplied slotA WITHOUT writing anything.1525  // If this fails the on-disk vault is left completely untouched.1526  const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));1527  const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");1528  if (!trialPayload) {1529    zeroKey(trialKey);1530    return { ok: false, reason: "wrong_passphrase" };1531  }1532  // Drop the trial key; `unlock()` below derives its own copy. Holding two1533  // copies of the master key in memory at once would be a needless surface.1534  zeroKey(trialKey);15351536  // Snapshot the about-to-be-overwritten on-disk state so the user can revert1537  // a mistaken Codex restore via the Vault History UI. Non-fatal if it fails.1538  await takeVaultSnapshot("restore");15391540  await writeSlot(SLOT_A, parsedSlotA);1541  if (parsedSlotB) {1542    await writeSlot(SLOT_B, parsedSlotB);1543  } else {1544    // Slot B must always exist with ciphertext length matching slot A1545    // (Projects.md §3.2). Codex prints may omit slot B (duress wasn't1546    // configured); regenerate noise to satisfy the invariant.1547    await writeSlot(1548      SLOT_B,1549      generateNoiseBlob(parsedSlotA.ciphertext.length / 2),1550    );1551  }1552  await chrome.storage.local.set({1553    peach_last_modified_at: String(params.timestamp),1554  });15551556  // Standard unlock path so domain index, settings, auto-lock, and1557  // recovery-key state all populate exactly as a normal unlock would.1558  const ok = await unlock(params.masterPassphrase);1559  if (!ok) {1560    // Should be unreachable — we just verified the passphrase against the1561    // same slotA we wrote. Treat as wrong_passphrase to keep the contract1562    // simple if some race or storage anomaly intrudes.1563    return { ok: false, reason: "wrong_passphrase" };1564  }1565  return { ok: true, entryCount: getEntries().length };1566}15671568// Returns the current in-memory derived key as a hex string.1569// Used by the biometric enable flow in Settings to store the key in Android Keystore.1570export function getDerivedKeyHex(): string {1571  if (!derivedKey) throw new Error("vault_not_unlocked");1572  return hex(derivedKey);1573}15741575/**1576 * Returns the vault's stable root key as hex, or null when locked / not yet1577 * populated. The root key is random per-vault, generated at creation, escrowed1578 * under the recovery words, and re-wrapped (not regenerated) on every password1579 * change — so it is INVARIANT across password rotation, unlike getDerivedKeyHex.1580 *1581 * This is the correct input for sync identity derivation (vault_id, the Noise1582 * NK static key, the Ed25519 manifest signing key, and per-entry envelope1583 * keys): paired devices keep the same identity and can still decrypt each1584 * other's entries after either side rotates its master password (SEV-2-B).1585 *1586 * Returns null rather than throwing so sync callers degrade to VAULT_LOCKED1587 * instead of crashing; rootKey is populated on every real-mode unlock via1588 * deriveRootKeyFromDerivedKey / migrateToRecovery.1589 */1590export function getRootKeyHex(): string | null {1591  return rootKey ? hex(rootKey) : null;1592}15931594export function getEntries(): VaultEntry[] {1595  if (!derivedKey) throw new Error("vault_locked");1596  return entries.filter((entry) => !entry.deletedAt);1597}15981599const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;16001601export function getIdentities(): SavedIdentity[] {1602  if (!derivedKey) throw new Error("vault_locked");1603  const active = entries.filter((e) => !e.deletedAt && e.type === "login");16041605  const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();1606  const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();16071608  for (const entry of active) {1609    const domain = extractDomain(entry.url ?? "") ?? "";1610    const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;16111612    function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {1613      const existing = map.get(v);1614      if (!existing || modifiedAt > existing.lastUsed) {1615        map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });1616      } else {1617        map.set(v, { ...existing, count: existing.count + 1 });1618      }1619    }16201621    const uVal = entry.username?.trim();1622    if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);16231624    // Also count the dedicated email field — entries created via the inline1625    // popup new-entry form store email here rather than in username.1626    const eVal = entry.email?.trim();1627    if (eVal) tally(emailMap, eVal);1628  }16291630  const toIdentity = (type: "email" | "username") =>1631    ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({1632      value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,1633    });16341635  return [1636    ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),1637    ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),1638  ];1639}16401641export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {1642  if (!derivedKey) throw new Error("vault_locked");16431644  const now = Date.now();1645  const added: VaultEntry[] = [];1646  for (const draft of drafts) {1647    try {1648      const sanitized = sanitizeEntryDraft(draft);1649      const nextEntry: VaultEntry = {1650        ...sanitized,1651        id: crypto.randomUUID(),1652        createdAt: now,1653        modifiedAt: monotonicEntryTimestamp(),1654      };1655      entries.push(nextEntry);1656      added.push(nextEntry);1657    } catch {1658      // Skip invalid drafts silently — caller can see diff between input and output length1659    }1660  }16611662  if (added.length > 0) {1663    await persistEntries();1664  }16651666  return added;1667}16681669/**1670 * Restore a set of entries in full fidelity — preserves id, createdAt,1671 * modifiedAt, and every other field unlike `batchAddEntries` which1672 * assigns fresh identity. Used by restore paths where the backup is the1673 * authoritative source of truth. `mode` controls how entries already in1674 * the vault are treated.1675 */1676export async function restoreEntries(1677  incoming: VaultEntry[],1678  mode: "replace" | "merge"1679): Promise<{ added: number; updated: number; skipped: number }> {1680  if (!derivedKey) throw new Error("vault_locked");16811682  // A replace with zero incoming entries is almost certainly a caller bug1683  // (e.g. an import that silently dropped everything). Refuse rather than1684  // wipe the vault.1685  if (mode === "replace" && incoming.length === 0) {1686    throw new Error("refuse to replace with empty entry set");1687  }16881689  let added = 0;1690  let updated = 0;1691  let skipped = 0;16921693  if (mode === "replace") {1694    entries = [];1695    for (const entry of incoming) {1696      const normalized = sanitizeRestoredEntry(entry);1697      if (!normalized) {1698        skipped += 1;1699        continue;1700      }1701      entries.push(normalized);1702      added += 1;1703    }1704  } else {1705    const byId = new Map<string, VaultEntry>();1706    for (const e of entries) byId.set(e.id, e);17071708    for (const entry of incoming) {1709      const normalized = sanitizeRestoredEntry(entry);1710      if (!normalized) {1711        skipped += 1;1712        continue;1713      }1714      const existing = byId.get(normalized.id);1715      if (!existing) {1716        entries.push(normalized);1717        added += 1;1718      } else if (normalized.modifiedAt > existing.modifiedAt) {1719        const idx = entries.findIndex((e) => e.id === existing.id);1720        if (idx !== -1) {1721          entries[idx] = normalized;1722          updated += 1;1723        }1724      } else {1725        skipped += 1;1726      }1727    }1728  }17291730  await persistEntries("import");1731  return { added, updated, skipped };1732}17331734/**1735 * Validate + normalise a VaultEntry coming from a backup, import, or sync1736 * peer. MV-6: this is a strict field WHITELIST — `normalizeEntry` copies1737 * only known VaultEntry fields (unknown/attacker keys are dropped), and1738 * nested `passkey`/`canary` shapes are rebuilt field-by-field, never1739 * spread. Returns null for values the live vault shouldn't accept.1740 */1741function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {1742  if (!entry || typeof entry !== "object") return null;1743  const title = typeof entry.title === "string" ? entry.title.trim() : "";1744  if (!title) return null;1745  const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();1746  const now = Date.now();1747  const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;1748  const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;17491750  // normalizeEntry whitelists every known VaultEntry field and runs the1751  // same legacy-passkey migration as the on-disk read path — pre-v2.11.01752  // backups with flat passkey fields still import correctly because the1753  // legacy flat fields are themselves whitelisted VaultEntry members.1754  const normalized = normalizeEntry({1755    ...entry,1756    id,1757    title,1758    type: entry.type ?? "login",1759    createdAt,1760    modifiedAt,1761  });17621763  if (normalized.passkey) {1764    normalized.passkey = sanitizePasskey(normalized.passkey);1765  }1766  if (normalized.canary) {1767    normalized.canary = sanitizeCanary(normalized.canary);1768  }1769  // PCH-01-016: bound tags on the restore path too, so both import funnels agree.1770  normalized.tags = sanitizeTags(normalized.tags);17711772  // Login entries from backup must carry a password (or be passkey-only,1773  // in which case the passkey sub-object replaces the password requirement).1774  if (1775    normalized.type === "login" &&1776    !normalized.passkey &&1777    typeof normalized.password !== "string"1778  ) {1779    return null;1780  }1781  if (entry.passkey && !normalized.passkey) {1782    // Entry claimed a passkey but the shape didn't validate — refuse the1783    // whole entry rather than silently importing a credential-less husk.1784    return null;1785  }17861787  return normalized;1788}17891790/**1791 * Rebuild a PasskeyData object from untrusted input, field by field.1792 * Returns undefined when required fields are missing/mistyped — a rogue1793 * passkey credential must not activate via import (MV-6 attack scenario).1794 */1795function sanitizePasskey(pk: unknown): PasskeyData | undefined {1796  if (!pk || typeof pk !== "object") return undefined;1797  const r = pk as Record<string, unknown>;1798  if (1799    typeof r.rpId !== "string" || !r.rpId ||1800    typeof r.credentialId !== "string" || !r.credentialId ||1801    typeof r.publicKeyCose !== "string" ||1802    typeof r.userHandle !== "string" ||1803    typeof r.userName !== "string"1804  ) {1805    return undefined;1806  }1807  return {1808    rpId: r.rpId,1809    rpName: typeof r.rpName === "string" ? r.rpName : r.rpId,1810    credentialId: r.credentialId,1811    publicKeyCose: r.publicKeyCose,1812    privateKeyJwk:1813      r.privateKeyJwk && typeof r.privateKeyJwk === "object"1814        ? (r.privateKeyJwk as JsonWebKey)1815        : undefined,1816    userHandle: r.userHandle,1817    userName: r.userName,1818    userDisplayName:1819      typeof r.userDisplayName === "string" ? r.userDisplayName : r.userName,1820    algorithm: r.algorithm === -8 ? -8 : -7,1821    signCount: typeof r.signCount === "number" ? r.signCount : 0,1822    aaguid: typeof r.aaguid === "string" ? r.aaguid : "",1823    backupEligible: r.backupEligible === true,1824    backupState: r.backupState === true,1825    lastUsedAt: typeof r.lastUsedAt === "number" ? r.lastUsedAt : undefined,1826    browser: r.browser === "chrome" || r.browser === "firefox" ? r.browser : undefined,1827    transports: Array.isArray(r.transports)1828      ? r.transports.filter((t): t is string => typeof t === "string")1829      : undefined,1830    createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),1831  };1832}18331834/**1835 * Rebuild a Canary object from untrusted input. The webhook must be a1836 * well-formed HTTPS URL — a poisoned canary.webhookUrl is a standing1837 * exfiltration endpoint that the canary subsystem will POST entry titles1838 * to (MV-6 attack scenario). Invalid → the canary is dropped, not the1839 * entry. FIRE_CANARY_PING re-validates with the full SSRF guard at fire1840 * time (isAllowedCanaryWebhookUrl), so this import-time check is the1841 * outer of two gates.1842 */1843function sanitizeCanary(c: unknown): Canary | undefined {1844  if (!c || typeof c !== "object") return undefined;1845  const r = c as Record<string, unknown>;1846  if (typeof r.webhookUrl !== "string") return undefined;1847  let url: URL;1848  try {1849    url = new URL(r.webhookUrl);1850  } catch {1851    return undefined;1852  }1853  if (url.protocol !== "https:") return undefined;1854  return {1855    webhookUrl: url.toString(),1856    label: typeof r.label === "string" ? r.label : undefined,1857    lastPinged: typeof r.lastPinged === "number" ? r.lastPinged : undefined,1858    pingCount: typeof r.pingCount === "number" ? r.pingCount : undefined,1859  };1860}18611862/**1863 * MV-6 / PCH-01-016: tags from imported / batch-added entries are untrusted.1864 * Keep only non-empty strings, cap each at 256 chars, and cap the count at 2551865 * (the same per-entry ceiling the export codec enforces, peachPayload.ts).1866 * Non-array or all-invalid input collapses to undefined.1867 */1868function sanitizeTags(tags: unknown): string[] | undefined {1869  if (!Array.isArray(tags)) return undefined;1870  const out: string[] = [];1871  for (const t of tags) {1872    if (typeof t !== "string") continue;1873    const trimmed = t.trim();1874    if (!trimmed) continue;1875    out.push(trimmed.slice(0, 256));1876    if (out.length >= 255) break;1877  }1878  return out.length > 0 ? out : undefined;1879}18801881// Soft-deletes every non-deleted entry in one call. The literal string1882// argument is a tripwire against accidental calls — any caller that would1883// wipe the vault has to consciously type "REPLACE_ALL". Do not relax this1884// to a boolean.1885export async function clearVaultEntries(1886  confirmation: "REPLACE_ALL"1887): Promise<void> {1888  if (confirmation !== "REPLACE_ALL") {1889    throw new Error("clearVaultEntries requires explicit confirmation");1890  }1891  if (!derivedKey) throw new Error("vault_locked");1892  for (const entry of entries) {1893    if (!entry.deletedAt) {1894      const stamp = monotonicEntryTimestamp(entry.modifiedAt);1895      entry.deletedAt = stamp;1896      entry.modifiedAt = stamp;1897    }1898  }1899  await persistEntries();1900}19011902export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {1903  if (!derivedKey) throw new Error("vault_locked");19041905  const sanitized = sanitizeEntryDraft(entry);1906  const now = Date.now();1907  const stamp = monotonicEntryTimestamp();1908  const nextEntry: VaultEntry = {1909    ...sanitized,1910    id: crypto.randomUUID(),1911    createdAt: now,1912    modifiedAt: stamp,1913    // Stamp passwordChangedAt at creation so age tracking is accurate from1914    // day one. Non-login entries carry the same stamp harmlessly.1915    passwordChangedAt: sanitized.password ? stamp : undefined,1916  };19171918  // Clone-and-replace so a failed persist rolls back the in-memory state1919  // (COR-008). Without this, a quota-full or storage error leaves the1920  // module-level `entries` ahead of what's actually on disk.1921  const rollback = entries;1922  entries = [...entries, nextEntry];1923  try {1924    await persistEntries();1925  } catch (err) {1926    entries = rollback;1927    throw err;1928  }19291930  // Fire-and-forget breach check (only for login entries if breach monitoring is enabled or not set)1931  if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {1932    checkBreach(nextEntry.password).then(async (count) => {1933      if (count > 0) {1934        const idx = entries.findIndex((e) => e.id === nextEntry.id);1935        if (idx !== -1) {1936          entries[idx] = { ...entries[idx], breach: count, modifiedAt: monotonicEntryTimestamp(entries[idx].modifiedAt) };1937          await persistEntries();1938        }1939      }1940    });1941  }19421943  fireSyncTrigger("vault_change");19441945  return nextEntry;1946}19471948/**1949 * Run the passkey-merge pass on the live in-memory entries and persist if1950 * anything changed. Called immediately after any passkey registration so that1951 * a same-domain TOTP-only entry already in the vault gets consolidated right1952 * away instead of waiting until the next lock/unlock cycle.1953 */1954export async function consolidatePasskeyEntries(): Promise<void> {1955  if (!derivedKey) return;1956  const { merged } = mergePasskeyOnlyIntoLogins(entries);1957  if (merged) {1958    await persistEntries();1959  }1960}19611962export async function updateEntry(1963  id: string,1964  patch: Partial<VaultEntry>1965): Promise<void> {1966  if (!derivedKey) throw new Error("vault_locked");19671968  const idx = entries.findIndex((entry) => entry.id === id);1969  if (idx === -1 || entries[idx].deletedAt) {1970    throw new Error("entry_not_found");1971  }19721973  const current = entries[idx];1974  const sanitizedPatch = sanitizeEntryPatch(patch);1975  // Refresh passwordChangedAt only when the password value actually changes —1976  // a metadata-only update (title, tags, etc.) must not reset the age clock1977  // that drives the Pro health rotation recommendation.1978  const passwordChanged =1979    "password" in patch &&1980    typeof sanitizedPatch.password === "string" &&1981    sanitizedPatch.password !== current.password;1982  const stamp = monotonicEntryTimestamp(current.modifiedAt);1983  // When the password actually changes, push the outgoing one onto the history1984  // (newest first) so the user can reveal/copy/restore it later. We record the1985  // age it carried (passwordChangedAt, falling back to createdAt) rather than1986  // `now`, so the list reflects when each password was last in effect. Only1987  // capture a non-empty prior value — clearing a password leaves no secret to1988  // keep, and we skip an immediate exact duplicate (e.g. restore-then-restore)1989  // to avoid noise.1990  const priorPassword = current.password;1991  const shouldCapture =1992    passwordChanged &&1993    typeof priorPassword === "string" &&1994    priorPassword.length > 0 &&1995    current.passwordHistory?.[0]?.password !== priorPassword;1996  const nextHistory = shouldCapture1997    ? [1998        { password: priorPassword!, changedAt: current.passwordChangedAt ?? current.createdAt },1999        ...(current.passwordHistory ?? []),2000      ].slice(0, PASSWORD_HISTORY_MAX)2001    : current.passwordHistory;2002  entries[idx] = {2003    ...current,2004    ...sanitizedPatch,2005    modifiedAt: stamp,2006    ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),2007  };2008200920102011  // Card entries must retain their card number2012  if (entries[idx].type === "card" && !entries[idx].cardNumber) {2013    entries[idx] = current;2014    throw new Error("card number is required for card entries");2015  }20162017  // Roll the in-memory entry back to its pre-edit state if the disk write2018  // fails (e.g. storage quota). Without this the module-level `entries` array2019  // would hold an edit that never landed on disk, diverging from the vault2020  // until the next unlock silently reverts it (SEV-3-A). Mirrors addEntry.2021  try {2022    await persistEntries();2023  } catch (err) {2024    entries[idx] = current;2025    throw err;2026  }20272028  // Breach check when password changes: clear immediately so old breach doesn't linger,2029  // then async-check the new password and only re-set if it's also found.2030  if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {2031    entries[idx] = { ...entries[idx], breach: undefined };2032    await persistEntries();2033    const password = entries[idx].password;2034    if (password) {2035      checkBreach(password).then(async (count) => {2036        const i = entries.findIndex((e) => e.id === id);2037        if (i !== -1 && count > 0) {2038          entries[i] = { ...entries[i], breach: count, modifiedAt: monotonicEntryTimestamp(entries[i].modifiedAt) };2039          await persistEntries();2040        }2041      });2042    }2043  }20442045  fireSyncTrigger("vault_change");2046}20472048export async function deleteEntry(id: string): Promise<void> {2049  if (!derivedKey) throw new Error("vault_locked");20502051  const entry = entries.find((item) => item.id === id);2052  if (!entry || entry.deletedAt) {2053    throw new Error("entry_not_found");2054  }20552056  // Tombstone timestamp must be strictly greater than the entry's last2057  // modification so the deletion wins LWW against any in-flight edit, even2058  // under clock skew (SEV-2-E).2059  const previousModifiedAt = entry.modifiedAt;2060  const stamp = monotonicEntryTimestamp(entry.modifiedAt);2061  entry.deletedAt = stamp;2062  entry.modifiedAt = stamp;2063  // Roll the tombstone back if the disk write fails, so a quota error doesn't2064  // leave the entry deleted in memory but alive on disk (SEV-3-A).2065  try {2066    await persistEntries();2067  } catch (err) {2068    delete entry.deletedAt;2069    entry.modifiedAt = previousModifiedAt;2070    throw err;2071  }2072  fireSyncTrigger("vault_change");2073}20742075export function getDeletedEntries(): VaultEntry[] {2076  if (!derivedKey) return [];2077  return entries.filter((e) => !!e.deletedAt);2078}20792080/**2081 * Returns the vault's monotonic version — the `peach_last_modified_at` value2082 * stamped on every user-initiated write. Remote (sync) writes do NOT advance2083 * this version so a sync round never cascades into a second outbound sync.2084 */2085export async function getVaultVersion(): Promise<number> {2086  try {2087    const raw = await chrome.storage.local.get("peach_last_modified_at");2088    const v = (raw as Record<string, unknown>).peach_last_modified_at;2089    if (typeof v === "number") return v;2090    if (typeof v === "string" && v !== "") {2091      const n = Number.parseInt(v, 10);2092      return Number.isFinite(n) ? n : 0;2093    }2094    return 0;2095  } catch {2096    return 0;2097  }2098}20992100/**2101 * Internal write variants — bypass `fireSyncTrigger` so the sync layer can2102 * apply entries without cascading into another outbound sync round.2103 *2104 * INVARIANT: callers must not pass entries whose IDs collide with existing2105 * active (non-deleted) entries unless the intent is an explicit overwrite.2106 * These functions do not validate field-level constraints (password required,2107 * card number required, etc.) — they are trust-the-caller paths for sync and2108 * test harness use only.2109 */2110export async function addEntryDirect(entry: VaultEntry): Promise<void> {2111  if (!derivedKey) throw new Error("vault_locked");2112  entries = [...entries, entry];2113  await persistEntries("sync_received");2114}21152116export async function updateEntryDirect(patch: VaultEntry): Promise<void> {2117  if (!derivedKey) throw new Error("vault_locked");2118  const idx = entries.findIndex((e) => e.id === patch.id);2119  if (idx === -1) throw new Error("entry_not_found");2120  entries[idx] = { ...entries[idx], ...patch };2121  await persistEntries("sync_received");2122}21232124export async function deleteEntryDirect(id: string, deletedAt: number): Promise<void> {2125  if (!derivedKey) throw new Error("vault_locked");2126  const idx = entries.findIndex((e) => e.id === id);2127  if (idx === -1) throw new Error("entry_not_found");2128  entries[idx] = { ...entries[idx], deletedAt, modifiedAt: deletedAt };2129  await persistEntries("sync_received");2130}21312132/**2133 * Apply a batch of remote entries + tombstones from a sync peer.2134 * Last-write-wins by `modifiedAt`; a tombstone supersedes a live entry when2135 * `deletedAt > modifiedAt` on the local side. Mutates `entries` directly and2136 * persists with reason `sync_received` — does NOT fire the sync dispatcher, so2137 * applying a sync round cannot cascade into another outbound sync.2138 *2139 * `applied` counts entries that actually changed local state (new add,2140 * overwrite-by-newer, or new tombstone). `received` is the raw payload size2141 * the caller can surface in the sync result UI.2142 */2143export async function applyMergedRemoteEntries(2144  remoteEntries: VaultEntry[],2145  remoteTombstones: Record<string, number>,2146  _context: { deviceName?: string } = {},2147): Promise<{ received: number; applied: number; conflicts: number }> {2148  // DESIGN: last-write-wins is applied PER-ENTRY, not per-field. If two devices2149  // concurrently edit different fields of the same entry, the one with the2150  // newer modifiedAt wins the whole entry and the other device's field edits2151  // are dropped silently. This is the deliberate trade-off for a simple,2152  // conflict-free merge — per-field CRDT merge is out of scope. Guidance for2153  // users: edit a given entry on one device at a time.2154  if (!derivedKey) throw new Error("vault_locked");21552156  const received = remoteEntries.length + Object.keys(remoteTombstones).length;2157  let applied = 0;2158  let conflicts = 0;21592160  const byId = new Map<string, VaultEntry>();2161  for (const e of entries) byId.set(e.id, e);21622163  const mergeNow = Date.now();21642165  for (const remote of remoteEntries) {2166    const sanitized = sanitizeRestoredEntry(remote);2167    if (!sanitized) continue;2168    // HV-1a: a far-future remote modifiedAt must not permanently pin a2169    // malicious value against honest local edits. Clamp BEFORE any2170    // comparison against local timestamps.2171    sanitized.modifiedAt = clampSyncTimestamp(sanitized.modifiedAt, mergeNow);2172    if (typeof sanitized.deletedAt === "number") {2173      sanitized.deletedAt = clampSyncTimestamp(sanitized.deletedAt, mergeNow);2174    }2175    const tombstoneTs = remoteTombstones[sanitized.id];2176    if (tombstoneTs !== undefined && clampSyncTimestamp(tombstoneTs, mergeNow) >= sanitized.modifiedAt) {2177      continue;2178    }2179    const local = byId.get(sanitized.id);2180    if (!local) {2181      entries.push(sanitized);2182      byId.set(sanitized.id, sanitized);2183      applied += 1;2184    } else if (sanitized.modifiedAt > local.modifiedAt) {2185      const idx = entries.findIndex((e) => e.id === local.id);2186      if (idx !== -1) {2187        entries[idx] = sanitized;2188        byId.set(sanitized.id, sanitized);2189        applied += 1;2190        if (!local.deletedAt) conflicts += 1;2191      }2192    }2193  }21942195  for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2196    if (typeof rawDeletedAt !== "number" || !Number.isFinite(rawDeletedAt)) continue;2197    // HV-1a/1c: clamp the tombstone timestamp before every comparison.2198    const deletedAt = clampSyncTimestamp(rawDeletedAt, mergeNow);2199    const local = byId.get(id);2200    if (!local) continue;2201    if (local.deletedAt && local.deletedAt >= deletedAt) continue;2202    if (deletedAt < local.modifiedAt) continue;2203    const idx = entries.findIndex((e) => e.id === id);2204    if (idx !== -1) {2205      entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };2206      applied += 1;2207    }2208  }22092210  if (applied > 0) {2211    await persistEntries("sync_received");2212    buildDomainIndexSync(entries);2213  }2214  return { received, applied, conflicts };2215}22162217export async function restoreEntry(id: string): Promise<void> {2218  if (!derivedKey) throw new Error("vault_locked");2219  const entry = entries.find((e) => e.id === id && e.deletedAt);2220  if (!entry) throw new Error("deleted entry not found");2221  delete entry.deletedAt;2222  entry.modifiedAt = monotonicEntryTimestamp(entry.modifiedAt);2223  await persistEntries();2224  buildDomainIndexSync(entries);2225}22262227export async function purgeEntry(id: string): Promise<void> {2228  if (!derivedKey) throw new Error("vault_locked");2229  const idx = entries.findIndex((e) => e.id === id && e.deletedAt);2230  if (idx === -1) throw new Error("deleted entry not found");2231  entries.splice(idx, 1);2232  await persistEntries();2233}22342235/** Permanently delete entries whose deletedAt is older than retentionMs. 0 = keep forever. */2236export async function purgeExpiredTrash(retentionMs: number): Promise<number> {2237  if (!derivedKey || retentionMs === 0) return 0;2238  const cutoff = Date.now() - retentionMs;2239  const before = entries.length;2240  entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));2241  const purged = before - entries.length;2242  if (purged > 0) await persistEntries();2243  return purged;2244}22452246export function queryDomain(domain: string): VaultEntry[] {2247  return domainIndex.get(domain) ?? [];2248}22492250export function getEntryById(id: string): VaultEntry | undefined {2251  return entries.find((entry) => entry.id === id && !entry.deletedAt);2252}22532254async function persistSlotA(2255  reason: VaultSnapshot["reason"] = "local_save",2256): Promise<StoredVault> {2257  if (!derivedKey) throw new Error("vault_locked");22582259  const slotA = await loadSlot(SLOT_A);2260  if (!slotA) throw new Error("missing slot A");22612262  // Snapshot the about-to-be-overwritten state BEFORE we mutate disk. Failures2263  // are swallowed by takeVaultSnapshot — history must never block a save.2264  await takeVaultSnapshot(reason);22652266  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);2267  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");22682269  // Preserve existing recovery escrow fields.2270  const nextSlotA: StoredVault = {2271    ...slotA,2272    nonce,2273    ciphertext,2274    tag,2275    // recovery_salt and recovery_wrapped_root_key are already set from loadSlot2276  };2277  await writeSlot(SLOT_A, nextSlotA);22782279  // Slot A (the real vault) is now committed. Wrap every later write so a2280  // mid-persist failure (e.g. a storage error after slot A landed) restores the2281  // prior slot A before rethrowing. Without this, a "failed" save that already2282  // wrote slot A leaves disk ahead of the in-memory rollback in addEntry/2283  // updateEntry/deleteEntry — the entry stays silently on disk and resurfaces2284  // as a duplicate on the next unlock (observed under storage-quota pressure).2285  try {2286    // When duress is not configured, keep slot B size-matched with slot A by2287    // regenerating its noise. When duress IS configured, leave slot B alone —2288    // we don't have the decoy key to re-encrypt it. This is a known trade-off.2289    if (!duressConfigured) {2290      await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));2291    }2292    // Only advance the vault version for locally-originated writes. Entries2293    // applied from a sync peer ("sync_received") must NOT bump the counter —2294    // otherwise applying a remote round makes us look newer than the peer and2295    // triggers a redundant outbound sync, defeating the no-op optimisation2296    // and risking a ping-pong between two devices (SEV-2-C).2297    if (reason !== "sync_received") {2298      await stampLocalVaultMutation();2299    }2300  } catch (err) {2301    // Best-effort restore — the prior slot A is smaller-or-equal, so this write2302    // fits even when the failure was a quota overflow.2303    await writeSlot(SLOT_A, slotA).catch(() => {});2304    throw err;2305  }23062307  return nextSlotA;2308}23092310async function persistSlotB(): Promise<void> {2311  if (!derivedKey) throw new Error("vault_locked");23122313  const slotB = await loadSlot(SLOT_B);2314  if (!slotB) throw new Error("missing slot B");23152316  // Decoy plaintext always reports duressConfigured=false — the decoy user2317  // sees a clean slate. persistSlotB only runs in decoy mode, which only2318  // exists once duress is configured, so pad to the fixed duress ceiling to2319  // keep slot B's length equal to slot A's (audit MEDIUM — deniability).2320  const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);2321  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");23222323  await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });2324  // Symmetric with persistSlotA: if the version stamp fails after the decoy2325  // slot committed, restore the prior slot B so a failed decoy-mode save can't2326  // leave disk ahead of the in-memory rollback.2327  try {2328    await stampLocalVaultMutation();2329  } catch (err) {2330    await writeSlot(SLOT_B, slotB).catch(() => {});2331    throw err;2332  }2333}23342335async function persistEntries(2336  reason: VaultSnapshot["reason"] = "local_save",2337): Promise<void> {2338  if (!derivedKey) throw new Error("vault_locked");23392340  if (vaultMode === "decoy") {2341    await persistSlotB();2342  } else {2343    await persistSlotA(reason);2344  }2345  buildDomainIndexSync(entries);2346}23472348function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {2349  if (!Array.isArray(values)) return undefined;2350  const seen = new Set<string>();2351  const cleaned: string[] = [];2352  for (const value of values) {2353    const trimmed = typeof value === "string" ? value.trim() : "";2354    if (!trimmed) continue;2355    const key = trimmed.toLowerCase();2356    if (seen.has(key)) continue;2357    seen.add(key);2358    cleaned.push(trimmed);2359  }2360  return cleaned.length > 0 ? cleaned : undefined;2361}23622363function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {2364  const title = entry.title.trim();2365  // Accept legacy `type:"passkey"` drafts but rewrite to "login" — the new2366  // model is "any entry, optionally with a passkey sub-object." Imports and2367  // any in-flight callers from before v2.11.0 keep working without throwing.2368  let type: VaultEntry["type"] = entry.type ?? "login";2369  if (type === "passkey") type = "login";23702371  if (!title) throw new Error("title is required");23722373  if (entry.passkey) {2374    const p = entry.passkey;2375    if (2376      !p.rpId ||2377      !p.credentialId ||2378      !p.publicKeyCose ||2379      !p.userHandle ||2380      !p.userName ||2381      (p.algorithm !== -7 && p.algorithm !== -8)2382    ) {2383      throw new Error("invalid passkey credential");2384    }2385  }2386  if (type === "card") {2387    if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {2388      throw new Error("cardholder name and card number are required");2389    }2390  }23912392  return {2393    type,2394    title,2395    username: type === "login" ? entry.username?.trim() ?? "" : undefined,2396    email: type === "login" ? entry.email?.trim() || undefined : undefined,2397    password: type === "login" ? entry.password : undefined,2398    url: type === "login" ? entry.url?.trim() ?? "" : undefined,2399    additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,2400    totp: type === "login" ? entry.totp?.trim() || undefined : undefined,2401    // PCH-01-019: preserve non-default TOTP params through batch-add/import so2402    // they are not silently stripped (they fall back to SHA-1/6/30 when absent).2403    totpAlgorithm: type === "login" ? entry.totpAlgorithm : undefined,2404    totpDigits: type === "login" ? entry.totpDigits : undefined,2405    totpPeriod: type === "login" ? entry.totpPeriod : undefined,2406    notes: entry.notes?.trim() || undefined,2407    breach: type === "login" ? entry.breach : undefined,2408    // PCH-01-016: the batch-add path was bypassing the MV-6 canary/tags2409    // whitelist applied on the RESTORE_ENTRIES path. Run both sanitizers here.2410    canary: type === "login" ? sanitizeCanary(entry.canary) : undefined,2411    tags: sanitizeTags(entry.tags),2412    passkey: entry.passkey,2413    cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,2414    cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,2415    expMonth: type === "card" ? entry.expMonth?.trim() : undefined,2416    expYear: type === "card" ? entry.expYear?.trim() : undefined,2417    cvc: type === "card" ? entry.cvc?.trim() : undefined,2418    cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,2419    network: type === "card" ? entry.network : undefined,2420    last4: type === "card" ? entry.last4?.trim() : undefined,2421  };2422}24232424function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {2425  const nextPatch: Partial<VaultEntry> = {};24262427  if ("type" in patch) {2428    nextPatch.type = patch.type;2429  }24302431  if ("title" in patch) {2432    const title = patch.title?.trim() ?? "";2433    if (!title) throw new Error("title is required");2434    nextPatch.title = title;2435  }24362437  if ("url" in patch) {2438    nextPatch.url = patch.url?.trim() ?? "";2439  }24402441  if ("additionalUrls" in patch) {2442    const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];2443    const seen = new Set<string>();2444    const cleaned: string[] = [];2445    for (const value of incoming) {2446      const trimmed = typeof value === "string" ? value.trim() : "";2447      if (!trimmed) continue;2448      const key = trimmed.toLowerCase();2449      if (seen.has(key)) continue;2450      seen.add(key);2451      cleaned.push(trimmed);2452    }2453    nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;2454  }24552456  if ("username" in patch) {2457    nextPatch.username = patch.username?.trim() ?? "";2458  }24592460  if ("email" in patch) {2461    nextPatch.email = patch.email?.trim() || undefined;2462  }24632464  if ("password" in patch) {2465    const password = patch.password ?? "";2466    // Allow clearing a password (e.g. on passkey-only entries)2467    nextPatch.password = password || undefined;2468  }24692470  if ("totp" in patch) {2471    nextPatch.totp = patch.totp?.trim() || undefined;2472  }24732474  if ("notes" in patch) {2475    nextPatch.notes = patch.notes?.trim() || undefined;2476  }24772478  if ("breach" in patch) {2479    nextPatch.breach = patch.breach;2480  }24812482  if ("canary" in patch) {2483    // PCH-02-001: route update patches through the same canary whitelist used2484    // by add/restore/sync. Invalid shapes drop the canary; `undefined` clears it.2485    nextPatch.canary = patch.canary ? sanitizeCanary(patch.canary) : undefined;2486  }24872488  if ("passkey" in patch) {2489    // Passkey sub-object replaces all the legacy flat passkey fields. A2490    // patch with `passkey: undefined` removes the credential from the entry2491    // (used by "remove passkey" without deleting the whole entry).2492    if (patch.passkey === undefined || patch.passkey === null) {2493      nextPatch.passkey = undefined;2494    } else {2495      const sanitized = sanitizePasskey(patch.passkey);2496      if (!sanitized) throw new Error("invalid passkey credential");2497      nextPatch.passkey = sanitized;2498    }2499  }25002501  if ("tags" in patch) {2502    // PCH-02-001: bound tags exactly like both import funnels.2503    nextPatch.tags = sanitizeTags(patch.tags);2504  }25052506  if ("cardholderName" in patch) {2507    nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;2508  }2509  if ("cardNumber" in patch) {2510    const n = patch.cardNumber ?? "";2511    nextPatch.cardNumber = n || undefined;2512  }2513  if ("expMonth" in patch) {2514    nextPatch.expMonth = patch.expMonth?.trim() || undefined;2515  }2516  if ("expYear" in patch) {2517    nextPatch.expYear = patch.expYear?.trim() || undefined;2518  }2519  if ("cvc" in patch) {2520    nextPatch.cvc = patch.cvc?.trim() || undefined;2521  }2522  if ("cardNickname" in patch) {2523    nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;2524  }2525  if ("network" in patch) {2526    nextPatch.network = patch.network;2527  }2528  if ("last4" in patch) {2529    nextPatch.last4 = patch.last4?.trim() || undefined;2530  }25312532  return nextPatch;2533}25342535function normalizeEntry(entry: VaultEntry | LegacyVaultEntry): VaultEntry {2536  const createdAt = "createdAt" in entry ? entry.createdAt : entry.created;2537  const modifiedAt =2538    "modifiedAt" in entry ? entry.modifiedAt : entry.updated;25392540  const base: VaultEntry = {2541    id: entry.id,2542    type: "type" in entry ? entry.type : "login",2543    title: entry.title,2544    username: entry.username,2545    email: "email" in entry ? entry.email : undefined,2546    password: entry.password,2547    url: entry.url,2548    additionalUrls:2549      "additionalUrls" in entry && Array.isArray(entry.additionalUrls)2550        ? entry.additionalUrls2551        : undefined,2552    totp: entry.totp,2553    // PCH-01-019: carry TOTP params through the normalize/restore path too.2554    totpAlgorithm: entry.totpAlgorithm,2555    totpDigits: entry.totpDigits,2556    totpPeriod: entry.totpPeriod,2557    notes: entry.notes,2558    breach: entry.breach,2559    // Preserve the password-age clock across lock/unlock. Without this the2560    // field is dropped on every decode and the advanced-health "aged password"2561    // signal silently resets to createdAt on each unlock (SEV-2-A).2562    passwordChangedAt:2563      "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,2564    // Preserve past-password history across lock/unlock. normalizeEntry is a2565    // field whitelist, so an unlisted field is silently dropped on every decode2566    // (same class as the passwordChangedAt SEV-2-A above).2567    passwordHistory:2568      "passwordHistory" in entry && Array.isArray(entry.passwordHistory)2569        ? entry.passwordHistory2570        : undefined,2571    canary: "canary" in entry ? entry.canary : undefined,2572    passkey: "passkey" in entry ? entry.passkey : undefined,2573    createdAt,2574    modifiedAt,2575    deletedAt: entry.deletedAt,2576    tags: "tags" in entry ? entry.tags : undefined,2577    cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,2578    cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,2579    expMonth: "expMonth" in entry ? entry.expMonth : undefined,2580    expYear: "expYear" in entry ? entry.expYear : undefined,2581    cvc: "cvc" in entry ? entry.cvc : undefined,2582    cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,2583    network: "network" in entry ? entry.network : undefined,2584    last4: "last4" in entry ? entry.last4 : undefined,2585  };25862587  return migrateLegacyPasskey(base, entry);2588}25892590/**2591 * v2.11.0 read migration. Pre-v2.11.0 passkey entries used `type:"passkey"`2592 * with flat top-level fields (rpId, credentialId, etc.). This converts them2593 * to the new shape — `type:"login"` with a `passkey` sub-object — so all2594 * downstream consumers can rely on the new model. The result is rewritten2595 * to disk on next vault save (hasLegacyShape detects the un-migrated case).2596 */2597function migrateLegacyPasskey(2598  base: VaultEntry,2599  raw: VaultEntry | LegacyVaultEntry2600): VaultEntry {2601  if (base.passkey) return base;2602  const flat = raw as Partial<VaultEntry>;2603  const isPasskeyType = base.type === "passkey";2604  const hasFlatPasskeyFields =2605    typeof flat.rpId === "string" &&2606    typeof flat.credentialId === "string" &&2607    typeof flat.publicKeyCose === "string" &&2608    typeof flat.userHandle === "string" &&2609    typeof flat.userName === "string";2610  if (!isPasskeyType && !hasFlatPasskeyFields) return base;2611  if (!hasFlatPasskeyFields) return base;26122613  const algorithm: -7 | -8 = flat.algorithm === -8 ? -8 : -7;2614  base.passkey = {2615    rpId: flat.rpId!,2616    rpName: flat.rpName ?? flat.rpId!,2617    credentialId: flat.credentialId!,2618    publicKeyCose: flat.publicKeyCose!,2619    privateKeyJwk: flat.privateKeyJwk,2620    userHandle: flat.userHandle!,2621    userName: flat.userName!,2622    userDisplayName: flat.userDisplayName ?? flat.userName!,2623    algorithm,2624    signCount: flat.signCount ?? 0,2625    aaguid: flat.aaguid ?? "",2626    backupEligible: flat.backupEligible === true,2627    backupState: flat.backupState === true,2628    lastUsedAt: flat.lastUsedAt,2629    browser: flat.browser,2630    transports: flat.transports,2631    createdAt: base.createdAt,2632  };2633  // Promote to "login" so the unified Entry view renders. Username gets2634  // populated from the passkey's userName so the entry is searchable in the2635  // existing autofill flow without a separate code path.2636  if (isPasskeyType) base.type = "login";2637  if (!base.username) base.username = flat.userName;2638  if (!base.url) base.url = `https://${flat.rpId}`;2639  return base;2640}264126422643// ---------------------------------------------------------------------------2644// Deduplication2645// ---------------------------------------------------------------------------26462647function entryDupeKey(e: VaultEntry): string {2648  if (e.type === "note") return `note|${e.title.toLowerCase()}`;2649  // Passkey-bearing entries dedupe by the credential's RP + user. Two logins2650  // on different sites that happen to share a username are still distinct;2651  // two passkey credentials for the same RP+user are duplicates regardless2652  // of any login fields they may also carry.2653  if (e.passkey) {2654    return `passkey|${e.passkey.rpId.toLowerCase()}|${e.passkey.userName.toLowerCase()}`;2655  }2656  return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;2657}26582659/** Returns the number of duplicate entries (those that would be removed). */2660export function countDuplicates(): number {2661  const best = new Map<string, VaultEntry>();2662  let dupeCount = 0;2663  for (const e of entries.filter((e) => !e.deletedAt)) {2664    const key = entryDupeKey(e);2665    const existing = best.get(key);2666    if (!existing) {2667      best.set(key, e);2668    } else {2669      dupeCount++;2670      // Keep the more recently modified one in the map2671      if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2672        best.set(key, e);2673      }2674    }2675  }2676  return dupeCount;2677}26782679/**2680 * Soft-deletes duplicate entries, keeping the most recently modified copy of2681 * each group. Returns the number of entries moved to trash.2682 */2683export async function deduplicateEntries(): Promise<number> {2684  if (!derivedKey) throw new Error("vault_locked");2685  // Dedup reshapes slot B permanently under the decoy key, which is2686  // forensically distinguishable from a freshly-seeded decoy vault. Refuse.2687  if (vaultMode === "decoy") {2688    throw new Error("deduplicate disabled in decoy mode");2689  }26902691  const best = new Map<string, VaultEntry>();2692  for (const e of entries.filter((en) => !en.deletedAt)) {2693    const key = entryDupeKey(e);2694    const existing = best.get(key);2695    if (!existing) {2696      best.set(key, e);2697    } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {2698      best.set(key, e);2699    }2700  }27012702  const keepIds = new Set(Array.from(best.values()).map((e) => e.id));2703  let removed = 0;2704  entries = entries.map((e) => {2705    if (!e.deletedAt && !keepIds.has(e.id)) {2706      removed++;2707      return { ...e, deletedAt: monotonicEntryTimestamp(e.modifiedAt) };2708    }2709    return e;2710  });27112712  if (removed > 0) await persistEntries();2713  return removed;2714}27152716// ---------------------------------------------------------------------------2717// Vault history — snapshot BEFORE every vault write so the saved blob is2718// what is about to be lost, not what was just written. Capped at 5. The2719// stored blobs are AES-256-GCM ciphertext under the master password, so2720// history adds zero security surface.2721// ---------------------------------------------------------------------------27222723const HISTORY_KEY = "peach_vault_history";2724const HISTORY_MAX = 5;27252726// PCH-01-023: coarsen a live-entry count into a low-resolution bucket so the2727// plaintext snapshot field cannot reveal exact vault size or single-entry change2728// deltas. Buckets widen as the vault grows so absolute leakage stays roughly2729// proportional rather than exact.2730function bucketEntryCount(n: number): number {2731  if (n <= 0) return 0;2732  if (n <= 10) return 10;2733  if (n <= 25) return 25;2734  if (n <= 50) return 50;2735  if (n <= 100) return 100;2736  if (n <= 250) return 250;2737  if (n <= 500) return 500;2738  return Math.ceil(n / 500) * 500;2739}27402741/**2742 * Snapshot the CURRENT on-disk vault state into history. Call this BEFORE2743 * overwriting peach_vault_a so the saved blob captures the about-to-be-lost2744 * state. Identical-to-most-recent blobs are skipped to avoid filling history2745 * with no-op writes.2746 */2747export async function takeVaultSnapshot(2748  reason: VaultSnapshot["reason"],2749): Promise<void> {2750  try {2751    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);2752    const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];2753    const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];27542755    // Nothing to snapshot if the real slot doesn't exist yet (fresh install,2756    // pre-createVault). createVault skips snapshots intentionally — there is2757    // no prior state to preserve.2758    if (!slotA) return;27592760    const vault_a = JSON.stringify(slotA);2761    const vault_b = JSON.stringify(slotB ?? slotA);27622763    // Best-effort entry count: only meaningful when the in-memory state is2764    // unlocked AND in real mode. Decoy mode would leak the decoy entry2765    // count; locked mode has no entries to count. Both fall through to null.2766    // PCH-01-023: store a coarse bucket, not the exact count — chrome.storage2767    // .local sits next to the AES-GCM blobs in plaintext, so an exact count would2768    // leak vault size and per-write deltas (the metadata padding hides this).2769    let entryCount: number | null = null;2770    if (derivedKey && vaultMode === "real") {2771      try {2772        entryCount = bucketEntryCount(entries.filter((e) => !e.deletedAt).length);2773      } catch {2774        entryCount = null;2775      }2776    }27772778    const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];2779    const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)2780      ? existingRaw2781      : { snapshots: [] };27822783    // Deduplication: if the most recent snapshot has byte-identical blobs,2784    // skip — saves the same vault N times in a row would otherwise burn the2785    // entire history window with no recovery value.2786    const latest = history.snapshots[0];2787    if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {2788      return;2789    }27902791    const snapshot: VaultSnapshot = {2792      id: crypto.randomUUID(),2793      savedAt: Date.now(),2794      reason,2795      vault_a,2796      vault_b,2797      entryCount,2798    };27992800    history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);2801    await chrome.storage.local.set({ [HISTORY_KEY]: history });2802  } catch (err) {2803    // Non-fatal — history must never block a save. A failed snapshot just2804    // means the user loses one rung of the safety ladder for this write.2805    // M4/QUA-006: log so the failure is visible; if it looks like a quota2806    // problem, notify the popup so the user can prune history themselves.2807    console.warn('[Peach] takeVaultSnapshot failed:', err);2808    if (String(err).includes('QUOTA') || String(err).includes('quota')) {2809      try {2810        await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });2811      } catch {2812        // popup may be closed; surfaced via console.warn above2813      }2814    }2815  }2816}28172818/** Wipe all vault history. Called by Panic / DESTROY_VAULT. */2819export async function clearVaultHistory(): Promise<void> {2820  try {2821    await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });2822  } catch {2823    // Non-fatal — DESTROY_VAULT also runs storage.local.clear().2824  }2825}28262827/** Read all snapshots, newest first, for the Settings vault history view. */2828export async function getVaultHistory(): Promise<VaultSnapshot[]> {2829  const raw = await chrome.storage.local.get(HISTORY_KEY);2830  const history = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];2831  if (!history || !Array.isArray(history.snapshots)) return [];2832  return history.snapshots;2833}28342835/**2836 * Replace the on-disk vault with the chosen snapshot's blobs and lock the2837 * vault. The current state is itself snapshotted with reason 'restore' first2838 * so the restore is reversible. After this returns, the user must unlock2839 * with the password that matches the restored blob.2840 */2841export async function restoreVaultSnapshot(2842  snapshotId: string,2843): Promise<{ ok: true } | { ok: false; error: string }> {2844  const history = await getVaultHistory();2845  const snapshot = history.find((s) => s.id === snapshotId);2846  if (!snapshot) return { ok: false, error: "snapshot_not_found" };28472848  // Snapshot the about-to-be-replaced current state so the restore is2849  // reversible. takeVaultSnapshot is no-op when the most recent entry is2850  // byte-identical, so a restore-of-a-restore stays clean.2851  await takeVaultSnapshot("restore");28522853  let restoredA: StoredVault;2854  let restoredB: StoredVault;2855  try {2856    restoredA = JSON.parse(snapshot.vault_a) as StoredVault;2857    restoredB = JSON.parse(snapshot.vault_b) as StoredVault;2858  } catch {2859    return { ok: false, error: "snapshot_corrupt" };2860  }28612862  await writeSlot(SLOT_A, restoredA);2863  await writeSlot(SLOT_B, restoredB);2864  await stampLocalVaultMutation();28652866  // Lock so the user must prove they can decrypt the restored blob. If they2867  // restored a pre-password-change snapshot they discover it immediately at2868  // the lock screen rather than silently holding an inaccessible vault.2869  lock();28702871  return { ok: true };2872}28732874/**2875 * Rotate the vault's sync identity by generating a FRESH ROOT KEY and2876 * re-wrapping everything under it (MV-8). Because every sync credential —2877 * vault_id, the Noise static keypair, the Ed25519 manifest signing key,2878 * and the per-entry envelope keys — derives from the root key, rotation2879 * makes a lost/stolen device's retained key material useless. All paired2880 * devices must re-pair afterwards.2881 *2882 * CONSEQUENCE THE UI MUST SURFACE: the 12 recovery words also derive from2883 * the root key, so rotation INVALIDATES the old recovery phrase. The flow2884 * sets peach_recovery_pending so the popup re-presents the new words for2885 * confirmation, same as the migrateToRecovery rotate path.2886 */2887export async function rotateSyncIdentity(): Promise<{ ok: boolean; error?: string }> {2888  if (!derivedKey || vaultMode !== "real") {2889    return { ok: false, error: "vault_locked" };2890  }2891  const slotA = await loadSlot(SLOT_A);2892  if (!slotA) return { ok: false, error: "missing_slot_a" };28932894  // 1. Fresh root key + recovery escrow (new words).2895  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =2896    await generateAndWrapRootKey();28972898  // 2. Re-wrap the new root key under the current password-derived key.2899  const newRootKey = unhex(rawRootKey);2900  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, newRootKey);29012902  // 3. Snapshot, then single atomic slot write — both escrow wrappings of2903  //    the new root key land together (same transactional rule as2904  //    changePassword). Entries are untouched: they are sealed under the2905  //    password-derived key, not the root key.2906  await takeVaultSnapshot("local_save");2907  const nextSlotA: StoredVault = {2908    ...slotA,2909    recovery_salt: recoverySalt,2910    recovery_wrapped_root_key: wrappedRootKey,2911    recovery_nonce: wrappedNonce,2912    recovery_tag: wrappedTag,2913    ...pwRoot,2914  };2915  await writeSlot(SLOT_A, nextSlotA);29162917  // 4. Swap in memory only after disk committed.2918  if (rootKey) zeroKey(rootKey);2919  rootKey = newRootKey;29202921  // 5. Old peers' identities derive from the dead root key — drop them all.2922  await clearPairedDevices();29232924  // 6. Force re-presentation of the NEW recovery words on next popup view.2925  await setRecoveryConfirmPending(); // same flag the create-vault flow uses29262927  await stampLocalVaultMutation();2928  return { ok: true };2929}29302931/**2932 * Change the master password. Re-encrypts slot A with a fresh salt + new2933 * derived key. Slot B (duress or noise) is left untouched when duress is2934 * configured — it uses an independent key derived from the duress password —2935 * and regenerated as noise when duress is not configured.2936 */2937export async function changePassword(2938  currentPassword: string,2939  newPassword: string2940): Promise<boolean> {2941  if (!derivedKey || vaultMode !== "real") return false;29422943  // Verify current password before allowing any change2944  const valid = await verifyMainPassword(currentPassword);2945  if (!valid) return false;29462947  const slotA = await loadSlot(SLOT_A);2948  if (!slotA) return false;2949  if (!rootKey) return false;29502951  // Derive fresh key from new password + new random salt2952  const newSalt = generateSalt();2953  const newKey = await deriveKey(newPassword, newSalt);29542955  // Re-encrypt the in-memory entries with the new key2956  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);2957  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");29582959  // Pre-wrap root key under the new derived key. Recovery fields wrap rootKey2960  // under recovery words and remain untouched — recovery phrase keeps working2961  // across password changes (H4/COR-002).2962  const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);29632964  const finalSlotA: StoredVault = {2965    ...slotA,2966    salt: hex(newSalt),2967    nonce,2968    ciphertext,2969    tag,2970    ...pwRoot,2971  };29722973  // Snapshot the OLD-key blob before overwriting it. If the user later2974  // restores from this snapshot they will need the OLD password — the2975  // post-restore lock surfaces that immediately.2976  await takeVaultSnapshot("local_save");29772978  // Single atomic write: ciphertext, salt, and pw_root_* fields all land in2979  // one storage transaction. An SW kill before this point leaves the old2980  // slot intact; after this point everything tied to the new password is2981  // already on disk together (M6/COR-004).2982  await writeSlot(SLOT_A, finalSlotA);29832984  // Swap the in-memory key synchronously before any further await. If we2985  // threw between the Slot A write and this swap, the next persistEntries()2986  // would overwrite Slot A with old-key ciphertext, locking the user out.2987  zeroKey(derivedKey);2988  derivedKey = newKey;29892990  // PCH-01-008: the MV3 session escrow still holds the OLD key. Without this,2991  // the next service-worker restore decrypts the new-key Slot A with the stale2992  // key, fails tryDecryptSlotResult, and silently drops the user to a lock2993  // screen. Re-escrow the new key so restore survives a password change.2994  void saveSessionKey(newKey, "real");29952996  // Regenerate noise for slot B when duress is not in use. Runs after the2997  // key swap so a failure here is a disposable noise regeneration, not a2998  // lockout.2999  if (!duressConfigured) {3000    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3001  }3002  await stampLocalVaultMutation();30033004  return true;3005}