Back to where your exchange keys go

The keystore

Turns a stored secret into a signing handle the app can use but not read. Unedited, from build 579b29d3.

lib/trading/keystore.ts lines 1-531
// Turning a stored credential into something that can sign.
//
// The bytes live in vault.ts, encrypted, and this file is the only place they
// are ever plaintext. The shape of every function here follows one rule: a
// decrypted secret exists as a Uint8Array for as long as it takes to import
// it, and is zeroed on the way out, including when the import throws.
//
// What comes back is a non-extractable CryptoKey held in memory for the
// session. So there are two layers, and they defend different things:
//
//   vault.ts    at rest, against anything that can read the disk
//   this file   in memory, against script reading a key back out of a handle
//
// Neither defends against script signing with a handle while the vault is
// open. Nothing available in a browser does.

import { exchangeLabel } from '@/lib/exchangeMeta';
import { t } from '@/lib/i18n';
import { importCoinbaseKey, importHmacKey, type JwtAlg } from './keys';
import { tradesOnThisDevice } from './nativeHttp';
import { NATIVE_DIRECT_VENUES, phoneCanSend } from './nativeDirect';
import { forgetVaultKey, noteVaultKey, setVaultIndex } from './vaultIndex';
import { hybridCandidate } from './desktopHybrid';
import { KEY_SPECS } from '../../relay/src/adapters/signingKey.ts';
import { requiredSandbox, rolloutEnforced, rolloutMode } from './rollout';
import { VENUES } from './venues';
import {
  describeCredential,
  ensureRestored,
  getCredential,
  isUnlocked,
  listExchanges,
  putCredential,
  removeCredential,
  VaultError,
} from './vault';

/**
 * Why a key was turned away, in a form the dashboard can count.
 *
 * The message is for the reader and says the specific thing; this says which
 * of three kinds of thing it was. 'release-gate' is a refusal of ours, a
 * venue or environment this build does not offer. 'exchange-refused' means
 * the exchange did not recognise the key at all. 'can-withdraw' is only ever
 * raised on the relay path today, where Coinbase reports the key's own
 * permissions: the direct path stopped refusing on it, see proveEnvironment.
 * 'unreachable' means the exchange was never reached, so the key is untested
 * rather than refused.
 */
export type KeyRefusal = 'release-gate' | 'exchange-refused' | 'can-withdraw' | 'wrong-environment' | 'unreachable';

export class UnsupportedKeyError extends Error {
  constructor(
    message: string,
    public readonly reason: KeyRefusal = 'release-gate',
  ) {
    super(message);
  }
}

/**
 * A key that works, on the other environment from the one picked.
 *
 * The most common refusal on Binance by far: a real key pasted with Practice
 * selected (support, 2026-10-09, and several before it). The exchange's own
 * answer cannot say so, since to the testnet a live key is just a key it has
 * never seen. So proveEnvironment asks the other host too, and this carries
 * which one said yes, for the sheet to offer the switch in one tap rather
 * than a paragraph about where keys come from.
 */
export class WrongEnvironmentError extends UnsupportedKeyError {
  constructor(
    message: string,
    /** The environment the key does work on: true for the practice one. */
    public readonly sandbox: boolean,
  ) {
    super(message, 'wrong-environment');
  }
}

/** What the signing layer needs, and nothing more. */
export interface SigningCredential {
  exchange: string;
  keyId: string;
  /** Absent for static-auth venues, which have nothing to sign with. */
  key?: CryptoKey;
  /**
   * Static-auth venues: the credential the exchange wants verbatim. And
   * secp256k1 venues (Hyperliquid), whose private key Web Crypto cannot hold
   * as a handle, so the adapter signs from the text.
   */
  staticSecret?: string;
  /** Sent verbatim in a header where an exchange uses one. */
  passphrase?: string;
  alg?: JwtAlg;
  /** Route to the exchange's paper or demo environment. */
  sandbox?: boolean;
}

/** Listed without unlocking, so the accounts screen renders while locked. */
export interface StoredKeySummary {
  exchange: string;
  keyId: string;
  sandbox?: boolean;
}

