vault.ts

142.6 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// Keep ambiguous records intact: an RP or account can own several credentials.1209function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {1210  let merged = false;1211  const transferable = new Set(["id", "type", "title", "username", "url", "passkey", "createdAt", "modifiedAt", "totp", "totpAlgorithm", "totpDigits", "totpPeriod"]);1212  for (const source of entries.filter((entry) => !entry.deletedAt && entry.passkey)) {1213    const passkey = source.passkey!;1214    if (source.type !== "login" && source.type !== "passkey") continue;1215    if (!passkey.userName || (source.username && source.username !== passkey.userName)) continue;1216    if (Object.entries(source).some(([key, value]) => !transferable.has(key) && value !== undefined && value !== "")) continue;1217    const targets = entries.filter((entry) => {1218      if (entry.deletedAt || entry.passkey || entry.type !== "login" || entry.username !== passkey.userName) return false;1219      return [entry.url, ...(entry.additionalUrls ?? [])].some((url) => {1220        if (!url) return false;1221        try {1222          return new URL(url.includes("://") ? url : `https://${url}`).hostname === passkey.rpId;1223        } catch {1224          return false;1225        }1226      });1227    });1228    if (targets.length !== 1) continue;1229    const target = targets[0]!;1230    if (source.totp && target.totp && (source.totp !== target.totp || source.totpAlgorithm !== target.totpAlgorithm || source.totpDigits !== target.totpDigits || source.totpPeriod !== target.totpPeriod)) continue;1231    target.passkey = passkey;1232    if (source.totp && !target.totp) {1233      target.totp = source.totp;1234      target.totpAlgorithm = source.totpAlgorithm;1235      target.totpDigits = source.totpDigits;1236      target.totpPeriod = source.totpPeriod;1237    }1238    const stamp = monotonicEntryTimestamp(Math.max(source.modifiedAt, target.modifiedAt));1239    target.modifiedAt = stamp;1240    source.modifiedAt = stamp;1241    source.deletedAt = stamp;1242    merged = true;1243  }1244  return { merged };1245}12461247// Validates that a `StoredVault` record on disk has the field shape we expect1248// before treating an AES-GCM decrypt success as a clean unlock. AES-GCM only1249// authenticates the static VERSION_BYTE AAD, not the `version` field on the1250// outer record — a corrupted `version: 42` slot still decrypts cleanly. This1251// check surfaces that as `corrupted` (M7/COR-007) so the popup can offer a1252// history-restore path instead of falsely reporting "wrong password".1253function hasValidVaultSchema(v: unknown): v is StoredVault {1254  if (typeof v !== "object" || v === null) return false;1255  const r = v as Record<string, unknown>;1256  return (1257    r.version === 1 &&1258    typeof r.salt === "string" &&1259    typeof r.nonce === "string" &&1260    typeof r.ciphertext === "string" &&1261    typeof r.tag === "string"1262  );1263}1264const MAX_HISTORY_BLOB_BYTES = 1_024 * 1_024;12651266function hasValidHistorySlot(value: unknown): value is StoredVault {1267  if (!hasValidVaultSchema(value)) return false;1268  return /^[0-9a-f]{32}$/i.test(value.salt) &&1269    /^[0-9a-f]{24}$/i.test(value.nonce) &&1270    /^[0-9a-f]+$/i.test(value.ciphertext) &&1271    value.ciphertext.length % 2 === 0 &&1272    value.ciphertext.length / 2 <= MAX_HISTORY_BLOB_BYTES &&1273    /^[0-9a-f]{32}$/i.test(value.tag);1274}12751276function parseHistorySlot(value: string): StoredVault | null {1277  try {1278    const parsed: unknown = JSON.parse(value);1279    return hasValidHistorySlot(parsed) ? parsed : null;1280  } catch {1281    return null;1282  }1283}12841285function isHistoryRecord(value: unknown): value is VaultSnapshot {1286  if (typeof value !== "object" || value === null) return false;1287  const record = value as Record<string, unknown>;1288  return typeof record.id === "string" && record.id.length > 0 && record.id.length <= 128 &&1289    typeof record.savedAt === "number" && Number.isFinite(record.savedAt) &&1290    typeof record.reason === "string" &&1291    typeof record.vault_a === "string" && record.vault_a.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1292    typeof record.vault_b === "string" && record.vault_b.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1293    (record.entryCount === null || typeof record.entryCount === "number");1294}12951296function sanitizeHistory(value: unknown): VaultSnapshot[] {1297  if (typeof value !== "object" || value === null) return [];1298  if (!("snapshots" in value) || !Array.isArray(value.snapshots)) return [];1299  return value.snapshots.filter(isHistoryRecord).slice(0, HISTORY_MAX);1300}13011302export type TryDecryptResult =1303  | { status: "ok"; payload: DecryptedPayload }1304  | { status: "wrong_key" }1305  | { status: "corrupted"; reason: string };13061307// Exported solely for `unlockFromCodex` below, which needs to verify a1308// supplied passphrase against a slotA blob *without* committing anything to1309// storage. Keep this internal otherwise — callers crossing the messages.ts1310// boundary should always go through `unlock` / `verifyMainPassword` so the1311// constant-time invariants in Projects.md §3.4 are not bypassed.1312export async function tryDecryptSlot(1313  vault: StoredVault,1314  key: Uint8Array,1315  aadTag?: string,1316): Promise<DecryptedPayload | null> {1317  const res = await tryDecryptSlotResult(vault, key, aadTag);1318  return res.status === "ok" ? res.payload : null;1319}13201321export async function tryDecryptSlotResult(1322  vault: StoredVault,1323  key: Uint8Array,1324  aadTag?: string,1325): Promise<TryDecryptResult> {1326  if (!hasValidVaultSchema(vault)) {1327    return { status: "corrupted", reason: "invalid_slot_schema" };1328  }1329  let plain: string;1330  try {1331    plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);1332  } catch {1333    return { status: "wrong_key" };1334  }1335  try {1336    const parsed = JSON.parse(plain) as unknown;1337    if (typeof parsed !== "object" || parsed === null) {1338      return { status: "corrupted", reason: "invalid_payload_shape" };1339    }1340    if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {1341      return { status: "corrupted", reason: "invalid_payload_shape" };1342    }1343    return { status: "ok", payload: decodePayload(plain) };1344  } catch {1345    return { status: "corrupted", reason: "invalid_payload_json" };1346  }1347}13481349// ---------------------------------------------------------------------------1350// Core operations1351// ---------------------------------------------------------------------------13521353function buildDomainIndexSync(all: VaultEntry[]): void {1354  domainIndex = new Map();13551356  for (const entry of all) {1357    if (entry.deletedAt) continue;1358    if (entry.type === "note" || entry.type === "card") continue;13591360    // An entry can match multiple sites via `additionalUrls`. Index each1361    // hostname so `queryDomain` returns the entry regardless of which alias1362    // the user is currently visiting. Dedupe per-entry so a single entry1363    // never appears twice in one bucket.1364    const domains = new Set<string>();1365    const primary = extractDomain(entry.url ?? "");1366    if (primary) domains.add(primary);1367    for (const extra of entry.additionalUrls ?? []) {1368      const d = extractDomain(extra);1369      if (d) domains.add(d);1370    }1371    if (domains.size === 0) continue;13721373    for (const domain of domains) {1374      const bucket = domainIndex.get(domain) ?? [];1375      bucket.push(entry);1376      domainIndex.set(domain, bucket);1377    }1378  }1379}13801381export async function createVault(password: string, replacement?: "warned-import"): Promise<{ committed: true; unlocked: boolean }> {1382  if (replacement !== undefined && replacement !== "warned-import") throw new Error("invalid_payload");1383  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");1384  vaultCreatesInFlight++;1385  let settle!: () => void;1386  creationSettled = new Promise<void>((resolve) => { settle = resolve; });1387  let nextKey: Uint8Array | null = null;1388  let nextRoot: Uint8Array | null = null;1389  let committed = false;1390  let publishedEpoch: number | null = null;1391  const epoch = vaultEpoch;1392  const check = () => {1393    if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1394  };1395  try {1396    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1397    check();1398    const occupied = raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;1399    if (occupied && replacement !== "warned-import") throw new Error("vault_already_exists");1400    const salt = generateSalt();1401    nextKey = await deriveKey(password, salt);1402    check();1403    const recovery = await generateAndWrapRootKey();1404    nextRoot = unhex(recovery.rawRootKey);1405    check();1406    const encrypted = await encrypt(nextKey, encodePayload([], false, 0), "slot_a_v1");1407    const pwRoot = await wrapRootKeyForDerivedKey(nextKey, nextRoot);1408    const recoveryVaultKey = await encrypt(nextRoot, hex(nextKey), "recovery_vault_key_v1");1409    check();1410    const slotA: StoredVault = {1411      ...encrypted, ...pwRoot, version: 1, salt: hex(salt),1412      recovery_vault_key: recoveryVaultKey,1413      recovery_salt: recovery.recoverySalt,1414      recovery_wrapped_root_key: recovery.wrappedRootKey,1415      recovery_nonce: recovery.wrappedNonce,1416      recovery_tag: recovery.wrappedTag,1417    };1418    const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1419    check();1420    if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");1421    const previous = Number(raw.peach_last_modified_at);1422    const update: Record<string, unknown> = {1423      [SLOT_A]: slotA, [SLOT_B]: generateNoiseBlob(encrypted.ciphertext.length / 2),1424      peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previous) ? previous + 1 : 0)),1425    };1426    if (occupied) {1427      const history = raw[HISTORY_KEY] as VaultHistory | undefined;1428      const snapshot: VaultSnapshot = {1429        id: crypto.randomUUID(), savedAt: Date.now(), reason: "restore", entryCount: null,1430        vault_a: JSON.stringify(raw[SLOT_A] ?? null), vault_b: JSON.stringify(raw[SLOT_B] ?? null),1431      };1432      update[HISTORY_KEY] = { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) };1433    }1434    try { await chrome.storage.local.set(update); }1435    catch (error) { throw mapStorageError(error); }1436    committed = true;1437    if (epoch !== vaultEpoch || vaultRemovalsInFlight) return { committed: true, unlocked: false };1438    const previousKey = derivedKey;1439    const previousRoot = rootKey;1440    publishedEpoch = ++vaultEpoch;1441    derivedKey = nextKey;1442    rootKey = nextRoot;1443    nextKey = null;1444    nextRoot = null;1445    entries = [];1446    tombstones = new Map();1447    vaultMode = "real";1448    duressConfigured = false;1449    buildDomainIndexSync(entries);1450    if (previousKey) zeroKey(previousKey);1451    if (previousRoot) zeroKey(previousRoot);1452    await clearSessionKey();1453    if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1454    await identityHooks?.onVaultCreated(password).catch((error) => {1455      console.warn("[Peach] local identity promotion failed:", error);1456    });1457    if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1458    touchAutoLock();1459    return { committed: true, unlocked: true };1460  } catch (error) {1461    if (!committed) throw error;1462    console.warn("[Peach] vault saved; unlock required:", error);1463    if (publishedEpoch === vaultEpoch) {1464      await lock().catch((lockError) => console.warn("[Peach] creation session cleanup failed:", lockError));1465    }1466    return { committed: true, unlocked: false };1467  } finally {1468    if (nextKey) zeroKey(nextKey);1469    if (nextRoot) zeroKey(nextRoot);1470    vaultCreatesInFlight--;1471    settle();1472  }1473}14741475/**1476 * Creates a local vault from an existing vault root key received through the1477 * SAS-gated adoption protocol. The password is local to this device; it wraps1478 * the adopted root key at rest and does not need to match the source device.1479 */1480export async function createVaultFromRootKey(1481  password: string,1482  rootKeyHex: string,1483): Promise<{ vaultId: string }> {1484  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");1485  if (typeof password !== "string" || password.length === 0) {1486    throw new Error("ADOPT_INVALID_PASSWORD");1487  }1488  if (typeof rootKeyHex !== "string" || !/^[0-9a-f]{64}$/.test(rootKeyHex)) {1489    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars");1490  }14911492  if (vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");1493  const rootKeyBytes = unhex(rootKeyHex);1494  if (rootKeyBytes.length !== 32) {1495    rootKeyBytes.fill(0);1496    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");1497  }14981499  vaultCreatesInFlight++;1500  let settle!: () => void;1501  creationSettled = new Promise<void>((resolve) => { settle = resolve; });1502  const epoch = vaultEpoch;1503  let nextDerivedKey: Uint8Array | null = null;1504  let sessionRootKey: Uint8Array | null = null;1505  let committed = false;1506  try {1507    if (await hasVault()) {1508      throw new Error("ADOPT_VAULT_ALREADY_EXISTS");1509    }15101511    const nextEntries: VaultEntry[] = [];1512    const nextDuressConfigured = false;1513    const vaultId = await computeVaultId(rootKeyBytes);1514    const salt = generateSalt();1515    nextDerivedKey = await deriveKey(password, salt);1516    const recovery = await wrapExistingRootKeyForRecovery(rootKeyBytes);15171518    sessionRootKey = new Uint8Array(rootKeyBytes);1519    const plaintext = encodePayload(nextEntries, nextDuressConfigured, 0);1520    const { nonce, ciphertext, tag } = await encrypt(nextDerivedKey, plaintext, "slot_a_v1");1521    const pwRoot = await wrapRootKeyForDerivedKey(nextDerivedKey, sessionRootKey);1522    const slotA: StoredVault = {1523      recovery_vault_key: await encrypt(sessionRootKey, hex(nextDerivedKey), "recovery_vault_key_v1"),1524      version: 1,1525      salt: hex(salt),1526      nonce,1527      ciphertext,1528      tag,1529      recovery_salt: recovery.recoverySalt,1530      recovery_wrapped_root_key: recovery.wrappedRootKey,1531      recovery_nonce: recovery.wrappedNonce,1532      recovery_tag: recovery.wrappedTag,1533      ...pwRoot,1534    };1535    const slotB = generateNoiseBlob(ciphertext.length / 2);1536    if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1537    await commitCreatedVaultSlots(slotA, slotB);1538    committed = true;1539    if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1540    vaultEpoch++;15411542    const previousDerivedKey = derivedKey;1543    const previousRootKey = rootKey;1544    derivedKey = nextDerivedKey;1545    rootKey = sessionRootKey;1546    nextDerivedKey = null;1547    sessionRootKey = null;1548    entries = nextEntries;1549    tombstones = new Map();1550    vaultMode = "real";1551    duressConfigured = nextDuressConfigured;1552    buildDomainIndexSync(entries);1553    if (previousDerivedKey && previousDerivedKey !== derivedKey) zeroKey(previousDerivedKey);1554    if (previousRootKey && previousRootKey !== rootKey) previousRootKey.fill(0);1555    touchAutoLock();15561557    // The receiver's identity was minted before this vault existed (adoption v21558    // needs it in its first frame), so re-seal it under the vault keys now.1559    await identityHooks?.onVaultCreated(password).catch((error) => {1560      console.warn("[Peach] local identity promotion failed:", error);1561    });15621563    return { vaultId };1564  } catch (error) {1565    if (committed) {1566      // Removal cannot use withVaultRemoval while this operation owns creationSettled.1567      try { await lock(); }1568      finally { await chrome.storage.local.remove([SLOT_A, SLOT_B, "peach_last_modified_at"]); }1569    }1570    throw error;1571  } finally {1572    vaultCreatesInFlight--;1573    settle();1574    rootKeyBytes.fill(0);1575    if (nextDerivedKey) zeroKey(nextDerivedKey);1576    if (sessionRootKey) sessionRootKey.fill(0);1577  }1578}15791580export async function hasVault(): Promise<boolean> {1581  const raw = await chrome.storage.local.get([SLOT_A, SLOT_B]);1582  return raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;1583}15841585/**1586 * Returns whether the real vault has recorded that a duress passphrase is1587 * configured. Reliable only after a real-mode unlock — before unlock or in1588 * decoy mode, returns false because we cannot read slot A's plaintext.1589 */1590export async function isDuressEnabled(): Promise<boolean> {1591  return vaultMode === "real" && duressConfigured;1592}15931594export async function setupDuress(duressPassword: string): Promise<void> {1595  if (vaultCreatesInFlight) throw new Error("vault_changed");1596  vaultWritesInFlight++;1597  try {1598  if (!derivedKey || vaultMode !== "real") {1599    throw new Error("vault must be unlocked in real mode");1600  }1601  // Encrypt the decoy payload (empty entries) under the duress key. Pad to1602  // at least the current slot A ciphertext size so the two slots look the1603  // same at rest at setup time.1604  const slotA = await loadSlot(SLOT_A);1605  if (!slotA) throw new Error("missing slot A");16061607  const decoySalt = generateSalt();1608  const decoyKey = await deriveKey(duressPassword, decoySalt);1609  try {1610    // Pad the decoy to the fixed duress ceiling. Slot A is re-encrypted to the1611    // same ceiling by the persistSlotA() call below (duressConfigured is now1612    // true), so both slots are exactly DURESS_SLOT_SIZE+tag at rest and their1613    // lengths cannot reveal that duress is configured (audit MEDIUM).1614    const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);1615    const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");1616    await writeSlot(SLOT_B, {1617      version: 1,1618      salt: hex(decoySalt),1619      nonce,1620      ciphertext,1621      tag,1622    });1623  } finally {1624    zeroKey(decoyKey);1625  }16261627  // Re-encrypt slot A with the duressConfigured flag set to true. No external1628  // flag is written — the bit lives inside the encrypted envelope.1629  duressConfigured = true;1630  await persistSlotA();1631  } finally { vaultWritesInFlight--; }1632}16331634export async function disableDuress(): Promise<void> {1635  if (vaultCreatesInFlight) throw new Error("vault_changed");1636  vaultWritesInFlight++;1637  try {1638  if (!derivedKey || vaultMode !== "real") {1639    throw new Error("vault must be unlocked in real mode");1640  }1641  // Overwrite slot B with fresh noise that matches slot A's size. The slot1642  // remains occupied so its mere existence does not signal that duress was1643  // ever configured.1644  const slotA = await loadSlot(SLOT_A);1645  if (slotA) {1646    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));1647  }16481649  duressConfigured = false;1650  await persistSlotA();1651  } finally { vaultWritesInFlight--; }1652}16531654// L14/COR-015: this function intentionally checks slot A (real vault) only.1655// A duress-mode user attempting changePassword is rejected earlier by the1656// vaultMode === 'decoy' check at changePassword. The real-vs-decoy1657// distinction here is by design — duress users cannot rotate the real1658// password by guessing it, and the asymmetry in error timing is acceptable1659// because duress mode is opt-in and the user knows their own decoy key.1660export async function verifyMainPassword(password: string): Promise<boolean> {1661  const slotA = await loadSlot(SLOT_A);1662  if (!slotA) return false;1663  const key = await deriveKey(password, unhex(slotA.salt));1664  try {1665    return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;1666  } finally {1667    zeroKey(key);1668  }1669}16701671export async function unlock(password: string): Promise<boolean> {1672  return attemptUnlockWithDerive(password, deriveKey);1673}16741675async function attemptUnlockWithDerive(1676  password: string,1677  derive: typeof deriveKey,1678): Promise<boolean> {1679  vaultUnlocksInFlight++;1680  try {1681  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;1682  const epoch = vaultEpoch;1683  const stale = () => epoch !== vaultEpoch;1684  // Load both current-format slots in parallel. Both exist on a supported1685  // install; the1686  // parallel load and the parallel derivation below keep wall-clock time1687  // constant regardless of which slot's passphrase (real or decoy) the1688  // caller supplied, so a timing side channel cannot distinguish the1689  // duress path from the real-unlock path (DUR-002).1690  const [slotA, slotB] = await Promise.all([1691    loadSlot(SLOT_A),1692    loadSlot(SLOT_B),1693  ]);16941695  // Derive both keys in parallel, unconditionally.1696  const [keyA, keyB] = await Promise.all([1697    slotA ? derive(password, unhex(slotA.salt)) : Promise.resolve(null),1698    slotB ? derive(password, unhex(slotB.salt)) : Promise.resolve(null),1699  ]);17001701  // Attempt both decrypts in parallel. The Result variant lets us distinguish1702  // 'wrong_key' from 'corrupted' so callers can offer a history-restore path1703  // when a slot's schema is invalid even though AES-GCM authenticated (M7).1704  const [resultA, resultB] = await Promise.all([1705    keyA && slotA1706      ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")1707      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1708    keyB && slotB1709      ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")1710      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),1711  ]);1712  const payloadA = resultA.status === "ok" ? resultA.payload : null;1713  const payloadB = resultB.status === "ok" ? resultB.payload : null;17141715  if (stale()) {1716    if (keyA) zeroKey(keyA);1717    if (keyB) zeroKey(keyB);1718    return false;1719  }17201721  if (payloadA && keyA) {1722    if (stale()) {1723      zeroKey(keyA);1724      if (keyB) zeroKey(keyB);1725      return false;1726    }1727    derivedKey = keyA;1728    vaultMode = "real";1729    entries = payloadA.entries;1730    tombstones = payloadA.tombstones;1731    duressConfigured = payloadA.duressConfigured;1732    buildDomainIndexSync(entries);1733    await loadSettings();1734    if (stale()) {1735      await lock();1736      return false;1737    }1738    touchAutoLock();1739    if (keyB) zeroKey(keyB);17401741    // Current vaults always carry a password-wrapped root key. Older vaults1742    // without this escrow are outside the supported storage format.1743    rootKey = slotA ? await deriveRootKeyFromDerivedKey(keyA, slotA) : null;1744    if (!rootKey) {1745      await lock();1746      return false;1747    }17481749    // Repair missing or stale escrow only after a real password authenticates the slot.1750    if (slotA) {1751      const escrowed = slotA.recovery_vault_key1752        ? await openSealedKey(rootKey, slotA.recovery_vault_key, "recovery_vault_key_v1") : null;1753      const matches = escrowed !== null && escrowed.every((byte, i) => byte === keyA[i]);1754      if (escrowed) zeroKey(escrowed);1755      if (stale()) { await lock(); return false; }1756      if (!matches) {1757        try {1758          const recoveryVaultKey = await encrypt(rootKey, hex(keyA), "recovery_vault_key_v1");1759          if (stale()) { await lock(); return false; }1760          await writeSlot(SLOT_A, { ...slotA, recovery_vault_key: recoveryVaultKey });1761          if (stale()) { await lock(); return false; }1762        } catch (error) {1763          await lock();1764          throw error;1765        }1766      }1767    }17681769    // PB-26-213: adopt legacy plaintext pair secrets into the encrypted1770    // record and refresh the trusted-session operational copy.1771    await reconcilePairSecrets(rootKey);1772    if (stale()) {1773      await lock();1774      return false;1775    }1776    await lockedSyncUnlockHook?.().catch((error) => {1777      console.warn("[Peach sync] locked inbox drain failed:", error);1778    });1779    if (stale()) {1780      await lock();1781      return false;1782    }1783    await resetPinFailedAttempts();1784    if (stale()) {1785      await lock();1786      return false;1787    }1788    await saveSessionKey(keyA, "real", epoch);1789    if (stale()) return false;1790    return true;1791  }17921793  if (payloadB && keyB) {1794    if (stale()) {1795      zeroKey(keyB);1796      if (keyA) zeroKey(keyA);1797      return false;1798    }1799    derivedKey = keyB;1800    vaultMode = "decoy";1801    decoySyncTeardownHook?.();1802    // A duress session must not retain the real vault's root key. It gates the1803    // recovery words, the sync identity, and the root wrap of the local device1804    // identity, so leaving it live would expose all three in duress mode.1805    if (rootKey) {1806      rootKey.fill(0);1807      rootKey = null;1808    }1809    entries = payloadB.entries;1810    tombstones = payloadB.tombstones;1811    duressConfigured = false;1812    buildDomainIndexSync(entries);1813    await loadSettings();1814    touchAutoLock();1815    if (keyA) zeroKey(keyA);1816    // PB-26-213: a duress session must never serve the real pair-secret map.1817    await dropSessionCache();1818    // Nor the real device identity: a duress session is not a real one.1819    await notifyIdentitySessionEnded();1820    if (stale()) {1821      await lock();1822      return false;1823    }1824    await saveSessionKey(keyB, "decoy", epoch);1825    if (stale()) return false;1826    return true;1827  }18281829  if (keyA) zeroKey(keyA);1830  if (keyB) zeroKey(keyB);1831  // Surface corruption (good AES tag, broken schema) distinctly from1832  // wrong-password so the popup can offer history-restore (M7/COR-007).1833  if (resultA.status === "corrupted") {1834    lastUnlockFailureReason = resultA.reason;1835  } else if (resultB.status === "corrupted") {1836    lastUnlockFailureReason = resultB.reason;1837  }1838  return false;1839  } finally { vaultUnlocksInFlight--; }1840}18411842// ---------------------------------------------------------------------------1843// MV3 service worker session key — survives SW restarts within a browser session1844// ---------------------------------------------------------------------------18451846// chrome.storage.session is cleared on browser close; survives SW restart.1847// Firefox does not implement it (persistent background script, no restart risk).1848const SESSION_KEY_STORAGE = "peach_session_dk";18491850// Order writes and removals so lock's awaited removal is a barrier after1851// every escrow write that started before it.1852let sessionKeyMutation = Promise.resolve();18531854function mutateSessionKey(mutation: () => Promise<void>): Promise<void> {1855  const task = sessionKeyMutation.then(mutation, mutation);1856  sessionKeyMutation = task.catch(() => undefined);1857  return task;1858}18591860// PB-26-203: the session-key escrow may only operate where startup positively1861// established trusted-only session storage. Defaults to available so direct1862// vault imports (tests, non-entry bootstraps) keep working; entry.ts applies1863// the real hardening result before the first restore.1864let sessionEscrowAvailable = true;18651866/**1867 * Apply the storage-hardening result at startup. When the trusted-only1868 * session state cannot be established, any stored session key is removed and1869 * the escrow stays off: the user unlocks again after a worker restart1870 * instead of trusting an unproven boundary.1871 */1872export async function applyStorageHardening(sessionEscrow: boolean): Promise<void> {1873  setSessionAllowed(sessionEscrow);1874  if (sessionEscrow) return;1875  sessionEscrowAvailable = false;1876  await clearSessionKey();1877}18781879async function saveSessionKey(1880  key: Uint8Array,1881  mode: "real" | "decoy",1882  expectedEpoch = vaultEpoch,1883): Promise<void> {1884  const session = chrome.storage.session;1885  if (!session || !sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;1886  const stored = { keyHex: hex(key), mode };1887  await mutateSessionKey(async () => {1888    if (!sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;1889    await session.set({ [SESSION_KEY_STORAGE]: stored });1890  });1891}18921893async function clearSessionKey(): Promise<void> {1894  const session = chrome.storage.session;1895  if (!session) return;1896  await mutateSessionKey(() => session.remove(SESSION_KEY_STORAGE));1897}18981899// A lock that only holds while the service worker stays alive is no lock at1900// all: a cold worker's restoreFromSession() would find the surviving session1901// key and silently re-unlock ~a minute after the user locked. So lock()1902// bumps this epoch synchronously at entry and zeroes keys/indexes before any1903// await; a restore that started earlier sees the mismatch after its next1904// await and aborts instead of publishing.1905let vaultEpoch = 0;19061907// One in-flight restore shared by concurrent callers: storage is read once1908// and the locked-sync unlock hook runs once.1909let restoreInFlight: Promise<boolean> | null = null;19101911/**1912 * On SW restart, re-derive all in-memory vault state from the session key1913 * stored in chrome.storage.session (set at unlock time, cleared by lock();1914 * also cleared on browser close or when restoration fails).1915 * Returns true if the vault was restored, false if no session key was found.1916 * No-ops if the vault is already unlocked.1917 */1918export async function restoreFromSession(): Promise<boolean> {1919  vaultUnlocksInFlight++;1920  try {1921  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;1922  if (derivedKey !== null) return true;1923  if (restoreInFlight) return restoreInFlight;1924  const task = restoreFromSessionInner();1925  restoreInFlight = task;1926  try {1927    return await task;1928  } finally {1929    restoreInFlight = null;1930  }1931  } finally { vaultUnlocksInFlight--; }1932}19331934async function restoreFromSessionInner(): Promise<boolean> {1935  const epoch = vaultEpoch;1936  const stale = () => epoch !== vaultEpoch;1937  if (derivedKey !== null) return true;1938  if (!sessionEscrowAvailable) return false;1939  if (!chrome.storage.session) return false;1940  const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);1941  if (stale()) return false;1942  const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;1943  if (!entry?.keyHex) return false;19441945  const key = unhex(entry.keyHex);1946  const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;1947  const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";1948  const slot = await loadSlot(slotKey);1949  if (stale()) { zeroKey(key); return false; }1950  if (!slot) { await clearSessionKey(); return false; }19511952  const result = await tryDecryptSlotResult(slot, key, aadTag);1953  if (stale()) { zeroKey(key); return false; }1954  if (result.status !== "ok") { await clearSessionKey(); return false; }19551956  // Decrypted payload stays in locals until the final epoch-checked commit1957  // below; nothing observable is published before then.1958  const payload = result.payload;1959  await loadSettings();1960  if (stale()) { zeroKey(key); return false; }19611962  // Rehydrate the root key used by sync identity derivation from the password1963  // escrow stored on the current vault format.1964  let freshRoot: Uint8Array | null = null;1965  if (entry.mode === "real") {1966    freshRoot = await deriveRootKeyFromDerivedKey(key, slot);1967    if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }1968    if (!freshRoot) {1969      await lock();1970      return false;1971    }1972  }19731974  if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }1975  if (freshRoot) {1976    // PB-26-213: encrypted pair-secret record + session copy, before publish.1977    await reconcilePairSecrets(freshRoot);1978    if (stale()) { zeroKey(key); zeroKey(freshRoot); return false; }1979  } else {1980    // PB-26-213: a duress restore must never serve the real pair-secret map.1981    await dropSessionCache();1982    // Nor the real device identity.1983    await notifyIdentitySessionEnded();1984    if (stale()) { zeroKey(key); return false; }1985  }1986  derivedKey = key;1987  vaultMode = entry.mode;1988  if (entry.mode === "decoy") decoySyncTeardownHook?.();1989  entries = payload.entries;1990  tombstones = payload.tombstones;1991  duressConfigured = entry.mode === "real" ? payload.duressConfigured : false;1992  if (freshRoot) rootKey = freshRoot;1993  buildDomainIndexSync(entries);1994  touchAutoLock();19951996  await lockedSyncUnlockHook?.().catch((error) => {1997    console.warn("[Peach sync] locked inbox drain failed:", error);1998  });1999  if (stale()) return false;20002001  return true;2002}20032004export async function lock(): Promise<void> {2005  // A user-initiated lock must be durable across MV3 service-worker restarts.2006  // The SW is idle-killed after ~30s of inactivity, and the popup's next open2007  // wakes a cold SW whose restoreFromSession() reads chrome.storage.session.2008  // If the session key survived lock(), that restore would silently re-unlock2009  // the vault ~a minute after the user locked it — a lock that only held2010  // while the SW happened to stay alive. The background-sync convenience the2011  // session key once bought (sync runner re-waking to a restored vault) is2012  // not worth an unlocked vault the user never asked to unlock; when locked,2013  // sync-runner correctly reports VAULT_LOCKED instead.2014  vaultEpoch++;2015  if (derivedKey) {2016    zeroKey(derivedKey);2017    derivedKey = null;2018  }2019  if (rootKey) {2020    rootKey.fill(0);2021    rootKey = null;2022  }20232024  entries = [];2025  tombstones = new Map();2026  domainIndex = new Map();2027  vaultMode = "real";2028  duressConfigured = false;2029  clearAutoLock();2030  await clearSessionKey();2031  // The decrypted identity is session state as well, so a locked vault must not2032  // leave one behind; clear it after the in-memory state is gone.2033  await notifyIdentitySessionEnded();2034}20352036export function isUnlocked(): boolean {2037  return derivedKey !== null;2038}2039/** True only while the active session is unlocked through the decoy slot. */2040export function isDecoyMode(): boolean {2041  return derivedKey !== null && vaultMode === "decoy";2042}20432044// Opens the vault using a pre-derived AES-256 key (skipping Argon2id). The2045// PIN-unlock path unwraps this key from its PIN wrap; the passphrase path2046// always derives from scratch via Argon2id.2047export async function unlockWithKey(2048  masterKeyHex: string,2049): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {2050  vaultUnlocksInFlight++;2051  try {2052  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };2053  const epoch = vaultEpoch;2054  const stale = () => epoch !== vaultEpoch;2055  let masterKeyBytes: Uint8Array | null = null;2056  try {2057    masterKeyBytes = unhex(masterKeyHex);2058    const stored = await loadSlot(SLOT_A);2059    if (!stored) return { ok: false, error: "invalid_key" };2060    const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");2061    if (!payload || stale()) {2062      zeroKey(masterKeyBytes);2063      return { ok: false, error: "invalid_key" };2064    }20652066    derivedKey = masterKeyBytes;2067    vaultMode = "real";2068    entries = payload.entries;2069    tombstones = payload.tombstones;2070    duressConfigured = payload.duressConfigured;2071    buildDomainIndexSync(entries);2072    await loadSettings();2073    touchAutoLock();20742075    rootKey = await deriveRootKeyFromDerivedKey(masterKeyBytes, stored);2076    if (!rootKey) {2077      await lock();2078      return { ok: false, error: "invalid_key" };2079    }2080    await reconcilePairSecrets(rootKey);2081    if (stale()) {2082      await lock();2083      return { ok: false, error: "invalid_key" };2084    }2085    await saveSessionKey(masterKeyBytes, "real", epoch);2086    if (stale()) return { ok: false, error: "invalid_key" };2087    return { ok: true, entries };2088  } catch {2089    if (masterKeyBytes && derivedKey !== masterKeyBytes) zeroKey(masterKeyBytes);2090    return { ok: false, error: "invalid_key" };2091  }2092  } finally { vaultUnlocksInFlight--; }2093}20942095// --- Adoption duress-slot helpers (passthrough, no decrypt) ---20962097/**2098 * Adoption SOURCE helper: returns the sealed slot B as a JSON string when2099 * duress is configured and slot B exists, so the inline snapshot can ship it2100 * to the receiver. Returns null otherwise. Never decrypts.2101 */2102export async function exportDuressSlotForAdoption(): Promise<string | null> {2103  if (!(await isDuressEnabled())) return null;2104  const slotB = await loadSlot(SLOT_B);2105  if (!slotB) return null;2106  return JSON.stringify(slotB);2107}21082109/**2110 * Adoption RECEIVER helper: installs a duress slot received from a source2111 * device. Validates the StoredVault shape (same guard as unlockFromCodex)2112 * and writes it to slot B. Throws on invalid shape so the caller can treat2113 * it as a non-fatal snapshot failure. Never decrypts.2114 */2115export async function installAdoptedDuressSlot(json: string): Promise<void> {2116  if (vaultCreatesInFlight) throw new Error("vault_changed");2117  vaultWritesInFlight++;2118  try {2119  let parsed: StoredVault;2120  try {2121    const raw = JSON.parse(json) as unknown;2122    if (!hasValidVaultSchema(raw)) {2123      throw new Error("invalid_duress_slot_shape");2124    }2125    parsed = raw;2126  } catch (err) {2127    if (err instanceof SyntaxError) {2128      throw new Error("invalid_duress_slot_shape");2129    }2130    throw err;2131  }2132  await writeSlot(SLOT_B, parsed);2133  } finally { vaultWritesInFlight--; }2134}21352136/**2137 * Restore the vault from a parsed Peach Codex payload.2138 *2139 * The supplied passphrase is verified against the Codex's slotA *before* any2140 * storage mutation — wrong passphrases return without touching disk. On2141 * success, the current vault state is snapshotted (reason: "restore") so the2142 * user can revert via Settings -> Vault History, then slotA/slotB are written2143 * and `peach_last_modified_at` is set to the Codex's recorded timestamp. A2144 * regular `unlock()` follows so the rest of the SW sees the standard2145 * post-unlock state.2146 *2147 * Intentionally non-Pro-gated — see peach_codex_v2.md "Pro gating". A Codex2148 * printed by a Pro user must always be restorable, even on a free device.2149 *2150 * Timing is not held constant here (in contrast to `unlock`): the Codex flow2151 * is an explicit user action with a known passphrase, not a passive lock2152 * screen, so the duress-vs-real timing side channel does not apply.2153 */2154export async function unlockFromCodex(params: {2155  slotA: string; // JSON string of StoredVault for slot A2156  slotB: string | null; // JSON string of StoredVault for slot B, or null2157  timestamp: number;2158  masterPassphrase: string;2159}): Promise<2160  | { ok: true; entryCount: number }2161  | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" | "missing_root_escrow" }2162> {2163  if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");2164  vaultReplacementInFlight = true;2165  try {2166    let parsedSlotA: StoredVault;2167    let parsedSlotB: StoredVault | null = null;2168    try {2169      const rawA = JSON.parse(params.slotA) as unknown;2170      if (!hasValidVaultSchema(rawA)) {2171        return { ok: false, reason: "invalid_slot_format" };2172      }2173      parsedSlotA = rawA;2174      if (params.slotB !== null) {2175        const rawB = JSON.parse(params.slotB) as unknown;2176        if (!hasValidVaultSchema(rawB)) {2177          return { ok: false, reason: "invalid_slot_format" };2178        }2179        parsedSlotB = rawB;2180      }2181    } catch {2182      return { ok: false, reason: "invalid_slot_format" };2183    }21842185    // Verify the passphrase and the password-wrapped root escrow against the2186    // staged Slot A WITHOUT writing anything. Payload decoding is part of the2187    // trial decrypt, so unlock() cannot be the first place these checks run.2188    const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));2189    const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");2190    if (!trialPayload) {2191      zeroKey(trialKey);2192      return { ok: false, reason: "wrong_passphrase" };2193    }2194    const hasEscrow =2195      !!parsedSlotA.pw_root_ciphertext && !!parsedSlotA.pw_root_nonce && !!parsedSlotA.pw_root_tag;2196    if (!hasEscrow) {2197      zeroKey(trialKey);2198      return { ok: false, reason: "missing_root_escrow" };2199    }2200    const stagedRootKey = await deriveRootKeyFromDerivedKey(trialKey, parsedSlotA);2201    if (!stagedRootKey) {2202      zeroKey(trialKey);2203      return { ok: false, reason: "wrong_passphrase" };2204    }2205    zeroKey(stagedRootKey);2206    zeroKey(trialKey);22072208    // Stage the complete candidate pair in memory before touching storage.2209    const stagedSlotB = parsedSlotB ?? generateNoiseBlob(parsedSlotA.ciphertext.length / 2);22102211    // Drop the trial key; `unlock()` below derives its own copy. Holding two2212    // copies of the master key in memory at once would be a needless surface.22132214    // Snapshot the about-to-be-overwritten on-disk state so the user can revert2215    // a mistaken Codex restore via the Vault History UI. Non-fatal if it fails.2216    await takeVaultSnapshot("restore");2217    const previousSlotA = await loadSlot(SLOT_A);2218    const previousSlotB = await loadSlot(SLOT_B);2219    let slotACommitted = false;2220    let slotBCommitted = false;2221    try {2222      await writeSlot(SLOT_A, parsedSlotA);2223      slotACommitted = true;2224      await writeSlot(SLOT_B, stagedSlotB);2225      slotBCommitted = true;2226      await chrome.storage.local.set({2227        peach_last_modified_at: String(params.timestamp),2228      });2229    } catch (err) {2230      if (slotBCommitted && previousSlotB) await writeSlot(SLOT_B, previousSlotB);2231      if (slotACommitted && previousSlotA) await writeSlot(SLOT_A, previousSlotA);2232      throw err;2233    }22342235    // Standard unlock path so domain index, settings, auto-lock, and2236    // recovery-key state all populate exactly as a normal unlock would.2237    const ok = await unlock(params.masterPassphrase);2238    if (!ok) {2239      // Should be unreachable — the staged candidate passed the same checks.2240      return { ok: false, reason: "wrong_passphrase" };2241    }2242    return { ok: true, entryCount: getEntries().length };2243  } finally {2244    vaultReplacementInFlight = false;2245  }2246}22472248// Returns the current in-memory derived key as a hex string. Only the PIN2249// unlock path needs this value, and it reads module state directly; this2250// accessor exists so unlockWithKey's root-key rehydration is testable.2251export /* @testable */ function getDerivedKeyHex(): string {2252  if (!derivedKey) throw new Error("vault_not_unlocked");2253  return hex(derivedKey);2254}22552256/**2257 * Returns the vault's stable root key as hex, or null when locked / not yet2258 * populated. The root key is random per-vault, generated at creation, escrowed2259 * under the recovery words, and re-wrapped (not regenerated) on every password2260 * change — so it is INVARIANT across password rotation, unlike getDerivedKeyHex.2261 *2262 * This is the correct input for sync identity derivation (vault_id, the Noise2263 * NK static key, the Ed25519 manifest signing key, and per-entry envelope2264 * keys): paired devices keep the same identity and can still decrypt each2265 * other's entries after either side rotates its master password (SEV-2-B).2266 *2267 * Returns null rather than throwing so sync callers degrade to VAULT_LOCKED2268 * instead of crashing; rootKey is populated on every supported real-mode2269 * unlock via deriveRootKeyFromDerivedKey.2270 */2271export function getRootKeyHex(): string | null {2272  return rootKey ? hex(rootKey) : null;2273}22742275export function getEntries(): VaultEntry[] {2276  if (!derivedKey) throw new Error("vault_locked");2277  return entries.filter((entry) => !entry.deletedAt);2278}22792280const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;22812282export function getIdentities(): SavedIdentity[] {2283  if (!derivedKey) throw new Error("vault_locked");2284  const active = entries.filter((e) => !e.deletedAt && e.type === "login");22852286  const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();2287  const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();22882289  for (const entry of active) {2290    const domain = extractDomain(entry.url ?? "") ?? "";2291    const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;22922293    function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {2294      const existing = map.get(v);2295      if (!existing || modifiedAt > existing.lastUsed) {2296        map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });2297      } else {2298        map.set(v, { ...existing, count: existing.count + 1 });2299      }2300    }23012302    const uVal = entry.username?.trim();2303    if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);23042305    // Also count the dedicated email field — entries created via the inline2306    // popup new-entry form store email here rather than in username.2307    const eVal = entry.email?.trim();2308    if (eVal) tally(emailMap, eVal);2309  }23102311  const toIdentity = (type: "email" | "username") =>2312    ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({2313      value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,2314    });23152316  return [2317    ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),2318    ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),2319  ];2320}23212322export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {2323  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");23242325  const now = Date.now();2326  const added: VaultEntry[] = [];2327  for (const draft of drafts) {2328    try {2329      const sanitized = sanitizeEntryDraft(draft);2330      const nextEntry: VaultEntry = {2331        ...sanitized,2332        id: crypto.randomUUID(),2333        createdAt: now,2334        modifiedAt: monotonicEntryTimestamp(),2335      };2336      entries.push(nextEntry);2337      added.push(nextEntry);2338    } catch {2339      // Skip invalid drafts silently — caller can see diff between input and output length2340    }2341  }23422343  if (added.length > 0) {2344    await persistEntries();2345  }23462347  return added;2348}23492350/**2351 * Restore a set of entries in full fidelity — preserves id, createdAt,2352 * modifiedAt, and every other field unlike `batchAddEntries` which2353 * assigns fresh identity. Used by restore paths where the backup is the2354 * authoritative source of truth. `mode` controls how entries already in2355 * the vault are treated.2356 */2357export async function restoreEntries(2358  incoming: VaultEntry[],2359  mode: "replace" | "merge"2360): Promise<{ added: number; updated: number; skipped: number }> {2361  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");23622363  // A replace with zero incoming entries is almost certainly a caller bug2364  // (e.g. an import that silently dropped everything). Refuse rather than2365  // wipe the vault.2366  if (mode === "replace" && incoming.length === 0) {2367    throw new Error("refuse to replace with empty entry set");2368  }23692370  let added = 0;2371  let updated = 0;2372  let skipped = 0;23732374  if (mode === "replace") {2375    entries = [];2376    for (const entry of incoming) {2377      const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2378      if (!normalized) {2379        skipped += 1;2380        continue;2381      }2382      entries.push(normalized);2383      if (normalized.deletedAt) {2384        tombstones.set(2385          normalized.id,2386          Math.max(tombstones.get(normalized.id) ?? 0, normalized.deletedAt),2387        );2388      } else {2389        tombstones.delete(normalized.id);2390      }2391      added += 1;2392    }2393  } else {2394    const byId = new Map<string, VaultEntry>();2395    for (const e of entries) byId.set(e.id, e);23962397    for (const entry of incoming) {2398      const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2399      if (!normalized) {2400        skipped += 1;2401        continue;2402      }2403      const existing = byId.get(normalized.id);2404      if (!existing) {2405        entries.push(normalized);2406        if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2407        else tombstones.delete(normalized.id);2408        added += 1;2409      } else if (normalized.modifiedAt > existing.modifiedAt) {2410        const idx = entries.findIndex((e) => e.id === existing.id);2411        if (idx !== -1) {2412          entries[idx] = normalized;2413          if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2414          else tombstones.delete(normalized.id);2415          updated += 1;2416        }2417      } else {2418        skipped += 1;2419      }2420    }2421  }24222423  await persistEntries("import");2424  return { added, updated, skipped };2425}24262427/**2428 * A Peach entry id is a UUID. A restored or imported file carries whatever id2429 * its author used, and no reader bounds it, so one oversized id would ride2430 * into every future sync frame and be rejected there — a permanent, opaque2431 * failure on both platforms, caused by data that was already local.2432 *2433 * The action is mint, not reject: this is the last point where an id is still2434 * ours to choose, so the worst outcome is one duplicate if the same vault is2435 * later restored beside a device still holding the old id. Rejecting would2436 * lose the user's import.2437 *2438 * Deliberately NOT inside sanitizeRestoredEntry, which applyMergedRemoteEntries2439 * also calls. Sync has to adopt a peer's id verbatim — that is the only thing2440 * keeping two devices agreed on which entry they are discussing — so reminting2441 * there would fork identity on every device, on every round.2442 */2443const ENTRY_ID_SHAPE = /^[A-Za-z0-9_-]{1,64}$/;24442445function naturalizeRestoredId(entry: VaultEntry | null): VaultEntry | null {2446  if (!entry || ENTRY_ID_SHAPE.test(entry.id)) return entry;2447  return { ...entry, id: crypto.randomUUID() };2448}24492450/**2451 * Validate + normalise a VaultEntry coming from a backup, import, or sync2452 * peer. MV-6: this is a strict field WHITELIST — `normalizeEntry` copies2453 * only known VaultEntry fields (unknown/attacker keys are dropped), and2454 * nested `passkey`/`canary` shapes are rebuilt field-by-field, never2455 * spread. Returns null for values the live vault shouldn't accept.2456 */2457function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {2458  if (!entry || typeof entry !== "object") return null;2459  const title = typeof entry.title === "string" ? entry.title.trim() : "";2460  if (!title) return null;2461  const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();2462  const now = Date.now();2463  const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;2464  const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;24652466  // normalizeEntry whitelists every known VaultEntry field before the entry2467  // reaches the live vault.2468  const normalized = normalizeEntry({2469    ...entry,2470    id,2471    title,2472    type: entry.type ?? "login",2473    createdAt,2474    modifiedAt,2475  });24762477  if (normalized.passkey) {2478    normalized.passkey = sanitizePasskey(normalized.passkey);2479  }2480  if (normalized.canary) {2481    normalized.canary = sanitizeCanary(normalized.canary);2482  }2483  // PCH-01-016: bound tags on the restore path too, so both import funnels agree.2484  normalized.tags = sanitizeTags(normalized.tags);24852486  // Login entries from backup must carry a password (or be passkey-only,2487  // in which case the passkey sub-object replaces the password requirement).2488  if (2489    normalized.type === "login" &&2490    !normalized.passkey &&2491    typeof normalized.password !== "string"2492  ) {2493    return null;2494  }2495  if (entry.passkey && !normalized.passkey) {2496    // Entry claimed a passkey but the shape didn't validate — refuse the2497    // whole entry rather than silently importing a credential-less husk.2498    return null;2499  }25002501  return normalized;2502}25032504/**2505 * Rebuild a PasskeyData object from untrusted input, field by field.2506 * Returns undefined when required fields are missing/mistyped — a rogue2507 * passkey credential must not activate via import (MV-6 attack scenario).2508 */2509function sanitizePasskey(pk: unknown): PasskeyData | undefined {2510  if (!pk || typeof pk !== "object") return undefined;2511  const r = pk as Record<string, unknown>;2512  if (2513    typeof r.rpId !== "string" || !r.rpId ||2514    typeof r.credentialId !== "string" || !r.credentialId ||2515    typeof r.publicKeyCose !== "string" ||2516    typeof r.userHandle !== "string" ||2517    typeof r.userName !== "string"2518  ) {2519    return undefined;2520  }2521  return {2522    rpId: r.rpId,2523    rpName: typeof r.rpName === "string" ? r.rpName : r.rpId,2524    credentialId: r.credentialId,2525    publicKeyCose: r.publicKeyCose,2526    privateKeyJwk:2527      r.privateKeyJwk && typeof r.privateKeyJwk === "object"2528        ? (r.privateKeyJwk as JsonWebKey)2529        : undefined,2530    userHandle: r.userHandle,2531    userName: r.userName,2532    userDisplayName:2533      typeof r.userDisplayName === "string" ? r.userDisplayName : r.userName,2534    algorithm: r.algorithm === -8 ? -8 : -7,2535    signCount: typeof r.signCount === "number" ? r.signCount : 0,2536    aaguid: typeof r.aaguid === "string" ? r.aaguid : "",2537    backupEligible: r.backupEligible === true,2538    backupState: r.backupState === true,2539    lastUsedAt: typeof r.lastUsedAt === "number" ? r.lastUsedAt : undefined,2540    browser: r.browser === "chrome" || r.browser === "firefox" ? r.browser : undefined,2541    transports: Array.isArray(r.transports)2542      ? r.transports.filter((t): t is string => typeof t === "string")2543      : undefined,2544    createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),2545  };2546}25472548/**2549 * Rebuild a Canary object from untrusted input. The webhook must be a2550 * well-formed HTTPS URL — a poisoned canary.webhookUrl is a standing2551 * exfiltration endpoint that the canary subsystem will POST entry titles2552 * to (MV-6 attack scenario). Invalid → the canary is dropped, not the2553 * entry. FIRE_CANARY_PING re-validates with the full SSRF guard at fire2554 * time (isAllowedCanaryWebhookUrl), so this import-time check is the2555 * outer of two gates.2556 */2557function sanitizeCanary(c: unknown): Canary | undefined {2558  if (!c || typeof c !== "object") return undefined;2559  const r = c as Record<string, unknown>;2560  if (typeof r.webhookUrl !== "string") return undefined;2561  let url: URL;2562  try {2563    url = new URL(r.webhookUrl);2564  } catch {2565    return undefined;2566  }2567  if (url.protocol !== "https:") return undefined;2568  return {2569    webhookUrl: url.toString(),2570    label: typeof r.label === "string" ? r.label : undefined,2571    lastPinged: typeof r.lastPinged === "number" ? r.lastPinged : undefined,2572    pingCount: typeof r.pingCount === "number" ? r.pingCount : undefined,2573  };2574}25752576/**2577 * MV-6 / PCH-01-016: tags from imported / batch-added entries are untrusted.2578 * Keep only non-empty strings, cap each at 256 chars, and cap the count at 2552579 * (the same per-entry ceiling the export codec enforces, peachPayload.ts).2580 * Non-array or all-invalid input collapses to undefined.2581 */2582function sanitizeTags(tags: unknown): string[] | undefined {2583  if (!Array.isArray(tags)) return undefined;2584  const out: string[] = [];2585  for (const t of tags) {2586    if (typeof t !== "string") continue;2587    const trimmed = t.trim();2588    if (!trimmed) continue;2589    out.push(trimmed.slice(0, 256));2590    if (out.length >= 255) break;2591  }2592  return out.length > 0 ? out : undefined;2593}25942595// Soft-deletes every non-deleted entry in one call. The literal string2596// argument is a tripwire against accidental calls — any caller that would2597// wipe the vault has to consciously type "REPLACE_ALL". Do not relax this2598// to a boolean.2599export async function clearVaultEntries(2600  confirmation: "REPLACE_ALL"2601): Promise<void> {2602  if (confirmation !== "REPLACE_ALL") {2603    throw new Error("clearVaultEntries requires explicit confirmation");2604  }2605  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");2606  for (const entry of entries) {2607    if (!entry.deletedAt) {2608      const stamp = monotonicEntryTimestamp(Math.max(2609        entry.modifiedAt,2610        tombstones.get(entry.id) ?? 0,2611      ));2612      entry.deletedAt = stamp;2613      entry.modifiedAt = stamp;2614      tombstones.set(entry.id, stamp);2615    }2616  }2617  await persistEntries();2618}26192620export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {2621  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");26222623  const sanitized = sanitizeEntryDraft(entry);2624  const now = Date.now();2625  const stamp = monotonicEntryTimestamp();2626  const nextEntry: VaultEntry = {2627    ...sanitized,2628    id: crypto.randomUUID(),2629    createdAt: now,2630    modifiedAt: stamp,2631    // Stamp passwordChangedAt at creation so age tracking is accurate from2632    // day one. Non-login entries carry the same stamp harmlessly.2633    passwordChangedAt: sanitized.password ? stamp : undefined,2634  };26352636  // Clone-and-replace so a failed persist rolls back the in-memory state2637  // (COR-008). Without this, a quota-full or storage error leaves the2638  // module-level `entries` ahead of what's actually on disk.2639  const rollback = entries;2640  entries = [...entries, nextEntry];2641  try {2642    await persistEntries();2643  } catch (err) {2644    entries = rollback;2645    throw err;2646  }26472648  // Fire-and-forget breach check (only for login entries if breach monitoring is enabled or not set)2649  if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password) {2650    const breachEpoch = vaultEpoch;2651    checkBreach(nextEntry.password).then(async (count) => {2652      if (count > 0 && breachEpoch === vaultEpoch && !vaultCreatesInFlight) {2653        const idx = entries.findIndex((e) => e.id === nextEntry.id);2654        if (idx !== -1) {2655          entries[idx] = { ...entries[idx], breach: count, modifiedAt: monotonicEntryTimestamp(entries[idx].modifiedAt) };2656          await persistEntries();2657        }2658      }2659    });2660  }26612662  fireSyncTrigger("vault_change");26632664  return nextEntry;2665}26662667/// Attach unambiguous account credentials without discarding other entry data.2668export async function consolidatePasskeyEntries(): Promise<void> {2669  if (!derivedKey || vaultCreatesInFlight) return;2670  const epoch = vaultEpoch;2671  const rollback = entries;2672  const next = entries.map((entry) => ({ ...entry }));2673  if (!mergePasskeyOnlyIntoLogins(next).merged) return;2674  const unchanged = next.map((entry) => ({ entry, modifiedAt: entry.modifiedAt }));2675  entries = next;2676  try {2677    await persistEntries();2678  } catch (err) {2679    // Other writers can replace entries or mutate a deletion in this array.2680    if (epoch === vaultEpoch && entries === next && entries.length === unchanged.length &&2681      unchanged.every(({ entry, modifiedAt }, index) => entries[index] === entry && entry.modifiedAt === modifiedAt)) {2682      entries = rollback;2683      buildDomainIndexSync(entries);2684    }2685    throw err;2686  }2687}26882689export async function updateEntry(2690  id: string,2691  patch: Partial<VaultEntry>2692): Promise<void> {2693  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");26942695  const idx = entries.findIndex((entry) => entry.id === id);2696  if (idx === -1 || entries[idx].deletedAt) {2697    throw new Error("entry_not_found");2698  }26992700  const current = entries[idx];2701  const sanitizedPatch = sanitizeEntryPatch(patch);2702  // Refresh passwordChangedAt only when the password value actually changes —2703  // a metadata-only update (title, tags, etc.) must not reset the age clock2704  // that drives the Pro health rotation recommendation.2705  const passwordChanged =2706    "password" in patch &&2707    typeof sanitizedPatch.password === "string" &&2708    sanitizedPatch.password !== current.password;2709  const stamp = monotonicEntryTimestamp(current.modifiedAt);2710  // When the password actually changes, push the outgoing one onto the history2711  // (newest first) so the user can reveal/copy/restore it later. We record the2712  // age it carried (passwordChangedAt, falling back to createdAt) rather than2713  // `now`, so the list reflects when each password was last in effect. Only2714  // capture a non-empty prior value — clearing a password leaves no secret to2715  // keep, and we skip an immediate exact duplicate (e.g. restore-then-restore)2716  // to avoid noise.2717  const priorPassword = current.password;2718  const shouldCapture =2719    passwordChanged &&2720    typeof priorPassword === "string" &&2721    priorPassword.length > 0 &&2722    current.passwordHistory?.[0]?.password !== priorPassword;2723  const nextHistory = shouldCapture2724    ? [2725        { password: priorPassword!, changedAt: current.passwordChangedAt ?? current.createdAt },2726        ...(current.passwordHistory ?? []),2727      ].slice(0, PASSWORD_HISTORY_MAX)2728    : current.passwordHistory;2729  entries[idx] = {2730    ...current,2731    ...sanitizedPatch,2732    modifiedAt: stamp,2733    ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),2734  };2735273627372738  // Card entries must retain their card number2739  if (entries[idx].type === "card" && !entries[idx].cardNumber) {2740    entries[idx] = current;2741    throw new Error("card number is required for card entries");2742  }27432744  // Roll the in-memory entry back to its pre-edit state if the disk write2745  // fails (e.g. storage quota). Without this the module-level `entries` array2746  // would hold an edit that never landed on disk, diverging from the vault2747  // until the next unlock silently reverts it (SEV-3-A). Mirrors addEntry.2748  try {2749    await persistEntries();2750  } catch (err) {2751    entries[idx] = current;2752    throw err;2753  }27542755  // Breach check when password changes: clear immediately so old breach doesn't linger,2756  // then async-check the new password and only re-set if it's also found.2757  if ("password" in patch && settings.breachMonitoring !== false && entries[idx].type === "login") {2758    entries[idx] = { ...entries[idx], breach: undefined };2759    await persistEntries();2760    const password = entries[idx].password;2761    if (password) {2762      checkBreach(password).then(async (count) => {2763        const i = entries.findIndex((e) => e.id === id);2764        if (i !== -1 && count > 0) {2765          entries[i] = { ...entries[i], breach: count, modifiedAt: monotonicEntryTimestamp(entries[i].modifiedAt) };2766          await persistEntries();2767        }2768      });2769    }2770  }27712772  fireSyncTrigger("vault_change");2773}27742775export async function deleteEntry(id: string): Promise<void> {2776  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");27772778  const entry = entries.find((item) => item.id === id);2779  if (!entry || entry.deletedAt) {2780    throw new Error("entry_not_found");2781  }27822783  // Tombstone timestamp must be strictly greater than the entry's last2784  // modification so the deletion wins LWW against any in-flight edit, even2785  // under clock skew (SEV-2-E).2786  const previousModifiedAt = entry.modifiedAt;2787  const previousTombstone = tombstones.get(id);2788  const stamp = monotonicEntryTimestamp(Math.max(entry.modifiedAt, previousTombstone ?? 0));2789  entry.deletedAt = stamp;2790  entry.modifiedAt = stamp;2791  tombstones.set(id, stamp);2792  // Roll the tombstone back if the disk write fails, so a quota error doesn't2793  // leave the entry deleted in memory but alive on disk (SEV-3-A).2794  try {2795    await persistEntries();2796  } catch (err) {2797    delete entry.deletedAt;2798    entry.modifiedAt = previousModifiedAt;2799    if (previousTombstone === undefined) tombstones.delete(id);2800    else tombstones.set(id, previousTombstone);2801    throw err;2802  }2803  fireSyncTrigger("vault_change");2804}28052806export function getDeletedEntries(): VaultEntry[] {2807  if (!derivedKey) return [];2808  return entries.filter((e) => !!e.deletedAt);2809}28102811/** Return all durable deletion timestamps, including purged full entries. */2812export function getTombstoneManifest(): Record<string, number> {2813  if (!derivedKey) return {};2814  return Object.fromEntries(tombstones);2815}28162817/**2818 * Returns the vault's monotonic version — the `peach_last_modified_at` value2819 * stamped on every user-initiated write. Remote (sync) writes do NOT advance2820 * this version so a sync round never cascades into a second outbound sync.2821 */2822export async function getVaultVersion(): Promise<number> {2823  try {2824    const raw = await chrome.storage.local.get("peach_last_modified_at");2825    const v = (raw as Record<string, unknown>).peach_last_modified_at;2826    if (typeof v === "number") return v;2827    if (typeof v === "string" && v !== "") {2828      const n = Number.parseInt(v, 10);2829      return Number.isFinite(n) ? n : 0;2830    }2831    return 0;2832  } catch {2833    return 0;2834  }2835}28362837/**2838 * Apply a batch of remote entries + tombstones from a sync peer.2839 * Last-write-wins by `modifiedAt`; a tombstone supersedes a live entry when2840 * `deletedAt > modifiedAt` on the local side. Mutates `entries` directly and2841 * persists with reason `sync_received` — does NOT fire the sync dispatcher, so2842 * applying a sync round cannot cascade into another outbound sync.2843 *2844 * `applied` counts entries that actually changed local state (new add,2845 * overwrite-by-newer, or new tombstone). `received` is the raw payload size2846 * the caller can surface in the sync result UI.2847 */2848export async function applyMergedRemoteEntries(2849  remoteEntries: VaultEntry[],2850  remoteTombstones: Record<string, number>,2851): Promise<{ received: number; applied: number; conflicts: number }> {2852  // DESIGN: last-write-wins is applied PER-ENTRY, not per-field. If two devices2853  // concurrently edit different fields of the same entry, the one with the2854  // newer modifiedAt wins the whole entry and the other device's field edits2855  // are dropped silently. This is the deliberate trade-off for a simple,2856  // conflict-free merge — per-field CRDT merge is out of scope. Guidance for2857  // users: edit a given entry on one device at a time.2858  if (!derivedKey || vaultCreatesInFlight || vaultMode === "decoy") throw new Error("vault_locked");28592860  const received = remoteEntries.length + Object.keys(remoteTombstones).length;2861  let applied = 0;2862  let conflicts = 0;28632864  const byId = new Map<string, VaultEntry>();2865  for (const e of entries) byId.set(e.id, e);28662867  const mergeNow = Date.now();2868  const remoteTombstoneTimes = new Map<string, number>();2869  for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2870    if (typeof rawDeletedAt === "number" && Number.isFinite(rawDeletedAt) && rawDeletedAt > 0) {2871      remoteTombstoneTimes.set(id, clampSyncTimestamp(rawDeletedAt, mergeNow));2872    }2873  }28742875  for (const remote of remoteEntries) {2876    const sanitized = sanitizeRestoredEntry(remote);2877    if (!sanitized) continue;2878    // HV-1a: a far-future remote modifiedAt must not permanently pin a2879    // malicious value against honest local edits. Clamp BEFORE any2880    // comparison against local timestamps.2881    sanitized.modifiedAt = clampSyncTimestamp(sanitized.modifiedAt, mergeNow);2882    if (typeof sanitized.deletedAt === "number") {2883      sanitized.deletedAt = clampSyncTimestamp(sanitized.deletedAt, mergeNow);2884    }2885    const remoteTombstoneTs = remoteTombstoneTimes.get(sanitized.id);2886    const localTombstoneTs = tombstones.get(sanitized.id);2887    const tombstoneTs = Math.max(remoteTombstoneTs ?? 0, localTombstoneTs ?? 0);2888    if (tombstoneTs > 0 && tombstoneTs >= sanitized.modifiedAt) {2889      continue;2890    }2891    const local = byId.get(sanitized.id);2892    if (!local) {2893      entries.push(sanitized);2894      byId.set(sanitized.id, sanitized);2895      tombstones.delete(sanitized.id);2896      applied += 1;2897    } else if (sanitized.modifiedAt > local.modifiedAt) {2898      const idx = entries.findIndex((e) => e.id === local.id);2899      if (idx !== -1) {2900        entries[idx] = sanitized;2901        byId.set(sanitized.id, sanitized);2902        tombstones.delete(sanitized.id);2903        applied += 1;2904        if (!local.deletedAt) conflicts += 1;2905      }2906    }2907  }29082909  for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {2910    if (typeof rawDeletedAt !== "number" || !Number.isFinite(rawDeletedAt) || rawDeletedAt <= 0) continue;2911    // HV-1a/1c: clamp the tombstone timestamp before every comparison.2912    const deletedAt = remoteTombstoneTimes.get(id)!;2913    const knownTombstone = tombstones.get(id);2914    if (knownTombstone !== undefined && knownTombstone >= deletedAt) continue;2915    const local = byId.get(id);2916    if (!local) {2917      tombstones.set(id, deletedAt);2918      applied += 1;2919      continue;2920    }2921    if (local.deletedAt && local.deletedAt >= deletedAt) continue;2922    if (deletedAt < local.modifiedAt) continue;2923    const idx = entries.findIndex((e) => e.id === id);2924    if (idx !== -1) {2925      entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };2926      tombstones.set(id, deletedAt);2927      applied += 1;2928    }2929  }29302931  if (applied > 0 && vaultMode === "real") {2932    await persistEntries("sync_received");2933    buildDomainIndexSync(entries);2934    // An open popup holds the entries it loaded at mount and polls nothing, so2935    // a background round (the relay listener responding to a peer's push, or the2936    // alarm-driven dial) otherwise lands silently and the user sees stale data2937    // until they reopen. Best-effort: no popup listening is the normal case.2938    try {2939      void chrome.runtime2940        .sendMessage({ type: "VAULT_ENTRIES_CHANGED" })2941        .catch(() => undefined);2942    } catch {2943      // messaging unavailable2944    }2945  }2946  return { received, applied, conflicts };2947}29482949export async function restoreEntry(id: string): Promise<void> {2950  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");2951  const entry = entries.find((e) => e.id === id && e.deletedAt);2952  if (!entry) throw new Error("deleted entry not found");2953  const previousDeletedAt = entry.deletedAt;2954  const previousModifiedAt = entry.modifiedAt;2955  const previousTombstone = tombstones.get(id);2956  delete entry.deletedAt;2957  entry.modifiedAt = monotonicEntryTimestamp(Math.max(2958    entry.modifiedAt,2959    previousTombstone ?? 0,2960  ));2961  tombstones.delete(id);2962  try {2963    await persistEntries();2964  } catch (err) {2965    entry.deletedAt = previousDeletedAt;2966    entry.modifiedAt = previousModifiedAt;2967    if (previousTombstone !== undefined) tombstones.set(id, previousTombstone);2968    throw err;2969  }2970  buildDomainIndexSync(entries);2971}29722973export async function purgeEntry(id: string): Promise<void> {2974  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");2975  const idx = entries.findIndex((e) => e.id === id && e.deletedAt);2976  if (idx === -1) throw new Error("deleted entry not found");2977  const entry = entries[idx]!;2978  tombstones.set(id, Math.max(tombstones.get(id) ?? 0, entry.deletedAt!));2979  entries.splice(idx, 1);2980  await persistEntries();2981}29822983/** Permanently delete entries whose deletedAt is older than retentionMs. 0 = keep forever. */2984export async function purgeExpiredTrash(retentionMs: number): Promise<number> {2985  if (!derivedKey || vaultCreatesInFlight || retentionMs === 0) return 0;2986  const cutoff = Date.now() - retentionMs;2987  const before = entries.length;2988  for (const entry of entries) {2989    if (entry.deletedAt && entry.deletedAt < cutoff) {2990      tombstones.set(entry.id, Math.max(tombstones.get(entry.id) ?? 0, entry.deletedAt));2991    }2992  }2993  entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));2994  const purged = before - entries.length;2995  if (purged > 0) await persistEntries();2996  return purged;2997}29982999export function queryDomain(domain: string): VaultEntry[] {3000  return domainIndex.get(domain) ?? [];3001}30023003export function getEntryById(id: string): VaultEntry | undefined {3004  return entries.find((entry) => entry.id === id && !entry.deletedAt);3005}30063007async function persistSlotA(3008  reason: VaultSnapshot["reason"] = "local_save",3009): Promise<StoredVault> {3010  if (!derivedKey) throw new Error("vault_locked");3011  const epoch = vaultEpoch;3012  const throwIfStale = () => {3013    if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3014  };30153016  const slotA = await loadSlot(SLOT_A);3017  throwIfStale();3018  if (!slotA) throw new Error("missing slot A");30193020  // Snapshot the about-to-be-overwritten state BEFORE we mutate disk. Failures3021  // are swallowed by takeVaultSnapshot — history must never block a save.3022  await takeVaultSnapshot(reason);3023  throwIfStale();30243025  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3026  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");3027  throwIfStale();30283029  // Preserve existing recovery escrow fields.3030  const nextSlotA: StoredVault = {3031    ...slotA,3032    nonce,3033    ciphertext,3034    tag,3035    // recovery_salt and recovery_wrapped_root_key are already set from loadSlot3036  };30373038  // Slot A (the real vault) is now committed. Wrap every later write so a3039  // mid-persist failure (e.g. a storage error after slot A landed) restores the3040  // prior slot A before rethrowing. Without this, a "failed" save that already3041  // wrote slot A leaves disk ahead of the in-memory rollback in addEntry/3042  // updateEntry/deleteEntry — the entry stays silently on disk and resurfaces3043  // as a duplicate on the next unlock (observed under storage-quota pressure).3044  let slotACommitted = false;3045  try {3046    throwIfStale();3047    await writeSlot(SLOT_A, nextSlotA);3048    slotACommitted = true;3049    throwIfStale();30503051    // When duress is not configured, keep slot B size-matched with slot A by3052    // regenerating its noise. When duress IS configured, leave slot B alone —3053    // we don't have the decoy key to re-encrypt it. This is a known trade-off.3054    if (!duressConfigured) {3055      throwIfStale();3056      await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3057      throwIfStale();3058    }3059    // Only advance the vault version for locally-originated writes. Entries3060    // applied from a sync peer ("sync_received") must NOT bump the counter —3061    // otherwise applying a remote round makes us look newer than the peer and3062    // triggers a redundant outbound sync, defeating the no-op optimisation3063    // and risking a ping-pong between two devices (SEV-2-C).3064    if (reason !== "sync_received") {3065      throwIfStale();3066      await stampLocalVaultMutation();3067      throwIfStale();3068    }3069  } catch (err) {3070    // Best-effort restore — the prior slot A is smaller-or-equal, so this write3071    // fits even when the failure was a quota overflow.3072    if (slotACommitted) await writeSlot(SLOT_A, slotA).catch(() => {});3073    if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3074    throw err;3075  }30763077  return nextSlotA;3078}30793080async function persistSlotB(): Promise<void> {3081  if (!derivedKey) throw new Error("vault_locked");30823083  const slotB = await loadSlot(SLOT_B);3084  if (!slotB) throw new Error("missing slot B");30853086  // Decoy plaintext always reports duressConfigured=false — the decoy user3087  // sees a clean slate. persistSlotB only runs in decoy mode, which only3088  // exists once duress is configured, so pad to the fixed duress ceiling to3089  // keep slot B's length equal to slot A's (audit MEDIUM — deniability).3090  const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);3091  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");30923093  await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });3094  // Symmetric with persistSlotA: if the version stamp fails after the decoy3095  // slot committed, restore the prior slot B so a failed decoy-mode save can't3096  // leave disk ahead of the in-memory rollback.3097  try {3098    await stampLocalVaultMutation();3099  } catch (err) {3100    await writeSlot(SLOT_B, slotB).catch(() => {});3101    throw err;3102  }3103}31043105async function persistEntries(3106  reason: VaultSnapshot["reason"] = "local_save",3107): Promise<void> {3108  if (vaultCreatesInFlight) throw new Error("vault_changed");3109  vaultWritesInFlight++;3110  try {3111  if (!derivedKey) throw new Error("vault_locked");31123113  // Reconcile direct soft-delete callers while restoring the previous map if3114  // storage rejects the save.3115  const previousTombstones = tombstones;3116  const pendingTombstones = new Map(tombstones);3117  tombstones = pendingTombstones;3118  reconcileTombstones();3119  try {3120    if (vaultMode === "decoy") {3121      await persistSlotB();3122    } else {3123      await persistSlotA(reason);3124    }3125  } catch (err) {3126    if (tombstones === pendingTombstones) tombstones = previousTombstones;3127    throw err;3128  }3129  buildDomainIndexSync(entries);3130  await refreshLockedSyncState();3131  } finally { vaultWritesInFlight--; }3132}31333134// PB-26-011: drop URLs whose parsed scheme is not http(s) at the storage3135// boundary. Schemeless values (e.g. "github.com") are inert and kept — they3136// pre-date this guard in existing data. Unparseable values are kept: the3137// reviewed render paths never execute them (favicons via _favicon/, domains3138// via tldts); this is defense-in-depth against future sinks.3139function allowHttpUrl(url: string | undefined): string {3140  const trimmed = url?.trim() ?? "";3141  if (!trimmed) return "";3142  try {3143    const parsed = new URL(trimmed);3144    if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return "";3145  } catch {3146    // No scheme to reject.3147  }3148  return trimmed;3149}31503151function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {3152  if (!Array.isArray(values)) return undefined;3153  const seen = new Set<string>();3154  const cleaned: string[] = [];3155  for (const value of values) {3156    const trimmed = typeof value === "string" ? value.trim() : "";3157    if (!trimmed) continue;3158    if (!allowHttpUrl(trimmed)) continue;3159    const key = trimmed.toLowerCase();3160    if (seen.has(key)) continue;3161    seen.add(key);3162    cleaned.push(trimmed);3163  }3164  return cleaned.length > 0 ? cleaned : undefined;3165}31663167function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {3168  const title = entry.title.trim();3169  const type: VaultEntry["type"] = entry.type ?? "login";31703171  if (!title) throw new Error("title is required");31723173  if (entry.passkey) {3174    const p = entry.passkey;3175    if (3176      !p.rpId ||3177      !p.credentialId ||3178      !p.publicKeyCose ||3179      !p.userHandle ||3180      !p.userName ||3181      (p.algorithm !== -7 && p.algorithm !== -8)3182    ) {3183      throw new Error("invalid passkey credential");3184    }3185  }3186  if (type === "card") {3187    if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {3188      throw new Error("cardholder name and card number are required");3189    }3190  }31913192  return {3193    type,3194    title,3195    username: type === "login" ? entry.username?.trim() ?? "" : undefined,3196    email: type === "login" ? entry.email?.trim() || undefined : undefined,3197    password: type === "login" ? entry.password : undefined,3198    url: type === "login" ? allowHttpUrl(entry.url) : undefined,3199    additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,3200    totp: type === "login" ? entry.totp?.trim() || undefined : undefined,3201    // PCH-01-019: preserve non-default TOTP params through batch-add/import so3202    // they are not silently stripped (they fall back to SHA-1/6/30 when absent).3203    totpAlgorithm: type === "login" ? entry.totpAlgorithm : undefined,3204    totpDigits: type === "login" ? entry.totpDigits : undefined,3205    totpPeriod: type === "login" ? entry.totpPeriod : undefined,3206    notes: entry.notes?.trim() || undefined,3207    breach: type === "login" ? entry.breach : undefined,3208    // PCH-01-016: the batch-add path was bypassing the MV-6 canary/tags3209    // whitelist applied on the RESTORE_ENTRIES path. Run both sanitizers here.3210    canary: type === "login" ? sanitizeCanary(entry.canary) : undefined,3211    tags: sanitizeTags(entry.tags),3212    passkey: entry.passkey,3213    cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,3214    cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,3215    expMonth: type === "card" ? entry.expMonth?.trim() : undefined,3216    expYear: type === "card" ? entry.expYear?.trim() : undefined,3217    cvc: type === "card" ? entry.cvc?.trim() : undefined,3218    cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,3219    network: type === "card" ? entry.network : undefined,3220    last4: type === "card" ? entry.last4?.trim() : undefined,3221  };3222}32233224function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {3225  const nextPatch: Partial<VaultEntry> = {};32263227  if ("type" in patch) {3228    nextPatch.type = patch.type;3229  }32303231  if ("title" in patch) {3232    const title = patch.title?.trim() ?? "";3233    if (!title) throw new Error("title is required");3234    nextPatch.title = title;3235  }32363237  if ("url" in patch) {3238    nextPatch.url = allowHttpUrl(patch.url);3239  }32403241  if ("additionalUrls" in patch) {3242    const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];3243    const seen = new Set<string>();3244    const cleaned: string[] = [];3245    for (const value of incoming) {3246      const trimmed = typeof value === "string" ? value.trim() : "";3247      if (!trimmed || !allowHttpUrl(trimmed)) continue;3248      const key = trimmed.toLowerCase();3249      if (seen.has(key)) continue;3250      seen.add(key);3251      cleaned.push(trimmed);3252    }3253    nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;3254  }32553256  if ("username" in patch) {3257    nextPatch.username = patch.username?.trim() ?? "";3258  }32593260  if ("email" in patch) {3261    nextPatch.email = patch.email?.trim() || undefined;3262  }32633264  if ("password" in patch) {3265    const password = patch.password ?? "";3266    // Allow clearing a password (e.g. on passkey-only entries)3267    nextPatch.password = password || undefined;3268  }32693270  if ("totp" in patch) {3271    nextPatch.totp = patch.totp?.trim() || undefined;3272  }32733274  if ("totpAlgorithm" in patch) {3275    nextPatch.totpAlgorithm = patch.totpAlgorithm;3276  }32773278  if ("totpDigits" in patch) {3279    nextPatch.totpDigits = patch.totpDigits;3280  }32813282  if ("totpPeriod" in patch) {3283    nextPatch.totpPeriod = patch.totpPeriod;3284  }32853286  if ("notes" in patch) {3287    nextPatch.notes = patch.notes?.trim() || undefined;3288  }32893290  if ("breach" in patch) {3291    nextPatch.breach = patch.breach;3292  }32933294  if ("canary" in patch) {3295    // PCH-02-001: route update patches through the same canary whitelist used3296    // by add/restore/sync. Invalid shapes drop the canary; `undefined` clears it.3297    nextPatch.canary = patch.canary ? sanitizeCanary(patch.canary) : undefined;3298  }32993300  if ("passkey" in patch) {3301    // A patch with `passkey: undefined` removes the credential from the entry3302    // (used by "remove passkey" without deleting the whole entry).3303    if (patch.passkey === undefined || patch.passkey === null) {3304      nextPatch.passkey = undefined;3305    } else {3306      const sanitized = sanitizePasskey(patch.passkey);3307      if (!sanitized) throw new Error("invalid passkey credential");3308      nextPatch.passkey = sanitized;3309    }3310  }33113312  if ("tags" in patch) {3313    // PCH-02-001: bound tags exactly like both import funnels.3314    nextPatch.tags = sanitizeTags(patch.tags);3315  }33163317  if ("cardholderName" in patch) {3318    nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;3319  }3320  if ("cardNumber" in patch) {3321    const n = patch.cardNumber ?? "";3322    nextPatch.cardNumber = n || undefined;3323  }3324  if ("expMonth" in patch) {3325    nextPatch.expMonth = patch.expMonth?.trim() || undefined;3326  }3327  if ("expYear" in patch) {3328    nextPatch.expYear = patch.expYear?.trim() || undefined;3329  }3330  if ("cvc" in patch) {3331    nextPatch.cvc = patch.cvc?.trim() || undefined;3332  }3333  if ("cardNickname" in patch) {3334    nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;3335  }3336  if ("network" in patch) {3337    nextPatch.network = patch.network;3338  }3339  if ("last4" in patch) {3340    nextPatch.last4 = patch.last4?.trim() || undefined;3341  }33423343  return nextPatch;3344}33453346function normalizeEntry(entry: VaultEntry): VaultEntry {3347  const base: VaultEntry = {3348    id: entry.id,3349    type: entry.type,3350    title: entry.title,3351    username: entry.username,3352    email: entry.email,3353    password: entry.password,3354    url: entry.url,3355    additionalUrls:3356      "additionalUrls" in entry && Array.isArray(entry.additionalUrls)3357        ? entry.additionalUrls3358        : undefined,3359    totp: entry.totp,3360    // PCH-01-019: carry TOTP params through the normalize/restore path too.3361    totpAlgorithm: entry.totpAlgorithm,3362    totpDigits: entry.totpDigits,3363    totpPeriod: entry.totpPeriod,3364    notes: entry.notes,3365    breach: entry.breach,3366    // Preserve the password-age clock across lock/unlock. Without this the3367    // field is dropped on every decode and the advanced-health "aged password"3368    // signal silently resets to createdAt on each unlock (SEV-2-A).3369    passwordChangedAt:3370      "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,3371    // Preserve past-password history across lock/unlock. normalizeEntry is a3372    // field whitelist, so an unlisted field is silently dropped on every decode3373    // (same class as the passwordChangedAt SEV-2-A above).3374    passwordHistory:3375      "passwordHistory" in entry && Array.isArray(entry.passwordHistory)3376        ? entry.passwordHistory3377        : undefined,3378    canary: entry.canary,3379    passkey: entry.passkey,3380    createdAt: entry.createdAt,3381    modifiedAt: entry.modifiedAt,3382    deletedAt: entry.deletedAt,3383    tags: entry.tags,3384    cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,3385    cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,3386    expMonth: "expMonth" in entry ? entry.expMonth : undefined,3387    expYear: "expYear" in entry ? entry.expYear : undefined,3388    cvc: "cvc" in entry ? entry.cvc : undefined,3389    cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,3390    network: "network" in entry ? entry.network : undefined,3391    last4: "last4" in entry ? entry.last4 : undefined,3392  };33933394  return base;3395}339633973398// ---------------------------------------------------------------------------3399// Deduplication3400// ---------------------------------------------------------------------------34013402function entryDupeKey(e: VaultEntry): string {3403  if (e.passkey) {3404    // Equal identities can still carry different passwords, notes or TOTP data.3405    const content = Object.fromEntries(Object.entries(e)3406      .filter(([key]) => key !== "id" && key !== "createdAt" && key !== "modifiedAt")3407      .sort(([a], [b]) => a.localeCompare(b)));3408    return `passkey|${e.passkey.rpId}|${e.passkey.credentialId}|${JSON.stringify(content)}`;3409  }3410  if (e.type === "note") return `note|${e.title.toLowerCase()}`;3411  return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;3412}34133414/** Returns the number of duplicate entries (those that would be removed). */3415export function countDuplicates(): number {3416  const best = new Map<string, VaultEntry>();3417  let dupeCount = 0;3418  for (const e of entries.filter((e) => !e.deletedAt)) {3419    const key = entryDupeKey(e);3420    const existing = best.get(key);3421    if (!existing) {3422      best.set(key, e);3423    } else {3424      dupeCount++;3425      // Keep the more recently modified one in the map3426      if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3427        best.set(key, e);3428      }3429    }3430  }3431  return dupeCount;3432}34333434/**3435 * Soft-deletes duplicate entries, keeping the most recently modified copy of3436 * each group. Returns the number of entries moved to trash.3437 */3438export async function deduplicateEntries(): Promise<number> {3439  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3440  // Dedup reshapes slot B permanently under the decoy key, which is3441  // forensically distinguishable from a freshly-seeded decoy vault. Refuse.3442  if (vaultMode === "decoy") {3443    throw new Error("deduplicate disabled in decoy mode");3444  }34453446  const best = new Map<string, VaultEntry>();3447  for (const e of entries.filter((en) => !en.deletedAt)) {3448    const key = entryDupeKey(e);3449    const existing = best.get(key);3450    if (!existing) {3451      best.set(key, e);3452    } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3453      best.set(key, e);3454    }3455  }34563457  const keepIds = new Set(Array.from(best.values()).map((e) => e.id));3458  let removed = 0;3459  entries = entries.map((e) => {3460    if (!e.deletedAt && !keepIds.has(e.id)) {3461      removed++;3462      const deletedAt = monotonicEntryTimestamp(Math.max(3463        e.modifiedAt,3464        tombstones.get(e.id) ?? 0,3465      ));3466      tombstones.set(e.id, deletedAt);3467      return { ...e, deletedAt };3468    }3469    return e;3470  });34713472  if (removed > 0) await persistEntries();3473  return removed;3474}34753476// ---------------------------------------------------------------------------3477// Vault history — snapshot BEFORE every vault write so the saved blob is3478// what is about to be lost, not what was just written. Capped at 5. The3479// stored blobs are AES-256-GCM ciphertext under the master password, so3480// history adds zero security surface.3481// ---------------------------------------------------------------------------34823483const HISTORY_KEY = "peach_vault_history";3484const HISTORY_MAX = 5;34853486// PCH-01-023: coarsen a live-entry count into a low-resolution bucket so the3487// plaintext snapshot field cannot reveal exact vault size or single-entry change3488// deltas. Buckets widen as the vault grows so absolute leakage stays roughly3489// proportional rather than exact.3490function bucketEntryCount(n: number): number {3491  if (n <= 0) return 0;3492  if (n <= 10) return 10;3493  if (n <= 25) return 25;3494  if (n <= 50) return 50;3495  if (n <= 100) return 100;3496  if (n <= 250) return 250;3497  if (n <= 500) return 500;3498  return Math.ceil(n / 500) * 500;3499}35003501/**3502 * Snapshot the CURRENT on-disk vault state into history. Call this BEFORE3503 * overwriting peach_vault_a so the saved blob captures the about-to-be-lost3504 * state. Identical-to-most-recent blobs are skipped to avoid filling history3505 * with no-op writes.3506 */3507export async function takeVaultSnapshot(3508  reason: VaultSnapshot["reason"],3509): Promise<void> {3510  if (recoveryInFlight || vaultCreatesInFlight) return;3511  // The history store is real-mode state by construction, so it must not be3512  // written from a decoy session either. The guard lives here rather than only3513  // at the call sites so the invariant survives a new caller (PB-26-915).3514  if (vaultMode === "decoy") return;3515  vaultWritesInFlight++;3516  try {3517    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);3518    const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];3519    const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];35203521    // Nothing to snapshot if the real slot doesn't exist yet (fresh install,3522    // pre-createVault). createVault skips snapshots intentionally — there is3523    // no prior state to preserve.3524    if (!slotA) return;35253526    const vault_a = JSON.stringify(slotA);3527    const vault_b = JSON.stringify(slotB ?? slotA);35283529    // Best-effort entry count: only meaningful when the in-memory state is3530    // unlocked AND in real mode. Decoy mode would leak the decoy entry3531    // count; locked mode has no entries to count. Both fall through to null.3532    // PCH-01-023: store a coarse bucket, not the exact count — chrome.storage3533    // .local sits next to the AES-GCM blobs in plaintext, so an exact count would3534    // leak vault size and per-write deltas (the metadata padding hides this).3535    let entryCount: number | null = null;3536    if (derivedKey && vaultMode === "real") {3537      try {3538        entryCount = bucketEntryCount(entries.filter((e) => !e.deletedAt).length);3539      } catch {3540        entryCount = null;3541      }3542    }35433544    const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];3545    const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)3546      ? existingRaw3547      : { snapshots: [] };35483549    // Deduplication: if the most recent snapshot has byte-identical blobs,3550    // skip — saves the same vault N times in a row would otherwise burn the3551    // entire history window with no recovery value.3552    const latest = history.snapshots[0];3553    if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {3554      return;3555    }35563557    const snapshot: VaultSnapshot = {3558      id: crypto.randomUUID(),3559      savedAt: Date.now(),3560      reason,3561      vault_a,3562      vault_b,3563      entryCount,3564    };35653566    history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);3567    if (recoveryInFlight || vaultCreatesInFlight) return;3568    await chrome.storage.local.set({ [HISTORY_KEY]: history });3569  } catch (err) {3570    // Non-fatal — history must never block a save. A failed snapshot just3571    // means the user loses one rung of the safety ladder for this write.3572    // M4/QUA-006: log so the failure is visible; if it looks like a quota3573    // problem, notify the popup so the user can prune history themselves.3574    console.warn('[Peach] takeVaultSnapshot failed:', err);3575    if (String(err).includes('QUOTA') || String(err).includes('quota')) {3576      try {3577        await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });3578      } catch {3579        // popup may be closed; surfaced via console.warn above3580      }3581    }3582  } finally { vaultWritesInFlight--; }3583}35843585/** Wipe all vault history. Called by Panic / DESTROY_VAULT. */3586export async function clearVaultHistory(): Promise<void> {3587  if (recoveryInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");3588  vaultWritesInFlight++;3589  try {3590    await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });3591  } catch {3592    // Non-fatal — DESTROY_VAULT also runs storage.local.clear().3593  } finally { vaultWritesInFlight--; }3594}35953596/** Read all snapshots, newest first, for the Settings vault history view. */3597export async function getVaultHistory(): Promise<VaultSnapshot[]> {3598  if (vaultMode === "decoy") return [];3599  const raw = await chrome.storage.local.get(HISTORY_KEY);3600  const value = (raw as Record<string, unknown>)[HISTORY_KEY];3601  return sanitizeHistory(value);3602}36033604/**3605 * Replace the on-disk vault with the chosen snapshot's blobs and lock the3606 * vault. The current state is itself snapshotted before replacement.3607 */3608export async function restoreVaultSnapshot(3609  snapshotId: string,3610): Promise<{ ok: true } | { ok: false; error: string }> {3611  if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "vault_changed" };3612  vaultReplacementInFlight = true;3613  try {3614    if (vaultMode === "decoy") return { ok: false, error: "vault_locked" };3615    const history = await getVaultHistory();3616    const snapshot = history.find((s) => s.id === snapshotId);3617    if (!snapshot) return { ok: false, error: "snapshot_not_found" };36183619    const restoredA = parseHistorySlot(snapshot.vault_a);3620    const restoredB = parseHistorySlot(snapshot.vault_b);3621    if (!restoredA || !restoredB) return { ok: false, error: "snapshot_corrupt" };36223623    await takeVaultSnapshot("restore");3624    const current = await chrome.storage.local.get([SLOT_A, SLOT_B]);3625    const previousA = (current as Record<string, unknown>)[SLOT_A];3626    const previousB = (current as Record<string, unknown>)[SLOT_B];3627    try {3628      if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };3629      await chrome.storage.local.set({ [SLOT_A]: restoredA, [SLOT_B]: restoredB });3630      await stampLocalVaultMutation();3631    } catch {3632      try {3633        await chrome.storage.local.set({ [SLOT_A]: previousA, [SLOT_B]: previousB });3634      } catch {3635        // Preserve the restore failure if storage cannot complete the rollback.3636      }3637      return { ok: false, error: "snapshot_corrupt" };3638    }36393640    await lock();3641    return { ok: true };3642  } finally {3643    vaultReplacementInFlight = false;3644  }3645}36463647/**3648 * Rotate the vault's sync identity by generating a FRESH ROOT KEY and3649 * re-wrapping everything under it (MV-8). Because every sync credential —3650 * vault_id, the Noise static keypair, the Ed25519 manifest signing key,3651 * and the per-entry envelope keys — derives from the root key, rotation3652 * makes a lost/stolen device's retained key material useless. All paired3653 * devices must re-pair afterwards.3654 *3655 * CONSEQUENCE THE UI MUST SURFACE: the 12 recovery words also derive from3656 * the root key, so rotation INVALIDATES the old recovery phrase. The flow3657 * sets peach_recovery_pending so the popup re-presents the new words for3658 * confirmation, same as the initial recovery-word confirmation path.3659 */3660export async function rotateSyncIdentity(): Promise<{ ok: boolean; error?: string }> {3661  if (vaultCreatesInFlight) throw new Error("vault_changed");3662  vaultWritesInFlight++;3663  try {3664  if (!derivedKey || vaultMode !== "real") {3665    return { ok: false, error: "vault_locked" };3666  }3667  const slotA = await loadSlot(SLOT_A);3668  if (!slotA) return { ok: false, error: "missing_slot_a" };36693670  // 1. Fresh root key + recovery escrow (new words).3671  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =3672    await generateAndWrapRootKey();36733674  // 2. Re-wrap the new root key under the current password-derived key.3675  const newRootKey = unhex(rawRootKey);3676  const recoveryVaultKey = await encrypt(newRootKey, hex(derivedKey), "recovery_vault_key_v1");3677  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, newRootKey);36783679  // 3. Snapshot, then single atomic slot write — both escrow wrappings of3680  //    the new root key land together (same transactional rule as3681  //    changePassword). Entries are untouched: they are sealed under the3682  //    password-derived key, not the root key.3683  await takeVaultSnapshot("local_save");3684  const nextSlotA: StoredVault = {3685    ...slotA,3686    recovery_vault_key: recoveryVaultKey,3687    recovery_salt: recoverySalt,3688    recovery_wrapped_root_key: wrappedRootKey,3689    recovery_nonce: wrappedNonce,3690    recovery_tag: wrappedTag,3691    ...pwRoot,3692  };3693  await writeSlot(SLOT_A, nextSlotA);36943695  // 4. Swap in memory only after disk committed.3696  if (rootKey) zeroKey(rootKey);3697  rootKey = newRootKey;36983699  // 4b. The identity's root wrap was encrypted under the dead root. Without3700  //     this the identity survives only until the unlock key also changes.3701  await notifyIdentityKeysRotated();37023703  // 5. Old peers' identities derive from the dead root key — drop them all,3704  // with their rendezvous secrets (PB-26-213: rotation clears the map, so3705  // there is nothing to rewrap under the new key).3706  await clearPairedDevices();3707  await clearPairSecrets();37083709  // 6. Force re-presentation of the NEW recovery words on next popup view.3710  await setRecoveryConfirmPending(); // same flag the create-vault flow uses37113712  await stampLocalVaultMutation();3713  return { ok: true };3714  } finally { vaultWritesInFlight--; }3715}37163717/**3718 * Change the master password. Re-encrypts slot A with a fresh salt + new3719 * derived key. Slot B (duress or noise) is left untouched when duress is3720 * configured — it uses an independent key derived from the duress password —3721 * and regenerated as noise when duress is not configured.3722 */3723export async function changePassword(3724  currentPassword: string,3725  newPassword: string3726): Promise<boolean> {3727  if (vaultCreatesInFlight) throw new Error("vault_changed");3728  vaultWritesInFlight++;3729  try {37303731  const epoch = vaultEpoch;3732  const stale = () => epoch !== vaultEpoch;3733  if (!derivedKey || vaultMode !== "real") return false;37343735  // Verify current password before allowing any change3736  const valid = await verifyMainPassword(currentPassword);3737  if (!valid) return false;37383739  const slotA = await loadSlot(SLOT_A);3740  if (!slotA) return false;3741  if (!rootKey) return false;37423743  // Derive fresh key from new password + new random salt3744  const newSalt = generateSalt();3745  const newKey = await deriveKey(newPassword, newSalt);3746  if (stale()) {3747    zeroKey(newKey);3748    return false;3749  }37503751  // Re-encrypt the in-memory entries with the new key3752  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3753  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");37543755  // Pre-wrap root key under the new derived key. Recovery fields wrap rootKey3756  // under recovery words and remain untouched — recovery phrase keeps working3757  // across password changes (H4/COR-002).3758  const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);37593760  const recoveryVaultKey = await encrypt(rootKey, hex(newKey), "recovery_vault_key_v1");3761  const finalSlotA: StoredVault = {3762    ...slotA,3763    recovery_vault_key: recoveryVaultKey,3764    salt: hex(newSalt),3765    nonce,3766    ciphertext,3767    tag,3768    ...pwRoot,3769  };37703771  // Snapshot the OLD-key blob before overwriting it. If the user later3772  // restores from this snapshot they will need the OLD password — the3773  // post-restore lock surfaces that immediately.3774  await takeVaultSnapshot("local_save");37753776  // Single atomic write: ciphertext, salt, and pw_root_* fields all land in3777  // one storage transaction. An SW kill before this point leaves the old3778  // slot intact; after this point everything tied to the new password is3779  // already on disk together (M6/COR-004).3780  await writeSlot(SLOT_A, finalSlotA);3781  if (stale()) {3782    zeroKey(newKey);3783    return false;3784  }37853786  // Swap the in-memory key synchronously before any further await. If we3787  // threw between the Slot A write and this swap, the next persistEntries()3788  // would overwrite Slot A with old-key ciphertext, locking the user out.3789  zeroKey(derivedKey);3790  derivedKey = newKey;37913792  // PCH-01-008: the MV3 session escrow still holds the OLD key. Without this,3793  // the next service-worker restore decrypts the new-key Slot A with the stale3794  // key, fails tryDecryptSlotResult, and silently drops the user to a lock3795  // screen. Re-escrow the new key so restore survives a password change.3796  if (stale()) {3797    await lock();3798    return false;3799  }3800  await saveSessionKey(newKey, "real", epoch);3801  if (stale()) return false;38023803  // The identity envelope holds one wrap per recovering key. Swapping the3804  // unlock key kills the local wrap, so re-wrap now or the next key swap3805  // orphans the identity -- and until then the old password still opens it.3806  await notifyIdentityKeysRotated();3807  if (stale()) return false;38083809  // Regenerate noise for slot B when duress is not in use. Runs after the3810  // key swap so a failure here is a disposable noise regeneration, not a3811  // lockout.3812  if (!duressConfigured) {3813    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3814  }3815  await clearPinUnlockStorage();3816  await stampLocalVaultMutation();38173818  return true;3819  } finally { vaultWritesInFlight--; }3820}