Key import
Imports each exchange’s key format into the browser’s crypto, non-extractable. Unedited, from build 579b29d3.
// Key material import for the exchange adapters.
//
// This file exists because the exchanges hand out private keys in formats
// Web Crypto will not import directly, and each one is wrong in a different
// way:
//
// - Coinbase ECDSA keys arrive as SEC1 PEM ("BEGIN EC PRIVATE KEY").
// Web Crypto's importKey only accepts "pkcs8" / "jwk" / "raw" / "spki",
// never SEC1, so a SEC1 key has to be taken apart and re-presented.
// We parse it into a JWK rather than synthesising PKCS8 DER: P-256 keys
// have a fixed shape, the scalar and the public point are both already
// in the SEC1 body, and a JWK needs no length arithmetic to get right.
//
// - Coinbase Ed25519 keys arrive either as PKCS8 PEM or as a bare base64
// 64-byte blob (32-byte seed followed by the 32-byte public key). The
// bare form needs the standard PKCS8 prefix glued on.
//
// Everything here runs in the browser. Every key is imported with
// extractable: false, so once a paste has been through this module the raw
// secret exists only as a CryptoKey handle: the page can sign with it and
// cannot read it back, and neither can anything that later injects script
// into the page. That is the whole point, so do not add an extractable
// import path here for debugging convenience.
/**
* Byte arrays backed by a plain ArrayBuffer.
*
* TypeScript 5.7 made Uint8Array generic over its buffer, and a bare
* `Uint8Array` widens to `ArrayBufferLike`, which includes SharedArrayBuffer
* and which Web Crypto's `BufferSource` will not accept. Naming the concrete
* form once beats casting at every subtle.* call site.
*/
export type Bytes = Uint8Array<ArrayBuffer>;
export type JwtAlg = 'ES256' | 'EdDSA';
export interface ImportedSigningKey {
key: CryptoKey;
alg: JwtAlg;
}
const enc = new TextEncoder();
export function b64uEncode(bytes: Uint8Array): string {
let s = '';
for (const b of bytes) s += String.fromCharCode(b);
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
export function b64uEncodeString(s: string): string {
return b64uEncode(enc.encode(s));
}
export function b64Decode(s: string): Bytes {
const norm = s.replace(/-/g, '+').replace(/_/g, '/').replace(/\s+/g, '');
const bin = atob(norm.padEnd(Math.ceil(norm.length / 4) * 4, '='));
const out = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
return out;
}
export function toHex(bytes: Uint8Array): string {
let s = '';
for (const b of bytes) s += b.toString(16).padStart(2, '0');
return s;
}
/** Strip the PEM armour and return the DER bytes. */
function pemToDer(pem: string): Bytes {
const body = pem
.replace(/-----BEGIN [^-]+-----/g, '')
.replace(/-----END [^-]+-----/g, '')
.replace(/\s+/g, '');
return b64Decode(body);
}
// --- minimal DER reader -----------------------------------------------------
// Only enough to walk a SEC1 ECPrivateKey. Not a general ASN.1 parser, and
// deliberately so: a general one is a much bigger attack surface than this
// needs, and the one structure we care about is fully specified by RFC 5915.
interface DerTlv {
tag: number;
body: Uint8Array;
next: number;
}
function readTlv(buf: Uint8Array, offset: number): DerTlv {
const tag = buf[offset];
let i = offset + 1;
let len = buf[i++];
if (len & 0x80) {
const n = len & 0x7f;
if (n === 0 || n > 4) throw new Error('der: unsupported length');
len = 0;
for (let k = 0; k < n; k++) len = (len << 8) | buf[i++];
}
if (i + len > buf.length) throw new Error('der: truncated');
return { tag, body: buf.subarray(i, i + len), next: i + len };
}
/**
* SEC1 ECPrivateKey (RFC 5915):
* SEQUENCE {
* version INTEGER (1),
* privateKey OCTET STRING, -- the 32-byte scalar d, for P-256
* parameters [0] ECParameters OPTIONAL,
* publicKey [1] BIT STRING OPTIONAL -- 0x00 || 0x04 || X || Y
* }
*/
function sec1ToJwk(der: Uint8Array): JsonWebKey {
const seq = readTlv(der, 0);
if (seq.tag !== 0x30) throw new Error('sec1: expected SEQUENCE');
const body = seq.body;
const version = readTlv(body, 0);
if (version.tag !== 0x02) throw new Error('sec1: expected version INTEGER');
const priv = readTlv(body, version.next);
if (priv.tag !== 0x04) throw new Error('sec1: expected privateKey OCTET STRING');
// Left-pad, because DER strips leading zero bytes from the scalar.
const d = new Uint8Array(32);
d.set(priv.body.subarray(Math.max(0, priv.body.length - 32)), Math.max(0, 32 - priv.body.length));
let cursor = priv.next;
let point: Uint8Array | undefined;
while (cursor < body.length) {
const tlv = readTlv(body, cursor);
// [1] IMPLICIT BIT STRING, context-specific constructed tag 0xa1.
if (tlv.tag === 0xa1) {
const bits = readTlv(tlv.body, 0);
// First byte of a BIT STRING is the unused-bit count, always 0 here.
point = bits.body.subarray(1);
break;
}
cursor = tlv.next;
}
if (!point || point[0] !== 0x04 || point.length !== 65) {
throw new Error('sec1: missing or compressed public point (need uncompressed 04||X||Y)');
}
return {
kty: 'EC',
crv: 'P-256',
d: b64uEncode(d),
x: b64uEncode(point.subarray(1, 33)),
y: b64uEncode(point.subarray(33, 65)),
ext: true,
};
}
// PKCS8 prefix for an Ed25519 private key: SEQUENCE { INTEGER 0,
// AlgorithmIdentifier { OID 1.3.101.112 }, OCTET STRING { OCTET STRING seed } }.
// Fixed for every Ed25519 key, so the 32-byte seed just gets appended.
const ED25519_PKCS8_PREFIX = new Uint8Array([
0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20,
]);
function ed25519SeedToPkcs8(seed: Uint8Array): Bytes {
const out = new Uint8Array(ED25519_PKCS8_PREFIX.length + 32);
out.set(ED25519_PKCS8_PREFIX, 0);
out.set(seed.subarray(0, 32), ED25519_PKCS8_PREFIX.length);
return out;
}
/**
* Import a Coinbase CDP private key in any of the shapes Coinbase issues.
*
* Returns the CryptoKey plus the JOSE algorithm name the JWT header must
* claim, because Coinbase requires the header to match the key type and the
* two key families are not interchangeable.
*/
export async function importCoinbaseKey(privateKey: string): Promise<ImportedSigningKey> {
const pem = privateKey.replace(/\\n/g, '\n').trim();
if (pem.includes('BEGIN EC PRIVATE KEY')) {
const jwk = sec1ToJwk(pemToDer(pem));
const key = await crypto.subtle.importKey(
'jwk',
jwk,
{ name: 'ECDSA', namedCurve: 'P-256' },
false,
['sign'],
);
return { key, alg: 'ES256' };
}
if (pem.includes('BEGIN PRIVATE KEY')) {
const der = pemToDer(pem);
// A PKCS8 body can hold either family, so read the algorithm OID rather
// than guessing from a byte offset. Ed25519 is 1.3.101.112, which DER
// encodes as 2b 65 70 and which sits at a fixed position because the
// Ed25519 AlgorithmIdentifier has no parameters and so never varies in
// length. An earlier version tested der[13] === 0x04, which is the
// OCTET STRING tag one byte late: der[13] is the 0x22 length byte, so
// the test never matched and every Ed25519 PEM fell through to the
// ECDSA import and threw "Invalid key type".
const isEd25519 = der.length === 48 && der[9] === 0x2b && der[10] === 0x65 && der[11] === 0x70;
if (isEd25519) {
const key = await crypto.subtle.importKey('pkcs8', der, { name: 'Ed25519' }, false, ['sign']);
return { key, alg: 'EdDSA' };
}
const key = await crypto.subtle.importKey(
'pkcs8',
der,
{ name: 'ECDSA', namedCurve: 'P-256' },
false,
['sign'],
);
return { key, alg: 'ES256' };
}
// Bare base64. Coinbase's Ed25519 keys come as 64 bytes: seed || public key.
const raw = b64Decode(pem);
if (raw.length === 64 || raw.length === 32) {
const key = await crypto.subtle.importKey(
'pkcs8',
ed25519SeedToPkcs8(raw),
{ name: 'Ed25519' },
false,
['sign'],
);
return { key, alg: 'EdDSA' };
}
throw new Error(`unrecognised Coinbase private key format (${raw.length} raw bytes)`);
}
/** Import an HMAC secret. Kraken's is base64; Binance's, OKX's and Gemini's are plain text. */
export async function importHmacKey(
secret: string,
hash: 'SHA-256' | 'SHA-384' | 'SHA-512',
decodeBase64 = false,
): Promise<CryptoKey> {
const raw = decodeBase64 ? b64Decode(secret) : enc.encode(secret);
return crypto.subtle.importKey('raw', raw, { name: 'HMAC', hash }, false, ['sign']);
}