Back to where your exchange keys go

Request signing

Signs requests with the handle. Never sees a secret as text. Unedited, from build 579b29d3.

lib/trading/sign.ts lines 1-258
// Request signing, in the browser, with a key the page cannot read.
//
// Every function here takes a CryptoKey handle out of the keystore and never a
// secret string. That is what makes the forwarder safe to run on our own
// server: by the time a request reaches the transport it is already signed,
// and the signature is the only thing that can authorise it.
//
// The signing schemes are the exchanges' own, unchanged. The one detail worth
// knowing before reading further is how much of the request each signature
// actually covers, because that is exactly the set of things a compromised
// forwarder could alter without the exchange noticing:
//
//   Binance, Binance.US   query string, including the body-as-query for POSTs
//   Kraken                path plus a SHA-256 of the nonce and the POST body
//   Coinbase              method, host and path ONLY. Not the body.
//
// Coinbase is the outlier and it is not a mistake in this file. Their JWT
// scheme signs a `uri` claim and nothing else about the request. See
// SIGNED_FORWARDER.md for what follows from that.

import { b64uEncode, b64uEncodeString, toHex, type JwtAlg } from './keys';

/**
 * What a signer needs. Declared here rather than borrowed from the keystore so
 * this module depends on nothing about how a credential is stored, and so
 * `key` is required: a signer with no key is not a thing this file can use.
 */
export interface SigningKey {
  keyId: string;
  key: CryptoKey;
  alg?: JwtAlg;
}

export interface SignedRequest {
  method: string;
  url: string;
  headers: Record<string, string>;
  body?: string;
}

const enc = new TextEncoder();

/**
 * Coinbase Advanced Trade: a fresh JWT per request, valid for 120 seconds.
 *
 * Not cached, deliberately. The `uri` claim binds a token to one method and
 * one path, so caching would buy a few milliseconds in exchange for a token
 * that outlives the call it was minted for.
 */
export async function mintCoinbaseJwt(
  cred: SigningKey,
  method: string,
  host: string,
  path: string,
): Promise<string> {
  const alg: JwtAlg = cred.alg ?? 'ES256';
  const now = Math.floor(Date.now() / 1000);
  const nonce = toHex(crypto.getRandomValues(new Uint8Array(16)));

  const header = { alg, kid: cred.keyId, typ: 'JWT', nonce };
  const payload = {
    sub: cred.keyId,
    iss: 'cdp',
    nbf: now,
    exp: now + 120,
    // Path only. A query string here makes Coinbase reject the token.
    uri: `${method} ${host}${path}`,
  };

  const signingInput = `${b64uEncodeString(JSON.stringify(header))}.${b64uEncodeString(
    JSON.stringify(payload),
  )}`;

  // Web Crypto's ECDSA output is already raw r||s, which is what JOSE wants.
  // Server-side JWT libraries usually have to unwrap DER here; we do not.
  const algParams: AlgorithmIdentifier | EcdsaParams =
    alg === 'ES256' ? { name: 'ECDSA', hash: 'SHA-256' } : { name: 'Ed25519' };
  const sig = new Uint8Array(
    await crypto.subtle.sign(algParams, cred.key, enc.encode(signingInput)),
  );

  return `${signingInput}.${b64uEncode(sig)}`;
}

export async function signCoinbase(
  cred: SigningKey,
  method: string,
  url: URL,
  body?: unknown,
): Promise<SignedRequest> {
  const jwt = await mintCoinbaseJwt(cred, method, url.hostname, url.pathname);
  return {
    method,
    url: url.toString(),
    headers: {
      Authorization: `Bearer ${jwt}`,
      'Content-Type': 'application/json',
    },
    body: body === undefined ? undefined : JSON.stringify(body),
  };
}

async function hmacBase64(key: CryptoKey, data: string): Promise<string> {
  const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, enc.encode(data)));
  let bin = '';
  for (const b of sig) bin += String.fromCharCode(b);
  return btoa(bin);
}

/**
 * OKX: base64 HMAC-SHA256 over timestamp + method + requestPath + body.
 *
 * `requestPath` includes the query string, so the signature covers everything
 * except the headers. The passphrase rides along unsigned in its own header
 * because OKX wants it verbatim, which is why the keystore cannot hold it as a
 * signing handle.
 */
export async function signOkx(
  cred: SigningKey & { passphrase?: string },
  method: string,
  url: URL,
  body?: unknown,
  opts: { simulated?: boolean; timestamp?: string } = {},
): Promise<SignedRequest> {
  // OKX requires ISO-8601 with exactly milliseconds. Date#toISOString gives
  // that shape; anything coarser is rejected as a bad timestamp.
  //
  // Injectable so the signature can be compared against ccxt's for the same
  // inputs. A signer whose clock cannot be fixed can only be tested against
  // itself, which proves nothing about whether the exchange would accept it.
  const timestamp = opts.timestamp ?? new Date().toISOString();
  const payload = body === undefined ? '' : JSON.stringify(body);
  const requestPath = url.pathname + url.search;

  const headers: Record<string, string> = {
    'OK-ACCESS-KEY': cred.keyId,
    'OK-ACCESS-SIGN': await hmacBase64(cred.key, timestamp + method.toUpperCase() + requestPath + payload),
    'OK-ACCESS-TIMESTAMP': timestamp,
    'OK-ACCESS-PASSPHRASE': cred.passphrase ?? '',
    'Content-Type': 'application/json',
  };
  // Demo trading is the same host and the same endpoints, switched by a
  // header. Convenient, and a good reason to be careful: forgetting it sends a
  // test order to the live book.
  if (opts.simulated) headers['x-simulated-trading'] = '1';

  return { method: method.toUpperCase(), url: url.toString(), headers, body: payload || undefined };
}

async function hmacHex(key: CryptoKey, data: string): Promise<string> {
  return toHex(new Uint8Array(await crypto.subtle.sign('HMAC', key, enc.encode(data))));
}

/**
 * Binance and Binance.US: HMAC-SHA256 over the query string, with the
 * signature appended as a further query parameter.
 *
 * POST bodies go in the query string too, which is Binance's own convention
 * and the reason their signature covers the whole request rather than just
 * the path.
 */
export async function signBinance(
  cred: SigningKey,
  method: string,
  url: URL,
  params: Record<string, string | number | undefined> = {},
): Promise<SignedRequest> {
  const signed = new URL(url.toString());
  for (const [k, v] of Object.entries(params)) {
    if (v !== undefined) signed.searchParams.set(k, String(v));
  }
  // Caller-supplied timestamp wins, so a test can pin the clock and diff the
  // result against ccxt's signature for the same request.
  if (!signed.searchParams.has('timestamp')) {
    signed.searchParams.set('timestamp', String(Date.now()));
  }
  // recvWindow is the exchange-side replay bound. It is what stops the
  // forwarder holding a signed request and sending it later.
  if (!signed.searchParams.has('recvWindow')) signed.searchParams.set('recvWindow', '5000');

  const signature = await hmacHex(cred.key, signed.searchParams.toString());
  signed.searchParams.set('signature', signature);

  return {
    method,
    url: signed.toString(),
    headers: { 'X-MBX-APIKEY': cred.keyId },
  };
}

/**
 * Gemini: every private call is a POST whose parameters travel in a header.
 *
 * The request path, a nonce and the call's own fields are JSON-encoded, then
 * base64, and that base64 string is both the X-GEMINI-PAYLOAD header and the
 * thing signed (hex HMAC-SHA384, with the secret used as plain text). The body
 * stays empty, which is what Gemini's own examples send.
 *
 * Key order in the JSON matters, since the signature is over the exact bytes:
 * request, nonce, then the call's fields, the order ccxt builds it in.
 * Cache-Control is left off on purpose. Gemini's CORS answer names only its
 * own three headers and Content-Type, so one more header fails the preflight.
 */
export async function signGemini(
  cred: SigningKey,
  url: URL,
  params: Record<string, unknown>,
  nonce: string,
): Promise<SignedRequest> {
  const payload = btoa(JSON.stringify({ request: url.pathname, nonce, ...params }));
  return {
    method: 'POST',
    url: url.toString(),
    headers: {
      'Content-Type': 'text/plain',
      'X-GEMINI-APIKEY': cred.keyId,
      'X-GEMINI-PAYLOAD': payload,
      'X-GEMINI-SIGNATURE': await hmacHex(cred.key, payload),
    },
  };
}

/**
 * Kraken: HMAC-SHA512 over path || SHA-256(nonce || body), base64 encoded.
 *
 * The nonce is a monotonic counter Kraken enforces per key, so a replayed
 * request is rejected as stale by the exchange itself.
 */
export async function signKraken(
  cred: SigningKey,
  url: URL,
  params: Record<string, string> = {},
): Promise<SignedRequest> {
  const nonce = String(Date.now() * 1000);
  const form = new URLSearchParams({ nonce, ...params });
  const body = form.toString();

  const inner = new Uint8Array(await crypto.subtle.digest('SHA-256', enc.encode(nonce + body)));
  const message = new Uint8Array(enc.encode(url.pathname).length + inner.length);
  message.set(enc.encode(url.pathname), 0);
  message.set(inner, enc.encode(url.pathname).length);

  const sig = new Uint8Array(await crypto.subtle.sign('HMAC', cred.key, message));
  let bin = '';
  for (const b of sig) bin += String.fromCharCode(b);

  return {
    method: 'POST',
    url: url.toString(),
    headers: {
      'API-Key': cred.keyId,
      'API-Sign': btoa(bin),
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body,
  };
}