Fix: Harden RSA key env parsing

This commit is contained in:
2026-03-15 14:55:02 -07:00
parent 96f1f9359e
commit 1c57c60770

View File

@@ -3,13 +3,34 @@ import crypto from 'crypto';
const DEFAULT_KALSHI_API_BASE = 'https://api.elections.kalshi.com';
const KALSHI_API_BASE = (process.env.KALSHI_API_BASE || DEFAULT_KALSHI_API_BASE).trim().replace(/\/+$/, '');
function normalizePrivateKey(value) {
if (!value) return '';
let key = String(value).trim();
// Strip accidental wrapping quotes from env UIs
if (
(key.startsWith('"') && key.endsWith('"')) ||
(key.startsWith("'") && key.endsWith("'"))
) {
key = key.slice(1, -1);
}
// Normalize line breaks from various env formats
return key
.replace(/\\r\\n/g, '\n')
.replace(/\r\n/g, '\n')
.replace(/\\n/g, '\n')
.trim();
}
/**
* Signs a Kalshi API request using RSA-PSS with SHA-256.
* Returns headers needed for authenticated requests.
*/
export function signRequest(method, path, timestampMs = Date.now()) {
const keyId = process.env.KALSHI_API_KEY_ID;
const privateKeyPem = process.env.KALSHI_RSA_PRIVATE_KEY?.replace(/\\n/g, '\n');
const keyId = process.env.KALSHI_API_KEY_ID?.trim();
const privateKeyPem = normalizePrivateKey(process.env.KALSHI_RSA_PRIVATE_KEY);
if (!keyId || !privateKeyPem) {
throw new Error('Missing KALSHI_API_KEY_ID or KALSHI_RSA_PRIVATE_KEY');