Fix: Strip query params from path before signing

This commit is contained in:
2026-03-16 12:12:44 -07:00
parent 4b403e4aba
commit 00e613e27a

View File

@@ -5,18 +5,13 @@ const KALSHI_API_BASE = (process.env.KALSHI_API_BASE || DEFAULT_KALSHI_API_BASE)
function normalizePrivateKey(value) { function normalizePrivateKey(value) {
if (!value) return ''; if (!value) return '';
let key = String(value).trim(); let key = String(value).trim();
// Strip accidental wrapping quotes from env UIs
if ( if (
(key.startsWith('"') && key.endsWith('"')) || (key.startsWith('"') && key.endsWith('"')) ||
(key.startsWith("'") && key.endsWith("'")) (key.startsWith("'") && key.endsWith("'"))
) { ) {
key = key.slice(1, -1); key = key.slice(1, -1);
} }
// Normalize line breaks from various env formats
return key return key
.replace(/\\r\\n/g, '\n') .replace(/\\r\\n/g, '\n')
.replace(/\r\n/g, '\n') .replace(/\r\n/g, '\n')
@@ -36,10 +31,17 @@ export function signRequest(method, path, timestampMs = Date.now()) {
throw new Error('Missing KALSHI_API_KEY_ID or KALSHI_RSA_PRIVATE_KEY'); throw new Error('Missing KALSHI_API_KEY_ID or KALSHI_RSA_PRIVATE_KEY');
} }
const ts = String(timestampMs); // Strip query parameters before signing per Kalshi docs
const message = `${ts}${method.toUpperCase()}${path}`; const pathWithoutQuery = path.split('?')[0];
const signature = crypto.sign('sha256', Buffer.from(message), { const ts = String(timestampMs);
const message = `${ts}${method.toUpperCase()}${pathWithoutQuery}`;
const sign = crypto.createSign('RSA-SHA256');
sign.update(message);
sign.end();
const signature = sign.sign({
key: privateKeyPem, key: privateKeyPem,
padding: crypto.constants.RSA_PKCS1_PSS_PADDING, padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST