Back to where your exchange keys go

The vault

Encrypts your secret on the device and decides what can unlock it. Unedited, from build 579b29d3.

lib/trading/vault.ts lines 1-832
// The device vault: nothing usable sits on disk.
//
// Before this, a signing key was stored as a non-extractable CryptoKey, which
// stops script from reading it back but does not stop anything that can read
// the browser's own storage files. And two credentials could not be CryptoKeys
// at all (a passphrase goes to the exchange verbatim, and a static secret IS
// the credential), so those were plain text in IndexedDB. That is the gap this
// closes.
//
// Everything is now AES-GCM ciphertext at rest under a key that is never
// stored anywhere. The key is derived at unlock time from something only the
// person present can produce:
//
//   passkey    A WebAuthn PRF evaluation. The authenticator will not produce
//              the output without user verification, so unlocking costs a
//              fingerprint or a face. This is the good path.
//   passcode   PBKDF2 over a passcode the user types. The fallback, for
//              browsers or devices with no PRF-capable authenticator.
//
// WebAuthn is being used here as a key derivation gate, not as authentication.
// There is no server to verify an assertion against and no attempt to pretend
// otherwise: the challenge is generated locally and never checked. The security
// property comes entirely from the authenticator refusing to evaluate the PRF
// without the user present, and from the PRF output never leaving the device.
//
// WHAT THIS BUYS, precisely, because the UI must not overclaim:
//
//   Locked, or on a stolen disk: a profile copy, a filesystem backup, a synced
//   browser profile, an evil-maid image. All of it yields ciphertext and a
//   salt. That is a real improvement and it is the point of this file.
//
//   Unlocked, with hostile script running in the page: no improvement at all.
//   Script that executes in the origin while the vault is open can sign, and
//   can read a decrypted passphrase. Encryption at rest does not and cannot
//   address that. Auto-lock narrows the window; it does not close it.

import { ensurePersistentStorage } from '@/lib/persistentStorage';
import type { Bytes } from './keys';
import { setVaultIndex } from './vaultIndex';
import {
  credentialIdBytes,
  credentialIdString,
  evaluatePrf,
  knownCredentialId,
  PASSKEY_NO_KEY_STORAGE,
  passkeyPrfAvailable,
  prfFromPasskey,
  rememberCredentialId,
} from '@/lib/passkeySupport';

const DB_NAME = 'tabmira-trading';
const DB_VERSION = 2;
const STORE = 'vault';
const META_ID = '__meta__';

/**
 * Records that are not exchange credentials.
 *
 * The vault turned out to be the right home for one secret that has nothing to
 * do with an exchange: the relay's data key, which until now sat in the clear
 * in another IndexedDB database. Putting it here rather than encrypting it
 * separately means it inherits everything this file already got right, and one
 * thing in particular: changeUnlockMethod re-encrypts what the vault holds, so
 * changing the passcode does not strand it.
 *
 * The prefix is what keeps it out of the accounts list. listExchanges() is
 * what the UI counts and renders, and a sealed record is not an account.
 */
const SEALED_PREFIX = '__sealed:';

/** The relay's data key, sealed. See lib/relay/device.ts. */
export const RELAY_DATA_KEY = `${SEALED_PREFIX}relay-data-key`;

/**
 * What the accounts have been worth, day by day, sealed.
 *
 * Here rather than in localStorage for the reason balanceCache.ts gives for
 * keeping balances in memory: a record of what somebody is worth should not sit
 * in plain storage where a copied profile carries it off. See
 * lib/portfolio/useValueHistory.ts.
 */
export const PORTFOLIO_HISTORY = `${SEALED_PREFIX}portfolio-value-history`;

/**
 * One venue's fills, sealed.
 *
 * Kept for the same reason as the value history above, and needed for a
 * separate one: an exchange hands back only its most recent fills, so a P&L
 * built from one fetch is a P&L built from a window. Collected here, it grows
 * into the whole account and stops shrinking every time the window moves.
 */
export const fillsRecord = (exchange: string) => `${SEALED_PREFIX}fills-${exchange}`;

