diff --git a/packages/core/src/plugin-catalog.ts b/packages/core/src/plugin-catalog.ts index 09cc49b..30a3c63 100644 --- a/packages/core/src/plugin-catalog.ts +++ b/packages/core/src/plugin-catalog.ts @@ -22,9 +22,9 @@ const V = '0.3.10'; const PLUGIN_CONFIG_SCHEMAS = Object.fromEntries( Object.entries({ coinbase: { - strings: [{ key: 'COINBASE_API_KEY_NAME', label: 'API key ID', hint: 'The key ID Coinbase shows (or a legacy organizations/.../apiKeys/... name)' }], + strings: [{ key: 'COINBASE_API_KEY_NAME', label: 'API key name (optional if you paste the key file below)', hint: 'organizations/.../apiKeys/... (the "name" in the downloaded key file)' }], secrets: [ - { key: 'COINBASE_API_PRIVATE_KEY', label: 'API secret', multiline: true, hint: 'The Secret Coinbase shows (Ed25519), or a legacy EC private key in PEM form' }, + { key: 'COINBASE_API_PRIVATE_KEY', label: 'Key file or private key', multiline: true, hint: 'Paste the whole downloaded key JSON file, or just its -----BEGIN EC PRIVATE KEY----- block. Create the key with signature algorithm ECDSA: Coinbase Advanced Trade rejects Ed25519.' }, { key: 'COINBASE_API_PRIVATE_KEY_B', label: 'EC private key B (PEM, optional)', multiline: true, hint: 'Second account key' }, { key: 'COINBASE_EC_KEY_B', label: 'EC key B legacy (PEM, optional)', multiline: true, hint: 'Legacy secondary key' }, ], diff --git a/packages/source-crypto-arb/src/feeds/coinbase-pem.test.ts b/packages/source-crypto-arb/src/feeds/coinbase-pem.test.ts index 441d85d..1c536b2 100644 --- a/packages/source-crypto-arb/src/feeds/coinbase-pem.test.ts +++ b/packages/source-crypto-arb/src/feeds/coinbase-pem.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it } from 'vitest'; import { createPublicKey, generateKeyPairSync, verify } from 'node:crypto'; -import { getCoinbasePem, getCoinbaseSigner, parseEd25519Secret } from './coinbase-pem.js'; +import { getCoinbaseKeyName, getCoinbasePem, getCoinbaseSigner, parseCoinbaseKeyFile, parseEd25519Secret } from './coinbase-pem.js'; const saved = process.env.COINBASE_API_PRIVATE_KEY; afterEach(() => { @@ -42,4 +42,45 @@ describe('coinbase signer', () => { expect(sig.length).toBe(64); expect(verify('SHA256', Buffer.from('header.payload'), { key: createPublicKey(privateKey), dsaEncoding: 'ieee-p1363' }, sig)).toBe(true); }); + + const NAME = 'organizations/11111111-2222-3333-4444-555555555555/apiKeys/66666666-7777-8888-9999-000000000000'; + + it('takes the whole downloaded key file: ES256 signer and the full key name', () => { + const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' }); + const pem = privateKey.export({ format: 'pem', type: 'sec1' }).toString(); + process.env.COINBASE_API_PRIVATE_KEY = JSON.stringify({ name: NAME, privateKey: pem }); + delete process.env.COINBASE_API_KEY_NAME; + expect(getCoinbaseKeyName()).toBe(NAME); + const signer = getCoinbaseSigner(); + expect(signer?.alg).toBe('ES256'); + const sig = signer!.sign('h.p'); + expect(verify('SHA256', Buffer.from('h.p'), { key: createPublicKey(privateKey), dsaEncoding: 'ieee-p1363' }, sig)).toBe(true); + }); + + it('prefers the key file full name over a bare key id typed in the name field', () => { + const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' }); + process.env.COINBASE_API_PRIVATE_KEY = JSON.stringify({ name: NAME, privateKey: privateKey.export({ format: 'pem', type: 'sec1' }).toString() }); + process.env.COINBASE_API_KEY_NAME = '66666666-7777-8888-9999-000000000000'; + expect(getCoinbaseKeyName()).toBe(NAME); + delete process.env.COINBASE_API_KEY_NAME; + }); + + it('keeps a PKCS#8 PEM intact, even pasted on one line', () => { + const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' }); + process.env.COINBASE_API_PRIVATE_KEY = privateKey.export({ format: 'pem', type: 'pkcs8' }).toString().replace(/\n/g, ' '); + const signer = getCoinbaseSigner(); + expect(signer?.alg).toBe('ES256'); + const sig = signer!.sign('h.p'); + expect(verify('SHA256', Buffer.from('h.p'), { key: createPublicKey(privateKey), dsaEncoding: 'ieee-p1363' }, sig)).toBe(true); + }); + + it('a key file with escaped newlines in privateKey still signs', () => { + const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' }); + const pem = privateKey.export({ format: 'pem', type: 'sec1' }).toString(); + // JSON.stringify writes \n escapes, exactly like the downloaded file. + const file = `{\n "name": "${NAME}",\n "privateKey": ${JSON.stringify(pem)}\n}\n`; + expect(parseCoinbaseKeyFile(file)?.name).toBe(NAME); + process.env.COINBASE_API_PRIVATE_KEY = file; + expect(getCoinbaseSigner()?.alg).toBe('ES256'); + }); }); diff --git a/packages/source-crypto-arb/src/feeds/coinbase-pem.ts b/packages/source-crypto-arb/src/feeds/coinbase-pem.ts index e224373..bb14264 100644 --- a/packages/source-crypto-arb/src/feeds/coinbase-pem.ts +++ b/packages/source-crypto-arb/src/feeds/coinbase-pem.ts @@ -4,12 +4,54 @@ * Supports: * - COINBASE_EC_KEY_B64: base64 of the raw EC key body * - COINBASE_API_PRIVATE_KEY_B64: base64 of the full PEM - * - COINBASE_API_PRIVATE_KEY: raw PEM string, or a CDP Ed25519 secret - * (the base64 "Secret" Coinbase shows next to the key ID; 64 bytes: - * 32-byte seed then 32-byte public key) + * - COINBASE_API_PRIVATE_KEY: the whole downloaded key file (JSON with + * "name"/"id" and "privateKey"), a raw PEM (SEC1 "EC PRIVATE KEY" or PKCS#8 + * "PRIVATE KEY"), or a CDP Ed25519 secret (base64, 64 bytes: seed then public key) + * + * Coinbase App / Advanced Trade (api.coinbase.com/api/v3/brokerage) accepts + * ECDSA (ES256) keys only: "Ed25519 (EdDSA) keys are NOT supported. You must use + * ES256" (docs.cdp.coinbase.com/coinbase-app/authentication-authorization/api-key-authentication). + * kid and sub are the full "organizations/{org}/apiKeys/{key}" name. */ import { createPrivateKey, createPublicKey, createSign, sign as edSign, type KeyObject } from 'node:crypto'; +interface CoinbaseKeyFile { name?: string; id?: string; privateKey?: string } + +/** The downloaded key file pasted whole (JSON), or null. */ +export function parseCoinbaseKeyFile(raw: string | undefined | null): CoinbaseKeyFile | null { + const v = (raw ?? '').trim(); + if (!v.startsWith('{')) return null; + try { + const j = JSON.parse(v) as Record; + const str = (k: string) => (typeof j[k] === 'string' ? (j[k] as string).trim() : undefined); + const privateKey = str('privateKey') ?? str('private_key') ?? str('secret'); + if (!privateKey) return null; + return { name: str('name'), id: str('id'), privateKey }; + } catch { + return null; + } +} + +/** The private key material, unwrapped from a pasted key file when needed. */ +function rawPrivateKey(): string | undefined { + const raw = process.env.COINBASE_API_PRIVATE_KEY; + return parseCoinbaseKeyFile(raw)?.privateKey ?? raw; +} + +const FULL_NAME = /^organizations\/[^/]+\/apiKeys\/[^/]+$/; + +/** + * The key name for kid/sub. A full organizations/.../apiKeys/... name wins + * (from the field or from a pasted key file); otherwise whatever was entered. + */ +export function getCoinbaseKeyName(): string | null { + const entered = (process.env.COINBASE_API_KEY_NAME ?? '').trim(); + const file = parseCoinbaseKeyFile(process.env.COINBASE_API_PRIVATE_KEY); + if (FULL_NAME.test(entered)) return entered; + if (file?.name && FULL_NAME.test(file.name)) return file.name; + return entered || file?.name || file?.id || null; +} + /** PKCS#8 DER prefix for an Ed25519 private key; the 32-byte seed follows. */ const ED25519_PKCS8_PREFIX = Buffer.from('302e020100300506032b657004220420', 'hex'); @@ -39,7 +81,7 @@ export interface CoinbaseSigner { /** The signer for whichever Coinbase key is configured, or null if none. */ export function getCoinbaseSigner(): CoinbaseSigner | null { - const ed = parseEd25519Secret(process.env.COINBASE_API_PRIVATE_KEY); + const ed = parseEd25519Secret(rawPrivateKey()); if (ed) return { alg: 'EdDSA', sign: (input) => edSign(null, Buffer.from(input), ed) }; const pem = getCoinbasePem(); if (!pem) return null; @@ -67,15 +109,17 @@ export function getCoinbasePem(): string | null { return Buffer.from(cleaned, 'base64').toString('utf8'); } - const rawPem = process.env.COINBASE_API_PRIVATE_KEY; + const rawPem = rawPrivateKey(); if (!rawPem) return null; // An Ed25519 secret is not a PEM; wrapping it in EC headers would make garbage. if (parseEd25519Secret(rawPem)) return null; const normalized = rawPem.replace(/\\n/g, '\n'); + // Keep the key's own type: SEC1 "EC PRIVATE KEY" or PKCS#8 "PRIVATE KEY". + const label = /-----BEGIN PRIVATE KEY-----/.test(normalized) ? 'PRIVATE KEY' : 'EC PRIVATE KEY'; const body = normalized - .replace(/-----(BEGIN|END) EC PRIVATE KEY-----/g, '') + .replace(/-----(BEGIN|END) (EC )?PRIVATE KEY-----/g, '') .replace(/\s+/g, ''); const lines = body.match(/.{1,64}/g) ?? []; - return `-----BEGIN EC PRIVATE KEY-----\n${lines.join('\n')}\n-----END EC PRIVATE KEY-----\n`; + return `-----BEGIN ${label}-----\n${lines.join('\n')}\n-----END ${label}-----\n`; } diff --git a/packages/source-crypto-arb/src/feeds/coinbase-private.ts b/packages/source-crypto-arb/src/feeds/coinbase-private.ts index b2ecdfe..df47c71 100644 --- a/packages/source-crypto-arb/src/feeds/coinbase-private.ts +++ b/packages/source-crypto-arb/src/feeds/coinbase-private.ts @@ -17,13 +17,13 @@ const PRODUCT_CACHE_TTL_MS = 5 * 60_000; export const MAX_POSITION_USD = 100; export const COINBASE_TAKER_FEE = 0.006; // 0.6% taker (Advanced Trade) -import { getCoinbasePem, getCoinbaseSigner } from './coinbase-pem.js'; +import { getCoinbasePem, getCoinbaseSigner, getCoinbaseKeyName } from './coinbase-pem.js'; let productFetchedAt = 0; let tradableProducts = new Set(); let productMetaById = new Map(); export function getCoinbaseAuthDebug(): { hasKeyName: boolean; keyNameLooksValid: boolean; hasPem: boolean } { - const keyName = process.env.COINBASE_API_KEY_NAME ?? ''; + const keyName = getCoinbaseKeyName() ?? ''; const pem = getCoinbasePem(); return { hasKeyName: keyName.length > 0, @@ -35,7 +35,7 @@ export function getCoinbaseAuthDebug(): { hasKeyName: boolean; keyNameLooksValid } function getKeys() { - const keyName = process.env.COINBASE_API_KEY_NAME; + const keyName = getCoinbaseKeyName(); const signer = getCoinbaseSigner(); if (!keyName || !signer) throw new Error('COINBASE_API_KEY_NAME / COINBASE_API_PRIVATE_KEY missing from env'); return { keyName, signer }; diff --git a/packages/source-crypto-arb/src/feeds/coinbase.ts b/packages/source-crypto-arb/src/feeds/coinbase.ts index cadbbd2..1bd6906 100644 --- a/packages/source-crypto-arb/src/feeds/coinbase.ts +++ b/packages/source-crypto-arb/src/feeds/coinbase.ts @@ -1,7 +1,7 @@ import type { PriceFeed, MarketSnapshot, OrderBook } from '@b1dz/core'; import { randomBytes } from 'node:crypto'; import { getSnapshot } from './ws-price-cache.js'; -import { getCoinbaseSigner } from './coinbase-pem.js'; +import { getCoinbaseSigner, getCoinbaseKeyName } from './coinbase-pem.js'; const BASE = 'https://api.coinbase.com'; @@ -10,7 +10,7 @@ function base64url(buf: Buffer): string { } function buildJwt(method: string, path: string): string | null { - const keyName = process.env.COINBASE_API_KEY_NAME; + const keyName = getCoinbaseKeyName(); const signer = getCoinbaseSigner(); if (!keyName || !signer) return null; diff --git a/packages/source-crypto-arb/src/pair-discovery.ts b/packages/source-crypto-arb/src/pair-discovery.ts index 6f846df..5a6a2f7 100644 --- a/packages/source-crypto-arb/src/pair-discovery.ts +++ b/packages/source-crypto-arb/src/pair-discovery.ts @@ -25,7 +25,7 @@ import { type DiscoveredPair, type FetchLike, } from '@b1dz/source-nichedb'; -import { getCoinbaseSigner } from './feeds/coinbase-pem.js'; +import { getCoinbaseSigner, getCoinbaseKeyName } from './feeds/coinbase-pem.js'; import { fetchJson } from './feeds/http.js'; /** Per-exchange 24h USD volume floor. A pair listed on a venue with volume @@ -90,7 +90,7 @@ function base64url(buf: Buffer): string { } async function getCoinbaseVolumes(): Promise> { - const keyName = process.env.COINBASE_API_KEY_NAME; + const keyName = getCoinbaseKeyName(); const signer = getCoinbaseSigner(); if (!keyName || !signer) return new Map(); const path = '/api/v3/brokerage/products';