// Imported keys, cached for the session. Dropped whenever the vault locks, so
// a locked vault cannot be signed against from a stale handle.
const cache = new Map<string, SigningCredential>();

function assertUnlocked() {
  if (!isUnlocked()) {
    cache.clear();
    throw new VaultError('locked', 'the vault is locked');
  }
}

/**
 * Read back a remembered session before calling the vault shut.
 *
 * A reload drops the key from memory while a week-long session sits in
 * IndexedDB. Only the Portfolio tab used to read it back, so a chart opened
 * straight from a deep link asked for its orders, was told the vault was
 * locked, and went on saying so until Portfolio had been looked at once.
 * Awaited here, every caller gets the same answer whichever screen mounts
 * first. Free after the first call: the vault memoises the read.
 */
async function requireUnlocked(): Promise<void> {
  await ensureRestored();
  assertUnlocked();
}

export async function listStoredKeys(): Promise<StoredKeySummary[]> {
  const ids = await listExchanges();
  const out: StoredKeySummary[] = [];
  for (const id of ids) {
    const d = await describeCredential(id);
    if (d) out.push(d);
  }
  // What the vault holds, read from the vault itself, so the routing's
  // synchronous copy (vaultIndex.ts) heals whatever happened to it.
  setVaultIndex(out.map((k) => k.exchange));
  return out;
}

export async function removeStoredKey(exchange: string): Promise<void> {
  cache.delete(exchange);
  await removeCredential(exchange);
  forgetVaultKey(exchange);
}

/** Called by the vault's lock path and on tab hide. */
export function forgetSessionKeys(): void {
  cache.clear();
}

/**
 * Import raw secret bytes into a signing handle, per the venue's scheme.
 *
 * Takes bytes rather than a string so the caller can wipe them. The one
 * unavoidable string is whatever the user pasted into the DOM, which
 * JavaScript gives no way to clear.
 */
async function importFor(
  exchange: string,
  secret: Uint8Array,
): Promise<{ key?: CryptoKey; staticSecret?: string; alg?: JwtAlg }> {
  const venue = VENUES[exchange];
  if (!venue) throw new UnsupportedKeyError(`${exchange} is not a venue this app can trade on`);

  // The importers take the pasted text, because every one of these formats is
  // defined over text: PEM armour, base64, or an ASCII secret. Decoding here
  // and re-encoding there would be two chances to corrupt it.
  const text = new TextDecoder().decode(secret);

  // A relay venue's key kept on the phone (nativeDirect.ts) is signed with by
  // the relay's own adapter, so it is imported the way that adapter imports
  // it, which is not always what the venue's auth scheme alone would say:
  // Gate's SHA-512 secret is text, Kraken's is base64.
  const spec = NATIVE_DIRECT_VENUES.has(exchange) ? KEY_SPECS[exchange as keyof typeof KEY_SPECS] : undefined;
  if (spec) {
    try {
      if (spec.kind === 'coinbase') {
        const { key, alg } = await importCoinbaseKey(text);
        return { key, alg };
      }
      return { key: await importHmacKey(text, spec.hash, spec.base64 === true) };
    } catch {
      throw new UnsupportedKeyError(
        t('This does not look like a {exchange} secret. Paste it exactly as {exchange} showed it.', {
          exchange: exchangeLabel(exchange),
        }),
      );
    }
  }

  switch (venue.auth) {
    case 'jwt': {
      const { key, alg } = await importCoinbaseKey(text);
      return { key, alg };
    }
    case 'hmac-sha512':
      return { key: await importHmacKey(text, 'SHA-512', true) };
    case 'hmac-sha384':
      // Gemini, the only venue on this scheme, signs with its secret as plain
      // text. This used to base64-decode it, unnoticed while Gemini had no
      // adapter, which would have failed every signature it made.
      return { key: await importHmacKey(text, 'SHA-384') };
    case 'hmac-sha256':
      return { key: await importHmacKey(text, 'SHA-256') };
    case 'static':
      // Nothing to import. The exchange wants this value back verbatim, so it
      // stays a string for as long as the session lasts. Encrypted at rest
      // like everything else; readable in memory, unlike everything else.
      return { staticSecret: text };
    case 'secp256k1': {
      // Web Crypto has no secp256k1 curve, so there is no handle to import
      // into. Checked here so a paste that cannot sign is refused at the form,
      // then held as text for the session, like a static secret. The adapter
      // turns it into bytes for each signature and zeroes them after.
      //
      // Loaded here rather than imported: the curve library behind it is
      // 50 KB that only a Hyperliquid key ever needs, and this module is on
      // the watchlist's first load through the exchange list.
      const { agentKeyBytes } = await import('./hyperliquidSign');
      try {
        agentKeyBytes(text).fill(0);
      } catch (e) {
        throw new UnsupportedKeyError((e as Error).message);
      }
      return { staticSecret: text.trim() };
    }
    case 'sha256-concat':
      // Bitunix hashes the secret as text after a digest of the request,
      // rather than keying an HMAC with it, so Web Crypto has no handle to
      // hold it in. Held as text for the session, like a static secret, and
      // only ever hashed, never sent.
      if (!text.trim()) throw new UnsupportedKeyError('the secret key is empty');
      return { staticSecret: text.trim() };
    default:
      throw new UnsupportedKeyError(`no import path for ${venue.auth}`);
  }
}