/** Plaintext this file decrypts to and hands out. Callers zero it when done. */
export interface Credential {
  exchange: string;
  keyId: string;
  /** Raw secret bytes. Never a string: a string cannot be wiped, a Uint8Array can. */
  secret: Bytes;
  /** Present only where the exchange uses one. */
  passphrase?: string;
  /** Coinbase only: which algorithm its JWT header must claim. */
  alg?: 'ES256' | 'EdDSA';
  /**
   * Whether this credential belongs to the exchange's paper or demo
   * environment. Stored outside the ciphertext, like keyId, so the accounts
   * list can label a paper account while the vault is locked. It is not a
   * secret, and a locked vault that cannot tell you which of your accounts is
   * the real one is worse than one that can.
   */
  sandbox?: boolean;
}

export type UnlockMethod = 'passkey' | 'passcode';

export interface VaultState {
  exists: boolean;
  unlocked: boolean;
  method?: UnlockMethod;
}

interface StoredMeta {
  exchange: string;
  version: 1;
  method: UnlockMethod;
  salt: Bytes;
  /** Passkey only. The credential to ask for at unlock. */
  credentialId?: Bytes;
  /** A known plaintext, encrypted. Lets unlock tell a wrong passcode from a corrupt vault. */
  checkIv: Bytes;
  checkCt: Bytes;
}

interface StoredCredential {
  exchange: string;
  keyId: string;
  alg?: 'ES256' | 'EdDSA';
  sandbox?: boolean;
  iv: Bytes;
  ct: Bytes;
}

const CHECK_PLAINTEXT = 'tabmira-vault-v1';
const PBKDF2_ITERATIONS = 600_000;

// The unlock key, held in module scope and never persisted. Non-extractable,
// so even this process cannot read its bytes back out.
let sessionKey: CryptoKey | undefined;
let sessionMethod: UnlockMethod | undefined;
let autoLockTimer: ReturnType<typeof setTimeout> | undefined;
// A week, not fifteen minutes.
//
// The old timer was a security choice made without weighing what it cost, and
// what it cost was the feature: the key also lived only in memory, so every
// reload locked the vault too. Placing an order meant unlocking first, which
// is the friction that made this unusable.
//
// BE CLEAR ABOUT THE TRADE. A remembered session is the AES key stored beside
// the ciphertext it opens. While one is held, the encryption at rest no longer
// protects anything against someone holding the unlocked phone; it still
// protects against an offline copy of the storage taken while locked, and
// against a device that has expired its session. That is the same bargain
// every banking app makes, and it leans on the device's own lockscreen for the
// rest. It is offered because the alternative was people not using the
// feature, which protects nothing at all.
//
// The key is stored non-extractable, so even script in the page cannot read it
// out and carry it elsewhere, and it is deleted on an explicit lock.
const SESSION_ID = '__session__';
const DEFAULT_SESSION_MS = 7 * 24 * 60 * 60_000;
let autoLockMs = DEFAULT_SESSION_MS;

const enc = new TextEncoder();
const dec = new TextDecoder();

// --- storage ----------------------------------------------------------------

/**
 * The vault's storage, behind an interface.
 *
 * IndexedDB in a browser. Swappable because security code that cannot be
 * tested without a browser does not get tested, and because the records here
 * are opaque ciphertext, so nothing about them is IndexedDB-shaped.
 */
export interface VaultStorage {
  get<T>(id: string): Promise<T | undefined>;
  put(record: { exchange: string }): Promise<void>;
  remove(id: string): Promise<void>;
  all<T>(): Promise<T[]>;
}

