vault.ts

143.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, generateSalt } from "../crypto/argon2";13import { extractDomain } from "../shared/domain";14import { clampSyncTimestamp } from "../shared/sync-limits";15import { computeVaultId } from "../shared/sync-identity";16// Static, not `await import()`: runtime import() throws in an MV3 service17// worker. Neither module imports vault.ts back, so there is no cycle to break.18import { triggerSyncIfReachable } from "./sync-trigger";19import { clearPairedDevices } from "./paired-devices";20import {21  rootKeyToWords,22  wordsToRootKeyMaterial,23  deriveRecoveryKey,24} from "../shared/recovery-words";25import type {26  AccentColorName,27  Canary,28  ManualSummonRecord,29  PasskeyData,30  RecoveryResult,31  SavedIdentity,32  StoredVault,33  VaultEntry,34  VaultHistory,35  VaultSnapshot,36} from "../shared/types";37import { decrypt, encrypt, zeroKey } from "./aes";38import { clearAutoLock, touchAutoLock } from "./alarms";39import { setRecoveryConfirmPending, revokeRecoveryReveal } from "./recovery-pending";40import {41  clearPairSecrets,42  dropSessionCache,43  reconcilePairSecrets,44  setSessionAllowed,45} from "./pair-secrets";4647type EntryDraft = Omit<48  VaultEntry,49  "id" | "createdAt" | "modifiedAt" | "deletedAt"50>;5152// Slot-neutral storage keys (v1.4.24+). Both slots always exist; slot B53// either holds the decoy vault (when duress is configured) or random noise54// that looks identical at rest. No external indicator is stored — duress55// configuration is recorded only inside the encrypted payload of slot A.56const SLOT_A = "peach_vault_a";57const SLOT_B = "peach_vault_b";5859// Plaintext is padded to the next multiple of this size before encryption.60// This coarsens ciphertext-length leakage into 1 KiB buckets.61const PAD_BLOCK = 1024;6263// How many past passwords to retain per entry. Generous enough to be useful as64// a recovery aid while bounding the secret material we hold (and the ciphertext65// growth) for an entry whose password is rotated frequently.66const PASSWORD_HISTORY_MAX = 50;6768// When duress is configured, BOTH slots are padded to this fixed ceiling so69// their ciphertext lengths are identical and cannot reveal that a hidden decoy70// vault exists (audit MEDIUM — plausible-deniability leak). 256 KiB comfortably71// holds a very large vault (thousands of entries incl. passkeys). The decoy72// slot can't be re-encrypted on every real-vault save (the real session has no73// decoy key), so a fixed ceiling — rather than size-matching on each write — is74// what keeps the two slots equal. A real vault whose plaintext exceeds this75// would grow past the ceiling and re-expose the bit; that is an extreme,76// documented edge well beyond normal use.77const DURESS_SLOT_SIZE = 262_144;7879let derivedKey: Uint8Array | null = null;80// 32-byte random root key, separate from the derivedKey used for vault encryption.81// The root key is wrapped (encrypted) under the recovery key derived from the82// 12-word phrase. When the user changes their password, only the wrapping changes;83// the root key and recovery words remain stable.84let rootKey: Uint8Array | null = null;85let recoveryInFlight = false;86let recoverySettled: Promise<void> = Promise.resolve();87let vaultRemovalsInFlight = 0;88let vaultRemovalEpoch = 0;89let vaultWritesInFlight = 0;90let vaultCreatesInFlight = 0;91let creationSettled: Promise<void> = Promise.resolve();92let vaultUnlocksInFlight = 0;93let vaultReplacementInFlight = false;94let entries: VaultEntry[] = [];95// Tombstones outlive their full entry records so a peer that was offline96// during a purge cannot reintroduce an old ciphertext envelope. This map is97// serialized only inside the encrypted vault payload.98let tombstones = new Map<string, number>();99let domainIndex: Map<string, VaultEntry[]> = new Map();100let vaultMode: "real" | "decoy" = "real";101// Cached post-unlock view of whether the real vault records that duress is102// configured. Only meaningful after a real-mode unlock; for decoy-mode unlock103// this stays false because we never see slot A's plaintext.104let duressConfigured = false;105106// Set to a corruption reason during the last unlock() attempt when both slots107// decrypted but failed schema validation. Consumed and cleared by108// consumeLastUnlockFailureReason() so messages.ts can surface vault_corrupted109// distinctly from wrong-password (M7/COR-007).110//111// NOTE: module-level state — if vault.ts is ever moved to a worker context,112// this must be replaced with a structured return value from unlock() or a113// postMessage channel. The signal is invisible across module-instance114// boundaries.115let lastUnlockFailureReason: string | null = null;116117export function consumeLastUnlockFailureReason(): string | null {118  const r = lastUnlockFailureReason;119  lastUnlockFailureReason = null;120  return r;121}122123// ---------------------------------------------------------------------------124// Settings (persisted inside the encrypted vault store as a sidecar key)125// ---------------------------------------------------------------------------126127export type TextSize = "small" | "medium" | "large";128129export interface VaultSettings {130  accentColor?: AccentColorName;131  theme?: "dark" | "light";132  autoLockMinutes?: number;133  clipboardClearSeconds?: number;134  lockOnClose?: boolean;135  breachMonitoring?: boolean;136  passkeyProviderEnabled?: boolean;137  trashRetentionDays?: number;138  manualSummonDomains?: Record<string, ManualSummonRecord>;139  manualSummonSalt?: string;140  declinedCardFingerprints?: string[];141142  /** Metadata is bounded because it remains outside the encrypted vault blob. */143  metadataVersion?: 1;144  /**145   * Text size scale for body copy and entry titles. Stops at "large" by146   * design — XL clips dense screens (Vault, Health) inside the fixed147   * 330×480 popup surface.148   */149  textSize?: TextSize;150  /**151   * When true, all entrance/exit transitions and ambient animations are152   * collapsed to instant. Honoured alongside the user's OS-level153   * `prefers-reduced-motion`.154   */155  reduceMotion?: boolean;156  /** Require an unlock after a worker restart before locked Sync resumes. */157  lockedSyncRequiresUnlock?: boolean;158  /** Whether this vault has a local PIN unlock wrapper configured. */159  pinEnabled?: boolean;160  /** Whether the lock screen should open on PIN instead of the password. */161  pinPreferred?: boolean;162  /**163   * User overrides for keyboard shortcuts. Keys are ShortcutAction names164   * (see src/shared/shortcuts.ts). Missing actions fall through to165   * DEFAULT_BINDINGS — `getActiveBindings(settings.shortcuts)` is the166   * canonical lookup. Storing only the deltas keeps the vault payload167   * small and lets default updates land for users who never rebind.168   */169  shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;170}171172interface StoredPinWrap {173  version: 1;174  salt: string;175  nonce: string;176  ciphertext: string;177  tag: string;178}179180const PIN_WRAP_STORAGE = "peach_pin_wrap";181const PIN_ATTEMPTS_STORAGE = "peach_pin_attempts";182const PIN_MIN_LENGTH = 4;183const PIN_MAX_LENGTH = 12;184const PIN_MAX_ATTEMPTS = 3;185186let settings: VaultSettings = {};187const CARD_DECLINE_MAX = 256;188/** Hex length of a keyed card-decline digest. Legacy records are 16 hex. */189const CARD_DECLINE_DIGEST_HEX = 32;190191async function metadataDigest(value: string, key: string): Promise<string> {192  const bytes = new TextEncoder().encode(`${key}:${value}`);193  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));194  return Array.from(digest.slice(0, 16)).map((byte) => byte.toString(16).padStart(2, "0")).join("");195}196197let inMemoryPinWrap: StoredPinWrap | null = null;198let inMemoryPinFailedAttempts = 0;199let sessionPinStorageFailed = false;200201export function getSettings(): VaultSettings {202  return settings;203}204205export async function ensureSettingsLoaded(): Promise<VaultSettings> {206  await loadSettings();207  return settings;208}209210export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {211  await loadSettings();212  // LV-7: cheap insurance against prototype pollution if a future caller ever213  // feeds parsed external JSON here (native spread keeps __proto__ an own-214  // property today, but Object.assign-style consumers and JSON revivers have215  // been burned before).216  const safe = Object.fromEntries(217    Object.entries(patch).filter(218      ([k]) => !["__proto__", "constructor", "prototype"].includes(k),219    ),220  ) as Partial<VaultSettings>;221  settings = { ...settings, ...safe };222  await persistSettings();223}224225function isValidPin(pin: string): boolean {226  return new RegExp(`^\\d{${PIN_MIN_LENGTH},${PIN_MAX_LENGTH}}$`).test(pin);227}228229/** Set up a local PIN wrapper after proving the current master password. */230export async function setupPinUnlock(currentPassword: string, pin: string): Promise<boolean> {231  if (vaultCreatesInFlight) return false;232  vaultWritesInFlight++;233  try {234  if (!derivedKey || vaultMode !== "real" || !isValidPin(pin)) return false;235  if (!(await verifyMainPassword(currentPassword))) return false;236237  const salt = generateSalt();238  const pinKey = await deriveKey(pin, salt);239  try {240    const wrapped = await encrypt(pinKey, hex(derivedKey), "pin_wrap_v1");241    await savePinWrap({ version: 1, salt: hex(salt), ...wrapped });242    await updateSettings({ pinEnabled: true });243    return true;244  } finally {245    zeroKey(pinKey);246  }247  } finally { vaultWritesInFlight--; }248}249250async function clearPinUnlockStorage(): Promise<void> {251  inMemoryPinWrap = null;252  inMemoryPinFailedAttempts = 0;253  sessionPinStorageFailed = false;254  if (chrome.storage.session) {255    await chrome.storage.session.remove([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);256  }257  await updateSettings({ pinEnabled: false });258}259260/** Remove the PIN wrapper after proving the current master password. */261export async function disablePinUnlock(currentPassword: string): Promise<boolean> {262  if (vaultCreatesInFlight) return false;263  vaultWritesInFlight++;264  try {265  if (!derivedKey || vaultMode !== "real") return false;266  if (!(await verifyMainPassword(currentPassword))) return false;267  await clearPinUnlockStorage();268  return true;269  } finally { vaultWritesInFlight--; }270}271272/** Unlock the real vault from its locally stored PIN-wrapped derived key. */273export async function unlockWithPin(pin: string): Promise<boolean> {274  vaultUnlocksInFlight++;275  try {276  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;277  if (!isValidPin(pin)) return false;278  await loadSettings();279  if (!settings.pinEnabled) return false;280281  const { stored, failedAttempts } = await loadPinState();282  if (failedAttempts >= PIN_MAX_ATTEMPTS) return false;283  if (284    !stored ||285    stored.version !== 1 ||286    !stored.salt ||287    !stored.nonce ||288    !stored.ciphertext ||289    !stored.tag290  ) return false;291292  const pinKey = await deriveKey(pin, unhex(stored.salt));293  let unwrappedKey: Uint8Array | null = null;294  try {295    const masterKeyHex = await decrypt(296      pinKey,297      stored.nonce,298      stored.ciphertext,299      stored.tag,300      "pin_wrap_v1",301    );302    if (!/^[0-9a-f]{64}$/.test(masterKeyHex)) return false;303    unwrappedKey = unhex(masterKeyHex);304    const result = await unlockWithKey(masterKeyHex);305    if (!result.ok) return false;306    await resetPinFailedAttempts();307    return true;308  } catch {309    await recordPinFailure(failedAttempts + 1);310    return false;311  } finally {312    zeroKey(pinKey);313    if (unwrappedKey) zeroKey(unwrappedKey);314  }315  } finally { vaultUnlocksInFlight--; }316}317318async function savePinWrap(stored: StoredPinWrap): Promise<void> {319  inMemoryPinWrap = stored;320  inMemoryPinFailedAttempts = 0;321  sessionPinStorageFailed = !chrome.storage.session;322  if (!chrome.storage.session) return;323  try {324    await chrome.storage.session.set({ [PIN_WRAP_STORAGE]: stored, [PIN_ATTEMPTS_STORAGE]: 0 });325    sessionPinStorageFailed = false;326  } catch {327    // Firefox fallback: keep the wrapper only in this background context.328    sessionPinStorageFailed = true;329  }330}331332async function loadPinState(): Promise<{333  stored: StoredPinWrap | undefined;334  failedAttempts: number;335}> {336  if (!chrome.storage.session) {337    return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };338  }339  try {340    const result = await chrome.storage.session.get([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);341    return {342      stored: (result[PIN_WRAP_STORAGE] as StoredPinWrap | undefined) ??343        (sessionPinStorageFailed ? inMemoryPinWrap ?? undefined : undefined),344      failedAttempts: typeof result[PIN_ATTEMPTS_STORAGE] === "number"345        ? result[PIN_ATTEMPTS_STORAGE]346        : 0,347    };348  } catch {349    return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };350  }351}352353async function recordPinFailure(failedAttempts: number): Promise<void> {354  inMemoryPinFailedAttempts = Math.min(failedAttempts, PIN_MAX_ATTEMPTS);355  if (!chrome.storage.session) return;356  try {357    await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: inMemoryPinFailedAttempts });358  } catch { /* in-memory counter remains the fallback */ }359}360361async function resetPinFailedAttempts(): Promise<void> {362  inMemoryPinFailedAttempts = 0;363  if (!chrome.storage.session) return;364  try {365    await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: 0 });366  } catch { /* in-memory counter remains the fallback */ }367}368369export async function getPinUnlockStatus(): Promise<{370  configured: boolean;371  available: boolean;372  attemptsRemaining: number;373}> {374  await loadSettings();375  if (!settings.pinEnabled) {376    return { configured: false, available: false, attemptsRemaining: 0 };377  }378  const { stored, failedAttempts } = await loadPinState();379  const available = Boolean(stored) && failedAttempts < PIN_MAX_ATTEMPTS;380  return {381    configured: true,382    available,383    attemptsRemaining: stored ? Math.max(0, PIN_MAX_ATTEMPTS - failedAttempts) : 0,384  };385}386387async function persistSettings(): Promise<void> {388  try {389    await chrome.storage.local.set({390      peach_settings: {391        ...settings,392        manualSummonDomains: undefined,393        manualSummonSalt: undefined,394        cardFingerprintSalt: undefined,395        declinedCardFingerprints: settings.declinedCardFingerprints ?? [],396        metadataVersion: 1,397      },398    });399  } catch (err) {400    throw mapStorageError(err);401  }402}403404function mapStorageError(err: unknown): Error {405  const message = err instanceof Error ? err.message : String(err);406  if (/QUOTA_BYTES|quota/i.test(message)) {407    return new Error("STORAGE_QUOTA_EXCEEDED");408  }409  return err instanceof Error ? err : new Error(message);410}411412async function loadSettings(): Promise<void> {413  const result = await chrome.storage.local.get("peach_settings");414  settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};415}416417// Fire-and-forget sync trigger after a committed vault write. A failure here418// must never fail the write that caused it.419function fireSyncTrigger(reason: "vault_change"): void {420  void Promise.resolve()421    .then(() => triggerSyncIfReachable({ reason }))422    .catch(() => {423      /* no sync runner registered, or nothing reachable — non-fatal */424    });425}426export function lockedSyncRequiresUnlock(): boolean {427  return settings.lockedSyncRequiresUnlock === true;428}429430let lockedSyncRefreshHook: (() => Promise<void>) | null = null;431let lockedSyncUnlockHook: (() => Promise<void>) | null = null;432let decoySyncTeardownHook: (() => void) | null = null;433export type IdentityHooks = {434  /** Drop the cached identity: the session is no longer a real unlocked one. */435  onSessionEnded: () => Promise<void>;436  /** Re-wrap the identity under the keys now in force, after a vault key swap. */437  onKeysRotated: () => Promise<void>;438  /** Promote a pre-vault identity once a vault exists, given the password that created it. */439  onVaultCreated: (password: string) => Promise<void>;440};441442let identityHooks: IdentityHooks | null = null;443444export function setIdentityHooks(hooks: IdentityHooks): void {445  identityHooks = hooks;446}447448async function notifyIdentitySessionEnded(): Promise<void> {449  await identityHooks?.onSessionEnded().catch((error) => {450    console.warn("[Peach] local identity cache clear failed:", error);451  });452}453454async function notifyIdentityKeysRotated(): Promise<void> {455  await identityHooks?.onKeysRotated().catch((error) => {456    console.warn("[Peach] local identity re-wrap failed:", error);457  });458}459460export type SealedBox = { nonce: string; ciphertext: string; tag: string };461export type IdentityKeyEnvelope = {462  root?: SealedBox;463  local?: SealedBox;464  pending?: SealedBox;465  pendingSalt?: string;466};467468export function setLockedSyncHooks(hooks: {469  refresh: () => Promise<void>;470  afterUnlock: () => Promise<void>;471  onDecoy?: () => void;472}): void {473  lockedSyncRefreshHook = hooks.refresh;474  lockedSyncUnlockHook = hooks.afterUnlock;475  decoySyncTeardownHook = hooks.onDecoy ?? null;476}477478async function refreshLockedSyncState(): Promise<void> {479  if (vaultMode !== "real" || !rootKey || !lockedSyncRefreshHook) return;480  await lockedSyncRefreshHook().catch((error) => {481    console.warn("[Peach sync] locked spool refresh failed:", error);482  });483}484485// ---------------------------------------------------------------------------486// HIBP breach check (k-anonymity model)487// ---------------------------------------------------------------------------488489export async function checkBreach(password: string): Promise<number> {490  // HIBP k-anonymity API is keyed on SHA-1 prefixes — this is dictated by491  // the public API, not a security choice. Do not migrate to SHA-256 here.492  const encoder = new TextEncoder();493  const hashBuffer = await crypto.subtle.digest("SHA-1", encoder.encode(password));494  const hashHex = Array.from(new Uint8Array(hashBuffer))495    .map((b) => b.toString(16).padStart(2, "0"))496    .join("")497    .toUpperCase();498499  const prefix = hashHex.slice(0, 5);500  const suffix = hashHex.slice(5);501502  try {503    // PCH-02-007: request HIBP response padding so response length does not504    // reveal how many suffixes a queried prefix returned.505    const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`, {506      headers: { "Add-Padding": "true" },507    });508    if (!res.ok) return 0;509    const text = await res.text();510    const match = text.split("\r\n").find((l) => l.startsWith(suffix));511    return match ? parseInt(match.split(":")[1], 10) : 0;512  } catch {513    return 0; // Network unavailable — don't block514  }515}516517export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {518  // Unreachable from the message layer, which gates on isUnlocked first.519  const key = await cardDeclineKey();520  if (!key) return;521  const fingerprint = await cardFingerprint(last4, expMonth, expYear);522  await loadSettings();523  settings = {524    ...settings,525    declinedCardFingerprints: [526      // Legacy records predate the keyed digest and are silently dropped here:527      // they are 16 hex characters rather than 32, and are no longer accepted.528      ...(settings.declinedCardFingerprints ?? []).filter(529        (stored) => stored.length === CARD_DECLINE_DIGEST_HEX,530      ),531      await metadataDigest(fingerprint, key),532    ].slice(-CARD_DECLINE_MAX),533  };534  await persistSettings();535}536537export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {538  await loadSettings();539  const key = await cardDeclineKey();540  if (!key) return false;541  const fingerprint = await cardFingerprint(last4, expMonth, expYear);542  const candidate = await metadataDigest(fingerprint, key);543  return (settings.declinedCardFingerprints ?? []).some(544    (stored) => stored.length === CARD_DECLINE_DIGEST_HEX && stored === candidate,545  );546}547548/**549 * Keying material for the declined-card digest, derived from the vault root550 * key so it is available only while unlocked and never written to storage.551 *552 * PB-26-108: the previous scheme stored a random salt beside the records. A553 * salt defeats precomputed tables, not an attacker holding the file — the554 * candidate space here is ~10^4 last-four values x 12 months x a few years, so555 * a stored salt left the card's last four and expiry recoverable offline in556 * seconds. `peach_settings` is unencrypted and directly readable by a content557 * script on Firefox, so the key has to live outside storage entirely.558 */559async function cardDeclineKey(): Promise<string | null> {560  const root = getRootKeyHex();561  if (!root) return null;562  const digest = new Uint8Array(563    await crypto.subtle.digest(564      "SHA-256",565      new TextEncoder().encode(`peach-card-decline-v1:${root}`),566    ),567  );568  return hex(digest);569}570571async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {572  const encoder = new TextEncoder();573  const buf = await crypto.subtle.digest("SHA-256", encoder.encode(`${last4}|${expMonth}|${expYear}`));574  return Array.from(new Uint8Array(buf).slice(0, 8))575    .map((b) => b.toString(16).padStart(2, "0"))576    .join("");577}578579function hex(buf: Uint8Array): string {580  return Array.from(buf)581    .map((b) => b.toString(16).padStart(2, "0"))582    .join("");583}584585function unhex(s: string): Uint8Array {586  const out = new Uint8Array(s.length / 2);587  for (let i = 0; i < s.length; i += 2) {588    out[i / 2] = parseInt(s.slice(i, i + 2), 16);589  }590  return out;591}592593// ---------------------------------------------------------------------------594// Root key generation and recovery word wrapping595// ---------------------------------------------------------------------------596597/**598 * Generate a random 32-byte root key and wrap it (AES-256-GCM) under a key599 * derived from the recovery word material via HKDF-SHA256. The wrapped blob600 * fields are stored in slot A alongside the password-wrapped ciphertext. The601 * root key itself is kept in memory for the session so getRecoveryWords() can602 * encode it without re-deriving.603 *604 * SECURITY MODEL (PCH-01-005): the recovery KEK is derived from the 12-word605 * material, which encodes only rootKey[0..16] (recovery-words.ts). The KEK is thus606 * derived from a PREFIX of the very plaintext it wraps, and effective recovery607 * security is 128-bit (standard for a 12-word phrase), NOT 256-bit. This is safe —608 * unwrapping requires the words, and the GCM ciphertext leaks nothing without them —609 * but it is intentional, not an oversight. A future escrow version wanting 256-bit610 * recovery must derive the words from INDEPENDENT entropy, not from the root key.611 */612async function generateAndWrapRootKey(): Promise<{613  rawRootKey: string; // hex of the plaintext root key — caller stores in rootKey614  recoverySalt: string;615  wrappedRootKey: string;616  wrappedNonce: string;617  wrappedTag: string;618}> {619  const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));620  try {621622  // Derive the recovery key from the BIP39 words encoding of the root key.623  const words = await rootKeyToWords(rootKeyBytes);624  const wordMaterial = await wordsToRootKeyMaterial(words);625  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));626  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);627628  // Wrap the root key with the recovery key using AES-256-GCM directly.629  // We hex-encode rootKeyBytes so the plaintext is always valid UTF-8.630  const nonce = crypto.getRandomValues(new Uint8Array(12));631  const encoded = new TextEncoder().encode(hex(rootKeyBytes));632  const raw = await crypto.subtle.encrypt(633    {634      name: "AES-GCM",635      iv: nonce,636      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,637      tagLength: 128,638    },639    recoveryKey,640    encoded641  );642  // WebCrypto returns ciphertext || auth tag concatenated; split them.643  const rawU8 = new Uint8Array(raw);644  const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));645  const tag = hex(rawU8.slice(rawU8.length - 16));646647  return {648    rawRootKey: hex(rootKeyBytes),649    recoverySalt: hex(recoverySalt),650    wrappedRootKey: ciphertext,651    wrappedNonce: hex(nonce),652    wrappedTag: tag,653  };654  } finally { zeroKey(rootKeyBytes); }655}656657async function wrapExistingRootKeyForRecovery(rootKeyBytes: Uint8Array): Promise<{658  recoverySalt: string;659  wrappedRootKey: string;660  wrappedNonce: string;661  wrappedTag: string;662}> {663  if (rootKeyBytes.length !== 32) {664    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");665  }666667  const words = await rootKeyToWords(rootKeyBytes);668  const wordMaterial = await wordsToRootKeyMaterial(words);669  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));670  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);671  const nonce = crypto.getRandomValues(new Uint8Array(12));672  const encoded = new TextEncoder().encode(hex(rootKeyBytes));673  const raw = await crypto.subtle.encrypt(674    {675      name: "AES-GCM",676      iv: nonce,677      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,678      tagLength: 128,679    },680    recoveryKey,681    encoded,682  );683  const rawU8 = new Uint8Array(raw);684  return {685    recoverySalt: hex(recoverySalt),686    wrappedRootKey: hex(rawU8.slice(0, rawU8.length - 16)),687    wrappedNonce: hex(nonce),688    wrappedTag: hex(rawU8.slice(rawU8.length - 16)),689  };690}691692/**693 * Unwrap the root key using recovery words. Called during recovery flow when694 * the user provides their 12-word phrase and a new password.695 */696async function unwrapRootKeyForRecovery(697  wrappedRootKey: string,698  wrappedNonce: string,699  wrappedTag: string,700  recoverySaltHex: string,701  words: string[]702): Promise<Uint8Array> {703  const wordMaterial = await wordsToRootKeyMaterial(words);704  const recoverySalt = unhex(recoverySaltHex);705  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);706707  // The root key bytes were hex-encoded before708  // encryption so the ciphertext is valid UTF-8. We inline the AES-GCM decrypt709  // here to avoid passing a CryptoKey to the string-based encrypt/decrypt helpers.710  // Each component is stored separately in the vault slot; decode them individually711  // so the nonce is always exactly the 12 bytes from wrappedNonce.712  const nonceRaw = unhex(wrappedNonce);713  const ciphertextRaw = unhex(wrappedRootKey);714  const tagRaw = unhex(wrappedTag);715  // Combine ciphertext and tag for AES-GCM (expects ciphertext||tag).716  // Use explicit ArrayBuffer allocations to satisfy TS BufferSource constraints.717  const nonceU8 = nonceRaw as unknown as Uint8Array<ArrayBuffer>;718  const combined = new Uint8Array(ciphertextRaw.length + tagRaw.length);719  combined.set(ciphertextRaw, 0);720  combined.set(tagRaw, ciphertextRaw.length);721  const raw = await crypto.subtle.decrypt(722    { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },723    recoveryKey,724    combined725  );726  const decryptedHex = new TextDecoder().decode(raw);727  const recovered = unhex(decryptedHex);728  if (recovered.length !== 32) { zeroKey(recovered); throw new Error("invalid_recovery_words"); }729  return recovered;730}731732/// Recover a locked real vault without publishing keys before its stored payload authenticates.733export async function recoverWithWords(words: string[], newPassword: string): Promise<RecoveryResult> {734  if (recoveryInFlight || derivedKey) throw new Error("recovery_requires_lock");735  if (vaultWritesInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");736  recoveryInFlight = true;737  let settle!: () => void;738  recoverySettled = new Promise<void>((resolve) => { settle = resolve; });739  const epoch = ++vaultEpoch;740  const check = () => {741    if (epoch !== vaultEpoch || derivedKey) throw new Error("vault_locked");742  };743  let recoveredRoot: Uint8Array | null = null;744  let oldKey: Uint8Array | null = null;745  let newKey: Uint8Array | null = null;746  let committed = false;747  try {748    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);749    check();750    const slot = raw[SLOT_A] as StoredVault | undefined;751    if (!slot) throw new Error("no_vault");752    if (!slot.recovery_salt || !slot.recovery_wrapped_root_key) throw new Error("recovery_not_setup");753    try {754      recoveredRoot = await unwrapRootKeyForRecovery(slot.recovery_wrapped_root_key,755        slot.recovery_nonce ?? "", slot.recovery_tag ?? "", slot.recovery_salt, words);756    } catch {757      throw new Error("invalid_recovery_words");758    }759    check();760    if (!slot.recovery_vault_key) throw new Error("recovery_requires_password_unlock");761    oldKey = await openSealedKey(recoveredRoot, slot.recovery_vault_key, "recovery_vault_key_v1");762    check();763    if (!oldKey) throw new Error("recovery_data_unavailable");764    const result = await tryDecryptSlotResult(slot, oldKey, "slot_a_v1");765    check();766    if (result.status !== "ok") throw new Error("recovery_data_unavailable");767    const payload = result.payload;768    await loadSettings();769    check();770    const salt = generateSalt();771    newKey = await deriveKey(newPassword, salt);772    check();773    // Preserve the authenticated plaintext, including fields unknown to this build.774    const plaintext = await decrypt(oldKey, slot.nonce, slot.ciphertext, slot.tag, "slot_a_v1");775    const encrypted = await encrypt(newKey, plaintext, "slot_a_v1");776    const pwRoot = await wrapRootKeyForDerivedKey(newKey, recoveredRoot);777    const recoveryVaultKey = await encrypt(recoveredRoot, hex(newKey), "recovery_vault_key_v1");778    check();779    const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);780    check();781    if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");782    const history = raw[HISTORY_KEY] as VaultHistory | undefined;783    const snapshot: VaultSnapshot = {784      id: crypto.randomUUID(), savedAt: Date.now(), reason: "local_save",785      vault_a: JSON.stringify(slot), vault_b: JSON.stringify(raw[SLOT_B] ?? slot), entryCount: null,786    };787    const previousStamp = Number(raw.peach_last_modified_at);788    const nextSlot: StoredVault = { ...slot, ...encrypted, ...pwRoot,789      salt: hex(salt), recovery_vault_key: recoveryVaultKey };790    // One storage transaction keeps the rollback snapshot and all new-key fields together.791    await chrome.storage.local.set({792      [SLOT_A]: nextSlot,793      [HISTORY_KEY]: { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) },794      peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previousStamp) ? previousStamp + 1 : 0)),795    });796    committed = true;797    check();798    derivedKey = newKey;799    rootKey = recoveredRoot;800    newKey = null;801    recoveredRoot = null;802    entries = payload.entries;803    tombstones = payload.tombstones;804    duressConfigured = payload.duressConfigured;805    vaultMode = "real";806    buildDomainIndexSync(entries);807    await saveSessionKey(derivedKey, "real", epoch);808    if (epoch !== vaultEpoch) throw new Error("vault_locked");809    await identityHooks?.onKeysRotated();810    if (epoch !== vaultEpoch) throw new Error("vault_locked");811    await reconcilePairSecrets(rootKey);812    if (epoch !== vaultEpoch) throw new Error("vault_locked");813    await clearPinUnlockStorage();814    if (epoch !== vaultEpoch) throw new Error("vault_locked");815    touchAutoLock();816    return { committed: true, unlocked: true };817  } catch (error) {818    if (committed) {819      console.warn("[Peach] recovery password saved; unlock required:", error);820      if (derivedKey && epoch === vaultEpoch) {821        try { await lock(); }822        catch (lockError) { console.warn("[Peach] recovery session cleanup failed:", lockError); }823      }824      return { committed: true, unlocked: false };825    }826    if (derivedKey && epoch === vaultEpoch) await lock();827    throw error;828  } finally {829    if (oldKey) zeroKey(oldKey);830    if (newKey) zeroKey(newKey);831    if (recoveredRoot) zeroKey(recoveredRoot);832    recoveryInFlight = false;833    settle();834  }835}836837/// Cancel recovery and finish its issued storage write before removing vault data.838export async function withVaultRemoval<T>(remove: () => Promise<T>): Promise<T> {839  vaultRemovalEpoch++;840  vaultRemovalsInFlight++;841  try {842    await lock();843    await recoverySettled;844    await creationSettled;845    return await remove();846  } finally {847    vaultRemovalsInFlight--;848  }849}850851/**852 * Recover the session root key by AES-GCM-decrypting the pw_root_* fields853 * (a second wrapping of the root key under the password-derived key). This854 * is what makes GET_RECOVERY_WORDS work across lock/unlock cycles without855 * the user re-entering their recovery phrase: the same root key bytes —856 * and therefore the same 12 words — survive every unlock.857 *858 * Returns null when the escrow is absent or decryption fails.859 */860async function deriveRootKeyFromDerivedKey(861  derivedKeyBytes: Uint8Array,862  slotA: StoredVault,863): Promise<Uint8Array | null> {864  if (!slotA.pw_root_ciphertext || !slotA.pw_root_nonce || !slotA.pw_root_tag) {865    return null;866  }867  try {868    const rootHex = await decrypt(869      derivedKeyBytes,870      slotA.pw_root_nonce,871      slotA.pw_root_ciphertext,872      slotA.pw_root_tag,873      "pw_root_v1",874    );875    return unhex(rootHex);876  } catch {877    return null;878  }879}880881export async function sealIdentityKeyUnderVault(ik: Uint8Array): Promise<IdentityKeyEnvelope> {882  if (vaultMode !== "real" || !rootKey || !derivedKey) throw new Error("vault_locked");883  // The root wrap survives password change and recovery-words re-key; the884  // local wrap is available during normal unlock. Pending is only pre-vault.885  const [root, local] = await Promise.all([886    encrypt(rootKey, hex(ik), "peach-local-identity-ik-root-v1"),887    encrypt(derivedKey, hex(ik), "peach-local-identity-ik-local-v1"),888  ]);889  return { root, local };890}891892export async function sealIdentityKeyPreVault(893  password: string,894  ik: Uint8Array,895): Promise<IdentityKeyEnvelope> {896  const salt = generateSalt();897  const key = await deriveKey(password, salt);898  try {899    const pending = await encrypt(key, hex(ik), "peach-local-identity-ik-pending-v1");900    return { pending, pendingSalt: hex(salt) };901  } finally {902    zeroKey(key);903  }904}905906/**907 * Open the identity key with any wrapping key that is currently available:908 * the live vault-unlock key, then the vault root key, then the pre-vault909 * password. Each attempt is awaited only after the previous one fails, so a910 * successful early unwrap never leaves a later decrypt rejection unobserved,911 * and the pre-vault Argon2id is not paid when a vault key already opens the912 * envelope.913 */914export async function openIdentityKey(915  env: IdentityKeyEnvelope,916  password?: string,917): Promise<Uint8Array | null> {918  if (env.local && derivedKey) {919    const ik = await openSealedKey(derivedKey, env.local, "peach-local-identity-ik-local-v1");920    if (ik) return ik;921  }922  if (env.root && rootKey) {923    const ik = await openSealedKey(rootKey, env.root, "peach-local-identity-ik-root-v1");924    if (ik) return ik;925  }926  if (!env.pending || !env.pendingSalt || password === undefined) return null;927  let key: Uint8Array;928  try {929    const salt = unhex(env.pendingSalt);930    key = await deriveKey(password, salt);931    salt.fill(0);932  } catch {933    return null;934  }935  try {936    return await openSealedKey(key, env.pending, "peach-local-identity-ik-pending-v1");937  } finally {938    zeroKey(key);939  }940}941942/** Decrypt a sealed 32-byte key; null for a wrong key, a bad shape, or corrupt bytes. */943async function openSealedKey(944  key: Uint8Array,945  box: SealedBox,946  info: string,947): Promise<Uint8Array | null> {948  try {949    const value = unhex(await decrypt(key, box.nonce, box.ciphertext, box.tag, info));950    if (value.length === 32) return value;951    value.fill(0);952    return null;953  } catch {954    return null;955  }956}957958// AES-GCM-wrap rootKey under derivedKey for the pw_root_* fields. Returns the959// hex-encoded ciphertext/nonce/tag triple ready to embed in StoredVault.960async function wrapRootKeyForDerivedKey(961  derivedKeyBytes: Uint8Array,962  rootKeyBytes: Uint8Array,963): Promise<{ pw_root_ciphertext: string; pw_root_nonce: string; pw_root_tag: string }> {964  const { nonce, ciphertext, tag } = await encrypt(derivedKeyBytes, hex(rootKeyBytes), "pw_root_v1");965  return {966    pw_root_ciphertext: ciphertext,967    pw_root_nonce: nonce,968    pw_root_tag: tag,969  };970}971972/** Returns the 12 recovery words for the current session's root key. */973export async function getRecoveryWords(): Promise<string[]> {974  if (!rootKey) {975    throw new Error("recovery not set up");976  }977  return rootKeyToWords(rootKey);978}979980async function loadSlot(key: string): Promise<StoredVault | null> {981  const result = await chrome.storage.local.get(key);982  return (result as Record<string, StoredVault | undefined>)[key] ?? null;983}984985async function writeSlot(key: string, vault: StoredVault): Promise<void> {986  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");987  vaultWritesInFlight++;988  try {989    await chrome.storage.local.set({ [key]: vault });990  } catch (err) {991    throw mapStorageError(err);992  } finally {993    vaultWritesInFlight--;994  }995}996997/**998 * Roll back a vault that was created by [createVaultFromRootKey] but999 * couldn't be paired (e.g. the subsequent license activation, identity1000 * derivation, or paired-device upsert failed). Without this, a failed1001 * receiver session leaves behind an empty vault — the user has to1002 * re-pair to get a working setup, but the empty vault sits in the way.1003 *1004 * The call is idempotent: removing keys that aren't there is a no-op.1005 */1006export async function rollbackAdoptedVault(): Promise<void> {1007  await withVaultRemoval(async () => {1008    try {1009      await chrome.storage.local.remove([1010        SLOT_A,1011        SLOT_B,1012        "peach_last_modified_at",1013      ]);1014    } catch (err) {1015      throw mapStorageError(err);1016    }1017  });1018}10191020async function commitCreatedVaultSlots(slotA: StoredVault, slotB: StoredVault): Promise<void> {1021  if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1022  vaultWritesInFlight++;1023  try {1024    const raw = await chrome.storage.local.get("peach_last_modified_at");1025    const previous = Number(1026      (raw as Record<string, unknown>).peach_last_modified_at,1027    );1028    const next = Math.max(1029      Date.now(),1030      Number.isFinite(previous) ? previous + 1 : 0,1031    );1032    try {1033      if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1034      await chrome.storage.local.set({1035        [SLOT_A]: slotA,1036        [SLOT_B]: slotB,1037        peach_last_modified_at: String(next),1038      });1039    } catch (err) {1040      throw mapStorageError(err);1041    }1042  } finally {1043    vaultWritesInFlight--;1044  }1045}10461047// Monotonic clock for per-entry modifiedAt / deletedAt timestamps. Guards the1048// sync layer's last-write-wins merge against wall-clock regressions (NTP step,1049// manual clock change, DST glitch): a backwards Date.now() must never produce1050// an entry timestamp that's <= the entry's existing modifiedAt, or a genuine1051// local edit would lose to a stale remote copy. The returned value is always1052// strictly greater than both the entry's current modifiedAt and the previous1053// call's result (SEV-2-E).1054let lastEntryTimestamp = 0;1055function monotonicEntryTimestamp(currentModifiedAt?: number): number {1056  const base = Math.max(1057    Date.now(),1058    (currentModifiedAt ?? 0) + 1,1059    lastEntryTimestamp + 1,1060  );1061  lastEntryTimestamp = base;1062  return base;1063}10641065async function stampLocalVaultMutation(): Promise<void> {1066  if (vaultCreatesInFlight) throw new Error("vault_changed");1067  const raw = await chrome.storage.local.get("peach_last_modified_at");1068  const previous = Number(1069    (raw as Record<string, unknown>).peach_last_modified_at,1070  );1071  const next = Math.max(1072    Date.now(),1073    Number.isFinite(previous) ? previous + 1 : 0,1074  );1075  if (vaultCreatesInFlight) throw new Error("vault_changed");1076  await chrome.storage.local.set({1077    peach_last_modified_at: String(next),1078  });1079}10801081// ---------------------------------------------------------------------------1082// Padding + noise helpers1083// ---------------------------------------------------------------------------10841085/**1086 * Pads the plaintext string with trailing spaces so that the encoded byte1087 * length is a multiple of PAD_BLOCK. JSON.parse tolerates trailing1088 * whitespace after a complete document, so the padding is transparent on1089 * decode. Ciphertext length equals plaintext length plus a 16-byte tag.1090 */1091function padPlaintext(json: string, minBytes = 0): string {1092  const encoded = new TextEncoder().encode(json);1093  const bucket = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);1094  // minBytes lets the duress path force a fixed ceiling so both slots match.1095  const target = Math.max(bucket, minBytes);1096  const padLen = target - encoded.length;1097  return json + " ".repeat(padLen);1098}10991100/**1101 * Produces a StoredVault-shaped record filled with CSPRNG bytes. The1102 * ciphertext length matches the given byte count. Because GCM ciphertext is1103 * pseudo-random, this blob is indistinguishable at rest from a real1104 * encrypted vault without the key.1105 *1106 * crypto.getRandomValues() caps each call at 65536 bytes (the Web Crypto1107 * spec hard limit). Chunk the fill so vaults larger than that — common once1108 * the user has dozens of entries or any passkey — don't throw.1109 */1110const CSPRNG_CHUNK = 65_536;11111112function fillRandom(buf: Uint8Array): Uint8Array {1113  for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {1114    const end = Math.min(offset + CSPRNG_CHUNK, buf.length);1115    const chunk = new Uint8Array(end - offset);1116    crypto.getRandomValues(chunk);1117    buf.set(chunk, offset);1118  }1119  return buf;1120}11211122function generateNoiseBlob(ciphertextBytes: number): StoredVault {1123  const salt = crypto.getRandomValues(new Uint8Array(16));1124  const nonce = crypto.getRandomValues(new Uint8Array(12));1125  const cipher = fillRandom(new Uint8Array(ciphertextBytes));1126  const tag = crypto.getRandomValues(new Uint8Array(16));1127  return {1128    version: 1,1129    salt: hex(salt),1130    nonce: hex(nonce),1131    ciphertext: hex(cipher),1132    tag: hex(tag),1133  };1134}11351136// ---------------------------------------------------------------------------1137// Encrypted plaintext envelope1138// ---------------------------------------------------------------------------11391140type VaultPayload = {1141  entries: VaultEntry[];1142  tombstones?: Record<string, number>;1143  duressConfigured?: boolean;1144};11451146type DecryptedPayload = {1147  entries: VaultEntry[];1148  tombstones: Map<string, number>;1149  duressConfigured: boolean;1150};11511152function encodePayload(entries: VaultEntry[], duress: boolean, minBytes = 0): string {1153  const envelope: VaultPayload = {1154    entries,1155    tombstones: Object.fromEntries(tombstones),1156    duressConfigured: duress,1157  };1158  return padPlaintext(JSON.stringify(envelope), minBytes);1159}11601161function decodeTombstones(raw: unknown, allEntries: VaultEntry[]): Map<string, number> {1162  const result = new Map<string, number>();1163  if (raw && typeof raw === "object" && !Array.isArray(raw)) {1164    for (const [id, timestamp] of Object.entries(raw as Record<string, unknown>)) {1165      if (typeof timestamp === "number" && Number.isFinite(timestamp) && timestamp > 0) {1166        result.set(id, timestamp);1167      }1168    }1169  }1170  // Older payloads had no ledger. Rebuild the durable portion from any1171  // soft-deleted entries before they are eligible for a later purge.1172  for (const entry of allEntries) {1173    if (typeof entry.deletedAt !== "number" || !Number.isFinite(entry.deletedAt) || entry.deletedAt <= 0) {1174      continue;1175    }1176    if ((result.get(entry.id) ?? 0) < entry.deletedAt) {1177      result.set(entry.id, entry.deletedAt);1178    }1179  }1180  return result;1181}11821183function reconcileTombstones(): void {1184  const byId = new Map(entries.map((entry) => [entry.id, entry]));1185  for (const [id] of tombstones) {1186    if (byId.has(id) && !byId.get(id)?.deletedAt) tombstones.delete(id);1187  }1188  for (const entry of entries) {1189    if (typeof entry.deletedAt === "number" && Number.isFinite(entry.deletedAt) && entry.deletedAt > 0) {1190      if ((tombstones.get(entry.id) ?? 0) < entry.deletedAt) {1191        tombstones.set(entry.id, entry.deletedAt);1192      }1193    }1194  }1195}11961197function decodePayload(plain: string): DecryptedPayload {1198  const parsed = JSON.parse(plain) as VaultPayload;1199  if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.entries)) {1200    throw new Error("invalid vault payload");1201  }1202  const normalized = parsed.entries.map(normalizeEntry);1203  return {1204    entries: normalized,1205    tombstones: decodeTombstones(parsed.tombstones, normalized),1206    duressConfigured: parsed.duressConfigured === true,1207  };1208}12091210// Keep ambiguous records intact: an RP or account can own several credentials.1211function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {1212  let merged = false;1213  const transferable = new Set(["id", "type", "title", "username", "url", "passkey", "createdAt", "modifiedAt", "totp", "totpAlgorithm", "totpDigits", "totpPeriod"]);1214  for (const source of entries.filter((entry) => !entry.deletedAt && entry.passkey)) {1215    const passkey = source.passkey!;1216    if (source.type !== "login" && source.type !== "passkey") continue;1217    if (!passkey.userName || (source.username && source.username !== passkey.userName)) continue;1218    if (Object.entries(source).some(([key, value]) => !transferable.has(key) && value !== undefined && value !== "")) continue;1219    const targets = entries.filter((entry) => {1220      if (entry.deletedAt || entry.passkey || entry.type !== "login" || entry.username !== passkey.userName) return false;1221      return [entry.url, ...(entry.additionalUrls ?? [])].some((url) => {1222        if (!url) return false;1223        try {1224          return new URL(url.includes("://") ? url : `https://${url}`).hostname === passkey.rpId;1225        } catch {1226          return false;1227        }1228      });1229    });1230    if (targets.length !== 1) continue;1231    const target = targets[0]!;1232    if (source.totp && target.totp && (source.totp !== target.totp || source.totpAlgorithm !== target.totpAlgorithm || source.totpDigits !== target.totpDigits || source.totpPeriod !== target.totpPeriod)) continue;1233    target.passkey = passkey;1234    if (source.totp && !target.totp) {1235      target.totp = source.totp;1236      target.totpAlgorithm = source.totpAlgorithm;1237      target.totpDigits = source.totpDigits;1238      target.totpPeriod = source.totpPeriod;1239    }1240    const stamp = monotonicEntryTimestamp(Math.max(source.modifiedAt, target.modifiedAt));1241    target.modifiedAt = stamp;1242    source.modifiedAt = stamp;1243    source.deletedAt = stamp;1244    merged = true;1245  }1246  return { merged };1247}12481249// Validates that a `StoredVault` record on disk has the field shape we expect1250// before treating an AES-GCM decrypt success as a clean unlock. AES-GCM only1251// authenticates the static VERSION_BYTE AAD, not the `version` field on the1252// outer record — a corrupted `version: 42` slot still decrypts cleanly. This1253// check surfaces that as `corrupted` (M7/COR-007) so the popup can offer a1254// history-restore path instead of falsely reporting "wrong password".1255function hasValidVaultSchema(v: unknown): v is StoredVault {1256  if (typeof v !== "object" || v === null) return false;1257  const r = v as Record<string, unknown>;1258  return (1259    r.version === 1 &&1260    typeof r.salt === "string" &&1261    typeof r.nonce === "string" &&1262    typeof r.ciphertext === "string" &&1263    typeof r.tag === "string"1264  );1265}1266const MAX_HISTORY_BLOB_BYTES = 1_024 * 1_024;12671268function hasValidHistorySlot(value: unknown): value is StoredVault {1269  if (!hasValidVaultSchema(value)) return false;1270  return /^[0-9a-f]{32}$/i.test(value.salt) &&1271    /^[0-9a-f]{24}$/i.test(value.nonce) &&1272    /^[0-9a-f]+$/i.test(value.ciphertext) &&1273    value.ciphertext.length % 2 === 0 &&1274    value.ciphertext.length / 2 <= MAX_HISTORY_BLOB_BYTES &&1275    /^[0-9a-f]{32}$/i.test(value.tag);1276}12771278function parseHistorySlot(value: string): StoredVault | null {1279  try {1280    const parsed: unknown = JSON.parse(value);1281    return hasValidHistorySlot(parsed) ? parsed : null;1282  } catch {1283    return null;1284  }1285}12861287function isHistoryRecord(value: unknown): value is VaultSnapshot {1288  if (typeof value !== "object" || value === null) return false;1289  const record = value as Record<string, unknown>;1290  return typeof record.id === "string" && record.id.length > 0 && record.id.length <= 128 &&1291    typeof record.savedAt === "number" && Number.isFinite(record.savedAt) &&1292    typeof record.reason === "string" &&1293    typeof record.vault_a === "string" && record.vault_a.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1294    typeof record.vault_b === "string" && record.vault_b.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1295    (record.entryCount === null || typeof record.entryCount === "number");1296}12971298function sanitizeHistory(value: unknown): VaultSnapshot[] {1299  if (typeof value !== "object" || value === null) return [];1300  if (!("snapshots" in value) || !Array.isArray(value.snapshots)) return [];1301  return value.snapshots.filter(isHistoryRecord).slice(0, HISTORY_MAX);1302}13031304export type TryDecryptResult =1305  | { status: "ok"; payload: DecryptedPayload }1306  | { status: "wrong_key" }1307  | { status: "corrupted"; reason: string };13081309// Exported solely for `unlockFromCodex` below, which needs to verify a1310// supplied passphrase against a slotA blob *without* committing anything to1311// storage. Keep this internal otherwise — callers crossing the messages.ts1312// boundary should always go through `unlock` / `verifyMainPassword` so the1313// constant-time invariants in Projects.md §3.4 are not bypassed.1314export async function tryDecryptSlot(1315  vault: StoredVault,1316  key: Uint8Array,1317  aadTag?: string,1318): Promise<DecryptedPayload | null> {1319  const res = await tryDecryptSlotResult(vault, key, aadTag);1320  return res.status === "ok" ? res.payload : null;1321}13221323export async function tryDecryptSlotResult(1324  vault: StoredVault,1325  key: Uint8Array,1326  aadTag?: string,1327): Promise<TryDecryptResult> {1328  if (!hasValidVaultSchema(vault)) {1329    return { status: "corrupted", reason: "invalid_slot_schema" };1330  }1331  let plain: string;1332  try {1333    plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);1334  } catch {1335    return { status: "wrong_key" };1336  }1337  try {1338    const parsed = JSON.parse(plain) as unknown;1339    if (typeof parsed !== "object" || parsed === null) {1340      return { status: "corrupted", reason: "invalid_payload_shape" };1341    }1342    if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {1343      return { status: "corrupted", reason: "invalid_payload_shape" };1344    }1345    return { status: "ok", payload: decodePayload(plain) };1346  } catch {1347    return { status: "corrupted", reason: "invalid_payload_json" };1348  }1349}13501351// ---------------------------------------------------------------------------1352// Core operations1353// ---------------------------------------------------------------------------13541355function buildDomainIndexSync(all: VaultEntry[]): void {1356  domainIndex = new Map();13571358  for (const entry of all) {1359    if (entry.deletedAt) continue;1360    if (entry.type === "note" || entry.type === "card") continue;13611362    // An entry can match multiple sites via `additionalUrls`. Index each1363    // hostname so `queryDomain` returns the entry regardless of which alias1364    // the user is currently visiting. Dedupe per-entry so a single entry1365    // never appears twice in one bucket.1366    const domains = new Set<string>();1367    const primary = extractDomain(entry.url ?? "");1368    if (primary) domains.add(primary);1369    for (const extra of entry.additionalUrls ?? []) {1370      const d = extractDomain(extra);1371      if (d) domains.add(d);1372    }1373    if (domains.size === 0) continue;13741375    for (const domain of domains) {1376      const bucket = domainIndex.get(domain) ?? [];1377      bucket.push(entry);1378      domainIndex.set(domain, bucket);1379    }1380  }1381}13821383export async function createVault(password: string, replacement?: "warned-import"): Promise<{ committed: true; unlocked: boolean }> {1384  if (replacement !== undefined && replacement !== "warned-import") throw new Error("invalid_payload");1385  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");1386  vaultCreatesInFlight++;1387  let settle!: () => void;1388  creationSettled = new Promise<void>((resolve) => { settle = resolve; });1389  let nextKey: Uint8Array | null = null;1390  let nextRoot: Uint8Array | null = null;1391  let committed = false;1392  let publishedEpoch: number | null = null;1393  const epoch = vaultEpoch;1394  const check = () => {1395    if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1396  };1397  try {1398    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1399    check();1400    const occupied = raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;1401    if (occupied && replacement !== "warned-import") throw new Error("vault_already_exists");1402    const salt = generateSalt();1403    nextKey = await deriveKey(password, salt);1404    check();1405    const recovery = await generateAndWrapRootKey();1406    nextRoot = unhex(recovery.rawRootKey);1407    check();1408    const encrypted = await encrypt(nextKey, encodePayload([], false, 0), "slot_a_v1");1409    const pwRoot = await wrapRootKeyForDerivedKey(nextKey, nextRoot);1410    const recoveryVaultKey = await encrypt(nextRoot, hex(nextKey), "recovery_vault_key_v1");1411    check();1412    const slotA: StoredVault = {1413      ...encrypted, ...pwRoot, version: 1, salt: hex(salt),1414      recovery_vault_key: recoveryVaultKey,1415      recovery_salt: recovery.recoverySalt,1416      recovery_wrapped_root_key: recovery.wrappedRootKey,1417      recovery_nonce: recovery.wrappedNonce,1418      recovery_tag: recovery.wrappedTag,1419    };1420    const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1421    check();1422    if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");1423    const previous = Number(raw.peach_last_modified_at);1424    const update: Record<string, unknown> = {1425      [SLOT_A]: slotA, [SLOT_B]: generateNoiseBlob(encrypted.ciphertext.length / 2),1426      peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previous) ? previous + 1 : 0)),1427    };1428    if (occupied) {1429      const history = raw[HISTORY_KEY] as VaultHistory | undefined;1430      const snapshot: VaultSnapshot = {1431        id: crypto.randomUUID(), savedAt: Date.now(), reason: "restore", entryCount: null,1432        vault_a: JSON.stringify(raw[SLOT_A] ?? null), vault_b: JSON.stringify(raw[SLOT_B] ?? null),1433      };1434      update[HISTORY_KEY] = { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) };1435    }1436    try { await chrome.storage.local.set(update); }1437    catch (error) { throw mapStorageError(error); }1438    committed = true;1439    if (epoch !== vaultEpoch || vaultRemovalsInFlight) return { committed: true, unlocked: false };1440    const previousKey = derivedKey;1441    const previousRoot = rootKey;1442    publishedEpoch = ++vaultEpoch;1443    derivedKey = nextKey;1444    rootKey = nextRoot;1445    nextKey = null;1446    nextRoot = null;1447    entries = [];1448    tombstones = new Map();1449    vaultMode = "real";1450    duressConfigured = false;1451    buildDomainIndexSync(entries);1452    if (previousKey) zeroKey(previousKey);1453    if (previousRoot) zeroKey(previousRoot);1454    await clearSessionKey();1455    if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1456    await identityHooks?.onVaultCreated(password).catch((error) => {1457      console.warn("[Peach] local identity promotion failed:", error);1458    });1459    if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1460    touchAutoLock();1461    return { committed: true, unlocked: true };1462  } catch (error) {1463    if (!committed) throw error;1464    console.warn("[Peach] vault saved; unlock required:", error);1465    if (publishedEpoch === vaultEpoch) {1466      await lock().catch((lockError) => console.warn("[Peach] creation session cleanup failed:", lockError));1467    }1468    return { committed: true, unlocked: false };1469  } finally {1470    if (nextKey) zeroKey(nextKey);1471    if (nextRoot) zeroKey(nextRoot);1472    vaultCreatesInFlight--;1473    settle();1474  }1475}14761477/**1478 * Creates a local vault from an existing vault root key received through the1479 * SAS-gated adoption protocol. The password is local to this device; it wraps1480 * the adopted root key at rest and does not need to match the source device.1481 */1482export async function createVaultFromRootKey(1483  password: string,1484  rootKeyHex: string,1485): Promise<{ vaultId: string }> {1486  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");1487  if (typeof password !== "string" || password.length === 0) {1488    throw new Error("ADOPT_INVALID_PASSWORD");1489  }1490  if (typeof rootKeyHex !== "string" || !/^[0-9a-f]{64}$/.test(rootKeyHex)) {1491    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars");1492  }14931494  if (vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");1495  const rootKeyBytes = unhex(rootKeyHex);1496  if (rootKeyBytes.length !== 32) {1497    rootKeyBytes.fill(0);1498    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");1499  }15001501  vaultCreatesInFlight++;1502  let settle!: () => void;1503  creationSettled = new Promise<void>((resolve) => { settle = resolve; });1504  const epoch = vaultEpoch;1505  let nextDerivedKey: Uint8Array | null = null;1506  let sessionRootKey: Uint8Array | null = null;1507  let committed = false;1508  try {1509    if (await hasVault()) {1510      throw new Error("ADOPT_VAULT_ALREADY_EXISTS");1511    }15121513    const nextEntries: VaultEntry[] = [];1514    const nextDuressConfigured = false;1515    const vaultId = await computeVaultId(rootKeyBytes);1516    const salt = generateSalt();1517    nextDerivedKey = await deriveKey(password, salt);1518    const recovery = await wrapExistingRootKeyForRecovery(rootKeyBytes);15191520    sessionRootKey = new Uint8Array(rootKeyBytes);1521    const plaintext = encodePayload(nextEntries, nextDuressConfigured, 0);1522    const { nonce, ciphertext, tag } = await encrypt(nextDerivedKey, plaintext, "slot_a_v1");1523    const pwRoot = await wrapRootKeyForDerivedKey(nextDerivedKey, sessionRootKey);1524    const slotA: StoredVault = {1525      recovery_vault_key: await encrypt(sessionRootKey, hex(nextDerivedKey), "recovery_vault_key_v1"),1526      version: 1,1527      salt: hex(salt),1528      nonce,1529      ciphertext,1530      tag,1531      recovery_salt: recovery.recoverySalt,1532      recovery_wrapped_root_key: recovery.wrappedRootKey,1533      recovery_nonce: recovery.wrappedNonce,1534      recovery_tag: recovery.wrappedTag,1535      ...pwRoot,1536    };1537    const slotB = generateNoiseBlob(ciphertext.length / 2);1538    if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1539    await commitCreatedVaultSlots(slotA, slotB);1540    committed = true;1541    if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1542    vaultEpoch++;15431544    const previousDerivedKey = derivedKey;1545    const previousRootKey = rootKey;1546    derivedKey = nextDerivedKey;1547    rootKey = sessionRootKey;1548    nextDerivedKey = null;1549    sessionRootKey = null;1550    entries = nextEntries;1551    tombstones = new Map();1552    vaultMode = "real";1553    duressConfigured = nextDuressConfigured;1554    buildDomainIndexSync(entries);1555    if (previousDerivedKey && previousDerivedKey !== derivedKey) zeroKey(previousDerivedKey);1556    if (previousRootKey && previousRootKey !== rootKey) previousRootKey.fill(0);1557    touchAutoLock();15581559    // The receiver's identity was minted before this vault existed (adoption v21560    // needs it in its first frame), so re-seal it under the vault keys now.1561    await identityHooks?.onVaultCreated(password).catch((error) => {1562      console.warn("[Peach] local identity promotion failed:", error);1563    });15641565    return { vaultId };1566  } catch (error) {1567    if (committed) {1568      // Removal cannot use withVaultRemoval while this operation owns creationSettled.1569      try { await lock(); }1570      finally { await chrome.storage.local.remove([SLOT_A, SLOT_B, "peach_last_modified_at"]); }1571    }1572    throw error;1573  } finally {1574    vaultCreatesInFlight--;1575    settle();1576    rootKeyBytes.fill(0);1577    if (nextDerivedKey) zeroKey(nextDerivedKey);1578    if (sessionRootKey) sessionRootKey.fill(0);1579  }1580}15811582export async function hasVault(): Promise<boolean> {1583  const raw = await chrome.storage.local.get([SLOT_A, SLOT_B]);1584  return raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;1585}15861587/**1588 * Returns whether the real vault has recorded that a duress passphrase is1589 * configured. Reliable only after a real-mode unlock — before unlock or in1590 * decoy mode, returns false because we cannot read slot A's plaintext.1591 */1592export async function isDuressEnabled(): Promise<boolean> {1593  return vaultMode === "real" && duressConfigured;1594}15951596export async function setupDuress(duressPassword: string): Promise<void> {1597  if (vaultCreatesInFlight) throw new Error("vault_changed");1598  vaultWritesInFlight++;1599  try {1600  if (!derivedKey || vaultMode !== "real") {1601    throw new Error("vault must be unlocked in real mode");1602  }1603  // Encrypt the decoy payload (empty entries) under the duress key. Pad to1604  // at least the current slot A ciphertext size so the two slots look the1605  // same at rest at setup time.1606  const slotA = await loadSlot(SLOT_A);1607  if (!slotA) throw new Error("missing slot A");16081609  const decoySalt = generateSalt();1610  const decoyKey = await deriveKey(duressPassword, decoySalt);1611  try {1612    // Pad the decoy to the fixed duress ceiling. Slot A is re-encrypted to the1613    // same ceiling by the persistSlotA() call below (duressConfigured is now1614    // true), so both slots are exactly DURESS_SLOT_SIZE+tag at rest and their1615    // lengths cannot reveal that duress is configured (audit MEDIUM).1616    const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);1617    const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");1618    await writeSlot(SLOT_B, {1619      version: 1,1620      salt: hex(decoySalt),1621      nonce,1622      ciphertext,1623      tag,1624    });1625  } finally {1626    zeroKey(decoyKey);1627  }16281629  // Re-encrypt slot A with the duressConfigured flag set to true. No external1630  // flag is written — the bit lives inside the encrypted envelope.1631  duressConfigured = true;1632  await persistSlotA();1633  } finally { vaultWritesInFlight--; }1634}16351636export async function disableDuress(): Promise<void> {1637  if (vaultCreatesInFlight) throw new Error("vault_changed");1638  vaultWritesInFlight++;1639  try {1640  if (!derivedKey || vaultMode !== "real") {1641    throw new Error("vault must be unlocked in real mode");1642  }1643  // Overwrite slot B with fresh noise that matches slot A's size. The slot1644  // remains occupied so its mere existence does not signal that duress was1645  // ever configured.1646  const slotA = await loadSlot(SLOT_A);1647  if (slotA) {1648    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));1649  }16501651  duressConfigured = false;1652  await persistSlotA();1653  } finally { vaultWritesInFlight--; }1654}16551656// L14/COR-015: this function intentionally checks slot A (real vault) only.1657// A duress-mode user attempting changePassword is rejected earlier by the1658// vaultMode === 'decoy' check at changePassword. The real-vs-decoy1659// distinction here is by design — duress users cannot rotate the real1660// password by guessing it, and the asymmetry in error timing is acceptable1661// because duress mode is opt-in and the user knows their own decoy key.1662export async function verifyMainPassword(password: string): Promise<boolean> {1663  const slotA = await loadSlot(SLOT_A);1664  if (!slotA) return false;1665  const key = await deriveKey(password, unhex(slotA.salt));1666  try {1667    return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;1668  } finally {1669    zeroKey(key);1670  }1671}16721673export async function unlock(password: string): Promise<boolean> {1674  return attemptUnlockWithDerive(password, deriveKey);1675}16761677async function attemptUnlockWithDerive(1678  password: string,1679  derive: typeof deriveKey,1680): Promise<boolean> {1681  vaultUnlocksInFlight++;1682  try {1683  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;1684  const epoch = vaultEpoch;1685  const stale = () => epoch !== vaultEpoch;1686  await revokeRecoveryReveal();1687  if (stale()) return false;1688  // Load both current-format slots in parallel. Both exist on a supported1689  // install; the1690  // parallel load and the parallel derivation below keep wall-clock time1691  // constant regardless of which slot's passphrase (real or decoy) the1692  // caller supplied, so a timing side channel cannot distinguish the1693  // duress path from the real-unlock path (DUR-002).1694  const [slotA, slotB] = await Promise.all([1695    loadSlot(SLOT_A),1696    loadSlot(SLOT_B),1697  ]);16981699  // Derive both keys in parallel, unconditionally.1700  const [keyA, keyB] = await Promise.all([1701    slotA ? derive(password, unhex(slotA.salt)) : Promise.resolve(null),1702    slotB ? derive(password, unhex(slotB.salt)) : Promise.resolve(null),1703  ]);17041705  // Attempt both decrypts in parallel. The Result variant lets us distinguish1706  // 'wrong_key' from 'corrupted' so callers can offer a history-restore path1707  // when a slot's schema is invalid even though AES-GCM authenticated (M7).1708  const [resultA, resultB] = await Promise.all([1709    keyA && slotA1710      ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")1711      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1712    keyB && slotB1713      ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")1714      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1715  ]);1716  const payloadA = resultA.status === "ok" ? resultA.payload : null;1717  const payloadB = resultB.status === "ok" ? resultB.payload : null;17181719  if (stale()) {1720    if (keyA) zeroKey(keyA);1721    if (keyB) zeroKey(keyB);1722    return false;1723  }17241725  if (payloadA && keyA) {1726    if (stale()) {1727      zeroKey(keyA);1728      if (keyB) zeroKey(keyB);1729      return false;1730    }1731    derivedKey = keyA;1732    vaultMode = "real";1733    entries = payloadA.entries;1734    tombstones = payloadA.tombstones;1735    duressConfigured = payloadA.duressConfigured;1736    buildDomainIndexSync(entries);1737    await loadSettings();1738    if (stale()) {1739      await lock();1740      return false;1741    }1742    touchAutoLock();1743    if (keyB) zeroKey(keyB);17441745    // Current vaults always carry a password-wrapped root key. Older vaults1746    // without this escrow are outside the supported storage format.1747    rootKey = slotA ? await deriveRootKeyFromDerivedKey(keyA, slotA) : null;1748    if (!rootKey) {1749      await lock();1750      return false;1751    }17521753    // Repair missing or stale escrow only after a real password authenticates the slot.1754    if (slotA) {1755      const escrowed = slotA.recovery_vault_key1756        ? await openSealedKey(rootKey, slotA.recovery_vault_key, "recovery_vault_key_v1") : null;1757      const matches = escrowed !== null && escrowed.every((byte, i) => byte === keyA[i]);1758      if (escrowed) zeroKey(escrowed);1759      if (stale()) { await lock(); return false; }1760      if (!matches) {1761        try {1762          const recoveryVaultKey = await encrypt(rootKey, hex(keyA), "recovery_vault_key_v1");1763          if (stale()) { await lock(); return false; }1764          await writeSlot(SLOT_A, { ...slotA, recovery_vault_key: recoveryVaultKey });1765          if (stale()) { await lock(); return false; }1766        } catch (error) {1767          await lock();1768          throw error;1769        }1770      }1771    }17721773    // PB-26-213: adopt legacy plaintext pair secrets into the encrypted1774    // record and refresh the trusted-session operational copy.1775    await reconcilePairSecrets(rootKey);1776    if (stale()) {1777      await lock();1778      return false;1779    }1780    await lockedSyncUnlockHook?.().catch((error) => {1781      console.warn("[Peach sync] locked inbox drain failed:", error);1782    });1783    if (stale()) {1784      await lock();1785      return false;1786    }1787    await resetPinFailedAttempts();1788    if (stale()) {1789      await lock();1790      return false;1791    }1792    await saveSessionKey(keyA, "real", epoch);1793    if (stale()) return false;1794    return true;1795  }17961797  if (payloadB && keyB) {1798    if (stale()) {1799      zeroKey(keyB);1800      if (keyA) zeroKey(keyA);1801      return false;1802    }1803    derivedKey = keyB;1804    vaultMode = "decoy";1805    decoySyncTeardownHook?.();1806    // A duress session must not retain the real vault's root key. It gates the1807    // recovery words, the sync identity, and the root wrap of the local device1808    // identity, so leaving it live would expose all three in duress mode.1809    if (rootKey) {1810      rootKey.fill(0);1811      rootKey = null;1812    }1813    entries = payloadB.entries;1814    tombstones = payloadB.tombstones;1815    duressConfigured = false;1816    buildDomainIndexSync(entries);1817    await loadSettings();1818    touchAutoLock();1819    if (keyA) zeroKey(keyA);1820    // PB-26-213: a duress session must never serve the real pair-secret map.1821    await dropSessionCache();1822    // Nor the real device identity: a duress session is not a real one.1823    await notifyIdentitySessionEnded();1824    if (stale()) {1825      await lock();1826      return false;1827    }1828    await saveSessionKey(keyB, "decoy", epoch);1829    if (stale()) return false;1830    return true;1831  }18321833  if (keyA) zeroKey(keyA);1834  if (keyB) zeroKey(keyB);1835  // Surface corruption (good AES tag, broken schema) distinctly from1836  // wrong-password so the popup can offer history-restore (M7/COR-007).1837  if (resultA.status === "corrupted") {1838    lastUnlockFailureReason = resultA.reason;1839  } else if (resultB.status === "corrupted") {1840    lastUnlockFailureReason = resultB.reason;1841  }1842  return false;1843  } finally { vaultUnlocksInFlight--; }1844}18451846// ---------------------------------------------------------------------------1847// MV3 service worker session key — survives SW restarts within a browser session1848// ---------------------------------------------------------------------------18491850// chrome.storage.session is cleared on browser close; survives SW restart.1851// Firefox does not implement it (persistent background script, no restart risk).1852const SESSION_KEY_STORAGE = "peach_session_dk";18531854// Order writes and removals so lock's awaited removal is a barrier after1855// every escrow write that started before it.1856let sessionKeyMutation = Promise.resolve();18571858function mutateSessionKey(mutation: () => Promise<void>): Promise<void> {1859  const task = sessionKeyMutation.then(mutation, mutation);1860  sessionKeyMutation = task.catch(() => undefined);1861  return task;1862}18631864// PB-26-203: the session-key escrow may only operate where startup positively1865// established trusted-only session storage. Defaults to available so direct1866// vault imports (tests, non-entry bootstraps) keep working; entry.ts applies1867// the real hardening result before the first restore.1868let sessionEscrowAvailable = true;18691870/**1871 * Apply the storage-hardening result at startup. When the trusted-only1872 * session state cannot be established, any stored session key is removed and1873 * the escrow stays off: the user unlocks again after a worker restart1874 * instead of trusting an unproven boundary.1875 */1876export async function applyStorageHardening(sessionEscrow: boolean): Promise<void> {1877  setSessionAllowed(sessionEscrow);1878  if (sessionEscrow) return;1879  sessionEscrowAvailable = false;1880  await clearSessionKey();1881}18821883async function saveSessionKey(1884  key: Uint8Array,1885  mode: "real" | "decoy",1886  expectedEpoch = vaultEpoch,1887): Promise<void> {1888  const session = chrome.storage.session;1889  if (!session || !sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;1890  const stored = { keyHex: hex(key), mode };1891  await mutateSessionKey(async () => {1892    if (!sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;1893    await session.set({ [SESSION_KEY_STORAGE]: stored });1894  });1895}18961897async function clearSessionKey(): Promise<void> {1898  const session = chrome.storage.session;1899  if (!session) return;1900  await mutateSessionKey(() => session.remove(SESSION_KEY_STORAGE));1901}19021903// A lock that only holds while the service worker stays alive is no lock at1904// all: a cold worker's restoreFromSession() would find the surviving session1905// key and silently re-unlock ~a minute after the user locked. So lock()1906// bumps this epoch synchronously at entry and zeroes keys/indexes before any1907// await; a restore that started earlier sees the mismatch after its next1908// await and aborts instead of publishing.1909let vaultEpoch = 0;19101911// One in-flight restore shared by concurrent callers: storage is read once1912// and the locked-sync unlock hook runs once.1913let restoreInFlight: Promise<boolean> | null = null;19141915/**1916 * On SW restart, re-derive all in-memory vault state from the session key1917 * stored in chrome.storage.session (set at unlock time, cleared by lock();1918 * also cleared on browser close or when restoration fails).1919 * Returns true if the vault was restored, false if no session key was found.1920 * No-ops if the vault is already unlocked.1921 */1922export async function restoreFromSession(): Promise<boolean> {1923  vaultUnlocksInFlight++;1924  try {1925  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;1926  if (derivedKey !== null) return true;1927  if (restoreInFlight) return restoreInFlight;1928  const task = restoreFromSessionInner();1929  restoreInFlight = task;1930  try {1931    return await task;1932  } finally {1933    restoreInFlight = null;1934  }1935  } finally { vaultUnlocksInFlight--; }1936}19371938async function restoreFromSessionInner(): Promise<boolean> {1939  const epoch = vaultEpoch;1940  const stale = () => epoch !== vaultEpoch;1941  if (derivedKey !== null) return true;1942  if (!sessionEscrowAvailable) return false;1943  if (!chrome.storage.session) return false;1944  const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);1945  if (stale()) return false;1946  const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;1947  if (!entry?.keyHex) return false;19481949  const key = unhex(entry.keyHex);1950  const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;1951  const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";1952  const slot = await loadSlot(slotKey);1953  if (stale()) { zeroKey(key); return false; }1954  if (!slot) { await clearSessionKey(); return false; }19551956  const result = await tryDecryptSlotResult(slot, key, aadTag);1957  if (stale()) { zeroKey(key); return false; }1958  if (result.status !== "ok") { await clearSessionKey(); return false; }19591960  // Decrypted payload stays in locals until the final epoch-checked commit1961  // below; nothing observable is published before then.1962  const payload = result.payload;1963  await loadSettings();1964  if (stale()) { zeroKey(key); return false; }19651966  // Rehydrate the root key used by sync identity derivation from the password1967  // escrow stored on the current vault format.1968  let freshRoot: Uint8Array | null = null;1969  if (entry.mode === "real") {1970    freshRoot = await deriveRootKeyFromDerivedKey(key, slot);1971    if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }1972    if (!freshRoot) {1973      await lock();1974      return false;1975    }1976  }19771978  if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }1979  if (freshRoot) {1980    // PB-26-213: encrypted pair-secret record + session copy, before publish.1981    await reconcilePairSecrets(freshRoot);1982    if (stale()) { zeroKey(key); zeroKey(freshRoot); return false; }1983  } else {1984    // PB-26-213: a duress restore must never serve the real pair-secret map.1985    await dropSessionCache();1986    // Nor the real device identity.1987    await notifyIdentitySessionEnded();1988    if (stale()) { zeroKey(key); return false; }1989  }1990  derivedKey = key;1991  vaultMode = entry.mode;1992  if (entry.mode === "decoy") decoySyncTeardownHook?.();1993  entries = payload.entries;1994  tombstones = payload.tombstones;1995  duressConfigured = entry.mode === "real" ? payload.duressConfigured : false;1996  if (freshRoot) rootKey = freshRoot;1997  buildDomainIndexSync(entries);1998  touchAutoLock();19992000  await lockedSyncUnlockHook?.().catch((error) => {2001    console.warn("[Peach sync] locked inbox drain failed:", error);2002  });2003  if (stale()) return false;20042005  return true;2006}20072008export async function lock(): Promise<void> {2009  const recoveryRevoked = revokeRecoveryReveal();2010  // A user-initiated lock must be durable across MV3 service-worker restarts.2011  // The SW is idle-killed after ~30s of inactivity, and the popup's next open2012  // wakes a cold SW whose restoreFromSession() reads chrome.storage.session.2013  // If the session key survived lock(), that restore would silently re-unlock2014  // the vault ~a minute after the user locked it — a lock that only held2015  // while the SW happened to stay alive. The background-sync convenience the2016  // session key once bought (sync runner re-waking to a restored vault) is2017  // not worth an unlocked vault the user never asked to unlock; when locked,2018  // sync-runner correctly reports VAULT_LOCKED instead.2019  vaultEpoch++;2020  if (derivedKey) {2021    zeroKey(derivedKey);2022    derivedKey = null;2023  }2024  if (rootKey) {2025    rootKey.fill(0);2026    rootKey = null;2027  }20282029  entries = [];2030  tombstones = new Map();2031  domainIndex = new Map();2032  vaultMode = "real";2033  duressConfigured = false;2034  clearAutoLock();2035  try {2036    chrome.runtime?.sendMessage?.({ type: "VAULT_LOCKED" })?.catch?.(() => undefined);2037  } catch { /* UI contexts may already be closed */ }2038  await clearSessionKey();2039  await recoveryRevoked;2040  // The decrypted identity is session state as well, so a locked vault must not2041  // leave one behind; clear it after the in-memory state is gone.2042  await notifyIdentitySessionEnded();2043}20442045/// Identifies the current unlock session for authorization across awaited work.2046export function getVaultEpoch(): number {2047  return vaultEpoch;2048}20492050export function isUnlocked(): boolean {2051  return derivedKey !== null;2052}2053/** True only while the active session is unlocked through the decoy slot. */2054export function isDecoyMode(): boolean {2055  return derivedKey !== null && vaultMode === "decoy";2056}20572058// Opens the vault using a pre-derived AES-256 key (skipping Argon2id). The2059// PIN-unlock path unwraps this key from its PIN wrap; the passphrase path2060// always derives from scratch via Argon2id.2061export async function unlockWithKey(2062  masterKeyHex: string,2063): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {2064  vaultUnlocksInFlight++;2065  try {2066  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };2067  const epoch = vaultEpoch;2068  const stale = () => epoch !== vaultEpoch;2069  await revokeRecoveryReveal();2070  if (stale()) return { ok: false, error: "vault_locked" };2071  let masterKeyBytes: Uint8Array | null = null;2072  try {2073    masterKeyBytes = unhex(masterKeyHex);2074    const stored = await loadSlot(SLOT_A);2075    if (!stored) return { ok: false, error: "invalid_key" };2076    const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");2077    if (!payload || stale()) {2078      zeroKey(masterKeyBytes);2079      return { ok: false, error: "invalid_key" };2080    }20812082    derivedKey = masterKeyBytes;2083    vaultMode = "real";2084    entries = payload.entries;2085    tombstones = payload.tombstones;2086    duressConfigured = payload.duressConfigured;2087    buildDomainIndexSync(entries);2088    await loadSettings();2089    touchAutoLock();20902091    rootKey = await deriveRootKeyFromDerivedKey(masterKeyBytes, stored);2092    if (!rootKey) {2093      await lock();2094      return { ok: false, error: "invalid_key" };2095    }2096    await reconcilePairSecrets(rootKey);2097    if (stale()) {2098      await lock();2099      return { ok: false, error: "invalid_key" };2100    }2101    await saveSessionKey(masterKeyBytes, "real", epoch);2102    if (stale()) return { ok: false, error: "invalid_key" };2103    return { ok: true, entries };2104  } catch {2105    if (masterKeyBytes && derivedKey !== masterKeyBytes) zeroKey(masterKeyBytes);2106    return { ok: false, error: "invalid_key" };2107  }2108  } finally { vaultUnlocksInFlight--; }2109}21102111// --- Adoption duress-slot helpers (passthrough, no decrypt) ---21122113/**2114 * Adoption SOURCE helper: returns the sealed slot B as a JSON string when2115 * duress is configured and slot B exists, so the inline snapshot can ship it2116 * to the receiver. Returns null otherwise. Never decrypts.2117 */2118export async function exportDuressSlotForAdoption(): Promise<string | null> {2119  if (!(await isDuressEnabled())) return null;2120  const slotB = await loadSlot(SLOT_B);2121  if (!slotB) return null;2122  return JSON.stringify(slotB);2123}21242125/**2126 * Adoption RECEIVER helper: installs a duress slot received from a source2127 * device. Validates the StoredVault shape (same guard as unlockFromCodex)2128 * and writes it to slot B. Throws on invalid shape so the caller can treat2129 * it as a non-fatal snapshot failure. Never decrypts.2130 */2131export async function installAdoptedDuressSlot(json: string): Promise<void> {2132  if (vaultCreatesInFlight) throw new Error("vault_changed");2133  vaultWritesInFlight++;2134  try {2135  let parsed: StoredVault;2136  try {2137    const raw = JSON.parse(json) as unknown;2138    if (!hasValidVaultSchema(raw)) {2139      throw new Error("invalid_duress_slot_shape");2140    }2141    parsed = raw;2142  } catch (err) {2143    if (err instanceof SyntaxError) {2144      throw new Error("invalid_duress_slot_shape");2145    }2146    throw err;2147  }2148  await writeSlot(SLOT_B, parsed);2149  } finally { vaultWritesInFlight--; }2150}21512152/**2153 * Restore the vault from a parsed Peach Codex payload.2154 *2155 * The supplied passphrase is verified against the Codex's slotA *before* any2156 * storage mutation — wrong passphrases return without touching disk. On2157 * success, the current vault state is snapshotted (reason: "restore") so the2158 * user can revert via Settings -> Vault History, then slotA/slotB are written2159 * and `peach_last_modified_at` is set to the Codex's recorded timestamp. A2160 * regular `unlock()` follows so the rest of the SW sees the standard2161 * post-unlock state.2162 *2163 * Intentionally non-Pro-gated — see peach_codex_v2.md "Pro gating". A Codex2164 * printed by a Pro user must always be restorable, even on a free device.2165 *2166 * Timing is not held constant here (in contrast to `unlock`): the Codex flow2167 * is an explicit user action with a known passphrase, not a passive lock2168 * screen, so the duress-vs-real timing side channel does not apply.2169 */2170export async function unlockFromCodex(params: {2171  slotA: string; // JSON string of StoredVault for slot A2172  slotB: string | null; // JSON string of StoredVault for slot B, or null2173  timestamp: number;2174  masterPassphrase: string;2175}): Promise<2176  | { ok: true; entryCount: number }2177  | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" | "missing_root_escrow" }2178> {2179  if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");2180  vaultReplacementInFlight = true;2181  try {2182    let parsedSlotA: StoredVault;2183    let parsedSlotB: StoredVault | null = null;2184    try {2185      const rawA = JSON.parse(params.slotA) as unknown;2186      if (!hasValidVaultSchema(rawA)) {2187        return { ok: false, reason: "invalid_slot_format" };2188      }2189      parsedSlotA = rawA;2190      if (params.slotB !== null) {2191        const rawB = JSON.parse(params.slotB) as unknown;2192        if (!hasValidVaultSchema(rawB)) {2193          return { ok: false, reason: "invalid_slot_format" };2194        }2195        parsedSlotB = rawB;2196      }2197    } catch {2198      return { ok: false, reason: "invalid_slot_format" };2199    }22002201    // Verify the passphrase and the password-wrapped root escrow against the2202    // staged Slot A WITHOUT writing anything. Payload decoding is part of the2203    // trial decrypt, so unlock() cannot be the first place these checks run.2204    const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));2205    const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");2206    if (!trialPayload) {2207      zeroKey(trialKey);2208      return { ok: false, reason: "wrong_passphrase" };2209    }2210    const hasEscrow =2211      !!parsedSlotA.pw_root_ciphertext && !!parsedSlotA.pw_root_nonce && !!parsedSlotA.pw_root_tag;2212    if (!hasEscrow) {2213      zeroKey(trialKey);2214      return { ok: false, reason: "missing_root_escrow" };2215    }2216    const stagedRootKey = await deriveRootKeyFromDerivedKey(trialKey, parsedSlotA);2217    if (!stagedRootKey) {2218      zeroKey(trialKey);2219      return { ok: false, reason: "wrong_passphrase" };2220    }2221    zeroKey(stagedRootKey);2222    zeroKey(trialKey);22232224    // Stage the complete candidate pair in memory before touching storage.2225    const stagedSlotB = parsedSlotB ?? generateNoiseBlob(parsedSlotA.ciphertext.length / 2);22262227    // Drop the trial key; `unlock()` below derives its own copy. Holding two2228    // copies of the master key in memory at once would be a needless surface.22292230    // Snapshot the about-to-be-overwritten on-disk state so the user can revert2231    // a mistaken Codex restore via the Vault History UI. Non-fatal if it fails.2232    await takeVaultSnapshot("restore");2233    const previousSlotA = await loadSlot(SLOT_A);2234    const previousSlotB = await loadSlot(SLOT_B);2235    let slotACommitted = false;2236    let slotBCommitted = false;2237    try {2238      await writeSlot(SLOT_A, parsedSlotA);2239      slotACommitted = true;2240      await writeSlot(SLOT_B, stagedSlotB);2241      slotBCommitted = true;2242      await chrome.storage.local.set({2243        peach_last_modified_at: String(params.timestamp),2244      });2245    } catch (err) {2246      if (slotBCommitted && previousSlotB) await writeSlot(SLOT_B, previousSlotB);2247      if (slotACommitted && previousSlotA) await writeSlot(SLOT_A, previousSlotA);2248      throw err;2249    }22502251    // Standard unlock path so domain index, settings, auto-lock, and2252    // recovery-key state all populate exactly as a normal unlock would.2253    const ok = await unlock(params.masterPassphrase);2254    if (!ok) {2255      // Should be unreachable — the staged candidate passed the same checks.2256      return { ok: false, reason: "wrong_passphrase" };2257    }2258    return { ok: true, entryCount: getEntries().length };2259  } finally {2260    vaultReplacementInFlight = false;2261  }2262}22632264// Returns the current in-memory derived key as a hex string. Only the PIN2265// unlock path needs this value, and it reads module state directly; this2266// accessor exists so unlockWithKey's root-key rehydration is testable.2267export /* @testable */ function getDerivedKeyHex(): string {2268  if (!derivedKey) throw new Error("vault_not_unlocked");2269  return hex(derivedKey);2270}22712272/**2273 * Returns the vault's stable root key as hex, or null when locked / not yet2274 * populated. The root key is random per-vault, generated at creation, escrowed2275 * under the recovery words, and re-wrapped (not regenerated) on every password2276 * change — so it is INVARIANT across password rotation, unlike getDerivedKeyHex.2277 *2278 * This is the correct input for sync identity derivation (vault_id, the Noise2279 * NK static key, the Ed25519 manifest signing key, and per-entry envelope2280 * keys): paired devices keep the same identity and can still decrypt each2281 * other's entries after either side rotates its master password (SEV-2-B).2282 *2283 * Returns null rather than throwing so sync callers degrade to VAULT_LOCKED2284 * instead of crashing; rootKey is populated on every supported real-mode2285 * unlock via deriveRootKeyFromDerivedKey.2286 */2287export function getRootKeyHex(): string | null {2288  return rootKey ? hex(rootKey) : null;2289}22902291export function getEntries(): VaultEntry[] {2292  if (!derivedKey) throw new Error("vault_locked");2293  return entries.filter((entry) => !entry.deletedAt);2294}22952296const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;22972298export function getIdentities(): SavedIdentity[] {2299  if (!derivedKey) throw new Error("vault_locked");2300  const active = entries.filter((e) => !e.deletedAt && e.type === "login");23012302  const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();2303  const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();23042305  for (const entry of active) {2306    const domain = extractDomain(entry.url ?? "") ?? "";2307    const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;23082309    function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {2310      const existing = map.get(v);2311      if (!existing || modifiedAt > existing.lastUsed) {2312        map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });2313      } else {2314        map.set(v, { ...existing, count: existing.count + 1 });2315      }2316    }23172318    const uVal = entry.username?.trim();2319    if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);23202321    // Also count the dedicated email field — entries created via the inline2322    // popup new-entry form store email here rather than in username.2323    const eVal = entry.email?.trim();2324    if (eVal) tally(emailMap, eVal);2325  }23262327  const toIdentity = (type: "email" | "username") =>2328    ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({2329      value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,2330    });23312332  return [2333    ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),2334    ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),2335  ];2336}23372338export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {2339  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");23402341  const now = Date.now();2342  const added: VaultEntry[] = [];2343  for (const draft of drafts) {2344    try {2345      const sanitized = sanitizeEntryDraft(draft);2346      const nextEntry: VaultEntry = {2347        ...sanitized,2348        id: crypto.randomUUID(),2349        createdAt: now,2350        modifiedAt: monotonicEntryTimestamp(),2351      };2352      entries.push(nextEntry);2353      added.push(nextEntry);2354    } catch {2355      // Skip invalid drafts silently — caller can see diff between input and output length2356    }2357  }23582359  if (added.length > 0) {2360    await persistEntries();2361  }23622363  return added;2364}23652366/**2367 * Restore a set of entries in full fidelity — preserves id, createdAt,2368 * modifiedAt, and every other field unlike `batchAddEntries` which2369 * assigns fresh identity. Used by restore paths where the backup is the2370 * authoritative source of truth. `mode` controls how entries already in2371 * the vault are treated.2372 */2373export async function restoreEntries(2374  incoming: VaultEntry[],2375  mode: "replace" | "merge"2376): Promise<{ added: number; updated: number; skipped: number }> {2377  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");23782379  // A replace with zero incoming entries is almost certainly a caller bug2380  // (e.g. an import that silently dropped everything). Refuse rather than2381  // wipe the vault.2382  if (mode === "replace" && incoming.length === 0) {2383    throw new Error("refuse to replace with empty entry set");2384  }23852386  let added = 0;2387  let updated = 0;2388  let skipped = 0;23892390  if (mode === "replace") {2391    entries = [];2392    for (const entry of incoming) {2393      const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2394      if (!normalized) {2395        skipped += 1;2396        continue;2397      }2398      entries.push(normalized);2399      if (normalized.deletedAt) {2400        tombstones.set(2401          normalized.id,2402          Math.max(tombstones.get(normalized.id) ?? 0, normalized.deletedAt),2403        );2404      } else {2405        tombstones.delete(normalized.id);2406      }2407      added += 1;2408    }2409  } else {2410    const byId = new Map<string, VaultEntry>();2411    for (const e of entries) byId.set(e.id, e);24122413    for (const entry of incoming) {2414      const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2415      if (!normalized) {2416        skipped += 1;2417        continue;2418      }2419      const existing = byId.get(normalized.id);2420      if (!existing) {2421        entries.push(normalized);2422        if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2423        else tombstones.delete(normalized.id);2424        added += 1;2425      } else if (normalized.modifiedAt > existing.modifiedAt) {2426        const idx = entries.findIndex((e) => e.id === existing.id);2427        if (idx !== -1) {2428          entries[idx] = normalized;2429          if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2430          else tombstones.delete(normalized.id);2431          updated += 1;2432        }2433      } else {2434        skipped += 1;2435      }2436    }2437  }24382439  await persistEntries("import");2440  return { added, updated, skipped };2441}24422443/**2444 * A Peach entry id is a UUID. A restored or imported file carries whatever id2445 * its author used, and no reader bounds it, so one oversized id would ride2446 * into every future sync frame and be rejected there — a permanent, opaque2447 * failure on both platforms, caused by data that was already local.2448 *2449 * The action is mint, not reject: this is the last point where an id is still2450 * ours to choose, so the worst outcome is one duplicate if the same vault is2451 * later restored beside a device still holding the old id. Rejecting would2452 * lose the user's import.2453 *2454 * Deliberately NOT inside sanitizeRestoredEntry, which applyMergedRemoteEntries2455 * also calls. Sync has to adopt a peer's id verbatim — that is the only thing2456 * keeping two devices agreed on which entry they are discussing — so reminting2457 * there would fork identity on every device, on every round.2458 */2459const ENTRY_ID_SHAPE = /^[A-Za-z0-9_-]{1,64}$/;24602461function naturalizeRestoredId(entry: VaultEntry | null): VaultEntry | null {2462  if (!entry || ENTRY_ID_SHAPE.test(entry.id)) return entry;2463  return { ...entry, id: crypto.randomUUID() };2464}24652466/**2467 * Validate + normalise a VaultEntry coming from a backup, import, or sync2468 * peer. MV-6: this is a strict field WHITELIST — `normalizeEntry` copies2469 * only known VaultEntry fields (unknown/attacker keys are dropped), and2470 * nested `passkey`/`canary` shapes are rebuilt field-by-field, never2471 * spread. Returns null for values the live vault shouldn't accept.2472 */2473function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {2474  if (!entry || typeof entry !== "object") return null;2475  const title = typeof entry.title === "string" ? entry.title.trim() : "";2476  if (!title) return null;2477  const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();2478  const now = Date.now();2479  const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;2480  const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;24812482  // normalizeEntry whitelists every known VaultEntry field before the entry2483  // reaches the live vault.2484  const normalized = normalizeEntry({2485    ...entry,2486    id,2487    title,2488    type: entry.type ?? "login",2489    createdAt,2490    modifiedAt,2491  });24922493  if (normalized.passkey) {2494    normalized.passkey = sanitizePasskey(normalized.passkey);2495  }2496  if (normalized.canary) {2497    normalized.canary = sanitizeCanary(normalized.canary);2498  }2499  // PCH-01-016: bound tags on the restore path too, so both import funnels agree.2500  normalized.tags = sanitizeTags(normalized.tags);25012502  // Login entries from backup must carry a password (or be passkey-only,2503  // in which case the passkey sub-object replaces the password requirement).2504  if (2505    normalized.type === "login" &&2506    !normalized.passkey &&2507    typeof normalized.password !== "string"2508  ) {2509    return null;2510  }2511  if (entry.passkey && !normalized.passkey) {2512    // Entry claimed a passkey but the shape didn't validate — refuse the2513    // whole entry rather than silently importing a credential-less husk.2514    return null;2515  }25162517  return normalized;2518}25192520/**2521 * Rebuild a PasskeyData object from untrusted input, field by field.2522 * Returns undefined when required fields are missing/mistyped — a rogue2523 * passkey credential must not activate via import (MV-6 attack scenario).2524 */2525function sanitizePasskey(pk: unknown): PasskeyData | undefined {2526  if (!pk || typeof pk !== "object") return undefined;2527  const r = pk as Record<string, unknown>;2528  if (2529    typeof r.rpId !== "string" || !r.rpId ||2530    typeof r.credentialId !== "string" || !r.credentialId ||2531    typeof r.publicKeyCose !== "string" ||2532    typeof r.userHandle !== "string" ||2533    typeof r.userName !== "string"2534  ) {2535    return undefined;2536  }2537  return {2538    rpId: r.rpId,2539    rpName: typeof r.rpName === "string" ? r.rpName : r.rpId,2540    credentialId: r.credentialId,2541    publicKeyCose: r.publicKeyCose,2542    privateKeyJwk:2543      r.privateKeyJwk && typeof r.privateKeyJwk === "object"2544        ? (r.privateKeyJwk as JsonWebKey)2545        : undefined,2546    userHandle: r.userHandle,2547    userName: r.userName,2548    userDisplayName:2549      typeof r.userDisplayName === "string" ? r.userDisplayName : r.userName,2550    algorithm: r.algorithm === -8 ? -8 : -7,2551    signCount: typeof r.signCount === "number" ? r.signCount : 0,2552    aaguid: typeof r.aaguid === "string" ? r.aaguid : "",2553    backupEligible: r.backupEligible === true,2554    backupState: r.backupState === true,2555    lastUsedAt: typeof r.lastUsedAt === "number" ? r.lastUsedAt : undefined,2556    browser: r.browser === "chrome" || r.browser === "firefox" ? r.browser : undefined,2557    transports: Array.isArray(r.transports)2558      ? r.transports.filter((t): t is string => typeof t === "string")2559      : undefined,2560    createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),2561  };2562}25632564/**2565 * Rebuild a Canary object from untrusted input. The webhook must be a2566 * well-formed HTTPS URL — a poisoned canary.webhookUrl is a standing2567 * exfiltration endpoint that the canary subsystem will POST entry titles2568 * to (MV-6 attack scenario). Invalid → the canary is dropped, not the2569 * entry. FIRE_CANARY_PING re-validates with the full SSRF guard at fire2570 * time (isAllowedCanaryWebhookUrl), so this import-time check is the2571 * outer of two gates.2572 */2573function sanitizeCanary(c: unknown): Canary | undefined {2574  if (!c || typeof c !== "object") return undefined;2575  const r = c as Record<string, unknown>;2576  if (typeof r.webhookUrl !== "string") return undefined;2577  let url: URL;2578  try {2579    url = new URL(r.webhookUrl);2580  } catch {2581    return undefined;2582  }2583  if (url.protocol !== "https:") return undefined;2584  return {2585    webhookUrl: url.toString(),2586    label: typeof r.label === "string" ? r.label : undefined,2587    lastPinged: typeof r.lastPinged === "number" ? r.lastPinged : undefined,2588    pingCount: typeof r.pingCount === "number" ? r.pingCount : undefined,2589  };2590}25912592/**2593 * MV-6 / PCH-01-016: tags from imported / batch-added entries are untrusted.2594 * Keep only non-empty strings, cap each at 256 chars, and cap the count at 2552595 * (the same per-entry ceiling the export codec enforces, peachPayload.ts).2596 * Non-array or all-invalid input collapses to undefined.2597 */2598function sanitizeTags(tags: unknown): string[] | undefined {2599  if (!Array.isArray(tags)) return undefined;2600  const out: string[] = [];2601  for (const t of tags) {2602    if (typeof t !== "string") continue;2603    const trimmed = t.trim();2604    if (!trimmed) continue;2605    out.push(trimmed.slice(0, 256));2606    if (out.length >= 255) break;2607  }2608  return out.length > 0 ? out : undefined;2609}26102611// Soft-deletes every non-deleted entry in one call. The literal string2612// argument is a tripwire against accidental calls — any caller that would2613// wipe the vault has to consciously type "REPLACE_ALL". Do not relax this2614// to a boolean.2615export async function clearVaultEntries(2616  confirmation: "REPLACE_ALL"2617): Promise<void> {2618  if (confirmation !== "REPLACE_ALL") {2619    throw new Error("clearVaultEntries requires explicit confirmation");2620  }2621  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");2622  for (const entry of entries) {2623    if (!entry.deletedAt) {2624      const stamp = monotonicEntryTimestamp(Math.max(2625        entry.modifiedAt,2626        tombstones.get(entry.id) ?? 0,2627      ));2628      entry.deletedAt = stamp;2629      entry.modifiedAt = stamp;2630      tombstones.set(entry.id, stamp);2631    }2632  }2633  await persistEntries();2634}26352636export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {2637  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");26382639  const sanitized = sanitizeEntryDraft(entry);2640  const now = Date.now();2641  const stamp = monotonicEntryTimestamp();2642  const nextEntry: VaultEntry = {2643    ...sanitized,2644    id: crypto.randomUUID(),2645    createdAt: now,2646    modifiedAt: stamp,2647    // Stamp passwordChangedAt at creation so age tracking is accurate from2648    // day one. Non-login entries carry the same stamp harmlessly.2649    passwordChangedAt: sanitized.password ? stamp : undefined,2650  };26512652  // Clone-and-replace so a failed persist rolls back the in-memory state2653  // (COR-008). Without this, a quota-full or storage error leaves the2654  // module-level `entries` ahead of what's actually on disk.2655  const rollback = entries;2656  entries = [...entries, nextEntry];2657  try {2658    await persistEntries();2659  } catch (err) {2660    entries = rollback;2661    throw err;2662  }26632664  // Fire-and-forget breach check (only for login entries if breach monitoring is enabled or not set)2665  if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {2666    const breachEpoch = vaultEpoch;2667    checkBreach(nextEntry.password).then(async (count) => {2668      if (count > 0 && breachEpoch === vaultEpoch && !vaultCreatesInFlight) {2669        const idx = entries.findIndex((e) => e.id === nextEntry.id);2670        if (idx !== -1) {2671          entries[idx] = { ...entries[idx], breach: count, modifiedAt: monotonicEntryTimestamp(entries[idx].modifiedAt) };2672          await persistEntries();2673        }2674      }2675    });2676  }26772678  fireSyncTrigger("vault_change");26792680  return nextEntry;2681}26822683/// Attach unambiguous account credentials without discarding other entry data.2684export async function consolidatePasskeyEntries(): Promise<void> {2685  if (!derivedKey || vaultCreatesInFlight) return;2686  const epoch = vaultEpoch;2687  const rollback = entries;2688  const next = entries.map((entry) => ({ ...entry }));2689  if (!mergePasskeyOnlyIntoLogins(next).merged) return;2690  const unchanged = next.map((entry) => ({ entry, modifiedAt: entry.modifiedAt }));2691  entries = next;2692  try {2693    await persistEntries();2694  } catch (err) {2695    // Other writers can replace entries or mutate a deletion in this array.2696    if (epoch === vaultEpoch && entries === next && entries.length === unchanged.length &&2697      unchanged.every(({ entry, modifiedAt }, index) => entries[index] === entry && entry.modifiedAt === modifiedAt)) {2698      entries = rollback;2699      buildDomainIndexSync(entries);2700    }2701    throw err;2702  }2703}27042705export async function updateEntry(2706  id: string,2707  patch: Partial<VaultEntry>2708): Promise<void> {2709  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");27102711  const idx = entries.findIndex((entry) => entry.id === id);2712  if (idx === -1 || entries[idx].deletedAt) {2713    throw new Error("entry_not_found");2714  }27152716  const current = entries[idx];2717  const sanitizedPatch = sanitizeEntryPatch(patch);2718  // Refresh passwordChangedAt only when the password value actually changes —2719  // a metadata-only update (title, tags, etc.) must not reset the age clock2720  // that drives the Pro health rotation recommendation.2721  const passwordChanged =2722    "password" in patch &&2723    typeof sanitizedPatch.password === "string" &&2724    sanitizedPatch.password !== current.password;2725  const stamp = monotonicEntryTimestamp(current.modifiedAt);2726  // When the password actually changes, push the outgoing one onto the history2727  // (newest first) so the user can reveal/copy/restore it later. We record the2728  // age it carried (passwordChangedAt, falling back to createdAt) rather than2729  // `now`, so the list reflects when each password was last in effect. Only2730  // capture a non-empty prior value — clearing a password leaves no secret to2731  // keep, and we skip an immediate exact duplicate (e.g. restore-then-restore)2732  // to avoid noise.2733  const priorPassword = current.password;2734  const shouldCapture =2735    passwordChanged &&2736    typeof priorPassword === "string" &&2737    priorPassword.length > 0 &&2738    current.passwordHistory?.[0]?.password !== priorPassword;2739  const nextHistory = shouldCapture2740    ? [2741        { password: priorPassword!, changedAt: current.passwordChangedAt ?? current.createdAt },2742        ...(current.passwordHistory ?? []),2743      ].slice(0, PASSWORD_HISTORY_MAX)2744    : current.passwordHistory;2745  entries[idx] = {2746    ...current,2747    ...sanitizedPatch,2748    modifiedAt: stamp,2749    ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),2750  };2751275227532754  // Card entries must retain their card number2755  if (entries[idx].type === "card" && !entries[idx].cardNumber) {2756    entries[idx] = current;2757    throw new Error("card number is required for card entries");2758  }27592760  // Roll the in-memory entry back to its pre-edit state if the disk write2761  // fails (e.g. storage quota). Without this the module-level `entries` array2762  // would hold an edit that never landed on disk, diverging from the vault2763  // until the next unlock silently reverts it (SEV-3-A). Mirrors addEntry.2764  try {2765    await persistEntries();2766  } catch (err) {2767    entries[idx] = current;2768    throw err;2769  }27702771  // Breach check when password changes: clear immediately so old breach doesn't linger,2772  // then async-check the new password and only re-set if it's also found.2773  if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {2774    entries[idx] = { ...entries[idx], breach: undefined };2775    await persistEntries();2776    const password = entries[idx].password;2777    if (password) {2778      checkBreach(password).then(async (count) => {2779        const i = entries.findIndex((e) => e.id === id);2780        if (i !== -1 && count > 0) {2781          entries[i] = { ...entries[i], breach: count, modifiedAt: monotonicEntryTimestamp(entries[i].modifiedAt) };2782          await persistEntries();2783        }2784      });2785    }2786  }27872788  fireSyncTrigger("vault_change");2789}27902791export async function deleteEntry(id: string): Promise<void> {2792  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");27932794  const entry = entries.find((item) => item.id === id);2795  if (!entry || entry.deletedAt) {2796    throw new Error("entry_not_found");2797  }27982799  // Tombstone timestamp must be strictly greater than the entry's last2800  // modification so the deletion wins LWW against any in-flight edit, even2801  // under clock skew (SEV-2-E).2802  const previousModifiedAt = entry.modifiedAt;2803  const previousTombstone = tombstones.get(id);2804  const stamp = monotonicEntryTimestamp(Math.max(entry.modifiedAt, previousTombstone ?? 0));2805  entry.deletedAt = stamp;2806  entry.modifiedAt = stamp;2807  tombstones.set(id, stamp);2808  // Roll the tombstone back if the disk write fails, so a quota error doesn't2809  // leave the entry deleted in memory but alive on disk (SEV-3-A).2810  try {2811    await persistEntries();2812  } catch (err) {2813    delete entry.deletedAt;2814    entry.modifiedAt = previousModifiedAt;2815    if (previousTombstone === undefined) tombstones.delete(id);2816    else tombstones.set(id, previousTombstone);2817    throw err;2818  }2819  fireSyncTrigger("vault_change");2820}28212822export function getDeletedEntries(): VaultEntry[] {2823  if (!derivedKey) return [];2824  return entries.filter((e) => !!e.deletedAt);2825}28262827/** Return all durable deletion timestamps, including purged full entries. */2828export function getTombstoneManifest(): Record<string, number> {2829  if (!derivedKey) return {};2830  return Object.fromEntries(tombstones);2831}28322833/**2834 * Returns the vault's monotonic version — the `peach_last_modified_at` value2835 * stamped on every user-initiated write. Remote (sync) writes do NOT advance2836 * this version so a sync round never cascades into a second outbound sync.2837 */2838export async function getVaultVersion(): Promise<number> {2839  try {2840    const raw = await chrome.storage.local.get("peach_last_modified_at");2841    const v = (raw as Record<string, unknown>).peach_last_modified_at;2842    if (typeof v === "number") return v;2843    if (typeof v === "string" && v !== "") {2844      const n = Number.parseInt(v, 10);2845      return Number.isFinite(n) ? n : 0;2846    }2847    return 0;2848  } catch {2849    return 0;2850  }2851}28522853/**2854 * Apply a batch of remote entries + tombstones from a sync peer.2855 * Last-write-wins by `modifiedAt`; a tombstone supersedes a live entry when2856 * `deletedAt > modifiedAt` on the local side. Mutates `entries` directly and2857 * persists with reason `sync_received` — does NOT fire the sync dispatcher, so2858 * applying a sync round cannot cascade into another outbound sync.2859 *2860 * `applied` counts entries that actually changed local state (new add,2861 * overwrite-by-newer, or new tombstone). `received` is the raw payload size2862 * the caller can surface in the sync result UI.2863 */2864export async function applyMergedRemoteEntries(2865  remoteEntries: VaultEntry[],2866  remoteTombstones: Record<string, number>,2867): Promise<{ received: number; applied: number; conflicts: number }> {2868  // DESIGN: last-write-wins is applied PER-ENTRY, not per-field. If two devices2869  // concurrently edit different fields of the same entry, the one with the2870  // newer modifiedAt wins the whole entry and the other device's field edits2871  // are dropped silently. This is the deliberate trade-off for a simple,2872  // conflict-free merge — per-field CRDT merge is out of scope. Guidance for2873  // users: edit a given entry on one device at a time.2874  if (!derivedKey || vaultCreatesInFlight || vaultMode === "decoy") throw new Error("vault_locked");28752876  const received = remoteEntries.length + Object.keys(remoteTombstones).length;2877  let applied = 0;2878  let conflicts = 0;28792880  const byId = new Map<string, VaultEntry>();2881  for (const e of entries) byId.set(e.id, e);28822883  const mergeNow = Date.now();2884  const remoteTombstoneTimes = new Map<string, number>();2885  for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2886    if (typeof rawDeletedAt === "number" && Number.isFinite(rawDeletedAt) && rawDeletedAt > 0) {2887      remoteTombstoneTimes.set(id, clampSyncTimestamp(rawDeletedAt, mergeNow));2888    }2889  }28902891  for (const remote of remoteEntries) {2892    const sanitized = sanitizeRestoredEntry(remote);2893    if (!sanitized) continue;2894    // HV-1a: a far-future remote modifiedAt must not permanently pin a2895    // malicious value against honest local edits. Clamp BEFORE any2896    // comparison against local timestamps.2897    sanitized.modifiedAt = clampSyncTimestamp(sanitized.modifiedAt, mergeNow);2898    if (typeof sanitized.deletedAt === "number") {2899      sanitized.deletedAt = clampSyncTimestamp(sanitized.deletedAt, mergeNow);2900    }2901    const remoteTombstoneTs = remoteTombstoneTimes.get(sanitized.id);2902    const localTombstoneTs = tombstones.get(sanitized.id);2903    const tombstoneTs = Math.max(remoteTombstoneTs ?? 0, localTombstoneTs ?? 0);2904    if (tombstoneTs > 0 && tombstoneTs >= sanitized.modifiedAt) {2905      continue;2906    }2907    const local = byId.get(sanitized.id);2908    if (!local) {2909      entries.push(sanitized);2910      byId.set(sanitized.id, sanitized);2911      tombstones.delete(sanitized.id);2912      applied += 1;2913    } else if (sanitized.modifiedAt > local.modifiedAt) {2914      const idx = entries.findIndex((e) => e.id === local.id);2915      if (idx !== -1) {2916        entries[idx] = sanitized;2917        byId.set(sanitized.id, sanitized);2918        tombstones.delete(sanitized.id);2919        applied += 1;2920        if (!local.deletedAt) conflicts += 1;2921      }2922    }2923  }29242925  for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2926    if (typeof rawDeletedAt !== "number" || !Number.isFinite(rawDeletedAt) || rawDeletedAt <= 0) continue;2927    // HV-1a/1c: clamp the tombstone timestamp before every comparison.2928    const deletedAt = remoteTombstoneTimes.get(id)!;2929    const knownTombstone = tombstones.get(id);2930    if (knownTombstone !== undefined && knownTombstone >= deletedAt) continue;2931    const local = byId.get(id);2932    if (!local) {2933      tombstones.set(id, deletedAt);2934      applied += 1;2935      continue;2936    }2937    if (local.deletedAt && local.deletedAt >= deletedAt) continue;2938    if (deletedAt < local.modifiedAt) continue;2939    const idx = entries.findIndex((e) => e.id === id);2940    if (idx !== -1) {2941      entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };2942      tombstones.set(id, deletedAt);2943      applied += 1;2944    }2945  }29462947  if (applied > 0 && vaultMode === "real") {2948    await persistEntries("sync_received");2949    buildDomainIndexSync(entries);2950    // An open popup holds the entries it loaded at mount and polls nothing, so2951    // a background round (the relay listener responding to a peer's push, or the2952    // alarm-driven dial) otherwise lands silently and the user sees stale data2953    // until they reopen. Best-effort: no popup listening is the normal case.2954    try {2955      void chrome.runtime2956        .sendMessage({ type: "VAULT_ENTRIES_CHANGED" })2957        .catch(() => undefined);2958    } catch {2959      // messaging unavailable2960    }2961  }2962  return { received, applied, conflicts };2963}29642965export async function restoreEntry(id: string): Promise<void> {2966  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");2967  const entry = entries.find((e) => e.id === id && e.deletedAt);2968  if (!entry) throw new Error("deleted entry not found");2969  const previousDeletedAt = entry.deletedAt;2970  const previousModifiedAt = entry.modifiedAt;2971  const previousTombstone = tombstones.get(id);2972  delete entry.deletedAt;2973  entry.modifiedAt = monotonicEntryTimestamp(Math.max(2974    entry.modifiedAt,2975    previousTombstone ?? 0,2976  ));2977  tombstones.delete(id);2978  try {2979    await persistEntries();2980  } catch (err) {2981    entry.deletedAt = previousDeletedAt;2982    entry.modifiedAt = previousModifiedAt;2983    if (previousTombstone !== undefined) tombstones.set(id, previousTombstone);2984    throw err;2985  }2986  buildDomainIndexSync(entries);2987}29882989export async function purgeEntry(id: string): Promise<void> {2990  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");2991  const idx = entries.findIndex((e) => e.id === id && e.deletedAt);2992  if (idx === -1) throw new Error("deleted entry not found");2993  const entry = entries[idx]!;2994  tombstones.set(id, Math.max(tombstones.get(id) ?? 0, entry.deletedAt!));2995  entries.splice(idx, 1);2996  await persistEntries();2997}29982999/** Permanently delete entries whose deletedAt is older than retentionMs. 0 = keep forever. */3000export async function purgeExpiredTrash(retentionMs: number): Promise<number> {3001  if (!derivedKey || vaultCreatesInFlight || retentionMs === 0) return 0;3002  const cutoff = Date.now() - retentionMs;3003  const before = entries.length;3004  for (const entry of entries) {3005    if (entry.deletedAt && entry.deletedAt < cutoff) {3006      tombstones.set(entry.id, Math.max(tombstones.get(entry.id) ?? 0, entry.deletedAt));3007    }3008  }3009  entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));3010  const purged = before - entries.length;3011  if (purged > 0) await persistEntries();3012  return purged;3013}30143015export function queryDomain(domain: string): VaultEntry[] {3016  return domainIndex.get(domain) ?? [];3017}30183019export function getEntryById(id: string): VaultEntry | undefined {3020  return entries.find((entry) => entry.id === id && !entry.deletedAt);3021}30223023async function persistSlotA(3024  reason: VaultSnapshot["reason"] = "local_save",3025): Promise<StoredVault> {3026  if (!derivedKey) throw new Error("vault_locked");3027  const epoch = vaultEpoch;3028  const throwIfStale = () => {3029    if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3030  };30313032  const slotA = await loadSlot(SLOT_A);3033  throwIfStale();3034  if (!slotA) throw new Error("missing slot A");30353036  // Snapshot the about-to-be-overwritten state BEFORE we mutate disk. Failures3037  // are swallowed by takeVaultSnapshot — history must never block a save.3038  await takeVaultSnapshot(reason);3039  throwIfStale();30403041  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3042  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");3043  throwIfStale();30443045  // Preserve existing recovery escrow fields.3046  const nextSlotA: StoredVault = {3047    ...slotA,3048    nonce,3049    ciphertext,3050    tag,3051    // recovery_salt and recovery_wrapped_root_key are already set from loadSlot3052  };30533054  // Slot A (the real vault) is now committed. Wrap every later write so a3055  // mid-persist failure (e.g. a storage error after slot A landed) restores the3056  // prior slot A before rethrowing. Without this, a "failed" save that already3057  // wrote slot A leaves disk ahead of the in-memory rollback in addEntry/3058  // updateEntry/deleteEntry — the entry stays silently on disk and resurfaces3059  // as a duplicate on the next unlock (observed under storage-quota pressure).3060  let slotACommitted = false;3061  try {3062    throwIfStale();3063    await writeSlot(SLOT_A, nextSlotA);3064    slotACommitted = true;3065    throwIfStale();30663067    // When duress is not configured, keep slot B size-matched with slot A by3068    // regenerating its noise. When duress IS configured, leave slot B alone —3069    // we don't have the decoy key to re-encrypt it. This is a known trade-off.3070    if (!duressConfigured) {3071      throwIfStale();3072      await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3073      throwIfStale();3074    }3075    // Only advance the vault version for locally-originated writes. Entries3076    // applied from a sync peer ("sync_received") must NOT bump the counter —3077    // otherwise applying a remote round makes us look newer than the peer and3078    // triggers a redundant outbound sync, defeating the no-op optimisation3079    // and risking a ping-pong between two devices (SEV-2-C).3080    if (reason !== "sync_received") {3081      throwIfStale();3082      await stampLocalVaultMutation();3083      throwIfStale();3084    }3085  } catch (err) {3086    // Best-effort restore — the prior slot A is smaller-or-equal, so this write3087    // fits even when the failure was a quota overflow.3088    if (slotACommitted) await writeSlot(SLOT_A, slotA).catch(() => {});3089    if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3090    throw err;3091  }30923093  return nextSlotA;3094}30953096async function persistSlotB(): Promise<void> {3097  if (!derivedKey) throw new Error("vault_locked");30983099  const slotB = await loadSlot(SLOT_B);3100  if (!slotB) throw new Error("missing slot B");31013102  // Decoy plaintext always reports duressConfigured=false — the decoy user3103  // sees a clean slate. persistSlotB only runs in decoy mode, which only3104  // exists once duress is configured, so pad to the fixed duress ceiling to3105  // keep slot B's length equal to slot A's (audit MEDIUM — deniability).3106  const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);3107  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");31083109  await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });3110  // Symmetric with persistSlotA: if the version stamp fails after the decoy3111  // slot committed, restore the prior slot B so a failed decoy-mode save can't3112  // leave disk ahead of the in-memory rollback.3113  try {3114    await stampLocalVaultMutation();3115  } catch (err) {3116    await writeSlot(SLOT_B, slotB).catch(() => {});3117    throw err;3118  }3119}31203121async function persistEntries(3122  reason: VaultSnapshot["reason"] = "local_save",3123): Promise<void> {3124  if (vaultCreatesInFlight) throw new Error("vault_changed");3125  vaultWritesInFlight++;3126  try {3127  if (!derivedKey) throw new Error("vault_locked");31283129  // Reconcile direct soft-delete callers while restoring the previous map if3130  // storage rejects the save.3131  const previousTombstones = tombstones;3132  const pendingTombstones = new Map(tombstones);3133  tombstones = pendingTombstones;3134  reconcileTombstones();3135  try {3136    if (vaultMode === "decoy") {3137      await persistSlotB();3138    } else {3139      await persistSlotA(reason);3140    }3141  } catch (err) {3142    if (tombstones === pendingTombstones) tombstones = previousTombstones;3143    throw err;3144  }3145  buildDomainIndexSync(entries);3146  await refreshLockedSyncState();3147  } finally { vaultWritesInFlight--; }3148}31493150// PB-26-011: drop URLs whose parsed scheme is not http(s) at the storage3151// boundary. Schemeless values (e.g. "github.com") are inert and kept — they3152// pre-date this guard in existing data. Unparseable values are kept: the3153// reviewed render paths never execute them (favicons via _favicon/, domains3154// via tldts); this is defense-in-depth against future sinks.3155function allowHttpUrl(url: string | undefined): string {3156  const trimmed = url?.trim() ?? "";3157  if (!trimmed) return "";3158  try {3159    const parsed = new URL(trimmed);3160    if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return "";3161  } catch {3162    // No scheme to reject.3163  }3164  return trimmed;3165}31663167function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {3168  if (!Array.isArray(values)) return undefined;3169  const seen = new Set<string>();3170  const cleaned: string[] = [];3171  for (const value of values) {3172    const trimmed = typeof value === "string" ? value.trim() : "";3173    if (!trimmed) continue;3174    if (!allowHttpUrl(trimmed)) continue;3175    const key = trimmed.toLowerCase();3176    if (seen.has(key)) continue;3177    seen.add(key);3178    cleaned.push(trimmed);3179  }3180  return cleaned.length > 0 ? cleaned : undefined;3181}31823183function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {3184  const title = entry.title.trim();3185  const type: VaultEntry["type"] = entry.type ?? "login";31863187  if (!title) throw new Error("title is required");31883189  if (entry.passkey) {3190    const p = entry.passkey;3191    if (3192      !p.rpId ||3193      !p.credentialId ||3194      !p.publicKeyCose ||3195      !p.userHandle ||3196      !p.userName ||3197      (p.algorithm !== -7 && p.algorithm !== -8)3198    ) {3199      throw new Error("invalid passkey credential");3200    }3201  }3202  if (type === "card") {3203    if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {3204      throw new Error("cardholder name and card number are required");3205    }3206  }32073208  return {3209    type,3210    title,3211    username: type === "login" ? entry.username?.trim() ?? "" : undefined,3212    email: type === "login" ? entry.email?.trim() || undefined : undefined,3213    password: type === "login" ? entry.password : undefined,3214    url: type === "login" ? allowHttpUrl(entry.url) : undefined,3215    additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,3216    totp: type === "login" ? entry.totp?.trim() || undefined : undefined,3217    // PCH-01-019: preserve non-default TOTP params through batch-add/import so3218    // they are not silently stripped (they fall back to SHA-1/6/30 when absent).3219    totpAlgorithm: type === "login" ? entry.totpAlgorithm : undefined,3220    totpDigits: type === "login" ? entry.totpDigits : undefined,3221    totpPeriod: type === "login" ? entry.totpPeriod : undefined,3222    notes: entry.notes?.trim() || undefined,3223    breach: type === "login" ? entry.breach : undefined,3224    // PCH-01-016: the batch-add path was bypassing the MV-6 canary/tags3225    // whitelist applied on the RESTORE_ENTRIES path. Run both sanitizers here.3226    canary: type === "login" ? sanitizeCanary(entry.canary) : undefined,3227    tags: sanitizeTags(entry.tags),3228    passkey: entry.passkey,3229    cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,3230    cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,3231    expMonth: type === "card" ? entry.expMonth?.trim() : undefined,3232    expYear: type === "card" ? entry.expYear?.trim() : undefined,3233    cvc: type === "card" ? entry.cvc?.trim() : undefined,3234    cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,3235    network: type === "card" ? entry.network : undefined,3236    last4: type === "card" ? entry.last4?.trim() : undefined,3237  };3238}32393240function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {3241  const nextPatch: Partial<VaultEntry> = {};32423243  if ("type" in patch) {3244    nextPatch.type = patch.type;3245  }32463247  if ("title" in patch) {3248    const title = patch.title?.trim() ?? "";3249    if (!title) throw new Error("title is required");3250    nextPatch.title = title;3251  }32523253  if ("url" in patch) {3254    nextPatch.url = allowHttpUrl(patch.url);3255  }32563257  if ("additionalUrls" in patch) {3258    const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];3259    const seen = new Set<string>();3260    const cleaned: string[] = [];3261    for (const value of incoming) {3262      const trimmed = typeof value === "string" ? value.trim() : "";3263      if (!trimmed || !allowHttpUrl(trimmed)) continue;3264      const key = trimmed.toLowerCase();3265      if (seen.has(key)) continue;3266      seen.add(key);3267      cleaned.push(trimmed);3268    }3269    nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;3270  }32713272  if ("username" in patch) {3273    nextPatch.username = patch.username?.trim() ?? "";3274  }32753276  if ("email" in patch) {3277    nextPatch.email = patch.email?.trim() || undefined;3278  }32793280  if ("password" in patch) {3281    const password = patch.password ?? "";3282    // Allow clearing a password (e.g. on passkey-only entries)3283    nextPatch.password = password || undefined;3284  }32853286  if ("totp" in patch) {3287    nextPatch.totp = patch.totp?.trim() || undefined;3288  }32893290  if ("totpAlgorithm" in patch) {3291    nextPatch.totpAlgorithm = patch.totpAlgorithm;3292  }32933294  if ("totpDigits" in patch) {3295    nextPatch.totpDigits = patch.totpDigits;3296  }32973298  if ("totpPeriod" in patch) {3299    nextPatch.totpPeriod = patch.totpPeriod;3300  }33013302  if ("notes" in patch) {3303    nextPatch.notes = patch.notes?.trim() || undefined;3304  }33053306  if ("breach" in patch) {3307    nextPatch.breach = patch.breach;3308  }33093310  if ("canary" in patch) {3311    // PCH-02-001: route update patches through the same canary whitelist used3312    // by add/restore/sync. Invalid shapes drop the canary; `undefined` clears it.3313    nextPatch.canary = patch.canary ? sanitizeCanary(patch.canary) : undefined;3314  }33153316  if ("passkey" in patch) {3317    // A patch with `passkey: undefined` removes the credential from the entry3318    // (used by "remove passkey" without deleting the whole entry).3319    if (patch.passkey === undefined || patch.passkey === null) {3320      nextPatch.passkey = undefined;3321    } else {3322      const sanitized = sanitizePasskey(patch.passkey);3323      if (!sanitized) throw new Error("invalid passkey credential");3324      nextPatch.passkey = sanitized;3325    }3326  }33273328  if ("tags" in patch) {3329    // PCH-02-001: bound tags exactly like both import funnels.3330    nextPatch.tags = sanitizeTags(patch.tags);3331  }33323333  if ("cardholderName" in patch) {3334    nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;3335  }3336  if ("cardNumber" in patch) {3337    const n = patch.cardNumber ?? "";3338    nextPatch.cardNumber = n || undefined;3339  }3340  if ("expMonth" in patch) {3341    nextPatch.expMonth = patch.expMonth?.trim() || undefined;3342  }3343  if ("expYear" in patch) {3344    nextPatch.expYear = patch.expYear?.trim() || undefined;3345  }3346  if ("cvc" in patch) {3347    nextPatch.cvc = patch.cvc?.trim() || undefined;3348  }3349  if ("cardNickname" in patch) {3350    nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;3351  }3352  if ("network" in patch) {3353    nextPatch.network = patch.network;3354  }3355  if ("last4" in patch) {3356    nextPatch.last4 = patch.last4?.trim() || undefined;3357  }33583359  return nextPatch;3360}33613362function normalizeEntry(entry: VaultEntry): VaultEntry {3363  const base: VaultEntry = {3364    id: entry.id,3365    type: entry.type,3366    title: entry.title,3367    username: entry.username,3368    email: entry.email,3369    password: entry.password,3370    url: entry.url,3371    additionalUrls:3372      "additionalUrls" in entry && Array.isArray(entry.additionalUrls)3373        ? entry.additionalUrls3374        : undefined,3375    totp: entry.totp,3376    // PCH-01-019: carry TOTP params through the normalize/restore path too.3377    totpAlgorithm: entry.totpAlgorithm,3378    totpDigits: entry.totpDigits,3379    totpPeriod: entry.totpPeriod,3380    notes: entry.notes,3381    breach: entry.breach,3382    // Preserve the password-age clock across lock/unlock. Without this the3383    // field is dropped on every decode and the advanced-health "aged password"3384    // signal silently resets to createdAt on each unlock (SEV-2-A).3385    passwordChangedAt:3386      "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,3387    // Preserve past-password history across lock/unlock. normalizeEntry is a3388    // field whitelist, so an unlisted field is silently dropped on every decode3389    // (same class as the passwordChangedAt SEV-2-A above).3390    passwordHistory:3391      "passwordHistory" in entry && Array.isArray(entry.passwordHistory)3392        ? entry.passwordHistory3393        : undefined,3394    canary: entry.canary,3395    passkey: entry.passkey,3396    createdAt: entry.createdAt,3397    modifiedAt: entry.modifiedAt,3398    deletedAt: entry.deletedAt,3399    tags: entry.tags,3400    cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,3401    cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,3402    expMonth: "expMonth" in entry ? entry.expMonth : undefined,3403    expYear: "expYear" in entry ? entry.expYear : undefined,3404    cvc: "cvc" in entry ? entry.cvc : undefined,3405    cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,3406    network: "network" in entry ? entry.network : undefined,3407    last4: "last4" in entry ? entry.last4 : undefined,3408  };34093410  return base;3411}341234133414// ---------------------------------------------------------------------------3415// Deduplication3416// ---------------------------------------------------------------------------34173418function entryDupeKey(e: VaultEntry): string {3419  if (e.passkey) {3420    // Equal identities can still carry different passwords, notes or TOTP data.3421    const content = Object.fromEntries(Object.entries(e)3422      .filter(([key]) => key !== "id" && key !== "createdAt" && key !== "modifiedAt")3423      .sort(([a], [b]) => a.localeCompare(b)));3424    return `passkey|${e.passkey.rpId}|${e.passkey.credentialId}|${JSON.stringify(content)}`;3425  }3426  if (e.type === "note") return `note|${e.title.toLowerCase()}`;3427  return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;3428}34293430/** Returns the number of duplicate entries (those that would be removed). */3431export function countDuplicates(): number {3432  const best = new Map<string, VaultEntry>();3433  let dupeCount = 0;3434  for (const e of entries.filter((e) => !e.deletedAt)) {3435    const key = entryDupeKey(e);3436    const existing = best.get(key);3437    if (!existing) {3438      best.set(key, e);3439    } else {3440      dupeCount++;3441      // Keep the more recently modified one in the map3442      if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3443        best.set(key, e);3444      }3445    }3446  }3447  return dupeCount;3448}34493450/**3451 * Soft-deletes duplicate entries, keeping the most recently modified copy of3452 * each group. Returns the number of entries moved to trash.3453 */3454export async function deduplicateEntries(): Promise<number> {3455  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3456  // Dedup reshapes slot B permanently under the decoy key, which is3457  // forensically distinguishable from a freshly-seeded decoy vault. Refuse.3458  if (vaultMode === "decoy") {3459    throw new Error("deduplicate disabled in decoy mode");3460  }34613462  const best = new Map<string, VaultEntry>();3463  for (const e of entries.filter((en) => !en.deletedAt)) {3464    const key = entryDupeKey(e);3465    const existing = best.get(key);3466    if (!existing) {3467      best.set(key, e);3468    } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3469      best.set(key, e);3470    }3471  }34723473  const keepIds = new Set(Array.from(best.values()).map((e) => e.id));3474  let removed = 0;3475  entries = entries.map((e) => {3476    if (!e.deletedAt && !keepIds.has(e.id)) {3477      removed++;3478      const deletedAt = monotonicEntryTimestamp(Math.max(3479        e.modifiedAt,3480        tombstones.get(e.id) ?? 0,3481      ));3482      tombstones.set(e.id, deletedAt);3483      return { ...e, deletedAt };3484    }3485    return e;3486  });34873488  if (removed > 0) await persistEntries();3489  return removed;3490}34913492// ---------------------------------------------------------------------------3493// Vault history — snapshot BEFORE every vault write so the saved blob is3494// what is about to be lost, not what was just written. Capped at 5. The3495// stored blobs are AES-256-GCM ciphertext under the master password, so3496// history adds zero security surface.3497// ---------------------------------------------------------------------------34983499const HISTORY_KEY = "peach_vault_history";3500const HISTORY_MAX = 5;35013502// PCH-01-023: coarsen a live-entry count into a low-resolution bucket so the3503// plaintext snapshot field cannot reveal exact vault size or single-entry change3504// deltas. Buckets widen as the vault grows so absolute leakage stays roughly3505// proportional rather than exact.3506function bucketEntryCount(n: number): number {3507  if (n <= 0) return 0;3508  if (n <= 10) return 10;3509  if (n <= 25) return 25;3510  if (n <= 50) return 50;3511  if (n <= 100) return 100;3512  if (n <= 250) return 250;3513  if (n <= 500) return 500;3514  return Math.ceil(n / 500) * 500;3515}35163517/**3518 * Snapshot the CURRENT on-disk vault state into history. Call this BEFORE3519 * overwriting peach_vault_a so the saved blob captures the about-to-be-lost3520 * state. Identical-to-most-recent blobs are skipped to avoid filling history3521 * with no-op writes.3522 */3523export async function takeVaultSnapshot(3524  reason: VaultSnapshot["reason"],3525): Promise<void> {3526  if (recoveryInFlight || vaultCreatesInFlight) return;3527  // The history store is real-mode state by construction, so it must not be3528  // written from a decoy session either. The guard lives here rather than only3529  // at the call sites so the invariant survives a new caller (PB-26-915).3530  if (vaultMode === "decoy") return;3531  vaultWritesInFlight++;3532  try {3533    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);3534    const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];3535    const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];35363537    // Nothing to snapshot if the real slot doesn't exist yet (fresh install,3538    // pre-createVault). createVault skips snapshots intentionally — there is3539    // no prior state to preserve.3540    if (!slotA) return;35413542    const vault_a = JSON.stringify(slotA);3543    const vault_b = JSON.stringify(slotB ?? slotA);35443545    // Best-effort entry count: only meaningful when the in-memory state is3546    // unlocked AND in real mode. Decoy mode would leak the decoy entry3547    // count; locked mode has no entries to count. Both fall through to null.3548    // PCH-01-023: store a coarse bucket, not the exact count — chrome.storage3549    // .local sits next to the AES-GCM blobs in plaintext, so an exact count would3550    // leak vault size and per-write deltas (the metadata padding hides this).3551    let entryCount: number | null = null;3552    if (derivedKey && vaultMode === "real") {3553      try {3554        entryCount = bucketEntryCount(entries.filter((e) => !e.deletedAt).length);3555      } catch {3556        entryCount = null;3557      }3558    }35593560    const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];3561    const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)3562      ? existingRaw3563      : { snapshots: [] };35643565    // Deduplication: if the most recent snapshot has byte-identical blobs,3566    // skip — saves the same vault N times in a row would otherwise burn the3567    // entire history window with no recovery value.3568    const latest = history.snapshots[0];3569    if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {3570      return;3571    }35723573    const snapshot: VaultSnapshot = {3574      id: crypto.randomUUID(),3575      savedAt: Date.now(),3576      reason,3577      vault_a,3578      vault_b,3579      entryCount,3580    };35813582    history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);3583    if (recoveryInFlight || vaultCreatesInFlight) return;3584    await chrome.storage.local.set({ [HISTORY_KEY]: history });3585  } catch (err) {3586    // Non-fatal — history must never block a save. A failed snapshot just3587    // means the user loses one rung of the safety ladder for this write.3588    // M4/QUA-006: log so the failure is visible; if it looks like a quota3589    // problem, notify the popup so the user can prune history themselves.3590    console.warn('[Peach] takeVaultSnapshot failed:', err);3591    if (String(err).includes('QUOTA') || String(err).includes('quota')) {3592      try {3593        await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });3594      } catch {3595        // popup may be closed; surfaced via console.warn above3596      }3597    }3598  } finally { vaultWritesInFlight--; }3599}36003601/** Wipe all vault history. Called by Panic / DESTROY_VAULT. */3602export async function clearVaultHistory(): Promise<void> {3603  if (recoveryInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");3604  vaultWritesInFlight++;3605  try {3606    await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });3607  } catch {3608    // Non-fatal — DESTROY_VAULT also runs storage.local.clear().3609  } finally { vaultWritesInFlight--; }3610}36113612/** Read all snapshots, newest first, for the Settings vault history view. */3613export async function getVaultHistory(): Promise<VaultSnapshot[]> {3614  if (vaultMode === "decoy") return [];3615  const raw = await chrome.storage.local.get(HISTORY_KEY);3616  const value = (raw as Record<string, unknown>)[HISTORY_KEY];3617  return sanitizeHistory(value);3618}36193620/**3621 * Replace the on-disk vault with the chosen snapshot's blobs and lock the3622 * vault. The current state is itself snapshotted before replacement.3623 */3624export async function restoreVaultSnapshot(3625  snapshotId: string,3626): Promise<{ ok: true } | { ok: false; error: string }> {3627  if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "vault_changed" };3628  vaultReplacementInFlight = true;3629  try {3630    if (vaultMode === "decoy") return { ok: false, error: "vault_locked" };3631    const history = await getVaultHistory();3632    const snapshot = history.find((s) => s.id === snapshotId);3633    if (!snapshot) return { ok: false, error: "snapshot_not_found" };36343635    const restoredA = parseHistorySlot(snapshot.vault_a);3636    const restoredB = parseHistorySlot(snapshot.vault_b);3637    if (!restoredA || !restoredB) return { ok: false, error: "snapshot_corrupt" };36383639    await takeVaultSnapshot("restore");3640    const current = await chrome.storage.local.get([SLOT_A, SLOT_B]);3641    const previousA = (current as Record<string, unknown>)[SLOT_A];3642    const previousB = (current as Record<string, unknown>)[SLOT_B];3643    try {3644      if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };3645      await chrome.storage.local.set({ [SLOT_A]: restoredA, [SLOT_B]: restoredB });3646      await stampLocalVaultMutation();3647    } catch {3648      try {3649        await chrome.storage.local.set({ [SLOT_A]: previousA, [SLOT_B]: previousB });3650      } catch {3651        // Preserve the restore failure if storage cannot complete the rollback.3652      }3653      return { ok: false, error: "snapshot_corrupt" };3654    }36553656    await lock();3657    return { ok: true };3658  } finally {3659    vaultReplacementInFlight = false;3660  }3661}36623663/**3664 * Rotate the vault's sync identity by generating a FRESH ROOT KEY and3665 * re-wrapping everything under it (MV-8). Because every sync credential —3666 * vault_id, the Noise static keypair, the Ed25519 manifest signing key,3667 * and the per-entry envelope keys — derives from the root key, rotation3668 * makes a lost/stolen device's retained key material useless. All paired3669 * devices must re-pair afterwards.3670 *3671 * CONSEQUENCE THE UI MUST SURFACE: the 12 recovery words also derive from3672 * the root key, so rotation INVALIDATES the old recovery phrase. The flow3673 * sets peach_recovery_pending so the popup re-presents the new words for3674 * confirmation, same as the initial recovery-word confirmation path.3675 */3676export async function rotateSyncIdentity(): Promise<{ ok: boolean; error?: string }> {3677  if (vaultCreatesInFlight) throw new Error("vault_changed");3678  const rotationEpoch = vaultEpoch;3679  const removalEpoch = vaultRemovalEpoch;3680  vaultWritesInFlight++;3681  try {3682  if (!derivedKey || vaultMode !== "real") {3683    return { ok: false, error: "vault_locked" };3684  }3685  const slotA = await loadSlot(SLOT_A);3686  if (!slotA) return { ok: false, error: "missing_slot_a" };36873688  // 1. Fresh root key + recovery escrow (new words).3689  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =3690    await generateAndWrapRootKey();36913692  // 2. Re-wrap the new root key under the current password-derived key.3693  const newRootKey = unhex(rawRootKey);3694  const recoveryVaultKey = await encrypt(newRootKey, hex(derivedKey), "recovery_vault_key_v1");3695  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, newRootKey);36963697  // 3. Snapshot, then single atomic slot write — both escrow wrappings of3698  //    the new root key land together (same transactional rule as3699  //    changePassword). Entries are untouched: they are sealed under the3700  //    password-derived key, not the root key.3701  await takeVaultSnapshot("local_save");3702  const nextSlotA: StoredVault = {3703    ...slotA,3704    recovery_vault_key: recoveryVaultKey,3705    recovery_salt: recoverySalt,3706    recovery_wrapped_root_key: wrappedRootKey,3707    recovery_nonce: wrappedNonce,3708    recovery_tag: wrappedTag,3709    ...pwRoot,3710  };3711  await writeSlot(SLOT_A, nextSlotA);37123713  // 4. Swap in memory only after disk committed.3714  if (rotationEpoch === vaultEpoch && derivedKey) {3715    if (rootKey) zeroKey(rootKey);3716    rootKey = newRootKey;3717  } else {3718    zeroKey(newRootKey);3719  }37203721  // 4b. The identity's root wrap was encrypted under the dead root. Without3722  //     this the identity survives only until the unlock key also changes.3723  await notifyIdentityKeysRotated();37243725  // 5. Old peers' identities derive from the dead root key — drop them all,3726  // with their rendezvous secrets (PB-26-213: rotation clears the map, so3727  // there is nothing to rewrap under the new key).3728  await clearPairedDevices();3729  await clearPairSecrets();37303731  // 6. Force re-presentation of the NEW recovery words on next popup view.3732  if (removalEpoch === vaultRemovalEpoch) {3733    await setRecoveryConfirmPending(rotationEpoch === vaultEpoch && isUnlocked());3734    touchAutoLock();3735  }37363737  await stampLocalVaultMutation();3738  return { ok: true };3739  } finally { vaultWritesInFlight--; }3740}37413742/**3743 * Change the master password. Re-encrypts slot A with a fresh salt + new3744 * derived key. Slot B (duress or noise) is left untouched when duress is3745 * configured — it uses an independent key derived from the duress password —3746 * and regenerated as noise when duress is not configured.3747 */3748export async function changePassword(3749  currentPassword: string,3750  newPassword: string3751): Promise<boolean> {3752  if (vaultCreatesInFlight) throw new Error("vault_changed");3753  vaultWritesInFlight++;3754  try {37553756  const epoch = vaultEpoch;3757  const stale = () => epoch !== vaultEpoch;3758  if (!derivedKey || vaultMode !== "real") return false;37593760  // Verify current password before allowing any change3761  const valid = await verifyMainPassword(currentPassword);3762  if (!valid) return false;37633764  const slotA = await loadSlot(SLOT_A);3765  if (!slotA) return false;3766  if (!rootKey) return false;37673768  // Derive fresh key from new password + new random salt3769  const newSalt = generateSalt();3770  const newKey = await deriveKey(newPassword, newSalt);3771  if (stale()) {3772    zeroKey(newKey);3773    return false;3774  }37753776  // Re-encrypt the in-memory entries with the new key3777  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3778  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");37793780  // Pre-wrap root key under the new derived key. Recovery fields wrap rootKey3781  // under recovery words and remain untouched — recovery phrase keeps working3782  // across password changes (H4/COR-002).3783  const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);37843785  const recoveryVaultKey = await encrypt(rootKey, hex(newKey), "recovery_vault_key_v1");3786  const finalSlotA: StoredVault = {3787    ...slotA,3788    recovery_vault_key: recoveryVaultKey,3789    salt: hex(newSalt),3790    nonce,3791    ciphertext,3792    tag,3793    ...pwRoot,3794  };37953796  // Snapshot the OLD-key blob before overwriting it. If the user later3797  // restores from this snapshot they will need the OLD password — the3798  // post-restore lock surfaces that immediately.3799  await takeVaultSnapshot("local_save");38003801  // Single atomic write: ciphertext, salt, and pw_root_* fields all land in3802  // one storage transaction. An SW kill before this point leaves the old3803  // slot intact; after this point everything tied to the new password is3804  // already on disk together (M6/COR-004).3805  await writeSlot(SLOT_A, finalSlotA);3806  if (stale()) {3807    zeroKey(newKey);3808    return false;3809  }38103811  // Swap the in-memory key synchronously before any further await. If we3812  // threw between the Slot A write and this swap, the next persistEntries()3813  // would overwrite Slot A with old-key ciphertext, locking the user out.3814  zeroKey(derivedKey);3815  derivedKey = newKey;38163817  // PCH-01-008: the MV3 session escrow still holds the OLD key. Without this,3818  // the next service-worker restore decrypts the new-key Slot A with the stale3819  // key, fails tryDecryptSlotResult, and silently drops the user to a lock3820  // screen. Re-escrow the new key so restore survives a password change.3821  if (stale()) {3822    await lock();3823    return false;3824  }3825  await saveSessionKey(newKey, "real", epoch);3826  if (stale()) return false;38273828  // The identity envelope holds one wrap per recovering key. Swapping the3829  // unlock key kills the local wrap, so re-wrap now or the next key swap3830  // orphans the identity -- and until then the old password still opens it.3831  await notifyIdentityKeysRotated();3832  if (stale()) return false;38333834  // Regenerate noise for slot B when duress is not in use. Runs after the3835  // key swap so a failure here is a disposable noise regeneration, not a3836  // lockout.3837  if (!duressConfigured) {3838    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3839  }3840  await clearPinUnlockStorage();3841  await stampLocalVaultMutation();38423843  return true;3844  } finally { vaultWritesInFlight--; }3845}