/**
 * Store a pasted credential, encrypted.
 *
 * Imports it first, so a key that cannot be used is rejected while the user is
 * still looking at the form rather than accepted and discovered broken later.
 */
export async function enrollKey(
  exchange: string,
  keyId: string,
  secret: string,
  passphrase?: string,
  sandbox?: boolean,
): Promise<void> {
  await requireUnlocked();

  // A relay venue keeps its credential in the user's own Worker, never here.
  // Outside the release gate on purpose: it is a fact about how the venue is
  // reached rather than a product decision, so it holds even with the DEV
  // switch lifted. It used to be covered by the 'balances' mode refusing
  // Coinbase outright, which stopped being true the moment Coinbase went
  // live, and a live Coinbase key landing in the device vault is exactly what
  // the relay exists to avoid.
  //
  // Except where this device is a phone app that sends the venue itself
  // (nativeDirect.ts): there the relay venue is a direct one, and its key is
  // kept here like any other. So is one a browser trades over the venue's
  // own socket (desktopHybrid.ts). Asked as "could", not "does": a venue
  // still on the relay because the relay holds its account
  // (relayFallback.ts) moves to this device by its key being stored here.
  if (VENUES[exchange]?.transport === 'relay' && !phoneCanSend(exchange) && !hybridCandidate(exchange)) {
    throw new UnsupportedKeyError(
      `${exchange} is connected through your relay, so its key is not stored on this device`,
    );
  }

  // An app-only venue (KuCoin, Bitunix) is signed for here but sent from the phone,
  // so a browser holding its key would hold a key nothing can use. Refused
  // for the same reason as the relay check above: a fact about the venue, so
  // outside the release gate.
  if (!tradesOnThisDevice(exchange)) {
    throw new UnsupportedKeyError(
      t('{exchange} connects in the TabMira app for Android and iPhone. It does not take requests from a browser.', {
        exchange: exchangeLabel(exchange),
      }),
    );
  }

  // The release gate, enforced where the credential is created rather than
  // only where it is offered. The picker decides what a user is shown; this
  // decides what can exist on the device. A live key that is never stored is a
  // live order that cannot be placed by any later code path, which is a much
  // stronger guarantee than a checkbox the UI happens to hide.
  // Skipped only by the DEV panel switch, which cannot be on in a production
  // build. Read through rolloutEnforced() rather than featureOn() directly, so
  // there is one definition of what "gated" means and not two that can drift.
  if (rolloutEnforced()) {
    const mode = rolloutMode(exchange);
    if (!mode) {
      throw new UnsupportedKeyError(`${exchange} is not part of this release yet`);
    }
    if (mode === 'balances') {
      // No venue is on this mode in the current release. Kept because the mode
      // still exists and a future venue may use it: reading an account without
      // trading it is a real thing to ship.
      throw new UnsupportedKeyError(
        `this release can read a ${exchange} account but not trade it, so there is no key to store`,
      );
    }
    if (mode === 'paper' && sandbox !== true) {
      throw new UnsupportedKeyError(
        `this release connects ${exchange} to its practice environment only, so a live key is not accepted`,
      );
    }
  }

  const bytes = new TextEncoder().encode(secret);
  try {
    const imported = await importFor(exchange, bytes);
    if (imported.key?.extractable) {
      throw new Error('refusing to store an extractable signing key');
    }
    await putCredential({ exchange, keyId, secret: bytes, passphrase, alg: imported.alg, sandbox });
    cache.set(exchange, { exchange, keyId, passphrase, sandbox, ...imported });
    noteVaultKey(exchange);
  } finally {
    // Runs on the throw path too. A rejected paste must not leave its bytes
    // sitting in a buffer for the garbage collector to get to eventually.
    bytes.fill(0);
  }
}