function indexedDbStorage(): VaultStorage {
  function openDb(): Promise<IDBDatabase> {
    return new Promise((resolve, reject) => {
      const req = indexedDB.open(DB_NAME, DB_VERSION);
      req.onupgradeneeded = () => {
        const db = req.result;
        if (!db.objectStoreNames.contains(STORE)) db.createObjectStore(STORE, { keyPath: 'exchange' });
        // v1 kept unencrypted records in `signing-keys`. There is no migration
        // that preserves them, deliberately: the point of this change is that
        // no code here reads an unencrypted store, and writing the plaintext
        // reader needed to migrate would undo it. The old store is dropped and
        // the user reconnects, which costs a paste.
        if (db.objectStoreNames.contains('signing-keys')) db.deleteObjectStore('signing-keys');
      };
      req.onsuccess = () => resolve(req.result);
      req.onerror = () => reject(req.error ?? new Error('indexeddb open failed'));
    });
  }

  function tx<T>(mode: IDBTransactionMode, run: (store: IDBObjectStore) => IDBRequest<T>): Promise<T> {
    return openDb().then(
      (db) =>
        new Promise<T>((resolve, reject) => {
          const t = db.transaction(STORE, mode);
          const req = run(t.objectStore(STORE));
          let result: T;

          req.onsuccess = () => {
            result = req.result;
            // A write is NOT durable when its request succeeds. It is durable
            // when the transaction commits, and the gap between the two is
            // where a credential goes missing: the UI reads the row back,
            // renders it, and the row is gone after a reload because the
            // process was frozen or killed before the commit landed. Android
            // freezes backgrounded Chrome aggressively, so the gap is real
            // rather than theoretical.
            if (mode === 'readonly') resolve(result);
          };
          req.onerror = () => reject(req.error ?? new Error('indexeddb request failed'));

          t.oncomplete = () => {
            db.close();
            if (mode !== 'readonly') resolve(result);
          };
          t.onabort = () => {
            db.close();
            reject(t.error ?? new Error('indexeddb transaction aborted'));
          };
          t.onerror = () => {
            db.close();
            reject(t.error ?? new Error('indexeddb transaction failed'));
          };
        }),
    );
  }

  return {
    get: <T,>(id: string) => tx<T | undefined>('readonly', (s) => s.get(id) as IDBRequest<T | undefined>),
    put: (record) => tx('readwrite', (s) => s.put(record)).then(() => undefined),
    remove: (id) => tx('readwrite', (s) => s.delete(id)).then(() => undefined),
    all: <T,>() => tx<T[]>('readonly', (s) => s.getAll() as IDBRequest<T[]>),
  };
}

/** A store that answers nothing, for server rendering and for locked-down browsers. */
const noStorage: VaultStorage = {
  get: async () => undefined,
  put: async () => {
    throw new VaultError('no_storage', 'this browser will not let the app store anything');
  },
  remove: async () => {},
  all: async () => [],
};

let storage: VaultStorage | undefined;

function store(): VaultStorage {
  if (!storage) storage = typeof indexedDB === 'undefined' ? noStorage : indexedDbStorage();
  return storage;
}

/** Replace the backing store. For tests, and for any future non-IndexedDB backend. */
export function setVaultStorage(next: VaultStorage | undefined): void {
  storage = next;
  lockVault();
}

async function readMeta(): Promise<StoredMeta | undefined> {
  return store().get<StoredMeta>(META_ID);
}

// --- key derivation --------------------------------------------------------

export class VaultError extends Error {
  readonly code: string;
  constructor(code: string, message: string) {
    super(message);
    this.name = 'VaultError';
    this.code = code;
  }
}

/**
 * Turn 32 bytes of unlock material into the AES key, via HKDF.
 *
 * HKDF rather than using the PRF output directly: the PRF result is already
 * uniform, but running it through a KDF with a per-vault salt means two
 * vaults on the same authenticator derive different keys, and a future second
 * purpose can take a different `info` without reusing this one.
 */
async function deriveFromBytes(material: Bytes, salt: Bytes): Promise<CryptoKey> {
  const base = await crypto.subtle.importKey('raw', material, 'HKDF', false, ['deriveKey']);
  return crypto.subtle.deriveKey(
    { name: 'HKDF', hash: 'SHA-256', salt, info: enc.encode('tabmira/vault/aes-gcm') },
    base,
    { name: 'AES-GCM', length: 256 },
    false,
    ['encrypt', 'decrypt'],
  );
}

async function deriveFromPasscode(passcode: string, salt: Bytes): Promise<CryptoKey> {
  const base = await crypto.subtle.importKey('raw', enc.encode(passcode), 'PBKDF2', false, ['deriveKey']);
  return crypto.subtle.deriveKey(
    { name: 'PBKDF2', hash: 'SHA-256', salt, iterations: PBKDF2_ITERATIONS },
    base,
    { name: 'AES-GCM', length: 256 },
    false,
    ['encrypt', 'decrypt'],
  );
}

/**
 * True when this browser can register a PRF-capable platform authenticator.
 *
 * This used to ask only whether a platform authenticator existed, which on
 * Windows is yes on the machines where none of this works. Hello then made the
 * passkey, refused to derive a key from it, and nothing recorded that, so the
 * offer came back on the next visit. Each attempt costs two prompts, since
 * creating a vault registers a passkey and then evaluates it. That is what
 * being spammed for a passkey looked like from the inside.
 *
 * lib/passkeySupport holds the answer now, including the part that can only be
 * learned by trying, and holds it for relay recovery too: one refusal, in
 * either, takes the offer off both.
 */
