import * as crypto from 'crypto'; /** * Kalshi authentication handler for API requests. * * Accepts the private key of either supported API key type. RSA keys sign * requests with RSA-PSS over SHA-256; Ed25519 keys sign the same pre-sign * text with Ed25519. The key type is detected from the PEM. */ export class KalshiAuth { private apiKey: string; private privateKey: crypto.KeyObject; constructor(apiKey: string, privateKeyPem: string) { this.apiKey = apiKey; this.privateKey = crypto.createPrivateKey(privateKeyPem); const keyType = this.privateKey.asymmetricKeyType; if (keyType !== 'rsa' && keyType !== 'ed25519') { throw new Error(`Unsupported private key type "${keyType}": Kalshi API keys are RSA or Ed25519`); } } private signText(text: string): string { if (this.privateKey.asymmetricKeyType === 'ed25519') { return crypto.sign(null, Buffer.from(text, 'utf8'), this.privateKey).toString('base64'); } const sign = crypto.createSign('RSA-SHA256'); sign.update(text); sign.end(); const signature = sign.sign({ key: this.privateKey, padding: crypto.constants.RSA_PKCS1_PSS_PADDING, saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST, }); return signature.toString('base64'); } public generateAuthHeaders(method: string, path: string): Record { const currentTimeMilliseconds = Date.now(); const timestampStr = currentTimeMilliseconds.toString(); const msgString = timestampStr + method + path; const sig = this.signText(msgString); return { 'KALSHI-ACCESS-KEY': this.apiKey, 'KALSHI-ACCESS-SIGNATURE': sig, 'KALSHI-ACCESS-TIMESTAMP': timestampStr }; } }