vault.ts

165.2 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";5960// Plaintext is padded to the next multiple of this size before encryption.61// This coarsens ciphertext-length leakage into 1 KiB buckets.62const PAD_BLOCK = 1024;6364// How many past passwords to retain per entry. Generous enough to be useful as65// a recovery aid while bounding the secret material we hold (and the ciphertext66// growth) for an entry whose password is rotated frequently.67const PASSWORD_HISTORY_MAX = 50;6869// When duress is configured, BOTH slots are padded to this fixed ceiling so70// their ciphertext lengths are identical and cannot reveal that a hidden decoy71// vault exists (audit MEDIUM — plausible-deniability leak). 256 KiB comfortably72// holds a very large vault (thousands of entries incl. passkeys). The decoy73// slot can't be re-encrypted on every real-vault save (the real session has no74// decoy key), so a fixed ceiling — rather than size-matching on each write — is75// what keeps the two slots equal. A real vault whose plaintext exceeds this76// would grow past the ceiling and re-expose the bit; that is an extreme,77// documented edge well beyond normal use.78const DURESS_SLOT_SIZE = 262_144;7980let derivedKey: Uint8Array | null = null;81// 32-byte random root key, separate from the derivedKey used for vault encryption.82// The root key is wrapped (encrypted) under the recovery key derived from the83// 12-word phrase. When the user changes their password, only the wrapping changes;84// the root key and recovery words remain stable.85let rootKey: Uint8Array | null = null;86let recoveryInFlight = false;87let recoverySettled: Promise<void> = Promise.resolve();88let vaultRemovalsInFlight = 0;89let vaultRemovalEpoch = 0;90let vaultWritesInFlight = 0;91let vaultCreatesInFlight = 0;92let creationSettled: Promise<void> = Promise.resolve();93let vaultUnlocksInFlight = 0;94let vaultReplacementInFlight = false;95let entries: VaultEntry[] = [];96// Tombstones outlive their full entry records so a peer that was offline97// during a purge cannot reintroduce an old ciphertext envelope. This map is98// serialized only inside the encrypted vault payload.99let tombstones = new Map<string, number>();100let domainIndex: Map<string, VaultEntry[]> = new Map();101let vaultMode: "real" | "decoy" = "real";102// Cached post-unlock view of whether the real vault records that duress is103// configured. Only meaningful after a real-mode unlock; for decoy-mode unlock104// this stays false because we never see slot A's plaintext.105let duressConfigured = false;106107// Set to a corruption reason during the last unlock() attempt when both slots108// decrypted but failed schema validation. Consumed and cleared by109// consumeLastUnlockFailureReason() so messages.ts can surface vault_corrupted110// distinctly from wrong-password (M7/COR-007).111//112// NOTE: module-level state — if vault.ts is ever moved to a worker context,113// this must be replaced with a structured return value from unlock() or a114// postMessage channel. The signal is invisible across module-instance115// boundaries.116let lastUnlockFailureReason: string | null = null;117118export function consumeLastUnlockFailureReason(): string | null {119  const r = lastUnlockFailureReason;120  lastUnlockFailureReason = null;121  return r;122}123124// ---------------------------------------------------------------------------125// Settings (persisted inside the encrypted vault store as a sidecar key)126// ---------------------------------------------------------------------------127128export type TextSize = "small" | "medium" | "large";129130export interface VaultSettings {131  accentColor?: AccentColorName;132  theme?: "dark" | "light";133  autoLockMinutes?: number;134  clipboardClearSeconds?: number;135  lockOnClose?: boolean;136  breachMonitoring?: boolean;137  passkeyProviderEnabled?: boolean;138  trashRetentionDays?: number;139  manualSummonDomains?: Record<string, ManualSummonRecord>;140  manualSummonSalt?: string;141  declinedCardFingerprints?: string[];142143  /** Metadata is bounded because it remains outside the encrypted vault blob. */144  metadataVersion?: 1;145  /**146   * Text size scale for body copy and entry titles. Stops at "large" by147   * design — XL clips dense screens (Vault, Health) inside the fixed148   * 330×480 popup surface.149   */150  textSize?: TextSize;151  /**152   * When true, all entrance/exit transitions and ambient animations are153   * collapsed to instant. Honoured alongside the user's OS-level154   * `prefers-reduced-motion`.155   */156  reduceMotion?: boolean;157  /** Require an unlock after a worker restart before locked Sync resumes. */158  lockedSyncRequiresUnlock?: boolean;159  /** Whether this vault has a local PIN unlock wrapper configured. */160  pinEnabled?: boolean;161  /** Whether the lock screen should open on PIN instead of the password. */162  pinPreferred?: boolean;163  /**164   * User overrides for keyboard shortcuts. Keys are ShortcutAction names165   * (see src/shared/shortcuts.ts). Missing actions fall through to166   * DEFAULT_BINDINGS — `getActiveBindings(settings.shortcuts)` is the167   * canonical lookup. Storing only the deltas keeps the vault payload168   * small and lets default updates land for users who never rebind.169   */170  shortcuts?: Record<string, { key: string; ctrl?: boolean; meta?: boolean; shift?: boolean; alt?: boolean }>;171}172173interface StoredPinWrap {174  version: 1;175  salt: string;176  nonce: string;177  ciphertext: string;178  tag: string;179}180181const PIN_WRAP_STORAGE = "peach_pin_wrap";182const PIN_ATTEMPTS_STORAGE = "peach_pin_attempts";183const PIN_MIN_LENGTH = 4;184const PIN_MAX_LENGTH = 12;185const PIN_MAX_ATTEMPTS = 3;186187let settings: VaultSettings = {};188const CARD_DECLINE_MAX = 256;189/** Hex length of a keyed card-decline digest. Legacy records are 16 hex. */190const CARD_DECLINE_DIGEST_HEX = 32;191192async function metadataDigest(value: string, key: string): Promise<string> {193  const bytes = new TextEncoder().encode(`${key}:${value}`);194  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));195  return Array.from(digest.slice(0, 16)).map((byte) => byte.toString(16).padStart(2, "0")).join("");196}197198let inMemoryPinWrap: StoredPinWrap | null = null;199let inMemoryPinFailedAttempts = 0;200let sessionPinStorageFailed = false;201202export function getSettings(): VaultSettings {203  return settings;204}205206export async function ensureSettingsLoaded(): Promise<VaultSettings> {207  await loadSettings();208  return settings;209}210211export async function updateSettings(patch: Partial<VaultSettings>): Promise<void> {212  await loadSettings();213  // LV-7: cheap insurance against prototype pollution if a future caller ever214  // feeds parsed external JSON here (native spread keeps __proto__ an own-215  // property today, but Object.assign-style consumers and JSON revivers have216  // been burned before).217  // `manualSummonDomains`/`manualSummonSalt` are legacy plaintext recall that218  // only the adoption path may clear; an external patch must not write them.219  const safe = Object.fromEntries(220    Object.entries(patch).filter(221      ([k]) => ![222        "__proto__", "constructor", "prototype",223        "manualSummonDomains", "manualSummonSalt",224      ].includes(k),225    ),226  ) as Partial<VaultSettings>;227  settings = { ...settings, ...safe };228  await persistSettings();229}230231function isValidPin(pin: string): boolean {232  return new RegExp(`^\\d{${PIN_MIN_LENGTH},${PIN_MAX_LENGTH}}$`).test(pin);233}234235/** Set up a local PIN wrapper after proving the current master password. */236export async function setupPinUnlock(currentPassword: string, pin: string): Promise<boolean> {237  if (vaultCreatesInFlight) return false;238  vaultWritesInFlight++;239  try {240  if (!derivedKey || vaultMode !== "real" || !isValidPin(pin)) return false;241  if (!(await verifyMainPassword(currentPassword))) return false;242243  const salt = generateSalt();244  const pinKey = await deriveKey(pin, salt);245  try {246    const wrapped = await encrypt(pinKey, hex(derivedKey), "pin_wrap_v1");247    await savePinWrap({ version: 1, salt: hex(salt), ...wrapped });248    await updateSettings({ pinEnabled: true });249    return true;250  } finally {251    zeroKey(pinKey);252  }253  } finally { vaultWritesInFlight--; }254}255256async function clearPinUnlockStorage(): Promise<void> {257  inMemoryPinWrap = null;258  inMemoryPinFailedAttempts = 0;259  sessionPinStorageFailed = false;260  if (chrome.storage.session) {261    await chrome.storage.session.remove([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);262  }263  await updateSettings({ pinEnabled: false });264}265266/** Remove the PIN wrapper after proving the current master password. */267export async function disablePinUnlock(currentPassword: string): Promise<boolean> {268  if (vaultCreatesInFlight) return false;269  vaultWritesInFlight++;270  try {271  if (!derivedKey || vaultMode !== "real") return false;272  if (!(await verifyMainPassword(currentPassword))) return false;273  await clearPinUnlockStorage();274  return true;275  } finally { vaultWritesInFlight--; }276}277278/** Unlock the real vault from its locally stored PIN-wrapped derived key. */279export async function unlockWithPin(pin: string): Promise<boolean> {280  vaultUnlocksInFlight++;281  try {282  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;283  if (!isValidPin(pin)) return false;284  await loadSettings();285  if (!settings.pinEnabled) return false;286287  const { stored, failedAttempts } = await loadPinState();288  if (failedAttempts >= PIN_MAX_ATTEMPTS) return false;289  if (290    !stored ||291    stored.version !== 1 ||292    !stored.salt ||293    !stored.nonce ||294    !stored.ciphertext ||295    !stored.tag296  ) return false;297298  const pinKey = await deriveKey(pin, unhex(stored.salt));299  let unwrappedKey: Uint8Array | null = null;300  try {301    const masterKeyHex = await decrypt(302      pinKey,303      stored.nonce,304      stored.ciphertext,305      stored.tag,306      "pin_wrap_v1",307    );308    if (!/^[0-9a-f]{64}$/.test(masterKeyHex)) return false;309    unwrappedKey = unhex(masterKeyHex);310    const result = await unlockWithKey(masterKeyHex);311    if (!result.ok) return false;312    await resetPinFailedAttempts();313    return true;314  } catch {315    await recordPinFailure(failedAttempts + 1);316    return false;317  } finally {318    zeroKey(pinKey);319    if (unwrappedKey) zeroKey(unwrappedKey);320  }321  } finally { vaultUnlocksInFlight--; }322}323324async function savePinWrap(stored: StoredPinWrap): Promise<void> {325  inMemoryPinWrap = stored;326  inMemoryPinFailedAttempts = 0;327  sessionPinStorageFailed = !chrome.storage.session;328  if (!chrome.storage.session) return;329  try {330    await chrome.storage.session.set({ [PIN_WRAP_STORAGE]: stored, [PIN_ATTEMPTS_STORAGE]: 0 });331    sessionPinStorageFailed = false;332  } catch {333    // Firefox fallback: keep the wrapper only in this background context.334    sessionPinStorageFailed = true;335  }336}337338async function loadPinState(): Promise<{339  stored: StoredPinWrap | undefined;340  failedAttempts: number;341}> {342  if (!chrome.storage.session) {343    return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };344  }345  try {346    const result = await chrome.storage.session.get([PIN_WRAP_STORAGE, PIN_ATTEMPTS_STORAGE]);347    return {348      stored: (result[PIN_WRAP_STORAGE] as StoredPinWrap | undefined) ??349        (sessionPinStorageFailed ? inMemoryPinWrap ?? undefined : undefined),350      failedAttempts: typeof result[PIN_ATTEMPTS_STORAGE] === "number"351        ? result[PIN_ATTEMPTS_STORAGE]352        : 0,353    };354  } catch {355    return { stored: inMemoryPinWrap ?? undefined, failedAttempts: inMemoryPinFailedAttempts };356  }357}358359async function recordPinFailure(failedAttempts: number): Promise<void> {360  inMemoryPinFailedAttempts = Math.min(failedAttempts, PIN_MAX_ATTEMPTS);361  if (!chrome.storage.session) return;362  try {363    await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: inMemoryPinFailedAttempts });364  } catch { /* in-memory counter remains the fallback */ }365}366367async function resetPinFailedAttempts(): Promise<void> {368  inMemoryPinFailedAttempts = 0;369  if (!chrome.storage.session) return;370  try {371    await chrome.storage.session.set({ [PIN_ATTEMPTS_STORAGE]: 0 });372  } catch { /* in-memory counter remains the fallback */ }373}374375export async function getPinUnlockStatus(): Promise<{376  configured: boolean;377  available: boolean;378  attemptsRemaining: number;379}> {380  await loadSettings();381  if (!settings.pinEnabled) {382    return { configured: false, available: false, attemptsRemaining: 0 };383  }384  const { stored, failedAttempts } = await loadPinState();385  const available = Boolean(stored) && failedAttempts < PIN_MAX_ATTEMPTS;386  return {387    configured: true,388    available,389    attemptsRemaining: stored ? Math.max(0, PIN_MAX_ATTEMPTS - failedAttempts) : 0,390  };391}392393async function persistSettings(): Promise<void> {394  try {395    await chrome.storage.local.set({396      peach_settings: {397        // Legacy plaintext recall is carried through every settings write until398        // adoption commits the encrypted copy and clears it explicitly.399        ...settings,400        cardFingerprintSalt: undefined,401        declinedCardFingerprints: settings.declinedCardFingerprints ?? [],402        metadataVersion: 1,403      },404    });405  } catch (err) {406    throw mapStorageError(err);407  }408}409410function mapStorageError(err: unknown): Error {411  const message = err instanceof Error ? err.message : String(err);412  if (/QUOTA_BYTES|quota/i.test(message)) {413    return new Error("STORAGE_QUOTA_EXCEEDED");414  }415  return err instanceof Error ? err : new Error(message);416}417418async function loadSettings(): Promise<void> {419  const result = await chrome.storage.local.get("peach_settings");420  settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};421}422423/** Drop the legacy plaintext recall only once its encrypted copy committed. */424async function clearLegacyManualSummonPlaintext(): Promise<void> {425  settings = { ...settings, manualSummonDomains: undefined, manualSummonSalt: undefined };426  await persistSettings();427}428429// ---------------------------------------------------------------------------430// Manual-summon recall (encrypted Browser-local state)431// ---------------------------------------------------------------------------432433// One storage key holds one sealed member per vault mode. The real member is434// sealed under the vault root key so it survives password changes; slot B has435// no root key, so the decoy member uses that session's decoy vault key. The436// distinct AAD contexts stop one mode from opening the other's member.437const RECALL_STORAGE = "peach_manual_summon_recall_v1";438const RECALL_REAL_AAD = "manual_summon_recall_v1";439const RECALL_DECOY_AAD = "manual_summon_recall_decoy_v1";440const RECALL_MAX_RECORDS = 256;441const RECALL_DOMAIN_MAX_BYTES = 253;442// Summon timestamps come from the device clock; anything further ahead than443// this is corrupt or forged data, not a real summon.444const RECALL_MAX_CLOCK_SKEW_MS = 5 * 60_000;445446interface SealedRecall {447  nonce: string;448  ciphertext: string;449  tag: string;450}451452interface StoredRecall {453  v: 1;454  real?: SealedRecall;455  decoy?: SealedRecall;456}457458let manualSummonRecall = new Map<string, ManualSummonRecord>();459let recallMutation: Promise<void> = Promise.resolve();460461function isValidRecallDomain(domain: unknown): domain is string {462  return typeof domain === "string" && domain.length > 0 &&463    new TextEncoder().encode(domain).length <= RECALL_DOMAIN_MAX_BYTES;464}465466function sanitizeSummonRecord(value: unknown, now: number): ManualSummonRecord | null {467  if (!value || typeof value !== "object") return null;468  const record = value as Record<string, unknown>;469  const firstSummonedAt = record.firstSummonedAt;470  const lastSummonedAt = record.lastSummonedAt;471  const latestAllowed = now + RECALL_MAX_CLOCK_SKEW_MS;472  for (const timestamp of [firstSummonedAt, lastSummonedAt]) {473    if (474      typeof timestamp !== "number" ||475      !Number.isSafeInteger(timestamp) ||476      timestamp < 0 ||477      timestamp > latestAllowed478    ) {479      return null;480    }481  }482  if (typeof record.summonCount !== "number" || !Number.isFinite(record.summonCount)) {483    return null;484  }485  return {486    firstSummonedAt: firstSummonedAt as number,487    lastSummonedAt: lastSummonedAt as number,488    // Only two aggression levels exist; anything past two is the same state.489    summonCount: Math.min(2, Math.max(1, Math.trunc(record.summonCount))),490  };491}492493function capManualSummonRecall(494  records: Map<string, ManualSummonRecord>,495): Map<string, ManualSummonRecord> {496  if (records.size <= RECALL_MAX_RECORDS) return records;497  const kept = new Map(records);498  while (kept.size > RECALL_MAX_RECORDS) {499    let oldestDomain: string | null = null;500    let oldestAt = Number.POSITIVE_INFINITY;501    for (const [domain, record] of kept) {502      if (record.lastSummonedAt < oldestAt) {503        oldestAt = record.lastSummonedAt;504        oldestDomain = domain;505      }506    }507    if (oldestDomain === null) break;508    kept.delete(oldestDomain);509  }510  return kept;511}512513function sanitizeManualSummonRecall(value: unknown): Map<string, ManualSummonRecord> {514  const records = new Map<string, ManualSummonRecord>();515  if (!value || typeof value !== "object" || Array.isArray(value)) return records;516  const now = Date.now();517  for (const [domain, raw] of Object.entries(value as Record<string, unknown>)) {518    if (!isValidRecallDomain(domain)) continue;519    const record = sanitizeSummonRecord(raw, now);520    if (record) records.set(domain, record);521  }522  return capManualSummonRecall(records);523}524525function readStoredRecall(value: unknown): StoredRecall {526  const stored: StoredRecall = { v: 1 };527  if (!value || typeof value !== "object" || Array.isArray(value)) return stored;528  for (const mode of ["real", "decoy"] as const) {529    const member = (value as Record<string, unknown>)[mode];530    if (!member || typeof member !== "object") continue;531    const sealed = member as Record<string, unknown>;532    if (533      typeof sealed.nonce === "string" &&534      typeof sealed.ciphertext === "string" &&535      typeof sealed.tag === "string"536    ) {537      stored[mode] = { nonce: sealed.nonce, ciphertext: sealed.ciphertext, tag: sealed.tag };538    }539  }540  return stored;541}542543function recallSealContext(): { key: Uint8Array; aad: string } | null {544  if (vaultMode === "decoy") {545    return derivedKey ? { key: derivedKey, aad: RECALL_DECOY_AAD } : null;546  }547  return rootKey ? { key: rootKey, aad: RECALL_REAL_AAD } : null;548}549550function serializeRecallMutation(run: () => Promise<void>): Promise<void> {551  const task = recallMutation.then(run, run);552  recallMutation = task.then(() => undefined, () => undefined);553  return task;554}555556async function readStoredRecallFromDisk(): Promise<StoredRecall> {557  const raw = await chrome.storage.local.get(RECALL_STORAGE);558  return readStoredRecall((raw as Record<string, unknown>)[RECALL_STORAGE]);559}560561// A lock zeroes the keys in place and a root rotation replaces the array, so562// the epoch and mode alone cannot prove a captured key still holds the bytes563// it was captured with.564function recallSealIsCurrent(565  epoch: number,566  mode: "real" | "decoy",567  sealKey: Uint8Array,568): boolean {569  return epoch === vaultEpoch && mode === vaultMode && recallSealContext()?.key === sealKey;570}571572async function loadManualSummonRecall(): Promise<void> {573  const epoch = vaultEpoch;574  const mode = vaultMode;575  const context = recallSealContext();576  manualSummonRecall = new Map();577  if (!context) return;578  let stored: StoredRecall;579  try {580    stored = await readStoredRecallFromDisk();581  } catch (error) {582    console.warn("[Peach] manual-summon recall read failed:", error);583    return;584  }585  if (epoch !== vaultEpoch || mode !== vaultMode) return;586  const member = stored[mode];587  if (!member) return;588  try {589    const plain = await decrypt(context.key, member.nonce, member.ciphertext, member.tag, context.aad);590    if (epoch !== vaultEpoch || mode !== vaultMode) return;591    manualSummonRecall = sanitizeManualSummonRecall(JSON.parse(plain));592  } catch {593    // Fail closed: leave the unreadable member on disk; the next successful594    // write in this mode replaces it.595    manualSummonRecall = new Map();596  }597}598599async function persistManualSummonRecall(): Promise<void> {600  const epoch = vaultEpoch;601  const mode = vaultMode;602  const context = recallSealContext();603  if (!derivedKey || !context) throw new Error("vault_locked");604  const sealKey = context.key;605  let stored: StoredRecall;606  try {607    stored = await readStoredRecallFromDisk();608  } catch (error) {609    throw mapStorageError(error);610  }611  // Merge the committed member first: an unlock still loading recall must not612  // let this write drop records it has not seen yet. The merge stays local so a613  // write that crosses a lock or a mode change publishes nothing.614  let records = manualSummonRecall;615  const existing = stored[mode];616  if (existing) {617    try {618      const plain = await decrypt(sealKey, existing.nonce, existing.ciphertext, existing.tag, context.aad);619      const merged = sanitizeManualSummonRecall(JSON.parse(plain));620      for (const [domain, record] of records) merged.set(domain, record);621      records = capManualSummonRecall(merged);622    } catch {623      // Fail closed on load, replace here: this session's records win.624    }625  }626  if (!recallSealIsCurrent(epoch, mode, sealKey)) throw new Error("vault_locked");627  const sealed = await encrypt(628    sealKey,629    JSON.stringify(Object.fromEntries(records)),630    context.aad,631  );632  if (!recallSealIsCurrent(epoch, mode, sealKey)) throw new Error("vault_locked");633  // Replace only this mode's member; the other mode's ciphertext stays intact.634  stored[mode] = sealed;635  try {636    await chrome.storage.local.set({ [RECALL_STORAGE]: stored });637  } catch (error) {638    throw mapStorageError(error);639  }640  // Committed: a lock that followed is not a failed summon, and the merged view641  // is published only into the session it still belongs to.642  if (recallSealIsCurrent(epoch, mode, sealKey)) manualSummonRecall = records;643}644645/**646 * Re-seal the real member from the retired root to the new one. Rotation calls647 * this inside the recall queue, so no queued write can still be encrypting with648 * the old key bytes when they are zeroed.649 */650async function rekeyManualSummonRecall(651  oldRootKey: Uint8Array,652  newRootKey: Uint8Array,653): Promise<void> {654  const epoch = vaultEpoch;655  const sealIsCurrent = (): boolean =>656    epoch === vaultEpoch && vaultMode === "real" && rootKey === oldRootKey;657  if (!sealIsCurrent()) throw new Error("vault_locked");658  const stored = await readStoredRecallFromDisk();659  let records = manualSummonRecall;660  const existing = stored.real;661  if (existing) {662    try {663      const plain = await decrypt(oldRootKey, existing.nonce, existing.ciphertext, existing.tag, RECALL_REAL_AAD);664      const merged = sanitizeManualSummonRecall(JSON.parse(plain));665      for (const [domain, record] of records) merged.set(domain, record);666      records = capManualSummonRecall(merged);667    } catch {668      // Fail closed on load, replace here: this session's records win.669    }670  }671  if (!existing && records.size === 0) return;672  if (!sealIsCurrent()) throw new Error("vault_locked");673  stored.real = await encrypt(674    newRootKey,675    JSON.stringify(Object.fromEntries(records)),676    RECALL_REAL_AAD,677  );678  if (!sealIsCurrent()) return;679  await chrome.storage.local.set({ [RECALL_STORAGE]: stored });680  if (sealIsCurrent()) manualSummonRecall = records;681}682683/**684 * Adopt recall left as plaintext in `peach_settings` by older builds. Only a685 * successful encrypted write authorises removing the plaintext copy.686 */687async function adoptLegacyManualSummonRecall(): Promise<void> {688  if (vaultMode !== "real" || !rootKey) return;689  const legacy = sanitizeManualSummonRecall(settings.manualSummonDomains);690  if (legacy.size === 0) return;691  const epoch = vaultEpoch;692  const previous = manualSummonRecall;693  const merged = new Map(legacy);694  for (const [domain, record] of previous) merged.set(domain, record);695  manualSummonRecall = capManualSummonRecall(merged);696  try {697    await persistManualSummonRecall();698  } catch (error) {699    if (epoch === vaultEpoch && vaultMode === "real") manualSummonRecall = previous;700    throw error;701  }702  await clearLegacyManualSummonPlaintext();703}704705async function restoreManualSummonRecall(): Promise<void> {706  try {707    await loadSettings();708  } catch (error) {709    console.warn("[Peach] manual-summon recall settings read failed:", error);710    return;711  }712  try {713    await serializeRecallMutation(async () => {714      await loadManualSummonRecall();715      await adoptLegacyManualSummonRecall();716    });717  } catch (error) {718    // Recall is a hint, never a reason to fail an unlock.719    console.warn("[Peach] manual-summon recall migration deferred:", error);720  }721}722723async function clearStoredManualSummonRecall(mode?: "real" | "decoy"): Promise<void> {724  if (mode === undefined) {725    manualSummonRecall = new Map();726    try {727      await chrome.storage.local.remove(RECALL_STORAGE);728    } catch (error) {729      console.warn("[Peach] manual-summon recall cleanup failed:", error);730    }731    return;732  }733  try {734    // Serialized with record writes: this is a read-modify-write of the shared735    // key and must not revert the other member to stale ciphertext.736    await serializeRecallMutation(async () => {737      const stored = await readStoredRecallFromDisk();738      if (!stored[mode]) return;739      delete stored[mode];740      if (stored.real || stored.decoy) {741        await chrome.storage.local.set({ [RECALL_STORAGE]: stored });742      } else {743        await chrome.storage.local.remove(RECALL_STORAGE);744      }745    });746  } catch (error) {747    console.warn("[Peach] manual-summon recall cleanup failed:", error);748  }749}750751/** This domain's recall record, if the current mode has one. */752export function getManualSummonRecord(domain: string): ManualSummonRecord | undefined {753  const recalled = manualSummonRecall.get(domain);754  if (recalled) return recalled;755  // Pre-migration plaintext is real-vault data; a decoy session must not see it.756  if (vaultMode !== "real" || !isValidRecallDomain(domain)) return undefined;757  return sanitizeSummonRecord(settings.manualSummonDomains?.[domain], Date.now()) ?? undefined;758}759760/** Record a manual summons for the caller's own domain and persist it. */761export async function recordManualSummon(domain: string): Promise<void> {762  if (!isValidRecallDomain(domain)) throw new Error("invalid_domain");763  vaultWritesInFlight++;764  try {765    const run = async (): Promise<void> => {766      if (!derivedKey || !recallSealContext()) throw new Error("vault_locked");767      const epoch = vaultEpoch;768      const mode = vaultMode;769      const previous = manualSummonRecall;770      const now = Date.now();771      const existing = previous.get(domain);772      const next = new Map(previous);773      next.set(domain, {774        firstSummonedAt: existing?.firstSummonedAt ?? now,775        summonCount: Math.min(2, (existing?.summonCount ?? 0) + 1),776        lastSummonedAt: now,777      });778      manualSummonRecall = capManualSummonRecall(next);779      try {780        await persistManualSummonRecall();781      } catch (error) {782        if (epoch === vaultEpoch && mode === vaultMode) manualSummonRecall = previous;783        throw error;784      }785    };786    // Serialize read-modify-write pairs so two quick summonses cannot lose one.787    await serializeRecallMutation(run);788  } finally {789    vaultWritesInFlight--;790  }791}792793// Fire-and-forget sync trigger after a committed vault write. A failure here794// must never fail the write that caused it.795function fireSyncTrigger(reason: "vault_change"): void {796  void Promise.resolve()797    .then(() => triggerSyncIfReachable({ reason }))798    .catch(() => {799      /* no sync runner registered, or nothing reachable — non-fatal */800    });801}802export function lockedSyncRequiresUnlock(): boolean {803  return settings.lockedSyncRequiresUnlock === true;804}805806let lockedSyncRefreshHook: (() => Promise<void>) | null = null;807let lockedSyncUnlockHook: (() => Promise<void>) | null = null;808let decoySyncTeardownHook: (() => void) | null = null;809export type IdentityHooks = {810  /** Drop the cached identity: the session is no longer a real unlocked one. */811  onSessionEnded: () => Promise<void>;812  /** Re-wrap the identity under the keys now in force, after a vault key swap. */813  onKeysRotated: () => Promise<void>;814  /** Promote a pre-vault identity once a vault exists, given the password that created it. */815  onVaultCreated: (password: string) => Promise<void>;816};817818let identityHooks: IdentityHooks | null = null;819820export function setIdentityHooks(hooks: IdentityHooks): void {821  identityHooks = hooks;822}823824async function notifyIdentitySessionEnded(): Promise<void> {825  await identityHooks?.onSessionEnded().catch((error) => {826    console.warn("[Peach] local identity cache clear failed:", error);827  });828}829830async function notifyIdentityKeysRotated(): Promise<void> {831  await identityHooks?.onKeysRotated().catch((error) => {832    console.warn("[Peach] local identity re-wrap failed:", error);833  });834}835836export type SealedBox = { nonce: string; ciphertext: string; tag: string };837export type IdentityKeyEnvelope = {838  root?: SealedBox;839  local?: SealedBox;840  pending?: SealedBox;841  pendingSalt?: string;842};843844export function setLockedSyncHooks(hooks: {845  refresh: () => Promise<void>;846  afterUnlock: () => Promise<void>;847  onDecoy?: () => void;848}): void {849  lockedSyncRefreshHook = hooks.refresh;850  lockedSyncUnlockHook = hooks.afterUnlock;851  decoySyncTeardownHook = hooks.onDecoy ?? null;852}853854async function refreshLockedSyncState(): Promise<void> {855  if (vaultMode !== "real" || !rootKey || !lockedSyncRefreshHook) return;856  await lockedSyncRefreshHook().catch((error) => {857    console.warn("[Peach sync] locked spool refresh failed:", error);858  });859}860861// ---------------------------------------------------------------------------862// HIBP breach check (k-anonymity model)863// ---------------------------------------------------------------------------864865export async function checkBreach(password: string, signal?: AbortSignal): Promise<number | null> {866  const controller = new AbortController();867  let timeout: ReturnType<typeof setTimeout> | undefined;868  let onAbort: (() => void) | undefined;869  try {870    const unavailable = new Promise<null>((resolve) => {871      onAbort = () => { controller.abort(); resolve(null); };872      signal?.addEventListener("abort", onAbort, { once: true });873      timeout = setTimeout(onAbort, 8_000);874      if (signal?.aborted) onAbort();875    });876    const lookup = async (): Promise<number | null> => {877      // HIBP's range API requires SHA-1; only the five-character prefix leaves the device.878      const hash = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(password));879      if (controller.signal.aborted) return null;880      const hex = Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, "0")).join("").toUpperCase();881      const res = await fetch(`https://api.pwnedpasswords.com/range/${hex.slice(0, 5)}`, {882        headers: { "Add-Padding": "true" },883        signal: controller.signal,884      });885      if (!res.ok) return null;886      const text = await res.text();887      const lines = text.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");888      let count = 0;889      const seen = new Set<string>();890      for (const line of lines) {891        const match = /^([A-Fa-f0-9]{35}):([0-9]+)$/.exec(line);892        if (!match) return null;893        const suffix = match[1].toUpperCase();894        const value = Number(match[2]);895        if (!Number.isSafeInteger(value) || seen.has(suffix)) return null;896        seen.add(suffix);897        if (suffix === hex.slice(5)) count = value;898      }899      return count;900    };901    return await Promise.race([lookup(), unavailable]);902  } catch {903    return null;904  } finally {905    clearTimeout(timeout);906    if (onAbort) signal?.removeEventListener("abort", onAbort);907  }908}909910type BreachCredential = { id: string; password: string; epoch: number; key: Uint8Array };911const breachChecks = new Map<string, symbol>();912913async function checkEntryBreach(credential: BreachCredential, signal?: AbortSignal): Promise<"unknown" | "unapplied" | number> {914  const { id, password, epoch } = credential;915  const isCurrent = () => {916    const entry = entries.find((entry) => entry.id === id);917    return !signal?.aborted && epoch === vaultEpoch && credential.key === derivedKey && !vaultCreatesInFlight &&918      entry?.type === "login" && !entry.deletedAt && entry.password === password;919  };920  if (!isCurrent()) return "unapplied";921  const token = Symbol();922  breachChecks.set(id, token);923  try {924    const count = await checkBreach(password, signal);925    const idx = entries.findIndex((entry) => entry.id === id);926    const current = entries[idx];927    if (signal?.aborted || epoch !== vaultEpoch || credential.key !== derivedKey || vaultCreatesInFlight ||928      breachChecks.get(id) !== token || !current || current.deletedAt || current.type !== "login" || current.password !== password) return "unapplied";929    if (count === null) return "unknown";930    if ((current.breach ?? 0) === count) return count;931    const owner = entries;932    const next = { ...current, breach: count, modifiedAt: monotonicEntryTimestamp(current.modifiedAt) };933    entries[idx] = next;934    try {935      await persistEntries();936    } catch (error) {937      if (epoch === vaultEpoch && entries === owner && entries[idx] === next && !next.deletedAt) entries[idx] = current;938      throw error;939    }940    if (!isCurrent() || breachChecks.get(id) !== token) return "unapplied";941    fireSyncTrigger("vault_change");942    return count;943  } finally {944    if (breachChecks.get(id) === token) breachChecks.delete(id);945  }946}947948function checkEntryBreachDetached(credential: BreachCredential): void {949  void checkEntryBreach(credential).catch(() => {950    console.warn("[Peach] Could not save a breach check result");951  });952}953954function emptyBreachScan(state: BreachScanStatus["state"] = "idle"): BreachScanStatus {955  return { id: null, state, total: 0, scanned: 0, unknown: 0, unapplied: 0, breached: 0, cancelled: 0 };956}957958type BreachScan = {959  epoch: number;960  key: Uint8Array | null;961  status: BreachScanStatus;962  credentials: BreachCredential[];963  controller: AbortController;964};965let breachScan: BreachScan | null = null;966967function cancelBreachScan(): void {968  breachChecks.clear();969  const scan = breachScan;970  if (!scan) return;971  scan.controller.abort();972  scan.credentials.length = 0;973  scan.key = null;974  if (scan.status.state === "running") {975    scan.status.cancelled = scan.status.total - scan.status.scanned - scan.status.unknown - scan.status.unapplied;976    scan.status.state = "cancelled";977  }978}979980/// Returns aggregate progress for the current unlock session without credential data.981export function getBreachScanStatus(): BreachScanStatus {982  if (!derivedKey) return emptyBreachScan(breachScan ? "cancelled" : "idle");983  if (!breachScan || breachScan.epoch !== vaultEpoch || breachScan.key !== derivedKey) return emptyBreachScan();984  return { ...breachScan.status };985}986987/// Starts a single background scan, or returns the current scan if it is still running.988export function startBreachScan(): BreachScanStatus {989  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");990  if (breachScan?.status.state === "running" && breachScan.epoch === vaultEpoch && breachScan.key === derivedKey) return getBreachScanStatus();991  cancelBreachScan();992  const key = derivedKey;993  const credentials = entries.filter((entry) => !entry.deletedAt && entry.type === "login" && entry.password)994    .map((entry) => ({ id: entry.id, password: entry.password!, epoch: vaultEpoch, key }));995  const scan: BreachScan = {996    epoch: vaultEpoch, key, credentials, controller: new AbortController(),997    status: { ...emptyBreachScan(credentials.length ? "running" : "complete"), id: crypto.randomUUID(), total: credentials.length },998  };999  breachScan = scan;1000  void runBreachScan(scan);1001  return { ...scan.status };1002}10031004async function runBreachScan(scan: BreachScan): Promise<void> {1005  try {1006    while (scan.credentials.length) {1007      if (scan.epoch !== vaultEpoch || scan.key !== derivedKey || scan.controller.signal.aborted) break;1008      const credential = scan.credentials.shift()!;1009      let result: "unknown" | "unapplied" | number;1010      try { result = await checkEntryBreach(credential, scan.controller.signal); }1011      catch { result = "unknown"; console.warn("[Peach] Could not save a breach scan result"); }1012      if (scan.epoch !== vaultEpoch || scan.key !== derivedKey || scan.controller.signal.aborted) break;1013      if (result === "unknown") scan.status.unknown++;1014      else if (result === "unapplied") scan.status.unapplied++;1015      else { scan.status.scanned++; if (result > 0) scan.status.breached++; }1016      if (scan.credentials.length) {1017        await new Promise<void>((resolve) => {1018          const done = () => { clearTimeout(timer); scan.controller.signal.removeEventListener("abort", done); resolve(); };1019          const timer = setTimeout(done, 200);1020          scan.controller.signal.addEventListener("abort", done, { once: true });1021          if (scan.controller.signal.aborted) done();1022        });1023      }1024    }1025  } finally {1026    scan.credentials.length = 0;1027    if (scan.status.state === "running") {1028      if (scan.epoch !== vaultEpoch || scan.key !== derivedKey || scan.controller.signal.aborted) {1029        scan.status.cancelled = scan.status.total - scan.status.scanned - scan.status.unknown - scan.status.unapplied;1030        scan.status.state = "cancelled";1031      } else scan.status.state = "complete";1032    }1033  }1034}10351036export async function declineCardSaveOffer(last4: string, expMonth: string, expYear: string): Promise<void> {1037  // Unreachable from the message layer, which gates on isUnlocked first.1038  const key = await cardDeclineKey();1039  if (!key) return;1040  const fingerprint = await cardFingerprint(last4, expMonth, expYear);1041  await loadSettings();1042  settings = {1043    ...settings,1044    declinedCardFingerprints: [1045      // Legacy records predate the keyed digest and are silently dropped here:1046      // they are 16 hex characters rather than 32, and are no longer accepted.1047      ...(settings.declinedCardFingerprints ?? []).filter(1048        (stored) => stored.length === CARD_DECLINE_DIGEST_HEX,1049      ),1050      await metadataDigest(fingerprint, key),1051    ].slice(-CARD_DECLINE_MAX),1052  };1053  await persistSettings();1054}10551056export async function isCardDeclined(last4: string, expMonth: string, expYear: string): Promise<boolean> {1057  await loadSettings();1058  const key = await cardDeclineKey();1059  if (!key) return false;1060  const fingerprint = await cardFingerprint(last4, expMonth, expYear);1061  const candidate = await metadataDigest(fingerprint, key);1062  return (settings.declinedCardFingerprints ?? []).some(1063    (stored) => stored.length === CARD_DECLINE_DIGEST_HEX && stored === candidate,1064  );1065}10661067/**1068 * Keying material for the declined-card digest, derived from the vault root1069 * key so it is available only while unlocked and never written to storage.1070 *1071 * PB-26-108: the previous scheme stored a random salt beside the records. A1072 * salt defeats precomputed tables, not an attacker holding the file — the1073 * candidate space here is ~10^4 last-four values x 12 months x a few years, so1074 * a stored salt left the card's last four and expiry recoverable offline in1075 * seconds. `peach_settings` is unencrypted and directly readable by a content1076 * script on Firefox, so the key has to live outside storage entirely.1077 */1078async function cardDeclineKey(): Promise<string | null> {1079  const root = getRootKeyHex();1080  if (!root) return null;1081  const digest = new Uint8Array(1082    await crypto.subtle.digest(1083      "SHA-256",1084      new TextEncoder().encode(`peach-card-decline-v1:${root}`),1085    ),1086  );1087  return hex(digest);1088}10891090async function cardFingerprint(last4: string, expMonth: string, expYear: string): Promise<string> {1091  const encoder = new TextEncoder();1092  const buf = await crypto.subtle.digest("SHA-256", encoder.encode(`${last4}|${expMonth}|${expYear}`));1093  return Array.from(new Uint8Array(buf).slice(0, 8))1094    .map((b) => b.toString(16).padStart(2, "0"))1095    .join("");1096}10971098function hex(buf: Uint8Array): string {1099  return Array.from(buf)1100    .map((b) => b.toString(16).padStart(2, "0"))1101    .join("");1102}11031104function unhex(s: string): Uint8Array {1105  const out = new Uint8Array(s.length / 2);1106  for (let i = 0; i < s.length; i += 2) {1107    out[i / 2] = parseInt(s.slice(i, i + 2), 16);1108  }1109  return out;1110}11111112// ---------------------------------------------------------------------------1113// Root key generation and recovery word wrapping1114// ---------------------------------------------------------------------------11151116/**1117 * Generate a random 32-byte root key and wrap it (AES-256-GCM) under a key1118 * derived from the recovery word material via HKDF-SHA256. The wrapped blob1119 * fields are stored in slot A alongside the password-wrapped ciphertext. The1120 * root key itself is kept in memory for the session so getRecoveryWords() can1121 * encode it without re-deriving.1122 *1123 * SECURITY MODEL (PCH-01-005): the recovery KEK is derived from the 12-word1124 * material, which encodes only rootKey[0..16] (recovery-words.ts). The KEK is thus1125 * derived from a PREFIX of the very plaintext it wraps, and effective recovery1126 * security is 128-bit (standard for a 12-word phrase), NOT 256-bit. This is safe —1127 * unwrapping requires the words, and the GCM ciphertext leaks nothing without them —1128 * but it is intentional, not an oversight. A future escrow version wanting 256-bit1129 * recovery must derive the words from INDEPENDENT entropy, not from the root key.1130 */1131async function generateAndWrapRootKey(): Promise<{1132  rawRootKey: string; // hex of the plaintext root key — caller stores in rootKey1133  recoverySalt: string;1134  wrappedRootKey: string;1135  wrappedNonce: string;1136  wrappedTag: string;1137}> {1138  const rootKeyBytes = crypto.getRandomValues(new Uint8Array(32));1139  try {11401141  // Derive the recovery key from the BIP39 words encoding of the root key.1142  const words = await rootKeyToWords(rootKeyBytes);1143  const wordMaterial = await wordsToRootKeyMaterial(words);1144  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));1145  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);11461147  // Wrap the root key with the recovery key using AES-256-GCM directly.1148  // We hex-encode rootKeyBytes so the plaintext is always valid UTF-8.1149  const nonce = crypto.getRandomValues(new Uint8Array(12));1150  const encoded = new TextEncoder().encode(hex(rootKeyBytes));1151  const raw = await crypto.subtle.encrypt(1152    {1153      name: "AES-GCM",1154      iv: nonce,1155      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,1156      tagLength: 128,1157    },1158    recoveryKey,1159    encoded1160  );1161  // WebCrypto returns ciphertext || auth tag concatenated; split them.1162  const rawU8 = new Uint8Array(raw);1163  const ciphertext = hex(rawU8.slice(0, rawU8.length - 16));1164  const tag = hex(rawU8.slice(rawU8.length - 16));11651166  return {1167    rawRootKey: hex(rootKeyBytes),1168    recoverySalt: hex(recoverySalt),1169    wrappedRootKey: ciphertext,1170    wrappedNonce: hex(nonce),1171    wrappedTag: tag,1172  };1173  } finally { zeroKey(rootKeyBytes); }1174}11751176async function wrapExistingRootKeyForRecovery(rootKeyBytes: Uint8Array): Promise<{1177  recoverySalt: string;1178  wrappedRootKey: string;1179  wrappedNonce: string;1180  wrappedTag: string;1181}> {1182  if (rootKeyBytes.length !== 32) {1183    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");1184  }11851186  const words = await rootKeyToWords(rootKeyBytes);1187  const wordMaterial = await wordsToRootKeyMaterial(words);1188  const recoverySalt = crypto.getRandomValues(new Uint8Array(16));1189  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);1190  const nonce = crypto.getRandomValues(new Uint8Array(12));1191  const encoded = new TextEncoder().encode(hex(rootKeyBytes));1192  const raw = await crypto.subtle.encrypt(1193    {1194      name: "AES-GCM",1195      iv: nonce,1196      additionalData: new Uint8Array([1]).buffer as ArrayBuffer,1197      tagLength: 128,1198    },1199    recoveryKey,1200    encoded,1201  );1202  const rawU8 = new Uint8Array(raw);1203  return {1204    recoverySalt: hex(recoverySalt),1205    wrappedRootKey: hex(rawU8.slice(0, rawU8.length - 16)),1206    wrappedNonce: hex(nonce),1207    wrappedTag: hex(rawU8.slice(rawU8.length - 16)),1208  };1209}12101211/**1212 * Unwrap the root key using recovery words. Called during recovery flow when1213 * the user provides their 12-word phrase and a new password.1214 */1215async function unwrapRootKeyForRecovery(1216  wrappedRootKey: string,1217  wrappedNonce: string,1218  wrappedTag: string,1219  recoverySaltHex: string,1220  words: string[]1221): Promise<Uint8Array> {1222  const wordMaterial = await wordsToRootKeyMaterial(words);1223  const recoverySalt = unhex(recoverySaltHex);1224  const recoveryKey = await deriveRecoveryKey(wordMaterial, recoverySalt);12251226  // The root key bytes were hex-encoded before1227  // encryption so the ciphertext is valid UTF-8. We inline the AES-GCM decrypt1228  // here to avoid passing a CryptoKey to the string-based encrypt/decrypt helpers.1229  // Each component is stored separately in the vault slot; decode them individually1230  // so the nonce is always exactly the 12 bytes from wrappedNonce.1231  const nonceRaw = unhex(wrappedNonce);1232  const ciphertextRaw = unhex(wrappedRootKey);1233  const tagRaw = unhex(wrappedTag);1234  // Combine ciphertext and tag for AES-GCM (expects ciphertext||tag).1235  // Use explicit ArrayBuffer allocations to satisfy TS BufferSource constraints.1236  const nonceU8 = nonceRaw as unknown as Uint8Array<ArrayBuffer>;1237  const combined = new Uint8Array(ciphertextRaw.length + tagRaw.length);1238  combined.set(ciphertextRaw, 0);1239  combined.set(tagRaw, ciphertextRaw.length);1240  const raw = await crypto.subtle.decrypt(1241    { name: "AES-GCM", iv: nonceU8, additionalData: new Uint8Array([1]).buffer as ArrayBuffer, tagLength: 128 },1242    recoveryKey,1243    combined1244  );1245  const decryptedHex = new TextDecoder().decode(raw);1246  const recovered = unhex(decryptedHex);1247  if (recovered.length !== 32) { zeroKey(recovered); throw new Error("invalid_recovery_words"); }1248  return recovered;1249}12501251/// Recover a locked real vault without publishing keys before its stored payload authenticates.1252export async function recoverWithWords(words: string[], newPassword: string): Promise<RecoveryResult> {1253  if (recoveryInFlight || derivedKey) throw new Error("recovery_requires_lock");1254  if (vaultWritesInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");1255  recoveryInFlight = true;1256  let settle!: () => void;1257  recoverySettled = new Promise<void>((resolve) => { settle = resolve; });1258  cancelBreachScan();1259  const epoch = ++vaultEpoch;1260  const check = () => {1261    if (epoch !== vaultEpoch || derivedKey) throw new Error("vault_locked");1262  };1263  let recoveredRoot: Uint8Array | null = null;1264  let oldKey: Uint8Array | null = null;1265  let newKey: Uint8Array | null = null;1266  let committed = false;1267  try {1268    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1269    check();1270    const slot = raw[SLOT_A] as StoredVault | undefined;1271    if (!slot) throw new Error("no_vault");1272    if (!slot.recovery_salt || !slot.recovery_wrapped_root_key) throw new Error("recovery_not_setup");1273    try {1274      recoveredRoot = await unwrapRootKeyForRecovery(slot.recovery_wrapped_root_key,1275        slot.recovery_nonce ?? "", slot.recovery_tag ?? "", slot.recovery_salt, words);1276    } catch {1277      throw new Error("invalid_recovery_words");1278    }1279    check();1280    if (!slot.recovery_vault_key) throw new Error("recovery_requires_password_unlock");1281    oldKey = await openSealedKey(recoveredRoot, slot.recovery_vault_key, "recovery_vault_key_v1");1282    check();1283    if (!oldKey) throw new Error("recovery_data_unavailable");1284    const result = await tryDecryptSlotResult(slot, oldKey, "slot_a_v1");1285    check();1286    if (result.status !== "ok") throw new Error("recovery_data_unavailable");1287    const payload = result.payload;1288    await loadSettings();1289    check();1290    const salt = generateSalt();1291    newKey = await deriveKey(newPassword, salt);1292    check();1293    // Preserve the authenticated plaintext, including fields unknown to this build.1294    const plaintext = await decrypt(oldKey, slot.nonce, slot.ciphertext, slot.tag, "slot_a_v1");1295    const encrypted = await encrypt(newKey, plaintext, "slot_a_v1");1296    const pwRoot = await wrapRootKeyForDerivedKey(newKey, recoveredRoot);1297    const recoveryVaultKey = await encrypt(recoveredRoot, hex(newKey), "recovery_vault_key_v1");1298    check();1299    const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1300    check();1301    if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");1302    const history = raw[HISTORY_KEY] as VaultHistory | undefined;1303    const snapshot: VaultSnapshot = {1304      id: crypto.randomUUID(), savedAt: Date.now(), reason: "local_save",1305      vault_a: JSON.stringify(slot), vault_b: JSON.stringify(raw[SLOT_B] ?? slot), entryCount: null,1306    };1307    const previousStamp = Number(raw.peach_last_modified_at);1308    const nextSlot: StoredVault = { ...slot, ...encrypted, ...pwRoot,1309      salt: hex(salt), recovery_vault_key: recoveryVaultKey };1310    // One storage transaction keeps the rollback snapshot and all new-key fields together.1311    await chrome.storage.local.set({1312      [SLOT_A]: nextSlot,1313      [HISTORY_KEY]: { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) },1314      peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previousStamp) ? previousStamp + 1 : 0)),1315    });1316    committed = true;1317    check();1318    cancelBreachScan();1319    derivedKey = newKey;1320    rootKey = recoveredRoot;1321    newKey = null;1322    recoveredRoot = null;1323    entries = payload.entries;1324    tombstones = payload.tombstones;1325    duressConfigured = payload.duressConfigured;1326    vaultMode = "real";1327    manualSummonRecall = new Map();1328    buildDomainIndexSync(entries);1329    await saveSessionKey(derivedKey, "real", epoch);1330    if (epoch !== vaultEpoch) throw new Error("vault_locked");1331    await identityHooks?.onKeysRotated();1332    if (epoch !== vaultEpoch) throw new Error("vault_locked");1333    await reconcilePairSecrets(rootKey);1334    if (epoch !== vaultEpoch) throw new Error("vault_locked");1335    await clearPinUnlockStorage();1336    if (epoch !== vaultEpoch) throw new Error("vault_locked");1337    await restoreManualSummonRecall();1338    if (epoch !== vaultEpoch) throw new Error("vault_locked");1339    touchAutoLock();1340    return { committed: true, unlocked: true };1341  } catch (error) {1342    if (committed) {1343      console.warn("[Peach] recovery password saved; unlock required:", error);1344      if (derivedKey && epoch === vaultEpoch) {1345        try { await lock(); }1346        catch (lockError) { console.warn("[Peach] recovery session cleanup failed:", lockError); }1347      }1348      return { committed: true, unlocked: false };1349    }1350    if (derivedKey && epoch === vaultEpoch) await lock();1351    throw error;1352  } finally {1353    if (oldKey) zeroKey(oldKey);1354    if (newKey) zeroKey(newKey);1355    if (recoveredRoot) zeroKey(recoveredRoot);1356    recoveryInFlight = false;1357    settle();1358  }1359}13601361/// Cancel recovery and finish its issued storage write before removing vault data.1362export async function withVaultRemoval<T>(remove: () => Promise<T>): Promise<T> {1363  vaultRemovalEpoch++;1364  vaultRemovalsInFlight++;1365  try {1366    await lock();1367    await recoverySettled;1368    await creationSettled;1369    return await remove();1370  } finally {1371    vaultRemovalsInFlight--;1372  }1373}13741375/**1376 * Recover the session root key by AES-GCM-decrypting the pw_root_* fields1377 * (a second wrapping of the root key under the password-derived key). This1378 * is what makes GET_RECOVERY_WORDS work across lock/unlock cycles without1379 * the user re-entering their recovery phrase: the same root key bytes —1380 * and therefore the same 12 words — survive every unlock.1381 *1382 * Returns null when the escrow is absent or decryption fails.1383 */1384async function deriveRootKeyFromDerivedKey(1385  derivedKeyBytes: Uint8Array,1386  slotA: StoredVault,1387): Promise<Uint8Array | null> {1388  if (!slotA.pw_root_ciphertext || !slotA.pw_root_nonce || !slotA.pw_root_tag) {1389    return null;1390  }1391  try {1392    const rootHex = await decrypt(1393      derivedKeyBytes,1394      slotA.pw_root_nonce,1395      slotA.pw_root_ciphertext,1396      slotA.pw_root_tag,1397      "pw_root_v1",1398    );1399    return unhex(rootHex);1400  } catch {1401    return null;1402  }1403}14041405export async function sealIdentityKeyUnderVault(ik: Uint8Array): Promise<IdentityKeyEnvelope> {1406  if (vaultMode !== "real" || !rootKey || !derivedKey) throw new Error("vault_locked");1407  // The root wrap survives password change and recovery-words re-key; the1408  // local wrap is available during normal unlock. Pending is only pre-vault.1409  const [root, local] = await Promise.all([1410    encrypt(rootKey, hex(ik), "peach-local-identity-ik-root-v1"),1411    encrypt(derivedKey, hex(ik), "peach-local-identity-ik-local-v1"),1412  ]);1413  return { root, local };1414}14151416export async function sealIdentityKeyPreVault(1417  password: string,1418  ik: Uint8Array,1419): Promise<IdentityKeyEnvelope> {1420  const salt = generateSalt();1421  const key = await deriveKey(password, salt);1422  try {1423    const pending = await encrypt(key, hex(ik), "peach-local-identity-ik-pending-v1");1424    return { pending, pendingSalt: hex(salt) };1425  } finally {1426    zeroKey(key);1427  }1428}14291430/**1431 * Open the identity key with any wrapping key that is currently available:1432 * the live vault-unlock key, then the vault root key, then the pre-vault1433 * password. Each attempt is awaited only after the previous one fails, so a1434 * successful early unwrap never leaves a later decrypt rejection unobserved,1435 * and the pre-vault Argon2id is not paid when a vault key already opens the1436 * envelope.1437 */1438export async function openIdentityKey(1439  env: IdentityKeyEnvelope,1440  password?: string,1441): Promise<Uint8Array | null> {1442  if (env.local && derivedKey) {1443    const ik = await openSealedKey(derivedKey, env.local, "peach-local-identity-ik-local-v1");1444    if (ik) return ik;1445  }1446  if (env.root && rootKey) {1447    const ik = await openSealedKey(rootKey, env.root, "peach-local-identity-ik-root-v1");1448    if (ik) return ik;1449  }1450  if (!env.pending || !env.pendingSalt || password === undefined) return null;1451  let key: Uint8Array;1452  try {1453    const salt = unhex(env.pendingSalt);1454    key = await deriveKey(password, salt);1455    salt.fill(0);1456  } catch {1457    return null;1458  }1459  try {1460    return await openSealedKey(key, env.pending, "peach-local-identity-ik-pending-v1");1461  } finally {1462    zeroKey(key);1463  }1464}14651466/** Decrypt a sealed 32-byte key; null for a wrong key, a bad shape, or corrupt bytes. */1467async function openSealedKey(1468  key: Uint8Array,1469  box: SealedBox,1470  info: string,1471): Promise<Uint8Array | null> {1472  try {1473    const value = unhex(await decrypt(key, box.nonce, box.ciphertext, box.tag, info));1474    if (value.length === 32) return value;1475    value.fill(0);1476    return null;1477  } catch {1478    return null;1479  }1480}14811482// AES-GCM-wrap rootKey under derivedKey for the pw_root_* fields. Returns the1483// hex-encoded ciphertext/nonce/tag triple ready to embed in StoredVault.1484async function wrapRootKeyForDerivedKey(1485  derivedKeyBytes: Uint8Array,1486  rootKeyBytes: Uint8Array,1487): Promise<{ pw_root_ciphertext: string; pw_root_nonce: string; pw_root_tag: string }> {1488  const { nonce, ciphertext, tag } = await encrypt(derivedKeyBytes, hex(rootKeyBytes), "pw_root_v1");1489  return {1490    pw_root_ciphertext: ciphertext,1491    pw_root_nonce: nonce,1492    pw_root_tag: tag,1493  };1494}14951496/** Returns the 12 recovery words for the current session's root key. */1497export async function getRecoveryWords(): Promise<string[]> {1498  if (!rootKey) {1499    throw new Error("recovery not set up");1500  }1501  return rootKeyToWords(rootKey);1502}15031504async function loadSlot(key: string): Promise<StoredVault | null> {1505  const result = await chrome.storage.local.get(key);1506  return (result as Record<string, StoredVault | undefined>)[key] ?? null;1507}15081509async function writeSlot(key: string, vault: StoredVault): Promise<void> {1510  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");1511  vaultWritesInFlight++;1512  try {1513    await chrome.storage.local.set({ [key]: vault });1514  } catch (err) {1515    throw mapStorageError(err);1516  } finally {1517    vaultWritesInFlight--;1518  }1519}15201521/**1522 * Roll back a vault that was created by [createVaultFromRootKey] but1523 * couldn't be paired (e.g. the subsequent license activation, identity1524 * derivation, or paired-device upsert failed). Without this, a failed1525 * receiver session leaves behind an empty vault — the user has to1526 * re-pair to get a working setup, but the empty vault sits in the way.1527 *1528 * The call is idempotent: removing keys that aren't there is a no-op.1529 */1530export async function rollbackAdoptedVault(): Promise<void> {1531  await withVaultRemoval(async () => {1532    try {1533      await chrome.storage.local.remove([1534        SLOT_A,1535        SLOT_B,1536        "peach_last_modified_at",1537        RECALL_STORAGE,1538      ]);1539    } catch (err) {1540      throw mapStorageError(err);1541    }1542  });1543}15441545async function commitCreatedVaultSlots(slotA: StoredVault, slotB: StoredVault): Promise<void> {1546  if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1547  vaultWritesInFlight++;1548  try {1549    const raw = await chrome.storage.local.get("peach_last_modified_at");1550    const previous = Number(1551      (raw as Record<string, unknown>).peach_last_modified_at,1552    );1553    const next = Math.max(1554      Date.now(),1555      Number.isFinite(previous) ? previous + 1 : 0,1556    );1557    try {1558      if (recoveryInFlight || vaultRemovalsInFlight) throw new Error("recovery_in_progress");1559      await chrome.storage.local.set({1560        [SLOT_A]: slotA,1561        [SLOT_B]: slotB,1562        peach_last_modified_at: String(next),1563      });1564    } catch (err) {1565      throw mapStorageError(err);1566    }1567  } finally {1568    vaultWritesInFlight--;1569  }1570}15711572// Monotonic clock for per-entry modifiedAt / deletedAt timestamps. Guards the1573// sync layer's last-write-wins merge against wall-clock regressions (NTP step,1574// manual clock change, DST glitch): a backwards Date.now() must never produce1575// an entry timestamp that's <= the entry's existing modifiedAt, or a genuine1576// local edit would lose to a stale remote copy. The returned value is always1577// strictly greater than both the entry's current modifiedAt and the previous1578// call's result (SEV-2-E).1579let lastEntryTimestamp = 0;1580function monotonicEntryTimestamp(currentModifiedAt?: number): number {1581  const base = Math.max(1582    Date.now(),1583    (currentModifiedAt ?? 0) + 1,1584    lastEntryTimestamp + 1,1585  );1586  lastEntryTimestamp = base;1587  return base;1588}15891590async function stampLocalVaultMutation(): Promise<void> {1591  if (vaultCreatesInFlight) throw new Error("vault_changed");1592  const raw = await chrome.storage.local.get("peach_last_modified_at");1593  const previous = Number(1594    (raw as Record<string, unknown>).peach_last_modified_at,1595  );1596  const next = Math.max(1597    Date.now(),1598    Number.isFinite(previous) ? previous + 1 : 0,1599  );1600  if (vaultCreatesInFlight) throw new Error("vault_changed");1601  await chrome.storage.local.set({1602    peach_last_modified_at: String(next),1603  });1604}16051606// ---------------------------------------------------------------------------1607// Padding + noise helpers1608// ---------------------------------------------------------------------------16091610/**1611 * Pads the plaintext string with trailing spaces so that the encoded byte1612 * length is a multiple of PAD_BLOCK. JSON.parse tolerates trailing1613 * whitespace after a complete document, so the padding is transparent on1614 * decode. Ciphertext length equals plaintext length plus a 16-byte tag.1615 */1616function padPlaintext(json: string, minBytes = 0): string {1617  const encoded = new TextEncoder().encode(json);1618  const bucket = Math.max(PAD_BLOCK, Math.ceil(encoded.length / PAD_BLOCK) * PAD_BLOCK);1619  // minBytes lets the duress path force a fixed ceiling so both slots match.1620  const target = Math.max(bucket, minBytes);1621  const padLen = target - encoded.length;1622  return json + " ".repeat(padLen);1623}16241625/**1626 * Produces a StoredVault-shaped record filled with CSPRNG bytes. The1627 * ciphertext length matches the given byte count. Because GCM ciphertext is1628 * pseudo-random, this blob is indistinguishable at rest from a real1629 * encrypted vault without the key.1630 *1631 * crypto.getRandomValues() caps each call at 65536 bytes (the Web Crypto1632 * spec hard limit). Chunk the fill so vaults larger than that — common once1633 * the user has dozens of entries or any passkey — don't throw.1634 */1635const CSPRNG_CHUNK = 65_536;16361637function fillRandom(buf: Uint8Array): Uint8Array {1638  for (let offset = 0; offset < buf.length; offset += CSPRNG_CHUNK) {1639    const end = Math.min(offset + CSPRNG_CHUNK, buf.length);1640    const chunk = new Uint8Array(end - offset);1641    crypto.getRandomValues(chunk);1642    buf.set(chunk, offset);1643  }1644  return buf;1645}16461647function generateNoiseBlob(ciphertextBytes: number): StoredVault {1648  const salt = crypto.getRandomValues(new Uint8Array(16));1649  const nonce = crypto.getRandomValues(new Uint8Array(12));1650  const cipher = fillRandom(new Uint8Array(ciphertextBytes));1651  const tag = crypto.getRandomValues(new Uint8Array(16));1652  return {1653    version: 1,1654    salt: hex(salt),1655    nonce: hex(nonce),1656    ciphertext: hex(cipher),1657    tag: hex(tag),1658  };1659}16601661// ---------------------------------------------------------------------------1662// Encrypted plaintext envelope1663// ---------------------------------------------------------------------------16641665type VaultPayload = {1666  entries: VaultEntry[];1667  tombstones?: Record<string, number>;1668  duressConfigured?: boolean;1669};16701671type DecryptedPayload = {1672  entries: VaultEntry[];1673  tombstones: Map<string, number>;1674  duressConfigured: boolean;1675};16761677function encodePayload(entries: VaultEntry[], duress: boolean, minBytes = 0): string {1678  const envelope: VaultPayload = {1679    entries,1680    tombstones: Object.fromEntries(tombstones),1681    duressConfigured: duress,1682  };1683  return padPlaintext(JSON.stringify(envelope), minBytes);1684}16851686function decodeTombstones(raw: unknown, allEntries: VaultEntry[]): Map<string, number> {1687  const result = new Map<string, number>();1688  if (raw && typeof raw === "object" && !Array.isArray(raw)) {1689    for (const [id, timestamp] of Object.entries(raw as Record<string, unknown>)) {1690      if (typeof timestamp === "number" && Number.isFinite(timestamp) && timestamp > 0) {1691        result.set(id, timestamp);1692      }1693    }1694  }1695  // Older payloads had no ledger. Rebuild the durable portion from any1696  // soft-deleted entries before they are eligible for a later purge.1697  for (const entry of allEntries) {1698    if (typeof entry.deletedAt !== "number" || !Number.isFinite(entry.deletedAt) || entry.deletedAt <= 0) {1699      continue;1700    }1701    if ((result.get(entry.id) ?? 0) < entry.deletedAt) {1702      result.set(entry.id, entry.deletedAt);1703    }1704  }1705  return result;1706}17071708function reconcileTombstones(): void {1709  const byId = new Map(entries.map((entry) => [entry.id, entry]));1710  for (const [id] of tombstones) {1711    if (byId.has(id) && !byId.get(id)?.deletedAt) tombstones.delete(id);1712  }1713  for (const entry of entries) {1714    if (typeof entry.deletedAt === "number" && Number.isFinite(entry.deletedAt) && entry.deletedAt > 0) {1715      if ((tombstones.get(entry.id) ?? 0) < entry.deletedAt) {1716        tombstones.set(entry.id, entry.deletedAt);1717      }1718    }1719  }1720}17211722function decodePayload(plain: string): DecryptedPayload {1723  const parsed = JSON.parse(plain) as VaultPayload;1724  if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.entries)) {1725    throw new Error("invalid vault payload");1726  }1727  const normalized = parsed.entries.map(normalizeEntry);1728  return {1729    entries: normalized,1730    tombstones: decodeTombstones(parsed.tombstones, normalized),1731    duressConfigured: parsed.duressConfigured === true,1732  };1733}17341735// Keep ambiguous records intact: an RP or account can own several credentials.1736function mergePasskeyOnlyIntoLogins(entries: VaultEntry[]): { merged: boolean } {1737  let merged = false;1738  const transferable = new Set(["id", "type", "title", "username", "url", "passkey", "createdAt", "modifiedAt", "totp", "totpAlgorithm", "totpDigits", "totpPeriod"]);1739  for (const source of entries.filter((entry) => !entry.deletedAt && entry.passkey)) {1740    const passkey = source.passkey!;1741    if (source.type !== "login" && source.type !== "passkey") continue;1742    if (!passkey.userName || (source.username && source.username !== passkey.userName)) continue;1743    if (Object.entries(source).some(([key, value]) => !transferable.has(key) && value !== undefined && value !== "")) continue;1744    const targets = entries.filter((entry) => {1745      if (entry.deletedAt || entry.passkey || entry.type !== "login" || entry.username !== passkey.userName) return false;1746      return [entry.url, ...(entry.additionalUrls ?? [])].some((url) => {1747        if (!url) return false;1748        try {1749          return new URL(url.includes("://") ? url : `https://${url}`).hostname === passkey.rpId;1750        } catch {1751          return false;1752        }1753      });1754    });1755    if (targets.length !== 1) continue;1756    const target = targets[0]!;1757    if (source.totp && target.totp && (source.totp !== target.totp || source.totpAlgorithm !== target.totpAlgorithm || source.totpDigits !== target.totpDigits || source.totpPeriod !== target.totpPeriod)) continue;1758    target.passkey = passkey;1759    if (source.totp && !target.totp) {1760      target.totp = source.totp;1761      target.totpAlgorithm = source.totpAlgorithm;1762      target.totpDigits = source.totpDigits;1763      target.totpPeriod = source.totpPeriod;1764    }1765    const stamp = monotonicEntryTimestamp(Math.max(source.modifiedAt, target.modifiedAt));1766    target.modifiedAt = stamp;1767    source.modifiedAt = stamp;1768    source.deletedAt = stamp;1769    merged = true;1770  }1771  return { merged };1772}17731774// Validates that a `StoredVault` record on disk has the field shape we expect1775// before treating an AES-GCM decrypt success as a clean unlock. AES-GCM only1776// authenticates the static VERSION_BYTE AAD, not the `version` field on the1777// outer record — a corrupted `version: 42` slot still decrypts cleanly. This1778// check surfaces that as `corrupted` (M7/COR-007) so the popup can offer a1779// history-restore path instead of falsely reporting "wrong password".1780function hasValidVaultSchema(v: unknown): v is StoredVault {1781  if (typeof v !== "object" || v === null) return false;1782  const r = v as Record<string, unknown>;1783  return (1784    r.version === 1 &&1785    typeof r.salt === "string" &&1786    typeof r.nonce === "string" &&1787    typeof r.ciphertext === "string" &&1788    typeof r.tag === "string"1789  );1790}1791const MAX_HISTORY_BLOB_BYTES = 1_024 * 1_024;17921793function hasValidHistorySlot(value: unknown): value is StoredVault {1794  if (!hasValidVaultSchema(value)) return false;1795  return /^[0-9a-f]{32}$/i.test(value.salt) &&1796    /^[0-9a-f]{24}$/i.test(value.nonce) &&1797    /^[0-9a-f]+$/i.test(value.ciphertext) &&1798    value.ciphertext.length % 2 === 0 &&1799    value.ciphertext.length / 2 <= MAX_HISTORY_BLOB_BYTES &&1800    /^[0-9a-f]{32}$/i.test(value.tag);1801}18021803function parseHistorySlot(value: string): StoredVault | null {1804  try {1805    const parsed: unknown = JSON.parse(value);1806    return hasValidHistorySlot(parsed) ? parsed : null;1807  } catch {1808    return null;1809  }1810}18111812function isHistoryRecord(value: unknown): value is VaultSnapshot {1813  if (typeof value !== "object" || value === null) return false;1814  const record = value as Record<string, unknown>;1815  return typeof record.id === "string" && record.id.length > 0 && record.id.length <= 128 &&1816    typeof record.savedAt === "number" && Number.isFinite(record.savedAt) &&1817    typeof record.reason === "string" &&1818    typeof record.vault_a === "string" && record.vault_a.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1819    typeof record.vault_b === "string" && record.vault_b.length <= MAX_HISTORY_BLOB_BYTES * 2 &&1820    (record.entryCount === null || typeof record.entryCount === "number");1821}18221823function sanitizeHistory(value: unknown): VaultSnapshot[] {1824  if (typeof value !== "object" || value === null) return [];1825  if (!("snapshots" in value) || !Array.isArray(value.snapshots)) return [];1826  return value.snapshots.filter(isHistoryRecord).slice(0, HISTORY_MAX);1827}18281829export type TryDecryptResult =1830  | { status: "ok"; payload: DecryptedPayload }1831  | { status: "wrong_key" }1832  | { status: "corrupted"; reason: string };18331834// Exported solely for `unlockFromCodex` below, which needs to verify a1835// supplied passphrase against a slotA blob *without* committing anything to1836// storage. Keep this internal otherwise — callers crossing the messages.ts1837// boundary should always go through `unlock` / `verifyMainPassword` so the1838// constant-time invariants in Projects.md §3.4 are not bypassed.1839export async function tryDecryptSlot(1840  vault: StoredVault,1841  key: Uint8Array,1842  aadTag?: string,1843): Promise<DecryptedPayload | null> {1844  const res = await tryDecryptSlotResult(vault, key, aadTag);1845  return res.status === "ok" ? res.payload : null;1846}18471848export async function tryDecryptSlotResult(1849  vault: StoredVault,1850  key: Uint8Array,1851  aadTag?: string,1852): Promise<TryDecryptResult> {1853  if (!hasValidVaultSchema(vault)) {1854    return { status: "corrupted", reason: "invalid_slot_schema" };1855  }1856  let plain: string;1857  try {1858    plain = await decrypt(key, vault.nonce, vault.ciphertext, vault.tag, aadTag);1859  } catch {1860    return { status: "wrong_key" };1861  }1862  try {1863    const parsed = JSON.parse(plain) as unknown;1864    if (typeof parsed !== "object" || parsed === null) {1865      return { status: "corrupted", reason: "invalid_payload_shape" };1866    }1867    if (!Array.isArray(parsed) && !Array.isArray((parsed as VaultPayload).entries)) {1868      return { status: "corrupted", reason: "invalid_payload_shape" };1869    }1870    return { status: "ok", payload: decodePayload(plain) };1871  } catch {1872    return { status: "corrupted", reason: "invalid_payload_json" };1873  }1874}18751876// ---------------------------------------------------------------------------1877// Core operations1878// ---------------------------------------------------------------------------18791880function buildDomainIndexSync(all: VaultEntry[]): void {1881  domainIndex = new Map();18821883  for (const entry of all) {1884    if (entry.deletedAt) continue;1885    if (entry.type === "note" || entry.type === "card") continue;18861887    // An entry can match multiple sites via `additionalUrls`. Index each1888    // hostname so `queryDomain` returns the entry regardless of which alias1889    // the user is currently visiting. Dedupe per-entry so a single entry1890    // never appears twice in one bucket.1891    const domains = new Set<string>();1892    const primary = extractDomain(entry.url ?? "");1893    if (primary) domains.add(primary);1894    for (const extra of entry.additionalUrls ?? []) {1895      const d = extractDomain(extra);1896      if (d) domains.add(d);1897    }1898    if (domains.size === 0) continue;18991900    for (const domain of domains) {1901      const bucket = domainIndex.get(domain) ?? [];1902      bucket.push(entry);1903      domainIndex.set(domain, bucket);1904    }1905  }1906}19071908export async function createVault(password: string, replacement?: "warned-import"): Promise<{ committed: true; unlocked: boolean }> {1909  if (replacement !== undefined && replacement !== "warned-import") throw new Error("invalid_payload");1910  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");1911  vaultCreatesInFlight++;1912  let settle!: () => void;1913  creationSettled = new Promise<void>((resolve) => { settle = resolve; });1914  let nextKey: Uint8Array | null = null;1915  let nextRoot: Uint8Array | null = null;1916  let committed = false;1917  let publishedEpoch: number | null = null;1918  const epoch = vaultEpoch;1919  const check = () => {1920    if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");1921  };1922  try {1923    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1924    check();1925    const occupied = raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;1926    if (occupied && replacement !== "warned-import") throw new Error("vault_already_exists");1927    const salt = generateSalt();1928    nextKey = await deriveKey(password, salt);1929    check();1930    const recovery = await generateAndWrapRootKey();1931    nextRoot = unhex(recovery.rawRootKey);1932    check();1933    const encrypted = await encrypt(nextKey, encodePayload([], false, 0), "slot_a_v1");1934    const pwRoot = await wrapRootKeyForDerivedKey(nextKey, nextRoot);1935    const recoveryVaultKey = await encrypt(nextRoot, hex(nextKey), "recovery_vault_key_v1");1936    check();1937    const slotA: StoredVault = {1938      ...encrypted, ...pwRoot, version: 1, salt: hex(salt),1939      recovery_vault_key: recoveryVaultKey,1940      recovery_salt: recovery.recoverySalt,1941      recovery_wrapped_root_key: recovery.wrappedRootKey,1942      recovery_nonce: recovery.wrappedNonce,1943      recovery_tag: recovery.wrappedTag,1944    };1945    const current = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY, "peach_last_modified_at"]);1946    check();1947    if (JSON.stringify(current) !== JSON.stringify(raw)) throw new Error("vault_changed");1948    const previous = Number(raw.peach_last_modified_at);1949    const update: Record<string, unknown> = {1950      [SLOT_A]: slotA, [SLOT_B]: generateNoiseBlob(encrypted.ciphertext.length / 2),1951      peach_last_modified_at: String(Math.max(Date.now(), Number.isFinite(previous) ? previous + 1 : 0)),1952    };1953    if (occupied) {1954      const history = raw[HISTORY_KEY] as VaultHistory | undefined;1955      const snapshot: VaultSnapshot = {1956        id: crypto.randomUUID(), savedAt: Date.now(), reason: "restore", entryCount: null,1957        vault_a: JSON.stringify(raw[SLOT_A] ?? null), vault_b: JSON.stringify(raw[SLOT_B] ?? null),1958      };1959      update[HISTORY_KEY] = { snapshots: [snapshot, ...(Array.isArray(history?.snapshots) ? history.snapshots : [])].slice(0, HISTORY_MAX) };1960    }1961    try { await chrome.storage.local.set(update); }1962    catch (error) { throw mapStorageError(error); }1963    committed = true;1964    if (epoch !== vaultEpoch || vaultRemovalsInFlight) return { committed: true, unlocked: false };1965    const previousKey = derivedKey;1966    const previousRoot = rootKey;1967    cancelBreachScan();1968    publishedEpoch = ++vaultEpoch;1969    derivedKey = nextKey;1970    rootKey = nextRoot;1971    nextKey = null;1972    nextRoot = null;1973    entries = [];1974    tombstones = new Map();1975    vaultMode = "real";1976    manualSummonRecall = new Map();1977    duressConfigured = false;1978    buildDomainIndexSync(entries);1979    if (previousKey) zeroKey(previousKey);1980    if (previousRoot) zeroKey(previousRoot);1981    await clearSessionKey();1982    if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1983    await identityHooks?.onVaultCreated(password).catch((error) => {1984      console.warn("[Peach] local identity promotion failed:", error);1985    });1986    if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1987    // A newly created vault owns a fresh root and a fresh slot B, so any1988    // recalled member sealed under the old vault is unreachable by design.1989    await clearStoredManualSummonRecall();1990    await restoreManualSummonRecall();1991    if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1992    touchAutoLock();1993    return { committed: true, unlocked: true };1994  } catch (error) {1995    if (!committed) throw error;1996    console.warn("[Peach] vault saved; unlock required:", error);1997    if (publishedEpoch === vaultEpoch) {1998      await lock().catch((lockError) => console.warn("[Peach] creation session cleanup failed:", lockError));1999    }2000    return { committed: true, unlocked: false };2001  } finally {2002    if (nextKey) zeroKey(nextKey);2003    if (nextRoot) zeroKey(nextRoot);2004    vaultCreatesInFlight--;2005    settle();2006  }2007}20082009/**2010 * Creates a local vault from an existing vault root key received through the2011 * SAS-gated adoption protocol. The password is local to this device; it wraps2012 * the adopted root key at rest and does not need to match the source device.2013 */2014export async function createVaultFromRootKey(2015  password: string,2016  rootKeyHex: string,2017): Promise<{ vaultId: string }> {2018  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");2019  if (typeof password !== "string" || password.length === 0) {2020    throw new Error("ADOPT_INVALID_PASSWORD");2021  }2022  if (typeof rootKeyHex !== "string" || !/^[0-9a-f]{64}$/.test(rootKeyHex)) {2023    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars");2024  }20252026  if (vaultCreatesInFlight || vaultReplacementInFlight || vaultWritesInFlight || vaultUnlocksInFlight) throw new Error("vault_changed");2027  const rootKeyBytes = unhex(rootKeyHex);2028  if (rootKeyBytes.length !== 32) {2029    rootKeyBytes.fill(0);2030    throw new Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes");2031  }20322033  vaultCreatesInFlight++;2034  let settle!: () => void;2035  creationSettled = new Promise<void>((resolve) => { settle = resolve; });2036  const epoch = vaultEpoch;2037  let nextDerivedKey: Uint8Array | null = null;2038  let sessionRootKey: Uint8Array | null = null;2039  let committed = false;2040  try {2041    if (await hasVault()) {2042      throw new Error("ADOPT_VAULT_ALREADY_EXISTS");2043    }20442045    const nextEntries: VaultEntry[] = [];2046    const nextDuressConfigured = false;2047    const vaultId = await computeVaultId(rootKeyBytes);2048    const salt = generateSalt();2049    nextDerivedKey = await deriveKey(password, salt);2050    const recovery = await wrapExistingRootKeyForRecovery(rootKeyBytes);20512052    sessionRootKey = new Uint8Array(rootKeyBytes);2053    const plaintext = encodePayload(nextEntries, nextDuressConfigured, 0);2054    const { nonce, ciphertext, tag } = await encrypt(nextDerivedKey, plaintext, "slot_a_v1");2055    const pwRoot = await wrapRootKeyForDerivedKey(nextDerivedKey, sessionRootKey);2056    const slotA: StoredVault = {2057      recovery_vault_key: await encrypt(sessionRootKey, hex(nextDerivedKey), "recovery_vault_key_v1"),2058      version: 1,2059      salt: hex(salt),2060      nonce,2061      ciphertext,2062      tag,2063      recovery_salt: recovery.recoverySalt,2064      recovery_wrapped_root_key: recovery.wrappedRootKey,2065      recovery_nonce: recovery.wrappedNonce,2066      recovery_tag: recovery.wrappedTag,2067      ...pwRoot,2068    };2069    const slotB = generateNoiseBlob(ciphertext.length / 2);2070    if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");2071    await commitCreatedVaultSlots(slotA, slotB);2072    committed = true;2073    if (epoch !== vaultEpoch || vaultRemovalsInFlight) throw new Error("vault_changed");2074    cancelBreachScan();2075    vaultEpoch++;20762077    const previousDerivedKey = derivedKey;2078    const previousRootKey = rootKey;2079    derivedKey = nextDerivedKey;2080    rootKey = sessionRootKey;2081    nextDerivedKey = null;2082    sessionRootKey = null;2083    entries = nextEntries;2084    tombstones = new Map();2085    vaultMode = "real";2086    manualSummonRecall = new Map();2087    duressConfigured = nextDuressConfigured;2088    buildDomainIndexSync(entries);2089    if (previousDerivedKey && previousDerivedKey !== derivedKey) zeroKey(previousDerivedKey);2090    if (previousRootKey && previousRootKey !== rootKey) previousRootKey.fill(0);2091    touchAutoLock();20922093    // The receiver's identity was minted before this vault existed (adoption v22094    // needs it in its first frame), so re-seal it under the vault keys now.2095    await identityHooks?.onVaultCreated(password).catch((error) => {2096      console.warn("[Peach] local identity promotion failed:", error);2097    });2098    await clearStoredManualSummonRecall();2099    await restoreManualSummonRecall();21002101    return { vaultId };2102  } catch (error) {2103    if (committed) {2104      // Removal cannot use withVaultRemoval while this operation owns creationSettled.2105      try { await lock(); }2106      finally { await chrome.storage.local.remove([SLOT_A, SLOT_B, RECALL_STORAGE, "peach_last_modified_at"]); }2107    }2108    throw error;2109  } finally {2110    vaultCreatesInFlight--;2111    settle();2112    rootKeyBytes.fill(0);2113    if (nextDerivedKey) zeroKey(nextDerivedKey);2114    if (sessionRootKey) sessionRootKey.fill(0);2115  }2116}21172118export async function hasVault(): Promise<boolean> {2119  const raw = await chrome.storage.local.get([SLOT_A, SLOT_B]);2120  return raw[SLOT_A] !== undefined || raw[SLOT_B] !== undefined;2121}21222123/**2124 * Returns whether the real vault has recorded that a duress passphrase is2125 * configured. Reliable only after a real-mode unlock — before unlock or in2126 * decoy mode, returns false because we cannot read slot A's plaintext.2127 */2128export async function isDuressEnabled(): Promise<boolean> {2129  return vaultMode === "real" && duressConfigured;2130}21312132export async function setupDuress(duressPassword: string): Promise<void> {2133  if (vaultCreatesInFlight) throw new Error("vault_changed");2134  vaultWritesInFlight++;2135  try {2136  if (!derivedKey || vaultMode !== "real") {2137    throw new Error("vault must be unlocked in real mode");2138  }2139  // Encrypt the decoy payload (empty entries) under the duress key. Pad to2140  // at least the current slot A ciphertext size so the two slots look the2141  // same at rest at setup time.2142  const slotA = await loadSlot(SLOT_A);2143  if (!slotA) throw new Error("missing slot A");21442145  const decoySalt = generateSalt();2146  const decoyKey = await deriveKey(duressPassword, decoySalt);2147  try {2148    // Pad the decoy to the fixed duress ceiling. Slot A is re-encrypted to the2149    // same ceiling by the persistSlotA() call below (duressConfigured is now2150    // true), so both slots are exactly DURESS_SLOT_SIZE+tag at rest and their2151    // lengths cannot reveal that duress is configured (audit MEDIUM).2152    const plaintext = encodePayload([], false, DURESS_SLOT_SIZE);2153    const { nonce, ciphertext, tag } = await encrypt(decoyKey, plaintext, "slot_b_v1");2154    await writeSlot(SLOT_B, {2155      version: 1,2156      salt: hex(decoySalt),2157      nonce,2158      ciphertext,2159      tag,2160    });2161    // The stored decoy member belonged to the previous decoy slot.2162    await clearStoredManualSummonRecall("decoy");2163  } finally {2164    zeroKey(decoyKey);2165  }21662167  // Re-encrypt slot A with the duressConfigured flag set to true. No external2168  // flag is written — the bit lives inside the encrypted envelope.2169  duressConfigured = true;2170  await persistSlotA();2171  } finally { vaultWritesInFlight--; }2172}21732174export async function disableDuress(): Promise<void> {2175  if (vaultCreatesInFlight) throw new Error("vault_changed");2176  vaultWritesInFlight++;2177  try {2178  if (!derivedKey || vaultMode !== "real") {2179    throw new Error("vault must be unlocked in real mode");2180  }2181  // Overwrite slot B with fresh noise that matches slot A's size. The slot2182  // remains occupied so its mere existence does not signal that duress was2183  // ever configured.2184  const slotA = await loadSlot(SLOT_A);2185  if (slotA) {2186    await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));2187    await clearStoredManualSummonRecall("decoy");2188  }21892190  duressConfigured = false;2191  await persistSlotA();2192  } finally { vaultWritesInFlight--; }2193}21942195// L14/COR-015: this function intentionally checks slot A (real vault) only.2196// A duress-mode user attempting changePassword is rejected earlier by the2197// vaultMode === 'decoy' check at changePassword. The real-vs-decoy2198// distinction here is by design — duress users cannot rotate the real2199// password by guessing it, and the asymmetry in error timing is acceptable2200// because duress mode is opt-in and the user knows their own decoy key.2201export async function verifyMainPassword(password: string): Promise<boolean> {2202  const slotA = await loadSlot(SLOT_A);2203  if (!slotA) return false;2204  const key = await deriveKey(password, unhex(slotA.salt));2205  try {2206    return (await tryDecryptSlot(slotA, key, "slot_a_v1")) !== null;2207  } finally {2208    zeroKey(key);2209  }2210}22112212export async function unlock(password: string): Promise<boolean> {2213  return attemptUnlockWithDerive(password, deriveKey);2214}22152216async function attemptUnlockWithDerive(2217  password: string,2218  derive: typeof deriveKey,2219): Promise<boolean> {2220  vaultUnlocksInFlight++;2221  try {2222  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;2223  const epoch = vaultEpoch;2224  const stale = () => epoch !== vaultEpoch;2225  await revokeRecoveryReveal();2226  if (stale()) return false;2227  // Load both current-format slots in parallel. Both exist on a supported2228  // install; the2229  // parallel load and the parallel derivation below keep wall-clock time2230  // constant regardless of which slot's passphrase (real or decoy) the2231  // caller supplied, so a timing side channel cannot distinguish the2232  // duress path from the real-unlock path (DUR-002).2233  const [slotA, slotB] = await Promise.all([2234    loadSlot(SLOT_A),2235    loadSlot(SLOT_B),2236  ]);22372238  // Derive both keys in parallel, unconditionally.2239  const [keyA, keyB] = await Promise.all([2240    slotA ? derive(password, unhex(slotA.salt)) : Promise.resolve(null),2241    slotB ? derive(password, unhex(slotB.salt)) : Promise.resolve(null),2242  ]);22432244  // Attempt both decrypts in parallel. The Result variant lets us distinguish2245  // 'wrong_key' from 'corrupted' so callers can offer a history-restore path2246  // when a slot's schema is invalid even though AES-GCM authenticated (M7).2247  const [resultA, resultB] = await Promise.all([2248    keyA && slotA2249      ? tryDecryptSlotResult(slotA, keyA, "slot_a_v1")2250      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),2251    keyB && slotB2252      ? tryDecryptSlotResult(slotB, keyB, "slot_b_v1")2253      : Promise.resolve({ status: "wrong_key" } as TryDecryptResult),2254  ]);2255  const payloadA = resultA.status === "ok" ? resultA.payload : null;2256  const payloadB = resultB.status === "ok" ? resultB.payload : null;22572258  if (stale()) {2259    if (keyA) zeroKey(keyA);2260    if (keyB) zeroKey(keyB);2261    return false;2262  }22632264  if (payloadA && keyA) {2265    if (stale()) {2266      zeroKey(keyA);2267      if (keyB) zeroKey(keyB);2268      return false;2269    }2270    cancelBreachScan();2271    derivedKey = keyA;2272    vaultMode = "real";2273    manualSummonRecall = new Map();2274    entries = payloadA.entries;2275    tombstones = payloadA.tombstones;2276    duressConfigured = payloadA.duressConfigured;2277    buildDomainIndexSync(entries);2278    await loadSettings();2279    if (stale()) {2280      await lock();2281      return false;2282    }2283    touchAutoLock();2284    if (keyB) zeroKey(keyB);22852286    // Current vaults always carry a password-wrapped root key. Older vaults2287    // without this escrow are outside the supported storage format.2288    rootKey = slotA ? await deriveRootKeyFromDerivedKey(keyA, slotA) : null;2289    if (!rootKey) {2290      await lock();2291      return false;2292    }22932294    // Repair missing or stale escrow only after a real password authenticates the slot.2295    if (slotA) {2296      const escrowed = slotA.recovery_vault_key2297        ? await openSealedKey(rootKey, slotA.recovery_vault_key, "recovery_vault_key_v1") : null;2298      const matches = escrowed !== null && escrowed.every((byte, i) => byte === keyA[i]);2299      if (escrowed) zeroKey(escrowed);2300      if (stale()) { await lock(); return false; }2301      if (!matches) {2302        try {2303          const recoveryVaultKey = await encrypt(rootKey, hex(keyA), "recovery_vault_key_v1");2304          if (stale()) { await lock(); return false; }2305          await writeSlot(SLOT_A, { ...slotA, recovery_vault_key: recoveryVaultKey });2306          if (stale()) { await lock(); return false; }2307        } catch (error) {2308          await lock();2309          throw error;2310        }2311      }2312    }23132314    // PB-26-213: adopt legacy plaintext pair secrets into the encrypted2315    // record and refresh the trusted-session operational copy.2316    await reconcilePairSecrets(rootKey);2317    if (stale()) {2318      await lock();2319      return false;2320    }2321    await lockedSyncUnlockHook?.().catch((error) => {2322      console.warn("[Peach sync] locked inbox drain failed:", error);2323    });2324    if (stale()) {2325      await lock();2326      return false;2327    }2328    await resetPinFailedAttempts();2329    if (stale()) {2330      await lock();2331      return false;2332    }2333    await saveSessionKey(keyA, "real", epoch);2334    if (stale()) return false;2335    await restoreManualSummonRecall();2336    if (stale()) return false;2337    return true;2338  }23392340  if (payloadB && keyB) {2341    if (stale()) {2342      zeroKey(keyB);2343      if (keyA) zeroKey(keyA);2344      return false;2345    }2346    cancelBreachScan();2347    derivedKey = keyB;2348    vaultMode = "decoy";2349    manualSummonRecall = new Map();2350    decoySyncTeardownHook?.();2351    // A duress session must not retain the real vault's root key. It gates the2352    // recovery words, the sync identity, and the root wrap of the local device2353    // identity, so leaving it live would expose all three in duress mode.2354    if (rootKey) {2355      rootKey.fill(0);2356      rootKey = null;2357    }2358    entries = payloadB.entries;2359    tombstones = payloadB.tombstones;2360    duressConfigured = false;2361    buildDomainIndexSync(entries);2362    await loadSettings();2363    touchAutoLock();2364    if (keyA) zeroKey(keyA);2365    // PB-26-213: a duress session must never serve the real pair-secret map.2366    await dropSessionCache();2367    // Nor the real device identity: a duress session is not a real one.2368    await notifyIdentitySessionEnded();2369    if (stale()) {2370      await lock();2371      return false;2372    }2373    await saveSessionKey(keyB, "decoy", epoch);2374    if (stale()) return false;2375    await restoreManualSummonRecall();2376    if (stale()) return false;2377    return true;2378  }23792380  if (keyA) zeroKey(keyA);2381  if (keyB) zeroKey(keyB);2382  // Surface corruption (good AES tag, broken schema) distinctly from2383  // wrong-password so the popup can offer history-restore (M7/COR-007).2384  if (resultA.status === "corrupted") {2385    lastUnlockFailureReason = resultA.reason;2386  } else if (resultB.status === "corrupted") {2387    lastUnlockFailureReason = resultB.reason;2388  }2389  return false;2390  } finally { vaultUnlocksInFlight--; }2391}23922393// ---------------------------------------------------------------------------2394// MV3 service worker session key — survives SW restarts within a browser session2395// ---------------------------------------------------------------------------23962397// chrome.storage.session is cleared on browser close; survives SW restart.2398// Firefox does not implement it (persistent background script, no restart risk).2399const SESSION_KEY_STORAGE = "peach_session_dk";24002401// Order writes and removals so lock's awaited removal is a barrier after2402// every escrow write that started before it.2403let sessionKeyMutation = Promise.resolve();24042405function mutateSessionKey(mutation: () => Promise<void>): Promise<void> {2406  const task = sessionKeyMutation.then(mutation, mutation);2407  sessionKeyMutation = task.catch(() => undefined);2408  return task;2409}24102411// PB-26-203: the session-key escrow may only operate where startup positively2412// established trusted-only session storage. Defaults to available so direct2413// vault imports (tests, non-entry bootstraps) keep working; entry.ts applies2414// the real hardening result before the first restore.2415let sessionEscrowAvailable = true;24162417/**2418 * Apply the storage-hardening result at startup. When the trusted-only2419 * session state cannot be established, any stored session key is removed and2420 * the escrow stays off: the user unlocks again after a worker restart2421 * instead of trusting an unproven boundary.2422 */2423export async function applyStorageHardening(sessionEscrow: boolean): Promise<void> {2424  setSessionAllowed(sessionEscrow);2425  if (sessionEscrow) return;2426  sessionEscrowAvailable = false;2427  await clearSessionKey();2428}24292430async function saveSessionKey(2431  key: Uint8Array,2432  mode: "real" | "decoy",2433  expectedEpoch = vaultEpoch,2434): Promise<void> {2435  const session = chrome.storage.session;2436  if (!session || !sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;2437  const stored = { keyHex: hex(key), mode };2438  await mutateSessionKey(async () => {2439    if (!sessionEscrowAvailable || expectedEpoch !== vaultEpoch) return;2440    await session.set({ [SESSION_KEY_STORAGE]: stored });2441  });2442}24432444async function clearSessionKey(): Promise<void> {2445  const session = chrome.storage.session;2446  if (!session) return;2447  await mutateSessionKey(() => session.remove(SESSION_KEY_STORAGE));2448}24492450// A lock that only holds while the service worker stays alive is no lock at2451// all: a cold worker's restoreFromSession() would find the surviving session2452// key and silently re-unlock ~a minute after the user locked. So lock()2453// bumps this epoch synchronously at entry and zeroes keys/indexes before any2454// await; a restore that started earlier sees the mismatch after its next2455// await and aborts instead of publishing.2456let vaultEpoch = 0;24572458// One in-flight restore shared by concurrent callers: storage is read once2459// and the locked-sync unlock hook runs once.2460let restoreInFlight: Promise<boolean> | null = null;24612462/**2463 * On SW restart, re-derive all in-memory vault state from the session key2464 * stored in chrome.storage.session (set at unlock time, cleared by lock();2465 * also cleared on browser close or when restoration fails).2466 * Returns true if the vault was restored, false if no session key was found.2467 * No-ops if the vault is already unlocked.2468 */2469export async function restoreFromSession(): Promise<boolean> {2470  vaultUnlocksInFlight++;2471  try {2472  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return false;2473  if (derivedKey !== null) return true;2474  if (restoreInFlight) return restoreInFlight;2475  const task = restoreFromSessionInner();2476  restoreInFlight = task;2477  try {2478    return await task;2479  } finally {2480    restoreInFlight = null;2481  }2482  } finally { vaultUnlocksInFlight--; }2483}24842485async function restoreFromSessionInner(): Promise<boolean> {2486  const epoch = vaultEpoch;2487  const stale = () => epoch !== vaultEpoch;2488  if (derivedKey !== null) return true;2489  if (!sessionEscrowAvailable) return false;2490  if (!chrome.storage.session) return false;2491  const stored = await chrome.storage.session.get(SESSION_KEY_STORAGE);2492  if (stale()) return false;2493  const entry = stored[SESSION_KEY_STORAGE] as { keyHex: string; mode: "real" | "decoy" } | undefined;2494  if (!entry?.keyHex) return false;24952496  const key = unhex(entry.keyHex);2497  const slotKey = entry.mode === "real" ? SLOT_A : SLOT_B;2498  const aadTag = entry.mode === "real" ? "slot_a_v1" : "slot_b_v1";2499  const slot = await loadSlot(slotKey);2500  if (stale()) { zeroKey(key); return false; }2501  if (!slot) { await clearSessionKey(); return false; }25022503  const result = await tryDecryptSlotResult(slot, key, aadTag);2504  if (stale()) { zeroKey(key); return false; }2505  if (result.status !== "ok") { await clearSessionKey(); return false; }25062507  // Decrypted payload stays in locals until the final epoch-checked commit2508  // below; nothing observable is published before then.2509  const payload = result.payload;2510  await loadSettings();2511  if (stale()) { zeroKey(key); return false; }25122513  // Rehydrate the root key used by sync identity derivation from the password2514  // escrow stored on the current vault format.2515  let freshRoot: Uint8Array | null = null;2516  if (entry.mode === "real") {2517    freshRoot = await deriveRootKeyFromDerivedKey(key, slot);2518    if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }2519    if (!freshRoot) {2520      await lock();2521      return false;2522    }2523  }25242525  if (stale()) { zeroKey(key); if (freshRoot) zeroKey(freshRoot); return false; }2526  if (freshRoot) {2527    // PB-26-213: encrypted pair-secret record + session copy, before publish.2528    await reconcilePairSecrets(freshRoot);2529    if (stale()) { zeroKey(key); zeroKey(freshRoot); return false; }2530  } else {2531    // PB-26-213: a duress restore must never serve the real pair-secret map.2532    await dropSessionCache();2533    // Nor the real device identity.2534    await notifyIdentitySessionEnded();2535    if (stale()) { zeroKey(key); return false; }2536  }2537  cancelBreachScan();2538  derivedKey = key;2539  vaultMode = entry.mode;2540  manualSummonRecall = new Map();2541  if (entry.mode === "decoy") decoySyncTeardownHook?.();2542  entries = payload.entries;2543  tombstones = payload.tombstones;2544  duressConfigured = entry.mode === "real" ? payload.duressConfigured : false;2545  if (freshRoot) rootKey = freshRoot;2546  buildDomainIndexSync(entries);2547  touchAutoLock();25482549  await lockedSyncUnlockHook?.().catch((error) => {2550    console.warn("[Peach sync] locked inbox drain failed:", error);2551  });2552  if (stale()) return false;2553  await restoreManualSummonRecall();2554  if (stale()) return false;25552556  return true;2557}25582559export async function lock(): Promise<void> {2560  const recoveryRevoked = revokeRecoveryReveal();2561  // A user-initiated lock must be durable across MV3 service-worker restarts.2562  // The SW is idle-killed after ~30s of inactivity, and the popup's next open2563  // wakes a cold SW whose restoreFromSession() reads chrome.storage.session.2564  // If the session key survived lock(), that restore would silently re-unlock2565  // the vault ~a minute after the user locked it — a lock that only held2566  // while the SW happened to stay alive. The background-sync convenience the2567  // session key once bought (sync runner re-waking to a restored vault) is2568  // not worth an unlocked vault the user never asked to unlock; when locked,2569  // sync-runner correctly reports VAULT_LOCKED instead.2570  cancelBreachScan();2571  vaultEpoch++;2572  if (derivedKey) {2573    zeroKey(derivedKey);2574    derivedKey = null;2575  }2576  if (rootKey) {2577    rootKey.fill(0);2578    rootKey = null;2579  }25802581  entries = [];2582  manualSummonRecall = new Map();2583  tombstones = new Map();2584  domainIndex = new Map();2585  vaultMode = "real";2586  duressConfigured = false;2587  clearAutoLock();2588  try {2589    chrome.runtime?.sendMessage?.({ type: "VAULT_LOCKED" })?.catch?.(() => undefined);2590  } catch { /* UI contexts may already be closed */ }2591  await clearSessionKey();2592  await recoveryRevoked;2593  // The decrypted identity is session state as well, so a locked vault must not2594  // leave one behind; clear it after the in-memory state is gone.2595  await notifyIdentitySessionEnded();2596}25972598/// Identifies the current unlock session for authorization across awaited work.2599export function getVaultEpoch(): number {2600  return vaultEpoch;2601}26022603export function isUnlocked(): boolean {2604  return derivedKey !== null;2605}2606/** True only while the active session is unlocked through the decoy slot. */2607export function isDecoyMode(): boolean {2608  return derivedKey !== null && vaultMode === "decoy";2609}26102611// Opens the vault using a pre-derived AES-256 key (skipping Argon2id). The2612// PIN-unlock path unwraps this key from its PIN wrap; the passphrase path2613// always derives from scratch via Argon2id.2614export async function unlockWithKey(2615  masterKeyHex: string,2616): Promise<{ ok: true; entries: VaultEntry[] } | { ok: false; error: string }> {2617  vaultUnlocksInFlight++;2618  try {2619  if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };2620  const epoch = vaultEpoch;2621  const stale = () => epoch !== vaultEpoch;2622  await revokeRecoveryReveal();2623  if (stale()) return { ok: false, error: "vault_locked" };2624  let masterKeyBytes: Uint8Array | null = null;2625  try {2626    masterKeyBytes = unhex(masterKeyHex);2627    const stored = await loadSlot(SLOT_A);2628    if (!stored) return { ok: false, error: "invalid_key" };2629    const payload = await tryDecryptSlot(stored, masterKeyBytes, "slot_a_v1");2630    if (!payload || stale()) {2631      zeroKey(masterKeyBytes);2632      return { ok: false, error: "invalid_key" };2633    }26342635    cancelBreachScan();2636    derivedKey = masterKeyBytes;2637    vaultMode = "real";2638    manualSummonRecall = new Map();2639    entries = payload.entries;2640    tombstones = payload.tombstones;2641    duressConfigured = payload.duressConfigured;2642    buildDomainIndexSync(entries);2643    await loadSettings();2644    touchAutoLock();26452646    rootKey = await deriveRootKeyFromDerivedKey(masterKeyBytes, stored);2647    if (!rootKey) {2648      await lock();2649      return { ok: false, error: "invalid_key" };2650    }2651    await reconcilePairSecrets(rootKey);2652    if (stale()) {2653      await lock();2654      return { ok: false, error: "invalid_key" };2655    }2656    await saveSessionKey(masterKeyBytes, "real", epoch);2657    if (stale()) return { ok: false, error: "invalid_key" };2658    await restoreManualSummonRecall();2659    if (stale()) return { ok: false, error: "invalid_key" };2660    return { ok: true, entries };2661  } catch {2662    if (masterKeyBytes && derivedKey !== masterKeyBytes) zeroKey(masterKeyBytes);2663    return { ok: false, error: "invalid_key" };2664  }2665  } finally { vaultUnlocksInFlight--; }2666}26672668// --- Adoption duress-slot helpers (passthrough, no decrypt) ---26692670/**2671 * Adoption SOURCE helper: returns the sealed slot B as a JSON string when2672 * duress is configured and slot B exists, so the inline snapshot can ship it2673 * to the receiver. Returns null otherwise. Never decrypts.2674 */2675export async function exportDuressSlotForAdoption(): Promise<string | null> {2676  if (!(await isDuressEnabled())) return null;2677  const slotB = await loadSlot(SLOT_B);2678  if (!slotB) return null;2679  return JSON.stringify(slotB);2680}26812682/**2683 * Adoption RECEIVER helper: installs a duress slot received from a source2684 * device. Validates the StoredVault shape (same guard as unlockFromCodex)2685 * and writes it to slot B. Throws on invalid shape so the caller can treat2686 * it as a non-fatal snapshot failure. Never decrypts.2687 */2688export async function installAdoptedDuressSlot(json: string): Promise<void> {2689  if (vaultCreatesInFlight) throw new Error("vault_changed");2690  vaultWritesInFlight++;2691  try {2692  let parsed: StoredVault;2693  try {2694    const raw = JSON.parse(json) as unknown;2695    if (!hasValidVaultSchema(raw)) {2696      throw new Error("invalid_duress_slot_shape");2697    }2698    parsed = raw;2699  } catch (err) {2700    if (err instanceof SyntaxError) {2701      throw new Error("invalid_duress_slot_shape");2702    }2703    throw err;2704  }2705  await writeSlot(SLOT_B, parsed);2706  // The adopted decoy slot replaces any local decoy the member belonged to.2707  await clearStoredManualSummonRecall("decoy");2708  manualSummonRecall = new Map();2709  await restoreManualSummonRecall();2710  } finally { vaultWritesInFlight--; }2711}27122713/**2714 * Restore the vault from a parsed Peach Codex payload.2715 *2716 * The supplied passphrase is verified against the Codex's slotA *before* any2717 * storage mutation — wrong passphrases return without touching disk. On2718 * success, the current vault state is snapshotted (reason: "restore") so the2719 * user can revert via Settings -> Vault History, then slotA/slotB are written2720 * and `peach_last_modified_at` is set to the Codex's recorded timestamp. A2721 * regular `unlock()` follows so the rest of the SW sees the standard2722 * post-unlock state.2723 *2724 * Intentionally non-Pro-gated — see peach_codex_v2.md "Pro gating". A Codex2725 * printed by a Pro user must always be restorable, even on a free device.2726 *2727 * Timing is not held constant here (in contrast to `unlock`): the Codex flow2728 * is an explicit user action with a known passphrase, not a passive lock2729 * screen, so the duress-vs-real timing side channel does not apply.2730 */2731export async function unlockFromCodex(params: {2732  slotA: string; // JSON string of StoredVault for slot A2733  slotB: string | null; // JSON string of StoredVault for slot B, or null2734  timestamp: number;2735  masterPassphrase: string;2736}): Promise<2737  | { ok: true; entryCount: number }2738  | { ok: false; reason: "wrong_passphrase" | "invalid_slot_format" | "missing_root_escrow" }2739> {2740  if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) throw new Error("vault_changed");2741  vaultReplacementInFlight = true;2742  try {2743    let parsedSlotA: StoredVault;2744    let parsedSlotB: StoredVault | null = null;2745    try {2746      const rawA = JSON.parse(params.slotA) as unknown;2747      if (!hasValidVaultSchema(rawA)) {2748        return { ok: false, reason: "invalid_slot_format" };2749      }2750      parsedSlotA = rawA;2751      if (params.slotB !== null) {2752        const rawB = JSON.parse(params.slotB) as unknown;2753        if (!hasValidVaultSchema(rawB)) {2754          return { ok: false, reason: "invalid_slot_format" };2755        }2756        parsedSlotB = rawB;2757      }2758    } catch {2759      return { ok: false, reason: "invalid_slot_format" };2760    }27612762    // Verify the passphrase and the password-wrapped root escrow against the2763    // staged Slot A WITHOUT writing anything. Payload decoding is part of the2764    // trial decrypt, so unlock() cannot be the first place these checks run.2765    const trialKey = await deriveKey(params.masterPassphrase, unhex(parsedSlotA.salt));2766    const trialPayload = await tryDecryptSlot(parsedSlotA, trialKey, "slot_a_v1");2767    if (!trialPayload) {2768      zeroKey(trialKey);2769      return { ok: false, reason: "wrong_passphrase" };2770    }2771    const hasEscrow =2772      !!parsedSlotA.pw_root_ciphertext && !!parsedSlotA.pw_root_nonce && !!parsedSlotA.pw_root_tag;2773    if (!hasEscrow) {2774      zeroKey(trialKey);2775      return { ok: false, reason: "missing_root_escrow" };2776    }2777    const stagedRootKey = await deriveRootKeyFromDerivedKey(trialKey, parsedSlotA);2778    if (!stagedRootKey) {2779      zeroKey(trialKey);2780      return { ok: false, reason: "wrong_passphrase" };2781    }2782    zeroKey(stagedRootKey);2783    zeroKey(trialKey);27842785    // Stage the complete candidate pair in memory before touching storage.2786    const stagedSlotB = parsedSlotB ?? generateNoiseBlob(parsedSlotA.ciphertext.length / 2);27872788    // Drop the trial key; `unlock()` below derives its own copy. Holding two2789    // copies of the master key in memory at once would be a needless surface.27902791    // Snapshot the about-to-be-overwritten on-disk state so the user can revert2792    // a mistaken Codex restore via the Vault History UI. Non-fatal if it fails.2793    await takeVaultSnapshot("restore");2794    const previousSlotA = await loadSlot(SLOT_A);2795    const previousSlotB = await loadSlot(SLOT_B);2796    let slotACommitted = false;2797    let slotBCommitted = false;2798    try {2799      await writeSlot(SLOT_A, parsedSlotA);2800      slotACommitted = true;2801      await writeSlot(SLOT_B, stagedSlotB);2802      slotBCommitted = true;2803      await chrome.storage.local.set({2804        peach_last_modified_at: String(params.timestamp),2805      });2806    } catch (err) {2807      if (slotBCommitted && previousSlotB) await writeSlot(SLOT_B, previousSlotB);2808      if (slotACommitted && previousSlotA) await writeSlot(SLOT_A, previousSlotA);2809      throw err;2810    }28112812    // Standard unlock path so domain index, settings, auto-lock, and2813    // recovery-key state all populate exactly as a normal unlock would.2814    const ok = await unlock(params.masterPassphrase);2815    if (!ok) {2816      // Should be unreachable — the staged candidate passed the same checks.2817      return { ok: false, reason: "wrong_passphrase" };2818    }2819    return { ok: true, entryCount: getEntries().length };2820  } finally {2821    vaultReplacementInFlight = false;2822  }2823}28242825// Returns the current in-memory derived key as a hex string. Only the PIN2826// unlock path needs this value, and it reads module state directly; this2827// accessor exists so unlockWithKey's root-key rehydration is testable.2828export /* @testable */ function getDerivedKeyHex(): string {2829  if (!derivedKey) throw new Error("vault_not_unlocked");2830  return hex(derivedKey);2831}28322833/**2834 * Returns the vault's stable root key as hex, or null when locked / not yet2835 * populated. The root key is random per-vault, generated at creation, escrowed2836 * under the recovery words, and re-wrapped (not regenerated) on every password2837 * change — so it is INVARIANT across password rotation, unlike getDerivedKeyHex.2838 *2839 * This is the correct input for sync identity derivation (vault_id, the Noise2840 * NK static key, the Ed25519 manifest signing key, and per-entry envelope2841 * keys): paired devices keep the same identity and can still decrypt each2842 * other's entries after either side rotates its master password (SEV-2-B).2843 *2844 * Returns null rather than throwing so sync callers degrade to VAULT_LOCKED2845 * instead of crashing; rootKey is populated on every supported real-mode2846 * unlock via deriveRootKeyFromDerivedKey.2847 */2848export function getRootKeyHex(): string | null {2849  return rootKey ? hex(rootKey) : null;2850}28512852export function getEntries(): VaultEntry[] {2853  if (!derivedKey) throw new Error("vault_locked");2854  return entries.filter((entry) => !entry.deletedAt);2855}28562857const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;28582859export function getIdentities(): SavedIdentity[] {2860  if (!derivedKey) throw new Error("vault_locked");2861  const active = entries.filter((e) => !e.deletedAt && e.type === "login");28622863  const emailMap = new Map<string, { lastUsed: number; count: number; domain: string }>();2864  const usernameMap = new Map<string, { lastUsed: number; count: number; domain: string }>();28652866  for (const entry of active) {2867    const domain = extractDomain(entry.url ?? "") ?? "";2868    const modifiedAt = entry.modifiedAt ?? entry.createdAt ?? 0;28692870    function tally(map: Map<string, { lastUsed: number; count: number; domain: string }>, v: string) {2871      const existing = map.get(v);2872      if (!existing || modifiedAt > existing.lastUsed) {2873        map.set(v, { lastUsed: modifiedAt, count: (existing?.count ?? 0) + 1, domain });2874      } else {2875        map.set(v, { ...existing, count: existing.count + 1 });2876      }2877    }28782879    const uVal = entry.username?.trim();2880    if (uVal) tally(EMAIL_RE.test(uVal) ? emailMap : usernameMap, uVal);28812882    // Also count the dedicated email field — entries created via the inline2883    // popup new-entry form store email here rather than in username.2884    const eVal = entry.email?.trim();2885    if (eVal) tally(emailMap, eVal);2886  }28872888  const toIdentity = (type: "email" | "username") =>2889    ([value, d]: [string, { lastUsed: number; count: number; domain: string }]): SavedIdentity => ({2890      value, type, lastUsed: d.lastUsed, useCount: d.count, exampleDomain: d.domain || undefined,2891    });28922893  return [2894    ...[...emailMap.entries()].map(toIdentity("email")).sort((a, b) => b.useCount - a.useCount),2895    ...[...usernameMap.entries()].map(toIdentity("username")).sort((a, b) => b.useCount - a.useCount),2896  ];2897}28982899export async function batchAddEntries(drafts: EntryDraft[]): Promise<VaultEntry[]> {2900  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");29012902  const now = Date.now();2903  const added: VaultEntry[] = [];2904  for (const draft of drafts) {2905    try {2906      const sanitized = sanitizeEntryDraft(draft);2907      const nextEntry: VaultEntry = {2908        ...sanitized,2909        id: crypto.randomUUID(),2910        createdAt: now,2911        modifiedAt: monotonicEntryTimestamp(),2912      };2913      entries.push(nextEntry);2914      added.push(nextEntry);2915    } catch {2916      // Skip invalid drafts silently — caller can see diff between input and output length2917    }2918  }29192920  if (added.length > 0) {2921    await persistEntries();2922  }29232924  return added;2925}29262927/**2928 * Restore a set of entries in full fidelity — preserves id, createdAt,2929 * modifiedAt, and every other field unlike `batchAddEntries` which2930 * assigns fresh identity. Used by restore paths where the backup is the2931 * authoritative source of truth. `mode` controls how entries already in2932 * the vault are treated.2933 */2934export async function restoreEntries(2935  incoming: VaultEntry[],2936  mode: "replace" | "merge"2937): Promise<{ added: number; updated: number; skipped: number }> {2938  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");29392940  // A replace with zero incoming entries is almost certainly a caller bug2941  // (e.g. an import that silently dropped everything). Refuse rather than2942  // wipe the vault.2943  if (mode === "replace" && incoming.length === 0) {2944    throw new Error("refuse to replace with empty entry set");2945  }29462947  let added = 0;2948  let updated = 0;2949  let skipped = 0;29502951  if (mode === "replace") {2952    entries = [];2953    for (const entry of incoming) {2954      const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2955      if (!normalized) {2956        skipped += 1;2957        continue;2958      }2959      entries.push(normalized);2960      if (normalized.deletedAt) {2961        tombstones.set(2962          normalized.id,2963          Math.max(tombstones.get(normalized.id) ?? 0, normalized.deletedAt),2964        );2965      } else {2966        tombstones.delete(normalized.id);2967      }2968      added += 1;2969    }2970  } else {2971    const byId = new Map<string, VaultEntry>();2972    for (const e of entries) byId.set(e.id, e);29732974    for (const entry of incoming) {2975      const normalized = naturalizeRestoredId(sanitizeRestoredEntry(entry));2976      if (!normalized) {2977        skipped += 1;2978        continue;2979      }2980      const existing = byId.get(normalized.id);2981      if (!existing) {2982        entries.push(normalized);2983        if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2984        else tombstones.delete(normalized.id);2985        added += 1;2986      } else if (normalized.modifiedAt > existing.modifiedAt) {2987        const idx = entries.findIndex((e) => e.id === existing.id);2988        if (idx !== -1) {2989          entries[idx] = normalized;2990          if (normalized.deletedAt) tombstones.set(normalized.id, normalized.deletedAt);2991          else tombstones.delete(normalized.id);2992          updated += 1;2993        }2994      } else {2995        skipped += 1;2996      }2997    }2998  }29993000  await persistEntries("import");3001  return { added, updated, skipped };3002}30033004/**3005 * A Peach entry id is a UUID. A restored or imported file carries whatever id3006 * its author used, and no reader bounds it, so one oversized id would ride3007 * into every future sync frame and be rejected there — a permanent, opaque3008 * failure on both platforms, caused by data that was already local.3009 *3010 * The action is mint, not reject: this is the last point where an id is still3011 * ours to choose, so the worst outcome is one duplicate if the same vault is3012 * later restored beside a device still holding the old id. Rejecting would3013 * lose the user's import.3014 *3015 * Deliberately NOT inside sanitizeRestoredEntry, which applyMergedRemoteEntries3016 * also calls. Sync has to adopt a peer's id verbatim — that is the only thing3017 * keeping two devices agreed on which entry they are discussing — so reminting3018 * there would fork identity on every device, on every round.3019 */3020const ENTRY_ID_SHAPE = /^[A-Za-z0-9_-]{1,64}$/;30213022function naturalizeRestoredId(entry: VaultEntry | null): VaultEntry | null {3023  if (!entry || ENTRY_ID_SHAPE.test(entry.id)) return entry;3024  return { ...entry, id: crypto.randomUUID() };3025}30263027/**3028 * Validate + normalise a VaultEntry coming from a backup, import, or sync3029 * peer. MV-6: this is a strict field WHITELIST — `normalizeEntry` copies3030 * only known VaultEntry fields (unknown/attacker keys are dropped), and3031 * nested `passkey`/`canary` shapes are rebuilt field-by-field, never3032 * spread. Returns null for values the live vault shouldn't accept.3033 */3034function sanitizeRestoredEntry(entry: VaultEntry): VaultEntry | null {3035  if (!entry || typeof entry !== "object") return null;3036  const title = typeof entry.title === "string" ? entry.title.trim() : "";3037  if (!title) return null;3038  const id = typeof entry.id === "string" && entry.id ? entry.id : crypto.randomUUID();3039  const now = Date.now();3040  const createdAt = typeof entry.createdAt === "number" ? entry.createdAt : now;3041  const modifiedAt = typeof entry.modifiedAt === "number" ? entry.modifiedAt : createdAt;30423043  // normalizeEntry whitelists every known VaultEntry field before the entry3044  // reaches the live vault.3045  const normalized = normalizeEntry({3046    ...entry,3047    id,3048    title,3049    type: entry.type ?? "login",3050    createdAt,3051    modifiedAt,3052  });30533054  if (normalized.passkey) {3055    normalized.passkey = sanitizePasskey(normalized.passkey);3056  }3057  if (normalized.canary) {3058    normalized.canary = sanitizeCanary(normalized.canary);3059  }3060  // PCH-01-016: bound tags on the restore path too, so both import funnels agree.3061  normalized.tags = sanitizeTags(normalized.tags);30623063  // Login entries from backup must carry a password (or be passkey-only,3064  // in which case the passkey sub-object replaces the password requirement).3065  if (3066    normalized.type === "login" &&3067    !normalized.passkey &&3068    typeof normalized.password !== "string"3069  ) {3070    return null;3071  }3072  if (entry.passkey && !normalized.passkey) {3073    // Entry claimed a passkey but the shape didn't validate — refuse the3074    // whole entry rather than silently importing a credential-less husk.3075    return null;3076  }30773078  return normalized;3079}30803081/**3082 * Rebuild a PasskeyData object from untrusted input, field by field.3083 * Returns undefined when required fields are missing/mistyped — a rogue3084 * passkey credential must not activate via import (MV-6 attack scenario).3085 */3086function sanitizePasskey(pk: unknown): PasskeyData | undefined {3087  if (!pk || typeof pk !== "object") return undefined;3088  const r = pk as Record<string, unknown>;3089  if (3090    typeof r.rpId !== "string" || !r.rpId ||3091    typeof r.credentialId !== "string" || !r.credentialId ||3092    typeof r.publicKeyCose !== "string" ||3093    typeof r.userHandle !== "string" ||3094    typeof r.userName !== "string"3095  ) {3096    return undefined;3097  }3098  return {3099    rpId: r.rpId,3100    rpName: typeof r.rpName === "string" ? r.rpName : r.rpId,3101    credentialId: r.credentialId,3102    publicKeyCose: r.publicKeyCose,3103    privateKeyJwk:3104      r.privateKeyJwk && typeof r.privateKeyJwk === "object"3105        ? (r.privateKeyJwk as JsonWebKey)3106        : undefined,3107    userHandle: r.userHandle,3108    userName: r.userName,3109    userDisplayName:3110      typeof r.userDisplayName === "string" ? r.userDisplayName : r.userName,3111    algorithm: r.algorithm === -8 ? -8 : -7,3112    signCount: typeof r.signCount === "number" ? r.signCount : 0,3113    aaguid: typeof r.aaguid === "string" ? r.aaguid : "",3114    backupEligible: r.backupEligible === true,3115    backupState: r.backupState === true,3116    lastUsedAt: typeof r.lastUsedAt === "number" ? r.lastUsedAt : undefined,3117    browser: r.browser === "chrome" || r.browser === "firefox" ? r.browser : undefined,3118    transports: Array.isArray(r.transports)3119      ? r.transports.filter((t): t is string => typeof t === "string")3120      : undefined,3121    createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),3122  };3123}31243125/**3126 * Rebuild a Canary object from untrusted input. The webhook must be a3127 * well-formed HTTPS URL — a poisoned canary.webhookUrl is a standing3128 * exfiltration endpoint that the canary subsystem will POST entry titles3129 * to (MV-6 attack scenario). Invalid → the canary is dropped, not the3130 * entry. FIRE_CANARY_PING revalidates the destination policy at dispatch3131 * (canaryWebhookUrl), so this import-time check is the3132 * outer of two gates.3133 */3134function sanitizeCanary(c: unknown): Canary | undefined {3135  if (!c || typeof c !== "object") return undefined;3136  const r = c as Record<string, unknown>;3137  if (typeof r.webhookUrl !== "string") return undefined;3138  let url: URL;3139  try {3140    url = new URL(r.webhookUrl);3141  } catch {3142    return undefined;3143  }3144  if (url.protocol !== "https:") return undefined;3145  return {3146    webhookUrl: url.toString(),3147    label: typeof r.label === "string" ? r.label : undefined,3148    lastPinged: typeof r.lastPinged === "number" ? r.lastPinged : undefined,3149    pingCount: typeof r.pingCount === "number" ? r.pingCount : undefined,3150  };3151}31523153/**3154 * MV-6 / PCH-01-016: tags from imported / batch-added entries are untrusted.3155 * Keep only non-empty strings, cap each at 256 chars, and cap the count at 2553156 * (the same per-entry ceiling the export codec enforces, peachPayload.ts).3157 * Non-array or all-invalid input collapses to undefined.3158 */3159function sanitizeTags(tags: unknown): string[] | undefined {3160  if (!Array.isArray(tags)) return undefined;3161  const out: string[] = [];3162  for (const t of tags) {3163    if (typeof t !== "string") continue;3164    const trimmed = t.trim();3165    if (!trimmed) continue;3166    out.push(trimmed.slice(0, 256));3167    if (out.length >= 255) break;3168  }3169  return out.length > 0 ? out : undefined;3170}31713172// Soft-deletes every non-deleted entry in one call. The literal string3173// argument is a tripwire against accidental calls — any caller that would3174// wipe the vault has to consciously type "REPLACE_ALL". Do not relax this3175// to a boolean.3176export async function clearVaultEntries(3177  confirmation: "REPLACE_ALL"3178): Promise<void> {3179  if (confirmation !== "REPLACE_ALL") {3180    throw new Error("clearVaultEntries requires explicit confirmation");3181  }3182  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3183  for (const entry of entries) {3184    if (!entry.deletedAt) {3185      const stamp = monotonicEntryTimestamp(Math.max(3186        entry.modifiedAt,3187        tombstones.get(entry.id) ?? 0,3188      ));3189      entry.deletedAt = stamp;3190      entry.modifiedAt = stamp;3191      tombstones.set(entry.id, stamp);3192    }3193  }3194  await persistEntries();3195}31963197export async function addEntry(entry: EntryDraft): Promise<VaultEntry> {3198  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3199  const epoch = vaultEpoch;3200  const key = derivedKey;32013202  const sanitized = sanitizeEntryDraft(entry);3203  const now = Date.now();3204  const stamp = monotonicEntryTimestamp();3205  const nextEntry: VaultEntry = {3206    ...sanitized,3207    id: crypto.randomUUID(),3208    createdAt: now,3209    modifiedAt: stamp,3210    // Stamp passwordChangedAt at creation so age tracking is accurate from3211    // day one. Non-login entries carry the same stamp harmlessly.3212    passwordChangedAt: sanitized.password ? stamp : undefined,3213  };32143215  // Clone-and-replace so a failed persist rolls back the in-memory state3216  // (COR-008). Without this, a quota-full or storage error leaves the3217  // module-level `entries` ahead of what's actually on disk.3218  const rollback = entries;3219  entries = [...entries, nextEntry];3220  try {3221    await persistEntries();3222  } catch (err) {3223    entries = rollback;3224    throw err;3225  }32263227  if (settings.breachMonitoring !== false && nextEntry.type === "login" && nextEntry.password && epoch === vaultEpoch) {3228    checkEntryBreachDetached({ id: nextEntry.id, password: nextEntry.password, epoch, key });3229  }32303231  fireSyncTrigger("vault_change");32323233  return nextEntry;3234}32353236/// Attach unambiguous account credentials without discarding other entry data.3237export async function consolidatePasskeyEntries(): Promise<void> {3238  if (!derivedKey || vaultCreatesInFlight) return;3239  const epoch = vaultEpoch;3240  const rollback = entries;3241  const next = entries.map((entry) => ({ ...entry }));3242  if (!mergePasskeyOnlyIntoLogins(next).merged) return;3243  const unchanged = next.map((entry) => ({ entry, modifiedAt: entry.modifiedAt }));3244  entries = next;3245  try {3246    await persistEntries();3247  } catch (err) {3248    // Other writers can replace entries or mutate a deletion in this array.3249    if (epoch === vaultEpoch && entries === next && entries.length === unchanged.length &&3250      unchanged.every(({ entry, modifiedAt }, index) => entries[index] === entry && entry.modifiedAt === modifiedAt)) {3251      entries = rollback;3252      buildDomainIndexSync(entries);3253    }3254    throw err;3255  }3256}32573258export async function updateEntry(3259  id: string,3260  patch: Partial<VaultEntry>3261): Promise<void> {3262  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");32633264  const idx = entries.findIndex((entry) => entry.id === id);3265  if (idx === -1 || entries[idx].deletedAt) {3266    throw new Error("entry_not_found");3267  }32683269  const current = entries[idx];3270  const owner = entries;3271  const epoch = vaultEpoch;3272  const key = derivedKey;3273  const sanitizedPatch = sanitizeEntryPatch(patch);3274  // Refresh passwordChangedAt only when the password value actually changes —3275  // a metadata-only update (title, tags, etc.) must not reset the age clock3276  // that drives the Pro health rotation recommendation.3277  const passwordChanged =3278    "password" in patch &&3279    typeof sanitizedPatch.password === "string" &&3280    sanitizedPatch.password !== current.password;3281  const stamp = monotonicEntryTimestamp(current.modifiedAt);3282  // When the password actually changes, push the outgoing one onto the history3283  // (newest first) so the user can reveal/copy/restore it later. We record the3284  // age it carried (passwordChangedAt, falling back to createdAt) rather than3285  // `now`, so the list reflects when each password was last in effect. Only3286  // capture a non-empty prior value — clearing a password leaves no secret to3287  // keep, and we skip an immediate exact duplicate (e.g. restore-then-restore)3288  // to avoid noise.3289  const priorPassword = current.password;3290  const shouldCapture =3291    passwordChanged &&3292    typeof priorPassword === "string" &&3293    priorPassword.length > 0 &&3294    current.passwordHistory?.[0]?.password !== priorPassword;3295  const nextHistory = shouldCapture3296    ? [3297        { password: priorPassword!, changedAt: current.passwordChangedAt ?? current.createdAt },3298        ...(current.passwordHistory ?? []),3299      ].slice(0, PASSWORD_HISTORY_MAX)3300    : current.passwordHistory;3301  const next = {3302    ...current,3303    ...sanitizedPatch,3304    modifiedAt: stamp,3305    ...(passwordChanged ? { passwordChangedAt: stamp, passwordHistory: nextHistory } : {}),3306  };3307  entries[idx] = next;33083309  // Card entries must retain their card number3310  if (entries[idx].type === "card" && !entries[idx].cardNumber) {3311    entries[idx] = current;3312    throw new Error("card number is required for card entries");3313  }33143315  // Roll the in-memory entry back to its pre-edit state if the disk write3316  // fails (e.g. storage quota). Without this the module-level `entries` array3317  // would hold an edit that never landed on disk, diverging from the vault3318  // until the next unlock silently reverts it (SEV-3-A). Mirrors addEntry.3319  try {3320    await persistEntries();3321  } catch (err) {3322    if (epoch === vaultEpoch && entries === owner && entries[idx] === next && next.modifiedAt === stamp && !next.deletedAt) entries[idx] = current;3323    throw err;3324  }33253326  if (passwordChanged && settings.breachMonitoring !== false && next.type === "login" && next.password && epoch === vaultEpoch) {3327    checkEntryBreachDetached({ id, password: next.password, epoch, key });3328  }33293330  fireSyncTrigger("vault_change");3331}33323333export async function deleteEntry(id: string): Promise<void> {3334  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");33353336  const entry = entries.find((item) => item.id === id);3337  if (!entry || entry.deletedAt) {3338    throw new Error("entry_not_found");3339  }33403341  // Tombstone timestamp must be strictly greater than the entry's last3342  // modification so the deletion wins LWW against any in-flight edit, even3343  // under clock skew (SEV-2-E).3344  const previousModifiedAt = entry.modifiedAt;3345  const previousTombstone = tombstones.get(id);3346  const stamp = monotonicEntryTimestamp(Math.max(entry.modifiedAt, previousTombstone ?? 0));3347  entry.deletedAt = stamp;3348  entry.modifiedAt = stamp;3349  tombstones.set(id, stamp);3350  // Roll the tombstone back if the disk write fails, so a quota error doesn't3351  // leave the entry deleted in memory but alive on disk (SEV-3-A).3352  try {3353    await persistEntries();3354  } catch (err) {3355    delete entry.deletedAt;3356    entry.modifiedAt = previousModifiedAt;3357    if (previousTombstone === undefined) tombstones.delete(id);3358    else tombstones.set(id, previousTombstone);3359    throw err;3360  }3361  fireSyncTrigger("vault_change");3362}33633364export function getDeletedEntries(): VaultEntry[] {3365  if (!derivedKey) return [];3366  return entries.filter((e) => !!e.deletedAt);3367}33683369/** Return all durable deletion timestamps, including purged full entries. */3370export function getTombstoneManifest(): Record<string, number> {3371  if (!derivedKey) return {};3372  return Object.fromEntries(tombstones);3373}33743375/**3376 * Returns the vault's monotonic version — the `peach_last_modified_at` value3377 * stamped on every user-initiated write. Remote (sync) writes do NOT advance3378 * this version so a sync round never cascades into a second outbound sync.3379 */3380export async function getVaultVersion(): Promise<number> {3381  try {3382    const raw = await chrome.storage.local.get("peach_last_modified_at");3383    const v = (raw as Record<string, unknown>).peach_last_modified_at;3384    if (typeof v === "number") return v;3385    if (typeof v === "string" && v !== "") {3386      const n = Number.parseInt(v, 10);3387      return Number.isFinite(n) ? n : 0;3388    }3389    return 0;3390  } catch {3391    return 0;3392  }3393}33943395/**3396 * Apply a batch of remote entries + tombstones from a sync peer.3397 * Last-write-wins by `modifiedAt`; a tombstone supersedes a live entry when3398 * `deletedAt > modifiedAt` on the local side. Mutates `entries` directly and3399 * persists with reason `sync_received` — does NOT fire the sync dispatcher, so3400 * applying a sync round cannot cascade into another outbound sync.3401 *3402 * `applied` counts entries that actually changed local state (new add,3403 * overwrite-by-newer, or new tombstone). `received` is the raw payload size3404 * the caller can surface in the sync result UI.3405 */3406export async function applyMergedRemoteEntries(3407  remoteEntries: VaultEntry[],3408  remoteTombstones: Record<string, number>,3409): Promise<{ received: number; applied: number; conflicts: number }> {3410  // DESIGN: last-write-wins is applied PER-ENTRY, not per-field. If two devices3411  // concurrently edit different fields of the same entry, the one with the3412  // newer modifiedAt wins the whole entry and the other device's field edits3413  // are dropped silently. This is the deliberate trade-off for a simple,3414  // conflict-free merge — per-field CRDT merge is out of scope. Guidance for3415  // users: edit a given entry on one device at a time.3416  if (!derivedKey || vaultCreatesInFlight || vaultMode === "decoy") throw new Error("vault_locked");34173418  const received = remoteEntries.length + Object.keys(remoteTombstones).length;3419  let applied = 0;3420  let conflicts = 0;34213422  const byId = new Map<string, VaultEntry>();3423  for (const e of entries) byId.set(e.id, e);34243425  const mergeNow = Date.now();3426  const remoteTombstoneTimes = new Map<string, number>();3427  for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {3428    if (typeof rawDeletedAt === "number" && Number.isFinite(rawDeletedAt) && rawDeletedAt > 0) {3429      remoteTombstoneTimes.set(id, clampSyncTimestamp(rawDeletedAt, mergeNow));3430    }3431  }34323433  for (const remote of remoteEntries) {3434    const sanitized = sanitizeRestoredEntry(remote);3435    if (!sanitized) continue;3436    // HV-1a: a far-future remote modifiedAt must not permanently pin a3437    // malicious value against honest local edits. Clamp BEFORE any3438    // comparison against local timestamps.3439    sanitized.modifiedAt = clampSyncTimestamp(sanitized.modifiedAt, mergeNow);3440    if (typeof sanitized.deletedAt === "number") {3441      sanitized.deletedAt = clampSyncTimestamp(sanitized.deletedAt, mergeNow);3442    }3443    const remoteTombstoneTs = remoteTombstoneTimes.get(sanitized.id);3444    const localTombstoneTs = tombstones.get(sanitized.id);3445    const tombstoneTs = Math.max(remoteTombstoneTs ?? 0, localTombstoneTs ?? 0);3446    if (tombstoneTs > 0 && tombstoneTs >= sanitized.modifiedAt) {3447      continue;3448    }3449    const local = byId.get(sanitized.id);3450    if (!local) {3451      entries.push(sanitized);3452      byId.set(sanitized.id, sanitized);3453      tombstones.delete(sanitized.id);3454      applied += 1;3455    } else if (sanitized.modifiedAt > local.modifiedAt) {3456      const idx = entries.findIndex((e) => e.id === local.id);3457      if (idx !== -1) {3458        entries[idx] = sanitized;3459        byId.set(sanitized.id, sanitized);3460        tombstones.delete(sanitized.id);3461        applied += 1;3462        if (!local.deletedAt) conflicts += 1;3463      }3464    }3465  }34663467  for (const [id, rawDeletedAt] of Object.entries(remoteTombstones)) {3468    if (typeof rawDeletedAt !== "number" || !Number.isFinite(rawDeletedAt) || rawDeletedAt <= 0) continue;3469    // HV-1a/1c: clamp the tombstone timestamp before every comparison.3470    const deletedAt = remoteTombstoneTimes.get(id)!;3471    const knownTombstone = tombstones.get(id);3472    if (knownTombstone !== undefined && knownTombstone >= deletedAt) continue;3473    const local = byId.get(id);3474    if (!local) {3475      tombstones.set(id, deletedAt);3476      applied += 1;3477      continue;3478    }3479    if (local.deletedAt && local.deletedAt >= deletedAt) continue;3480    if (deletedAt < local.modifiedAt) continue;3481    const idx = entries.findIndex((e) => e.id === id);3482    if (idx !== -1) {3483      entries[idx] = { ...local, deletedAt, modifiedAt: deletedAt };3484      tombstones.set(id, deletedAt);3485      applied += 1;3486    }3487  }34883489  if (applied > 0 && vaultMode === "real") {3490    await persistEntries("sync_received");3491    buildDomainIndexSync(entries);3492    // An open popup holds the entries it loaded at mount and polls nothing, so3493    // a background round (the relay listener responding to a peer's push, or the3494    // alarm-driven dial) otherwise lands silently and the user sees stale data3495    // until they reopen. Best-effort: no popup listening is the normal case.3496    try {3497      void chrome.runtime3498        .sendMessage({ type: "VAULT_ENTRIES_CHANGED" })3499        .catch(() => undefined);3500    } catch {3501      // messaging unavailable3502    }3503  }3504  return { received, applied, conflicts };3505}35063507export async function restoreEntry(id: string): Promise<void> {3508  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3509  const entry = entries.find((e) => e.id === id && e.deletedAt);3510  if (!entry) throw new Error("deleted entry not found");3511  const previousDeletedAt = entry.deletedAt;3512  const previousModifiedAt = entry.modifiedAt;3513  const previousTombstone = tombstones.get(id);3514  delete entry.deletedAt;3515  entry.modifiedAt = monotonicEntryTimestamp(Math.max(3516    entry.modifiedAt,3517    previousTombstone ?? 0,3518  ));3519  tombstones.delete(id);3520  try {3521    await persistEntries();3522  } catch (err) {3523    entry.deletedAt = previousDeletedAt;3524    entry.modifiedAt = previousModifiedAt;3525    if (previousTombstone !== undefined) tombstones.set(id, previousTombstone);3526    throw err;3527  }3528  buildDomainIndexSync(entries);3529}35303531export async function purgeEntry(id: string): Promise<void> {3532  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3533  const idx = entries.findIndex((e) => e.id === id && e.deletedAt);3534  if (idx === -1) throw new Error("deleted entry not found");3535  const entry = entries[idx]!;3536  tombstones.set(id, Math.max(tombstones.get(id) ?? 0, entry.deletedAt!));3537  entries.splice(idx, 1);3538  await persistEntries();3539}35403541/** Permanently delete entries whose deletedAt is older than retentionMs. 0 = keep forever. */3542export async function purgeExpiredTrash(retentionMs: number): Promise<number> {3543  if (!derivedKey || vaultCreatesInFlight || retentionMs === 0) return 0;3544  const cutoff = Date.now() - retentionMs;3545  const before = entries.length;3546  for (const entry of entries) {3547    if (entry.deletedAt && entry.deletedAt < cutoff) {3548      tombstones.set(entry.id, Math.max(tombstones.get(entry.id) ?? 0, entry.deletedAt));3549    }3550  }3551  entries = entries.filter((e) => !(e.deletedAt && e.deletedAt < cutoff));3552  const purged = before - entries.length;3553  if (purged > 0) await persistEntries();3554  return purged;3555}35563557export function queryDomain(domain: string): VaultEntry[] {3558  return domainIndex.get(domain) ?? [];3559}35603561export function getEntryById(id: string): VaultEntry | undefined {3562  return entries.find((entry) => entry.id === id && !entry.deletedAt);3563}35643565async function persistSlotA(3566  reason: VaultSnapshot["reason"] = "local_save",3567): Promise<StoredVault> {3568  if (!derivedKey) throw new Error("vault_locked");3569  const epoch = vaultEpoch;3570  const throwIfStale = () => {3571    if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3572  };35733574  const slotA = await loadSlot(SLOT_A);3575  throwIfStale();3576  if (!slotA) throw new Error("missing slot A");35773578  // Snapshot the about-to-be-overwritten state BEFORE we mutate disk. Failures3579  // are swallowed by takeVaultSnapshot — history must never block a save.3580  await takeVaultSnapshot(reason);3581  throwIfStale();35823583  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);3584  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_a_v1");3585  throwIfStale();35863587  // Preserve existing recovery escrow fields.3588  const nextSlotA: StoredVault = {3589    ...slotA,3590    nonce,3591    ciphertext,3592    tag,3593    // recovery_salt and recovery_wrapped_root_key are already set from loadSlot3594  };35953596  // Slot A (the real vault) is now committed. Wrap every later write so a3597  // mid-persist failure (e.g. a storage error after slot A landed) restores the3598  // prior slot A before rethrowing. Without this, a "failed" save that already3599  // wrote slot A leaves disk ahead of the in-memory rollback in addEntry/3600  // updateEntry/deleteEntry — the entry stays silently on disk and resurfaces3601  // as a duplicate on the next unlock (observed under storage-quota pressure).3602  let slotACommitted = false;3603  try {3604    throwIfStale();3605    await writeSlot(SLOT_A, nextSlotA);3606    slotACommitted = true;3607    throwIfStale();36083609    // When duress is not configured, keep slot B size-matched with slot A by3610    // regenerating its noise. When duress IS configured, leave slot B alone —3611    // we don't have the decoy key to re-encrypt it. This is a known trade-off.3612    if (!duressConfigured) {3613      throwIfStale();3614      await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));3615      throwIfStale();3616    }3617    // Only advance the vault version for locally-originated writes. Entries3618    // applied from a sync peer ("sync_received") must NOT bump the counter —3619    // otherwise applying a remote round makes us look newer than the peer and3620    // triggers a redundant outbound sync, defeating the no-op optimisation3621    // and risking a ping-pong between two devices (SEV-2-C).3622    if (reason !== "sync_received") {3623      throwIfStale();3624      await stampLocalVaultMutation();3625      throwIfStale();3626    }3627  } catch (err) {3628    // Best-effort restore — the prior slot A is smaller-or-equal, so this write3629    // fits even when the failure was a quota overflow.3630    if (slotACommitted) await writeSlot(SLOT_A, slotA).catch(() => {});3631    if (epoch !== vaultEpoch || !derivedKey) throw new Error("vault_locked");3632    throw err;3633  }36343635  return nextSlotA;3636}36373638async function persistSlotB(): Promise<void> {3639  if (!derivedKey) throw new Error("vault_locked");36403641  const slotB = await loadSlot(SLOT_B);3642  if (!slotB) throw new Error("missing slot B");36433644  // Decoy plaintext always reports duressConfigured=false — the decoy user3645  // sees a clean slate. persistSlotB only runs in decoy mode, which only3646  // exists once duress is configured, so pad to the fixed duress ceiling to3647  // keep slot B's length equal to slot A's (audit MEDIUM — deniability).3648  const plaintext = encodePayload(entries, false, DURESS_SLOT_SIZE);3649  const { nonce, ciphertext, tag } = await encrypt(derivedKey, plaintext, "slot_b_v1");36503651  await writeSlot(SLOT_B, { ...slotB, nonce, ciphertext, tag });3652  // Symmetric with persistSlotA: if the version stamp fails after the decoy3653  // slot committed, restore the prior slot B so a failed decoy-mode save can't3654  // leave disk ahead of the in-memory rollback.3655  try {3656    await stampLocalVaultMutation();3657  } catch (err) {3658    await writeSlot(SLOT_B, slotB).catch(() => {});3659    throw err;3660  }3661}36623663async function persistEntries(3664  reason: VaultSnapshot["reason"] = "local_save",3665): Promise<void> {3666  if (vaultCreatesInFlight) throw new Error("vault_changed");3667  vaultWritesInFlight++;3668  try {3669  if (!derivedKey) throw new Error("vault_locked");36703671  // Reconcile direct soft-delete callers while restoring the previous map if3672  // storage rejects the save.3673  const previousTombstones = tombstones;3674  const pendingTombstones = new Map(tombstones);3675  tombstones = pendingTombstones;3676  reconcileTombstones();3677  try {3678    if (vaultMode === "decoy") {3679      await persistSlotB();3680    } else {3681      await persistSlotA(reason);3682    }3683  } catch (err) {3684    if (tombstones === pendingTombstones) tombstones = previousTombstones;3685    throw err;3686  }3687  buildDomainIndexSync(entries);3688  await refreshLockedSyncState();3689  } finally { vaultWritesInFlight--; }3690}36913692// PB-26-011: drop URLs whose parsed scheme is not http(s) at the storage3693// boundary. Schemeless values (e.g. "github.com") are inert and kept — they3694// pre-date this guard in existing data. Unparseable values are kept: the3695// reviewed render paths never execute them (favicons via _favicon/, domains3696// via tldts); this is defense-in-depth against future sinks.3697function allowHttpUrl(url: string | undefined): string {3698  const trimmed = url?.trim() ?? "";3699  if (!trimmed) return "";3700  try {3701    const parsed = new URL(trimmed);3702    if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return "";3703  } catch {3704    // No scheme to reject.3705  }3706  return trimmed;3707}37083709function cleanAdditionalUrls(values: string[] | undefined): string[] | undefined {3710  if (!Array.isArray(values)) return undefined;3711  const seen = new Set<string>();3712  const cleaned: string[] = [];3713  for (const value of values) {3714    const trimmed = typeof value === "string" ? value.trim() : "";3715    if (!trimmed) continue;3716    if (!allowHttpUrl(trimmed)) continue;3717    const key = trimmed.toLowerCase();3718    if (seen.has(key)) continue;3719    seen.add(key);3720    cleaned.push(trimmed);3721  }3722  return cleaned.length > 0 ? cleaned : undefined;3723}37243725function sanitizeEntryDraft(entry: EntryDraft): EntryDraft {3726  const title = entry.title.trim();3727  const type: VaultEntry["type"] = entry.type ?? "login";37283729  if (!title) throw new Error("title is required");37303731  if (entry.passkey) {3732    const p = entry.passkey;3733    if (3734      !p.rpId ||3735      !p.credentialId ||3736      !p.publicKeyCose ||3737      !p.userHandle ||3738      !p.userName ||3739      (p.algorithm !== -7 && p.algorithm !== -8)3740    ) {3741      throw new Error("invalid passkey credential");3742    }3743  }3744  if (type === "card") {3745    if (!entry.cardholderName?.trim() || !entry.cardNumber?.trim()) {3746      throw new Error("cardholder name and card number are required");3747    }3748  }37493750  return {3751    type,3752    title,3753    username: type === "login" ? entry.username?.trim() ?? "" : undefined,3754    email: type === "login" ? entry.email?.trim() || undefined : undefined,3755    password: type === "login" ? entry.password : undefined,3756    url: type === "login" ? allowHttpUrl(entry.url) : undefined,3757    additionalUrls: type === "login" ? cleanAdditionalUrls(entry.additionalUrls) : undefined,3758    totp: type === "login" ? entry.totp?.trim() || undefined : undefined,3759    // PCH-01-019: preserve non-default TOTP params through batch-add/import so3760    // they are not silently stripped (they fall back to SHA-1/6/30 when absent).3761    totpAlgorithm: type === "login" ? entry.totpAlgorithm : undefined,3762    totpDigits: type === "login" ? entry.totpDigits : undefined,3763    totpPeriod: type === "login" ? entry.totpPeriod : undefined,3764    notes: entry.notes?.trim() || undefined,3765    breach: type === "login" ? entry.breach : undefined,3766    // PCH-01-016: the batch-add path was bypassing the MV-6 canary/tags3767    // whitelist applied on the RESTORE_ENTRIES path. Run both sanitizers here.3768    canary: type === "login" ? sanitizeCanary(entry.canary) : undefined,3769    tags: sanitizeTags(entry.tags),3770    passkey: entry.passkey,3771    cardholderName: type === "card" ? entry.cardholderName?.trim() : undefined,3772    cardNumber: type === "card" ? entry.cardNumber?.trim() : undefined,3773    expMonth: type === "card" ? entry.expMonth?.trim() : undefined,3774    expYear: type === "card" ? entry.expYear?.trim() : undefined,3775    cvc: type === "card" ? entry.cvc?.trim() : undefined,3776    cardNickname: type === "card" ? entry.cardNickname?.trim() || undefined : undefined,3777    network: type === "card" ? entry.network : undefined,3778    last4: type === "card" ? entry.last4?.trim() : undefined,3779  };3780}37813782function sanitizeEntryPatch(patch: Partial<VaultEntry>): Partial<VaultEntry> {3783  const nextPatch: Partial<VaultEntry> = {};37843785  if ("type" in patch) {3786    nextPatch.type = patch.type;3787  }37883789  if ("title" in patch) {3790    const title = patch.title?.trim() ?? "";3791    if (!title) throw new Error("title is required");3792    nextPatch.title = title;3793  }37943795  if ("url" in patch) {3796    nextPatch.url = allowHttpUrl(patch.url);3797  }37983799  if ("additionalUrls" in patch) {3800    const incoming = Array.isArray(patch.additionalUrls) ? patch.additionalUrls : [];3801    const seen = new Set<string>();3802    const cleaned: string[] = [];3803    for (const value of incoming) {3804      const trimmed = typeof value === "string" ? value.trim() : "";3805      if (!trimmed || !allowHttpUrl(trimmed)) continue;3806      const key = trimmed.toLowerCase();3807      if (seen.has(key)) continue;3808      seen.add(key);3809      cleaned.push(trimmed);3810    }3811    nextPatch.additionalUrls = cleaned.length > 0 ? cleaned : undefined;3812  }38133814  if ("username" in patch) {3815    nextPatch.username = patch.username?.trim() ?? "";3816  }38173818  if ("email" in patch) {3819    nextPatch.email = patch.email?.trim() || undefined;3820  }38213822  if ("password" in patch) {3823    const password = patch.password ?? "";3824    // Allow clearing a password (e.g. on passkey-only entries)3825    nextPatch.password = password || undefined;3826  }38273828  if ("totp" in patch) {3829    nextPatch.totp = patch.totp?.trim() || undefined;3830  }38313832  if ("totpAlgorithm" in patch) {3833    nextPatch.totpAlgorithm = patch.totpAlgorithm;3834  }38353836  if ("totpDigits" in patch) {3837    nextPatch.totpDigits = patch.totpDigits;3838  }38393840  if ("totpPeriod" in patch) {3841    nextPatch.totpPeriod = patch.totpPeriod;3842  }38433844  if ("notes" in patch) {3845    nextPatch.notes = patch.notes?.trim() || undefined;3846  }38473848  if ("breach" in patch) {3849    nextPatch.breach = patch.breach;3850  }38513852  if ("canary" in patch) {3853    // PCH-02-001: route update patches through the same canary whitelist used3854    // by add/restore/sync. Invalid shapes drop the canary; `undefined` clears it.3855    nextPatch.canary = patch.canary ? sanitizeCanary(patch.canary) : undefined;3856  }38573858  if ("passkey" in patch) {3859    // A patch with `passkey: undefined` removes the credential from the entry3860    // (used by "remove passkey" without deleting the whole entry).3861    if (patch.passkey === undefined || patch.passkey === null) {3862      nextPatch.passkey = undefined;3863    } else {3864      const sanitized = sanitizePasskey(patch.passkey);3865      if (!sanitized) throw new Error("invalid passkey credential");3866      nextPatch.passkey = sanitized;3867    }3868  }38693870  if ("tags" in patch) {3871    // PCH-02-001: bound tags exactly like both import funnels.3872    nextPatch.tags = sanitizeTags(patch.tags);3873  }38743875  if ("cardholderName" in patch) {3876    nextPatch.cardholderName = patch.cardholderName?.trim() || undefined;3877  }3878  if ("cardNumber" in patch) {3879    const n = patch.cardNumber ?? "";3880    nextPatch.cardNumber = n || undefined;3881  }3882  if ("expMonth" in patch) {3883    nextPatch.expMonth = patch.expMonth?.trim() || undefined;3884  }3885  if ("expYear" in patch) {3886    nextPatch.expYear = patch.expYear?.trim() || undefined;3887  }3888  if ("cvc" in patch) {3889    nextPatch.cvc = patch.cvc?.trim() || undefined;3890  }3891  if ("cardNickname" in patch) {3892    nextPatch.cardNickname = patch.cardNickname?.trim() || undefined;3893  }3894  if ("network" in patch) {3895    nextPatch.network = patch.network;3896  }3897  if ("last4" in patch) {3898    nextPatch.last4 = patch.last4?.trim() || undefined;3899  }39003901  return nextPatch;3902}39033904function normalizeEntry(entry: VaultEntry): VaultEntry {3905  const base: VaultEntry = {3906    id: entry.id,3907    type: entry.type,3908    title: entry.title,3909    username: entry.username,3910    email: entry.email,3911    password: entry.password,3912    url: entry.url,3913    additionalUrls:3914      "additionalUrls" in entry && Array.isArray(entry.additionalUrls)3915        ? entry.additionalUrls3916        : undefined,3917    totp: entry.totp,3918    // PCH-01-019: carry TOTP params through the normalize/restore path too.3919    totpAlgorithm: entry.totpAlgorithm,3920    totpDigits: entry.totpDigits,3921    totpPeriod: entry.totpPeriod,3922    notes: entry.notes,3923    breach: entry.breach,3924    // Preserve the password-age clock across lock/unlock. Without this the3925    // field is dropped on every decode and the advanced-health "aged password"3926    // signal silently resets to createdAt on each unlock (SEV-2-A).3927    passwordChangedAt:3928      "passwordChangedAt" in entry ? entry.passwordChangedAt : undefined,3929    // Preserve past-password history across lock/unlock. normalizeEntry is a3930    // field whitelist, so an unlisted field is silently dropped on every decode3931    // (same class as the passwordChangedAt SEV-2-A above).3932    passwordHistory:3933      "passwordHistory" in entry && Array.isArray(entry.passwordHistory)3934        ? entry.passwordHistory3935        : undefined,3936    canary: entry.canary,3937    passkey: entry.passkey,3938    createdAt: entry.createdAt,3939    modifiedAt: entry.modifiedAt,3940    deletedAt: entry.deletedAt,3941    tags: entry.tags,3942    cardholderName: "cardholderName" in entry ? entry.cardholderName : undefined,3943    cardNumber: "cardNumber" in entry ? entry.cardNumber : undefined,3944    expMonth: "expMonth" in entry ? entry.expMonth : undefined,3945    expYear: "expYear" in entry ? entry.expYear : undefined,3946    cvc: "cvc" in entry ? entry.cvc : undefined,3947    cardNickname: "cardNickname" in entry ? entry.cardNickname : undefined,3948    network: "network" in entry ? entry.network : undefined,3949    last4: "last4" in entry ? entry.last4 : undefined,3950  };39513952  return base;3953}395439553956// ---------------------------------------------------------------------------3957// Deduplication3958// ---------------------------------------------------------------------------39593960function entryDupeKey(e: VaultEntry): string {3961  if (e.passkey) {3962    // Equal identities can still carry different passwords, notes or TOTP data.3963    const content = Object.fromEntries(Object.entries(e)3964      .filter(([key]) => key !== "id" && key !== "createdAt" && key !== "modifiedAt")3965      .sort(([a], [b]) => a.localeCompare(b)));3966    return `passkey|${e.passkey.rpId}|${e.passkey.credentialId}|${JSON.stringify(content)}`;3967  }3968  if (e.type === "note") return `note|${e.title.toLowerCase()}`;3969  return `login|${e.title.toLowerCase()}|${(e.url ?? "").toLowerCase()}|${(e.username ?? "").toLowerCase()}`;3970}39713972/** Returns the number of duplicate entries (those that would be removed). */3973export function countDuplicates(): number {3974  const best = new Map<string, VaultEntry>();3975  let dupeCount = 0;3976  for (const e of entries.filter((e) => !e.deletedAt)) {3977    const key = entryDupeKey(e);3978    const existing = best.get(key);3979    if (!existing) {3980      best.set(key, e);3981    } else {3982      dupeCount++;3983      // Keep the more recently modified one in the map3984      if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {3985        best.set(key, e);3986      }3987    }3988  }3989  return dupeCount;3990}39913992/**3993 * Soft-deletes duplicate entries, keeping the most recently modified copy of3994 * each group. Returns the number of entries moved to trash.3995 */3996export async function deduplicateEntries(): Promise<number> {3997  if (!derivedKey || vaultCreatesInFlight) throw new Error("vault_locked");3998  // Dedup reshapes slot B permanently under the decoy key, which is3999  // forensically distinguishable from a freshly-seeded decoy vault. Refuse.4000  if (vaultMode === "decoy") {4001    throw new Error("deduplicate disabled in decoy mode");4002  }40034004  const best = new Map<string, VaultEntry>();4005  for (const e of entries.filter((en) => !en.deletedAt)) {4006    const key = entryDupeKey(e);4007    const existing = best.get(key);4008    if (!existing) {4009      best.set(key, e);4010    } else if ((e.modifiedAt ?? e.createdAt ?? 0) > (existing.modifiedAt ?? existing.createdAt ?? 0)) {4011      best.set(key, e);4012    }4013  }40144015  const keepIds = new Set(Array.from(best.values()).map((e) => e.id));4016  let removed = 0;4017  entries = entries.map((e) => {4018    if (!e.deletedAt && !keepIds.has(e.id)) {4019      removed++;4020      const deletedAt = monotonicEntryTimestamp(Math.max(4021        e.modifiedAt,4022        tombstones.get(e.id) ?? 0,4023      ));4024      tombstones.set(e.id, deletedAt);4025      return { ...e, deletedAt };4026    }4027    return e;4028  });40294030  if (removed > 0) await persistEntries();4031  return removed;4032}40334034// ---------------------------------------------------------------------------4035// Vault history — snapshot BEFORE every vault write so the saved blob is4036// what is about to be lost, not what was just written. Capped at 5. The4037// stored blobs are AES-256-GCM ciphertext under the master password, so4038// history adds zero security surface.4039// ---------------------------------------------------------------------------40404041const HISTORY_KEY = "peach_vault_history";4042const HISTORY_MAX = 5;40434044// PCH-01-023: coarsen a live-entry count into a low-resolution bucket so the4045// plaintext snapshot field cannot reveal exact vault size or single-entry change4046// deltas. Buckets widen as the vault grows so absolute leakage stays roughly4047// proportional rather than exact.4048function bucketEntryCount(n: number): number {4049  if (n <= 0) return 0;4050  if (n <= 10) return 10;4051  if (n <= 25) return 25;4052  if (n <= 50) return 50;4053  if (n <= 100) return 100;4054  if (n <= 250) return 250;4055  if (n <= 500) return 500;4056  return Math.ceil(n / 500) * 500;4057}40584059/**4060 * Snapshot the CURRENT on-disk vault state into history. Call this BEFORE4061 * overwriting peach_vault_a so the saved blob captures the about-to-be-lost4062 * state. Identical-to-most-recent blobs are skipped to avoid filling history4063 * with no-op writes.4064 */4065export async function takeVaultSnapshot(4066  reason: VaultSnapshot["reason"],4067): Promise<void> {4068  if (recoveryInFlight || vaultCreatesInFlight) return;4069  // The history store is real-mode state by construction, so it must not be4070  // written from a decoy session either. The guard lives here rather than only4071  // at the call sites so the invariant survives a new caller (PB-26-915).4072  if (vaultMode === "decoy") return;4073  vaultWritesInFlight++;4074  try {4075    const raw = await chrome.storage.local.get([SLOT_A, SLOT_B, HISTORY_KEY]);4076    const slotA = (raw as Record<string, StoredVault | undefined>)[SLOT_A];4077    const slotB = (raw as Record<string, StoredVault | undefined>)[SLOT_B];40784079    // Nothing to snapshot if the real slot doesn't exist yet (fresh install,4080    // pre-createVault). createVault skips snapshots intentionally — there is4081    // no prior state to preserve.4082    if (!slotA) return;40834084    const vault_a = JSON.stringify(slotA);4085    const vault_b = JSON.stringify(slotB ?? slotA);40864087    // Best-effort entry count: only meaningful when the in-memory state is4088    // unlocked AND in real mode. Decoy mode would leak the decoy entry4089    // count; locked mode has no entries to count. Both fall through to null.4090    // PCH-01-023: store a coarse bucket, not the exact count — chrome.storage4091    // .local sits next to the AES-GCM blobs in plaintext, so an exact count would4092    // leak vault size and per-write deltas (the metadata padding hides this).4093    let entryCount: number | null = null;4094    if (derivedKey && vaultMode === "real") {4095      try {4096        entryCount = bucketEntryCount(entries.filter((e) => !e.deletedAt).length);4097      } catch {4098        entryCount = null;4099      }4100    }41014102    const existingRaw = (raw as Record<string, VaultHistory | undefined>)[HISTORY_KEY];4103    const history: VaultHistory = existingRaw && Array.isArray(existingRaw.snapshots)4104      ? existingRaw4105      : { snapshots: [] };41064107    // Deduplication: if the most recent snapshot has byte-identical blobs,4108    // skip — saves the same vault N times in a row would otherwise burn the4109    // entire history window with no recovery value.4110    const latest = history.snapshots[0];4111    if (latest && latest.vault_a === vault_a && latest.vault_b === vault_b) {4112      return;4113    }41144115    const snapshot: VaultSnapshot = {4116      id: crypto.randomUUID(),4117      savedAt: Date.now(),4118      reason,4119      vault_a,4120      vault_b,4121      entryCount,4122    };41234124    history.snapshots = [snapshot, ...history.snapshots].slice(0, HISTORY_MAX);4125    if (recoveryInFlight || vaultCreatesInFlight) return;4126    await chrome.storage.local.set({ [HISTORY_KEY]: history });4127  } catch (err) {4128    // Non-fatal — history must never block a save. A failed snapshot just4129    // means the user loses one rung of the safety ladder for this write.4130    // M4/QUA-006: log so the failure is visible; if it looks like a quota4131    // problem, notify the popup so the user can prune history themselves.4132    console.warn('[Peach] takeVaultSnapshot failed:', err);4133    if (String(err).includes('QUOTA') || String(err).includes('quota')) {4134      try {4135        await chrome.runtime.sendMessage({ type: 'VAULT_STORAGE_QUOTA_WARNING' });4136      } catch {4137        // popup may be closed; surfaced via console.warn above4138      }4139    }4140  } finally { vaultWritesInFlight--; }4141}41424143/** Wipe all vault history. Called by Panic / DESTROY_VAULT. */4144export async function clearVaultHistory(): Promise<void> {4145  if (recoveryInFlight || vaultCreatesInFlight) throw new Error("recovery_in_progress");4146  vaultWritesInFlight++;4147  try {4148    await chrome.storage.local.set({ [HISTORY_KEY]: { snapshots: [] } satisfies VaultHistory });4149  } catch {4150    // Non-fatal — DESTROY_VAULT also runs storage.local.clear().4151  } finally { vaultWritesInFlight--; }4152}41534154/** Read all snapshots, newest first, for the Settings vault history view. */4155export async function getVaultHistory(): Promise<VaultSnapshot[]> {4156  if (vaultMode === "decoy") return [];4157  const raw = await chrome.storage.local.get(HISTORY_KEY);4158  const value = (raw as Record<string, unknown>)[HISTORY_KEY];4159  return sanitizeHistory(value);4160}41614162/**4163 * Replace the on-disk vault with the chosen snapshot's blobs and lock the4164 * vault. The current state is itself snapshotted before replacement.4165 */4166export async function restoreVaultSnapshot(4167  snapshotId: string,4168): Promise<{ ok: true } | { ok: false; error: string }> {4169  if (recoveryInFlight || vaultReplacementInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "vault_changed" };4170  vaultReplacementInFlight = true;4171  try {4172    if (vaultMode === "decoy") return { ok: false, error: "vault_locked" };4173    const history = await getVaultHistory();4174    const snapshot = history.find((s) => s.id === snapshotId);4175    if (!snapshot) return { ok: false, error: "snapshot_not_found" };41764177    const restoredA = parseHistorySlot(snapshot.vault_a);4178    const restoredB = parseHistorySlot(snapshot.vault_b);4179    if (!restoredA || !restoredB) return { ok: false, error: "snapshot_corrupt" };41804181    await takeVaultSnapshot("restore");4182    const current = await chrome.storage.local.get([SLOT_A, SLOT_B]);4183    const previousA = (current as Record<string, unknown>)[SLOT_A];4184    const previousB = (current as Record<string, unknown>)[SLOT_B];4185    try {4186      if (recoveryInFlight || vaultRemovalsInFlight || vaultCreatesInFlight) return { ok: false, error: "recovery_in_progress" };4187      await chrome.storage.local.set({ [SLOT_A]: restoredA, [SLOT_B]: restoredB });4188      await stampLocalVaultMutation();4189    } catch {4190      try {4191        await chrome.storage.local.set({ [SLOT_A]: previousA, [SLOT_B]: previousB });4192      } catch {4193        // Preserve the restore failure if storage cannot complete the rollback.4194      }4195      return { ok: false, error: "snapshot_corrupt" };4196    }41974198    await lock();4199    return { ok: true };4200  } finally {4201    vaultReplacementInFlight = false;4202  }4203}42044205/**4206 * Rotate the vault's sync identity by generating a FRESH ROOT KEY and4207 * re-wrapping everything under it (MV-8). Because every sync credential —4208 * vault_id, the Noise static keypair, the Ed25519 manifest signing key,4209 * and the per-entry envelope keys — derives from the root key, rotation4210 * makes a lost/stolen device's retained key material useless. All paired4211 * devices must re-pair afterwards.4212 *4213 * CONSEQUENCE THE UI MUST SURFACE: the 12 recovery words also derive from4214 * the root key, so rotation INVALIDATES the old recovery phrase. The flow4215 * sets peach_recovery_pending so the popup re-presents the new words for4216 * confirmation, same as the initial recovery-word confirmation path.4217 */4218export async function rotateSyncIdentity(): Promise<{ ok: boolean; error?: string }> {4219  if (vaultCreatesInFlight) throw new Error("vault_changed");4220  const rotationEpoch = vaultEpoch;4221  const removalEpoch = vaultRemovalEpoch;4222  vaultWritesInFlight++;4223  try {4224  if (!derivedKey || vaultMode !== "real") {4225    return { ok: false, error: "vault_locked" };4226  }4227  const slotA = await loadSlot(SLOT_A);4228  if (!slotA) return { ok: false, error: "missing_slot_a" };42294230  // 1. Fresh root key + recovery escrow (new words).4231  const { rawRootKey, recoverySalt, wrappedRootKey, wrappedNonce, wrappedTag } =4232    await generateAndWrapRootKey();42334234  // 2. Re-wrap the new root key under the current password-derived key.4235  const newRootKey = unhex(rawRootKey);4236  const recoveryVaultKey = await encrypt(newRootKey, hex(derivedKey), "recovery_vault_key_v1");4237  const pwRoot = await wrapRootKeyForDerivedKey(derivedKey, newRootKey);42384239  // 3. Snapshot, then single atomic slot write — both escrow wrappings of4240  //    the new root key land together (same transactional rule as4241  //    changePassword). Entries are untouched: they are sealed under the4242  //    password-derived key, not the root key.4243  await takeVaultSnapshot("local_save");4244  const nextSlotA: StoredVault = {4245    ...slotA,4246    recovery_vault_key: recoveryVaultKey,4247    recovery_salt: recoverySalt,4248    recovery_wrapped_root_key: wrappedRootKey,4249    recovery_nonce: wrappedNonce,4250    recovery_tag: wrappedTag,4251    ...pwRoot,4252  };4253  await writeSlot(SLOT_A, nextSlotA);42544255  // 4. Swap in memory only after disk committed.4256  if (rotationEpoch === vaultEpoch && derivedKey && rootKey) {4257    const oldRootKey = rootKey;4258    // The old root must stay live until the recall member is re-sealed: a queued4259    // write encrypts with the bytes it captured, so zeroing in place first would4260    // seal it under an all-zero key. Both the re-key and the swap run inside the4261    // recall queue so no write can interleave with either.4262    await serializeRecallMutation(async () => {4263      await rekeyManualSummonRecall(oldRootKey, newRootKey).catch((error) => {4264        console.warn("[Peach] manual-summon recall re-key failed:", error);4265      });4266      if (rootKey === oldRootKey) {4267        rootKey = newRootKey;4268        zeroKey(oldRootKey);4269      } else {4270        zeroKey(newRootKey);4271      }4272    });4273  } else {4274    zeroKey(newRootKey);4275  }42764277  // 4b. The identity's root wrap was encrypted under the dead root. Without4278  //     this the identity survives only until the unlock key also changes.4279  await notifyIdentityKeysRotated();42804281  // 5. Old peers' identities derive from the dead root key — drop them all,4282  // with their rendezvous secrets (PB-26-213: rotation clears the map, so4283  // there is nothing to rewrap under the new key).4284  await clearPairedDevices();4285  await clearPairSecrets();42864287  // 6. Force re-presentation of the NEW recovery words on next popup view.4288  if (removalEpoch === vaultRemovalEpoch) {4289    await setRecoveryConfirmPending(rotationEpoch === vaultEpoch && isUnlocked());4290    touchAutoLock();4291  }42924293  await stampLocalVaultMutation();4294  return { ok: true };4295  } finally { vaultWritesInFlight--; }4296}42974298/**4299 * Change the master password. Re-encrypts slot A with a fresh salt + new4300 * derived key. Slot B (duress or noise) is left untouched when duress is4301 * configured — it uses an independent key derived from the duress password —4302 * and regenerated as noise when duress is not configured.4303 */4304export async function changePassword(4305  currentPassword: string,4306  newPassword: string4307): Promise<boolean> {4308  if (vaultCreatesInFlight) throw new Error("vault_changed");4309  vaultWritesInFlight++;4310  try {43114312  const epoch = vaultEpoch;4313  const stale = () => epoch !== vaultEpoch;4314  if (!derivedKey || vaultMode !== "real") return false;43154316  // Verify current password before allowing any change4317  const valid = await verifyMainPassword(currentPassword);4318  if (!valid) return false;43194320  const slotA = await loadSlot(SLOT_A);4321  if (!slotA) return false;4322  if (!rootKey) return false;43234324  // Derive fresh key from new password + new random salt4325  const newSalt = generateSalt();4326  const newKey = await deriveKey(newPassword, newSalt);4327  if (stale()) {4328    zeroKey(newKey);4329    return false;4330  }43314332  // Re-encrypt the in-memory entries with the new key4333  const plaintext = encodePayload(entries, duressConfigured, duressConfigured ? DURESS_SLOT_SIZE : 0);4334  const { nonce, ciphertext, tag } = await encrypt(newKey, plaintext, "slot_a_v1");43354336  // Pre-wrap root key under the new derived key. Recovery fields wrap rootKey4337  // under recovery words and remain untouched — recovery phrase keeps working4338  // across password changes (H4/COR-002).4339  const pwRoot = await wrapRootKeyForDerivedKey(newKey, rootKey);43404341  const recoveryVaultKey = await encrypt(rootKey, hex(newKey), "recovery_vault_key_v1");4342  const finalSlotA: StoredVault = {4343    ...slotA,4344    recovery_vault_key: recoveryVaultKey,4345    salt: hex(newSalt),4346    nonce,4347    ciphertext,4348    tag,4349    ...pwRoot,4350  };43514352  // Snapshot the OLD-key blob before overwriting it. If the user later4353  // restores from this snapshot they will need the OLD password — the4354  // post-restore lock surfaces that immediately.4355  await takeVaultSnapshot("local_save");43564357  // Single atomic write: ciphertext, salt, and pw_root_* fields all land in4358  // one storage transaction. An SW kill before this point leaves the old4359  // slot intact; after this point everything tied to the new password is4360  // already on disk together (M6/COR-004).4361  await writeSlot(SLOT_A, finalSlotA);4362  if (stale()) {4363    zeroKey(newKey);4364    return false;4365  }43664367  // Swap the in-memory key synchronously before any further await. If we4368  // threw between the Slot A write and this swap, the next persistEntries()4369  // would overwrite Slot A with old-key ciphertext, locking the user out.4370  zeroKey(derivedKey);4371  cancelBreachScan();4372  derivedKey = newKey;43734374  // PCH-01-008: the MV3 session escrow still holds the OLD key. Without this,4375  // the next service-worker restore decrypts the new-key Slot A with the stale4376  // key, fails tryDecryptSlotResult, and silently drops the user to a lock4377  // screen. Re-escrow the new key so restore survives a password change.4378  if (stale()) {4379    await lock();4380    return false;4381  }4382  await saveSessionKey(newKey, "real", epoch);4383  if (stale()) return false;43844385  // The identity envelope holds one wrap per recovering key. Swapping the4386  // unlock key kills the local wrap, so re-wrap now or the next key swap4387  // orphans the identity -- and until then the old password still opens it.4388  await notifyIdentityKeysRotated();4389  if (stale()) return false;43904391  // Regenerate noise for slot B when duress is not in use. Runs after the4392  // key swap so a failure here is a disposable noise regeneration, not a4393  // lockout.4394  if (!duressConfigured) {4395    await writeSlot(SLOT_B, generateNoiseBlob(ciphertext.length / 2));4396  }4397  await clearPinUnlockStorage();4398  await stampLocalVaultMutation();43994400  return true;4401  } finally { vaultWritesInFlight--; }4402}