export const passkeyUnlockAvailable = passkeyPrfAvailable;

/**
 * This device's passkey, evaluated for this vault's salt.
 *
 * The vault used to register a passkey of its own here, while relay recovery
 * registered another, so a person with one finger had two "TabMira" entries in
 * their password manager and no way to tell which of them held what. The
 * credential is shared now; the salt and the HKDF `info` below are still this
 * vault's alone, so the key derived here is no more related to the relay's
 * than it ever was.
 */
async function passkeyMaterial(salt: Bytes): Promise<{ credentialId: Bytes; material: Bytes }> {
  try {
    const { credentialId, prf } = await prfFromPasskey({ salt, label: 'TabMira trading vault' });
    return { credentialId: credentialIdBytes(credentialId), material: new Uint8Array(prf) };
  } catch (e) {
    throw asVaultError(e);
  }
}

/** The shared module's failures, in the vocabulary this file's callers read. */
function asVaultError(e: unknown): VaultError {
  const err = e as Error;
  if (err.name === 'NotAllowedError') {
    return new VaultError('passkey_cancelled', 'the passkey prompt was dismissed');
  }
  if (err.name === PASSKEY_NO_KEY_STORAGE) {
    return new VaultError(
      'prf_unsupported',
      'this device made a passkey but will not derive a key from it, so the vault needs a passcode instead',
    );
  }
  // Inside the native shell the WebView hands passkeys to Android's
  // Credential Manager, and a phone with no passkey service switched on
  // (Google Password Manager, Samsung Pass, a password manager) answers
  // NotReadableError, "an unknown error occurred while talking to the
  // credential manager". Chrome never needed one, so this can be the first
  // time the phone has been asked. The fix is a system setting, which the
  // screen can point at; retrying the button cannot help.
  if (err.name === 'NotReadableError') {
    return new VaultError(
      'no_passkey_service',
      'this phone has no passkey service turned on, so the vault needs a passcode until one is',
    );
  }
  return e instanceof VaultError ? e : new VaultError('passkey_failed', err.message || 'the passkey did not work');
}

// --- lifecycle -------------------------------------------------------------

export async function vaultState(): Promise<VaultState> {
  await ensureRestored();
  const meta = await readMeta();
  return { exists: Boolean(meta), unlocked: Boolean(sessionKey), method: meta?.method ?? sessionMethod };
}

interface StoredSession {
  exchange: string;
  key: CryptoKey;
  method: UnlockMethod;
  expiresAt: number;
}

async function saveSession(key: CryptoKey, method: UnlockMethod): Promise<void> {
  try {
    await store().put({ exchange: SESSION_ID, key, method, expiresAt: Date.now() + autoLockMs } as StoredSession);
  } catch {
    // A browser that will not persist it just means unlocking again next time,
    // which is the old behaviour rather than a failure worth surfacing.
  }
}

let restoring: Promise<void> | undefined;

/**
 * Bring back a session this device already had.
 *
 * Runs once per page and is awaited by everything that needs the key, so a
 * reload does not read as locked before it has looked.
 */
export function ensureRestored(): Promise<void> {
  if (sessionKey) return Promise.resolve();
  if (!restoring) {
    restoring = (async () => {
      try {
        const held = await store().get<StoredSession>(SESSION_ID);
        if (!held?.key) return;
        if (Date.now() >= held.expiresAt) {
          await store().remove(SESSION_ID);
          return;
        }
        sessionKey = held.key;
        sessionMethod = held.method;
        // The timer runs to what is left of the stored session rather than a
        // fresh week, or a vault would never actually expire while in use.
        if (autoLockTimer) clearTimeout(autoLockTimer);
        autoLockTimer = setTimeout(lockVault, held.expiresAt - Date.now());
      } catch {
        // Nothing to restore, which is indistinguishable from never having had
        // one and is handled the same way: ask for the passcode.
      }
    })();
  }
  return restoring;
}

/**
 * Forget the key this module is holding without touching what is stored.
 *
 * Exactly what a page reload does, and the only way to test that a remembered
 * session actually comes back rather than never having gone away.
 */
export function forgetSessionMemoryForTest(): void {
  sessionKey = undefined;
  sessionMethod = undefined;
  restoring = undefined;
  if (autoLockTimer) clearTimeout(autoLockTimer);
  autoLockTimer = undefined;
}

export function isUnlocked(): boolean {
  return Boolean(sessionKey);
}

