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 } 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 vaultWritesInFlight = 0;89let vaultCreatesInFlight = 0;90let creationSettled: Promise<void> = Promise.resolve();91let vaultUnlocksInFlight = 0;92let vaultReplacementInFlight = false;93let entries: VaultEntry[] = [];94// Tombstones outlive their full entry records so a peer that was offline95// during a purge cannot reintroduce an old ciphertext envelope. This map is96// serialized only inside the encrypted vault payload.97let tombstones = new Map<string, number>();98let domainIndex: Map<string, VaultEntry[]> = new Map();99let vaultMode: "real" | "decoy" = "real";100// Cached post-unlock view of whether the real vault records that duress is101// configured. Only meaningful after a real-mode unlock; for decoy-mode unlock102// this stays false because we never see slot A's plaintext.103let duressConfigured = false;104105// Set to a corruption reason during the last unlock() attempt when both slots106// decrypted but failed schema validation. Consumed and cleared by107// consumeLastUnlockFailureReason() so messages.ts can surface vault_corrupted108// distinctly from wrong-password (M7/COR-007).109//110// NOTE: module-level state — if vault.ts is ever moved to a worker context,111// this must be replaced with a structured return value from unlock() or a112// postMessage channel. The signal is invisible across module-instance113// boundaries.114let lastUnlockFailureReason: string | null = null;115116export function consumeLastUnlockFailureReason(): string | null {117  const r = lastUnlockFailureReason;118  lastUnlockFailureReason = null;119  return r;120}121122// ---------------------------------------------------------------------------123// Settings (persisted inside the encrypted vault store as a sidecar key)124// ---------------------------------------------------------------------------125126export type TextSize = "small" | "medium" | "large";127128export interface VaultSettings {129  accentColor?: AccentColorName;130  theme?: "dark" | "light";131  autoLockMinutes?: number;132  clipboardClearSeconds?: number;133  lockOnClose?: boolean;134  breachMonitoring?: boolean;135  passkeyProviderEnabled?: boolean;136  trashRetentionDays?: number;137  manualSummonDomains?: Record<string, ManualSummonRecord>;138  manualSummonSalt?: string;139  declinedCardFingerprints?: string[];140141  /** Metadata is bounded because it remains outside the encrypted vault blob. */142  metadataVersion?: 1;143  /**144   * Text size scale for body copy and entry titles. Stops at "large" by145   * design — XL clips dense screens (Vault, Health) inside the fixed146   * 330×480 popup surface.147   */148  textSize?: TextSize;149  /**150   * When true, all entrance/exit transitions and ambient animations are151   * collapsed to instant. Honoured alongside the user's OS-level152   * `prefers-reduced-motion`.153   */154  reduceMotion?: boolean;155  /** Require an unlock after a worker restart before locked Sync resumes. */156  lockedSyncRequiresUnlock?: boolean;157  /** Whether this vault has a local PIN unlock wrapper configured. */158  pinEnabled?: boolean;159  /** Whether the lock screen should open on PIN instead of the password. */160  pinPreferred?: boolean;161  /**162   * User overrides for keyboard shortcuts. Keys are ShortcutAction names163   * (see src/shared/shortcuts.ts). Missing actions fall through to164   * DEFAULT_BINDINGS — `getActiveBindings(settings.shortcuts)` is the165   * canonical lookup. Storing only the deltas keeps the vault payload166   * small and lets default updates land for users who never rebind.167   */168  shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;169}170171interface StoredPinWrap {172  version: 1;173  salt: string;174  nonce: string;175  ciphertext: string;176  tag: string;177}178179const PIN_WRAP_STORAGE = "peach_pin_wrap";180const PIN_ATTEMPTS_STORAGE = "peach_pin_attempts";181const PIN_MIN_LENGTH = 4;182const PIN_MAX_LENGTH = 12;183const PIN_MAX_ATTEMPTS = 3;184185let settings: VaultSettings = {};186const CARD_DECLINE_MAX = 256;187/** Hex length of a keyed card-decline digest. Legacy records are 16 hex. */188const CARD_DECLINE_DIGEST_HEX = 32;189190async function metadataDigest(value: string, key: string): Promise<string> {191  const bytes = new TextEncoder().encode(`${key}:${value}`);192  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));193  return Array.from(digest.slice(0, 16)).map((byte) => byte.toString(16).padStart(2, "0")).join("");194}195196let inMemoryPinWrap: StoredPinWrap | null = null;197let inMemoryPinFailedAttempts = 0;198let sessionPinStorageFailed = false;199200export function getSettings(): VaultSettings {201  return settings;202}203204export async function ensureSettingsLoaded(): Promise<VaultSettings> {205  await loadSettings();206  return settings;207}208209export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {210  await loadSettings();211  // LV-7: cheap insurance against prototype pollution if a future caller ever212  // feeds parsed external JSON here (native spread keeps __proto__ an own-213  // property today, but Object.assign-style consumers and JSON revivers have214  // been burned before).215  const safe = Object.fromEntries(216    Object.entries(patch).filter(217      ([k]) => !["__proto__", "constructor", "prototype"].includes(k),218    ),219  ) as Partial<VaultSettings>;220  settings = { ...settings, ...safe };221  await persistSettings();222}223224function isValidPin(pin: string): boolean {225  return new RegExp(`^\\d{${PIN_MIN_LENGTH},${PIN_MAX_LENGTH}}$`).test(pin);226}227228/** Set up a local PIN wrapper after proving the current master password. */229export async function setupPinUnlock(currentPassword: string, pin: string): Promise<boolean> {230  if (vaultCreatesInFlight) return false;231  vaultWritesInFlight++;232  try {233  if (!derivedKey || vaultMode !== "real" || !isValidPin(pin)) return false;234  if (!(await verifyMainPassword(currentPassword))) return false;235236  const salt = generateSalt();237  const pinKey = await deriveKey(pin, salt);238  try {239    const wrapped = await encrypt(pinKey, hex(derivedKey), "pin_wrap_v1");240    await savePinWrap({ version: 1, salt: hex(salt), ...wrapped });241    await updateSettings({ pinEnabled: true });242    return true;243  } finally {244    zeroKey(pinKey);245  }246  } finally { vaultWritesInFlight--; }247}248249async function clearPinUnlockStorage(): Promise<void> {250  inMemoryPinWrap = null;251  inMemoryPinFailedAttempts = 0;252  sessionPinStorageFailed = false;253  if (chrome.storage.session) {254    await chrome.storage.session.remove([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);255  }256  await updateSettings({ pinEnabled: false });257}258259/** Remove the PIN wrapper after proving the current master password. */260export async function disablePinUnlock(currentPassword: string): Promise<boolean> {261  if (vaultCreatesInFlight) return false;262  vaultWritesInFlight++;263  try {264  if (!derivedKey || vaultMode !== "real") return false;265  if (!(await verifyMainPassword(currentPassword))) return false;266  await clearPinUnlockStorage();267  return true;268  } finally { vaultWritesInFlight--; }269}270271/** Unlock the real vault from its locally stored PIN-wrapped derived key. */272export async function unlockWithPin(pin: string): Promise<boolean> {273  vaultUnlocksInFlight++;274  try {275  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;276  if (!isValidPin(pin)) return false;277  await loadSettings();278  if (!settings.pinEnabled) return false;279280  const { stored, failedAttempts } = await loadPinState();281  if (failedAttempts >= PIN_MAX_ATTEMPTS) return false;282  if (283    !stored ||284    stored.version !== 1 ||285    !stored.salt ||286    !stored.nonce ||287    !stored.ciphertext ||288    !stored.tag289  ) return false;290291  const pinKey = await deriveKey(pin, unhex(stored.salt));292  let unwrappedKey: Uint8Array | null = null;293  try {294    const masterKeyHex = await decrypt(295      pinKey,296      stored.nonce,297      stored.ciphertext,298      stored.tag,299      "pin_wrap_v1",300    );301    if (!/^[0-9a-f]{64}$/.test(masterKeyHex)) return false;302    unwrappedKey = unhex(masterKeyHex);303    const result = await unlockWithKey(masterKeyHex);304    if (!result.ok) return false;305    await resetPinFailedAttempts();306    return true;307  } catch {308    await recordPinFailure(failedAttempts + 1);309    return false;310  } finally {311    zeroKey(pinKey);312    if (unwrappedKey) zeroKey(unwrappedKey);313  }314  } finally { vaultUnlocksInFlight--; }315}316317async function savePinWrap(stored: StoredPinWrap): Promise<void> {318  inMemoryPinWrap = stored;319  inMemoryPinFailedAttempts = 0;320  sessionPinStorageFailed = !chrome.storage.session;321  if (!chrome.storage.session) return;322  try {323    await chrome.storage.session.set({ [PIN_WRAP_STORAGE]: stored, [PIN_ATTEMPTS_STORAGE]: 0 });324    sessionPinStorageFailed = false;325  } catch {326    // Firefox fallback: keep the wrapper only in this background context.327    sessionPinStorageFailed = true;328  }329}330331async function loadPinState(): Promise<{332  stored: StoredPinWrap | undefined;333  failedAttempts: number;334}> {335  if (!chrome.storage.session) {336    return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };337  }338  try {339    const result = await chrome.storage.session.get([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);340    return {341      stored: (result[PIN_WRAP_STORAGE] as StoredPinWrap | undefined) ??342        (sessionPinStorageFailed ? inMemoryPinWrap ?? undefined : undefined),343      failedAttempts: typeof result[PIN_ATTEMPTS_STORAGE] === "number"344        ? result[PIN_ATTEMPTS_STORAGE]345        : 0,346    };347  } catch {348    return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };349  }350}351352async function recordPinFailure(failedAttempts: number): Promise<void> {353  inMemoryPinFailedAttempts = Math.min(failedAttempts, PIN_MAX_ATTEMPTS);354  if (!chrome.storage.session) return;355  try {356    await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: inMemoryPinFailedAttempts });357  } catch { /* in-memory counter remains the fallback */ }358}359360async function resetPinFailedAttempts(): Promise<void> {361  inMemoryPinFailedAttempts = 0;362  if (!chrome.storage.session) return;363  try {364    await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: 0 });365  } catch { /* in-memory counter remains the fallback */ }366}367368export async function getPinUnlockStatus(): Promise<{369  configured: boolean;370  available: boolean;371  attemptsRemaining: number;372}> {373  await loadSettings();374  if (!settings.pinEnabled) {375    return { configured: false, available: false, attemptsRemaining: 0 };376  }377  const { stored, failedAttempts } = await loadPinState();378  const available = Boolean(stored) && failedAttempts < PIN_MAX_ATTEMPTS;379  return {380    configured: true,381    available,382    attemptsRemaining: stored ? Math.max(0, PIN_MAX_ATTEMPTS - failedAttempts) : 0,383  };384}385386async function persistSettings(): Promise<void> {387  try {388    await chrome.storage.local.set({389      peach_settings: {390        ...settings,391        manualSummonDomains: undefined,392        manualSummonSalt: undefined,393        cardFingerprintSalt: undefined,394        declinedCardFingerprints: settings.declinedCardFingerprints ?? [],395        metadataVersion: 1,396      },397    });398  } catch (err) {399    throw mapStorageError(err);400  }401}402403function mapStorageError(err: unknown): Error {404  const message = err instanceof Error ? err.message : String(err);405  if (/QUOTA_BYTES|quota/i.test(message)) {406    return new Error("STORAGE_QUOTA_EXCEEDED");407  }408  return err instanceof Error ? err : new Error(message);409}410411async function loadSettings(): Promise<void> {412  const result = await chrome.storage.local.get("peach_settings");413  settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};414}415416// Fire-and-forget sync trigger after a committed vault write. A failure here417// must never fail the write that caused it.418function fireSyncTrigger(reason: "vault_change"): void {419  void Promise.resolve()420    .then(() => triggerSyncIfReachable({ reason }))421    .catch(() => {422      /* no sync runner registered, or nothing reachable — non-fatal */423    });424}425export function lockedSyncRequiresUnlock(): boolean {426  return settings.lockedSyncRequiresUnlock === true;427}428429let lockedSyncRefreshHook: (() => Promise<void>) | null = null;430let lockedSyncUnlockHook: (() => Promise<void>) | null = null;431let decoySyncTeardownHook: (() => void) | null = null;432export type IdentityHooks = {433  /** Drop the cached identity: the session is no longer a real unlocked one. */434  onSessionEnded: () => Promise<void>;435  /** Re-wrap the identity under the keys now in force, after a vault key swap. */436  onKeysRotated: () => Promise<void>;437  /** Promote a pre-vault identity once a vault exists, given the password that created it. */438  onVaultCreated: (password: string) => Promise<void>;439};440441let identityHooks: IdentityHooks | null = null;442443export function setIdentityHooks(hooks: IdentityHooks): void {444  identityHooks = hooks;445}446447async function notifyIdentitySessionEnded(): Promise<void> {448  await identityHooks?.onSessionEnded().catch((error) => {449    console.warn("[Peach] local identity cache clear failed:", error);450  });451}452453async function notifyIdentityKeysRotated(): Promise<void> {454  await identityHooks?.onKeysRotated().catch((error) => {455    console.warn("[Peach] local identity re-wrap failed:", error);456  });457}458459export type SealedBox = { nonce: string; ciphertext: string; tag: string };460export type IdentityKeyEnvelope = {461  root?: SealedBox;462  local?: SealedBox;463  pending?: SealedBox;464  pendingSalt?: string;465};466467export function setLockedSyncHooks(hooks: {468  refresh: () => Promise<void>;469  afterUnlock: () => Promise<void>;470  onDecoy?: () => void;471}): void {472  lockedSyncRefreshHook = hooks.refresh;473  lockedSyncUnlockHook = hooks.afterUnlock;474  decoySyncTeardownHook = hooks.onDecoy ?? null;475}476477async function refreshLockedSyncState(): Promise<void> {478  if (vaultMode !== "real" || !rootKey || !lockedSyncRefreshHook) return;479  await lockedSyncRefreshHook().catch((error) => {480    console.warn("[Peach sync] locked spool refresh failed:", error);481  });482}483484// ---------------------------------------------------------------------------485// HIBP breach check (k-anonymity model)486// ---------------------------------------------------------------------------487488export async function checkBreach(password: string): Promise<number> {489  // HIBP k-anonymity API is keyed on SHA-1 prefixes — this is dictated by490  // the public API, not a security choice. Do not migrate to SHA-256 here.491  const encoder = new TextEncoder();492  const hashBuffer = await crypto.subtle.digest("SHA-1", encoder.encode(password));493  const hashHex = Array.from(new Uint8Array(hashBuffer))494    .map((b) => b.toString(16).padStart(2, "0"))495    .join("")496    .toUpperCase();497498  const prefix = hashHex.slice(0, 5);499  const suffix = hashHex.slice(5);500501  try {502    // PCH-02-007: request HIBP response padding so response length does not503    // reveal how many suffixes a queried prefix returned.504    const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`, {505      headers: { "Add-Padding": "true" },506    });507    if (!res.ok) return 0;508    const text = await res.text();509    const match = text.split("\r\n").find((l) => l.startsWith(suffix));510    return match ? parseInt(match.split(":")[1], 10) : 0;511  } catch {512    return 0; // Network unavailable — don't block513  }514}515516export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {517  // Unreachable from the message layer, which gates on isUnlocked first.518  const key = await cardDeclineKey();519  if (!key) return;520  const fingerprint = await cardFingerprint(last4, expMonth, expYear);521  await loadSettings();522  settings = {523    ...settings,524    declinedCardFingerprints: [525      // Legacy records predate the keyed digest and are silently dropped here:526      // they are 16 hex characters rather than 32, and are no longer accepted.527      ...(settings.declinedCardFingerprints ?? []).filter(528        (stored) => stored.length === CARD_DECLINE_DIGEST_HEX,529      ),530      await metadataDigest(fingerprint, key),531    ].slice(-CARD_DECLINE_MAX),532  };533  await persistSettings();534}535536export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {537  await loadSettings();538  const key = await cardDeclineKey();539  if (!key) return false;540  const fingerprint = await cardFingerprint(last4, expMonth, expYear);541  const candidate = await metadataDigest(fingerprint, key);542  return (settings.declinedCardFingerprints ?? []).some(543    (stored) => stored.length === CARD_DECLINE_DIGEST_HEX && stored === candidate,544  );545}546547/**548 * Keying material for the declined-card digest, derived from the vault root549 * key so it is available only while unlocked and never written to storage.550 *551 * PB-26-108: the previous scheme stored a random salt beside the records. A552 * salt defeats precomputed tables, not an attacker holding the file — the553 * candidate space here is ~10^4 last-four values x 12 months x a few years, so554 * a stored salt left the card's last four and expiry recoverable offline in555 * seconds. `peach_settings` is unencrypted and directly readable by a content556 * script on Firefox, so the key has to live outside storage entirely.557 */558async function cardDeclineKey(): Promise<string | null> {559  const root = getRootKeyHex();560  if (!root) return null;561  const digest = new Uint8Array(562    await crypto.subtle.digest(563      "SHA-256",564      new TextEncoder().encode(`peach-card-decline-v1:${root}`),565    ),566  );567  return hex(digest);568}569570async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {571  const encoder = new TextEncoder();572  const buf = await crypto.subtle.digest("SHA-256", encoder.encode(`${last4}|${expMonth}|${expYear}`));573  return Array.from(new Uint8Array(buf).slice(0, 8))574    .map((b) => b.toString(16).padStart(2, "0"))575    .join("");576}577578function hex(buf: Uint8Array): string {579  return Array.from(buf)580    .map((b) => b.toString(16).padStart(2, "0"))581    .join("");582}583584function unhex(s: string): Uint8Array {585  const out = new Uint8Array(s.length / 2);586  for (let i = 0; i < s.length; i += 2) {587    out[i / 2] = parseInt(s.slice(i, i + 2), 16);588  }589  return out;590}591592// ---------------------------------------------------------------------------593// Root key generation and recovery word wrapping594// ---------------------------------------------------------------------------595596/**597 * Generate a random 32-byte root key and wrap it (AES-256-GCM) under a key598 * derived from the recovery word material via HKDF-SHA256. The wrapped blob599 * fields are stored in slot A alongside the password-wrapped ciphertext. The600 * root key itself is kept in memory for the session so getRecoveryWords() can601 * encode it without re-deriving.602 *603 * SECURITY MODEL (PCH-01-005): the recovery KEK is derived from the 12-word604 * material, which encodes only rootKey[0..16] (recovery-words.ts). The KEK is thus605 * derived from a PREFIX of the very plaintext it wraps, and effective recovery606 * security is 128-bit (standard for a 12-word phrase), NOT 256-bit. This is safe —607 * unwrapping requires the words, and the GCM ciphertext leaks nothing without them —608 * but it is intentional, not an oversight. A future escrow version wanting 256-bit609 * recovery must derive the words from INDEPENDENT entropy, not from the root key.610 */611async function generateAndWrapRootKey(): Promise<{612  rawRootKey: string; // hex of the plaintext root key — caller stores in rootKey613  recoverySalt: string;614  wrappedRootKey: string;615  wrappedNonce: string;616  wrappedTag: string;617}> {618  const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));619  try {620621  // Derive the recovery key from the BIP39 words encoding of the root key.622  const words = await rootKeyToWords(rootKeyBytes);623  const wordMaterial = await wordsToRootKeyMaterial(words);624  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));625  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);626627  // Wrap the root key with the recovery key using AES-256-GCM directly.628  // We hex-encode rootKeyBytes so the plaintext is always valid UTF-8.629  const nonce = crypto.getRandomValues(new Uint8Array(12));630  const encoded = new TextEncoder().encode(hex(rootKeyBytes));631  const raw = await crypto.subtle.encrypt(632    {633      name: "AES-GCM",634      iv: nonce,635      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,636      tagLength: 128,637    },638    recoveryKey,639    encoded640  );641  // WebCrypto returns ciphertext || auth tag concatenated; split them.642  const rawU8 = new Uint8Array(raw);643  const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));644  const tag = hex(rawU8.slice(rawU8.length - 16));645646  return {647    rawRootKey: hex(rootKeyBytes),648    recoverySalt: hex(recoverySalt),649    wrappedRootKey: ciphertext,650    wrappedNonce: hex(nonce),651    wrappedTag: tag,652  };653  } finally { zeroKey(rootKeyBytes); }654}655656async function wrapExistingRootKeyForRecovery(rootKeyBytes: Uint8Array): Promise<{657  recoverySalt: string;658  wrappedRootKey: string;659  wrappedNonce: string;660  wrappedTag: string;661}> {662  if (rootKeyBytes.length !== 32) {663    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");664  }665666  const words = await rootKeyToWords(rootKeyBytes);667  const wordMaterial = await wordsToRootKeyMaterial(words);668  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));669  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);670  const nonce = crypto.getRandomValues(new Uint8Array(12));671  const encoded = new TextEncoder().encode(hex(rootKeyBytes));672  const raw = await crypto.subtle.encrypt(673    {674      name: "AES-GCM",675      iv: nonce,676      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,677      tagLength: 128,678    },679    recoveryKey,680    encoded,681  );682  const rawU8 = new Uint8Array(raw);683  return {684    recoverySalt: hex(recoverySalt),685    wrappedRootKey: hex(rawU8.slice(0, rawU8.length - 16)),686    wrappedNonce: hex(nonce),687    wrappedTag: hex(rawU8.slice(rawU8.length - 16)),688  };689}690691/**692 * Unwrap the root key using recovery words. Called during recovery flow when693 * the user provides their 12-word phrase and a new password.694 */695async function unwrapRootKeyForRecovery(696  wrappedRootKey: string,697  wrappedNonce: string,698  wrappedTag: string,699  recoverySaltHex: string,700  words: string[]701): Promise<Uint8Array> {702  const wordMaterial = await wordsToRootKeyMaterial(words);703  const recoverySalt = unhex(recoverySaltHex);704  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);705706  // The root key bytes were hex-encoded before707  // encryption so the ciphertext is valid UTF-8. We inline the AES-GCM decrypt708  // here to avoid passing a CryptoKey to the string-based encrypt/decrypt helpers.709  // Each component is stored separately in the vault slot; decode them individually710  // so the nonce is always exactly the 12 bytes from wrappedNonce.711  const nonceRaw = unhex(wrappedNonce);712  const ciphertextRaw = unhex(wrappedRootKey);713  const tagRaw = unhex(wrappedTag);714  // Combine ciphertext and tag for AES-GCM (expects ciphertext||tag).715  // Use explicit ArrayBuffer allocations to satisfy TS BufferSource constraints.716  const nonceU8 = nonceRaw as unknown as Uint8Array<ArrayBuffer>;717  const combined = new Uint8Array(ciphertextRaw.length + tagRaw.length);718  combined.set(ciphertextRaw, 0);719  combined.set(tagRaw, ciphertextRaw.length);720  const raw = await crypto.subtle.decrypt(721    { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },722    recoveryKey,723    combined724  );725  const decryptedHex = new TextDecoder().decode(raw);726  const recovered = unhex(decryptedHex);727  if (recovered.length !== 32) { zeroKey(recovered); throw new Error("invalid_recovery_words"); }728  return recovered;729}730731/// Recover a locked real vault without publishing keys before its stored payload authenticates.732export async function recoverWithWords(words: string[], newPassword: string): Promise<RecoveryResult> {733  if (recoveryInFlight || derivedKey) throw new Error("recovery_requires_lock");734  if (vaultWritesInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");735  recoveryInFlight = true;736  let settle!: () => void;737  recoverySettled = new Promise<void>((resolve) => { settle = resolve; });738  const epoch = ++vaultEpoch;739  const check = () => {740    if (epoch !== vaultEpoch || derivedKey) throw new Error("vault_locked");741  };742  let recoveredRoot: Uint8Array | null = null;743  let oldKey: Uint8Array | null = null;744  let newKey: Uint8Array | null = null;745  let committed = false;746  try {747    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);748    check();749    const slot = raw[SLOT_A] as StoredVault | undefined;750    if (!slot) throw new Error("no_vault");751    if (!slot.recovery_salt || !slot.recovery_wrapped_root_key) throw new Error("recovery_not_setup");752    try {753      recoveredRoot = await unwrapRootKeyForRecovery(slot.recovery_wrapped_root_key,754        slot.recovery_nonce ?? "", slot.recovery_tag ?? "", slot.recovery_salt, words);755    } catch {756      throw new Error("invalid_recovery_words");757    }758    check();759    if (!slot.recovery_vault_key) throw new Error("recovery_requires_password_unlock");760    oldKey = await openSealedKey(recoveredRoot, slot.recovery_vault_key, "recovery_vault_key_v1");761    check();762    if (!oldKey) throw new Error("recovery_data_unavailable");763    const result = await tryDecryptSlotResult(slot, oldKey, "slot_a_v1");764    check();765    if (result.status !== "ok") throw new Error("recovery_data_unavailable");766    const payload = result.payload;767    await loadSettings();768    check();769    const salt = generateSalt();770    newKey = await deriveKey(newPassword, salt);771    check();772    // Preserve the authenticated plaintext, including fields unknown to this build.773    const plaintext = await decrypt(oldKey, slot.nonce, slot.ciphertext, slot.tag, "slot_a_v1");774    const encrypted = await encrypt(newKey, plaintext, "slot_a_v1");775    const pwRoot = await wrapRootKeyForDerivedKey(newKey, recoveredRoot);776    const recoveryVaultKey = await encrypt(recoveredRoot, hex(newKey), "recovery_vault_key_v1");777    check();778    const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);779    check();780    if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");781    const history = raw[HISTORY_KEY] as VaultHistory | undefined;782    const snapshot: VaultSnapshot = {783      id: crypto.randomUUID(), savedAt: Date.now(), reason: "local_save",784      vault_a: JSON.stringify(slot), vault_b: JSON.stringify(raw[SLOT_B] ?? slot), entryCount: null,785    };786    const previousStamp = Number(raw.peach_last_modified_at);787    const nextSlot: StoredVault = { ...slot, ...encrypted, ...pwRoot,788      salt: hex(salt), recovery_vault_key: recoveryVaultKey };789    // One storage transaction keeps the rollback snapshot and all new-key fields together.790    await chrome.storage.local.set({791      [SLOT_A]: nextSlot,792      [HISTORY_KEY]: { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) },793      peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previousStamp) ? previousStamp + 1 : 0)),794    });795    committed = true;796    check();797    derivedKey = newKey;798    rootKey = recoveredRoot;799    newKey = null;800    recoveredRoot = null;801    entries = payload.entries;802    tombstones = payload.tombstones;803    duressConfigured = payload.duressConfigured;804    vaultMode = "real";805    buildDomainIndexSync(entries);806    await saveSessionKey(derivedKey, "real", epoch);807    if (epoch !== vaultEpoch) throw new Error("vault_locked");808    await identityHooks?.onKeysRotated();809    if (epoch !== vaultEpoch) throw new Error("vault_locked");810    await reconcilePairSecrets(rootKey);811    if (epoch !== vaultEpoch) throw new Error("vault_locked");812    await clearPinUnlockStorage();813    if (epoch !== vaultEpoch) throw new Error("vault_locked");814    touchAutoLock();815    return { committed: true, unlocked: true };816  } catch (error) {817    if (committed) {818      console.warn("[Peach] recovery password saved; unlock required:", error);819      if (derivedKey && epoch === vaultEpoch) {820        try { await lock(); }821        catch (lockError) { console.warn("[Peach] recovery session cleanup failed:", lockError); }822      }823      return { committed: true, unlocked: false };824    }825    if (derivedKey && epoch === vaultEpoch) await lock();826    throw error;827  } finally {828    if (oldKey) zeroKey(oldKey);829    if (newKey) zeroKey(newKey);830    if (recoveredRoot) zeroKey(recoveredRoot);831    recoveryInFlight = false;832    settle();833  }834}835836/// Cancel recovery and finish its issued storage write before removing vault data.837export async function withVaultRemoval<T>(remove: () => Promise<T>): Promise<T> {838  vaultRemovalsInFlight++;839  try {840    await lock();841    await recoverySettled;842    await creationSettled;843    return await remove();844  } finally {845    vaultRemovalsInFlight--;846  }847}848849/**850 * Recover the session root key by AES-GCM-decrypting the pw_root_* fields851 * (a second wrapping of the root key under the password-derived key). This852 * is what makes GET_RECOVERY_WORDS work across lock/unlock cycles without853 * the user re-entering their recovery phrase: the same root key bytes —854 * and therefore the same 12 words — survive every unlock.855 *856 * Returns null when the escrow is absent or decryption fails.857 */858async function deriveRootKeyFromDerivedKey(859  derivedKeyBytes: Uint8Array,860  slotA: StoredVault,861): Promise<Uint8Array | null> {862  if (!slotA.pw_root_ciphertext || !slotA.pw_root_nonce || !slotA.pw_root_tag) {863    return null;864  }865  try {866    const rootHex = await decrypt(867      derivedKeyBytes,868      slotA.pw_root_nonce,869      slotA.pw_root_ciphertext,870      slotA.pw_root_tag,871      "pw_root_v1",872    );873    return unhex(rootHex);874  } catch {875    return null;876  }877}878879export async function sealIdentityKeyUnderVault(ik: Uint8Array): Promise<IdentityKeyEnvelope> {880  if (vaultMode !== "real" || !rootKey || !derivedKey) throw new Error("vault_locked");881  // The root wrap survives password change and recovery-words re-key; the882  // local wrap is available during normal unlock. Pending is only pre-vault.883  const [root, local] = await Promise.all([884    encrypt(rootKey, hex(ik), "peach-local-identity-ik-root-v1"),885    encrypt(derivedKey, hex(ik), "peach-local-identity-ik-local-v1"),886  ]);887  return { root, local };888}889890export async function sealIdentityKeyPreVault(891  password: string,892  ik: Uint8Array,893): Promise<IdentityKeyEnvelope> {894  const salt = generateSalt();895  const key = await deriveKey(password, salt);896  try {897    const pending = await encrypt(key, hex(ik), "peach-local-identity-ik-pending-v1");898    return { pending, pendingSalt: hex(salt) };899  } finally {900    zeroKey(key);901  }902}903904/**905 * Open the identity key with any wrapping key that is currently available:906 * the live vault-unlock key, then the vault root key, then the pre-vault907 * password. Each attempt is awaited only after the previous one fails, so a908 * successful early unwrap never leaves a later decrypt rejection unobserved,909 * and the pre-vault Argon2id is not paid when a vault key already opens the910 * envelope.911 */912export async function openIdentityKey(913  env: IdentityKeyEnvelope,914  password?: string,915): Promise<Uint8Array | null> {916  if (env.local && derivedKey) {917    const ik = await openSealedKey(derivedKey, env.local, "peach-local-identity-ik-local-v1");918    if (ik) return ik;919  }920  if (env.root && rootKey) {921    const ik = await openSealedKey(rootKey, env.root, "peach-local-identity-ik-root-v1");922    if (ik) return ik;923  }924  if (!env.pending || !env.pendingSalt || password === undefined) return null;925  let key: Uint8Array;926  try {927    const salt = unhex(env.pendingSalt);928    key = await deriveKey(password, salt);929    salt.fill(0);930  } catch {931    return null;932  }933  try {934    return await openSealedKey(key, env.pending, "peach-local-identity-ik-pending-v1");935  } finally {936    zeroKey(key);937  }938}939940/** Decrypt a sealed 32-byte key; null for a wrong key, a bad shape, or corrupt bytes. */941async function openSealedKey(942  key: Uint8Array,943  box: SealedBox,944  info: string,945): Promise<Uint8Array | null> {946  try {947    const value = unhex(await decrypt(key, box.nonce, box.ciphertext, box.tag, info));948    if (value.length === 32) return value;949    value.fill(0);950    return null;951  } catch {952    return null;953  }954}955956// AES-GCM-wrap rootKey under derivedKey for the pw_root_* fields. Returns the957// hex-encoded ciphertext/nonce/tag triple ready to embed in StoredVault.958async function wrapRootKeyForDerivedKey(959  derivedKeyBytes: Uint8Array,960  rootKeyBytes: Uint8Array,961): Promise<{ pw_root_ciphertext: string; pw_root_nonce: string; pw_root_tag: string }> {962  const { nonce, ciphertext, tag } = await encrypt(derivedKeyBytes, hex(rootKeyBytes), "pw_root_v1");963  return {964    pw_root_ciphertext: ciphertext,965    pw_root_nonce: nonce,966    pw_root_tag: tag,967  };968}969970/** Returns the 12 recovery words for the current session's root key. */971export async function getRecoveryWords(): Promise<string[]> {972  if (!rootKey) {973    throw new Error("recovery not set up");974  }975  return rootKeyToWords(rootKey);976}977978async function loadSlot(key: string): Promise<StoredVault | null> {979  const result = await chrome.storage.local.get(key);980  return (result as Record<string, StoredVault | undefined>)[key] ?? null;981}982983async function writeSlot(key: string, vault: StoredVault): Promise<void> {984  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");985  vaultWritesInFlight++;986  try {987    await chrome.storage.local.set({ [key]: vault });988  } catch (err) {989    throw mapStorageError(err);990  } finally {991    vaultWritesInFlight--;992  }993}994995/**996 * Roll back a vault that was created by [createVaultFromRootKey] but997 * couldn't be paired (e.g. the subsequent license activation, identity998 * derivation, or paired-device upsert failed). Without this, a failed999 * receiver session leaves behind an empty vault — the user has to1000 * re-pair to get a working setup, but the empty vault sits in the way.1001 *1002 * The call is idempotent: removing keys that aren't there is a no-op.1003 */1004export async function rollbackAdoptedVault(): Promise<void> {1005  await withVaultRemoval(async () => {1006    try {1007      await chrome.storage.local.remove([1008        SLOT_A,1009        SLOT_B,1010        "peach_last_modified_at",1011      ]);1012    } catch (err) {1013      throw mapStorageError(err);1014    }1015  });1016}10171018async function commitCreatedVaultSlots(slotA: StoredVault, slotB: StoredVault): Promise<void> {1019  if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1020  vaultWritesInFlight++;1021  try {1022    const raw = await chrome.storage.local.get("peach_last_modified_at");1023    const previous = Number(1024      (raw as Record<string, unknown>).peach_last_modified_at,1025    );1026    const next = Math.max(1027      Date.now(),1028      Number.isFinite(previous) ? previous + 1 : 0,1029    );1030    try {1031      if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1032      await chrome.storage.local.set({1033        [SLOT_A]: slotA,1034        [SLOT_B]: slotB,1035        peach_last_modified_at: String(next),1036      });1037    } catch (err) {1038      throw mapStorageError(err);1039    }1040  } finally {1041    vaultWritesInFlight--;1042  }1043}10441045// Monotonic clock for per-entry modifiedAt / deletedAt timestamps. Guards the1046// sync layer's last-write-wins merge against wall-clock regressions (NTP step,1047// manual clock change, DST glitch): a backwards Date.now() must never produce1048// an entry timestamp that's <= the entry's existing modifiedAt, or a genuine1049// local edit would lose to a stale remote copy. The returned value is always1050// strictly greater than both the entry's current modifiedAt and the previous1051// call's result (SEV-2-E).1052let lastEntryTimestamp = 0;1053function monotonicEntryTimestamp(currentModifiedAt?: number): number {1054  const base = Math.max(1055    Date.now(),1056    (currentModifiedAt ?? 0) + 1,1057    lastEntryTimestamp + 1,1058  );1059  lastEntryTimestamp = base;1060  return base;1061}10621063async function stampLocalVaultMutation(): Promise<void> {1064  if (vaultCreatesInFlight) throw new Error("vault_changed");1065  const raw = await chrome.storage.local.get("peach_last_modified_at");1066  const previous = Number(1067    (raw as Record<string, unknown>).peach_last_modified_at,1068  );1069  const next = Math.max(1070    Date.now(),1071    Number.isFinite(previous) ? previous + 1 : 0,1072  );1073  if (vaultCreatesInFlight) throw new Error("vault_changed");1074  await chrome.storage.local.set({1075    peach_last_modified_at: String(next),1076  });1077}10781079// ---------------------------------------------------------------------------1080// Padding + noise helpers1081// ---------------------------------------------------------------------------10821083/**1084 * Pads the plaintext string with trailing spaces so that the encoded byte1085 * length is a multiple of PAD_BLOCK. JSON.parse tolerates trailing1086 * whitespace after a complete document, so the padding is transparent on1087 * decode. Ciphertext length equals plaintext length plus a 16-byte tag.1088 */1089function padPlaintext(json: string, minBytes = 0): string {1090  const encoded = new TextEncoder().encode(json);1091  const bucket = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);1092  // minBytes lets the duress path force a fixed ceiling so both slots match.1093  const target = Math.max(bucket, minBytes);1094  const padLen = target - encoded.length;1095  return json + " ".repeat(padLen);1096}10971098/**1099 * Produces a StoredVault-shaped record filled with CSPRNG bytes. The1100 * ciphertext length matches the given byte count. Because GCM ciphertext is1101 * pseudo-random, this blob is indistinguishable at rest from a real1102 * encrypted vault without the key.1103 *1104 * crypto.getRandomValues() caps each call at 65536 bytes (the Web Crypto1105 * spec hard limit). Chunk the fill so vaults larger than that — common once1106 * the user has dozens of entries or any passkey — don't throw.1107 */1108const CSPRNG_CHUNK = 65_536;11091110function fillRandom(buf: Uint8Array): Uint8Array {1111  for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {1112    const end = Math.min(offset + CSPRNG_CHUNK, buf.length);1113    const chunk = new Uint8Array(end - offset);1114    crypto.getRandomValues(chunk);1115    buf.set(chunk, offset);1116  }1117  return buf;1118}11191120function generateNoiseBlob(ciphertextBytes: number): StoredVault {1121  const salt = crypto.getRandomValues(new Uint8Array(16));1122  const nonce = crypto.getRandomValues(new Uint8Array(12));1123  const cipher = fillRandom(new Uint8Array(ciphertextBytes));1124  const tag = crypto.getRandomValues(new Uint8Array(16));1125  return {1126    version: 1,1127    salt: hex(salt),1128    nonce: hex(nonce),1129    ciphertext: hex(cipher),1130    tag: hex(tag),1131  };1132}11331134// ---------------------------------------------------------------------------1135// Encrypted plaintext envelope1136// ---------------------------------------------------------------------------11371138type VaultPayload = {1139  entries: VaultEntry[];1140  tombstones?: Record<string, number>;1141  duressConfigured?: boolean;1142};11431144type DecryptedPayload = {1145  entries: VaultEntry[];1146  tombstones: Map<string, number>;1147  duressConfigured: boolean;1148};11491150function encodePayload(entries: VaultEntry[], duress: boolean, minBytes = 0): string {1151  const envelope: VaultPayload = {1152    entries,1153    tombstones: Object.fromEntries(tombstones),1154    duressConfigured: duress,1155  };1156  return padPlaintext(JSON.stringify(envelope), minBytes);1157}11581159function decodeTombstones(raw: unknown, allEntries: VaultEntry[]): Map<string, number> {1160  const result = new Map<string, number>();1161  if (raw && typeof raw === "object" && !Array.isArray(raw)) {1162    for (const [id, timestamp] of Object.entries(raw as Record<string, unknown>)) {1163      if (typeof timestamp === "number" && Number.isFinite(timestamp) && timestamp > 0) {1164        result.set(id, timestamp);1165      }1166    }1167  }1168  // Older payloads had no ledger. Rebuild the durable portion from any1169  // soft-deleted entries before they are eligible for a later purge.1170  for (const entry of allEntries) {1171    if (typeof entry.deletedAt !== "number" || !Number.isFinite(entry.deletedAt) || entry.deletedAt <= 0) {1172      continue;1173    }1174    if ((result.get(entry.id) ?? 0) < entry.deletedAt) {1175      result.set(entry.id, entry.deletedAt);1176    }1177  }1178  return result;1179}11801181function reconcileTombstones(): void {1182  const byId = new Map(entries.map((entry) => [entry.id, entry]));1183  for (const [id] of tombstones) {1184    if (byId.has(id) && !byId.get(id)?.deletedAt) tombstones.delete(id);1185  }1186  for (const entry of entries) {1187    if (typeof entry.deletedAt === "number" && Number.isFinite(entry.deletedAt) && entry.deletedAt > 0) {1188      if ((tombstones.get(entry.id) ?? 0) < entry.deletedAt) {1189        tombstones.set(entry.id, entry.deletedAt);1190      }1191    }1192  }1193}11941195function decodePayload(plain: string): DecryptedPayload {1196  const parsed = JSON.parse(plain) as VaultPayload;1197  if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.entries)) {1198    throw new Error("invalid vault payload");1199  }1200  const normalized = parsed.entries.map(normalizeEntry);1201  return {1202    entries: normalized,1203    tombstones: decodeTombstones(parsed.tombstones, normalized),1204    duressConfigured: parsed.duressConfigured === true,1205  };1206}12071208/**1209 * Consolidate duplicate passkey records after registration.1210 *1211 * Multiple registrations for one RP can leave duplicate passkey records. This1212 * pass collapses the duplicates:1213 *1214 *   1. Group passkey-bearing (and not deleted) entries by `passkey.rpId`.1215 *   2. Within each group, the most recently-active credential wins (prefer1216 *      lastUsedAt, fall back to passkey.createdAt, fall back to modifiedAt).1217 *   3. If a NON-passkey login entry exists for that RP (matched by url or1218 *      additionalUrls hostname), attach the winning passkey to it and1219 *      soft-delete every passkey-bearing entry in the group.1220 *   4. Otherwise, soft-delete every loser in the group, keeping the winner1221 *      as a passkey-only entry.1222 *1223 * Soft delete (deletedAt) rather than splice — the trash flow keeps the1224 * record around for retention and the user can restore if the heuristic1225 * picked wrong. The `merged` flag goes back to decodePayload so the1226 * unlock path persists the consolidated shape immediately.1227 */1228function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {1229  let merged = false;1230  const now = Date.now();12311232  const candidates = entries.filter((e) => !e.deletedAt && e.passkey);1233  const byRpId = new Map<string, VaultEntry[]>();1234  for (const e of candidates) {1235    const rpId = e.passkey!.rpId;1236    const list = byRpId.get(rpId);1237    if (list) list.push(e);1238    else byRpId.set(rpId, [e]);1239  }12401241  for (const [rpId, group] of byRpId) {1242    if (group.length === 0) continue;1243    group.sort((a, b) => {1244      const aT =1245        a.passkey!.lastUsedAt ?? a.passkey!.createdAt ?? a.modifiedAt ?? a.createdAt;1246      const bT =1247        b.passkey!.lastUsedAt ?? b.passkey!.createdAt ?? b.modifiedAt ?? b.createdAt;1248      return bT - aT;1249    });1250    const winner = group[0]!;12511252    // Look for a NON-passkey login entry matching this RP. Use the URL1253    // hostname rather than a substring search so a "login.foo.com" entry1254    // doesn't accidentally absorb a passkey for "foo.com".1255    const loginTarget = entries.find((e) => {1256      if (e.deletedAt || e.passkey || e.type !== "login") return false;1257      if (e.url && extractDomain(e.url) === rpId) return true;1258      for (const extra of e.additionalUrls ?? []) {1259        if (extractDomain(extra) === rpId) return true;1260      }1261      return false;1262    });12631264    if (loginTarget) {1265      loginTarget.passkey = winner.passkey;1266      // A passkey entry may also carry the site's TOTP seed. Preserve it when1267      // the passkey is consolidated onto an existing login instead of1268      // soft-deleting the only record that held the 2FA configuration.1269      if (!loginTarget.totp && winner.totp) {1270        loginTarget.totp = winner.totp;1271        loginTarget.totpAlgorithm = winner.totpAlgorithm;1272        loginTarget.totpDigits = winner.totpDigits;1273        loginTarget.totpPeriod = winner.totpPeriod;1274      }1275      loginTarget.modifiedAt = now;1276      for (const dup of group) {1277        if (!dup.deletedAt) {1278          dup.deletedAt = now;1279          dup.modifiedAt = now;1280        }1281      }1282      merged = true;1283    } else if (group.length > 1) {1284      for (let i = 1; i < group.length; i += 1) {1285        const dup = group[i]!;1286        if (!dup.deletedAt) {1287          dup.deletedAt = now;1288          dup.modifiedAt = now;1289        }1290      }1291      merged = true;1292    }1293  }12941295  return { merged };1296}12971298// Validates that a `StoredVault` record on disk has the field shape we expect1299// before treating an AES-GCM decrypt success as a clean unlock. AES-GCM only1300// authenticates the static VERSION_BYTE AAD, not the `version` field on the1301// outer record — a corrupted `version: 42` slot still decrypts cleanly. This1302// check surfaces that as `corrupted` (M7/COR-007) so the popup can offer a1303// history-restore path instead of falsely reporting "wrong password".1304function hasValidVaultSchema(v: unknown): v is StoredVault {1305  if (typeof v !== "object" || v === null) return false;1306  const r = v as Record<string, unknown>;1307  return (1308    r.version === 1 &&1309    typeof r.salt === "string" &&1310    typeof r.nonce === "string" &&1311    typeof r.ciphertext === "string" &&1312    typeof r.tag === "string"1313  );1314}1315const MAX_HISTORY_BLOB_BYTES = 1_024 * 1_024;13161317function hasValidHistorySlot(value: unknown): value is StoredVault {1318  if (!hasValidVaultSchema(value)) return false;1319  return /^[0-9a-f]{32}$/i.test(value.salt) &&1320    /^[0-9a-f]{24}$/i.test(value.nonce) &&1321    /^[0-9a-f]+$/i.test(value.ciphertext) &&1322    value.ciphertext.length % 2 === 0 &&1323    value.ciphertext.length / 2 <= MAX_HISTORY_BLOB_BYTES &&1324    /^[0-9a-f]{32}$/i.test(value.tag);1325}13261327function parseHistorySlot(value: string): StoredVault | null {1328  try {1329    const parsed: unknown = JSON.parse(value);1330    return hasValidHistorySlot(parsed) ? parsed : null;1331  } catch {1332    return null;1333  }1334}13351336function isHistoryRecord(value: unknown): value is VaultSnapshot {1337  if (typeof value !== "object" || value === null) return false;1338  const record = value as Record<string, unknown>;1339  return typeof record.id === "string" && record.id.length > 0 && record.id.length <= 128 &&1340    typeof record.savedAt === "number" && Number.isFinite(record.savedAt) &&1341    typeof record.reason === "string" &&1342    typeof record.vault_a === "string" && record.vault_a.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1343    typeof record.vault_b === "string" && record.vault_b.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1344    (record.entryCount === null || typeof record.entryCount === "number");1345}13461347function sanitizeHistory(value: unknown): VaultSnapshot[] {1348  if (typeof value !== "object" || value === null) return [];1349  if (!("snapshots" in value) || !Array.isArray(value.snapshots)) return [];1350  return value.snapshots.filter(isHistoryRecord).slice(0, HISTORY_MAX);1351}13521353export type TryDecryptResult =1354  | { status: "ok"; payload: DecryptedPayload }1355  | { status: "wrong_key" }1356  | { status: "corrupted"; reason: string };13571358// Exported solely for `unlockFromCodex` below, which needs to verify a1359// supplied passphrase against a slotA blob *without* committing anything to1360// storage. Keep this internal otherwise — callers crossing the messages.ts1361// boundary should always go through `unlock` / `verifyMainPassword` so the1362// constant-time invariants in Projects.md §3.4 are not bypassed.1363export async function tryDecryptSlot(1364  vault: StoredVault,1365  key: Uint8Array,1366  aadTag?: string,1367): Promise<DecryptedPayload | null> {1368  const res = await tryDecryptSlotResult(vault, key, aadTag);1369  return res.status === "ok" ? res.payload : null;1370}13711372export async function tryDecryptSlotResult(1373  vault: StoredVault,1374  key: Uint8Array,1375  aadTag?: string,1376): Promise<TryDecryptResult> {1377  if (!hasValidVaultSchema(vault)) {1378    return { status: "corrupted", reason: "invalid_slot_schema" };1379  }1380  let plain: string;1381  try {1382    plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);1383  } catch {1384    return { status: "wrong_key" };1385  }1386  try {1387    const parsed = JSON.parse(plain) as unknown;1388    if (typeof parsed !== "object" || parsed === null) {1389      return { status: "corrupted", reason: "invalid_payload_shape" };1390    }1391    if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {1392      return { status: "corrupted", reason: "invalid_payload_shape" };1393    }1394    return { status: "ok", payload: decodePayload(plain) };1395  } catch {1396    return { status: "corrupted", reason: "invalid_payload_json" };1397  }1398}13991400// ---------------------------------------------------------------------------1401// Core operations1402// ---------------------------------------------------------------------------14031404function buildDomainIndexSync(all: VaultEntry[]): void {1405  domainIndex = new Map();14061407  for (const entry of all) {1408    if (entry.deletedAt) continue;1409    if (entry.type === "note" || entry.type === "card") continue;14101411    // An entry can match multiple sites via `additionalUrls`. Index each1412    // hostname so `queryDomain` returns the entry regardless of which alias1413    // the user is currently visiting. Dedupe per-entry so a single entry1414    // never appears twice in one bucket.1415    const domains = new Set<string>();1416    const primary = extractDomain(entry.url ?? "");1417    if (primary) domains.add(primary);1418    for (const extra of entry.additionalUrls ?? []) {1419      const d = extractDomain(extra);1420      if (d) domains.add(d);1421    }1422    if (domains.size === 0) continue;14231424    for (const domain of domains) {1425      const bucket = domainIndex.get(domain) ?? [];1426      bucket.push(entry);1427      domainIndex.set(domain, bucket);1428    }1429  }1430}14311432export async function createVault(password: string, replacement?: "warned-import"): Promise<{ committed: true; unlocked: boolean }> {1433  if (replacement !== undefined && replacement !== "warned-import") throw new Error("invalid_payload");1434  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");1435  vaultCreatesInFlight++;1436  let settle!: () => void;1437  creationSettled = new Promise<void>((resolve) => { settle = resolve; });1438  let nextKey: Uint8Array | null = null;1439  let nextRoot: Uint8Array | null = null;1440  let committed = false;1441  let publishedEpoch: number | null = null;1442  const epoch = vaultEpoch;1443  const check = () => {1444    if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1445  };1446  try {1447    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1448    check();1449    const occupied = raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;1450    if (occupied && replacement !== "warned-import") throw new Error("vault_already_exists");1451    const salt = generateSalt();1452    nextKey = await deriveKey(password, salt);1453    check();1454    const recovery = await generateAndWrapRootKey();1455    nextRoot = unhex(recovery.rawRootKey);1456    check();1457    const encrypted = await encrypt(nextKey, encodePayload([], false, 0), "slot_a_v1");1458    const pwRoot = await wrapRootKeyForDerivedKey(nextKey, nextRoot);1459    const recoveryVaultKey = await encrypt(nextRoot, hex(nextKey), "recovery_vault_key_v1");1460    check();1461    const slotA: StoredVault = {1462      ...encrypted, ...pwRoot, version: 1, salt: hex(salt),1463      recovery_vault_key: recoveryVaultKey,1464      recovery_salt: recovery.recoverySalt,1465      recovery_wrapped_root_key: recovery.wrappedRootKey,1466      recovery_nonce: recovery.wrappedNonce,1467      recovery_tag: recovery.wrappedTag,1468    };1469    const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1470    check();1471    if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");1472    const previous = Number(raw.peach_last_modified_at);1473    const update: Record<string, unknown> = {1474      [SLOT_A]: slotA, [SLOT_B]: generateNoiseBlob(encrypted.ciphertext.length / 2),1475      peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previous) ? previous + 1 : 0)),1476    };1477    if (occupied) {1478      const history = raw[HISTORY_KEY] as VaultHistory | undefined;1479      const snapshot: VaultSnapshot = {1480        id: crypto.randomUUID(), savedAt: Date.now(), reason: "restore", entryCount: null,1481        vault_a: JSON.stringify(raw[SLOT_A] ?? null), vault_b: JSON.stringify(raw[SLOT_B] ?? null),1482      };1483      update[HISTORY_KEY] = { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) };1484    }1485    try { await chrome.storage.local.set(update); }1486    catch (error) { throw mapStorageError(error); }1487    committed = true;1488    if (epoch !== vaultEpoch || vaultRemovalsInFlight) return { committed: true, unlocked: false };1489    const previousKey = derivedKey;1490    const previousRoot = rootKey;1491    publishedEpoch = ++vaultEpoch;1492    derivedKey = nextKey;1493    rootKey = nextRoot;1494    nextKey = null;1495    nextRoot = null;1496    entries = [];1497    tombstones = new Map();1498    vaultMode = "real";1499    duressConfigured = false;1500    buildDomainIndexSync(entries);1501    if (previousKey) zeroKey(previousKey);1502    if (previousRoot) zeroKey(previousRoot);1503    await clearSessionKey();1504    if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1505    await identityHooks?.onVaultCreated(password).catch((error) => {1506      console.warn("[Peach] local identity promotion failed:", error);1507    });1508    if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1509    touchAutoLock();1510    return { committed: true, unlocked: true };1511  } catch (error) {1512    if (!committed) throw error;1513    console.warn("[Peach] vault saved; unlock required:", error);1514    if (publishedEpoch === vaultEpoch) {1515      await lock().catch((lockError) => console.warn("[Peach] creation session cleanup failed:", lockError));1516    }1517    return { committed: true, unlocked: false };1518  } finally {1519    if (nextKey) zeroKey(nextKey);1520    if (nextRoot) zeroKey(nextRoot);1521    vaultCreatesInFlight--;1522    settle();1523  }1524}15251526/**1527 * Creates a local vault from an existing vault root key received through the1528 * SAS-gated adoption protocol. The password is local to this device; it wraps1529 * the adopted root key at rest and does not need to match the source device.1530 */1531export async function createVaultFromRootKey(1532  password: string,1533  rootKeyHex: string,1534): Promise<{ vaultId: string }> {1535  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");1536  if (typeof password !== "string" || password.length === 0) {1537    throw new Error("ADOPT_INVALID_PASSWORD");1538  }1539  if (typeof rootKeyHex !== "string" || !/^[0-9a-f]{64}$/.test(rootKeyHex)) {1540    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars");1541  }15421543  if (vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");1544  const rootKeyBytes = unhex(rootKeyHex);1545  if (rootKeyBytes.length !== 32) {1546    rootKeyBytes.fill(0);1547    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");1548  }15491550  vaultCreatesInFlight++;1551  let settle!: () => void;1552  creationSettled = new Promise<void>((resolve) => { settle = resolve; });1553  const epoch = vaultEpoch;1554  let nextDerivedKey: Uint8Array | null = null;1555  let sessionRootKey: Uint8Array | null = null;1556  let committed = false;1557  try {1558    if (await hasVault()) {1559      throw new Error("ADOPT_VAULT_ALREADY_EXISTS");1560    }15611562    const nextEntries: VaultEntry[] = [];1563    const nextDuressConfigured = false;1564    const vaultId = await computeVaultId(rootKeyBytes);1565    const salt = generateSalt();1566    nextDerivedKey = await deriveKey(password, salt);1567    const recovery = await wrapExistingRootKeyForRecovery(rootKeyBytes);15681569    sessionRootKey = new Uint8Array(rootKeyBytes);1570    const plaintext = encodePayload(nextEntries, nextDuressConfigured, 0);1571    const { nonce, ciphertext, tag } = await encrypt(nextDerivedKey, plaintext, "slot_a_v1");1572    const pwRoot = await wrapRootKeyForDerivedKey(nextDerivedKey, sessionRootKey);1573    const slotA: StoredVault = {1574      recovery_vault_key: await encrypt(sessionRootKey, hex(nextDerivedKey), "recovery_vault_key_v1"),1575      version: 1,1576      salt: hex(salt),1577      nonce,1578      ciphertext,1579      tag,1580      recovery_salt: recovery.recoverySalt,1581      recovery_wrapped_root_key: recovery.wrappedRootKey,1582      recovery_nonce: recovery.wrappedNonce,1583      recovery_tag: recovery.wrappedTag,1584      ...pwRoot,1585    };1586    const slotB = generateNoiseBlob(ciphertext.length / 2);1587    if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1588    await commitCreatedVaultSlots(slotA, slotB);1589    committed = true;1590    if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1591    vaultEpoch++;15921593    const previousDerivedKey = derivedKey;1594    const previousRootKey = rootKey;1595    derivedKey = nextDerivedKey;1596    rootKey = sessionRootKey;1597    nextDerivedKey = null;1598    sessionRootKey = null;1599    entries = nextEntries;1600    tombstones = new Map();1601    vaultMode = "real";1602    duressConfigured = nextDuressConfigured;1603    buildDomainIndexSync(entries);1604    if (previousDerivedKey && previousDerivedKey !== derivedKey) zeroKey(previousDerivedKey);1605    if (previousRootKey && previousRootKey !== rootKey) previousRootKey.fill(0);1606    touchAutoLock();16071608    // The receiver's identity was minted before this vault existed (adoption v21609    // needs it in its first frame), so re-seal it under the vault keys now.1610    await identityHooks?.onVaultCreated(password).catch((error) => {1611      console.warn("[Peach] local identity promotion failed:", error);1612    });16131614    return { vaultId };1615  } catch (error) {1616    if (committed) {1617      // Removal cannot use withVaultRemoval while this operation owns creationSettled.1618      try { await lock(); }1619      finally { await chrome.storage.local.remove([SLOT_A, SLOT_B, "peach_last_modified_at"]); }1620    }1621    throw error;1622  } finally {1623    vaultCreatesInFlight--;1624    settle();1625    rootKeyBytes.fill(0);1626    if (nextDerivedKey) zeroKey(nextDerivedKey);1627    if (sessionRootKey) sessionRootKey.fill(0);1628  }1629}16301631export async function hasVault(): Promise<boolean> {1632  const raw = await chrome.storage.local.get([SLOT_A, SLOT_B]);1633  return raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;1634}16351636/**1637 * Returns whether the real vault has recorded that a duress passphrase is1638 * configured. Reliable only after a real-mode unlock — before unlock or in1639 * decoy mode, returns false because we cannot read slot A's plaintext.1640 */1641export async function isDuressEnabled(): Promise<boolean> {1642  return vaultMode === "real" && duressConfigured;1643}16441645export async function setupDuress(duressPassword: string): Promise<void> {1646  if (vaultCreatesInFlight) throw new Error("vault_changed");1647  vaultWritesInFlight++;1648  try {1649  if (!derivedKey || vaultMode !== "real") {1650    throw new Error("vault must be unlocked in real mode");1651  }1652  // Encrypt the decoy payload (empty entries) under the duress key. Pad to1653  // at least the current slot A ciphertext size so the two slots look the1654  // same at rest at setup time.1655  const slotA = await loadSlot(SLOT_A);1656  if (!slotA) throw new Error("missing slot A");16571658  const decoySalt = generateSalt();1659  const decoyKey = await deriveKey(duressPassword, decoySalt);1660  try {1661    // Pad the decoy to the fixed duress ceiling. Slot A is re-encrypted to the1662    // same ceiling by the persistSlotA() call below (duressConfigured is now1663    // true), so both slots are exactly DURESS_SLOT_SIZE+tag at rest and their1664    // lengths cannot reveal that duress is configured (audit MEDIUM).1665    const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);1666    const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");1667    await writeSlot(SLOT_B, {1668      version: 1,1669      salt: hex(decoySalt),1670      nonce,1671      ciphertext,1672      tag,1673    });1674  } finally {1675    zeroKey(decoyKey);1676  }16771678  // Re-encrypt slot A with the duressConfigured flag set to true. No external1679  // flag is written — the bit lives inside the encrypted envelope.1680  duressConfigured = true;1681  await persistSlotA();1682  } finally { vaultWritesInFlight--; }1683}16841685export async function disableDuress(): Promise<void> {1686  if (vaultCreatesInFlight) throw new Error("vault_changed");1687  vaultWritesInFlight++;1688  try {1689  if (!derivedKey || vaultMode !== "real") {1690    throw new Error("vault must be unlocked in real mode");1691  }1692  // Overwrite slot B with fresh noise that matches slot A's size. The slot1693  // remains occupied so its mere existence does not signal that duress was1694  // ever configured.1695  const slotA = await loadSlot(SLOT_A);1696  if (slotA) {1697    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));1698  }16991700  duressConfigured = false;1701  await persistSlotA();1702  } finally { vaultWritesInFlight--; }1703}17041705// L14/COR-015: this function intentionally checks slot A (real vault) only.1706// A duress-mode user attempting changePassword is rejected earlier by the1707// vaultMode === 'decoy' check at changePassword. The real-vs-decoy1708// distinction here is by design — duress users cannot rotate the real1709// password by guessing it, and the asymmetry in error timing is acceptable1710// because duress mode is opt-in and the user knows their own decoy key.1711export async function verifyMainPassword(password: string): Promise<boolean> {1712  const slotA = await loadSlot(SLOT_A);1713  if (!slotA) return false;1714  const key = await deriveKey(password, unhex(slotA.salt));1715  try {1716    return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;1717  } finally {1718    zeroKey(key);1719  }1720}17211722export async function unlock(password: string): Promise<boolean> {1723  return attemptUnlockWithDerive(password, deriveKey);1724}17251726async function attemptUnlockWithDerive(1727  password: string,1728  derive: typeof deriveKey,1729): Promise<boolean> {1730  vaultUnlocksInFlight++;1731  try {1732  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;1733  const epoch = vaultEpoch;1734  const stale = () => epoch !== vaultEpoch;1735  // Load both current-format slots in parallel. Both exist on a supported1736  // install; the1737  // parallel load and the parallel derivation below keep wall-clock time1738  // constant regardless of which slot's passphrase (real or decoy) the1739  // caller supplied, so a timing side channel cannot distinguish the1740  // duress path from the real-unlock path (DUR-002).1741  const [slotA, slotB] = await Promise.all([1742    loadSlot(SLOT_A),1743    loadSlot(SLOT_B),1744  ]);17451746  // Derive both keys in parallel, unconditionally.1747  const [keyA, keyB] = await Promise.all([1748    slotA ? derive(password, unhex(slotA.salt)) : Promise.resolve(null),1749    slotB ? derive(password, unhex(slotB.salt)) : Promise.resolve(null),1750  ]);17511752  // Attempt both decrypts in parallel. The Result variant lets us distinguish1753  // 'wrong_key' from 'corrupted' so callers can offer a history-restore path1754  // when a slot's schema is invalid even though AES-GCM authenticated (M7).1755  const [resultA, resultB] = await Promise.all([1756    keyA && slotA1757      ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")1758      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1759    keyB && slotB1760      ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")1761      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1762  ]);1763  const payloadA = resultA.status === "ok" ? resultA.payload : null;1764  const payloadB = resultB.status === "ok" ? resultB.payload : null;17651766  if (stale()) {1767    if (keyA) zeroKey(keyA);1768    if (keyB) zeroKey(keyB);1769    return false;1770  }17711772  if (payloadA && keyA) {1773    if (stale()) {1774      zeroKey(keyA);1775      if (keyB) zeroKey(keyB);1776      return false;1777    }1778    derivedKey = keyA;1779    vaultMode = "real";1780    entries = payloadA.entries;1781    tombstones = payloadA.tombstones;1782    duressConfigured = payloadA.duressConfigured;1783    buildDomainIndexSync(entries);1784    await loadSettings();1785    if (stale()) {1786      await lock();1787      return false;1788    }1789    touchAutoLock();1790    if (keyB) zeroKey(keyB);17911792    // Current vaults always carry a password-wrapped root key. Older vaults1793    // without this escrow are outside the supported storage format.1794    rootKey = slotA ? await deriveRootKeyFromDerivedKey(keyA, slotA) : null;1795    if (!rootKey) {1796      await lock();1797      return false;1798    }17991800    // Repair missing or stale escrow only after a real password authenticates the slot.1801    if (slotA) {1802      const escrowed = slotA.recovery_vault_key1803        ? await openSealedKey(rootKey, slotA.recovery_vault_key, "recovery_vault_key_v1") : null;1804      const matches = escrowed !== null && escrowed.every((byte, i) => byte === keyA[i]);1805      if (escrowed) zeroKey(escrowed);1806      if (stale()) { await lock(); return false; }1807      if (!matches) {1808        try {1809          const recoveryVaultKey = await encrypt(rootKey, hex(keyA), "recovery_vault_key_v1");1810          if (stale()) { await lock(); return false; }1811          await writeSlot(SLOT_A, { ...slotA, recovery_vault_key: recoveryVaultKey });1812          if (stale()) { await lock(); return false; }1813        } catch (error) {1814          await lock();1815          throw error;1816        }1817      }1818    }18191820    // PB-26-213: adopt legacy plaintext pair secrets into the encrypted1821    // record and refresh the trusted-session operational copy.1822    await reconcilePairSecrets(rootKey);1823    if (stale()) {1824      await lock();1825      return false;1826    }1827    await lockedSyncUnlockHook?.().catch((error) => {1828      console.warn("[Peach sync] locked inbox drain failed:", error);1829    });1830    if (stale()) {1831      await lock();1832      return false;1833    }1834    await resetPinFailedAttempts();1835    if (stale()) {1836      await lock();1837      return false;1838    }1839    await saveSessionKey(keyA, "real", epoch);1840    if (stale()) return false;1841    return true;1842  }18431844  if (payloadB && keyB) {1845    if (stale()) {1846      zeroKey(keyB);1847      if (keyA) zeroKey(keyA);1848      return false;1849    }1850    derivedKey = keyB;1851    vaultMode = "decoy";1852    decoySyncTeardownHook?.();1853    // A duress session must not retain the real vault's root key. It gates the1854    // recovery words, the sync identity, and the root wrap of the local device1855    // identity, so leaving it live would expose all three in duress mode.1856    if (rootKey) {1857      rootKey.fill(0);1858      rootKey = null;1859    }1860    entries = payloadB.entries;1861    tombstones = payloadB.tombstones;1862    duressConfigured = false;1863    buildDomainIndexSync(entries);1864    await loadSettings();1865    touchAutoLock();1866    if (keyA) zeroKey(keyA);1867    // PB-26-213: a duress session must never serve the real pair-secret map.1868    await dropSessionCache();1869    // Nor the real device identity: a duress session is not a real one.1870    await notifyIdentitySessionEnded();1871    if (stale()) {1872      await lock();1873      return false;1874    }1875    await saveSessionKey(keyB, "decoy", epoch);1876    if (stale()) return false;1877    return true;1878  }18791880  if (keyA) zeroKey(keyA);1881  if (keyB) zeroKey(keyB);1882  // Surface corruption (good AES tag, broken schema) distinctly from1883  // wrong-password so the popup can offer history-restore (M7/COR-007).1884  if (resultA.status === "corrupted") {1885    lastUnlockFailureReason = resultA.reason;1886  } else if (resultB.status === "corrupted") {1887    lastUnlockFailureReason = resultB.reason;1888  }1889  return false;1890  } finally { vaultUnlocksInFlight--; }1891}18921893// ---------------------------------------------------------------------------1894// MV3 service worker session key — survives SW restarts within a browser session1895// ---------------------------------------------------------------------------18961897// chrome.storage.session is cleared on browser close; survives SW restart.1898// Firefox does not implement it (persistent background script, no restart risk).1899const SESSION_KEY_STORAGE = "peach_session_dk";19001901// Order writes and removals so lock's awaited removal is a barrier after1902// every escrow write that started before it.1903let sessionKeyMutation = Promise.resolve();19041905function mutateSessionKey(mutation: () => Promise<void>): Promise<void> {1906  const task = sessionKeyMutation.then(mutation, mutation);1907  sessionKeyMutation = task.catch(() => undefined);1908  return task;1909}19101911// PB-26-203: the session-key escrow may only operate where startup positively1912// established trusted-only session storage. Defaults to available so direct1913// vault imports (tests, non-entry bootstraps) keep working; entry.ts applies1914// the real hardening result before the first restore.1915let sessionEscrowAvailable = true;19161917/**1918 * Apply the storage-hardening result at startup. When the trusted-only1919 * session state cannot be established, any stored session key is removed and1920 * the escrow stays off: the user unlocks again after a worker restart1921 * instead of trusting an unproven boundary.1922 */1923export async function applyStorageHardening(sessionEscrow: boolean): Promise<void> {1924  setSessionAllowed(sessionEscrow);1925  if (sessionEscrow) return;1926  sessionEscrowAvailable = false;1927  await clearSessionKey();1928}19291930async function saveSessionKey(1931  key: Uint8Array,1932  mode: "real" | "decoy",1933  expectedEpoch = vaultEpoch,1934): Promise<void> {1935  const session = chrome.storage.session;1936  if (!session || !sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;1937  const stored = { keyHex: hex(key), mode };1938  await mutateSessionKey(async () => {1939    if (!sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;1940    await session.set({ [SESSION_KEY_STORAGE]: stored });1941  });1942}19431944async function clearSessionKey(): Promise<void> {1945  const session = chrome.storage.session;1946  if (!session) return;1947  await mutateSessionKey(() => session.remove(SESSION_KEY_STORAGE));1948}19491950// A lock that only holds while the service worker stays alive is no lock at1951// all: a cold worker's restoreFromSession() would find the surviving session1952// key and silently re-unlock ~a minute after the user locked. So lock()1953// bumps this epoch synchronously at entry and zeroes keys/indexes before any1954// await; a restore that started earlier sees the mismatch after its next1955// await and aborts instead of publishing.1956let vaultEpoch = 0;19571958// One in-flight restore shared by concurrent callers: storage is read once1959// and the locked-sync unlock hook runs once.1960let restoreInFlight: Promise<boolean> | null = null;19611962/**1963 * On SW restart, re-derive all in-memory vault state from the session key1964 * stored in chrome.storage.session (set at unlock time, cleared by lock();1965 * also cleared on browser close or when restoration fails).1966 * Returns true if the vault was restored, false if no session key was found.1967 * No-ops if the vault is already unlocked.1968 */1969export async function restoreFromSession(): Promise<boolean> {1970  vaultUnlocksInFlight++;1971  try {1972  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;1973  if (derivedKey !== null) return true;1974  if (restoreInFlight) return restoreInFlight;1975  const task = restoreFromSessionInner();1976  restoreInFlight = task;1977  try {1978    return await task;1979  } finally {1980    restoreInFlight = null;1981  }1982  } finally { vaultUnlocksInFlight--; }1983}19841985async function restoreFromSessionInner(): Promise<boolean> {1986  const epoch = vaultEpoch;1987  const stale = () => epoch !== vaultEpoch;1988  if (derivedKey !== null) return true;1989  if (!sessionEscrowAvailable) return false;1990  if (!chrome.storage.session) return false;1991  const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);1992  if (stale()) return false;1993  const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;1994  if (!entry?.keyHex) return false;19951996  const key = unhex(entry.keyHex);1997  const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;1998  const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";1999  const slot = await loadSlot(slotKey);2000  if (stale()) { zeroKey(key); return false; }2001  if (!slot) { await clearSessionKey(); return false; }20022003  const result = await tryDecryptSlotResult(slot, key, aadTag);2004  if (stale()) { zeroKey(key); return false; }2005  if (result.status !== "ok") { await clearSessionKey(); return false; }20062007  // Decrypted payload stays in locals until the final epoch-checked commit2008  // below; nothing observable is published before then.2009  const payload = result.payload;2010  await loadSettings();2011  if (stale()) { zeroKey(key); return false; }20122013  // Rehydrate the root key used by sync identity derivation from the password2014  // escrow stored on the current vault format.2015  let freshRoot: Uint8Array | null = null;2016  if (entry.mode === "real") {2017    freshRoot = await deriveRootKeyFromDerivedKey(key, slot);2018    if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }2019    if (!freshRoot) {2020      await lock();2021      return false;2022    }2023  }20242025  if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }2026  if (freshRoot) {2027    // PB-26-213: encrypted pair-secret record + session copy, before publish.2028    await reconcilePairSecrets(freshRoot);2029    if (stale()) { zeroKey(key); zeroKey(freshRoot); return false; }2030  } else {2031    // PB-26-213: a duress restore must never serve the real pair-secret map.2032    await dropSessionCache();2033    // Nor the real device identity.2034    await notifyIdentitySessionEnded();2035    if (stale()) { zeroKey(key); return false; }2036  }2037  derivedKey = key;2038  vaultMode = entry.mode;2039  if (entry.mode === "decoy") decoySyncTeardownHook?.();2040  entries = payload.entries;2041  tombstones = payload.tombstones;2042  duressConfigured = entry.mode === "real" ? payload.duressConfigured : false;2043  if (freshRoot) rootKey = freshRoot;2044  buildDomainIndexSync(entries);2045  touchAutoLock();20462047  await lockedSyncUnlockHook?.().catch((error) => {2048    console.warn("[Peach sync] locked inbox drain failed:", error);2049  });2050  if (stale()) return false;20512052  return true;2053}20542055export async function lock(): Promise<void> {2056  // A user-initiated lock must be durable across MV3 service-worker restarts.2057  // The SW is idle-killed after ~30s of inactivity, and the popup's next open2058  // wakes a cold SW whose restoreFromSession() reads chrome.storage.session.2059  // If the session key survived lock(), that restore would silently re-unlock2060  // the vault ~a minute after the user locked it — a lock that only held2061  // while the SW happened to stay alive. The background-sync convenience the2062  // session key once bought (sync runner re-waking to a restored vault) is2063  // not worth an unlocked vault the user never asked to unlock; when locked,2064  // sync-runner correctly reports VAULT_LOCKED instead.2065  vaultEpoch++;2066  if (derivedKey) {2067    zeroKey(derivedKey);2068    derivedKey = null;2069  }2070  if (rootKey) {2071    rootKey.fill(0);2072    rootKey = null;2073  }20742075  entries = [];2076  tombstones = new Map();2077  domainIndex = new Map();2078  vaultMode = "real";2079  duressConfigured = false;2080  clearAutoLock();2081  await clearSessionKey();2082  // The decrypted identity is session state as well, so a locked vault must not2083  // leave one behind; clear it after the in-memory state is gone.2084  await notifyIdentitySessionEnded();2085}20862087export function isUnlocked(): boolean {2088  return derivedKey !== null;2089}2090/** True only while the active session is unlocked through the decoy slot. */2091export function isDecoyMode(): boolean {2092  return derivedKey !== null && vaultMode === "decoy";2093}20942095// Opens the vault using a pre-derived AES-256 key (skipping Argon2id). The2096// PIN-unlock path unwraps this key from its PIN wrap; the passphrase path2097// always derives from scratch via Argon2id.2098export async function unlockWithKey(2099  masterKeyHex: string,2100): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {2101  vaultUnlocksInFlight++;2102  try {2103  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };2104  const epoch = vaultEpoch;2105  const stale = () => epoch !== vaultEpoch;2106  let masterKeyBytes: Uint8Array | null = null;2107  try {2108    masterKeyBytes = unhex(masterKeyHex);2109    const stored = await loadSlot(SLOT_A);2110    if (!stored) return { ok: false, error: "invalid_key" };2111    const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");2112    if (!payload || stale()) {2113      zeroKey(masterKeyBytes);2114      return { ok: false, error: "invalid_key" };2115    }21162117    derivedKey = masterKeyBytes;2118    vaultMode = "real";2119    entries = payload.entries;2120    tombstones = payload.tombstones;2121    duressConfigured = payload.duressConfigured;2122    buildDomainIndexSync(entries);2123    await loadSettings();2124    touchAutoLock();21252126    rootKey = await deriveRootKeyFromDerivedKey(masterKeyBytes, stored);2127    if (!rootKey) {2128      await lock();2129      return { ok: false, error: "invalid_key" };2130    }2131    await reconcilePairSecrets(rootKey);2132    if (stale()) {2133      await lock();2134      return { ok: false, error: "invalid_key" };2135    }2136    await saveSessionKey(masterKeyBytes, "real", epoch);2137    if (stale()) return { ok: false, error: "invalid_key" };2138    return { ok: true, entries };2139  } catch {2140    if (masterKeyBytes && derivedKey !== masterKeyBytes) zeroKey(masterKeyBytes);2141    return { ok: false, error: "invalid_key" };2142  }2143  } finally { vaultUnlocksInFlight--; }2144}21452146// --- Adoption duress-slot helpers (passthrough, no decrypt) ---21472148/**2149 * Adoption SOURCE helper: returns the sealed slot B as a JSON string when2150 * duress is configured and slot B exists, so the inline snapshot can ship it2151 * to the receiver. Returns null otherwise. Never decrypts.2152 */2153export async function exportDuressSlotForAdoption(): Promise<string | null> {2154  if (!(await isDuressEnabled())) return null;2155  const slotB = await loadSlot(SLOT_B);2156  if (!slotB) return null;2157  return JSON.stringify(slotB);2158}21592160/**2161 * Adoption RECEIVER helper: installs a duress slot received from a source2162 * device. Validates the StoredVault shape (same guard as unlockFromCodex)2163 * and writes it to slot B. Throws on invalid shape so the caller can treat2164 * it as a non-fatal snapshot failure. Never decrypts.2165 */2166export async function installAdoptedDuressSlot(json: string): Promise<void> {2167  if (vaultCreatesInFlight) throw new Error("vault_changed");2168  vaultWritesInFlight++;2169  try {2170  let parsed: StoredVault;2171  try {2172    const raw = JSON.parse(json) as unknown;2173    if (!hasValidVaultSchema(raw)) {2174      throw new Error("invalid_duress_slot_shape");2175    }2176    parsed = raw;2177  } catch (err) {2178    if (err instanceof SyntaxError) {2179      throw new Error("invalid_duress_slot_shape");2180    }2181    throw err;2182  }2183  await writeSlot(SLOT_B, parsed);2184  } finally { vaultWritesInFlight--; }2185}21862187/**2188 * Restore the vault from a parsed Peach Codex payload.2189 *2190 * The supplied passphrase is verified against the Codex's slotA *before* any2191 * storage mutation — wrong passphrases return without touching disk. On2192 * success, the current vault state is snapshotted (reason: "restore") so the2193 * user can revert via Settings -> Vault History, then slotA/slotB are written2194 * and `peach_last_modified_at` is set to the Codex's recorded timestamp. A2195 * regular `unlock()` follows so the rest of the SW sees the standard2196 * post-unlock state.2197 *2198 * Intentionally non-Pro-gated — see peach_codex_v2.md "Pro gating". A Codex2199 * printed by a Pro user must always be restorable, even on a free device.2200 *2201 * Timing is not held constant here (in contrast to `unlock`): the Codex flow2202 * is an explicit user action with a known passphrase, not a passive lock2203 * screen, so the duress-vs-real timing side channel does not apply.2204 */2205export async function unlockFromCodex(params: {2206  slotA: string; // JSON string of StoredVault for slot A2207  slotB: string | null; // JSON string of StoredVault for slot B, or null2208  timestamp: number;2209  masterPassphrase: string;2210}): Promise<2211  | { ok: true; entryCount: number }2212  | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" | "missing_root_escrow" }2213> {2214  if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");2215  vaultReplacementInFlight = true;2216  try {2217    let parsedSlotA: StoredVault;2218    let parsedSlotB: StoredVault | null = null;2219    try {2220      const rawA = JSON.parse(params.slotA) as unknown;2221      if (!hasValidVaultSchema(rawA)) {2222        return { ok: false, reason: "invalid_slot_format" };2223      }2224      parsedSlotA = rawA;2225      if (params.slotB !== null) {2226        const rawB = JSON.parse(params.slotB) as unknown;2227        if (!hasValidVaultSchema(rawB)) {2228          return { ok: false, reason: "invalid_slot_format" };2229        }2230        parsedSlotB = rawB;2231      }2232    } catch {2233      return { ok: false, reason: "invalid_slot_format" };2234    }22352236    // Verify the passphrase and the password-wrapped root escrow against the2237    // staged Slot A WITHOUT writing anything. Payload decoding is part of the2238    // trial decrypt, so unlock() cannot be the first place these checks run.2239    const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));2240    const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");2241    if (!trialPayload) {2242      zeroKey(trialKey);2243      return { ok: false, reason: "wrong_passphrase" };2244    }2245    const hasEscrow =2246      !!parsedSlotA.pw_root_ciphertext && !!parsedSlotA.pw_root_nonce && !!parsedSlotA.pw_root_tag;2247    if (!hasEscrow) {2248      zeroKey(trialKey);2249      return { ok: false, reason: "missing_root_escrow" };2250    }2251    const stagedRootKey = await deriveRootKeyFromDerivedKey(trialKey, parsedSlotA);2252    if (!stagedRootKey) {2253      zeroKey(trialKey);2254      return { ok: false, reason: "wrong_passphrase" };2255    }2256    zeroKey(stagedRootKey);2257    zeroKey(trialKey);22582259    // Stage the complete candidate pair in memory before touching storage.2260    const stagedSlotB = parsedSlotB ?? generateNoiseBlob(parsedSlotA.ciphertext.length / 2);22612262    // Drop the trial key; `unlock()` below derives its own copy. Holding two2263    // copies of the master key in memory at once would be a needless surface.22642265    // Snapshot the about-to-be-overwritten on-disk state so the user can revert2266    // a mistaken Codex restore via the Vault History UI. Non-fatal if it fails.2267    await takeVaultSnapshot("restore");2268    const previousSlotA = await loadSlot(SLOT_A);2269    const previousSlotB = await loadSlot(SLOT_B);2270    let slotACommitted = false;2271    let slotBCommitted = false;2272    try {2273      await writeSlot(SLOT_A, parsedSlotA);2274      slotACommitted = true;2275      await writeSlot(SLOT_B, stagedSlotB);2276      slotBCommitted = true;2277      await chrome.storage.local.set({2278        peach_last_modified_at: String(params.timestamp),2279      });2280    } catch (err) {2281      if (slotBCommitted && previousSlotB) await writeSlot(SLOT_B, previousSlotB);2282      if (slotACommitted && previousSlotA) await writeSlot(SLOT_A, previousSlotA);2283      throw err;2284    }22852286    // Standard unlock path so domain index, settings, auto-lock, and2287    // recovery-key state all populate exactly as a normal unlock would.2288    const ok = await unlock(params.masterPassphrase);2289    if (!ok) {2290      // Should be unreachable — the staged candidate passed the same checks.2291      return { ok: false, reason: "wrong_passphrase" };2292    }2293    return { ok: true, entryCount: getEntries().length };2294  } finally {2295    vaultReplacementInFlight = false;2296  }2297}22982299// Returns the current in-memory derived key as a hex string. Only the PIN2300// unlock path needs this value, and it reads module state directly; this2301// accessor exists so unlockWithKey's root-key rehydration is testable.2302export /* @testable */ function getDerivedKeyHex(): string {2303  if (!derivedKey) throw new Error("vault_not_unlocked");2304  return hex(derivedKey);2305}23062307/**2308 * Returns the vault's stable root key as hex, or null when locked / not yet2309 * populated. The root key is random per-vault, generated at creation, escrowed2310 * under the recovery words, and re-wrapped (not regenerated) on every password2311 * change — so it is INVARIANT across password rotation, unlike getDerivedKeyHex.2312 *2313 * This is the correct input for sync identity derivation (vault_id, the Noise2314 * NK static key, the Ed25519 manifest signing key, and per-entry envelope2315 * keys): paired devices keep the same identity and can still decrypt each2316 * other's entries after either side rotates its master password (SEV-2-B).2317 *2318 * Returns null rather than throwing so sync callers degrade to VAULT_LOCKED2319 * instead of crashing; rootKey is populated on every supported real-mode2320 * unlock via deriveRootKeyFromDerivedKey.2321 */2322export function getRootKeyHex(): string | null {2323  return rootKey ? hex(rootKey) : null;2324}23252326export function getEntries(): VaultEntry[] {2327  if (!derivedKey) throw new Error("vault_locked");2328  return entries.filter((entry) => !entry.deletedAt);2329}23302331const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;23322333export function getIdentities(): SavedIdentity[] {2334  if (!derivedKey) throw new Error("vault_locked");2335  const active = entries.filter((e) => !e.deletedAt && e.type === "login");23362337  const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();2338  const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();23392340  for (const entry of active) {2341    const domain = extractDomain(entry.url ?? "") ?? "";2342    const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;23432344    function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {2345      const existing = map.get(v);2346      if (!existing || modifiedAt > existing.lastUsed) {2347        map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });2348      } else {2349        map.set(v, { ...existing, count: existing.count + 1 });2350      }2351    }23522353    const uVal = entry.username?.trim();2354    if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);23552356    // Also count the dedicated email field — entries created via the inline2357    // popup new-entry form store email here rather than in username.2358    const eVal = entry.email?.trim();2359    if (eVal) tally(emailMap, eVal);2360  }23612362  const toIdentity = (type: "email" | "username") =>2363    ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({2364      value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,2365    });23662367  return [2368    ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),2369    ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),2370  ];2371}23722373export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {2374  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");23752376  const now = Date.now();2377  const added: VaultEntry[] = [];2378  for (const draft of drafts) {2379    try {2380      const sanitized = sanitizeEntryDraft(draft);2381      const nextEntry: VaultEntry = {2382        ...sanitized,2383        id: crypto.randomUUID(),2384        createdAt: now,2385        modifiedAt: monotonicEntryTimestamp(),2386      };2387      entries.push(nextEntry);2388      added.push(nextEntry);2389    } catch {2390      // Skip invalid drafts silently — caller can see diff between input and output length2391    }2392  }23932394  if (added.length > 0) {2395    await persistEntries();2396  }23972398  return added;2399}24002401/**2402 * Restore a set of entries in full fidelity — preserves id, createdAt,2403 * modifiedAt, and every other field unlike `batchAddEntries` which2404 * assigns fresh identity. Used by restore paths where the backup is the2405 * authoritative source of truth. `mode` controls how entries already in2406 * the vault are treated.2407 */2408export async function restoreEntries(2409  incoming: VaultEntry[],2410  mode: "replace" | "merge"2411): Promise<{ added: number; updated: number; skipped: number }> {2412  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");24132414  // A replace with zero incoming entries is almost certainly a caller bug2415  // (e.g. an import that silently dropped everything). Refuse rather than2416  // wipe the vault.2417  if (mode === "replace" && incoming.length === 0) {2418    throw new Error("refuse to replace with empty entry set");2419  }24202421  let added = 0;2422  let updated = 0;2423  let skipped = 0;24242425  if (mode === "replace") {2426    entries = [];2427    for (const entry of incoming) {2428      const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2429      if (!normalized) {2430        skipped += 1;2431        continue;2432      }2433      entries.push(normalized);2434      if (normalized.deletedAt) {2435        tombstones.set(2436          normalized.id,2437          Math.max(tombstones.get(normalized.id) ?? 0, normalized.deletedAt),2438        );2439      } else {2440        tombstones.delete(normalized.id);2441      }2442      added += 1;2443    }2444  } else {2445    const byId = new Map<string, VaultEntry>();2446    for (const e of entries) byId.set(e.id, e);24472448    for (const entry of incoming) {2449      const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2450      if (!normalized) {2451        skipped += 1;2452        continue;2453      }2454      const existing = byId.get(normalized.id);2455      if (!existing) {2456        entries.push(normalized);2457        if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2458        else tombstones.delete(normalized.id);2459        added += 1;2460      } else if (normalized.modifiedAt > existing.modifiedAt) {2461        const idx = entries.findIndex((e) => e.id === existing.id);2462        if (idx !== -1) {2463          entries[idx] = normalized;2464          if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2465          else tombstones.delete(normalized.id);2466          updated += 1;2467        }2468      } else {2469        skipped += 1;2470      }2471    }2472  }24732474  await persistEntries("import");2475  return { added, updated, skipped };2476}24772478/**2479 * A Peach entry id is a UUID. A restored or imported file carries whatever id2480 * its author used, and no reader bounds it, so one oversized id would ride2481 * into every future sync frame and be rejected there — a permanent, opaque2482 * failure on both platforms, caused by data that was already local.2483 *2484 * The action is mint, not reject: this is the last point where an id is still2485 * ours to choose, so the worst outcome is one duplicate if the same vault is2486 * later restored beside a device still holding the old id. Rejecting would2487 * lose the user's import.2488 *2489 * Deliberately NOT inside sanitizeRestoredEntry, which applyMergedRemoteEntries2490 * also calls. Sync has to adopt a peer's id verbatim — that is the only thing2491 * keeping two devices agreed on which entry they are discussing — so reminting2492 * there would fork identity on every device, on every round.2493 */2494const ENTRY_ID_SHAPE = /^[A-Za-z0-9_-]{1,64}$/;24952496function naturalizeRestoredId(entry: VaultEntry | null): VaultEntry | null {2497  if (!entry || ENTRY_ID_SHAPE.test(entry.id)) return entry;2498  return { ...entry, id: crypto.randomUUID() };2499}25002501/**2502 * Validate + normalise a VaultEntry coming from a backup, import, or sync2503 * peer. MV-6: this is a strict field WHITELIST — `normalizeEntry` copies2504 * only known VaultEntry fields (unknown/attacker keys are dropped), and2505 * nested `passkey`/`canary` shapes are rebuilt field-by-field, never2506 * spread. Returns null for values the live vault shouldn't accept.2507 */2508function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {2509  if (!entry || typeof entry !== "object") return null;2510  const title = typeof entry.title === "string" ? entry.title.trim() : "";2511  if (!title) return null;2512  const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();2513  const now = Date.now();2514  const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;2515  const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;25162517  // normalizeEntry whitelists every known VaultEntry field before the entry2518  // reaches the live vault.2519  const normalized = normalizeEntry({2520    ...entry,2521    id,2522    title,2523    type: entry.type ?? "login",2524    createdAt,2525    modifiedAt,2526  });25272528  if (normalized.passkey) {2529    normalized.passkey = sanitizePasskey(normalized.passkey);2530  }2531  if (normalized.canary) {2532    normalized.canary = sanitizeCanary(normalized.canary);2533  }2534  // PCH-01-016: bound tags on the restore path too, so both import funnels agree.2535  normalized.tags = sanitizeTags(normalized.tags);25362537  // Login entries from backup must carry a password (or be passkey-only,2538  // in which case the passkey sub-object replaces the password requirement).2539  if (2540    normalized.type === "login" &&2541    !normalized.passkey &&2542    typeof normalized.password !== "string"2543  ) {2544    return null;2545  }2546  if (entry.passkey && !normalized.passkey) {2547    // Entry claimed a passkey but the shape didn't validate — refuse the2548    // whole entry rather than silently importing a credential-less husk.2549    return null;2550  }25512552  return normalized;2553}25542555/**2556 * Rebuild a PasskeyData object from untrusted input, field by field.2557 * Returns undefined when required fields are missing/mistyped — a rogue2558 * passkey credential must not activate via import (MV-6 attack scenario).2559 */2560function sanitizePasskey(pk: unknown): PasskeyData | undefined {2561  if (!pk || typeof pk !== "object") return undefined;2562  const r = pk as Record<string, unknown>;2563  if (2564    typeof r.rpId !== "string" || !r.rpId ||2565    typeof r.credentialId !== "string" || !r.credentialId ||2566    typeof r.publicKeyCose !== "string" ||2567    typeof r.userHandle !== "string" ||2568    typeof r.userName !== "string"2569  ) {2570    return undefined;2571  }2572  return {2573    rpId: r.rpId,2574    rpName: typeof r.rpName === "string" ? r.rpName : r.rpId,2575    credentialId: r.credentialId,2576    publicKeyCose: r.publicKeyCose,2577    privateKeyJwk:2578      r.privateKeyJwk && typeof r.privateKeyJwk === "object"2579        ? (r.privateKeyJwk as JsonWebKey)2580        : undefined,2581    userHandle: r.userHandle,2582    userName: r.userName,2583    userDisplayName:2584      typeof r.userDisplayName === "string" ? r.userDisplayName : r.userName,2585    algorithm: r.algorithm === -8 ? -8 : -7,2586    signCount: typeof r.signCount === "number" ? r.signCount : 0,2587    aaguid: typeof r.aaguid === "string" ? r.aaguid : "",2588    backupEligible: r.backupEligible === true,2589    backupState: r.backupState === true,2590    lastUsedAt: typeof r.lastUsedAt === "number" ? r.lastUsedAt : undefined,2591    browser: r.browser === "chrome" || r.browser === "firefox" ? r.browser : undefined,2592    transports: Array.isArray(r.transports)2593      ? r.transports.filter((t): t is string => typeof t === "string")2594      : undefined,2595    createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),2596  };2597}25982599/**2600 * Rebuild a Canary object from untrusted input. The webhook must be a2601 * well-formed HTTPS URL — a poisoned canary.webhookUrl is a standing2602 * exfiltration endpoint that the canary subsystem will POST entry titles2603 * to (MV-6 attack scenario). Invalid → the canary is dropped, not the2604 * entry. FIRE_CANARY_PING re-validates with the full SSRF guard at fire2605 * time (isAllowedCanaryWebhookUrl), so this import-time check is the2606 * outer of two gates.2607 */2608function sanitizeCanary(c: unknown): Canary | undefined {2609  if (!c || typeof c !== "object") return undefined;2610  const r = c as Record<string, unknown>;2611  if (typeof r.webhookUrl !== "string") return undefined;2612  let url: URL;2613  try {2614    url = new URL(r.webhookUrl);2615  } catch {2616    return undefined;2617  }2618  if (url.protocol !== "https:") return undefined;2619  return {2620    webhookUrl: url.toString(),2621    label: typeof r.label === "string" ? r.label : undefined,2622    lastPinged: typeof r.lastPinged === "number" ? r.lastPinged : undefined,2623    pingCount: typeof r.pingCount === "number" ? r.pingCount : undefined,2624  };2625}26262627/**2628 * MV-6 / PCH-01-016: tags from imported / batch-added entries are untrusted.2629 * Keep only non-empty strings, cap each at 256 chars, and cap the count at 2552630 * (the same per-entry ceiling the export codec enforces, peachPayload.ts).2631 * Non-array or all-invalid input collapses to undefined.2632 */2633function sanitizeTags(tags: unknown): string[] | undefined {2634  if (!Array.isArray(tags)) return undefined;2635  const out: string[] = [];2636  for (const t of tags) {2637    if (typeof t !== "string") continue;2638    const trimmed = t.trim();2639    if (!trimmed) continue;2640    out.push(trimmed.slice(0, 256));2641    if (out.length >= 255) break;2642  }2643  return out.length > 0 ? out : undefined;2644}26452646// Soft-deletes every non-deleted entry in one call. The literal string2647// argument is a tripwire against accidental calls — any caller that would2648// wipe the vault has to consciously type "REPLACE_ALL". Do not relax this2649// to a boolean.2650export async function clearVaultEntries(2651  confirmation: "REPLACE_ALL"2652): Promise<void> {2653  if (confirmation !== "REPLACE_ALL") {2654    throw new Error("clearVaultEntries requires explicit confirmation");2655  }2656  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");2657  for (const entry of entries) {2658    if (!entry.deletedAt) {2659      const stamp = monotonicEntryTimestamp(Math.max(2660        entry.modifiedAt,2661        tombstones.get(entry.id) ?? 0,2662      ));2663      entry.deletedAt = stamp;2664      entry.modifiedAt = stamp;2665      tombstones.set(entry.id, stamp);2666    }2667  }2668  await persistEntries();2669}26702671export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {2672  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");26732674  const sanitized = sanitizeEntryDraft(entry);2675  const now = Date.now();2676  const stamp = monotonicEntryTimestamp();2677  const nextEntry: VaultEntry = {2678    ...sanitized,2679    id: crypto.randomUUID(),2680    createdAt: now,2681    modifiedAt: stamp,2682    // Stamp passwordChangedAt at creation so age tracking is accurate from2683    // day one. Non-login entries carry the same stamp harmlessly.2684    passwordChangedAt: sanitized.password ? stamp : undefined,2685  };26862687  // Clone-and-replace so a failed persist rolls back the in-memory state2688  // (COR-008). Without this, a quota-full or storage error leaves the2689  // module-level `entries` ahead of what's actually on disk.2690  const rollback = entries;2691  entries = [...entries, nextEntry];2692  try {2693    await persistEntries();2694  } catch (err) {2695    entries = rollback;2696    throw err;2697  }26982699  // Fire-and-forget breach check (only for login entries if breach monitoring is enabled or not set)2700  if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {2701    const breachEpoch = vaultEpoch;2702    checkBreach(nextEntry.password).then(async (count) => {2703      if (count > 0 && breachEpoch === vaultEpoch && !vaultCreatesInFlight) {2704        const idx = entries.findIndex((e) => e.id === nextEntry.id);2705        if (idx !== -1) {2706          entries[idx] = { ...entries[idx], breach: count, modifiedAt: monotonicEntryTimestamp(entries[idx].modifiedAt) };2707          await persistEntries();2708        }2709      }2710    });2711  }27122713  fireSyncTrigger("vault_change");27142715  return nextEntry;2716}27172718/**2719 * Run the passkey-merge pass on the live in-memory entries and persist if2720 * anything changed. Called immediately after any passkey registration so that2721 * a same-domain TOTP-only entry already in the vault gets consolidated right2722 * away instead of waiting until the next lock/unlock cycle.2723 */2724export async function consolidatePasskeyEntries(): Promise<void> {2725  if (!derivedKey || vaultCreatesInFlight) return;2726  const { merged } = mergePasskeyOnlyIntoLogins(entries);2727  if (merged) {2728    await persistEntries();2729  }2730}27312732export async function updateEntry(2733  id: string,2734  patch: Partial<VaultEntry>2735): Promise<void> {2736  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");27372738  const idx = entries.findIndex((entry) => entry.id === id);2739  if (idx === -1 || entries[idx].deletedAt) {2740    throw new Error("entry_not_found");2741  }27422743  const current = entries[idx];2744  const sanitizedPatch = sanitizeEntryPatch(patch);2745  // Refresh passwordChangedAt only when the password value actually changes —2746  // a metadata-only update (title, tags, etc.) must not reset the age clock2747  // that drives the Pro health rotation recommendation.2748  const passwordChanged =2749    "password" in patch &&2750    typeof sanitizedPatch.password === "string" &&2751    sanitizedPatch.password !== current.password;2752  const stamp = monotonicEntryTimestamp(current.modifiedAt);2753  // When the password actually changes, push the outgoing one onto the history2754  // (newest first) so the user can reveal/copy/restore it later. We record the2755  // age it carried (passwordChangedAt, falling back to createdAt) rather than2756  // `now`, so the list reflects when each password was last in effect. Only2757  // capture a non-empty prior value — clearing a password leaves no secret to2758  // keep, and we skip an immediate exact duplicate (e.g. restore-then-restore)2759  // to avoid noise.2760  const priorPassword = current.password;2761  const shouldCapture =2762    passwordChanged &&2763    typeof priorPassword === "string" &&2764    priorPassword.length > 0 &&2765    current.passwordHistory?.[0]?.password !== priorPassword;2766  const nextHistory = shouldCapture2767    ? [2768        { password: priorPassword!, changedAt: current.passwordChangedAt ?? current.createdAt },2769        ...(current.passwordHistory ?? []),2770      ].slice(0, PASSWORD_HISTORY_MAX)2771    : current.passwordHistory;2772  entries[idx] = {2773    ...current,2774    ...sanitizedPatch,2775    modifiedAt: stamp,2776    ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),2777  };2778277927802781  // Card entries must retain their card number2782  if (entries[idx].type === "card" && !entries[idx].cardNumber) {2783    entries[idx] = current;2784    throw new Error("card number is required for card entries");2785  }27862787  // Roll the in-memory entry back to its pre-edit state if the disk write2788  // fails (e.g. storage quota). Without this the module-level `entries` array2789  // would hold an edit that never landed on disk, diverging from the vault2790  // until the next unlock silently reverts it (SEV-3-A). Mirrors addEntry.2791  try {2792    await persistEntries();2793  } catch (err) {2794    entries[idx] = current;2795    throw err;2796  }27972798  // Breach check when password changes: clear immediately so old breach doesn't linger,2799  // then async-check the new password and only re-set if it's also found.2800  if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {2801    entries[idx] = { ...entries[idx], breach: undefined };2802    await persistEntries();2803    const password = entries[idx].password;2804    if (password) {2805      checkBreach(password).then(async (count) => {2806        const i = entries.findIndex((e) => e.id === id);2807        if (i !== -1 && count > 0) {2808          entries[i] = { ...entries[i], breach: count, modifiedAt: monotonicEntryTimestamp(entries[i].modifiedAt) };2809          await persistEntries();2810        }2811      });2812    }2813  }28142815  fireSyncTrigger("vault_change");2816}28172818export async function deleteEntry(id: string): Promise<void> {2819  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");28202821  const entry = entries.find((item) => item.id === id);2822  if (!entry || entry.deletedAt) {2823    throw new Error("entry_not_found");2824  }28252826  // Tombstone timestamp must be strictly greater than the entry's last2827  // modification so the deletion wins LWW against any in-flight edit, even2828  // under clock skew (SEV-2-E).2829  const previousModifiedAt = entry.modifiedAt;2830  const previousTombstone = tombstones.get(id);2831  const stamp = monotonicEntryTimestamp(Math.max(entry.modifiedAt, previousTombstone ?? 0));2832  entry.deletedAt = stamp;2833  entry.modifiedAt = stamp;2834  tombstones.set(id, stamp);2835  // Roll the tombstone back if the disk write fails, so a quota error doesn't2836  // leave the entry deleted in memory but alive on disk (SEV-3-A).2837  try {2838    await persistEntries();2839  } catch (err) {2840    delete entry.deletedAt;2841    entry.modifiedAt = previousModifiedAt;2842    if (previousTombstone === undefined) tombstones.delete(id);2843    else tombstones.set(id, previousTombstone);2844    throw err;2845  }2846  fireSyncTrigger("vault_change");2847}28482849export function getDeletedEntries(): VaultEntry[] {2850  if (!derivedKey) return [];2851  return entries.filter((e) => !!e.deletedAt);2852}28532854/** Return all durable deletion timestamps, including purged full entries. */2855export function getTombstoneManifest(): Record<string, number> {2856  if (!derivedKey) return {};2857  return Object.fromEntries(tombstones);2858}28592860/**2861 * Returns the vault's monotonic version — the `peach_last_modified_at` value2862 * stamped on every user-initiated write. Remote (sync) writes do NOT advance2863 * this version so a sync round never cascades into a second outbound sync.2864 */2865export async function getVaultVersion(): Promise<number> {2866  try {2867    const raw = await chrome.storage.local.get("peach_last_modified_at");2868    const v = (raw as Record<string, unknown>).peach_last_modified_at;2869    if (typeof v === "number") return v;2870    if (typeof v === "string" && v !== "") {2871      const n = Number.parseInt(v, 10);2872      return Number.isFinite(n) ? n : 0;2873    }2874    return 0;2875  } catch {2876    return 0;2877  }2878}28792880/**2881 * Apply a batch of remote entries + tombstones from a sync peer.2882 * Last-write-wins by `modifiedAt`; a tombstone supersedes a live entry when2883 * `deletedAt > modifiedAt` on the local side. Mutates `entries` directly and2884 * persists with reason `sync_received` — does NOT fire the sync dispatcher, so2885 * applying a sync round cannot cascade into another outbound sync.2886 *2887 * `applied` counts entries that actually changed local state (new add,2888 * overwrite-by-newer, or new tombstone). `received` is the raw payload size2889 * the caller can surface in the sync result UI.2890 */2891export async function applyMergedRemoteEntries(2892  remoteEntries: VaultEntry[],2893  remoteTombstones: Record<string, number>,2894): Promise<{ received: number; applied: number; conflicts: number }> {2895  // DESIGN: last-write-wins is applied PER-ENTRY, not per-field. If two devices2896  // concurrently edit different fields of the same entry, the one with the2897  // newer modifiedAt wins the whole entry and the other device's field edits2898  // are dropped silently. This is the deliberate trade-off for a simple,2899  // conflict-free merge — per-field CRDT merge is out of scope. Guidance for2900  // users: edit a given entry on one device at a time.2901  if (!derivedKey || vaultCreatesInFlight || vaultMode === "decoy") throw new Error("vault_locked");29022903  const received = remoteEntries.length + Object.keys(remoteTombstones).length;2904  let applied = 0;2905  let conflicts = 0;29062907  const byId = new Map<string, VaultEntry>();2908  for (const e of entries) byId.set(e.id, e);29092910  const mergeNow = Date.now();2911  const remoteTombstoneTimes = new Map<string, number>();2912  for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2913    if (typeof rawDeletedAt === "number" && Number.isFinite(rawDeletedAt) && rawDeletedAt > 0) {2914      remoteTombstoneTimes.set(id, clampSyncTimestamp(rawDeletedAt, mergeNow));2915    }2916  }29172918  for (const remote of remoteEntries) {2919    const sanitized = sanitizeRestoredEntry(remote);2920    if (!sanitized) continue;2921    // HV-1a: a far-future remote modifiedAt must not permanently pin a2922    // malicious value against honest local edits. Clamp BEFORE any2923    // comparison against local timestamps.2924    sanitized.modifiedAt = clampSyncTimestamp(sanitized.modifiedAt, mergeNow);2925    if (typeof sanitized.deletedAt === "number") {2926      sanitized.deletedAt = clampSyncTimestamp(sanitized.deletedAt, mergeNow);2927    }2928    const remoteTombstoneTs = remoteTombstoneTimes.get(sanitized.id);2929    const localTombstoneTs = tombstones.get(sanitized.id);2930    const tombstoneTs = Math.max(remoteTombstoneTs ?? 0, localTombstoneTs ?? 0);2931    if (tombstoneTs > 0 && tombstoneTs >= sanitized.modifiedAt) {2932      continue;2933    }2934    const local = byId.get(sanitized.id);2935    if (!local) {2936      entries.push(sanitized);2937      byId.set(sanitized.id, sanitized);2938      tombstones.delete(sanitized.id);2939      applied += 1;2940    } else if (sanitized.modifiedAt > local.modifiedAt) {2941      const idx = entries.findIndex((e) => e.id === local.id);2942      if (idx !== -1) {2943        entries[idx] = sanitized;2944        byId.set(sanitized.id, sanitized);2945        tombstones.delete(sanitized.id);2946        applied += 1;2947        if (!local.deletedAt) conflicts += 1;2948      }2949    }2950  }29512952  for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2953    if (typeof rawDeletedAt !== "number" || !Number.isFinite(rawDeletedAt) || rawDeletedAt <= 0) continue;2954    // HV-1a/1c: clamp the tombstone timestamp before every comparison.2955    const deletedAt = remoteTombstoneTimes.get(id)!;2956    const knownTombstone = tombstones.get(id);2957    if (knownTombstone !== undefined && knownTombstone >= deletedAt) continue;2958    const local = byId.get(id);2959    if (!local) {2960      tombstones.set(id, deletedAt);2961      applied += 1;2962      continue;2963    }2964    if (local.deletedAt && local.deletedAt >= deletedAt) continue;2965    if (deletedAt < local.modifiedAt) continue;2966    const idx = entries.findIndex((e) => e.id === id);2967    if (idx !== -1) {2968      entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };2969      tombstones.set(id, deletedAt);2970      applied += 1;2971    }2972  }29732974  if (applied > 0 && vaultMode === "real") {2975    await persistEntries("sync_received");2976    buildDomainIndexSync(entries);2977    // An open popup holds the entries it loaded at mount and polls nothing, so2978    // a background round (the relay listener responding to a peer's push, or the2979    // alarm-driven dial) otherwise lands silently and the user sees stale data2980    // until they reopen. Best-effort: no popup listening is the normal case.2981    try {2982      void chrome.runtime2983        .sendMessage({ type: "VAULT_ENTRIES_CHANGED" })2984        .catch(() => undefined);2985    } catch {2986      // messaging unavailable2987    }2988  }2989  return { received, applied, conflicts };2990}29912992export async function restoreEntry(id: string): Promise<void> {2993  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");2994  const entry = entries.find((e) => e.id === id && e.deletedAt);2995  if (!entry) throw new Error("deleted entry not found");2996  const previousDeletedAt = entry.deletedAt;2997  const previousModifiedAt = entry.modifiedAt;2998  const previousTombstone = tombstones.get(id);2999  delete entry.deletedAt;3000  entry.modifiedAt = monotonicEntryTimestamp(Math.max(3001    entry.modifiedAt,3002    previousTombstone ?? 0,3003  ));3004  tombstones.delete(id);3005  try {3006    await persistEntries();3007  } catch (err) {3008    entry.deletedAt = previousDeletedAt;3009    entry.modifiedAt = previousModifiedAt;3010    if (previousTombstone !== undefined) tombstones.set(id, previousTombstone);3011    throw err;3012  }3013  buildDomainIndexSync(entries);3014}30153016export async function purgeEntry(id: string): Promise<void> {3017  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3018  const idx = entries.findIndex((e) => e.id === id && e.deletedAt);3019  if (idx === -1) throw new Error("deleted entry not found");3020  const entry = entries[idx]!;3021  tombstones.set(id, Math.max(tombstones.get(id) ?? 0, entry.deletedAt!));3022  entries.splice(idx, 1);3023  await persistEntries();3024}30253026/** Permanently delete entries whose deletedAt is older than retentionMs. 0 = keep forever. */3027export async function purgeExpiredTrash(retentionMs: number): Promise<number> {3028  if (!derivedKey || vaultCreatesInFlight || retentionMs === 0) return 0;3029  const cutoff = Date.now() - retentionMs;3030  const before = entries.length;3031  for (const entry of entries) {3032    if (entry.deletedAt && entry.deletedAt < cutoff) {3033      tombstones.set(entry.id, Math.max(tombstones.get(entry.id) ?? 0, entry.deletedAt));3034    }3035  }3036  entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));3037  const purged = before - entries.length;3038  if (purged > 0) await persistEntries();3039  return purged;3040}30413042export function queryDomain(domain: string): VaultEntry[] {3043  return domainIndex.get(domain) ?? [];3044}30453046export function getEntryById(id: string): VaultEntry | undefined {3047  return entries.find((entry) => entry.id === id && !entry.deletedAt);3048}30493050async function persistSlotA(3051  reason: VaultSnapshot["reason"] = "local_save",3052): Promise<StoredVault> {3053  if (!derivedKey) throw new Error("vault_locked");3054  const epoch = vaultEpoch;3055  const throwIfStale = () => {3056    if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3057  };30583059  const slotA = await loadSlot(SLOT_A);3060  throwIfStale();3061  if (!slotA) throw new Error("missing slot A");30623063  // Snapshot the about-to-be-overwritten state BEFORE we mutate disk. Failures3064  // are swallowed by takeVaultSnapshot — history must never block a save.3065  await takeVaultSnapshot(reason);3066  throwIfStale();30673068  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3069  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");3070  throwIfStale();30713072  // Preserve existing recovery escrow fields.3073  const nextSlotA: StoredVault = {3074    ...slotA,3075    nonce,3076    ciphertext,3077    tag,3078    // recovery_salt and recovery_wrapped_root_key are already set from loadSlot3079  };30803081  // Slot A (the real vault) is now committed. Wrap every later write so a3082  // mid-persist failure (e.g. a storage error after slot A landed) restores the3083  // prior slot A before rethrowing. Without this, a "failed" save that already3084  // wrote slot A leaves disk ahead of the in-memory rollback in addEntry/3085  // updateEntry/deleteEntry — the entry stays silently on disk and resurfaces3086  // as a duplicate on the next unlock (observed under storage-quota pressure).3087  let slotACommitted = false;3088  try {3089    throwIfStale();3090    await writeSlot(SLOT_A, nextSlotA);3091    slotACommitted = true;3092    throwIfStale();30933094    // When duress is not configured, keep slot B size-matched with slot A by3095    // regenerating its noise. When duress IS configured, leave slot B alone —3096    // we don't have the decoy key to re-encrypt it. This is a known trade-off.3097    if (!duressConfigured) {3098      throwIfStale();3099      await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3100      throwIfStale();3101    }3102    // Only advance the vault version for locally-originated writes. Entries3103    // applied from a sync peer ("sync_received") must NOT bump the counter —3104    // otherwise applying a remote round makes us look newer than the peer and3105    // triggers a redundant outbound sync, defeating the no-op optimisation3106    // and risking a ping-pong between two devices (SEV-2-C).3107    if (reason !== "sync_received") {3108      throwIfStale();3109      await stampLocalVaultMutation();3110      throwIfStale();3111    }3112  } catch (err) {3113    // Best-effort restore — the prior slot A is smaller-or-equal, so this write3114    // fits even when the failure was a quota overflow.3115    if (slotACommitted) await writeSlot(SLOT_A, slotA).catch(() => {});3116    if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3117    throw err;3118  }31193120  return nextSlotA;3121}31223123async function persistSlotB(): Promise<void> {3124  if (!derivedKey) throw new Error("vault_locked");31253126  const slotB = await loadSlot(SLOT_B);3127  if (!slotB) throw new Error("missing slot B");31283129  // Decoy plaintext always reports duressConfigured=false — the decoy user3130  // sees a clean slate. persistSlotB only runs in decoy mode, which only3131  // exists once duress is configured, so pad to the fixed duress ceiling to3132  // keep slot B's length equal to slot A's (audit MEDIUM — deniability).3133  const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);3134  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");31353136  await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });3137  // Symmetric with persistSlotA: if the version stamp fails after the decoy3138  // slot committed, restore the prior slot B so a failed decoy-mode save can't3139  // leave disk ahead of the in-memory rollback.3140  try {3141    await stampLocalVaultMutation();3142  } catch (err) {3143    await writeSlot(SLOT_B, slotB).catch(() => {});3144    throw err;3145  }3146}31473148async function persistEntries(3149  reason: VaultSnapshot["reason"] = "local_save",3150): Promise<void> {3151  if (vaultCreatesInFlight) throw new Error("vault_changed");3152  vaultWritesInFlight++;3153  try {3154  if (!derivedKey) throw new Error("vault_locked");31553156  // Reconcile direct soft-delete callers while restoring the previous map if3157  // storage rejects the save.3158  const previousTombstones = tombstones;3159  tombstones = new Map(tombstones);3160  reconcileTombstones();3161  try {3162    if (vaultMode === "decoy") {3163      await persistSlotB();3164    } else {3165      await persistSlotA(reason);3166    }3167  } catch (err) {3168    tombstones = previousTombstones;3169    throw err;3170  }3171  buildDomainIndexSync(entries);3172  await refreshLockedSyncState();3173  } finally { vaultWritesInFlight--; }3174}31753176// PB-26-011: drop URLs whose parsed scheme is not http(s) at the storage3177// boundary. Schemeless values (e.g. "github.com") are inert and kept — they3178// pre-date this guard in existing data. Unparseable values are kept: the3179// reviewed render paths never execute them (favicons via _favicon/, domains3180// via tldts); this is defense-in-depth against future sinks.3181function allowHttpUrl(url: string | undefined): string {3182  const trimmed = url?.trim() ?? "";3183  if (!trimmed) return "";3184  try {3185    const parsed = new URL(trimmed);3186    if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return "";3187  } catch {3188    // No scheme to reject.3189  }3190  return trimmed;3191}31923193function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {3194  if (!Array.isArray(values)) return undefined;3195  const seen = new Set<string>();3196  const cleaned: string[] = [];3197  for (const value of values) {3198    const trimmed = typeof value === "string" ? value.trim() : "";3199    if (!trimmed) continue;3200    if (!allowHttpUrl(trimmed)) continue;3201    const key = trimmed.toLowerCase();3202    if (seen.has(key)) continue;3203    seen.add(key);3204    cleaned.push(trimmed);3205  }3206  return cleaned.length > 0 ? cleaned : undefined;3207}32083209function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {3210  const title = entry.title.trim();3211  const type: VaultEntry["type"] = entry.type ?? "login";32123213  if (!title) throw new Error("title is required");32143215  if (entry.passkey) {3216    const p = entry.passkey;3217    if (3218      !p.rpId ||3219      !p.credentialId ||3220      !p.publicKeyCose ||3221      !p.userHandle ||3222      !p.userName ||3223      (p.algorithm !== -7 && p.algorithm !== -8)3224    ) {3225      throw new Error("invalid passkey credential");3226    }3227  }3228  if (type === "card") {3229    if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {3230      throw new Error("cardholder name and card number are required");3231    }3232  }32333234  return {3235    type,3236    title,3237    username: type === "login" ? entry.username?.trim() ?? "" : undefined,3238    email: type === "login" ? entry.email?.trim() || undefined : undefined,3239    password: type === "login" ? entry.password : undefined,3240    url: type === "login" ? allowHttpUrl(entry.url) : undefined,3241    additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,3242    totp: type === "login" ? entry.totp?.trim() || undefined : undefined,3243    // PCH-01-019: preserve non-default TOTP params through batch-add/import so3244    // they are not silently stripped (they fall back to SHA-1/6/30 when absent).3245    totpAlgorithm: type === "login" ? entry.totpAlgorithm : undefined,3246    totpDigits: type === "login" ? entry.totpDigits : undefined,3247    totpPeriod: type === "login" ? entry.totpPeriod : undefined,3248    notes: entry.notes?.trim() || undefined,3249    breach: type === "login" ? entry.breach : undefined,3250    // PCH-01-016: the batch-add path was bypassing the MV-6 canary/tags3251    // whitelist applied on the RESTORE_ENTRIES path. Run both sanitizers here.3252    canary: type === "login" ? sanitizeCanary(entry.canary) : undefined,3253    tags: sanitizeTags(entry.tags),3254    passkey: entry.passkey,3255    cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,3256    cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,3257    expMonth: type === "card" ? entry.expMonth?.trim() : undefined,3258    expYear: type === "card" ? entry.expYear?.trim() : undefined,3259    cvc: type === "card" ? entry.cvc?.trim() : undefined,3260    cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,3261    network: type === "card" ? entry.network : undefined,3262    last4: type === "card" ? entry.last4?.trim() : undefined,3263  };3264}32653266function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {3267  const nextPatch: Partial<VaultEntry> = {};32683269  if ("type" in patch) {3270    nextPatch.type = patch.type;3271  }32723273  if ("title" in patch) {3274    const title = patch.title?.trim() ?? "";3275    if (!title) throw new Error("title is required");3276    nextPatch.title = title;3277  }32783279  if ("url" in patch) {3280    nextPatch.url = allowHttpUrl(patch.url);3281  }32823283  if ("additionalUrls" in patch) {3284    const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];3285    const seen = new Set<string>();3286    const cleaned: string[] = [];3287    for (const value of incoming) {3288      const trimmed = typeof value === "string" ? value.trim() : "";3289      if (!trimmed || !allowHttpUrl(trimmed)) continue;3290      const key = trimmed.toLowerCase();3291      if (seen.has(key)) continue;3292      seen.add(key);3293      cleaned.push(trimmed);3294    }3295    nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;3296  }32973298  if ("username" in patch) {3299    nextPatch.username = patch.username?.trim() ?? "";3300  }33013302  if ("email" in patch) {3303    nextPatch.email = patch.email?.trim() || undefined;3304  }33053306  if ("password" in patch) {3307    const password = patch.password ?? "";3308    // Allow clearing a password (e.g. on passkey-only entries)3309    nextPatch.password = password || undefined;3310  }33113312  if ("totp" in patch) {3313    nextPatch.totp = patch.totp?.trim() || undefined;3314  }33153316  if ("totpAlgorithm" in patch) {3317    nextPatch.totpAlgorithm = patch.totpAlgorithm;3318  }33193320  if ("totpDigits" in patch) {3321    nextPatch.totpDigits = patch.totpDigits;3322  }33233324  if ("totpPeriod" in patch) {3325    nextPatch.totpPeriod = patch.totpPeriod;3326  }33273328  if ("notes" in patch) {3329    nextPatch.notes = patch.notes?.trim() || undefined;3330  }33313332  if ("breach" in patch) {3333    nextPatch.breach = patch.breach;3334  }33353336  if ("canary" in patch) {3337    // PCH-02-001: route update patches through the same canary whitelist used3338    // by add/restore/sync. Invalid shapes drop the canary; `undefined` clears it.3339    nextPatch.canary = patch.canary ? sanitizeCanary(patch.canary) : undefined;3340  }33413342  if ("passkey" in patch) {3343    // A patch with `passkey: undefined` removes the credential from the entry3344    // (used by "remove passkey" without deleting the whole entry).3345    if (patch.passkey === undefined || patch.passkey === null) {3346      nextPatch.passkey = undefined;3347    } else {3348      const sanitized = sanitizePasskey(patch.passkey);3349      if (!sanitized) throw new Error("invalid passkey credential");3350      nextPatch.passkey = sanitized;3351    }3352  }33533354  if ("tags" in patch) {3355    // PCH-02-001: bound tags exactly like both import funnels.3356    nextPatch.tags = sanitizeTags(patch.tags);3357  }33583359  if ("cardholderName" in patch) {3360    nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;3361  }3362  if ("cardNumber" in patch) {3363    const n = patch.cardNumber ?? "";3364    nextPatch.cardNumber = n || undefined;3365  }3366  if ("expMonth" in patch) {3367    nextPatch.expMonth = patch.expMonth?.trim() || undefined;3368  }3369  if ("expYear" in patch) {3370    nextPatch.expYear = patch.expYear?.trim() || undefined;3371  }3372  if ("cvc" in patch) {3373    nextPatch.cvc = patch.cvc?.trim() || undefined;3374  }3375  if ("cardNickname" in patch) {3376    nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;3377  }3378  if ("network" in patch) {3379    nextPatch.network = patch.network;3380  }3381  if ("last4" in patch) {3382    nextPatch.last4 = patch.last4?.trim() || undefined;3383  }33843385  return nextPatch;3386}33873388function normalizeEntry(entry: VaultEntry): VaultEntry {3389  const base: VaultEntry = {3390    id: entry.id,3391    type: entry.type,3392    title: entry.title,3393    username: entry.username,3394    email: entry.email,3395    password: entry.password,3396    url: entry.url,3397    additionalUrls:3398      "additionalUrls" in entry && Array.isArray(entry.additionalUrls)3399        ? entry.additionalUrls3400        : undefined,3401    totp: entry.totp,3402    // PCH-01-019: carry TOTP params through the normalize/restore path too.3403    totpAlgorithm: entry.totpAlgorithm,3404    totpDigits: entry.totpDigits,3405    totpPeriod: entry.totpPeriod,3406    notes: entry.notes,3407    breach: entry.breach,3408    // Preserve the password-age clock across lock/unlock. Without this the3409    // field is dropped on every decode and the advanced-health "aged password"3410    // signal silently resets to createdAt on each unlock (SEV-2-A).3411    passwordChangedAt:3412      "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,3413    // Preserve past-password history across lock/unlock. normalizeEntry is a3414    // field whitelist, so an unlisted field is silently dropped on every decode3415    // (same class as the passwordChangedAt SEV-2-A above).3416    passwordHistory:3417      "passwordHistory" in entry && Array.isArray(entry.passwordHistory)3418        ? entry.passwordHistory3419        : undefined,3420    canary: entry.canary,3421    passkey: entry.passkey,3422    createdAt: entry.createdAt,3423    modifiedAt: entry.modifiedAt,3424    deletedAt: entry.deletedAt,3425    tags: entry.tags,3426    cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,3427    cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,3428    expMonth: "expMonth" in entry ? entry.expMonth : undefined,3429    expYear: "expYear" in entry ? entry.expYear : undefined,3430    cvc: "cvc" in entry ? entry.cvc : undefined,3431    cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,3432    network: "network" in entry ? entry.network : undefined,3433    last4: "last4" in entry ? entry.last4 : undefined,3434  };34353436  return base;3437}343834393440// ---------------------------------------------------------------------------3441// Deduplication3442// ---------------------------------------------------------------------------34433444function entryDupeKey(e: VaultEntry): string {3445  if (e.type === "note") return `note|${e.title.toLowerCase()}`;3446  // Passkey-bearing entries dedupe by the credential's RP + user. Two logins3447  // on different sites that happen to share a username are still distinct;3448  // two passkey credentials for the same RP+user are duplicates regardless3449  // of any login fields they may also carry.3450  if (e.passkey) {3451    return `passkey|${e.passkey.rpId.toLowerCase()}|${e.passkey.userName.toLowerCase()}`;3452  }3453  return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;3454}34553456/** Returns the number of duplicate entries (those that would be removed). */3457export function countDuplicates(): number {3458  const best = new Map<string, VaultEntry>();3459  let dupeCount = 0;3460  for (const e of entries.filter((e) => !e.deletedAt)) {3461    const key = entryDupeKey(e);3462    const existing = best.get(key);3463    if (!existing) {3464      best.set(key, e);3465    } else {3466      dupeCount++;3467      // Keep the more recently modified one in the map3468      if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3469        best.set(key, e);3470      }3471    }3472  }3473  return dupeCount;3474}34753476/**3477 * Soft-deletes duplicate entries, keeping the most recently modified copy of3478 * each group. Returns the number of entries moved to trash.3479 */3480export async function deduplicateEntries(): Promise<number> {3481  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3482  // Dedup reshapes slot B permanently under the decoy key, which is3483  // forensically distinguishable from a freshly-seeded decoy vault. Refuse.3484  if (vaultMode === "decoy") {3485    throw new Error("deduplicate disabled in decoy mode");3486  }34873488  const best = new Map<string, VaultEntry>();3489  for (const e of entries.filter((en) => !en.deletedAt)) {3490    const key = entryDupeKey(e);3491    const existing = best.get(key);3492    if (!existing) {3493      best.set(key, e);3494    } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3495      best.set(key, e);3496    }3497  }34983499  const keepIds = new Set(Array.from(best.values()).map((e) => e.id));3500  let removed = 0;3501  entries = entries.map((e) => {3502    if (!e.deletedAt && !keepIds.has(e.id)) {3503      removed++;3504      const deletedAt = monotonicEntryTimestamp(Math.max(3505        e.modifiedAt,3506        tombstones.get(e.id) ?? 0,3507      ));3508      tombstones.set(e.id, deletedAt);3509      return { ...e, deletedAt };3510    }3511    return e;3512  });35133514  if (removed > 0) await persistEntries();3515  return removed;3516}35173518// ---------------------------------------------------------------------------3519// Vault history — snapshot BEFORE every vault write so the saved blob is3520// what is about to be lost, not what was just written. Capped at 5. The3521// stored blobs are AES-256-GCM ciphertext under the master password, so3522// history adds zero security surface.3523// ---------------------------------------------------------------------------35243525const HISTORY_KEY = "peach_vault_history";3526const HISTORY_MAX = 5;35273528// PCH-01-023: coarsen a live-entry count into a low-resolution bucket so the3529// plaintext snapshot field cannot reveal exact vault size or single-entry change3530// deltas. Buckets widen as the vault grows so absolute leakage stays roughly3531// proportional rather than exact.3532function bucketEntryCount(n: number): number {3533  if (n <= 0) return 0;3534  if (n <= 10) return 10;3535  if (n <= 25) return 25;3536  if (n <= 50) return 50;3537  if (n <= 100) return 100;3538  if (n <= 250) return 250;3539  if (n <= 500) return 500;3540  return Math.ceil(n / 500) * 500;3541}35423543/**3544 * Snapshot the CURRENT on-disk vault state into history. Call this BEFORE3545 * overwriting peach_vault_a so the saved blob captures the about-to-be-lost3546 * state. Identical-to-most-recent blobs are skipped to avoid filling history3547 * with no-op writes.3548 */3549export async function takeVaultSnapshot(3550  reason: VaultSnapshot["reason"],3551): Promise<void> {3552  if (recoveryInFlight || vaultCreatesInFlight) return;3553  // The history store is real-mode state by construction, so it must not be3554  // written from a decoy session either. The guard lives here rather than only3555  // at the call sites so the invariant survives a new caller (PB-26-915).3556  if (vaultMode === "decoy") return;3557  vaultWritesInFlight++;3558  try {3559    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);3560    const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];3561    const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];35623563    // Nothing to snapshot if the real slot doesn't exist yet (fresh install,3564    // pre-createVault). createVault skips snapshots intentionally — there is3565    // no prior state to preserve.3566    if (!slotA) return;35673568    const vault_a = JSON.stringify(slotA);3569    const vault_b = JSON.stringify(slotB ?? slotA);35703571    // Best-effort entry count: only meaningful when the in-memory state is3572    // unlocked AND in real mode. Decoy mode would leak the decoy entry3573    // count; locked mode has no entries to count. Both fall through to null.3574    // PCH-01-023: store a coarse bucket, not the exact count — chrome.storage3575    // .local sits next to the AES-GCM blobs in plaintext, so an exact count would3576    // leak vault size and per-write deltas (the metadata padding hides this).3577    let entryCount: number | null = null;3578    if (derivedKey && vaultMode === "real") {3579      try {3580        entryCount = bucketEntryCount(entries.filter((e) => !e.deletedAt).length);3581      } catch {3582        entryCount = null;3583      }3584    }35853586    const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];3587    const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)3588      ? existingRaw3589      : { snapshots: [] };35903591    // Deduplication: if the most recent snapshot has byte-identical blobs,3592    // skip — saves the same vault N times in a row would otherwise burn the3593    // entire history window with no recovery value.3594    const latest = history.snapshots[0];3595    if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {3596      return;3597    }35983599    const snapshot: VaultSnapshot = {3600      id: crypto.randomUUID(),3601      savedAt: Date.now(),3602      reason,3603      vault_a,3604      vault_b,3605      entryCount,3606    };36073608    history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);3609    if (recoveryInFlight || vaultCreatesInFlight) return;3610    await chrome.storage.local.set({ [HISTORY_KEY]: history });3611  } catch (err) {3612    // Non-fatal — history must never block a save. A failed snapshot just3613    // means the user loses one rung of the safety ladder for this write.3614    // M4/QUA-006: log so the failure is visible; if it looks like a quota3615    // problem, notify the popup so the user can prune history themselves.3616    console.warn('[Peach] takeVaultSnapshot failed:', err);3617    if (String(err).includes('QUOTA') || String(err).includes('quota')) {3618      try {3619        await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });3620      } catch {3621        // popup may be closed; surfaced via console.warn above3622      }3623    }3624  } finally { vaultWritesInFlight--; }3625}36263627/** Wipe all vault history. Called by Panic / DESTROY_VAULT. */3628export async function clearVaultHistory(): Promise<void> {3629  if (recoveryInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");3630  vaultWritesInFlight++;3631  try {3632    await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });3633  } catch {3634    // Non-fatal — DESTROY_VAULT also runs storage.local.clear().3635  } finally { vaultWritesInFlight--; }3636}36373638/** Read all snapshots, newest first, for the Settings vault history view. */3639export async function getVaultHistory(): Promise<VaultSnapshot[]> {3640  if (vaultMode === "decoy") return [];3641  const raw = await chrome.storage.local.get(HISTORY_KEY);3642  const value = (raw as Record<string, unknown>)[HISTORY_KEY];3643  return sanitizeHistory(value);3644}36453646/**3647 * Replace the on-disk vault with the chosen snapshot's blobs and lock the3648 * vault. The current state is itself snapshotted before replacement.3649 */3650export async function restoreVaultSnapshot(3651  snapshotId: string,3652): Promise<{ ok: true } | { ok: false; error: string }> {3653  if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "vault_changed" };3654  vaultReplacementInFlight = true;3655  try {3656    if (vaultMode === "decoy") return { ok: false, error: "vault_locked" };3657    const history = await getVaultHistory();3658    const snapshot = history.find((s) => s.id === snapshotId);3659    if (!snapshot) return { ok: false, error: "snapshot_not_found" };36603661    const restoredA = parseHistorySlot(snapshot.vault_a);3662    const restoredB = parseHistorySlot(snapshot.vault_b);3663    if (!restoredA || !restoredB) return { ok: false, error: "snapshot_corrupt" };36643665    await takeVaultSnapshot("restore");3666    const current = await chrome.storage.local.get([SLOT_A, SLOT_B]);3667    const previousA = (current as Record<string, unknown>)[SLOT_A];3668    const previousB = (current as Record<string, unknown>)[SLOT_B];3669    try {3670      if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };3671      await chrome.storage.local.set({ [SLOT_A]: restoredA, [SLOT_B]: restoredB });3672      await stampLocalVaultMutation();3673    } catch {3674      try {3675        await chrome.storage.local.set({ [SLOT_A]: previousA, [SLOT_B]: previousB });3676      } catch {3677        // Preserve the restore failure if storage cannot complete the rollback.3678      }3679      return { ok: false, error: "snapshot_corrupt" };3680    }36813682    await lock();3683    return { ok: true };3684  } finally {3685    vaultReplacementInFlight = false;3686  }3687}36883689/**3690 * Rotate the vault's sync identity by generating a FRESH ROOT KEY and3691 * re-wrapping everything under it (MV-8). Because every sync credential —3692 * vault_id, the Noise static keypair, the Ed25519 manifest signing key,3693 * and the per-entry envelope keys — derives from the root key, rotation3694 * makes a lost/stolen device's retained key material useless. All paired3695 * devices must re-pair afterwards.3696 *3697 * CONSEQUENCE THE UI MUST SURFACE: the 12 recovery words also derive from3698 * the root key, so rotation INVALIDATES the old recovery phrase. The flow3699 * sets peach_recovery_pending so the popup re-presents the new words for3700 * confirmation, same as the initial recovery-word confirmation path.3701 */3702export async function rotateSyncIdentity(): Promise<{ ok: boolean; error?: string }> {3703  if (vaultCreatesInFlight) throw new Error("vault_changed");3704  vaultWritesInFlight++;3705  try {3706  if (!derivedKey || vaultMode !== "real") {3707    return { ok: false, error: "vault_locked" };3708  }3709  const slotA = await loadSlot(SLOT_A);3710  if (!slotA) return { ok: false, error: "missing_slot_a" };37113712  // 1. Fresh root key + recovery escrow (new words).3713  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =3714    await generateAndWrapRootKey();37153716  // 2. Re-wrap the new root key under the current password-derived key.3717  const newRootKey = unhex(rawRootKey);3718  const recoveryVaultKey = await encrypt(newRootKey, hex(derivedKey), "recovery_vault_key_v1");3719  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, newRootKey);37203721  // 3. Snapshot, then single atomic slot write — both escrow wrappings of3722  //    the new root key land together (same transactional rule as3723  //    changePassword). Entries are untouched: they are sealed under the3724  //    password-derived key, not the root key.3725  await takeVaultSnapshot("local_save");3726  const nextSlotA: StoredVault = {3727    ...slotA,3728    recovery_vault_key: recoveryVaultKey,3729    recovery_salt: recoverySalt,3730    recovery_wrapped_root_key: wrappedRootKey,3731    recovery_nonce: wrappedNonce,3732    recovery_tag: wrappedTag,3733    ...pwRoot,3734  };3735  await writeSlot(SLOT_A, nextSlotA);37363737  // 4. Swap in memory only after disk committed.3738  if (rootKey) zeroKey(rootKey);3739  rootKey = newRootKey;37403741  // 4b. The identity's root wrap was encrypted under the dead root. Without3742  //     this the identity survives only until the unlock key also changes.3743  await notifyIdentityKeysRotated();37443745  // 5. Old peers' identities derive from the dead root key — drop them all,3746  // with their rendezvous secrets (PB-26-213: rotation clears the map, so3747  // there is nothing to rewrap under the new key).3748  await clearPairedDevices();3749  await clearPairSecrets();37503751  // 6. Force re-presentation of the NEW recovery words on next popup view.3752  await setRecoveryConfirmPending(); // same flag the create-vault flow uses37533754  await stampLocalVaultMutation();3755  return { ok: true };3756  } finally { vaultWritesInFlight--; }3757}37583759/**3760 * Change the master password. Re-encrypts slot A with a fresh salt + new3761 * derived key. Slot B (duress or noise) is left untouched when duress is3762 * configured — it uses an independent key derived from the duress password —3763 * and regenerated as noise when duress is not configured.3764 */3765export async function changePassword(3766  currentPassword: string,3767  newPassword: string3768): Promise<boolean> {3769  if (vaultCreatesInFlight) throw new Error("vault_changed");3770  vaultWritesInFlight++;3771  try {37723773  const epoch = vaultEpoch;3774  const stale = () => epoch !== vaultEpoch;3775  if (!derivedKey || vaultMode !== "real") return false;37763777  // Verify current password before allowing any change3778  const valid = await verifyMainPassword(currentPassword);3779  if (!valid) return false;37803781  const slotA = await loadSlot(SLOT_A);3782  if (!slotA) return false;3783  if (!rootKey) return false;37843785  // Derive fresh key from new password + new random salt3786  const newSalt = generateSalt();3787  const newKey = await deriveKey(newPassword, newSalt);3788  if (stale()) {3789    zeroKey(newKey);3790    return false;3791  }37923793  // Re-encrypt the in-memory entries with the new key3794  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3795  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");37963797  // Pre-wrap root key under the new derived key. Recovery fields wrap rootKey3798  // under recovery words and remain untouched — recovery phrase keeps working3799  // across password changes (H4/COR-002).3800  const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);38013802  const recoveryVaultKey = await encrypt(rootKey, hex(newKey), "recovery_vault_key_v1");3803  const finalSlotA: StoredVault = {3804    ...slotA,3805    recovery_vault_key: recoveryVaultKey,3806    salt: hex(newSalt),3807    nonce,3808    ciphertext,3809    tag,3810    ...pwRoot,3811  };38123813  // Snapshot the OLD-key blob before overwriting it. If the user later3814  // restores from this snapshot they will need the OLD password — the3815  // post-restore lock surfaces that immediately.3816  await takeVaultSnapshot("local_save");38173818  // Single atomic write: ciphertext, salt, and pw_root_* fields all land in3819  // one storage transaction. An SW kill before this point leaves the old3820  // slot intact; after this point everything tied to the new password is3821  // already on disk together (M6/COR-004).3822  await writeSlot(SLOT_A, finalSlotA);3823  if (stale()) {3824    zeroKey(newKey);3825    return false;3826  }38273828  // Swap the in-memory key synchronously before any further await. If we3829  // threw between the Slot A write and this swap, the next persistEntries()3830  // would overwrite Slot A with old-key ciphertext, locking the user out.3831  zeroKey(derivedKey);3832  derivedKey = newKey;38333834  // PCH-01-008: the MV3 session escrow still holds the OLD key. Without this,3835  // the next service-worker restore decrypts the new-key Slot A with the stale3836  // key, fails tryDecryptSlotResult, and silently drops the user to a lock3837  // screen. Re-escrow the new key so restore survives a password change.3838  if (stale()) {3839    await lock();3840    return false;3841  }3842  await saveSessionKey(newKey, "real", epoch);3843  if (stale()) return false;38443845  // The identity envelope holds one wrap per recovering key. Swapping the3846  // unlock key kills the local wrap, so re-wrap now or the next key swap3847  // orphans the identity -- and until then the old password still opens it.3848  await notifyIdentityKeysRotated();3849  if (stale()) return false;38503851  // Regenerate noise for slot B when duress is not in use. Runs after the3852  // key swap so a failure here is a disposable noise regeneration, not a3853  // lockout.3854  if (!duressConfigured) {3855    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3856  }3857  await clearPinUnlockStorage();3858  await stampLocalVaultMutation();38593860  return true;3861  } finally { vaultWritesInFlight--; }3862}