vault.ts

165.7 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  BreachScanStatus,28  Canary,29  ManualSummonRecord,30  PasskeyData,31  RecoveryResult,32  SavedIdentity,33  StoredVault,34  VaultEntry,35  VaultHistory,36  VaultSnapshot,37} from "../shared/types";38import { decrypt, encrypt, zeroKey } from "./aes";39import { clearAutoLock, touchAutoLock } from "./alarms";40import { setRecoveryConfirmPending, revokeRecoveryReveal } from "./recovery-pending";41import {42  clearPairSecrets,43  dropSessionCache,44  reconcilePairSecrets,45  setSessionAllowed,46} from "./pair-secrets";4748type EntryDraft = Omit<49  VaultEntry,50  "id" | "createdAt" | "modifiedAt" | "deletedAt"51>;5253// Slot-neutral storage keys (v1.4.24+). Both slots always exist; slot B54// either holds the decoy vault (when duress is configured) or random noise55// that looks identical at rest. No external indicator is stored — duress56// configuration is recorded only inside the encrypted payload of slot A.57const SLOT_A = "peach_vault_a";58const SLOT_B = "peach_vault_b";59export const SETTINGS_STORAGE_KEY = "peach_settings";6061// Plaintext is padded to the next multiple of this size before encryption.62// This coarsens ciphertext-length leakage into 1 KiB buckets.63const PAD_BLOCK = 1024;6465// How many past passwords to retain per entry. Generous enough to be useful as66// a recovery aid while bounding the secret material we hold (and the ciphertext67// growth) for an entry whose password is rotated frequently.68const PASSWORD_HISTORY_MAX = 50;6970// When duress is configured, BOTH slots are padded to this fixed ceiling so71// their ciphertext lengths are identical and cannot reveal that a hidden decoy72// vault exists (audit MEDIUM — plausible-deniability leak). 256 KiB comfortably73// holds a very large vault (thousands of entries incl. passkeys). The decoy74// slot can't be re-encrypted on every real-vault save (the real session has no75// decoy key), so a fixed ceiling — rather than size-matching on each write — is76// what keeps the two slots equal. A real vault whose plaintext exceeds this77// would grow past the ceiling and re-expose the bit; that is an extreme,78// documented edge well beyond normal use.79const DURESS_SLOT_SIZE = 262_144;8081let derivedKey: Uint8Array | null = null;82// 32-byte random root key, separate from the derivedKey used for vault encryption.83// The root key is wrapped (encrypted) under the recovery key derived from the84// 12-word phrase. When the user changes their password, only the wrapping changes;85// the root key and recovery words remain stable.86let rootKey: Uint8Array | null = null;87let recoveryInFlight = false;88let recoverySettled: Promise<void> = Promise.resolve();89let vaultRemovalsInFlight = 0;90let vaultRemovalEpoch = 0;91let vaultWritesInFlight = 0;92let vaultCreatesInFlight = 0;93let creationSettled: Promise<void> = Promise.resolve();94let vaultUnlocksInFlight = 0;95let vaultReplacementInFlight = false;96let entries: VaultEntry[] = [];97// Tombstones outlive their full entry records so a peer that was offline98// during a purge cannot reintroduce an old ciphertext envelope. This map is99// serialized only inside the encrypted vault payload.100let tombstones = new Map<string, number>();101let domainIndex: Map<string, VaultEntry[]> = new Map();102let vaultMode: "real" | "decoy" = "real";103// Cached post-unlock view of whether the real vault records that duress is104// configured. Only meaningful after a real-mode unlock; for decoy-mode unlock105// this stays false because we never see slot A's plaintext.106let duressConfigured = false;107108// Set to a corruption reason during the last unlock() attempt when both slots109// decrypted but failed schema validation. Consumed and cleared by110// consumeLastUnlockFailureReason() so messages.ts can surface vault_corrupted111// distinctly from wrong-password (M7/COR-007).112//113// NOTE: module-level state — if vault.ts is ever moved to a worker context,114// this must be replaced with a structured return value from unlock() or a115// postMessage channel. The signal is invisible across module-instance116// boundaries.117let lastUnlockFailureReason: string | null = null;118119export function consumeLastUnlockFailureReason(): string | null {120  const r = lastUnlockFailureReason;121  lastUnlockFailureReason = null;122  return r;123}124125// ---------------------------------------------------------------------------126// Settings (persisted inside the encrypted vault store as a sidecar key)127// ---------------------------------------------------------------------------128129export type TextSize = "small" | "medium" | "large";130131export interface VaultSettings {132  accentColor?: AccentColorName;133  theme?: "dark" | "light";134  autoLockMinutes?: number;135  clipboardClearSeconds?: number;136  lockOnClose?: boolean;137  breachMonitoring?: boolean;138  passkeyProviderEnabled?: boolean;139  trashRetentionDays?: number;140  manualSummonDomains?: Record<string, ManualSummonRecord>;141  manualSummonSalt?: string;142  declinedCardFingerprints?: string[];143144  /** Metadata is bounded because it remains outside the encrypted vault blob. */145  metadataVersion?: 1;146  /**147   * Text size scale for body copy and entry titles. Stops at "large" by148   * design — XL clips dense screens (Vault, Health) inside the fixed149   * 330×480 popup surface.150   */151  textSize?: TextSize;152  /**153   * When true, all entrance/exit transitions and ambient animations are154   * collapsed to instant. Honoured alongside the user's OS-level155   * `prefers-reduced-motion`.156   */157  reduceMotion?: boolean;158  /** Require an unlock after a worker restart before locked Sync resumes. */159  lockedSyncRequiresUnlock?: boolean;160  /** Whether this vault has a local PIN unlock wrapper configured. */161  pinEnabled?: boolean;162  /** Whether the lock screen should open on PIN instead of the password. */163  pinPreferred?: boolean;164  /**165   * User overrides for keyboard shortcuts. Keys are ShortcutAction names166   * (see src/shared/shortcuts.ts). Missing actions fall through to167   * DEFAULT_BINDINGS — `getActiveBindings(settings.shortcuts)` is the168   * canonical lookup. Storing only the deltas keeps the vault payload169   * small and lets default updates land for users who never rebind.170   */171  shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;172}173174interface StoredPinWrap {175  version: 1;176  salt: string;177  nonce: string;178  ciphertext: string;179  tag: string;180}181182const PIN_WRAP_STORAGE = "peach_pin_wrap";183const PIN_ATTEMPTS_STORAGE = "peach_pin_attempts";184const PIN_MIN_LENGTH = 4;185const PIN_MAX_LENGTH = 12;186const PIN_MAX_ATTEMPTS = 3;187188let settings: VaultSettings = {};189const CARD_DECLINE_MAX = 256;190/** Hex length of a keyed card-decline digest. Legacy records are 16 hex. */191const CARD_DECLINE_DIGEST_HEX = 32;192193async function metadataDigest(value: string, key: string): Promise<string> {194  const bytes = new TextEncoder().encode(`${key}:${value}`);195  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));196  return Array.from(digest.slice(0, 16)).map((byte) => byte.toString(16).padStart(2, "0")).join("");197}198199let inMemoryPinWrap: StoredPinWrap | null = null;200let inMemoryPinFailedAttempts = 0;201let sessionPinStorageFailed = false;202203export function getSettings(): VaultSettings {204  return settings;205}206207export async function ensureSettingsLoaded(): Promise<VaultSettings> {208  await loadSettings();209  return settings;210}211212export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {213  await loadSettings();214  // LV-7: cheap insurance against prototype pollution if a future caller ever215  // feeds parsed external JSON here (native spread keeps __proto__ an own-216  // property today, but Object.assign-style consumers and JSON revivers have217  // been burned before).218  // `manualSummonDomains`/`manualSummonSalt` are legacy plaintext recall that219  // only the adoption path may clear; an external patch must not write them.220  const safe = Object.fromEntries(221    Object.entries(patch).filter(222      ([k]) => ![223        "__proto__", "constructor", "prototype",224        "manualSummonDomains", "manualSummonSalt",225      ].includes(k),226    ),227  ) as Partial<VaultSettings>;228  settings = { ...settings, ...safe };229  await persistSettings();230}231232function isValidPin(pin: string): boolean {233  return new RegExp(`^\\d{${PIN_MIN_LENGTH},${PIN_MAX_LENGTH}}$`).test(pin);234}235236/** Set up a local PIN wrapper after proving the current master password. */237export async function setupPinUnlock(currentPassword: string, pin: string): Promise<boolean> {238  if (vaultCreatesInFlight) return false;239  vaultWritesInFlight++;240  try {241  if (!derivedKey || vaultMode !== "real" || !isValidPin(pin)) return false;242  if (!(await verifyMainPassword(currentPassword))) return false;243244  const salt = generateSalt();245  const pinKey = await deriveKey(pin, salt);246  try {247    const wrapped = await encrypt(pinKey, hex(derivedKey), "pin_wrap_v1");248    await savePinWrap({ version: 1, salt: hex(salt), ...wrapped });249    await updateSettings({ pinEnabled: true });250    return true;251  } finally {252    zeroKey(pinKey);253  }254  } finally { vaultWritesInFlight--; }255}256257async function clearPinUnlockStorage(): Promise<void> {258  inMemoryPinWrap = null;259  inMemoryPinFailedAttempts = 0;260  sessionPinStorageFailed = false;261  if (chrome.storage.session) {262    await chrome.storage.session.remove([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);263  }264  await updateSettings({ pinEnabled: false });265}266267/** Remove the PIN wrapper after proving the current master password. */268export async function disablePinUnlock(currentPassword: string): Promise<boolean> {269  if (vaultCreatesInFlight) return false;270  vaultWritesInFlight++;271  try {272  if (!derivedKey || vaultMode !== "real") return false;273  if (!(await verifyMainPassword(currentPassword))) return false;274  await clearPinUnlockStorage();275  return true;276  } finally { vaultWritesInFlight--; }277}278279/** Unlock the real vault from its locally stored PIN-wrapped derived key. */280export async function unlockWithPin(pin: string): Promise<boolean> {281  vaultUnlocksInFlight++;282  try {283  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;284  if (!isValidPin(pin)) return false;285  await loadSettings();286  if (!settings.pinEnabled) return false;287288  const { stored, failedAttempts } = await loadPinState();289  if (failedAttempts >= PIN_MAX_ATTEMPTS) return false;290  if (291    !stored ||292    stored.version !== 1 ||293    !stored.salt ||294    !stored.nonce ||295    !stored.ciphertext ||296    !stored.tag297  ) return false;298299  const pinKey = await deriveKey(pin, unhex(stored.salt));300  let unwrappedKey: Uint8Array | null = null;301  try {302    const masterKeyHex = await decrypt(303      pinKey,304      stored.nonce,305      stored.ciphertext,306      stored.tag,307      "pin_wrap_v1",308    );309    if (!/^[0-9a-f]{64}$/.test(masterKeyHex)) return false;310    unwrappedKey = unhex(masterKeyHex);311    const result = await unlockWithKey(masterKeyHex);312    if (!result.ok) return false;313    await resetPinFailedAttempts();314    return true;315  } catch {316    await recordPinFailure(failedAttempts + 1);317    return false;318  } finally {319    zeroKey(pinKey);320    if (unwrappedKey) zeroKey(unwrappedKey);321  }322  } finally { vaultUnlocksInFlight--; }323}324325async function savePinWrap(stored: StoredPinWrap): Promise<void> {326  inMemoryPinWrap = stored;327  inMemoryPinFailedAttempts = 0;328  sessionPinStorageFailed = !chrome.storage.session;329  if (!chrome.storage.session) return;330  try {331    await chrome.storage.session.set({ [PIN_WRAP_STORAGE]: stored, [PIN_ATTEMPTS_STORAGE]: 0 });332    sessionPinStorageFailed = false;333  } catch {334    // Firefox fallback: keep the wrapper only in this background context.335    sessionPinStorageFailed = true;336  }337}338339async function loadPinState(): Promise<{340  stored: StoredPinWrap | undefined;341  failedAttempts: number;342}> {343  if (!chrome.storage.session) {344    return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };345  }346  try {347    const result = await chrome.storage.session.get([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);348    return {349      stored: (result[PIN_WRAP_STORAGE] as StoredPinWrap | undefined) ??350        (sessionPinStorageFailed ? inMemoryPinWrap ?? undefined : undefined),351      failedAttempts: typeof result[PIN_ATTEMPTS_STORAGE] === "number"352        ? result[PIN_ATTEMPTS_STORAGE]353        : 0,354    };355  } catch {356    return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };357  }358}359360async function recordPinFailure(failedAttempts: number): Promise<void> {361  inMemoryPinFailedAttempts = Math.min(failedAttempts, PIN_MAX_ATTEMPTS);362  if (!chrome.storage.session) return;363  try {364    await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: inMemoryPinFailedAttempts });365  } catch { /* in-memory counter remains the fallback */ }366}367368async function resetPinFailedAttempts(): Promise<void> {369  inMemoryPinFailedAttempts = 0;370  if (!chrome.storage.session) return;371  try {372    await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: 0 });373  } catch { /* in-memory counter remains the fallback */ }374}375376export async function getPinUnlockStatus(): Promise<{377  configured: boolean;378  available: boolean;379  attemptsRemaining: number;380}> {381  await loadSettings();382  if (!settings.pinEnabled) {383    return { configured: false, available: false, attemptsRemaining: 0 };384  }385  const { stored, failedAttempts } = await loadPinState();386  const available = Boolean(stored) && failedAttempts < PIN_MAX_ATTEMPTS;387  return {388    configured: true,389    available,390    attemptsRemaining: stored ? Math.max(0, PIN_MAX_ATTEMPTS - failedAttempts) : 0,391  };392}393394async function persistSettings(): Promise<void> {395  try {396    await chrome.storage.local.set({397      [SETTINGS_STORAGE_KEY]: {398        // Legacy plaintext recall is carried through every settings write until399        // adoption commits the encrypted copy and clears it explicitly.400        ...settings,401        cardFingerprintSalt: undefined,402        declinedCardFingerprints: settings.declinedCardFingerprints ?? [],403        metadataVersion: 1,404      },405    });406  } catch (err) {407    throw mapStorageError(err);408  }409}410411function mapStorageError(err: unknown): Error {412  const message = err instanceof Error ? err.message : String(err);413  if (/QUOTA_BYTES|quota/i.test(message)) {414    return new Error("STORAGE_QUOTA_EXCEEDED");415  }416  return err instanceof Error ? err : new Error(message);417}418419async function loadSettings(): Promise<void> {420  const result = await chrome.storage.local.get(SETTINGS_STORAGE_KEY);421  settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};422}423424/** Drop the legacy plaintext recall only once its encrypted copy committed. */425async function clearLegacyManualSummonPlaintext(): Promise<void> {426  settings = { ...settings, manualSummonDomains: undefined, manualSummonSalt: undefined };427  await persistSettings();428}429430// ---------------------------------------------------------------------------431// Manual-summon recall (encrypted Browser-local state)432// ---------------------------------------------------------------------------433434// One storage key holds one sealed member per vault mode. The real member is435// sealed under the vault root key so it survives password changes; slot B has436// no root key, so the decoy member uses that session's decoy vault key. The437// distinct AAD contexts stop one mode from opening the other's member.438const RECALL_STORAGE = "peach_manual_summon_recall_v1";439const RECALL_REAL_AAD = "manual_summon_recall_v1";440const RECALL_DECOY_AAD = "manual_summon_recall_decoy_v1";441const RECALL_MAX_RECORDS = 256;442const RECALL_DOMAIN_MAX_BYTES = 253;443// Summon timestamps come from the device clock; anything further ahead than444// this is corrupt or forged data, not a real summon.445const RECALL_MAX_CLOCK_SKEW_MS = 5 * 60_000;446447interface SealedRecall {448  nonce: string;449  ciphertext: string;450  tag: string;451}452453interface StoredRecall {454  v: 1;455  real?: SealedRecall;456  decoy?: SealedRecall;457}458459let manualSummonRecall = new Map<string, ManualSummonRecord>();460let recallMutation: Promise<void> = Promise.resolve();461462function isValidRecallDomain(domain: unknown): domain is string {463  return typeof domain === "string" && domain.length > 0 &&464    new TextEncoder().encode(domain).length <= RECALL_DOMAIN_MAX_BYTES;465}466467function sanitizeSummonRecord(value: unknown, now: number): ManualSummonRecord | null {468  if (!value || typeof value !== "object") return null;469  const record = value as Record<string, unknown>;470  const firstSummonedAt = record.firstSummonedAt;471  const lastSummonedAt = record.lastSummonedAt;472  const latestAllowed = now + RECALL_MAX_CLOCK_SKEW_MS;473  for (const timestamp of [firstSummonedAt, lastSummonedAt]) {474    if (475      typeof timestamp !== "number" ||476      !Number.isSafeInteger(timestamp) ||477      timestamp < 0 ||478      timestamp > latestAllowed479    ) {480      return null;481    }482  }483  if (typeof record.summonCount !== "number" || !Number.isFinite(record.summonCount)) {484    return null;485  }486  return {487    firstSummonedAt: firstSummonedAt as number,488    lastSummonedAt: lastSummonedAt as number,489    // Only two aggression levels exist; anything past two is the same state.490    summonCount: Math.min(2, Math.max(1, Math.trunc(record.summonCount))),491  };492}493494function capManualSummonRecall(495  records: Map<string, ManualSummonRecord>,496): Map<string, ManualSummonRecord> {497  if (records.size <= RECALL_MAX_RECORDS) return records;498  const kept = new Map(records);499  while (kept.size > RECALL_MAX_RECORDS) {500    let oldestDomain: string | null = null;501    let oldestAt = Number.POSITIVE_INFINITY;502    for (const [domain, record] of kept) {503      if (record.lastSummonedAt < oldestAt) {504        oldestAt = record.lastSummonedAt;505        oldestDomain = domain;506      }507    }508    if (oldestDomain === null) break;509    kept.delete(oldestDomain);510  }511  return kept;512}513514function sanitizeManualSummonRecall(value: unknown): Map<string, ManualSummonRecord> {515  const records = new Map<string, ManualSummonRecord>();516  if (!value || typeof value !== "object" || Array.isArray(value)) return records;517  const now = Date.now();518  for (const [domain, raw] of Object.entries(value as Record<string, unknown>)) {519    if (!isValidRecallDomain(domain)) continue;520    const record = sanitizeSummonRecord(raw, now);521    if (record) records.set(domain, record);522  }523  return capManualSummonRecall(records);524}525526function readStoredRecall(value: unknown): StoredRecall {527  const stored: StoredRecall = { v: 1 };528  if (!value || typeof value !== "object" || Array.isArray(value)) return stored;529  for (const mode of ["real", "decoy"] as const) {530    const member = (value as Record<string, unknown>)[mode];531    if (!member || typeof member !== "object") continue;532    const sealed = member as Record<string, unknown>;533    if (534      typeof sealed.nonce === "string" &&535      typeof sealed.ciphertext === "string" &&536      typeof sealed.tag === "string"537    ) {538      stored[mode] = { nonce: sealed.nonce, ciphertext: sealed.ciphertext, tag: sealed.tag };539    }540  }541  return stored;542}543544function recallSealContext(): { key: Uint8Array; aad: string } | null {545  if (vaultMode === "decoy") {546    return derivedKey ? { key: derivedKey, aad: RECALL_DECOY_AAD } : null;547  }548  return rootKey ? { key: rootKey, aad: RECALL_REAL_AAD } : null;549}550551function serializeRecallMutation(run: () => Promise<void>): Promise<void> {552  const task = recallMutation.then(run, run);553  recallMutation = task.then(() => undefined, () => undefined);554  return task;555}556557async function readStoredRecallFromDisk(): Promise<StoredRecall> {558  const raw = await chrome.storage.local.get(RECALL_STORAGE);559  return readStoredRecall((raw as Record<string, unknown>)[RECALL_STORAGE]);560}561562// A lock zeroes the keys in place and a root rotation replaces the array, so563// the epoch and mode alone cannot prove a captured key still holds the bytes564// it was captured with.565function recallSealIsCurrent(566  epoch: number,567  mode: "real" | "decoy",568  sealKey: Uint8Array,569): boolean {570  return epoch === vaultEpoch && mode === vaultMode && recallSealContext()?.key === sealKey;571}572573async function loadManualSummonRecall(): Promise<void> {574  const epoch = vaultEpoch;575  const mode = vaultMode;576  const context = recallSealContext();577  manualSummonRecall = new Map();578  if (!context) return;579  let stored: StoredRecall;580  try {581    stored = await readStoredRecallFromDisk();582  } catch (error) {583    console.warn("[Peach] manual-summon recall read failed:", error);584    return;585  }586  if (epoch !== vaultEpoch || mode !== vaultMode) return;587  const member = stored[mode];588  if (!member) return;589  try {590    const plain = await decrypt(context.key, member.nonce, member.ciphertext, member.tag, context.aad);591    if (epoch !== vaultEpoch || mode !== vaultMode) return;592    manualSummonRecall = sanitizeManualSummonRecall(JSON.parse(plain));593  } catch {594    // Fail closed: leave the unreadable member on disk; the next successful595    // write in this mode replaces it.596    manualSummonRecall = new Map();597  }598}599600async function persistManualSummonRecall(): Promise<void> {601  const epoch = vaultEpoch;602  const mode = vaultMode;603  const context = recallSealContext();604  if (!derivedKey || !context) throw new Error("vault_locked");605  const sealKey = context.key;606  let stored: StoredRecall;607  try {608    stored = await readStoredRecallFromDisk();609  } catch (error) {610    throw mapStorageError(error);611  }612  // Merge the committed member first: an unlock still loading recall must not613  // let this write drop records it has not seen yet. The merge stays local so a614  // write that crosses a lock or a mode change publishes nothing.615  let records = manualSummonRecall;616  const existing = stored[mode];617  if (existing) {618    try {619      const plain = await decrypt(sealKey, existing.nonce, existing.ciphertext, existing.tag, context.aad);620      const merged = sanitizeManualSummonRecall(JSON.parse(plain));621      for (const [domain, record] of records) merged.set(domain, record);622      records = capManualSummonRecall(merged);623    } catch {624      // Fail closed on load, replace here: this session's records win.625    }626  }627  if (!recallSealIsCurrent(epoch, mode, sealKey)) throw new Error("vault_locked");628  const sealed = await encrypt(629    sealKey,630    JSON.stringify(Object.fromEntries(records)),631    context.aad,632  );633  if (!recallSealIsCurrent(epoch, mode, sealKey)) throw new Error("vault_locked");634  // Replace only this mode's member; the other mode's ciphertext stays intact.635  stored[mode] = sealed;636  try {637    await chrome.storage.local.set({ [RECALL_STORAGE]: stored });638  } catch (error) {639    throw mapStorageError(error);640  }641  // Committed: a lock that followed is not a failed summon, and the merged view642  // is published only into the session it still belongs to.643  if (recallSealIsCurrent(epoch, mode, sealKey)) manualSummonRecall = records;644}645646/**647 * Re-seal the real member from the retired root to the new one. Rotation calls648 * this inside the recall queue, so no queued write can still be encrypting with649 * the old key bytes when they are zeroed.650 */651async function rekeyManualSummonRecall(652  oldRootKey: Uint8Array,653  newRootKey: Uint8Array,654): Promise<void> {655  const epoch = vaultEpoch;656  const sealIsCurrent = (): boolean =>657    epoch === vaultEpoch && vaultMode === "real" && rootKey === oldRootKey;658  if (!sealIsCurrent()) throw new Error("vault_locked");659  const stored = await readStoredRecallFromDisk();660  let records = manualSummonRecall;661  const existing = stored.real;662  if (existing) {663    try {664      const plain = await decrypt(oldRootKey, existing.nonce, existing.ciphertext, existing.tag, RECALL_REAL_AAD);665      const merged = sanitizeManualSummonRecall(JSON.parse(plain));666      for (const [domain, record] of records) merged.set(domain, record);667      records = capManualSummonRecall(merged);668    } catch {669      // Fail closed on load, replace here: this session's records win.670    }671  }672  if (!existing && records.size === 0) return;673  if (!sealIsCurrent()) throw new Error("vault_locked");674  stored.real = await encrypt(675    newRootKey,676    JSON.stringify(Object.fromEntries(records)),677    RECALL_REAL_AAD,678  );679  if (!sealIsCurrent()) return;680  await chrome.storage.local.set({ [RECALL_STORAGE]: stored });681  if (sealIsCurrent()) manualSummonRecall = records;682}683684/**685 * Adopt recall left as plaintext in `peach_settings` by older builds. Only a686 * successful encrypted write authorises removing the plaintext copy.687 */688async function adoptLegacyManualSummonRecall(): Promise<void> {689  if (vaultMode !== "real" || !rootKey) return;690  const legacy = sanitizeManualSummonRecall(settings.manualSummonDomains);691  if (legacy.size === 0) return;692  const epoch = vaultEpoch;693  const previous = manualSummonRecall;694  const merged = new Map(legacy);695  for (const [domain, record] of previous) merged.set(domain, record);696  manualSummonRecall = capManualSummonRecall(merged);697  try {698    await persistManualSummonRecall();699  } catch (error) {700    if (epoch === vaultEpoch && vaultMode === "real") manualSummonRecall = previous;701    throw error;702  }703  await clearLegacyManualSummonPlaintext();704}705706async function restoreManualSummonRecall(): Promise<void> {707  try {708    await loadSettings();709  } catch (error) {710    console.warn("[Peach] manual-summon recall settings read failed:", error);711    return;712  }713  try {714    await serializeRecallMutation(async () => {715      await loadManualSummonRecall();716      await adoptLegacyManualSummonRecall();717    });718  } catch (error) {719    // Recall is a hint, never a reason to fail an unlock.720    console.warn("[Peach] manual-summon recall migration deferred:", error);721  }722}723724async function clearStoredManualSummonRecall(mode?: "real" | "decoy"): Promise<void> {725  if (mode === undefined) {726    manualSummonRecall = new Map();727    try {728      await chrome.storage.local.remove(RECALL_STORAGE);729    } catch (error) {730      console.warn("[Peach] manual-summon recall cleanup failed:", error);731    }732    return;733  }734  try {735    // Serialized with record writes: this is a read-modify-write of the shared736    // key and must not revert the other member to stale ciphertext.737    await serializeRecallMutation(async () => {738      const stored = await readStoredRecallFromDisk();739      if (!stored[mode]) return;740      delete stored[mode];741      if (stored.real || stored.decoy) {742        await chrome.storage.local.set({ [RECALL_STORAGE]: stored });743      } else {744        await chrome.storage.local.remove(RECALL_STORAGE);745      }746    });747  } catch (error) {748    console.warn("[Peach] manual-summon recall cleanup failed:", error);749  }750}751752/** This domain's recall record, if the current mode has one. */753export function getManualSummonRecord(domain: string): ManualSummonRecord | undefined {754  const recalled = manualSummonRecall.get(domain);755  if (recalled) return recalled;756  // Pre-migration plaintext is real-vault data; a decoy session must not see it.757  if (vaultMode !== "real" || !isValidRecallDomain(domain)) return undefined;758  return sanitizeSummonRecord(settings.manualSummonDomains?.[domain], Date.now()) ?? undefined;759}760761/** Record a manual summons for the caller's own domain and persist it. */762export async function recordManualSummon(domain: string): Promise<void> {763  if (!isValidRecallDomain(domain)) throw new Error("invalid_domain");764  vaultWritesInFlight++;765  try {766    const run = async (): Promise<void> => {767      if (!derivedKey || !recallSealContext()) throw new Error("vault_locked");768      const epoch = vaultEpoch;769      const mode = vaultMode;770      const previous = manualSummonRecall;771      const now = Date.now();772      const existing = previous.get(domain);773      const next = new Map(previous);774      next.set(domain, {775        firstSummonedAt: existing?.firstSummonedAt ?? now,776        summonCount: Math.min(2, (existing?.summonCount ?? 0) + 1),777        lastSummonedAt: now,778      });779      manualSummonRecall = capManualSummonRecall(next);780      try {781        await persistManualSummonRecall();782      } catch (error) {783        if (epoch === vaultEpoch && mode === vaultMode) manualSummonRecall = previous;784        throw error;785      }786    };787    // Serialize read-modify-write pairs so two quick summonses cannot lose one.788    await serializeRecallMutation(run);789  } finally {790    vaultWritesInFlight--;791  }792}793794// Fire-and-forget sync trigger after a committed vault write. A failure here795// must never fail the write that caused it.796function fireSyncTrigger(reason: "vault_change"): void {797  void Promise.resolve()798    .then(() => triggerSyncIfReachable({ reason }))799    .catch(() => {800      /* no sync runner registered, or nothing reachable — non-fatal */801    });802}803export function lockedSyncRequiresUnlock(): boolean {804  return settings.lockedSyncRequiresUnlock === true;805}806807let lockedSyncRefreshHook: (() => Promise<void>) | null = null;808let lockedSyncUnlockHook: (() => Promise<void>) | null = null;809let vaultLockHook: (() => void) | null = null;810let decoySyncTeardownHook: (() => void) | null = null;811export type IdentityHooks = {812  /** Drop the cached identity: the session is no longer a real unlocked one. */813  onSessionEnded: () => Promise<void>;814  /** Re-wrap the identity under the keys now in force, after a vault key swap. */815  onKeysRotated: () => Promise<void>;816  /** Promote a pre-vault identity once a vault exists, given the password that created it. */817  onVaultCreated: (password: string) => Promise<void>;818};819820let identityHooks: IdentityHooks | null = null;821822export function setIdentityHooks(hooks: IdentityHooks): void {823  identityHooks = hooks;824}825826async function notifyIdentitySessionEnded(): Promise<void> {827  await identityHooks?.onSessionEnded().catch((error) => {828    console.warn("[Peach] local identity cache clear failed:", error);829  });830}831832async function notifyIdentityKeysRotated(): Promise<void> {833  await identityHooks?.onKeysRotated().catch((error) => {834    console.warn("[Peach] local identity re-wrap failed:", error);835  });836}837838export type SealedBox = { nonce: string; ciphertext: string; tag: string };839export type IdentityKeyEnvelope = {840  root?: SealedBox;841  local?: SealedBox;842  pending?: SealedBox;843  pendingSalt?: string;844};845846export function setLockedSyncHooks(hooks: {847  refresh: () => Promise<void>;848  afterUnlock: () => Promise<void>;849  onLock?: () => void;850  onDecoy?: () => void;851}): void {852  lockedSyncRefreshHook = hooks.refresh;853  lockedSyncUnlockHook = hooks.afterUnlock;854  vaultLockHook = hooks.onLock ?? null;855  decoySyncTeardownHook = hooks.onDecoy ?? null;856}857858async function refreshLockedSyncState(): Promise<void> {859  if (vaultMode !== "real" || !rootKey || !lockedSyncRefreshHook) return;860  await lockedSyncRefreshHook().catch((error) => {861    console.warn("[Peach sync] locked spool refresh failed:", error);862  });863}864865// ---------------------------------------------------------------------------866// HIBP breach check (k-anonymity model)867// ---------------------------------------------------------------------------868869export async function checkBreach(password: string, signal?: AbortSignal): Promise<number | null> {870  const controller = new AbortController();871  let timeout: ReturnType<typeof setTimeout> | undefined;872  let onAbort: (() => void) | undefined;873  try {874    const unavailable = new Promise<null>((resolve) => {875      onAbort = () => { controller.abort(); resolve(null); };876      signal?.addEventListener("abort", onAbort, { once: true });877      timeout = setTimeout(onAbort, 8_000);878      if (signal?.aborted) onAbort();879    });880    const lookup = async (): Promise<number | null> => {881      // HIBP's range API requires SHA-1; only the five-character prefix leaves the device.882      const hash = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(password));883      if (controller.signal.aborted) return null;884      const hex = Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, "0")).join("").toUpperCase();885      const res = await fetch(`https://api.pwnedpasswords.com/range/${hex.slice(0, 5)}`, {886        headers: { "Add-Padding": "true" },887        signal: controller.signal,888      });889      if (!res.ok) return null;890      const text = await res.text();891      const lines = text.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");892      let count = 0;893      const seen = new Set<string>();894      for (const line of lines) {895        const match = /^([A-Fa-f0-9]{35}):([0-9]+)$/.exec(line);896        if (!match) return null;897        const suffix = match[1].toUpperCase();898        const value = Number(match[2]);899        if (!Number.isSafeInteger(value) || seen.has(suffix)) return null;900        seen.add(suffix);901        if (suffix === hex.slice(5)) count = value;902      }903      return count;904    };905    return await Promise.race([lookup(), unavailable]);906  } catch {907    return null;908  } finally {909    clearTimeout(timeout);910    if (onAbort) signal?.removeEventListener("abort", onAbort);911  }912}913914type BreachCredential = { id: string; password: string; epoch: number; key: Uint8Array };915const breachChecks = new Map<string, symbol>();916917async function checkEntryBreach(credential: BreachCredential, signal?: AbortSignal): Promise<"unknown" | "unapplied" | number> {918  const { id, password, epoch } = credential;919  const isCurrent = () => {920    const entry = entries.find((entry) => entry.id === id);921    return !signal?.aborted && epoch === vaultEpoch && credential.key === derivedKey && !vaultCreatesInFlight &&922      entry?.type === "login" && !entry.deletedAt && entry.password === password;923  };924  if (!isCurrent()) return "unapplied";925  const token = Symbol();926  breachChecks.set(id, token);927  try {928    const count = await checkBreach(password, signal);929    const idx = entries.findIndex((entry) => entry.id === id);930    const current = entries[idx];931    if (signal?.aborted || epoch !== vaultEpoch || credential.key !== derivedKey || vaultCreatesInFlight ||932      breachChecks.get(id) !== token || !current || current.deletedAt || current.type !== "login" || current.password !== password) return "unapplied";933    if (count === null) return "unknown";934    if ((current.breach ?? 0) === count) return count;935    const owner = entries;936    const next = { ...current, breach: count, modifiedAt: monotonicEntryTimestamp(current.modifiedAt) };937    entries[idx] = next;938    try {939      await persistEntries();940    } catch (error) {941      if (epoch === vaultEpoch && entries === owner && entries[idx] === next && !next.deletedAt) entries[idx] = current;942      throw error;943    }944    if (!isCurrent() || breachChecks.get(id) !== token) return "unapplied";945    fireSyncTrigger("vault_change");946    return count;947  } finally {948    if (breachChecks.get(id) === token) breachChecks.delete(id);949  }950}951952function checkEntryBreachDetached(credential: BreachCredential): void {953  void checkEntryBreach(credential).catch(() => {954    console.warn("[Peach] Could not save a breach check result");955  });956}957958function emptyBreachScan(state: BreachScanStatus["state"] = "idle"): BreachScanStatus {959  return { id: null, state, total: 0, scanned: 0, unknown: 0, unapplied: 0, breached: 0, cancelled: 0 };960}961962type BreachScan = {963  epoch: number;964  key: Uint8Array | null;965  status: BreachScanStatus;966  credentials: BreachCredential[];967  controller: AbortController;968};969let breachScan: BreachScan | null = null;970971function cancelBreachScan(): void {972  breachChecks.clear();973  const scan = breachScan;974  if (!scan) return;975  scan.controller.abort();976  scan.credentials.length = 0;977  scan.key = null;978  if (scan.status.state === "running") {979    scan.status.cancelled = scan.status.total - scan.status.scanned - scan.status.unknown - scan.status.unapplied;980    scan.status.state = "cancelled";981  }982}983984/// Returns aggregate progress for the current unlock session without credential data.985export function getBreachScanStatus(): BreachScanStatus {986  if (!derivedKey) return emptyBreachScan(breachScan ? "cancelled" : "idle");987  if (!breachScan || breachScan.epoch !== vaultEpoch || breachScan.key !== derivedKey) return emptyBreachScan();988  return { ...breachScan.status };989}990991/// Starts a single background scan, or returns the current scan if it is still running.992export function startBreachScan(): BreachScanStatus {993  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");994  if (breachScan?.status.state === "running" && breachScan.epoch === vaultEpoch && breachScan.key === derivedKey) return getBreachScanStatus();995  cancelBreachScan();996  const key = derivedKey;997  const credentials = entries.filter((entry) => !entry.deletedAt && entry.type === "login" && entry.password)998    .map((entry) => ({ id: entry.id, password: entry.password!, epoch: vaultEpoch, key }));999  const scan: BreachScan = {1000    epoch: vaultEpoch, key, credentials, controller: new AbortController(),1001    status: { ...emptyBreachScan(credentials.length ? "running" : "complete"), id: crypto.randomUUID(), total: credentials.length },1002  };1003  breachScan = scan;1004  void runBreachScan(scan);1005  return { ...scan.status };1006}10071008async function runBreachScan(scan: BreachScan): Promise<void> {1009  try {1010    while (scan.credentials.length) {1011      if (scan.epoch !== vaultEpoch || scan.key !== derivedKey || scan.controller.signal.aborted) break;1012      const credential = scan.credentials.shift()!;1013      let result: "unknown" | "unapplied" | number;1014      try { result = await checkEntryBreach(credential, scan.controller.signal); }1015      catch { result = "unknown"; console.warn("[Peach] Could not save a breach scan result"); }1016      if (scan.epoch !== vaultEpoch || scan.key !== derivedKey || scan.controller.signal.aborted) break;1017      if (result === "unknown") scan.status.unknown++;1018      else if (result === "unapplied") scan.status.unapplied++;1019      else { scan.status.scanned++; if (result > 0) scan.status.breached++; }1020      if (scan.credentials.length) {1021        await new Promise<void>((resolve) => {1022          const done = () => { clearTimeout(timer); scan.controller.signal.removeEventListener("abort", done); resolve(); };1023          const timer = setTimeout(done, 200);1024          scan.controller.signal.addEventListener("abort", done, { once: true });1025          if (scan.controller.signal.aborted) done();1026        });1027      }1028    }1029  } finally {1030    scan.credentials.length = 0;1031    if (scan.status.state === "running") {1032      if (scan.epoch !== vaultEpoch || scan.key !== derivedKey || scan.controller.signal.aborted) {1033        scan.status.cancelled = scan.status.total - scan.status.scanned - scan.status.unknown - scan.status.unapplied;1034        scan.status.state = "cancelled";1035      } else scan.status.state = "complete";1036    }1037  }1038}10391040export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {1041  // Unreachable from the message layer, which gates on isUnlocked first.1042  const key = await cardDeclineKey();1043  if (!key) return;1044  const fingerprint = await cardFingerprint(last4, expMonth, expYear);1045  await loadSettings();1046  settings = {1047    ...settings,1048    declinedCardFingerprints: [1049      // Legacy records predate the keyed digest and are silently dropped here:1050      // they are 16 hex characters rather than 32, and are no longer accepted.1051      ...(settings.declinedCardFingerprints ?? []).filter(1052        (stored) => stored.length === CARD_DECLINE_DIGEST_HEX,1053      ),1054      await metadataDigest(fingerprint, key),1055    ].slice(-CARD_DECLINE_MAX),1056  };1057  await persistSettings();1058}10591060export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {1061  await loadSettings();1062  const key = await cardDeclineKey();1063  if (!key) return false;1064  const fingerprint = await cardFingerprint(last4, expMonth, expYear);1065  const candidate = await metadataDigest(fingerprint, key);1066  return (settings.declinedCardFingerprints ?? []).some(1067    (stored) => stored.length === CARD_DECLINE_DIGEST_HEX && stored === candidate,1068  );1069}10701071/**1072 * Keying material for the declined-card digest, derived from the vault root1073 * key so it is available only while unlocked and never written to storage.1074 *1075 * PB-26-108: the previous scheme stored a random salt beside the records. A1076 * salt defeats precomputed tables, not an attacker holding the file — the1077 * candidate space here is ~10^4 last-four values x 12 months x a few years, so1078 * a stored salt left the card's last four and expiry recoverable offline in1079 * seconds. `peach_settings` is unencrypted and directly readable by a content1080 * script on Firefox, so the key has to live outside storage entirely.1081 */1082async function cardDeclineKey(): Promise<string | null> {1083  const root = getRootKeyHex();1084  if (!root) return null;1085  const digest = new Uint8Array(1086    await crypto.subtle.digest(1087      "SHA-256",1088      new TextEncoder().encode(`peach-card-decline-v1:${root}`),1089    ),1090  );1091  return hex(digest);1092}10931094async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {1095  const encoder = new TextEncoder();1096  const buf = await crypto.subtle.digest("SHA-256", encoder.encode(`${last4}|${expMonth}|${expYear}`));1097  return Array.from(new Uint8Array(buf).slice(0, 8))1098    .map((b) => b.toString(16).padStart(2, "0"))1099    .join("");1100}11011102function hex(buf: Uint8Array): string {1103  return Array.from(buf)1104    .map((b) => b.toString(16).padStart(2, "0"))1105    .join("");1106}11071108function unhex(s: string): Uint8Array {1109  const out = new Uint8Array(s.length / 2);1110  for (let i = 0; i < s.length; i += 2) {1111    out[i / 2] = parseInt(s.slice(i, i + 2), 16);1112  }1113  return out;1114}11151116// ---------------------------------------------------------------------------1117// Root key generation and recovery word wrapping1118// ---------------------------------------------------------------------------11191120/**1121 * Generate a random 32-byte root key and wrap it (AES-256-GCM) under a key1122 * derived from the recovery word material via HKDF-SHA256. The wrapped blob1123 * fields are stored in slot A alongside the password-wrapped ciphertext. The1124 * root key itself is kept in memory for the session so getRecoveryWords() can1125 * encode it without re-deriving.1126 *1127 * SECURITY MODEL (PCH-01-005): the recovery KEK is derived from the 12-word1128 * material, which encodes only rootKey[0..16] (recovery-words.ts). The KEK is thus1129 * derived from a PREFIX of the very plaintext it wraps, and effective recovery1130 * security is 128-bit (standard for a 12-word phrase), NOT 256-bit. This is safe —1131 * unwrapping requires the words, and the GCM ciphertext leaks nothing without them —1132 * but it is intentional, not an oversight. A future escrow version wanting 256-bit1133 * recovery must derive the words from INDEPENDENT entropy, not from the root key.1134 */1135async function generateAndWrapRootKey(): Promise<{1136  rawRootKey: string; // hex of the plaintext root key — caller stores in rootKey1137  recoverySalt: string;1138  wrappedRootKey: string;1139  wrappedNonce: string;1140  wrappedTag: string;1141}> {1142  const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));1143  try {11441145  // Derive the recovery key from the BIP39 words encoding of the root key.1146  const words = await rootKeyToWords(rootKeyBytes);1147  const wordMaterial = await wordsToRootKeyMaterial(words);1148  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));1149  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);11501151  // Wrap the root key with the recovery key using AES-256-GCM directly.1152  // We hex-encode rootKeyBytes so the plaintext is always valid UTF-8.1153  const nonce = crypto.getRandomValues(new Uint8Array(12));1154  const encoded = new TextEncoder().encode(hex(rootKeyBytes));1155  const raw = await crypto.subtle.encrypt(1156    {1157      name: "AES-GCM",1158      iv: nonce,1159      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,1160      tagLength: 128,1161    },1162    recoveryKey,1163    encoded1164  );1165  // WebCrypto returns ciphertext || auth tag concatenated; split them.1166  const rawU8 = new Uint8Array(raw);1167  const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));1168  const tag = hex(rawU8.slice(rawU8.length - 16));11691170  return {1171    rawRootKey: hex(rootKeyBytes),1172    recoverySalt: hex(recoverySalt),1173    wrappedRootKey: ciphertext,1174    wrappedNonce: hex(nonce),1175    wrappedTag: tag,1176  };1177  } finally { zeroKey(rootKeyBytes); }1178}11791180async function wrapExistingRootKeyForRecovery(rootKeyBytes: Uint8Array): Promise<{1181  recoverySalt: string;1182  wrappedRootKey: string;1183  wrappedNonce: string;1184  wrappedTag: string;1185}> {1186  if (rootKeyBytes.length !== 32) {1187    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");1188  }11891190  const words = await rootKeyToWords(rootKeyBytes);1191  const wordMaterial = await wordsToRootKeyMaterial(words);1192  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));1193  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);1194  const nonce = crypto.getRandomValues(new Uint8Array(12));1195  const encoded = new TextEncoder().encode(hex(rootKeyBytes));1196  const raw = await crypto.subtle.encrypt(1197    {1198      name: "AES-GCM",1199      iv: nonce,1200      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,1201      tagLength: 128,1202    },1203    recoveryKey,1204    encoded,1205  );1206  const rawU8 = new Uint8Array(raw);1207  return {1208    recoverySalt: hex(recoverySalt),1209    wrappedRootKey: hex(rawU8.slice(0, rawU8.length - 16)),1210    wrappedNonce: hex(nonce),1211    wrappedTag: hex(rawU8.slice(rawU8.length - 16)),1212  };1213}12141215/**1216 * Unwrap the root key using recovery words. Called during recovery flow when1217 * the user provides their 12-word phrase and a new password.1218 */1219async function unwrapRootKeyForRecovery(1220  wrappedRootKey: string,1221  wrappedNonce: string,1222  wrappedTag: string,1223  recoverySaltHex: string,1224  words: string[]1225): Promise<Uint8Array> {1226  const wordMaterial = await wordsToRootKeyMaterial(words);1227  const recoverySalt = unhex(recoverySaltHex);1228  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);12291230  // The root key bytes were hex-encoded before1231  // encryption so the ciphertext is valid UTF-8. We inline the AES-GCM decrypt1232  // here to avoid passing a CryptoKey to the string-based encrypt/decrypt helpers.1233  // Each component is stored separately in the vault slot; decode them individually1234  // so the nonce is always exactly the 12 bytes from wrappedNonce.1235  const nonceRaw = unhex(wrappedNonce);1236  const ciphertextRaw = unhex(wrappedRootKey);1237  const tagRaw = unhex(wrappedTag);1238  // Combine ciphertext and tag for AES-GCM (expects ciphertext||tag).1239  // Use explicit ArrayBuffer allocations to satisfy TS BufferSource constraints.1240  const nonceU8 = nonceRaw as unknown as Uint8Array<ArrayBuffer>;1241  const combined = new Uint8Array(ciphertextRaw.length + tagRaw.length);1242  combined.set(ciphertextRaw, 0);1243  combined.set(tagRaw, ciphertextRaw.length);1244  const raw = await crypto.subtle.decrypt(1245    { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },1246    recoveryKey,1247    combined1248  );1249  const decryptedHex = new TextDecoder().decode(raw);1250  const recovered = unhex(decryptedHex);1251  if (recovered.length !== 32) { zeroKey(recovered); throw new Error("invalid_recovery_words"); }1252  return recovered;1253}12541255/// Recover a locked real vault without publishing keys before its stored payload authenticates.1256export async function recoverWithWords(words: string[], newPassword: string): Promise<RecoveryResult> {1257  if (recoveryInFlight || derivedKey) throw new Error("recovery_requires_lock");1258  if (vaultWritesInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");1259  recoveryInFlight = true;1260  let settle!: () => void;1261  recoverySettled = new Promise<void>((resolve) => { settle = resolve; });1262  cancelBreachScan();1263  const epoch = ++vaultEpoch;1264  const check = () => {1265    if (epoch !== vaultEpoch || derivedKey) throw new Error("vault_locked");1266  };1267  let recoveredRoot: Uint8Array | null = null;1268  let oldKey: Uint8Array | null = null;1269  let newKey: Uint8Array | null = null;1270  let committed = false;1271  try {1272    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1273    check();1274    const slot = raw[SLOT_A] as StoredVault | undefined;1275    if (!slot) throw new Error("no_vault");1276    if (!slot.recovery_salt || !slot.recovery_wrapped_root_key) throw new Error("recovery_not_setup");1277    try {1278      recoveredRoot = await unwrapRootKeyForRecovery(slot.recovery_wrapped_root_key,1279        slot.recovery_nonce ?? "", slot.recovery_tag ?? "", slot.recovery_salt, words);1280    } catch {1281      throw new Error("invalid_recovery_words");1282    }1283    check();1284    if (!slot.recovery_vault_key) throw new Error("recovery_requires_password_unlock");1285    oldKey = await openSealedKey(recoveredRoot, slot.recovery_vault_key, "recovery_vault_key_v1");1286    check();1287    if (!oldKey) throw new Error("recovery_data_unavailable");1288    const result = await tryDecryptSlotResult(slot, oldKey, "slot_a_v1");1289    check();1290    if (result.status !== "ok") throw new Error("recovery_data_unavailable");1291    const payload = result.payload;1292    await loadSettings();1293    check();1294    const salt = generateSalt();1295    newKey = await deriveKey(newPassword, salt);1296    check();1297    // Preserve the authenticated plaintext, including fields unknown to this build.1298    const plaintext = await decrypt(oldKey, slot.nonce, slot.ciphertext, slot.tag, "slot_a_v1");1299    const encrypted = await encrypt(newKey, plaintext, "slot_a_v1");1300    const pwRoot = await wrapRootKeyForDerivedKey(newKey, recoveredRoot);1301    const recoveryVaultKey = await encrypt(recoveredRoot, hex(newKey), "recovery_vault_key_v1");1302    check();1303    const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1304    check();1305    if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");1306    const history = raw[HISTORY_KEY] as VaultHistory | undefined;1307    const snapshot: VaultSnapshot = {1308      id: crypto.randomUUID(), savedAt: Date.now(), reason: "local_save",1309      vault_a: JSON.stringify(slot), vault_b: JSON.stringify(raw[SLOT_B] ?? slot), entryCount: null,1310    };1311    const previousStamp = Number(raw.peach_last_modified_at);1312    const nextSlot: StoredVault = { ...slot, ...encrypted, ...pwRoot,1313      salt: hex(salt), recovery_vault_key: recoveryVaultKey };1314    // One storage transaction keeps the rollback snapshot and all new-key fields together.1315    await chrome.storage.local.set({1316      [SLOT_A]: nextSlot,1317      [HISTORY_KEY]: { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) },1318      peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previousStamp) ? previousStamp + 1 : 0)),1319    });1320    committed = true;1321    check();1322    cancelBreachScan();1323    derivedKey = newKey;1324    rootKey = recoveredRoot;1325    newKey = null;1326    recoveredRoot = null;1327    entries = payload.entries;1328    tombstones = payload.tombstones;1329    duressConfigured = payload.duressConfigured;1330    vaultMode = "real";1331    manualSummonRecall = new Map();1332    buildDomainIndexSync(entries);1333    await saveSessionKey(derivedKey, "real", epoch);1334    if (epoch !== vaultEpoch) throw new Error("vault_locked");1335    await identityHooks?.onKeysRotated();1336    if (epoch !== vaultEpoch) throw new Error("vault_locked");1337    await reconcilePairSecrets(rootKey);1338    if (epoch !== vaultEpoch) throw new Error("vault_locked");1339    await clearPinUnlockStorage();1340    if (epoch !== vaultEpoch) throw new Error("vault_locked");1341    await restoreManualSummonRecall();1342    if (epoch !== vaultEpoch) throw new Error("vault_locked");1343    touchAutoLock();1344    return { committed: true, unlocked: true };1345  } catch (error) {1346    if (committed) {1347      console.warn("[Peach] recovery password saved; unlock required:", error);1348      if (derivedKey && epoch === vaultEpoch) {1349        try { await lock(); }1350        catch (lockError) { console.warn("[Peach] recovery session cleanup failed:", lockError); }1351      }1352      return { committed: true, unlocked: false };1353    }1354    if (derivedKey && epoch === vaultEpoch) await lock();1355    throw error;1356  } finally {1357    if (oldKey) zeroKey(oldKey);1358    if (newKey) zeroKey(newKey);1359    if (recoveredRoot) zeroKey(recoveredRoot);1360    recoveryInFlight = false;1361    settle();1362  }1363}13641365/// Cancel recovery and finish its issued storage write before removing vault data.1366export async function withVaultRemoval<T>(remove: () => Promise<T>): Promise<T> {1367  vaultRemovalEpoch++;1368  vaultRemovalsInFlight++;1369  try {1370    await lock();1371    await recoverySettled;1372    await creationSettled;1373    return await remove();1374  } finally {1375    vaultRemovalsInFlight--;1376  }1377}13781379/**1380 * Recover the session root key by AES-GCM-decrypting the pw_root_* fields1381 * (a second wrapping of the root key under the password-derived key). This1382 * is what makes GET_RECOVERY_WORDS work across lock/unlock cycles without1383 * the user re-entering their recovery phrase: the same root key bytes —1384 * and therefore the same 12 words — survive every unlock.1385 *1386 * Returns null when the escrow is absent or decryption fails.1387 */1388async function deriveRootKeyFromDerivedKey(1389  derivedKeyBytes: Uint8Array,1390  slotA: StoredVault,1391): Promise<Uint8Array | null> {1392  if (!slotA.pw_root_ciphertext || !slotA.pw_root_nonce || !slotA.pw_root_tag) {1393    return null;1394  }1395  try {1396    const rootHex = await decrypt(1397      derivedKeyBytes,1398      slotA.pw_root_nonce,1399      slotA.pw_root_ciphertext,1400      slotA.pw_root_tag,1401      "pw_root_v1",1402    );1403    return unhex(rootHex);1404  } catch {1405    return null;1406  }1407}14081409export async function sealIdentityKeyUnderVault(ik: Uint8Array): Promise<IdentityKeyEnvelope> {1410  if (vaultMode !== "real" || !rootKey || !derivedKey) throw new Error("vault_locked");1411  // The root wrap survives password change and recovery-words re-key; the1412  // local wrap is available during normal unlock. Pending is only pre-vault.1413  const [root, local] = await Promise.all([1414    encrypt(rootKey, hex(ik), "peach-local-identity-ik-root-v1"),1415    encrypt(derivedKey, hex(ik), "peach-local-identity-ik-local-v1"),1416  ]);1417  return { root, local };1418}14191420export async function sealIdentityKeyPreVault(1421  password: string,1422  ik: Uint8Array,1423): Promise<IdentityKeyEnvelope> {1424  const salt = generateSalt();1425  const key = await deriveKey(password, salt);1426  try {1427    const pending = await encrypt(key, hex(ik), "peach-local-identity-ik-pending-v1");1428    return { pending, pendingSalt: hex(salt) };1429  } finally {1430    zeroKey(key);1431  }1432}14331434/**1435 * Open the identity key with any wrapping key that is currently available:1436 * the live vault-unlock key, then the vault root key, then the pre-vault1437 * password. Each attempt is awaited only after the previous one fails, so a1438 * successful early unwrap never leaves a later decrypt rejection unobserved,1439 * and the pre-vault Argon2id is not paid when a vault key already opens the1440 * envelope.1441 */1442export async function openIdentityKey(1443  env: IdentityKeyEnvelope,1444  password?: string,1445): Promise<Uint8Array | null> {1446  if (env.local && derivedKey) {1447    const ik = await openSealedKey(derivedKey, env.local, "peach-local-identity-ik-local-v1");1448    if (ik) return ik;1449  }1450  if (env.root && rootKey) {1451    const ik = await openSealedKey(rootKey, env.root, "peach-local-identity-ik-root-v1");1452    if (ik) return ik;1453  }1454  if (!env.pending || !env.pendingSalt || password === undefined) return null;1455  let key: Uint8Array;1456  try {1457    const salt = unhex(env.pendingSalt);1458    key = await deriveKey(password, salt);1459    salt.fill(0);1460  } catch {1461    return null;1462  }1463  try {1464    return await openSealedKey(key, env.pending, "peach-local-identity-ik-pending-v1");1465  } finally {1466    zeroKey(key);1467  }1468}14691470/** Decrypt a sealed 32-byte key; null for a wrong key, a bad shape, or corrupt bytes. */1471async function openSealedKey(1472  key: Uint8Array,1473  box: SealedBox,1474  info: string,1475): Promise<Uint8Array | null> {1476  try {1477    const value = unhex(await decrypt(key, box.nonce, box.ciphertext, box.tag, info));1478    if (value.length === 32) return value;1479    value.fill(0);1480    return null;1481  } catch {1482    return null;1483  }1484}14851486// AES-GCM-wrap rootKey under derivedKey for the pw_root_* fields. Returns the1487// hex-encoded ciphertext/nonce/tag triple ready to embed in StoredVault.1488async function wrapRootKeyForDerivedKey(1489  derivedKeyBytes: Uint8Array,1490  rootKeyBytes: Uint8Array,1491): Promise<{ pw_root_ciphertext: string; pw_root_nonce: string; pw_root_tag: string }> {1492  const { nonce, ciphertext, tag } = await encrypt(derivedKeyBytes, hex(rootKeyBytes), "pw_root_v1");1493  return {1494    pw_root_ciphertext: ciphertext,1495    pw_root_nonce: nonce,1496    pw_root_tag: tag,1497  };1498}14991500/** Returns the 12 recovery words for the current session's root key. */1501export async function getRecoveryWords(): Promise<string[]> {1502  if (!rootKey) {1503    throw new Error("recovery not set up");1504  }1505  return rootKeyToWords(rootKey);1506}15071508async function loadSlot(key: string): Promise<StoredVault | null> {1509  const result = await chrome.storage.local.get(key);1510  return (result as Record<string, StoredVault | undefined>)[key] ?? null;1511}15121513async function writeSlot(key: string, vault: StoredVault): Promise<void> {1514  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");1515  vaultWritesInFlight++;1516  try {1517    await chrome.storage.local.set({ [key]: vault });1518  } catch (err) {1519    throw mapStorageError(err);1520  } finally {1521    vaultWritesInFlight--;1522  }1523}15241525/**1526 * Roll back a vault that was created by [createVaultFromRootKey] but1527 * couldn't be paired (e.g. the subsequent license activation, identity1528 * derivation, or paired-device upsert failed). Without this, a failed1529 * receiver session leaves behind an empty vault — the user has to1530 * re-pair to get a working setup, but the empty vault sits in the way.1531 *1532 * The call is idempotent: removing keys that aren't there is a no-op.1533 */1534export async function rollbackAdoptedVault(): Promise<void> {1535  await withVaultRemoval(async () => {1536    try {1537      await chrome.storage.local.remove([1538        SLOT_A,1539        SLOT_B,1540        "peach_last_modified_at",1541        RECALL_STORAGE,1542      ]);1543    } catch (err) {1544      throw mapStorageError(err);1545    }1546  });1547}15481549async function commitCreatedVaultSlots(slotA: StoredVault, slotB: StoredVault): Promise<void> {1550  if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1551  vaultWritesInFlight++;1552  try {1553    const raw = await chrome.storage.local.get("peach_last_modified_at");1554    const previous = Number(1555      (raw as Record<string, unknown>).peach_last_modified_at,1556    );1557    const next = Math.max(1558      Date.now(),1559      Number.isFinite(previous) ? previous + 1 : 0,1560    );1561    try {1562      if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1563      await chrome.storage.local.set({1564        [SLOT_A]: slotA,1565        [SLOT_B]: slotB,1566        peach_last_modified_at: String(next),1567      });1568    } catch (err) {1569      throw mapStorageError(err);1570    }1571  } finally {1572    vaultWritesInFlight--;1573  }1574}15751576// Monotonic clock for per-entry modifiedAt / deletedAt timestamps. Guards the1577// sync layer's last-write-wins merge against wall-clock regressions (NTP step,1578// manual clock change, DST glitch): a backwards Date.now() must never produce1579// an entry timestamp that's <= the entry's existing modifiedAt, or a genuine1580// local edit would lose to a stale remote copy. The returned value is always1581// strictly greater than both the entry's current modifiedAt and the previous1582// call's result (SEV-2-E).1583let lastEntryTimestamp = 0;1584function monotonicEntryTimestamp(currentModifiedAt?: number): number {1585  const base = Math.max(1586    Date.now(),1587    (currentModifiedAt ?? 0) + 1,1588    lastEntryTimestamp + 1,1589  );1590  lastEntryTimestamp = base;1591  return base;1592}15931594async function stampLocalVaultMutation(): Promise<void> {1595  if (vaultCreatesInFlight) throw new Error("vault_changed");1596  const raw = await chrome.storage.local.get("peach_last_modified_at");1597  const previous = Number(1598    (raw as Record<string, unknown>).peach_last_modified_at,1599  );1600  const next = Math.max(1601    Date.now(),1602    Number.isFinite(previous) ? previous + 1 : 0,1603  );1604  if (vaultCreatesInFlight) throw new Error("vault_changed");1605  await chrome.storage.local.set({1606    peach_last_modified_at: String(next),1607  });1608}16091610// ---------------------------------------------------------------------------1611// Padding + noise helpers1612// ---------------------------------------------------------------------------16131614/**1615 * Pads the plaintext string with trailing spaces so that the encoded byte1616 * length is a multiple of PAD_BLOCK. JSON.parse tolerates trailing1617 * whitespace after a complete document, so the padding is transparent on1618 * decode. Ciphertext length equals plaintext length plus a 16-byte tag.1619 */1620function padPlaintext(json: string, minBytes = 0): string {1621  const encoded = new TextEncoder().encode(json);1622  const bucket = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);1623  // minBytes lets the duress path force a fixed ceiling so both slots match.1624  const target = Math.max(bucket, minBytes);1625  const padLen = target - encoded.length;1626  return json + " ".repeat(padLen);1627}16281629/**1630 * Produces a StoredVault-shaped record filled with CSPRNG bytes. The1631 * ciphertext length matches the given byte count. Because GCM ciphertext is1632 * pseudo-random, this blob is indistinguishable at rest from a real1633 * encrypted vault without the key.1634 *1635 * crypto.getRandomValues() caps each call at 65536 bytes (the Web Crypto1636 * spec hard limit). Chunk the fill so vaults larger than that — common once1637 * the user has dozens of entries or any passkey — don't throw.1638 */1639const CSPRNG_CHUNK = 65_536;16401641function fillRandom(buf: Uint8Array): Uint8Array {1642  for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {1643    const end = Math.min(offset + CSPRNG_CHUNK, buf.length);1644    const chunk = new Uint8Array(end - offset);1645    crypto.getRandomValues(chunk);1646    buf.set(chunk, offset);1647  }1648  return buf;1649}16501651function generateNoiseBlob(ciphertextBytes: number): StoredVault {1652  const salt = crypto.getRandomValues(new Uint8Array(16));1653  const nonce = crypto.getRandomValues(new Uint8Array(12));1654  const cipher = fillRandom(new Uint8Array(ciphertextBytes));1655  const tag = crypto.getRandomValues(new Uint8Array(16));1656  return {1657    version: 1,1658    salt: hex(salt),1659    nonce: hex(nonce),1660    ciphertext: hex(cipher),1661    tag: hex(tag),1662  };1663}16641665// ---------------------------------------------------------------------------1666// Encrypted plaintext envelope1667// ---------------------------------------------------------------------------16681669type VaultPayload = {1670  entries: VaultEntry[];1671  tombstones?: Record<string, number>;1672  duressConfigured?: boolean;1673};16741675type DecryptedPayload = {1676  entries: VaultEntry[];1677  tombstones: Map<string, number>;1678  duressConfigured: boolean;1679};16801681function encodePayload(entries: VaultEntry[], duress: boolean, minBytes = 0): string {1682  const envelope: VaultPayload = {1683    entries,1684    tombstones: Object.fromEntries(tombstones),1685    duressConfigured: duress,1686  };1687  return padPlaintext(JSON.stringify(envelope), minBytes);1688}16891690function decodeTombstones(raw: unknown, allEntries: VaultEntry[]): Map<string, number> {1691  const result = new Map<string, number>();1692  if (raw && typeof raw === "object" && !Array.isArray(raw)) {1693    for (const [id, timestamp] of Object.entries(raw as Record<string, unknown>)) {1694      if (typeof timestamp === "number" && Number.isFinite(timestamp) && timestamp > 0) {1695        result.set(id, timestamp);1696      }1697    }1698  }1699  // Older payloads had no ledger. Rebuild the durable portion from any1700  // soft-deleted entries before they are eligible for a later purge.1701  for (const entry of allEntries) {1702    if (typeof entry.deletedAt !== "number" || !Number.isFinite(entry.deletedAt) || entry.deletedAt <= 0) {1703      continue;1704    }1705    if ((result.get(entry.id) ?? 0) < entry.deletedAt) {1706      result.set(entry.id, entry.deletedAt);1707    }1708  }1709  return result;1710}17111712function reconcileTombstones(): void {1713  const byId = new Map(entries.map((entry) => [entry.id, entry]));1714  for (const [id] of tombstones) {1715    if (byId.has(id) && !byId.get(id)?.deletedAt) tombstones.delete(id);1716  }1717  for (const entry of entries) {1718    if (typeof entry.deletedAt === "number" && Number.isFinite(entry.deletedAt) && entry.deletedAt > 0) {1719      if ((tombstones.get(entry.id) ?? 0) < entry.deletedAt) {1720        tombstones.set(entry.id, entry.deletedAt);1721      }1722    }1723  }1724}17251726function decodePayload(plain: string): DecryptedPayload {1727  const parsed = JSON.parse(plain) as VaultPayload;1728  if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.entries)) {1729    throw new Error("invalid vault payload");1730  }1731  const normalized = parsed.entries.map(normalizeEntry);1732  return {1733    entries: normalized,1734    tombstones: decodeTombstones(parsed.tombstones, normalized),1735    duressConfigured: parsed.duressConfigured === true,1736  };1737}17381739// Keep ambiguous records intact: an RP or account can own several credentials.1740function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {1741  let merged = false;1742  const transferable = new Set(["id", "type", "title", "username", "url", "passkey", "createdAt", "modifiedAt", "totp", "totpAlgorithm", "totpDigits", "totpPeriod"]);1743  for (const source of entries.filter((entry) => !entry.deletedAt && entry.passkey)) {1744    const passkey = source.passkey!;1745    if (source.type !== "login" && source.type !== "passkey") continue;1746    if (!passkey.userName || (source.username && source.username !== passkey.userName)) continue;1747    if (Object.entries(source).some(([key, value]) => !transferable.has(key) && value !== undefined && value !== "")) continue;1748    const targets = entries.filter((entry) => {1749      if (entry.deletedAt || entry.passkey || entry.type !== "login" || entry.username !== passkey.userName) return false;1750      return [entry.url, ...(entry.additionalUrls ?? [])].some((url) => {1751        if (!url) return false;1752        try {1753          return new URL(url.includes("://") ? url : `https://${url}`).hostname === passkey.rpId;1754        } catch {1755          return false;1756        }1757      });1758    });1759    if (targets.length !== 1) continue;1760    const target = targets[0]!;1761    if (source.totp && target.totp && (source.totp !== target.totp || source.totpAlgorithm !== target.totpAlgorithm || source.totpDigits !== target.totpDigits || source.totpPeriod !== target.totpPeriod)) continue;1762    target.passkey = passkey;1763    if (source.totp && !target.totp) {1764      target.totp = source.totp;1765      target.totpAlgorithm = source.totpAlgorithm;1766      target.totpDigits = source.totpDigits;1767      target.totpPeriod = source.totpPeriod;1768    }1769    const stamp = monotonicEntryTimestamp(Math.max(source.modifiedAt, target.modifiedAt));1770    target.modifiedAt = stamp;1771    source.modifiedAt = stamp;1772    source.deletedAt = stamp;1773    merged = true;1774  }1775  return { merged };1776}17771778// Validates that a `StoredVault` record on disk has the field shape we expect1779// before treating an AES-GCM decrypt success as a clean unlock. AES-GCM only1780// authenticates the static VERSION_BYTE AAD, not the `version` field on the1781// outer record — a corrupted `version: 42` slot still decrypts cleanly. This1782// check surfaces that as `corrupted` (M7/COR-007) so the popup can offer a1783// history-restore path instead of falsely reporting "wrong password".1784function hasValidVaultSchema(v: unknown): v is StoredVault {1785  if (typeof v !== "object" || v === null) return false;1786  const r = v as Record<string, unknown>;1787  return (1788    r.version === 1 &&1789    typeof r.salt === "string" &&1790    typeof r.nonce === "string" &&1791    typeof r.ciphertext === "string" &&1792    typeof r.tag === "string"1793  );1794}1795const MAX_HISTORY_BLOB_BYTES = 1_024 * 1_024;17961797function hasValidHistorySlot(value: unknown): value is StoredVault {1798  if (!hasValidVaultSchema(value)) return false;1799  return /^[0-9a-f]{32}$/i.test(value.salt) &&1800    /^[0-9a-f]{24}$/i.test(value.nonce) &&1801    /^[0-9a-f]+$/i.test(value.ciphertext) &&1802    value.ciphertext.length % 2 === 0 &&1803    value.ciphertext.length / 2 <= MAX_HISTORY_BLOB_BYTES &&1804    /^[0-9a-f]{32}$/i.test(value.tag);1805}18061807function parseHistorySlot(value: string): StoredVault | null {1808  try {1809    const parsed: unknown = JSON.parse(value);1810    return hasValidHistorySlot(parsed) ? parsed : null;1811  } catch {1812    return null;1813  }1814}18151816function isHistoryRecord(value: unknown): value is VaultSnapshot {1817  if (typeof value !== "object" || value === null) return false;1818  const record = value as Record<string, unknown>;1819  return typeof record.id === "string" && record.id.length > 0 && record.id.length <= 128 &&1820    typeof record.savedAt === "number" && Number.isFinite(record.savedAt) &&1821    typeof record.reason === "string" &&1822    typeof record.vault_a === "string" && record.vault_a.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1823    typeof record.vault_b === "string" && record.vault_b.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1824    (record.entryCount === null || typeof record.entryCount === "number");1825}18261827function sanitizeHistory(value: unknown): VaultSnapshot[] {1828  if (typeof value !== "object" || value === null) return [];1829  if (!("snapshots" in value) || !Array.isArray(value.snapshots)) return [];1830  return value.snapshots.filter(isHistoryRecord).slice(0, HISTORY_MAX);1831}18321833export type TryDecryptResult =1834  | { status: "ok"; payload: DecryptedPayload }1835  | { status: "wrong_key" }1836  | { status: "corrupted"; reason: string };18371838// Exported solely for `unlockFromCodex` below, which needs to verify a1839// supplied passphrase against a slotA blob *without* committing anything to1840// storage. Keep this internal otherwise — callers crossing the messages.ts1841// boundary should always go through `unlock` / `verifyMainPassword` so the1842// constant-time invariants in Projects.md §3.4 are not bypassed.1843export async function tryDecryptSlot(1844  vault: StoredVault,1845  key: Uint8Array,1846  aadTag?: string,1847): Promise<DecryptedPayload | null> {1848  const res = await tryDecryptSlotResult(vault, key, aadTag);1849  return res.status === "ok" ? res.payload : null;1850}18511852export async function tryDecryptSlotResult(1853  vault: StoredVault,1854  key: Uint8Array,1855  aadTag?: string,1856): Promise<TryDecryptResult> {1857  if (!hasValidVaultSchema(vault)) {1858    return { status: "corrupted", reason: "invalid_slot_schema" };1859  }1860  let plain: string;1861  try {1862    plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);1863  } catch {1864    return { status: "wrong_key" };1865  }1866  try {1867    const parsed = JSON.parse(plain) as unknown;1868    if (typeof parsed !== "object" || parsed === null) {1869      return { status: "corrupted", reason: "invalid_payload_shape" };1870    }1871    if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {1872      return { status: "corrupted", reason: "invalid_payload_shape" };1873    }1874    return { status: "ok", payload: decodePayload(plain) };1875  } catch {1876    return { status: "corrupted", reason: "invalid_payload_json" };1877  }1878}18791880// ---------------------------------------------------------------------------1881// Core operations1882// ---------------------------------------------------------------------------18831884function buildDomainIndexSync(all: VaultEntry[]): void {1885  domainIndex = new Map();18861887  for (const entry of all) {1888    if (entry.deletedAt) continue;1889    if (entry.type === "note" || entry.type === "card") continue;18901891    // An entry can match multiple sites via `additionalUrls`. Index each1892    // hostname so `queryDomain` returns the entry regardless of which alias1893    // the user is currently visiting. Dedupe per-entry so a single entry1894    // never appears twice in one bucket.1895    const domains = new Set<string>();1896    const primary = extractDomain(entry.url ?? "");1897    if (primary) domains.add(primary);1898    for (const extra of entry.additionalUrls ?? []) {1899      const d = extractDomain(extra);1900      if (d) domains.add(d);1901    }1902    if (domains.size === 0) continue;19031904    for (const domain of domains) {1905      const bucket = domainIndex.get(domain) ?? [];1906      bucket.push(entry);1907      domainIndex.set(domain, bucket);1908    }1909  }1910}19111912export async function createVault(password: string, replacement?: "warned-import"): Promise<{ committed: true; unlocked: boolean }> {1913  if (replacement !== undefined && replacement !== "warned-import") throw new Error("invalid_payload");1914  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");1915  vaultCreatesInFlight++;1916  let settle!: () => void;1917  creationSettled = new Promise<void>((resolve) => { settle = resolve; });1918  let nextKey: Uint8Array | null = null;1919  let nextRoot: Uint8Array | null = null;1920  let committed = false;1921  let publishedEpoch: number | null = null;1922  const epoch = vaultEpoch;1923  const check = () => {1924    if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1925  };1926  try {1927    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1928    check();1929    const occupied = raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;1930    if (occupied && replacement !== "warned-import") throw new Error("vault_already_exists");1931    const salt = generateSalt();1932    nextKey = await deriveKey(password, salt);1933    check();1934    const recovery = await generateAndWrapRootKey();1935    nextRoot = unhex(recovery.rawRootKey);1936    check();1937    const encrypted = await encrypt(nextKey, encodePayload([], false, 0), "slot_a_v1");1938    const pwRoot = await wrapRootKeyForDerivedKey(nextKey, nextRoot);1939    const recoveryVaultKey = await encrypt(nextRoot, hex(nextKey), "recovery_vault_key_v1");1940    check();1941    const slotA: StoredVault = {1942      ...encrypted, ...pwRoot, version: 1, salt: hex(salt),1943      recovery_vault_key: recoveryVaultKey,1944      recovery_salt: recovery.recoverySalt,1945      recovery_wrapped_root_key: recovery.wrappedRootKey,1946      recovery_nonce: recovery.wrappedNonce,1947      recovery_tag: recovery.wrappedTag,1948    };1949    const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1950    check();1951    if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");1952    const previous = Number(raw.peach_last_modified_at);1953    const update: Record<string, unknown> = {1954      [SLOT_A]: slotA, [SLOT_B]: generateNoiseBlob(encrypted.ciphertext.length / 2),1955      peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previous) ? previous + 1 : 0)),1956    };1957    if (occupied) {1958      const history = raw[HISTORY_KEY] as VaultHistory | undefined;1959      const snapshot: VaultSnapshot = {1960        id: crypto.randomUUID(), savedAt: Date.now(), reason: "restore", entryCount: null,1961        vault_a: JSON.stringify(raw[SLOT_A] ?? null), vault_b: JSON.stringify(raw[SLOT_B] ?? null),1962      };1963      update[HISTORY_KEY] = { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) };1964    }1965    try { await chrome.storage.local.set(update); }1966    catch (error) { throw mapStorageError(error); }1967    committed = true;1968    if (epoch !== vaultEpoch || vaultRemovalsInFlight) return { committed: true, unlocked: false };1969    const previousKey = derivedKey;1970    const previousRoot = rootKey;1971    cancelBreachScan();1972    publishedEpoch = ++vaultEpoch;1973    derivedKey = nextKey;1974    rootKey = nextRoot;1975    nextKey = null;1976    nextRoot = null;1977    entries = [];1978    tombstones = new Map();1979    vaultMode = "real";1980    manualSummonRecall = new Map();1981    duressConfigured = false;1982    buildDomainIndexSync(entries);1983    if (previousKey) zeroKey(previousKey);1984    if (previousRoot) zeroKey(previousRoot);1985    await clearSessionKey();1986    if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1987    await identityHooks?.onVaultCreated(password).catch((error) => {1988      console.warn("[Peach] local identity promotion failed:", error);1989    });1990    if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1991    // A newly created vault owns a fresh root and a fresh slot B, so any1992    // recalled member sealed under the old vault is unreachable by design.1993    await clearStoredManualSummonRecall();1994    await restoreManualSummonRecall();1995    if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1996    touchAutoLock();1997    return { committed: true, unlocked: true };1998  } catch (error) {1999    if (!committed) throw error;2000    console.warn("[Peach] vault saved; unlock required:", error);2001    if (publishedEpoch === vaultEpoch) {2002      await lock().catch((lockError) => console.warn("[Peach] creation session cleanup failed:", lockError));2003    }2004    return { committed: true, unlocked: false };2005  } finally {2006    if (nextKey) zeroKey(nextKey);2007    if (nextRoot) zeroKey(nextRoot);2008    vaultCreatesInFlight--;2009    settle();2010  }2011}20122013/**2014 * Creates a local vault from an existing vault root key received through the2015 * SAS-gated adoption protocol. The password is local to this device; it wraps2016 * the adopted root key at rest and does not need to match the source device.2017 */2018export async function createVaultFromRootKey(2019  password: string,2020  rootKeyHex: string,2021): Promise<{ vaultId: string }> {2022  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");2023  if (typeof password !== "string" || password.length === 0) {2024    throw new Error("ADOPT_INVALID_PASSWORD");2025  }2026  if (typeof rootKeyHex !== "string" || !/^[0-9a-f]{64}$/.test(rootKeyHex)) {2027    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars");2028  }20292030  if (vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");2031  const rootKeyBytes = unhex(rootKeyHex);2032  if (rootKeyBytes.length !== 32) {2033    rootKeyBytes.fill(0);2034    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");2035  }20362037  vaultCreatesInFlight++;2038  let settle!: () => void;2039  creationSettled = new Promise<void>((resolve) => { settle = resolve; });2040  const epoch = vaultEpoch;2041  let nextDerivedKey: Uint8Array | null = null;2042  let sessionRootKey: Uint8Array | null = null;2043  let committed = false;2044  try {2045    if (await hasVault()) {2046      throw new Error("ADOPT_VAULT_ALREADY_EXISTS");2047    }20482049    const nextEntries: VaultEntry[] = [];2050    const nextDuressConfigured = false;2051    const vaultId = await computeVaultId(rootKeyBytes);2052    const salt = generateSalt();2053    nextDerivedKey = await deriveKey(password, salt);2054    const recovery = await wrapExistingRootKeyForRecovery(rootKeyBytes);20552056    sessionRootKey = new Uint8Array(rootKeyBytes);2057    const plaintext = encodePayload(nextEntries, nextDuressConfigured, 0);2058    const { nonce, ciphertext, tag } = await encrypt(nextDerivedKey, plaintext, "slot_a_v1");2059    const pwRoot = await wrapRootKeyForDerivedKey(nextDerivedKey, sessionRootKey);2060    const slotA: StoredVault = {2061      recovery_vault_key: await encrypt(sessionRootKey, hex(nextDerivedKey), "recovery_vault_key_v1"),2062      version: 1,2063      salt: hex(salt),2064      nonce,2065      ciphertext,2066      tag,2067      recovery_salt: recovery.recoverySalt,2068      recovery_wrapped_root_key: recovery.wrappedRootKey,2069      recovery_nonce: recovery.wrappedNonce,2070      recovery_tag: recovery.wrappedTag,2071      ...pwRoot,2072    };2073    const slotB = generateNoiseBlob(ciphertext.length / 2);2074    if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");2075    await commitCreatedVaultSlots(slotA, slotB);2076    committed = true;2077    if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");2078    cancelBreachScan();2079    vaultEpoch++;20802081    const previousDerivedKey = derivedKey;2082    const previousRootKey = rootKey;2083    derivedKey = nextDerivedKey;2084    rootKey = sessionRootKey;2085    nextDerivedKey = null;2086    sessionRootKey = null;2087    entries = nextEntries;2088    tombstones = new Map();2089    vaultMode = "real";2090    manualSummonRecall = new Map();2091    duressConfigured = nextDuressConfigured;2092    buildDomainIndexSync(entries);2093    if (previousDerivedKey && previousDerivedKey !== derivedKey) zeroKey(previousDerivedKey);2094    if (previousRootKey && previousRootKey !== rootKey) previousRootKey.fill(0);2095    touchAutoLock();20962097    // The receiver's identity was minted before this vault existed (adoption v22098    // needs it in its first frame), so re-seal it under the vault keys now.2099    await identityHooks?.onVaultCreated(password).catch((error) => {2100      console.warn("[Peach] local identity promotion failed:", error);2101    });2102    await clearStoredManualSummonRecall();2103    await restoreManualSummonRecall();21042105    return { vaultId };2106  } catch (error) {2107    if (committed) {2108      // Removal cannot use withVaultRemoval while this operation owns creationSettled.2109      try { await lock(); }2110      finally { await chrome.storage.local.remove([SLOT_A, SLOT_B, RECALL_STORAGE, "peach_last_modified_at"]); }2111    }2112    throw error;2113  } finally {2114    vaultCreatesInFlight--;2115    settle();2116    rootKeyBytes.fill(0);2117    if (nextDerivedKey) zeroKey(nextDerivedKey);2118    if (sessionRootKey) sessionRootKey.fill(0);2119  }2120}21212122export async function hasVault(): Promise<boolean> {2123  const raw = await chrome.storage.local.get([SLOT_A, SLOT_B]);2124  return raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;2125}21262127/**2128 * Returns whether the real vault has recorded that a duress passphrase is2129 * configured. Reliable only after a real-mode unlock — before unlock or in2130 * decoy mode, returns false because we cannot read slot A's plaintext.2131 */2132export async function isDuressEnabled(): Promise<boolean> {2133  return vaultMode === "real" && duressConfigured;2134}21352136export async function setupDuress(duressPassword: string): Promise<void> {2137  if (vaultCreatesInFlight) throw new Error("vault_changed");2138  vaultWritesInFlight++;2139  try {2140  if (!derivedKey || vaultMode !== "real") {2141    throw new Error("vault must be unlocked in real mode");2142  }2143  // Encrypt the decoy payload (empty entries) under the duress key. Pad to2144  // at least the current slot A ciphertext size so the two slots look the2145  // same at rest at setup time.2146  const slotA = await loadSlot(SLOT_A);2147  if (!slotA) throw new Error("missing slot A");21482149  const decoySalt = generateSalt();2150  const decoyKey = await deriveKey(duressPassword, decoySalt);2151  try {2152    // Pad the decoy to the fixed duress ceiling. Slot A is re-encrypted to the2153    // same ceiling by the persistSlotA() call below (duressConfigured is now2154    // true), so both slots are exactly DURESS_SLOT_SIZE+tag at rest and their2155    // lengths cannot reveal that duress is configured (audit MEDIUM).2156    const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);2157    const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");2158    await writeSlot(SLOT_B, {2159      version: 1,2160      salt: hex(decoySalt),2161      nonce,2162      ciphertext,2163      tag,2164    });2165    // The stored decoy member belonged to the previous decoy slot.2166    await clearStoredManualSummonRecall("decoy");2167  } finally {2168    zeroKey(decoyKey);2169  }21702171  // Re-encrypt slot A with the duressConfigured flag set to true. No external2172  // flag is written — the bit lives inside the encrypted envelope.2173  duressConfigured = true;2174  await persistSlotA();2175  } finally { vaultWritesInFlight--; }2176}21772178export async function disableDuress(): Promise<void> {2179  if (vaultCreatesInFlight) throw new Error("vault_changed");2180  vaultWritesInFlight++;2181  try {2182  if (!derivedKey || vaultMode !== "real") {2183    throw new Error("vault must be unlocked in real mode");2184  }2185  // Overwrite slot B with fresh noise that matches slot A's size. The slot2186  // remains occupied so its mere existence does not signal that duress was2187  // ever configured.2188  const slotA = await loadSlot(SLOT_A);2189  if (slotA) {2190    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));2191    await clearStoredManualSummonRecall("decoy");2192  }21932194  duressConfigured = false;2195  await persistSlotA();2196  } finally { vaultWritesInFlight--; }2197}21982199// L14/COR-015: this function intentionally checks slot A (real vault) only.2200// A duress-mode user attempting changePassword is rejected earlier by the2201// vaultMode === 'decoy' check at changePassword. The real-vs-decoy2202// distinction here is by design — duress users cannot rotate the real2203// password by guessing it, and the asymmetry in error timing is acceptable2204// because duress mode is opt-in and the user knows their own decoy key.2205export async function verifyMainPassword(password: string): Promise<boolean> {2206  const slotA = await loadSlot(SLOT_A);2207  if (!slotA) return false;2208  const key = await deriveKey(password, unhex(slotA.salt));2209  try {2210    return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;2211  } finally {2212    zeroKey(key);2213  }2214}22152216export async function unlock(password: string): Promise<boolean> {2217  return attemptUnlockWithDerive(password, deriveKey);2218}22192220async function attemptUnlockWithDerive(2221  password: string,2222  derive: typeof deriveKey,2223): Promise<boolean> {2224  vaultUnlocksInFlight++;2225  try {2226  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;2227  const epoch = vaultEpoch;2228  const stale = () => epoch !== vaultEpoch;2229  await revokeRecoveryReveal();2230  if (stale()) return false;2231  // Load both current-format slots in parallel. Both exist on a supported2232  // install; the2233  // parallel load and the parallel derivation below keep wall-clock time2234  // constant regardless of which slot's passphrase (real or decoy) the2235  // caller supplied, so a timing side channel cannot distinguish the2236  // duress path from the real-unlock path (DUR-002).2237  const [slotA, slotB] = await Promise.all([2238    loadSlot(SLOT_A),2239    loadSlot(SLOT_B),2240  ]);22412242  // Derive both keys in parallel, unconditionally.2243  const [keyA, keyB] = await Promise.all([2244    slotA ? derive(password, unhex(slotA.salt)) : Promise.resolve(null),2245    slotB ? derive(password, unhex(slotB.salt)) : Promise.resolve(null),2246  ]);22472248  // Attempt both decrypts in parallel. The Result variant lets us distinguish2249  // 'wrong_key' from 'corrupted' so callers can offer a history-restore path2250  // when a slot's schema is invalid even though AES-GCM authenticated (M7).2251  const [resultA, resultB] = await Promise.all([2252    keyA && slotA2253      ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")2254      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),2255    keyB && slotB2256      ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")2257      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),2258  ]);2259  const payloadA = resultA.status === "ok" ? resultA.payload : null;2260  const payloadB = resultB.status === "ok" ? resultB.payload : null;22612262  if (stale()) {2263    if (keyA) zeroKey(keyA);2264    if (keyB) zeroKey(keyB);2265    return false;2266  }22672268  if (payloadA && keyA) {2269    if (stale()) {2270      zeroKey(keyA);2271      if (keyB) zeroKey(keyB);2272      return false;2273    }2274    cancelBreachScan();2275    derivedKey = keyA;2276    vaultMode = "real";2277    manualSummonRecall = new Map();2278    entries = payloadA.entries;2279    tombstones = payloadA.tombstones;2280    duressConfigured = payloadA.duressConfigured;2281    buildDomainIndexSync(entries);2282    await loadSettings();2283    if (stale()) {2284      await lock();2285      return false;2286    }2287    touchAutoLock();2288    if (keyB) zeroKey(keyB);22892290    // Current vaults always carry a password-wrapped root key. Older vaults2291    // without this escrow are outside the supported storage format.2292    rootKey = slotA ? await deriveRootKeyFromDerivedKey(keyA, slotA) : null;2293    if (!rootKey) {2294      await lock();2295      return false;2296    }22972298    // Repair missing or stale escrow only after a real password authenticates the slot.2299    if (slotA) {2300      const escrowed = slotA.recovery_vault_key2301        ? await openSealedKey(rootKey, slotA.recovery_vault_key, "recovery_vault_key_v1") : null;2302      const matches = escrowed !== null && escrowed.every((byte, i) => byte === keyA[i]);2303      if (escrowed) zeroKey(escrowed);2304      if (stale()) { await lock(); return false; }2305      if (!matches) {2306        try {2307          const recoveryVaultKey = await encrypt(rootKey, hex(keyA), "recovery_vault_key_v1");2308          if (stale()) { await lock(); return false; }2309          await writeSlot(SLOT_A, { ...slotA, recovery_vault_key: recoveryVaultKey });2310          if (stale()) { await lock(); return false; }2311        } catch (error) {2312          await lock();2313          throw error;2314        }2315      }2316    }23172318    // PB-26-213: adopt legacy plaintext pair secrets into the encrypted2319    // record and refresh the trusted-session operational copy.2320    await reconcilePairSecrets(rootKey);2321    if (stale()) {2322      await lock();2323      return false;2324    }2325    await lockedSyncUnlockHook?.().catch((error) => {2326      console.warn("[Peach sync] locked inbox drain failed:", error);2327    });2328    if (stale()) {2329      await lock();2330      return false;2331    }2332    await resetPinFailedAttempts();2333    if (stale()) {2334      await lock();2335      return false;2336    }2337    await saveSessionKey(keyA, "real", epoch);2338    if (stale()) return false;2339    await restoreManualSummonRecall();2340    if (stale()) return false;2341    return true;2342  }23432344  if (payloadB && keyB) {2345    if (stale()) {2346      zeroKey(keyB);2347      if (keyA) zeroKey(keyA);2348      return false;2349    }2350    cancelBreachScan();2351    derivedKey = keyB;2352    vaultMode = "decoy";2353    manualSummonRecall = new Map();2354    decoySyncTeardownHook?.();2355    // A duress session must not retain the real vault's root key. It gates the2356    // recovery words, the sync identity, and the root wrap of the local device2357    // identity, so leaving it live would expose all three in duress mode.2358    if (rootKey) {2359      rootKey.fill(0);2360      rootKey = null;2361    }2362    entries = payloadB.entries;2363    tombstones = payloadB.tombstones;2364    duressConfigured = false;2365    buildDomainIndexSync(entries);2366    await loadSettings();2367    touchAutoLock();2368    if (keyA) zeroKey(keyA);2369    // PB-26-213: a duress session must never serve the real pair-secret map.2370    await dropSessionCache();2371    // Nor the real device identity: a duress session is not a real one.2372    await notifyIdentitySessionEnded();2373    if (stale()) {2374      await lock();2375      return false;2376    }2377    await saveSessionKey(keyB, "decoy", epoch);2378    if (stale()) return false;2379    await restoreManualSummonRecall();2380    if (stale()) return false;2381    return true;2382  }23832384  if (keyA) zeroKey(keyA);2385  if (keyB) zeroKey(keyB);2386  // Surface corruption (good AES tag, broken schema) distinctly from2387  // wrong-password so the popup can offer history-restore (M7/COR-007).2388  if (resultA.status === "corrupted") {2389    lastUnlockFailureReason = resultA.reason;2390  } else if (resultB.status === "corrupted") {2391    lastUnlockFailureReason = resultB.reason;2392  }2393  return false;2394  } finally { vaultUnlocksInFlight--; }2395}23962397// ---------------------------------------------------------------------------2398// MV3 service worker session key — survives SW restarts within a browser session2399// ---------------------------------------------------------------------------24002401// chrome.storage.session is cleared on browser close; survives SW restart.2402// Firefox does not implement it (persistent background script, no restart risk).2403const SESSION_KEY_STORAGE = "peach_session_dk";24042405// Order writes and removals so lock's awaited removal is a barrier after2406// every escrow write that started before it.2407let sessionKeyMutation = Promise.resolve();24082409function mutateSessionKey(mutation: () => Promise<void>): Promise<void> {2410  const task = sessionKeyMutation.then(mutation, mutation);2411  sessionKeyMutation = task.catch(() => undefined);2412  return task;2413}24142415// PB-26-203: the session-key escrow may only operate where startup positively2416// established trusted-only session storage. Defaults to available so direct2417// vault imports (tests, non-entry bootstraps) keep working; entry.ts applies2418// the real hardening result before the first restore.2419let sessionEscrowAvailable = true;24202421/**2422 * Apply the storage-hardening result at startup. When the trusted-only2423 * session state cannot be established, any stored session key is removed and2424 * the escrow stays off: the user unlocks again after a worker restart2425 * instead of trusting an unproven boundary.2426 */2427export async function applyStorageHardening(sessionEscrow: boolean): Promise<void> {2428  setSessionAllowed(sessionEscrow);2429  if (sessionEscrow) return;2430  sessionEscrowAvailable = false;2431  await clearSessionKey();2432}24332434async function saveSessionKey(2435  key: Uint8Array,2436  mode: "real" | "decoy",2437  expectedEpoch = vaultEpoch,2438): Promise<void> {2439  const session = chrome.storage.session;2440  if (!session || !sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;2441  const stored = { keyHex: hex(key), mode };2442  await mutateSessionKey(async () => {2443    if (!sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;2444    await session.set({ [SESSION_KEY_STORAGE]: stored });2445  });2446}24472448async function clearSessionKey(): Promise<void> {2449  const session = chrome.storage.session;2450  if (!session) return;2451  await mutateSessionKey(() => session.remove(SESSION_KEY_STORAGE));2452}24532454// A lock that only holds while the service worker stays alive is no lock at2455// all: a cold worker's restoreFromSession() would find the surviving session2456// key and silently re-unlock ~a minute after the user locked. So lock()2457// bumps this epoch synchronously at entry and zeroes keys/indexes before any2458// await; a restore that started earlier sees the mismatch after its next2459// await and aborts instead of publishing.2460let vaultEpoch = 0;24612462// One in-flight restore shared by concurrent callers: storage is read once2463// and the locked-sync unlock hook runs once.2464let restoreInFlight: Promise<boolean> | null = null;24652466/**2467 * On SW restart, re-derive all in-memory vault state from the session key2468 * stored in chrome.storage.session (set at unlock time, cleared by lock();2469 * also cleared on browser close or when restoration fails).2470 * Returns true if the vault was restored, false if no session key was found.2471 * No-ops if the vault is already unlocked.2472 */2473export async function restoreFromSession(): Promise<boolean> {2474  vaultUnlocksInFlight++;2475  try {2476  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;2477  if (derivedKey !== null) return true;2478  if (restoreInFlight) return restoreInFlight;2479  const task = restoreFromSessionInner();2480  restoreInFlight = task;2481  try {2482    return await task;2483  } finally {2484    restoreInFlight = null;2485  }2486  } finally { vaultUnlocksInFlight--; }2487}24882489async function restoreFromSessionInner(): Promise<boolean> {2490  const epoch = vaultEpoch;2491  const stale = () => epoch !== vaultEpoch;2492  if (derivedKey !== null) return true;2493  if (!sessionEscrowAvailable) return false;2494  if (!chrome.storage.session) return false;2495  const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);2496  if (stale()) return false;2497  const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;2498  if (!entry?.keyHex) return false;24992500  const key = unhex(entry.keyHex);2501  const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;2502  const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";2503  const slot = await loadSlot(slotKey);2504  if (stale()) { zeroKey(key); return false; }2505  if (!slot) { await clearSessionKey(); return false; }25062507  const result = await tryDecryptSlotResult(slot, key, aadTag);2508  if (stale()) { zeroKey(key); return false; }2509  if (result.status !== "ok") { await clearSessionKey(); return false; }25102511  // Decrypted payload stays in locals until the final epoch-checked commit2512  // below; nothing observable is published before then.2513  const payload = result.payload;2514  await loadSettings();2515  if (stale()) { zeroKey(key); return false; }25162517  // Rehydrate the root key used by sync identity derivation from the password2518  // escrow stored on the current vault format.2519  let freshRoot: Uint8Array | null = null;2520  if (entry.mode === "real") {2521    freshRoot = await deriveRootKeyFromDerivedKey(key, slot);2522    if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }2523    if (!freshRoot) {2524      await lock();2525      return false;2526    }2527  }25282529  if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }2530  if (freshRoot) {2531    // PB-26-213: encrypted pair-secret record + session copy, before publish.2532    await reconcilePairSecrets(freshRoot);2533    if (stale()) { zeroKey(key); zeroKey(freshRoot); return false; }2534  } else {2535    // PB-26-213: a duress restore must never serve the real pair-secret map.2536    await dropSessionCache();2537    // Nor the real device identity.2538    await notifyIdentitySessionEnded();2539    if (stale()) { zeroKey(key); return false; }2540  }2541  cancelBreachScan();2542  derivedKey = key;2543  vaultMode = entry.mode;2544  manualSummonRecall = new Map();2545  if (entry.mode === "decoy") decoySyncTeardownHook?.();2546  entries = payload.entries;2547  tombstones = payload.tombstones;2548  duressConfigured = entry.mode === "real" ? payload.duressConfigured : false;2549  if (freshRoot) rootKey = freshRoot;2550  buildDomainIndexSync(entries);2551  touchAutoLock();25522553  await lockedSyncUnlockHook?.().catch((error) => {2554    console.warn("[Peach sync] locked inbox drain failed:", error);2555  });2556  if (stale()) return false;2557  await restoreManualSummonRecall();2558  if (stale()) return false;25592560  return true;2561}25622563export async function lock(): Promise<void> {2564  const recoveryRevoked = revokeRecoveryReveal();2565  // A user-initiated lock must be durable across MV3 service-worker restarts.2566  // The SW is idle-killed after ~30s of inactivity, and the popup's next open2567  // wakes a cold SW whose restoreFromSession() reads chrome.storage.session.2568  // If the session key survived lock(), that restore would silently re-unlock2569  // the vault ~a minute after the user locked it — a lock that only held2570  // while the SW happened to stay alive. The background-sync convenience the2571  // session key once bought (sync runner re-waking to a restored vault) is2572  // not worth an unlocked vault the user never asked to unlock; when locked,2573  // sync-runner correctly reports VAULT_LOCKED instead.2574  cancelBreachScan();2575  vaultEpoch++;2576  if (derivedKey) {2577    zeroKey(derivedKey);2578    derivedKey = null;2579  }2580  if (rootKey) {2581    rootKey.fill(0);2582    rootKey = null;2583  }25842585  entries = [];2586  manualSummonRecall = new Map();2587  tombstones = new Map();2588  domainIndex = new Map();2589  vaultMode = "real";2590  duressConfigured = false;2591  clearAutoLock();2592  try {2593    chrome.runtime?.sendMessage?.({ type: "VAULT_LOCKED" })?.catch?.(() => undefined);2594  } catch { /* UI contexts may already be closed */ }2595  await clearSessionKey();2596  await recoveryRevoked;2597  // The decrypted identity is session state as well, so a locked vault must not2598  // leave one behind; clear it after the in-memory state is gone.2599  await notifyIdentitySessionEnded();2600  vaultLockHook?.();2601}26022603/// Identifies the current unlock session for authorization across awaited work.2604export function getVaultEpoch(): number {2605  return vaultEpoch;2606}26072608export function isUnlocked(): boolean {2609  return derivedKey !== null;2610}2611/** True only while the active session is unlocked through the decoy slot. */2612export function isDecoyMode(): boolean {2613  return derivedKey !== null && vaultMode === "decoy";2614}26152616// Opens the vault using a pre-derived AES-256 key (skipping Argon2id). The2617// PIN-unlock path unwraps this key from its PIN wrap; the passphrase path2618// always derives from scratch via Argon2id.2619export async function unlockWithKey(2620  masterKeyHex: string,2621): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {2622  vaultUnlocksInFlight++;2623  try {2624  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };2625  const epoch = vaultEpoch;2626  const stale = () => epoch !== vaultEpoch;2627  await revokeRecoveryReveal();2628  if (stale()) return { ok: false, error: "vault_locked" };2629  let masterKeyBytes: Uint8Array | null = null;2630  try {2631    masterKeyBytes = unhex(masterKeyHex);2632    const stored = await loadSlot(SLOT_A);2633    if (!stored) return { ok: false, error: "invalid_key" };2634    const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");2635    if (!payload || stale()) {2636      zeroKey(masterKeyBytes);2637      return { ok: false, error: "invalid_key" };2638    }26392640    cancelBreachScan();2641    derivedKey = masterKeyBytes;2642    vaultMode = "real";2643    manualSummonRecall = new Map();2644    entries = payload.entries;2645    tombstones = payload.tombstones;2646    duressConfigured = payload.duressConfigured;2647    buildDomainIndexSync(entries);2648    await loadSettings();2649    touchAutoLock();26502651    rootKey = await deriveRootKeyFromDerivedKey(masterKeyBytes, stored);2652    if (!rootKey) {2653      await lock();2654      return { ok: false, error: "invalid_key" };2655    }2656    await reconcilePairSecrets(rootKey);2657    if (stale()) {2658      await lock();2659      return { ok: false, error: "invalid_key" };2660    }2661    await saveSessionKey(masterKeyBytes, "real", epoch);2662    if (stale()) return { ok: false, error: "invalid_key" };2663    await restoreManualSummonRecall();2664    if (stale()) return { ok: false, error: "invalid_key" };2665    // The PIN/adoption unlock path publishes the same in-memory state as the2666    // password path, and the mesh relay reconcile depends on it.2667    await lockedSyncUnlockHook?.().catch((error) => {2668      console.warn("[Peach sync] locked inbox drain failed:", error);2669    });2670    if (stale()) return { ok: false, error: "invalid_key" };2671    return { ok: true, entries };2672  } catch {2673    if (masterKeyBytes && derivedKey !== masterKeyBytes) zeroKey(masterKeyBytes);2674    return { ok: false, error: "invalid_key" };2675  }2676  } finally { vaultUnlocksInFlight--; }2677}26782679// --- Adoption duress-slot helpers (passthrough, no decrypt) ---26802681/**2682 * Adoption SOURCE helper: returns the sealed slot B as a JSON string when2683 * duress is configured and slot B exists, so the inline snapshot can ship it2684 * to the receiver. Returns null otherwise. Never decrypts.2685 */2686export async function exportDuressSlotForAdoption(): Promise<string | null> {2687  if (!(await isDuressEnabled())) return null;2688  const slotB = await loadSlot(SLOT_B);2689  if (!slotB) return null;2690  return JSON.stringify(slotB);2691}26922693/**2694 * Adoption RECEIVER helper: installs a duress slot received from a source2695 * device. Validates the StoredVault shape (same guard as unlockFromCodex)2696 * and writes it to slot B. Throws on invalid shape so the caller can treat2697 * it as a non-fatal snapshot failure. Never decrypts.2698 */2699export async function installAdoptedDuressSlot(json: string): Promise<void> {2700  if (vaultCreatesInFlight) throw new Error("vault_changed");2701  vaultWritesInFlight++;2702  try {2703  let parsed: StoredVault;2704  try {2705    const raw = JSON.parse(json) as unknown;2706    if (!hasValidVaultSchema(raw)) {2707      throw new Error("invalid_duress_slot_shape");2708    }2709    parsed = raw;2710  } catch (err) {2711    if (err instanceof SyntaxError) {2712      throw new Error("invalid_duress_slot_shape");2713    }2714    throw err;2715  }2716  await writeSlot(SLOT_B, parsed);2717  // The adopted decoy slot replaces any local decoy the member belonged to.2718  await clearStoredManualSummonRecall("decoy");2719  manualSummonRecall = new Map();2720  await restoreManualSummonRecall();2721  } finally { vaultWritesInFlight--; }2722}27232724/**2725 * Restore the vault from a parsed Peach Codex payload.2726 *2727 * The supplied passphrase is verified against the Codex's slotA *before* any2728 * storage mutation — wrong passphrases return without touching disk. On2729 * success, the current vault state is snapshotted (reason: "restore") so the2730 * user can revert via Settings -> Vault History, then slotA/slotB are written2731 * and `peach_last_modified_at` is set to the Codex's recorded timestamp. A2732 * regular `unlock()` follows so the rest of the SW sees the standard2733 * post-unlock state.2734 *2735 * Intentionally non-Pro-gated — see peach_codex_v2.md "Pro gating". A Codex2736 * printed by a Pro user must always be restorable, even on a free device.2737 *2738 * Timing is not held constant here (in contrast to `unlock`): the Codex flow2739 * is an explicit user action with a known passphrase, not a passive lock2740 * screen, so the duress-vs-real timing side channel does not apply.2741 */2742export async function unlockFromCodex(params: {2743  slotA: string; // JSON string of StoredVault for slot A2744  slotB: string | null; // JSON string of StoredVault for slot B, or null2745  timestamp: number;2746  masterPassphrase: string;2747}): Promise<2748  | { ok: true; entryCount: number }2749  | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" | "missing_root_escrow" }2750> {2751  if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");2752  vaultReplacementInFlight = true;2753  try {2754    let parsedSlotA: StoredVault;2755    let parsedSlotB: StoredVault | null = null;2756    try {2757      const rawA = JSON.parse(params.slotA) as unknown;2758      if (!hasValidVaultSchema(rawA)) {2759        return { ok: false, reason: "invalid_slot_format" };2760      }2761      parsedSlotA = rawA;2762      if (params.slotB !== null) {2763        const rawB = JSON.parse(params.slotB) as unknown;2764        if (!hasValidVaultSchema(rawB)) {2765          return { ok: false, reason: "invalid_slot_format" };2766        }2767        parsedSlotB = rawB;2768      }2769    } catch {2770      return { ok: false, reason: "invalid_slot_format" };2771    }27722773    // Verify the passphrase and the password-wrapped root escrow against the2774    // staged Slot A WITHOUT writing anything. Payload decoding is part of the2775    // trial decrypt, so unlock() cannot be the first place these checks run.2776    const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));2777    const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");2778    if (!trialPayload) {2779      zeroKey(trialKey);2780      return { ok: false, reason: "wrong_passphrase" };2781    }2782    const hasEscrow =2783      !!parsedSlotA.pw_root_ciphertext && !!parsedSlotA.pw_root_nonce && !!parsedSlotA.pw_root_tag;2784    if (!hasEscrow) {2785      zeroKey(trialKey);2786      return { ok: false, reason: "missing_root_escrow" };2787    }2788    const stagedRootKey = await deriveRootKeyFromDerivedKey(trialKey, parsedSlotA);2789    if (!stagedRootKey) {2790      zeroKey(trialKey);2791      return { ok: false, reason: "wrong_passphrase" };2792    }2793    zeroKey(stagedRootKey);2794    zeroKey(trialKey);27952796    // Stage the complete candidate pair in memory before touching storage.2797    const stagedSlotB = parsedSlotB ?? generateNoiseBlob(parsedSlotA.ciphertext.length / 2);27982799    // Drop the trial key; `unlock()` below derives its own copy. Holding two2800    // copies of the master key in memory at once would be a needless surface.28012802    // Snapshot the about-to-be-overwritten on-disk state so the user can revert2803    // a mistaken Codex restore via the Vault History UI. Non-fatal if it fails.2804    await takeVaultSnapshot("restore");2805    const previousSlotA = await loadSlot(SLOT_A);2806    const previousSlotB = await loadSlot(SLOT_B);2807    let slotACommitted = false;2808    let slotBCommitted = false;2809    try {2810      await writeSlot(SLOT_A, parsedSlotA);2811      slotACommitted = true;2812      await writeSlot(SLOT_B, stagedSlotB);2813      slotBCommitted = true;2814      await chrome.storage.local.set({2815        peach_last_modified_at: String(params.timestamp),2816      });2817    } catch (err) {2818      if (slotBCommitted && previousSlotB) await writeSlot(SLOT_B, previousSlotB);2819      if (slotACommitted && previousSlotA) await writeSlot(SLOT_A, previousSlotA);2820      throw err;2821    }28222823    // Standard unlock path so domain index, settings, auto-lock, and2824    // recovery-key state all populate exactly as a normal unlock would.2825    const ok = await unlock(params.masterPassphrase);2826    if (!ok) {2827      // Should be unreachable — the staged candidate passed the same checks.2828      return { ok: false, reason: "wrong_passphrase" };2829    }2830    return { ok: true, entryCount: getEntries().length };2831  } finally {2832    vaultReplacementInFlight = false;2833  }2834}28352836// Returns the current in-memory derived key as a hex string. Only the PIN2837// unlock path needs this value, and it reads module state directly; this2838// accessor exists so unlockWithKey's root-key rehydration is testable.2839export /* @testable */ function getDerivedKeyHex(): string {2840  if (!derivedKey) throw new Error("vault_not_unlocked");2841  return hex(derivedKey);2842}28432844/**2845 * Returns the vault's stable root key as hex, or null when locked / not yet2846 * populated. The root key is random per-vault, generated at creation, escrowed2847 * under the recovery words, and re-wrapped (not regenerated) on every password2848 * change — so it is INVARIANT across password rotation, unlike getDerivedKeyHex.2849 *2850 * This is the correct input for sync identity derivation (vault_id, the Noise2851 * NK static key, the Ed25519 manifest signing key, and per-entry envelope2852 * keys): paired devices keep the same identity and can still decrypt each2853 * other's entries after either side rotates its master password (SEV-2-B).2854 *2855 * Returns null rather than throwing so sync callers degrade to VAULT_LOCKED2856 * instead of crashing; rootKey is populated on every supported real-mode2857 * unlock via deriveRootKeyFromDerivedKey.2858 */2859export function getRootKeyHex(): string | null {2860  return rootKey ? hex(rootKey) : null;2861}28622863export function getEntries(): VaultEntry[] {2864  if (!derivedKey) throw new Error("vault_locked");2865  return entries.filter((entry) => !entry.deletedAt);2866}28672868const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;28692870export function getIdentities(): SavedIdentity[] {2871  if (!derivedKey) throw new Error("vault_locked");2872  const active = entries.filter((e) => !e.deletedAt && e.type === "login");28732874  const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();2875  const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();28762877  for (const entry of active) {2878    const domain = extractDomain(entry.url ?? "") ?? "";2879    const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;28802881    function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {2882      const existing = map.get(v);2883      if (!existing || modifiedAt > existing.lastUsed) {2884        map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });2885      } else {2886        map.set(v, { ...existing, count: existing.count + 1 });2887      }2888    }28892890    const uVal = entry.username?.trim();2891    if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);28922893    // Also count the dedicated email field — entries created via the inline2894    // popup new-entry form store email here rather than in username.2895    const eVal = entry.email?.trim();2896    if (eVal) tally(emailMap, eVal);2897  }28982899  const toIdentity = (type: "email" | "username") =>2900    ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({2901      value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,2902    });29032904  return [2905    ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),2906    ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),2907  ];2908}29092910export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {2911  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");29122913  const now = Date.now();2914  const added: VaultEntry[] = [];2915  for (const draft of drafts) {2916    try {2917      const sanitized = sanitizeEntryDraft(draft);2918      const nextEntry: VaultEntry = {2919        ...sanitized,2920        id: crypto.randomUUID(),2921        createdAt: now,2922        modifiedAt: monotonicEntryTimestamp(),2923      };2924      entries.push(nextEntry);2925      added.push(nextEntry);2926    } catch {2927      // Skip invalid drafts silently — caller can see diff between input and output length2928    }2929  }29302931  if (added.length > 0) {2932    await persistEntries();2933  }29342935  return added;2936}29372938/**2939 * Restore a set of entries in full fidelity — preserves id, createdAt,2940 * modifiedAt, and every other field unlike `batchAddEntries` which2941 * assigns fresh identity. Used by restore paths where the backup is the2942 * authoritative source of truth. `mode` controls how entries already in2943 * the vault are treated.2944 */2945export async function restoreEntries(2946  incoming: VaultEntry[],2947  mode: "replace" | "merge"2948): Promise<{ added: number; updated: number; skipped: number }> {2949  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");29502951  // A replace with zero incoming entries is almost certainly a caller bug2952  // (e.g. an import that silently dropped everything). Refuse rather than2953  // wipe the vault.2954  if (mode === "replace" && incoming.length === 0) {2955    throw new Error("refuse to replace with empty entry set");2956  }29572958  let added = 0;2959  let updated = 0;2960  let skipped = 0;29612962  if (mode === "replace") {2963    entries = [];2964    for (const entry of incoming) {2965      const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2966      if (!normalized) {2967        skipped += 1;2968        continue;2969      }2970      entries.push(normalized);2971      if (normalized.deletedAt) {2972        tombstones.set(2973          normalized.id,2974          Math.max(tombstones.get(normalized.id) ?? 0, normalized.deletedAt),2975        );2976      } else {2977        tombstones.delete(normalized.id);2978      }2979      added += 1;2980    }2981  } else {2982    const byId = new Map<string, VaultEntry>();2983    for (const e of entries) byId.set(e.id, e);29842985    for (const entry of incoming) {2986      const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2987      if (!normalized) {2988        skipped += 1;2989        continue;2990      }2991      const existing = byId.get(normalized.id);2992      if (!existing) {2993        entries.push(normalized);2994        if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2995        else tombstones.delete(normalized.id);2996        added += 1;2997      } else if (normalized.modifiedAt > existing.modifiedAt) {2998        const idx = entries.findIndex((e) => e.id === existing.id);2999        if (idx !== -1) {3000          entries[idx] = normalized;3001          if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);3002          else tombstones.delete(normalized.id);3003          updated += 1;3004        }3005      } else {3006        skipped += 1;3007      }3008    }3009  }30103011  await persistEntries("import");3012  return { added, updated, skipped };3013}30143015/**3016 * A Peach entry id is a UUID. A restored or imported file carries whatever id3017 * its author used, and no reader bounds it, so one oversized id would ride3018 * into every future sync frame and be rejected there — a permanent, opaque3019 * failure on both platforms, caused by data that was already local.3020 *3021 * The action is mint, not reject: this is the last point where an id is still3022 * ours to choose, so the worst outcome is one duplicate if the same vault is3023 * later restored beside a device still holding the old id. Rejecting would3024 * lose the user's import.3025 *3026 * Deliberately NOT inside sanitizeRestoredEntry, which applyMergedRemoteEntries3027 * also calls. Sync has to adopt a peer's id verbatim — that is the only thing3028 * keeping two devices agreed on which entry they are discussing — so reminting3029 * there would fork identity on every device, on every round.3030 */3031const ENTRY_ID_SHAPE = /^[A-Za-z0-9_-]{1,64}$/;30323033function naturalizeRestoredId(entry: VaultEntry | null): VaultEntry | null {3034  if (!entry || ENTRY_ID_SHAPE.test(entry.id)) return entry;3035  return { ...entry, id: crypto.randomUUID() };3036}30373038/**3039 * Validate + normalise a VaultEntry coming from a backup, import, or sync3040 * peer. MV-6: this is a strict field WHITELIST — `normalizeEntry` copies3041 * only known VaultEntry fields (unknown/attacker keys are dropped), and3042 * nested `passkey`/`canary` shapes are rebuilt field-by-field, never3043 * spread. Returns null for values the live vault shouldn't accept.3044 */3045function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {3046  if (!entry || typeof entry !== "object") return null;3047  const title = typeof entry.title === "string" ? entry.title.trim() : "";3048  if (!title) return null;3049  const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();3050  const now = Date.now();3051  const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;3052  const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;30533054  // normalizeEntry whitelists every known VaultEntry field before the entry3055  // reaches the live vault.3056  const normalized = normalizeEntry({3057    ...entry,3058    id,3059    title,3060    type: entry.type ?? "login",3061    createdAt,3062    modifiedAt,3063  });30643065  if (normalized.passkey) {3066    normalized.passkey = sanitizePasskey(normalized.passkey);3067  }3068  if (normalized.canary) {3069    normalized.canary = sanitizeCanary(normalized.canary);3070  }3071  // PCH-01-016: bound tags on the restore path too, so both import funnels agree.3072  normalized.tags = sanitizeTags(normalized.tags);30733074  // Login entries from backup must carry a password (or be passkey-only,3075  // in which case the passkey sub-object replaces the password requirement).3076  if (3077    normalized.type === "login" &&3078    !normalized.passkey &&3079    typeof normalized.password !== "string"3080  ) {3081    return null;3082  }3083  if (entry.passkey && !normalized.passkey) {3084    // Entry claimed a passkey but the shape didn't validate — refuse the3085    // whole entry rather than silently importing a credential-less husk.3086    return null;3087  }30883089  return normalized;3090}30913092/**3093 * Rebuild a PasskeyData object from untrusted input, field by field.3094 * Returns undefined when required fields are missing/mistyped — a rogue3095 * passkey credential must not activate via import (MV-6 attack scenario).3096 */3097function sanitizePasskey(pk: unknown): PasskeyData | undefined {3098  if (!pk || typeof pk !== "object") return undefined;3099  const r = pk as Record<string, unknown>;3100  if (3101    typeof r.rpId !== "string" || !r.rpId ||3102    typeof r.credentialId !== "string" || !r.credentialId ||3103    typeof r.publicKeyCose !== "string" ||3104    typeof r.userHandle !== "string" ||3105    typeof r.userName !== "string"3106  ) {3107    return undefined;3108  }3109  return {3110    rpId: r.rpId,3111    rpName: typeof r.rpName === "string" ? r.rpName : r.rpId,3112    credentialId: r.credentialId,3113    publicKeyCose: r.publicKeyCose,3114    privateKeyJwk:3115      r.privateKeyJwk && typeof r.privateKeyJwk === "object"3116        ? (r.privateKeyJwk as JsonWebKey)3117        : undefined,3118    userHandle: r.userHandle,3119    userName: r.userName,3120    userDisplayName:3121      typeof r.userDisplayName === "string" ? r.userDisplayName : r.userName,3122    algorithm: r.algorithm === -8 ? -8 : -7,3123    signCount: typeof r.signCount === "number" ? r.signCount : 0,3124    aaguid: typeof r.aaguid === "string" ? r.aaguid : "",3125    backupEligible: r.backupEligible === true,3126    backupState: r.backupState === true,3127    lastUsedAt: typeof r.lastUsedAt === "number" ? r.lastUsedAt : undefined,3128    browser: r.browser === "chrome" || r.browser === "firefox" ? r.browser : undefined,3129    transports: Array.isArray(r.transports)3130      ? r.transports.filter((t): t is string => typeof t === "string")3131      : undefined,3132    createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),3133  };3134}31353136/**3137 * Rebuild a Canary object from untrusted input. The webhook must be a3138 * well-formed HTTPS URL — a poisoned canary.webhookUrl is a standing3139 * exfiltration endpoint that the canary subsystem will POST entry titles3140 * to (MV-6 attack scenario). Invalid → the canary is dropped, not the3141 * entry. FIRE_CANARY_PING revalidates the destination policy at dispatch3142 * (canaryWebhookUrl), so this import-time check is the3143 * outer of two gates.3144 */3145function sanitizeCanary(c: unknown): Canary | undefined {3146  if (!c || typeof c !== "object") return undefined;3147  const r = c as Record<string, unknown>;3148  if (typeof r.webhookUrl !== "string") return undefined;3149  let url: URL;3150  try {3151    url = new URL(r.webhookUrl);3152  } catch {3153    return undefined;3154  }3155  if (url.protocol !== "https:") return undefined;3156  return {3157    webhookUrl: url.toString(),3158    label: typeof r.label === "string" ? r.label : undefined,3159    lastPinged: typeof r.lastPinged === "number" ? r.lastPinged : undefined,3160    pingCount: typeof r.pingCount === "number" ? r.pingCount : undefined,3161  };3162}31633164/**3165 * MV-6 / PCH-01-016: tags from imported / batch-added entries are untrusted.3166 * Keep only non-empty strings, cap each at 256 chars, and cap the count at 2553167 * (the same per-entry ceiling the export codec enforces, peachPayload.ts).3168 * Non-array or all-invalid input collapses to undefined.3169 */3170function sanitizeTags(tags: unknown): string[] | undefined {3171  if (!Array.isArray(tags)) return undefined;3172  const out: string[] = [];3173  for (const t of tags) {3174    if (typeof t !== "string") continue;3175    const trimmed = t.trim();3176    if (!trimmed) continue;3177    out.push(trimmed.slice(0, 256));3178    if (out.length >= 255) break;3179  }3180  return out.length > 0 ? out : undefined;3181}31823183// Soft-deletes every non-deleted entry in one call. The literal string3184// argument is a tripwire against accidental calls — any caller that would3185// wipe the vault has to consciously type "REPLACE_ALL". Do not relax this3186// to a boolean.3187export async function clearVaultEntries(3188  confirmation: "REPLACE_ALL"3189): Promise<void> {3190  if (confirmation !== "REPLACE_ALL") {3191    throw new Error("clearVaultEntries requires explicit confirmation");3192  }3193  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3194  for (const entry of entries) {3195    if (!entry.deletedAt) {3196      const stamp = monotonicEntryTimestamp(Math.max(3197        entry.modifiedAt,3198        tombstones.get(entry.id) ?? 0,3199      ));3200      entry.deletedAt = stamp;3201      entry.modifiedAt = stamp;3202      tombstones.set(entry.id, stamp);3203    }3204  }3205  await persistEntries();3206}32073208export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {3209  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3210  const epoch = vaultEpoch;3211  const key = derivedKey;32123213  const sanitized = sanitizeEntryDraft(entry);3214  const now = Date.now();3215  const stamp = monotonicEntryTimestamp();3216  const nextEntry: VaultEntry = {3217    ...sanitized,3218    id: crypto.randomUUID(),3219    createdAt: now,3220    modifiedAt: stamp,3221    // Stamp passwordChangedAt at creation so age tracking is accurate from3222    // day one. Non-login entries carry the same stamp harmlessly.3223    passwordChangedAt: sanitized.password ? stamp : undefined,3224  };32253226  // Clone-and-replace so a failed persist rolls back the in-memory state3227  // (COR-008). Without this, a quota-full or storage error leaves the3228  // module-level `entries` ahead of what's actually on disk.3229  const rollback = entries;3230  entries = [...entries, nextEntry];3231  try {3232    await persistEntries();3233  } catch (err) {3234    entries = rollback;3235    throw err;3236  }32373238  if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password && epoch === vaultEpoch) {3239    checkEntryBreachDetached({ id: nextEntry.id, password: nextEntry.password, epoch, key });3240  }32413242  fireSyncTrigger("vault_change");32433244  return nextEntry;3245}32463247/// Attach unambiguous account credentials without discarding other entry data.3248export async function consolidatePasskeyEntries(): Promise<void> {3249  if (!derivedKey || vaultCreatesInFlight) return;3250  const epoch = vaultEpoch;3251  const rollback = entries;3252  const next = entries.map((entry) => ({ ...entry }));3253  if (!mergePasskeyOnlyIntoLogins(next).merged) return;3254  const unchanged = next.map((entry) => ({ entry, modifiedAt: entry.modifiedAt }));3255  entries = next;3256  try {3257    await persistEntries();3258  } catch (err) {3259    // Other writers can replace entries or mutate a deletion in this array.3260    if (epoch === vaultEpoch && entries === next && entries.length === unchanged.length &&3261      unchanged.every(({ entry, modifiedAt }, index) => entries[index] === entry && entry.modifiedAt === modifiedAt)) {3262      entries = rollback;3263      buildDomainIndexSync(entries);3264    }3265    throw err;3266  }3267}32683269export async function updateEntry(3270  id: string,3271  patch: Partial<VaultEntry>3272): Promise<void> {3273  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");32743275  const idx = entries.findIndex((entry) => entry.id === id);3276  if (idx === -1 || entries[idx].deletedAt) {3277    throw new Error("entry_not_found");3278  }32793280  const current = entries[idx];3281  const owner = entries;3282  const epoch = vaultEpoch;3283  const key = derivedKey;3284  const sanitizedPatch = sanitizeEntryPatch(patch);3285  // Refresh passwordChangedAt only when the password value actually changes —3286  // a metadata-only update (title, tags, etc.) must not reset the age clock3287  // that drives the Pro health rotation recommendation.3288  const passwordChanged =3289    "password" in patch &&3290    typeof sanitizedPatch.password === "string" &&3291    sanitizedPatch.password !== current.password;3292  const stamp = monotonicEntryTimestamp(current.modifiedAt);3293  // When the password actually changes, push the outgoing one onto the history3294  // (newest first) so the user can reveal/copy/restore it later. We record the3295  // age it carried (passwordChangedAt, falling back to createdAt) rather than3296  // `now`, so the list reflects when each password was last in effect. Only3297  // capture a non-empty prior value — clearing a password leaves no secret to3298  // keep, and we skip an immediate exact duplicate (e.g. restore-then-restore)3299  // to avoid noise.3300  const priorPassword = current.password;3301  const shouldCapture =3302    passwordChanged &&3303    typeof priorPassword === "string" &&3304    priorPassword.length > 0 &&3305    current.passwordHistory?.[0]?.password !== priorPassword;3306  const nextHistory = shouldCapture3307    ? [3308        { password: priorPassword!, changedAt: current.passwordChangedAt ?? current.createdAt },3309        ...(current.passwordHistory ?? []),3310      ].slice(0, PASSWORD_HISTORY_MAX)3311    : current.passwordHistory;3312  const next = {3313    ...current,3314    ...sanitizedPatch,3315    modifiedAt: stamp,3316    ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),3317  };3318  entries[idx] = next;33193320  // Card entries must retain their card number3321  if (entries[idx].type === "card" && !entries[idx].cardNumber) {3322    entries[idx] = current;3323    throw new Error("card number is required for card entries");3324  }33253326  // Roll the in-memory entry back to its pre-edit state if the disk write3327  // fails (e.g. storage quota). Without this the module-level `entries` array3328  // would hold an edit that never landed on disk, diverging from the vault3329  // until the next unlock silently reverts it (SEV-3-A). Mirrors addEntry.3330  try {3331    await persistEntries();3332  } catch (err) {3333    if (epoch === vaultEpoch && entries === owner && entries[idx] === next && next.modifiedAt === stamp && !next.deletedAt) entries[idx] = current;3334    throw err;3335  }33363337  if (passwordChanged && settings.breachMonitoring !== false && next.type === "login" && next.password && epoch === vaultEpoch) {3338    checkEntryBreachDetached({ id, password: next.password, epoch, key });3339  }33403341  fireSyncTrigger("vault_change");3342}33433344export async function deleteEntry(id: string): Promise<void> {3345  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");33463347  const entry = entries.find((item) => item.id === id);3348  if (!entry || entry.deletedAt) {3349    throw new Error("entry_not_found");3350  }33513352  // Tombstone timestamp must be strictly greater than the entry's last3353  // modification so the deletion wins LWW against any in-flight edit, even3354  // under clock skew (SEV-2-E).3355  const previousModifiedAt = entry.modifiedAt;3356  const previousTombstone = tombstones.get(id);3357  const stamp = monotonicEntryTimestamp(Math.max(entry.modifiedAt, previousTombstone ?? 0));3358  entry.deletedAt = stamp;3359  entry.modifiedAt = stamp;3360  tombstones.set(id, stamp);3361  // Roll the tombstone back if the disk write fails, so a quota error doesn't3362  // leave the entry deleted in memory but alive on disk (SEV-3-A).3363  try {3364    await persistEntries();3365  } catch (err) {3366    delete entry.deletedAt;3367    entry.modifiedAt = previousModifiedAt;3368    if (previousTombstone === undefined) tombstones.delete(id);3369    else tombstones.set(id, previousTombstone);3370    throw err;3371  }3372  fireSyncTrigger("vault_change");3373}33743375export function getDeletedEntries(): VaultEntry[] {3376  if (!derivedKey) return [];3377  return entries.filter((e) => !!e.deletedAt);3378}33793380/** Return all durable deletion timestamps, including purged full entries. */3381export function getTombstoneManifest(): Record<string, number> {3382  if (!derivedKey) return {};3383  return Object.fromEntries(tombstones);3384}33853386/**3387 * Returns the vault's monotonic version — the `peach_last_modified_at` value3388 * stamped on every user-initiated write. Remote (sync) writes do NOT advance3389 * this version so a sync round never cascades into a second outbound sync.3390 */3391export async function getVaultVersion(): Promise<number> {3392  try {3393    const raw = await chrome.storage.local.get("peach_last_modified_at");3394    const v = (raw as Record<string, unknown>).peach_last_modified_at;3395    if (typeof v === "number") return v;3396    if (typeof v === "string" && v !== "") {3397      const n = Number.parseInt(v, 10);3398      return Number.isFinite(n) ? n : 0;3399    }3400    return 0;3401  } catch {3402    return 0;3403  }3404}34053406/**3407 * Apply a batch of remote entries + tombstones from a sync peer.3408 * Last-write-wins by `modifiedAt`; a tombstone supersedes a live entry when3409 * `deletedAt > modifiedAt` on the local side. Mutates `entries` directly and3410 * persists with reason `sync_received` — does NOT fire the sync dispatcher, so3411 * applying a sync round cannot cascade into another outbound sync.3412 *3413 * `applied` counts entries that actually changed local state (new add,3414 * overwrite-by-newer, or new tombstone). `received` is the raw payload size3415 * the caller can surface in the sync result UI.3416 */3417export async function applyMergedRemoteEntries(3418  remoteEntries: VaultEntry[],3419  remoteTombstones: Record<string, number>,3420): Promise<{ received: number; applied: number; conflicts: number }> {3421  // DESIGN: last-write-wins is applied PER-ENTRY, not per-field. If two devices3422  // concurrently edit different fields of the same entry, the one with the3423  // newer modifiedAt wins the whole entry and the other device's field edits3424  // are dropped silently. This is the deliberate trade-off for a simple,3425  // conflict-free merge — per-field CRDT merge is out of scope. Guidance for3426  // users: edit a given entry on one device at a time.3427  if (!derivedKey || vaultCreatesInFlight || vaultMode === "decoy") throw new Error("vault_locked");34283429  const received = remoteEntries.length + Object.keys(remoteTombstones).length;3430  let applied = 0;3431  let conflicts = 0;34323433  const byId = new Map<string, VaultEntry>();3434  for (const e of entries) byId.set(e.id, e);34353436  const mergeNow = Date.now();3437  const remoteTombstoneTimes = new Map<string, number>();3438  for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {3439    if (typeof rawDeletedAt === "number" && Number.isFinite(rawDeletedAt) && rawDeletedAt > 0) {3440      remoteTombstoneTimes.set(id, clampSyncTimestamp(rawDeletedAt, mergeNow));3441    }3442  }34433444  for (const remote of remoteEntries) {3445    const sanitized = sanitizeRestoredEntry(remote);3446    if (!sanitized) continue;3447    // HV-1a: a far-future remote modifiedAt must not permanently pin a3448    // malicious value against honest local edits. Clamp BEFORE any3449    // comparison against local timestamps.3450    sanitized.modifiedAt = clampSyncTimestamp(sanitized.modifiedAt, mergeNow);3451    if (typeof sanitized.deletedAt === "number") {3452      sanitized.deletedAt = clampSyncTimestamp(sanitized.deletedAt, mergeNow);3453    }3454    const remoteTombstoneTs = remoteTombstoneTimes.get(sanitized.id);3455    const localTombstoneTs = tombstones.get(sanitized.id);3456    const tombstoneTs = Math.max(remoteTombstoneTs ?? 0, localTombstoneTs ?? 0);3457    if (tombstoneTs > 0 && tombstoneTs >= sanitized.modifiedAt) {3458      continue;3459    }3460    const local = byId.get(sanitized.id);3461    if (!local) {3462      entries.push(sanitized);3463      byId.set(sanitized.id, sanitized);3464      tombstones.delete(sanitized.id);3465      applied += 1;3466    } else if (sanitized.modifiedAt > local.modifiedAt) {3467      const idx = entries.findIndex((e) => e.id === local.id);3468      if (idx !== -1) {3469        entries[idx] = sanitized;3470        byId.set(sanitized.id, sanitized);3471        tombstones.delete(sanitized.id);3472        applied += 1;3473        if (!local.deletedAt) conflicts += 1;3474      }3475    }3476  }34773478  for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {3479    if (typeof rawDeletedAt !== "number" || !Number.isFinite(rawDeletedAt) || rawDeletedAt <= 0) continue;3480    // HV-1a/1c: clamp the tombstone timestamp before every comparison.3481    const deletedAt = remoteTombstoneTimes.get(id)!;3482    const knownTombstone = tombstones.get(id);3483    if (knownTombstone !== undefined && knownTombstone >= deletedAt) continue;3484    const local = byId.get(id);3485    if (!local) {3486      tombstones.set(id, deletedAt);3487      applied += 1;3488      continue;3489    }3490    if (local.deletedAt && local.deletedAt >= deletedAt) continue;3491    if (deletedAt < local.modifiedAt) continue;3492    const idx = entries.findIndex((e) => e.id === id);3493    if (idx !== -1) {3494      entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };3495      tombstones.set(id, deletedAt);3496      applied += 1;3497    }3498  }34993500  if (applied > 0 && vaultMode === "real") {3501    await persistEntries("sync_received");3502    buildDomainIndexSync(entries);3503    // An open popup holds the entries it loaded at mount and polls nothing, so3504    // a background round (the relay listener responding to a peer's push, or the3505    // alarm-driven dial) otherwise lands silently and the user sees stale data3506    // until they reopen. Best-effort: no popup listening is the normal case.3507    try {3508      void chrome.runtime3509        .sendMessage({ type: "VAULT_ENTRIES_CHANGED" })3510        .catch(() => undefined);3511    } catch {3512      // messaging unavailable3513    }3514  }3515  return { received, applied, conflicts };3516}35173518export async function restoreEntry(id: string): Promise<void> {3519  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3520  const entry = entries.find((e) => e.id === id && e.deletedAt);3521  if (!entry) throw new Error("deleted entry not found");3522  const previousDeletedAt = entry.deletedAt;3523  const previousModifiedAt = entry.modifiedAt;3524  const previousTombstone = tombstones.get(id);3525  delete entry.deletedAt;3526  entry.modifiedAt = monotonicEntryTimestamp(Math.max(3527    entry.modifiedAt,3528    previousTombstone ?? 0,3529  ));3530  tombstones.delete(id);3531  try {3532    await persistEntries();3533  } catch (err) {3534    entry.deletedAt = previousDeletedAt;3535    entry.modifiedAt = previousModifiedAt;3536    if (previousTombstone !== undefined) tombstones.set(id, previousTombstone);3537    throw err;3538  }3539  buildDomainIndexSync(entries);3540}35413542export async function purgeEntry(id: string): Promise<void> {3543  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3544  const idx = entries.findIndex((e) => e.id === id && e.deletedAt);3545  if (idx === -1) throw new Error("deleted entry not found");3546  const entry = entries[idx]!;3547  tombstones.set(id, Math.max(tombstones.get(id) ?? 0, entry.deletedAt!));3548  entries.splice(idx, 1);3549  await persistEntries();3550}35513552/** Permanently delete entries whose deletedAt is older than retentionMs. 0 = keep forever. */3553export async function purgeExpiredTrash(retentionMs: number): Promise<number> {3554  if (!derivedKey || vaultCreatesInFlight || retentionMs === 0) return 0;3555  const cutoff = Date.now() - retentionMs;3556  const before = entries.length;3557  for (const entry of entries) {3558    if (entry.deletedAt && entry.deletedAt < cutoff) {3559      tombstones.set(entry.id, Math.max(tombstones.get(entry.id) ?? 0, entry.deletedAt));3560    }3561  }3562  entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));3563  const purged = before - entries.length;3564  if (purged > 0) await persistEntries();3565  return purged;3566}35673568export function queryDomain(domain: string): VaultEntry[] {3569  return domainIndex.get(domain) ?? [];3570}35713572export function getEntryById(id: string): VaultEntry | undefined {3573  return entries.find((entry) => entry.id === id && !entry.deletedAt);3574}35753576async function persistSlotA(3577  reason: VaultSnapshot["reason"] = "local_save",3578): Promise<StoredVault> {3579  if (!derivedKey) throw new Error("vault_locked");3580  const epoch = vaultEpoch;3581  const throwIfStale = () => {3582    if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3583  };35843585  const slotA = await loadSlot(SLOT_A);3586  throwIfStale();3587  if (!slotA) throw new Error("missing slot A");35883589  // Snapshot the about-to-be-overwritten state BEFORE we mutate disk. Failures3590  // are swallowed by takeVaultSnapshot — history must never block a save.3591  await takeVaultSnapshot(reason);3592  throwIfStale();35933594  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3595  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");3596  throwIfStale();35973598  // Preserve existing recovery escrow fields.3599  const nextSlotA: StoredVault = {3600    ...slotA,3601    nonce,3602    ciphertext,3603    tag,3604    // recovery_salt and recovery_wrapped_root_key are already set from loadSlot3605  };36063607  // Slot A (the real vault) is now committed. Wrap every later write so a3608  // mid-persist failure (e.g. a storage error after slot A landed) restores the3609  // prior slot A before rethrowing. Without this, a "failed" save that already3610  // wrote slot A leaves disk ahead of the in-memory rollback in addEntry/3611  // updateEntry/deleteEntry — the entry stays silently on disk and resurfaces3612  // as a duplicate on the next unlock (observed under storage-quota pressure).3613  let slotACommitted = false;3614  try {3615    throwIfStale();3616    await writeSlot(SLOT_A, nextSlotA);3617    slotACommitted = true;3618    throwIfStale();36193620    // When duress is not configured, keep slot B size-matched with slot A by3621    // regenerating its noise. When duress IS configured, leave slot B alone —3622    // we don't have the decoy key to re-encrypt it. This is a known trade-off.3623    if (!duressConfigured) {3624      throwIfStale();3625      await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3626      throwIfStale();3627    }3628    // Only advance the vault version for locally-originated writes. Entries3629    // applied from a sync peer ("sync_received") must NOT bump the counter —3630    // otherwise applying a remote round makes us look newer than the peer and3631    // triggers a redundant outbound sync, defeating the no-op optimisation3632    // and risking a ping-pong between two devices (SEV-2-C).3633    if (reason !== "sync_received") {3634      throwIfStale();3635      await stampLocalVaultMutation();3636      throwIfStale();3637    }3638  } catch (err) {3639    // Best-effort restore — the prior slot A is smaller-or-equal, so this write3640    // fits even when the failure was a quota overflow.3641    if (slotACommitted) await writeSlot(SLOT_A, slotA).catch(() => {});3642    if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3643    throw err;3644  }36453646  return nextSlotA;3647}36483649async function persistSlotB(): Promise<void> {3650  if (!derivedKey) throw new Error("vault_locked");36513652  const slotB = await loadSlot(SLOT_B);3653  if (!slotB) throw new Error("missing slot B");36543655  // Decoy plaintext always reports duressConfigured=false — the decoy user3656  // sees a clean slate. persistSlotB only runs in decoy mode, which only3657  // exists once duress is configured, so pad to the fixed duress ceiling to3658  // keep slot B's length equal to slot A's (audit MEDIUM — deniability).3659  const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);3660  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");36613662  await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });3663  // Symmetric with persistSlotA: if the version stamp fails after the decoy3664  // slot committed, restore the prior slot B so a failed decoy-mode save can't3665  // leave disk ahead of the in-memory rollback.3666  try {3667    await stampLocalVaultMutation();3668  } catch (err) {3669    await writeSlot(SLOT_B, slotB).catch(() => {});3670    throw err;3671  }3672}36733674async function persistEntries(3675  reason: VaultSnapshot["reason"] = "local_save",3676): Promise<void> {3677  if (vaultCreatesInFlight) throw new Error("vault_changed");3678  vaultWritesInFlight++;3679  try {3680  if (!derivedKey) throw new Error("vault_locked");36813682  // Reconcile direct soft-delete callers while restoring the previous map if3683  // storage rejects the save.3684  const previousTombstones = tombstones;3685  const pendingTombstones = new Map(tombstones);3686  tombstones = pendingTombstones;3687  reconcileTombstones();3688  try {3689    if (vaultMode === "decoy") {3690      await persistSlotB();3691    } else {3692      await persistSlotA(reason);3693    }3694  } catch (err) {3695    if (tombstones === pendingTombstones) tombstones = previousTombstones;3696    throw err;3697  }3698  buildDomainIndexSync(entries);3699  await refreshLockedSyncState();3700  } finally { vaultWritesInFlight--; }3701}37023703// PB-26-011: drop URLs whose parsed scheme is not http(s) at the storage3704// boundary. Schemeless values (e.g. "github.com") are inert and kept — they3705// pre-date this guard in existing data. Unparseable values are kept: the3706// reviewed render paths never execute them (favicons via _favicon/, domains3707// via tldts); this is defense-in-depth against future sinks.3708function allowHttpUrl(url: string | undefined): string {3709  const trimmed = url?.trim() ?? "";3710  if (!trimmed) return "";3711  try {3712    const parsed = new URL(trimmed);3713    if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return "";3714  } catch {3715    // No scheme to reject.3716  }3717  return trimmed;3718}37193720function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {3721  if (!Array.isArray(values)) return undefined;3722  const seen = new Set<string>();3723  const cleaned: string[] = [];3724  for (const value of values) {3725    const trimmed = typeof value === "string" ? value.trim() : "";3726    if (!trimmed) continue;3727    if (!allowHttpUrl(trimmed)) continue;3728    const key = trimmed.toLowerCase();3729    if (seen.has(key)) continue;3730    seen.add(key);3731    cleaned.push(trimmed);3732  }3733  return cleaned.length > 0 ? cleaned : undefined;3734}37353736function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {3737  const title = entry.title.trim();3738  const type: VaultEntry["type"] = entry.type ?? "login";37393740  if (!title) throw new Error("title is required");37413742  if (entry.passkey) {3743    const p = entry.passkey;3744    if (3745      !p.rpId ||3746      !p.credentialId ||3747      !p.publicKeyCose ||3748      !p.userHandle ||3749      !p.userName ||3750      (p.algorithm !== -7 && p.algorithm !== -8)3751    ) {3752      throw new Error("invalid passkey credential");3753    }3754  }3755  if (type === "card") {3756    if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {3757      throw new Error("cardholder name and card number are required");3758    }3759  }37603761  return {3762    type,3763    title,3764    username: type === "login" ? entry.username?.trim() ?? "" : undefined,3765    email: type === "login" ? entry.email?.trim() || undefined : undefined,3766    password: type === "login" ? entry.password : undefined,3767    url: type === "login" ? allowHttpUrl(entry.url) : undefined,3768    additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,3769    totp: type === "login" ? entry.totp?.trim() || undefined : undefined,3770    // PCH-01-019: preserve non-default TOTP params through batch-add/import so3771    // they are not silently stripped (they fall back to SHA-1/6/30 when absent).3772    totpAlgorithm: type === "login" ? entry.totpAlgorithm : undefined,3773    totpDigits: type === "login" ? entry.totpDigits : undefined,3774    totpPeriod: type === "login" ? entry.totpPeriod : undefined,3775    notes: entry.notes?.trim() || undefined,3776    breach: type === "login" ? entry.breach : undefined,3777    // PCH-01-016: the batch-add path was bypassing the MV-6 canary/tags3778    // whitelist applied on the RESTORE_ENTRIES path. Run both sanitizers here.3779    canary: type === "login" ? sanitizeCanary(entry.canary) : undefined,3780    tags: sanitizeTags(entry.tags),3781    passkey: entry.passkey,3782    cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,3783    cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,3784    expMonth: type === "card" ? entry.expMonth?.trim() : undefined,3785    expYear: type === "card" ? entry.expYear?.trim() : undefined,3786    cvc: type === "card" ? entry.cvc?.trim() : undefined,3787    cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,3788    network: type === "card" ? entry.network : undefined,3789    last4: type === "card" ? entry.last4?.trim() : undefined,3790  };3791}37923793function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {3794  const nextPatch: Partial<VaultEntry> = {};37953796  if ("type" in patch) {3797    nextPatch.type = patch.type;3798  }37993800  if ("title" in patch) {3801    const title = patch.title?.trim() ?? "";3802    if (!title) throw new Error("title is required");3803    nextPatch.title = title;3804  }38053806  if ("url" in patch) {3807    nextPatch.url = allowHttpUrl(patch.url);3808  }38093810  if ("additionalUrls" in patch) {3811    const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];3812    const seen = new Set<string>();3813    const cleaned: string[] = [];3814    for (const value of incoming) {3815      const trimmed = typeof value === "string" ? value.trim() : "";3816      if (!trimmed || !allowHttpUrl(trimmed)) continue;3817      const key = trimmed.toLowerCase();3818      if (seen.has(key)) continue;3819      seen.add(key);3820      cleaned.push(trimmed);3821    }3822    nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;3823  }38243825  if ("username" in patch) {3826    nextPatch.username = patch.username?.trim() ?? "";3827  }38283829  if ("email" in patch) {3830    nextPatch.email = patch.email?.trim() || undefined;3831  }38323833  if ("password" in patch) {3834    const password = patch.password ?? "";3835    // Allow clearing a password (e.g. on passkey-only entries)3836    nextPatch.password = password || undefined;3837  }38383839  if ("totp" in patch) {3840    nextPatch.totp = patch.totp?.trim() || undefined;3841  }38423843  if ("totpAlgorithm" in patch) {3844    nextPatch.totpAlgorithm = patch.totpAlgorithm;3845  }38463847  if ("totpDigits" in patch) {3848    nextPatch.totpDigits = patch.totpDigits;3849  }38503851  if ("totpPeriod" in patch) {3852    nextPatch.totpPeriod = patch.totpPeriod;3853  }38543855  if ("notes" in patch) {3856    nextPatch.notes = patch.notes?.trim() || undefined;3857  }38583859  if ("breach" in patch) {3860    nextPatch.breach = patch.breach;3861  }38623863  if ("canary" in patch) {3864    // PCH-02-001: route update patches through the same canary whitelist used3865    // by add/restore/sync. Invalid shapes drop the canary; `undefined` clears it.3866    nextPatch.canary = patch.canary ? sanitizeCanary(patch.canary) : undefined;3867  }38683869  if ("passkey" in patch) {3870    // A patch with `passkey: undefined` removes the credential from the entry3871    // (used by "remove passkey" without deleting the whole entry).3872    if (patch.passkey === undefined || patch.passkey === null) {3873      nextPatch.passkey = undefined;3874    } else {3875      const sanitized = sanitizePasskey(patch.passkey);3876      if (!sanitized) throw new Error("invalid passkey credential");3877      nextPatch.passkey = sanitized;3878    }3879  }38803881  if ("tags" in patch) {3882    // PCH-02-001: bound tags exactly like both import funnels.3883    nextPatch.tags = sanitizeTags(patch.tags);3884  }38853886  if ("cardholderName" in patch) {3887    nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;3888  }3889  if ("cardNumber" in patch) {3890    const n = patch.cardNumber ?? "";3891    nextPatch.cardNumber = n || undefined;3892  }3893  if ("expMonth" in patch) {3894    nextPatch.expMonth = patch.expMonth?.trim() || undefined;3895  }3896  if ("expYear" in patch) {3897    nextPatch.expYear = patch.expYear?.trim() || undefined;3898  }3899  if ("cvc" in patch) {3900    nextPatch.cvc = patch.cvc?.trim() || undefined;3901  }3902  if ("cardNickname" in patch) {3903    nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;3904  }3905  if ("network" in patch) {3906    nextPatch.network = patch.network;3907  }3908  if ("last4" in patch) {3909    nextPatch.last4 = patch.last4?.trim() || undefined;3910  }39113912  return nextPatch;3913}39143915function normalizeEntry(entry: VaultEntry): VaultEntry {3916  const base: VaultEntry = {3917    id: entry.id,3918    type: entry.type,3919    title: entry.title,3920    username: entry.username,3921    email: entry.email,3922    password: entry.password,3923    url: entry.url,3924    additionalUrls:3925      "additionalUrls" in entry && Array.isArray(entry.additionalUrls)3926        ? entry.additionalUrls3927        : undefined,3928    totp: entry.totp,3929    // PCH-01-019: carry TOTP params through the normalize/restore path too.3930    totpAlgorithm: entry.totpAlgorithm,3931    totpDigits: entry.totpDigits,3932    totpPeriod: entry.totpPeriod,3933    notes: entry.notes,3934    breach: entry.breach,3935    // Preserve the password-age clock across lock/unlock. Without this the3936    // field is dropped on every decode and the advanced-health "aged password"3937    // signal silently resets to createdAt on each unlock (SEV-2-A).3938    passwordChangedAt:3939      "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,3940    // Preserve past-password history across lock/unlock. normalizeEntry is a3941    // field whitelist, so an unlisted field is silently dropped on every decode3942    // (same class as the passwordChangedAt SEV-2-A above).3943    passwordHistory:3944      "passwordHistory" in entry && Array.isArray(entry.passwordHistory)3945        ? entry.passwordHistory3946        : undefined,3947    canary: entry.canary,3948    passkey: entry.passkey,3949    createdAt: entry.createdAt,3950    modifiedAt: entry.modifiedAt,3951    deletedAt: entry.deletedAt,3952    tags: entry.tags,3953    cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,3954    cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,3955    expMonth: "expMonth" in entry ? entry.expMonth : undefined,3956    expYear: "expYear" in entry ? entry.expYear : undefined,3957    cvc: "cvc" in entry ? entry.cvc : undefined,3958    cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,3959    network: "network" in entry ? entry.network : undefined,3960    last4: "last4" in entry ? entry.last4 : undefined,3961  };39623963  return base;3964}396539663967// ---------------------------------------------------------------------------3968// Deduplication3969// ---------------------------------------------------------------------------39703971function entryDupeKey(e: VaultEntry): string {3972  if (e.passkey) {3973    // Equal identities can still carry different passwords, notes or TOTP data.3974    const content = Object.fromEntries(Object.entries(e)3975      .filter(([key]) => key !== "id" && key !== "createdAt" && key !== "modifiedAt")3976      .sort(([a], [b]) => a.localeCompare(b)));3977    return `passkey|${e.passkey.rpId}|${e.passkey.credentialId}|${JSON.stringify(content)}`;3978  }3979  if (e.type === "note") return `note|${e.title.toLowerCase()}`;3980  return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;3981}39823983/** Returns the number of duplicate entries (those that would be removed). */3984export function countDuplicates(): number {3985  const best = new Map<string, VaultEntry>();3986  let dupeCount = 0;3987  for (const e of entries.filter((e) => !e.deletedAt)) {3988    const key = entryDupeKey(e);3989    const existing = best.get(key);3990    if (!existing) {3991      best.set(key, e);3992    } else {3993      dupeCount++;3994      // Keep the more recently modified one in the map3995      if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3996        best.set(key, e);3997      }3998    }3999  }4000  return dupeCount;4001}40024003/**4004 * Soft-deletes duplicate entries, keeping the most recently modified copy of4005 * each group. Returns the number of entries moved to trash.4006 */4007export async function deduplicateEntries(): Promise<number> {4008  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");4009  // Dedup reshapes slot B permanently under the decoy key, which is4010  // forensically distinguishable from a freshly-seeded decoy vault. Refuse.4011  if (vaultMode === "decoy") {4012    throw new Error("deduplicate disabled in decoy mode");4013  }40144015  const best = new Map<string, VaultEntry>();4016  for (const e of entries.filter((en) => !en.deletedAt)) {4017    const key = entryDupeKey(e);4018    const existing = best.get(key);4019    if (!existing) {4020      best.set(key, e);4021    } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {4022      best.set(key, e);4023    }4024  }40254026  const keepIds = new Set(Array.from(best.values()).map((e) => e.id));4027  let removed = 0;4028  entries = entries.map((e) => {4029    if (!e.deletedAt && !keepIds.has(e.id)) {4030      removed++;4031      const deletedAt = monotonicEntryTimestamp(Math.max(4032        e.modifiedAt,4033        tombstones.get(e.id) ?? 0,4034      ));4035      tombstones.set(e.id, deletedAt);4036      return { ...e, deletedAt };4037    }4038    return e;4039  });40404041  if (removed > 0) await persistEntries();4042  return removed;4043}40444045// ---------------------------------------------------------------------------4046// Vault history — snapshot BEFORE every vault write so the saved blob is4047// what is about to be lost, not what was just written. Capped at 5. The4048// stored blobs are AES-256-GCM ciphertext under the master password, so4049// history adds zero security surface.4050// ---------------------------------------------------------------------------40514052const HISTORY_KEY = "peach_vault_history";4053const HISTORY_MAX = 5;40544055// PCH-01-023: coarsen a live-entry count into a low-resolution bucket so the4056// plaintext snapshot field cannot reveal exact vault size or single-entry change4057// deltas. Buckets widen as the vault grows so absolute leakage stays roughly4058// proportional rather than exact.4059function bucketEntryCount(n: number): number {4060  if (n <= 0) return 0;4061  if (n <= 10) return 10;4062  if (n <= 25) return 25;4063  if (n <= 50) return 50;4064  if (n <= 100) return 100;4065  if (n <= 250) return 250;4066  if (n <= 500) return 500;4067  return Math.ceil(n / 500) * 500;4068}40694070/**4071 * Snapshot the CURRENT on-disk vault state into history. Call this BEFORE4072 * overwriting peach_vault_a so the saved blob captures the about-to-be-lost4073 * state. Identical-to-most-recent blobs are skipped to avoid filling history4074 * with no-op writes.4075 */4076export async function takeVaultSnapshot(4077  reason: VaultSnapshot["reason"],4078): Promise<void> {4079  if (recoveryInFlight || vaultCreatesInFlight) return;4080  // The history store is real-mode state by construction, so it must not be4081  // written from a decoy session either. The guard lives here rather than only4082  // at the call sites so the invariant survives a new caller (PB-26-915).4083  if (vaultMode === "decoy") return;4084  vaultWritesInFlight++;4085  try {4086    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);4087    const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];4088    const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];40894090    // Nothing to snapshot if the real slot doesn't exist yet (fresh install,4091    // pre-createVault). createVault skips snapshots intentionally — there is4092    // no prior state to preserve.4093    if (!slotA) return;40944095    const vault_a = JSON.stringify(slotA);4096    const vault_b = JSON.stringify(slotB ?? slotA);40974098    // Best-effort entry count: only meaningful when the in-memory state is4099    // unlocked AND in real mode. Decoy mode would leak the decoy entry4100    // count; locked mode has no entries to count. Both fall through to null.4101    // PCH-01-023: store a coarse bucket, not the exact count — chrome.storage4102    // .local sits next to the AES-GCM blobs in plaintext, so an exact count would4103    // leak vault size and per-write deltas (the metadata padding hides this).4104    let entryCount: number | null = null;4105    if (derivedKey && vaultMode === "real") {4106      try {4107        entryCount = bucketEntryCount(entries.filter((e) => !e.deletedAt).length);4108      } catch {4109        entryCount = null;4110      }4111    }41124113    const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];4114    const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)4115      ? existingRaw4116      : { snapshots: [] };41174118    // Deduplication: if the most recent snapshot has byte-identical blobs,4119    // skip — saves the same vault N times in a row would otherwise burn the4120    // entire history window with no recovery value.4121    const latest = history.snapshots[0];4122    if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {4123      return;4124    }41254126    const snapshot: VaultSnapshot = {4127      id: crypto.randomUUID(),4128      savedAt: Date.now(),4129      reason,4130      vault_a,4131      vault_b,4132      entryCount,4133    };41344135    history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);4136    if (recoveryInFlight || vaultCreatesInFlight) return;4137    await chrome.storage.local.set({ [HISTORY_KEY]: history });4138  } catch (err) {4139    // Non-fatal — history must never block a save. A failed snapshot just4140    // means the user loses one rung of the safety ladder for this write.4141    // M4/QUA-006: log so the failure is visible; if it looks like a quota4142    // problem, notify the popup so the user can prune history themselves.4143    console.warn('[Peach] takeVaultSnapshot failed:', err);4144    if (String(err).includes('QUOTA') || String(err).includes('quota')) {4145      try {4146        await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });4147      } catch {4148        // popup may be closed; surfaced via console.warn above4149      }4150    }4151  } finally { vaultWritesInFlight--; }4152}41534154/** Wipe all vault history. Called by Panic / DESTROY_VAULT. */4155export async function clearVaultHistory(): Promise<void> {4156  if (recoveryInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");4157  vaultWritesInFlight++;4158  try {4159    await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });4160  } catch {4161    // Non-fatal — DESTROY_VAULT also runs storage.local.clear().4162  } finally { vaultWritesInFlight--; }4163}41644165/** Read all snapshots, newest first, for the Settings vault history view. */4166export async function getVaultHistory(): Promise<VaultSnapshot[]> {4167  if (vaultMode === "decoy") return [];4168  const raw = await chrome.storage.local.get(HISTORY_KEY);4169  const value = (raw as Record<string, unknown>)[HISTORY_KEY];4170  return sanitizeHistory(value);4171}41724173/**4174 * Replace the on-disk vault with the chosen snapshot's blobs and lock the4175 * vault. The current state is itself snapshotted before replacement.4176 */4177export async function restoreVaultSnapshot(4178  snapshotId: string,4179): Promise<{ ok: true } | { ok: false; error: string }> {4180  if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "vault_changed" };4181  vaultReplacementInFlight = true;4182  try {4183    if (vaultMode === "decoy") return { ok: false, error: "vault_locked" };4184    const history = await getVaultHistory();4185    const snapshot = history.find((s) => s.id === snapshotId);4186    if (!snapshot) return { ok: false, error: "snapshot_not_found" };41874188    const restoredA = parseHistorySlot(snapshot.vault_a);4189    const restoredB = parseHistorySlot(snapshot.vault_b);4190    if (!restoredA || !restoredB) return { ok: false, error: "snapshot_corrupt" };41914192    await takeVaultSnapshot("restore");4193    const current = await chrome.storage.local.get([SLOT_A, SLOT_B]);4194    const previousA = (current as Record<string, unknown>)[SLOT_A];4195    const previousB = (current as Record<string, unknown>)[SLOT_B];4196    try {4197      if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };4198      await chrome.storage.local.set({ [SLOT_A]: restoredA, [SLOT_B]: restoredB });4199      await stampLocalVaultMutation();4200    } catch {4201      try {4202        await chrome.storage.local.set({ [SLOT_A]: previousA, [SLOT_B]: previousB });4203      } catch {4204        // Preserve the restore failure if storage cannot complete the rollback.4205      }4206      return { ok: false, error: "snapshot_corrupt" };4207    }42084209    await lock();4210    return { ok: true };4211  } finally {4212    vaultReplacementInFlight = false;4213  }4214}42154216/**4217 * Rotate the vault's sync identity by generating a FRESH ROOT KEY and4218 * re-wrapping everything under it (MV-8). Because every sync credential —4219 * vault_id, the Noise static keypair, the Ed25519 manifest signing key,4220 * and the per-entry envelope keys — derives from the root key, rotation4221 * makes a lost/stolen device's retained key material useless. All paired4222 * devices must re-pair afterwards.4223 *4224 * CONSEQUENCE THE UI MUST SURFACE: the 12 recovery words also derive from4225 * the root key, so rotation INVALIDATES the old recovery phrase. The flow4226 * sets peach_recovery_pending so the popup re-presents the new words for4227 * confirmation, same as the initial recovery-word confirmation path.4228 */4229export async function rotateSyncIdentity(): Promise<{ ok: boolean; error?: string }> {4230  if (vaultCreatesInFlight) throw new Error("vault_changed");4231  const rotationEpoch = vaultEpoch;4232  const removalEpoch = vaultRemovalEpoch;4233  vaultWritesInFlight++;4234  try {4235  if (!derivedKey || vaultMode !== "real") {4236    return { ok: false, error: "vault_locked" };4237  }4238  const slotA = await loadSlot(SLOT_A);4239  if (!slotA) return { ok: false, error: "missing_slot_a" };42404241  // 1. Fresh root key + recovery escrow (new words).4242  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =4243    await generateAndWrapRootKey();42444245  // 2. Re-wrap the new root key under the current password-derived key.4246  const newRootKey = unhex(rawRootKey);4247  const recoveryVaultKey = await encrypt(newRootKey, hex(derivedKey), "recovery_vault_key_v1");4248  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, newRootKey);42494250  // 3. Snapshot, then single atomic slot write — both escrow wrappings of4251  //    the new root key land together (same transactional rule as4252  //    changePassword). Entries are untouched: they are sealed under the4253  //    password-derived key, not the root key.4254  await takeVaultSnapshot("local_save");4255  const nextSlotA: StoredVault = {4256    ...slotA,4257    recovery_vault_key: recoveryVaultKey,4258    recovery_salt: recoverySalt,4259    recovery_wrapped_root_key: wrappedRootKey,4260    recovery_nonce: wrappedNonce,4261    recovery_tag: wrappedTag,4262    ...pwRoot,4263  };4264  await writeSlot(SLOT_A, nextSlotA);42654266  // 4. Swap in memory only after disk committed.4267  if (rotationEpoch === vaultEpoch && derivedKey && rootKey) {4268    const oldRootKey = rootKey;4269    // The old root must stay live until the recall member is re-sealed: a queued4270    // write encrypts with the bytes it captured, so zeroing in place first would4271    // seal it under an all-zero key. Both the re-key and the swap run inside the4272    // recall queue so no write can interleave with either.4273    await serializeRecallMutation(async () => {4274      await rekeyManualSummonRecall(oldRootKey, newRootKey).catch((error) => {4275        console.warn("[Peach] manual-summon recall re-key failed:", error);4276      });4277      if (rootKey === oldRootKey) {4278        rootKey = newRootKey;4279        zeroKey(oldRootKey);4280      } else {4281        zeroKey(newRootKey);4282      }4283    });4284  } else {4285    zeroKey(newRootKey);4286  }42874288  // 4b. The identity's root wrap was encrypted under the dead root. Without4289  //     this the identity survives only until the unlock key also changes.4290  await notifyIdentityKeysRotated();42914292  // 5. Old peers' identities derive from the dead root key — drop them all,4293  // with their rendezvous secrets (PB-26-213: rotation clears the map, so4294  // there is nothing to rewrap under the new key).4295  await clearPairedDevices();4296  await clearPairSecrets();42974298  // 6. Force re-presentation of the NEW recovery words on next popup view.4299  if (removalEpoch === vaultRemovalEpoch) {4300    await setRecoveryConfirmPending(rotationEpoch === vaultEpoch && isUnlocked());4301    touchAutoLock();4302  }43034304  await stampLocalVaultMutation();4305  return { ok: true };4306  } finally { vaultWritesInFlight--; }4307}43084309/**4310 * Change the master password. Re-encrypts slot A with a fresh salt + new4311 * derived key. Slot B (duress or noise) is left untouched when duress is4312 * configured — it uses an independent key derived from the duress password —4313 * and regenerated as noise when duress is not configured.4314 */4315export async function changePassword(4316  currentPassword: string,4317  newPassword: string4318): Promise<boolean> {4319  if (vaultCreatesInFlight) throw new Error("vault_changed");4320  vaultWritesInFlight++;4321  try {43224323  const epoch = vaultEpoch;4324  const stale = () => epoch !== vaultEpoch;4325  if (!derivedKey || vaultMode !== "real") return false;43264327  // Verify current password before allowing any change4328  const valid = await verifyMainPassword(currentPassword);4329  if (!valid) return false;43304331  const slotA = await loadSlot(SLOT_A);4332  if (!slotA) return false;4333  if (!rootKey) return false;43344335  // Derive fresh key from new password + new random salt4336  const newSalt = generateSalt();4337  const newKey = await deriveKey(newPassword, newSalt);4338  if (stale()) {4339    zeroKey(newKey);4340    return false;4341  }43424343  // Re-encrypt the in-memory entries with the new key4344  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);4345  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");43464347  // Pre-wrap root key under the new derived key. Recovery fields wrap rootKey4348  // under recovery words and remain untouched — recovery phrase keeps working4349  // across password changes (H4/COR-002).4350  const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);43514352  const recoveryVaultKey = await encrypt(rootKey, hex(newKey), "recovery_vault_key_v1");4353  const finalSlotA: StoredVault = {4354    ...slotA,4355    recovery_vault_key: recoveryVaultKey,4356    salt: hex(newSalt),4357    nonce,4358    ciphertext,4359    tag,4360    ...pwRoot,4361  };43624363  // Snapshot the OLD-key blob before overwriting it. If the user later4364  // restores from this snapshot they will need the OLD password — the4365  // post-restore lock surfaces that immediately.4366  await takeVaultSnapshot("local_save");43674368  // Single atomic write: ciphertext, salt, and pw_root_* fields all land in4369  // one storage transaction. An SW kill before this point leaves the old4370  // slot intact; after this point everything tied to the new password is4371  // already on disk together (M6/COR-004).4372  await writeSlot(SLOT_A, finalSlotA);4373  if (stale()) {4374    zeroKey(newKey);4375    return false;4376  }43774378  // Swap the in-memory key synchronously before any further await. If we4379  // threw between the Slot A write and this swap, the next persistEntries()4380  // would overwrite Slot A with old-key ciphertext, locking the user out.4381  zeroKey(derivedKey);4382  cancelBreachScan();4383  derivedKey = newKey;43844385  // PCH-01-008: the MV3 session escrow still holds the OLD key. Without this,4386  // the next service-worker restore decrypts the new-key Slot A with the stale4387  // key, fails tryDecryptSlotResult, and silently drops the user to a lock4388  // screen. Re-escrow the new key so restore survives a password change.4389  if (stale()) {4390    await lock();4391    return false;4392  }4393  await saveSessionKey(newKey, "real", epoch);4394  if (stale()) return false;43954396  // The identity envelope holds one wrap per recovering key. Swapping the4397  // unlock key kills the local wrap, so re-wrap now or the next key swap4398  // orphans the identity -- and until then the old password still opens it.4399  await notifyIdentityKeysRotated();4400  if (stale()) return false;44014402  // Regenerate noise for slot B when duress is not in use. Runs after the4403  // key swap so a failure here is a disposable noise regeneration, not a4404  // lockout.4405  if (!duressConfigured) {4406    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));4407  }4408  await clearPinUnlockStorage();4409  await stampLocalVaultMutation();44104411  return true;4412  } finally { vaultWritesInFlight--; }4413}