/**
 * Told when the vault shuts, by whoever shut it.
 *
 * There are three ways it happens (the lock button, the week running out, and
 * destroying the vault) and a screen that is only drawn while unlocked has to
 * hear about all of them. Polling isUnlocked() would work and would also be a
 * timer running for the life of the app to catch something that happens twice
 * a fortnight.
 */
const lockListeners = new Set<() => void>();

export function onVaultLock(listener: () => void): () => void {
  lockListeners.add(listener);
  return () => {
    lockListeners.delete(listener);
  };
}

/**
 * Drop the unlock key and stop the idle timer.
 *
 * Called on tab hide, on idle, and by the lock button. The CryptoKey is
 * non-extractable, so dropping the last reference is the whole of what can be
 * done: there is no buffer to wipe because the bytes were never in one.
 */
export function lockVault(): void {
  sessionKey = undefined;
  sessionMethod = undefined;
  restoring = undefined;
  // Deleted, not left to expire. Lock means locked now, and a stored session
  // that outlived the button that dismissed it would be the worst kind of
  // surprise.
  void store().remove(SESSION_ID).catch(() => {});
  if (autoLockTimer) clearTimeout(autoLockTimer);
  autoLockTimer = undefined;
  for (const listener of lockListeners) listener();
}

function touchAutoLock(): void {
  if (autoLockTimer) clearTimeout(autoLockTimer);
  if (!sessionKey) return;
  autoLockTimer = setTimeout(lockVault, autoLockMs);
}

/** Minutes of inactivity before the vault locks itself. */
export function setAutoLockMinutes(minutes: number): void {
  autoLockMs = Math.max(1, minutes) * 60_000;
  touchAutoLock();
  if (sessionKey && sessionMethod) void saveSession(sessionKey, sessionMethod);
}

/**
 * Create the vault. Destroys anything already stored, because a new unlock key
 * cannot decrypt records written under the old one.
 */
export async function createVault(
  method: UnlockMethod,
  passcode?: string,
): Promise<void> {
  const salt = crypto.getRandomValues(new Uint8Array(32));
  let key: CryptoKey;
  let credentialId: Bytes | undefined;

  if (method === 'passkey') {
    const asked = await passkeyMaterial(salt);
    credentialId = asked.credentialId;
    key = await deriveFromBytes(asked.material, salt);
    asked.material.fill(0);
  } else {
    if (!passcode || passcode.length < 8) {
      throw new VaultError('weak_passcode', 'a passcode needs at least 8 characters');
    }
    key = await deriveFromPasscode(passcode, salt);
  }

  const checkIv = crypto.getRandomValues(new Uint8Array(12));
  const checkCt = new Uint8Array(
    await crypto.subtle.encrypt({ name: 'AES-GCM', iv: checkIv }, key, enc.encode(CHECK_PLAINTEXT)),
  );

  for (const id of await listRecords()) await store().remove(id);

  const meta: StoredMeta = { exchange: META_ID, version: 1, method, salt, credentialId, checkIv, checkCt };
  await store().put(meta);
  // The vault is the only copy of a direct venue's key. Ask the browser not
  // to clear it, here and again on every key stored (see putCredential).
  void ensurePersistentStorage();

  sessionKey = key;
  sessionMethod = method;
  // Remembered from the moment it is created, so setting a passcode does not
  // then immediately ask for it again on the next page load.
  await saveSession(key, method);
  touchAutoLock();
}

/**
 * Swap how this vault unlocks, keeping everything in it.
 *
 * The naive version is to destroy the vault and reconnect every exchange,
 * which costs the user a paste per account and means going back to the
 * exchange for a secret it only ever showed once. Instead the credentials are
 * decrypted under the current key and re-encrypted under the new one, so
 * changing the lock does not change what is behind it.
 *
 * Requires the vault to be open, and deliberately so: re-encrypting what you
 * cannot read is not possible, and being asked to unlock before changing the
 * lock is the same thing every password change asks for.
 *
 * The new salt is fresh rather than reused. Keeping the old one would mean the
 * same derivation input produced the same key across a change that is supposed
 * to have replaced it.
 */