/**
 * Prove the stored key works where it is meant to, by asking the exchange, and
 * drop it if it does not.
 *
 * Two questions, one call. While a venue is paper-only, this is what turns
 * that rule from a promise into a fact: a testnet key and a live key are the
 * same shape, the user picked which to paste, and only the exchange can tell
 * them apart, because a testnet key does not authenticate against
 * ws-api.binance.com and a live key does not authenticate against the testnet.
 * Once the gate is lifted, the same call is the only thing standing between a
 * mistyped or revoked live key and a "Connected" screen. It used to return
 * early in that case, and a key of sixty-four X's went straight to Connected,
 * with the refusal turning up later on the account row.
 *
 * A key that can withdraw is not refused here any more. It used to be, on
 * the adapter's canWithdraw, and for Binance that flag came from
 * account.status, which describes the account rather than the key: any
 * verified account can withdraw, so every live key was turned away with a
 * message about a permission its owner had left off (reported 2026-09-17).
 * The key's own restrictions live on a REST endpoint the WebSocket API does
 * not expose, so the app cannot ask. The guide and the key form say to leave
 * withdrawals off, and that request is what stands now.
 *
 * Separate from enrollKey rather than folded into it, for two reasons. The
 * import has to happen first, since this needs a signing handle to make the
 * call with. And enrollKey stays offline and synchronous in what it promises,
 * so it can be unit tested without a network and the connect sheet can show
 * "checking with Binance" around the part that actually waits.
 *
 * Fails closed. A network error, a timeout, an exchange having a bad day: none
 * of those prove anything about the key, so none of them may leave it stored.
 */
export async function proveEnvironment(exchange: string): Promise<void> {
  const { adapterFor, hasSandbox } = await import('./adapters');
  const adapter = adapterFor(exchange);
  // No adapter means nothing here can place an order anyway, so there is
  // nothing to prove and refusing would only block a working connection.
  if (!adapter) return;

  // The gate's environment where there is one, the key's own otherwise.
  const required = requiredSandbox(exchange);
  let sandbox = required ?? false;
  let report: { canRead: boolean; unreachable?: boolean; notes: string[] };
  try {
    const cred = await getSigningCredential(exchange);
    sandbox = required ?? cred.sandbox ?? false;
    report = await adapter.validate(cred, { sandbox });
  } catch (e) {
    report = { canRead: false, notes: [(e as Error).message] };
  }

  const label = exchangeLabel(exchange);
  if (report.canRead) return;

  // Never reached, so there is nothing to conclude about the key and no
  // point asking the other environment. Still not kept: this fails closed
  // like everything else here. The sheet keeps the paste for another try.
  if (report.unreachable) {
    await removeStoredKey(exchange);
    throw new UnsupportedKeyError(
      t("Couldn't reach {exchange} from this device, so the key was not checked. Check your connection and press Connect again. If {exchange} does not serve your country, it cannot be connected from here.", {
        exchange: label,
      }),
      'unreachable',
    );
  }

  // Where the release leaves the choice to the key, a refusal on one host is
  // worth one more question to the other before calling the key bad. Only
  // then: a venue pinned to practice has no other environment to offer, and
  // asking the live host about a key that may not go there would be a live
  // call made for nothing.
  let other: { canRead: boolean; notes: string[] } | undefined;
  if (required === undefined && hasSandbox(exchange)) {
    try {
      const cred = await getSigningCredential(exchange);
      other = await adapter.validate(cred, { sandbox: !sandbox });
    } catch (e) {
      other = { canRead: false, notes: [(e as Error).message] };
    }
  }

  await removeStoredKey(exchange);
  if (other?.canRead) {
    throw new WrongEnvironmentError(
      sandbox
        ? `This is a real ${label} key, and Practice account is selected. It has not been kept.`
        : `This is a ${label} practice key, and Real money is selected. It has not been kept.`,
      !sandbox,
    );
  }
  if (other) {
    // Neither host knows it. The live host's words are the useful ones,
    // since only a live key has permissions and IP lists to get wrong.
    const live = sandbox ? other : report;
    throw new UnsupportedKeyError(
      `${label} did not accept this key as a real key or a practice one, so it has not been kept. `
        + live.notes.join(' '),
      'exchange-refused',
    );
  }
  throw new UnsupportedKeyError(
    sandbox
      ? `${label} did not recognise this key on its practice environment, so it has not been kept. `
        + 'Create a key on the testnet and paste that one. '
        + report.notes.join(' ')
      : `${label} did not accept this key, so it has not been kept. ${report.notes.join(' ')}`,
    'exchange-refused',
  );
}