export async function changeUnlockMethod(method: UnlockMethod, passcode?: string): Promise<void> {
  const current = requireKey();
  const meta = await readMeta();
  if (!meta) throw new VaultError('no_vault', 'there is no vault on this device yet');

  // Read everything out first. If any of this fails, nothing has been touched.
  const ids = await listRecords();
  const held: Credential[] = [];
  for (const id of ids) {
    const record = await store().get<StoredCredential>(id);
    if (!record) continue;
    const plain = new Uint8Array(
      await crypto.subtle.decrypt({ name: 'AES-GCM', iv: record.iv }, current, record.ct),
    );
    const parsed = JSON.parse(dec.decode(plain)) as { secret: number[]; passphrase: string | null };
    plain.fill(0);
    held.push({
      exchange: record.exchange,
      keyId: record.keyId,
      alg: record.alg,
      sandbox: record.sandbox,
      secret: new Uint8Array(parsed.secret),
      passphrase: parsed.passphrase ?? undefined,
    });
  }

  try {
    const salt = crypto.getRandomValues(new Uint8Array(32));
    let key: CryptoKey;
    let credentialId: Bytes | undefined;

    if (method === 'passkey') {
      const asked = await passkeyMaterial(salt);
      credentialId = asked.credentialId;
      key = await deriveFromBytes(asked.material, salt);
      asked.material.fill(0);
    } else {
      if (!passcode || passcode.length < 8) {
        throw new VaultError('weak_passcode', 'a passcode needs at least 8 characters');
      }
      key = await deriveFromPasscode(passcode, salt);
    }

    const checkIv = crypto.getRandomValues(new Uint8Array(12));
    const checkCt = new Uint8Array(
      await crypto.subtle.encrypt({ name: 'AES-GCM', iv: checkIv }, key, enc.encode(CHECK_PLAINTEXT)),
    );

    // The session key becomes the new one before anything is written, so
    // putCredential below encrypts under it.
    sessionKey = key;
    sessionMethod = method;
    for (const credential of held) await putCredential(credential);
    await store().put({ exchange: META_ID, version: 1, method, salt, credentialId, checkIv, checkCt } as StoredMeta);
    touchAutoLock();
  } catch (e) {
    // Put the old key back so the vault is still open and still readable. The
    // stored records were never rewritten on this path, so they still match it.
    sessionKey = current;
    sessionMethod = meta.method;
    throw e;
  } finally {
    for (const credential of held) credential.secret.fill(0);
  }
}

export async function unlockVault(passcode?: string): Promise<void> {
  const meta = await readMeta();
  if (!meta) throw new VaultError('no_vault', 'there is no vault on this device yet');

  let key: CryptoKey;
  if (meta.method === 'passkey') {
    if (!meta.credentialId) throw new VaultError('vault_corrupt', 'this vault is missing its passkey reference');
    // The credential this vault named when it was made, which on a vault older
    // than the shared credential is one of the two that used to exist. It goes
    // on working: a wrap always says which passkey opens it, and that is read
    // rather than assumed.
    const named = credentialIdString(meta.credentialId);
    let material: Bytes;
    try {
      material = new Uint8Array(await evaluatePrf(named, meta.salt));
    } catch (e) {
      throw asVaultError(e);
    }
    // It opened, so if this device has not settled on a passkey yet, this is
    // the one. Whichever feature is used first decides, and the rest borrow it
    // instead of registering their own.
    if (!knownCredentialId()) rememberCredentialId(named);
    key = await deriveFromBytes(material, meta.salt);
    material.fill(0);
  } else {
    if (!passcode) throw new VaultError('passcode_required', 'this vault unlocks with a passcode');
    key = await deriveFromPasscode(passcode, meta.salt);
  }

  // Verify against the known plaintext before accepting the key. Without this
  // a wrong passcode would be discovered later, at an order, and reported as
  // whatever that failure happened to look like.
  try {
    const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: meta.checkIv }, key, meta.checkCt);
    if (dec.decode(plain) !== CHECK_PLAINTEXT) throw new Error('mismatch');
  } catch {
    throw new VaultError(
      meta.method === 'passkey' ? 'passkey_mismatch' : 'wrong_passcode',
      meta.method === 'passkey'
        ? 'that passkey does not open this vault'
        : 'that passcode does not open this vault',
    );
  }

  sessionKey = key;
  sessionMethod = meta.method;
  await saveSession(key, meta.method);
  touchAutoLock();
}

function requireKey(): CryptoKey {
  if (!sessionKey) throw new VaultError('locked', 'the vault is locked');
  touchAutoLock();
  return sessionKey;
}

// --- records ---------------------------------------------------------------

export async function listExchanges(): Promise<string[]> {
  return (await listRecords()).filter((id) => !id.startsWith(SEALED_PREFIX));
}

/**
 * Every encrypted record, sealed ones included.
 *
 * Used by the two paths that must not miss one: re-encrypting under a new
 * unlock method, and deleting the vault. listExchanges() is the narrower
 * question the UI asks, and answering both with one function is how the relay
 * data key would quietly stop opening after a passcode change.
 */
async function listRecords(): Promise<string[]> {
  const all = await store().all<StoredCredential>();
  return all.map((r) => r.exchange).filter((id) => id !== META_ID && id !== SESSION_ID);
}

/**
 * Encrypt and store one credential.
 *
 * `secret` arrives as bytes and is NOT zeroed here: the caller owns the buffer
 * and knows when it is finished with it. Zeroing a caller's argument is the
 * kind of surprise that produces a bug two callers later.
 */
export async function putCredential(input: Credential): Promise<void> {
  await ensureRestored();
  const key = requireKey();
  const iv = crypto.getRandomValues(new Uint8Array(12));

  // The passphrase travels inside the same ciphertext as the secret rather
  // than in its own field, so a record leaks nothing about whether an exchange
  // uses one.
  const payload = enc.encode(
    JSON.stringify({ secret: Array.from(input.secret), passphrase: input.passphrase ?? null }),
  );
  const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, payload));
  payload.fill(0);

  const record: StoredCredential = {
    exchange: input.exchange,
    keyId: input.keyId,
    alg: input.alg,
    sandbox: input.sandbox,
    iv,
    ct,
  };
  await store().put(record);
  void ensurePersistentStorage();
}

/**
 * Decrypt one credential.
 *
 * The returned `secret` is live plaintext. Zero it as soon as it has been
 * imported or sent: `credential.secret.fill(0)`.
 */
export async function getCredential(exchange: string): Promise<Credential | undefined> {
  await ensureRestored();
  const key = requireKey();
  const record = await store().get<StoredCredential>(exchange);
  if (!record) return undefined;

  const plain = new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: record.iv }, key, record.ct));
  const parsed = JSON.parse(dec.decode(plain)) as { secret: number[]; passphrase: string | null };
  plain.fill(0);

  return {
    exchange: record.exchange,
    keyId: record.keyId,
    alg: record.alg,
    sandbox: record.sandbox,
    secret: new Uint8Array(parsed.secret),
    passphrase: parsed.passphrase ?? undefined,
  };
}

/** Key id and algorithm, without unlocking. Enough to render the accounts list. */
export async function describeCredential(
  exchange: string,
): Promise<{ exchange: string; keyId: string; sandbox?: boolean } | undefined> {
  const record = await store().get<StoredCredential>(exchange);
  return record
    ? { exchange: record.exchange, keyId: record.keyId, sandbox: record.sandbox }
    : undefined;
}

export async function removeCredential(exchange: string): Promise<void> {
  await store().remove(exchange);
}

/**
 * Put a secret that is not an exchange credential into the vault.
 *
 * Same encryption, same key, same lifetime as everything else here; the only
 * difference is that it is not an account and so does not appear in the
 * accounts list. Takes a string rather than bytes because the one caller has a
 * base64 key, and a string it did not create is not a string it can wipe.
 */
export async function sealSecret(id: string, value: string): Promise<void> {
  if (!id.startsWith(SEALED_PREFIX)) throw new VaultError('bad_id', 'a sealed record needs the sealed prefix');
  const bytes = enc.encode(value);
  try {
    await putCredential({ exchange: id, keyId: '', secret: bytes });
  } finally {
    bytes.fill(0);
  }
}

/** Read one back, or undefined if it was never sealed. Throws if the vault is shut. */
export async function openSecret(id: string): Promise<string | undefined> {
  const held = await getCredential(id);
  if (!held) return undefined;
  try {
    return dec.decode(held.secret);
  } finally {
    held.secret.fill(0);
  }
}

/** Whether a sealed record exists, without opening it. Answers while locked. */
export async function hasSealedSecret(id: string): Promise<boolean> {
  return Boolean(await store().get<StoredCredential>(id));
}

/** Remove the vault and everything in it. */
export async function destroyVault(): Promise<void> {
  lockVault();
  for (const id of await listRecords()) await store().remove(id);
  await store().remove(META_ID);
  // The routing's copy of what is in here (vaultIndex.ts): nothing now.
  setVaultIndex([]);
}