/**
 * Get the signing handle for one exchange, decrypting if this is the first use
 * this session.
 *
 * Throws VaultError('locked') when the vault is shut, which is the caller's
 * cue to prompt for unlock rather than to report a failure.
 */
export async function getSigningCredential(exchange: string): Promise<SigningCredential> {
  await requireUnlocked();

  const hit = cache.get(exchange);
  if (hit) return hit;

  const stored = await getCredential(exchange);
  if (!stored) throw new UnsupportedKeyError(`no credential stored for ${exchange}`);

  try {
    const imported = await importFor(exchange, stored.secret);
    const credential: SigningCredential = {
      exchange,
      keyId: stored.keyId,
      passphrase: stored.passphrase,
      sandbox: stored.sandbox,
      ...imported,
    };
    cache.set(exchange, credential);
    return credential;
  } finally {
    stored.secret.fill(0);
  }
}

export type SecretExposure = 'signing-handle' | 'readable-in-memory';

export interface StorageNote {
  exposure: SecretExposure;
  /** One sentence, written for the person about to paste a credential. */
  detail: string;
}

/**
 * How this venue's secret is held once the vault is open, in words the UI can
 * show.
 *
 * At rest the answer is the same everywhere and the sheet says it once:
 * encrypted, opened only by this device's passkey or passcode. What differs is
 * what the secret becomes while the vault is unlocked, and that difference is
 * worth stating because it is the only part the user could be surprised by.
 */
export function storageNote(exchange: string): StorageNote {
  if (VENUES[exchange]?.auth === 'secp256k1') {
    return {
      exposure: 'readable-in-memory',
      detail:
        'Hyperliquid signs with a kind of key this browser cannot hold as a locked handle, so while the '
        + "app is unlocked the API wallet's private key is readable in memory. It is encrypted whenever "
        + 'the vault is locked, never leaves this device, and an API wallet cannot withdraw.',
    };
  }
  if (VENUES[exchange]?.auth === 'sha256-concat') {
    return {
      exposure: 'readable-in-memory',
      detail:
        'Bitunix signs each request by hashing the secret with it, which a locked signing key in this '
        + 'app cannot do, so while the app is unlocked the secret is readable in memory. It is encrypted '
        + 'whenever the vault is locked, and it never leaves this device.',
    };
  }
  if (VENUES[exchange]?.auth === 'static') {
    return {
      exposure: 'readable-in-memory',
      detail:
        'This exchange authenticates with the secret itself rather than a signature, so while the app '
        + 'is unlocked the secret is readable in memory. It is encrypted whenever the vault is locked, '
        + 'and it never leaves this device.',
    };
  }
  return {
    exposure: 'signing-handle',
    detail:
      'Once unlocked, your secret becomes a signing key this browser will use but will not hand back, '
      + 'to us or to anything else. Locked, it is encrypted on this device and nowhere else.',
  };
}