From 84022996f6e68ba54d39bbc459b91ed07465c86c Mon Sep 17 00:00:00 2001 From: odds-api-io Date: Thu, 26 Nov 2026 09:13:18 +0100 Subject: [PATCH 1/5] fix: keep the API key out of error messages and causes (1.6.3) Network errors from fetch implementations that quote the request URL, error bodies that echo it, and WebSocket construction errors put the apiKey query parameter into the SDK error. Mask the key and key-like query parameters or headers in messages, stacks and bodies, and attach the underlying error as a masked cause. --- CHANGELOG.md | 5 ++ CITATION.cff | 4 +- README.md | 2 +- package.json | 2 +- src/client.ts | 17 +++-- src/errors.ts | 14 +++-- src/redact.ts | 62 +++++++++++++++++++ src/version.ts | 2 +- src/websocket.ts | 17 +++-- test/redaction.test.mjs | 134 ++++++++++++++++++++++++++++++++++++++++ 10 files changed, 241 insertions(+), 18 deletions(-) create mode 100644 src/redact.ts create mode 100644 test/redaction.test.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 29c291f..124bfa0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## 1.6.3 (2026-11-26) + +### Security +- Errors no longer contain the API key. The key is sent as the `apiKey` query parameter. In 1.6.2 and earlier, a `fetch` implementation that quotes the request URL in its errors (such as `node-fetch`), an error body that echoes the URL, or a WebSocket that could not be created (for example an invalid `url` with `ws`) put the full URL, key included, into the SDK error message and the error passed to `error` listeners. The key, and any key-like query parameter or header, is now masked as `***` in `message`, `stack` and `body`. `NetworkError`, `TimeoutError` and `OddsWebSocketError` now carry the underlying error as `cause`, with the key masked through the whole `cause` chain. If you have shared such an error from an older version, regenerate the key in your dashboard settings at https://odds-api.io/dashboard/settings. + ## 1.6.2 (2026-11-20) ### Fixed diff --git a/CITATION.cff b/CITATION.cff index 119aba8..a4e6429 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -2,8 +2,8 @@ cff-version: 1.2.0 message: "If you use this software, please cite it using the metadata from this file." type: software title: "odds-api-io: Official Node.js SDK for Odds-API.io" -version: 1.6.2 -date-released: "2026-11-20" +version: 1.6.3 +date-released: "2026-11-26" authors: - name: "Outlier AS" email: "hello@odds-api.io" diff --git a/README.md b/README.md index 8242ce7..42408bf 100644 --- a/README.md +++ b/README.md @@ -482,5 +482,5 @@ This is the official SDK for Odds-API.io. This tool is for informational purpose If you use this package in research or a publication, please cite it. Citation metadata is in [CITATION.cff](CITATION.cff) (GitHub renders a "Cite this repository" button from it) and Zenodo metadata is in `.zenodo.json`. ``` -Outlier AS. odds-api-io: Official Node.js SDK for Odds-API.io (version 1.6.2). https://github.com/odds-api-io/odds-api-node +Outlier AS. odds-api-io: Official Node.js SDK for Odds-API.io (version 1.6.3). https://github.com/odds-api-io/odds-api-node ``` diff --git a/package.json b/package.json index dbc5509..f5f8eca 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "odds-api-io", - "version": "1.6.2", + "version": "1.6.3", "description": "Official Node.js and TypeScript SDK for the Odds-API.io sports betting odds API: real-time odds API for 500+ bookmakers, REST and WebSocket", "keywords": [ "odds api", diff --git a/src/client.ts b/src/client.ts index 16e6790..3b7acc2 100644 --- a/src/client.ts +++ b/src/client.ts @@ -68,6 +68,7 @@ import { TimeoutError, NetworkError, } from './errors.js'; +import { redactError, redactSecrets } from './redact.js'; import { VERSION } from './version.js'; const DEFAULT_BASE_URL = 'https://api.odds-api.io/v3'; @@ -208,10 +209,11 @@ export class OddsAPIClient { response = await doFetch(url.toString(), { method, headers, body, signal: controller.signal }); } catch (error: any) { clearTimeout(timeoutId); + const cause = redactError(error, [this.apiKey]); const err = error?.name === 'AbortError' - ? new TimeoutError(`Request timeout after ${this.timeout}ms`) - : new NetworkError(`Network request failed: ${error?.message ?? error}`); + ? new TimeoutError(`Request timeout after ${this.timeout}ms`, { cause }) + : new NetworkError(this.redact(`Network request failed: ${error?.message ?? error}`), { cause }); if (attempt < retries) { await sleep(this.backoff(attempt)); continue; @@ -237,14 +239,19 @@ export class OddsAPIClient { throw error; } catch (error: any) { if (error instanceof OddsAPIError) throw error; - if (error?.name === 'AbortError') throw new TimeoutError(`Request timeout after ${this.timeout}ms`); - throw new NetworkError(`Failed to read response: ${error?.message ?? error}`); + const cause = redactError(error, [this.apiKey]); + if (error?.name === 'AbortError') throw new TimeoutError(`Request timeout after ${this.timeout}ms`, { cause }); + throw new NetworkError(this.redact(`Failed to read response: ${error?.message ?? error}`), { cause }); } finally { clearTimeout(timeoutId); } } } + private redact(text: string): string { + return redactSecrets(text, [this.apiKey]); + } + private backoff(attempt: number): number { const base = Math.min(this.maxRetryDelay, 500 * 2 ** attempt); return Math.round(base * (0.75 + Math.random() * 0.25)); @@ -268,7 +275,7 @@ export class OddsAPIClient { const status = response.status; let body = ''; try { - body = await response.text(); + body = this.redact(await response.text()); } catch { body = ''; } diff --git a/src/errors.ts b/src/errors.ts index 2d180e9..19d86ae 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -5,6 +5,8 @@ export interface OddsAPIErrorDetails { /** The raw response body. */ body?: string; rateLimit?: RateLimitInfo; + /** The underlying error, with the API key masked. */ + cause?: unknown; } /** Base class for every error the SDK throws. `message` is the server's own error text when there is one. */ @@ -12,6 +14,7 @@ export class OddsAPIError extends Error { readonly status?: number; readonly body?: string; readonly rateLimit?: RateLimitInfo; + declare readonly cause?: unknown; constructor(message: string, details: OddsAPIErrorDetails = {}) { super(message); @@ -19,6 +22,9 @@ export class OddsAPIError extends Error { this.status = details.status; this.body = details.body; this.rateLimit = details.rateLimit; + if (details.cause !== undefined) { + Object.defineProperty(this, 'cause', { value: details.cause, writable: true, configurable: true }); + } Object.setPrototypeOf(this, new.target.prototype); } } @@ -97,16 +103,16 @@ export class ServerError extends OddsAPIError { /** The request took longer than the configured timeout. */ export class TimeoutError extends OddsAPIError { - constructor(message = 'Request timeout') { - super(message); + constructor(message = 'Request timeout', details: OddsAPIErrorDetails = {}) { + super(message, details); this.name = 'TimeoutError'; } } /** The request never reached the server or the connection failed. */ export class NetworkError extends OddsAPIError { - constructor(message: string) { - super(message); + constructor(message: string, details: OddsAPIErrorDetails = {}) { + super(message, details); this.name = 'NetworkError'; } } diff --git a/src/redact.ts b/src/redact.ts new file mode 100644 index 0000000..55d7e01 --- /dev/null +++ b/src/redact.ts @@ -0,0 +1,62 @@ +/** + * Keeps the API key out of error messages, stacks and `cause` chains. The key + * travels as the `apiKey` query parameter, and some fetch and WebSocket + * implementations put the request URL into their error messages. + */ + +const REDACTED = '***'; +const SECRET_PARAM = + /(^|[^A-Za-z0-9_])(api[_-]?key|access[_-]?token|auth[_-]?token|token|secret|password|key)(=|%3D)[^&#\s'"<>()[\],;]+/gi; +const SECRET_HEADER = /((?:x-)?api[_-]?key|authorization)(['"]?\s*:\s*['"]?)(?:bearer\s+|basic\s+)?[^'"\s,}&]+/gi; +const MAX_DEPTH = 8; + +type Secrets = readonly (string | undefined)[]; + +function variants(secrets: Secrets): string[] { + const found = new Set(); + for (const secret of secrets) { + if (!secret) continue; + found.add(secret); + found.add(encodeURIComponent(secret)); + found.add(encodeURIComponent(secret).replace(/%20/g, '+')); + } + return [...found].sort((a, b) => b.length - a.length); +} + +/** `text` with the given secrets and any key-like query parameter or header masked. */ +export function redactSecrets(text: string, secrets: Secrets = []): string { + let out = text; + for (const secret of variants(secrets)) out = out.split(secret).join(REDACTED); + out = out.replace(SECRET_PARAM, (_m, pre: string, name: string, eq: string) => `${pre}${name}${eq}${REDACTED}`); + return out.replace(SECRET_HEADER, (_m, name: string, sep: string) => `${name}${sep}${REDACTED}`); +} + +function redactValue(value: unknown, secrets: Secrets, depth: number): unknown { + if (typeof value === 'string') return redactSecrets(value, secrets); + if (value instanceof Error) return redactError(value, secrets, depth + 1); + if (Array.isArray(value)) return value.map((item) => redactValue(item, secrets, depth + 1)); + if (value instanceof URL) return redactSecrets(value.toString(), secrets); + return value; +} + +/** + * A copy of `error` (same prototype, so `instanceof` still works) whose message, + * stack, string properties and whole `cause` chain have the secrets masked. + */ +export function redactError(error: T, secrets: Secrets, depth = 0): T { + if (typeof error === 'string') return redactSecrets(error, secrets) as T; + if (!(error instanceof Error) || depth > MAX_DEPTH) return error; + const copy = Object.create(Object.getPrototypeOf(error)) as Error; + for (const key of Object.getOwnPropertyNames(error)) { + const descriptor = Object.getOwnPropertyDescriptor(error, key); + if (!descriptor) continue; + if ('value' in descriptor) descriptor.value = redactValue(descriptor.value, secrets, depth); + else if (descriptor.get) { + const value = redactValue((error as any)[key], secrets, depth); + Object.defineProperty(copy, key, { value, enumerable: descriptor.enumerable, configurable: true, writable: true }); + continue; + } + Object.defineProperty(copy, key, descriptor); + } + return copy as T; +} diff --git a/src/version.ts b/src/version.ts index e946876..0a3fc64 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const VERSION = '1.6.2'; +export const VERSION = '1.6.3'; diff --git a/src/websocket.ts b/src/websocket.ts index ed46971..db92359 100644 --- a/src/websocket.ts +++ b/src/websocket.ts @@ -1,5 +1,6 @@ import type { Clock, CommaList, EventStatus, Market, MarketName, Score } from './types.js'; import { OddsAPIError } from './errors.js'; +import { redactError, redactSecrets } from './redact.js'; const DEFAULT_WS_URL = 'wss://api.odds-api.io/v3/ws'; const MAX_TIMER_DELAY = 2 ** 31 - 1; @@ -162,8 +163,8 @@ export class OddsWebSocketError extends OddsAPIError { /** WebSocket close code, or the HTTP status of a refused handshake. */ readonly code?: number; - constructor(message: string, code?: number) { - super(message, { status: code !== undefined && code < 1000 ? code : undefined }); + constructor(message: string, code?: number, cause?: unknown) { + super(message, { status: code !== undefined && code < 1000 ? code : undefined, cause }); this.name = 'OddsWebSocketError'; this.code = code; } @@ -380,7 +381,7 @@ export class OddsWebSocket { const text: string = event?.message ?? event?.error?.message ?? ''; const status = /Unexpected server response: (\d{3})/.exec(text); if (status) this.handshakeError = this.handshakeFailure(Number(status[1])); - else this.emit('error', new OddsWebSocketError(text || 'WebSocket error')); + else this.emit('error', new OddsWebSocketError(redactSecrets(text, [this.options.apiKey]) || 'WebSocket error')); }; socket.onclose = (event) => { @@ -490,7 +491,8 @@ export class OddsWebSocket { return Math.min(MAX_TIMER_DELAY, jitter(Math.max(backoff, this.retryAfterMs ?? 0))); } - private fail(error: Error): void { + private fail(raw: Error): void { + const error = this.safeError(raw); this.stopped = true; if (this.reconnectTimer) clearTimeout(this.reconnectTimer); this.rejectOpen?.(error); @@ -500,6 +502,13 @@ export class OddsWebSocket { this.finish(error); } + private safeError(error: Error): Error { + const secrets = [this.options.apiKey]; + if (error instanceof OddsAPIError) return error; + const message = redactSecrets(error?.message ?? String(error), secrets); + return new OddsWebSocketError(message, undefined, redactError(error, secrets)); + } + private finish(error?: Error): void { this.openPromise = undefined; this.ended = true; diff --git a/test/redaction.test.mjs b/test/redaction.test.mjs new file mode 100644 index 0000000..96ea609 --- /dev/null +++ b/test/redaction.test.mjs @@ -0,0 +1,134 @@ +import { test, describe } from 'node:test'; +import assert from 'node:assert/strict'; +import { createServer } from 'node:net'; +import { inspect } from 'node:util'; +import { + OddsAPIClient, + OddsAPIError, + InvalidAPIKeyError, + ServerError, + TimeoutError, + NetworkError, + OddsWebSocket, +} from 'odds-api-io'; + +const KEY = 'sk-live-7f3a9c1e5b2d4f60a8e1'; + +function assertNoKey(error) { + const texts = [String(error), error.message, error.stack, inspect(error, { depth: 20 }), error.body ?? '']; + for (let link = error.cause, depth = 0; link && depth < 10; link = link.cause, depth++) { + texts.push(String(link), link.message ?? '', link.stack ?? '', inspect(link, { depth: 20 })); + } + for (const text of texts) assert.ok(!String(text).includes(KEY), `key leaked in: ${text}`); +} + +async function closedPort() { + const server = createServer(); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const { port } = server.address(); + await new Promise((resolve) => server.close(resolve)); + return port; +} + +function client(fetch, config = {}) { + return new OddsAPIClient({ apiKey: KEY, baseUrl: 'https://example.test/v3', fetch, maxRetries: 0, ...config }); +} + +describe('API key redaction', () => { + test('a refused connection with the built-in fetch hides the key', async () => { + const port = await closedPort(); + const c = new OddsAPIClient({ apiKey: KEY, baseUrl: `http://127.0.0.1:${port}/v3`, maxRetries: 0 }); + const error = await c.getEvents({ sport: 'football' }).then( + () => assert.fail('expected a NetworkError'), + (e) => e + ); + assert.ok(error instanceof NetworkError); + assert.ok(error.cause, 'the underlying error is kept as cause'); + assertNoKey(error); + }); + + test('a fetch error that quotes the URL is masked in the message and the cause chain', async () => { + const fetch = async (url) => { + const inner = new Error(`connect ECONNREFUSED for ${url}`); + inner.code = 'ECONNREFUSED'; + const outer = new TypeError(`request to ${url} failed, reason: connect ECONNREFUSED`); + outer.cause = inner; + outer.url = url; + throw outer; + }; + const error = await client(fetch).getEvents({ sport: 'football' }).catch((e) => e); + assert.ok(error instanceof NetworkError); + assert.match(error.message, /apiKey=\*\*\*/); + assert.ok(error.cause instanceof TypeError); + assert.equal(error.cause.cause.code, 'ECONNREFUSED'); + assertNoKey(error); + }); + + test('a timeout hides the key', async () => { + const fetch = (url, init) => + new Promise((_resolve, reject) => { + init.signal.addEventListener('abort', () => { + const abort = new Error(`The operation was aborted: ${url}`); + abort.name = 'AbortError'; + reject(abort); + }); + }); + const error = await client(fetch, { timeout: 20 }).getEvents({ sport: 'football' }).catch((e) => e); + assert.ok(error instanceof TimeoutError); + assertNoKey(error); + }); + + test('an HTTP error whose body echoes the URL hides the key', async () => { + const fetch = async (url) => + new Response(JSON.stringify({ error: `Invalid API key in ${url}` }), { + status: 401, + headers: { 'content-type': 'application/json' }, + }); + const error = await client(fetch).getEvents({ sport: 'football' }).catch((e) => e); + assert.ok(error instanceof InvalidAPIKeyError); + assertNoKey(error); + }); + + test('an HTML proxy error hides the key', async () => { + const fetch = async (url) => new Response(`502 Bad Gateway ${url}`, { status: 502 }); + const error = await client(fetch).getEvents({ sport: 'football' }).catch((e) => e); + assert.ok(error instanceof ServerError); + assertNoKey(error); + }); + + test('a JSON parse error on a success response hides the key', async () => { + const fetch = async (url) => new Response(`${url}`, { status: 200 }); + const error = await client(fetch).getEvents({ sport: 'football' }).catch((e) => e); + assert.ok(error instanceof NetworkError); + assert.match(error.message, /Failed to read response/); + assertNoKey(error); + }); + + test('a WebSocket that cannot be created hides the key', async () => { + const feed = new OddsWebSocket({ apiKey: KEY, markets: ['ML'], url: 'not a websocket url', reconnect: false }); + feed.on('error', () => undefined); + const error = await feed.connect().catch((e) => e); + assert.ok(error instanceof OddsAPIError); + assertNoKey(error); + feed.close(); + }); + + test('the WebSocket error event hides the key', async () => { + class Socket { + constructor(url) { + setTimeout(() => { + this.onerror?.({ message: `getaddrinfo ENOTFOUND for ${url}` }); + this.onclose?.({ code: 1006, reason: '' }); + }, 0); + } + close() {} + } + const errors = []; + const feed = new OddsWebSocket({ apiKey: KEY, markets: ['ML'], WebSocket: Socket, reconnect: false }); + feed.on('error', (e) => errors.push(e)); + await feed.connect().catch(() => undefined); + assert.ok(errors.length > 0); + for (const error of errors) assertNoKey(error); + feed.close(); + }); +}); From f8ff970eb8ca956b636a70dcc3866215328e934d Mon Sep 17 00:00:00 2001 From: odds-api-io Date: Thu, 26 Nov 2026 09:20:57 +0100 Subject: [PATCH 2/5] fix: mask nested cause objects, cut deep chains, keep abort causes readable Copy causes as plain Error objects instead of prototype clones, so a native DOMException stays readable. Mask plain-object and array values inside causes, reduce other objects to their type name, handle cycles, and replace anything past the depth limit with a placeholder. --- CHANGELOG.md | 2 +- src/redact.ts | 108 +++++++++++++++++++++++++++++++--------- test/redaction.test.mjs | 59 +++++++++++++++++++++- 3 files changed, 143 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 124bfa0..766adae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ ## 1.6.3 (2026-11-26) ### Security -- Errors no longer contain the API key. The key is sent as the `apiKey` query parameter. In 1.6.2 and earlier, a `fetch` implementation that quotes the request URL in its errors (such as `node-fetch`), an error body that echoes the URL, or a WebSocket that could not be created (for example an invalid `url` with `ws`) put the full URL, key included, into the SDK error message and the error passed to `error` listeners. The key, and any key-like query parameter or header, is now masked as `***` in `message`, `stack` and `body`. `NetworkError`, `TimeoutError` and `OddsWebSocketError` now carry the underlying error as `cause`, with the key masked through the whole `cause` chain. If you have shared such an error from an older version, regenerate the key in your dashboard settings at https://odds-api.io/dashboard/settings. +- Errors no longer contain the API key. The key is sent as the `apiKey` query parameter. In 1.6.2 and earlier, a `fetch` implementation that quotes the request URL in its errors (such as `node-fetch`), an error body that echoes the URL, or a WebSocket that could not be created (for example an invalid `url` with `ws`) put the full URL, key included, into the SDK error message and the error passed to `error` listeners. The key, and any key-like query parameter or header, is now masked as `***` in `message`, `stack` and `body`. `NetworkError`, `TimeoutError` and `OddsWebSocketError` now carry the underlying error as `cause`: a plain `Error` copy with the same `name`, `code` and message, masked through the whole `cause` chain. If you have shared such an error from an older version, regenerate the key in your dashboard settings at https://odds-api.io/dashboard/settings. ## 1.6.2 (2026-11-20) diff --git a/src/redact.ts b/src/redact.ts index 55d7e01..40f7fd6 100644 --- a/src/redact.ts +++ b/src/redact.ts @@ -9,6 +9,7 @@ const SECRET_PARAM = /(^|[^A-Za-z0-9_])(api[_-]?key|access[_-]?token|auth[_-]?token|token|secret|password|key)(=|%3D)[^&#\s'"<>()[\],;]+/gi; const SECRET_HEADER = /((?:x-)?api[_-]?key|authorization)(['"]?\s*:\s*['"]?)(?:bearer\s+|basic\s+)?[^'"\s,}&]+/gi; const MAX_DEPTH = 8; +const TRUNCATED = '[truncated]'; type Secrets = readonly (string | undefined)[]; @@ -31,32 +32,91 @@ export function redactSecrets(text: string, secrets: Secrets = []): string { return out.replace(SECRET_HEADER, (_m, name: string, sep: string) => `${name}${sep}${REDACTED}`); } -function redactValue(value: unknown, secrets: Secrets, depth: number): unknown { - if (typeof value === 'string') return redactSecrets(value, secrets); - if (value instanceof Error) return redactError(value, secrets, depth + 1); - if (Array.isArray(value)) return value.map((item) => redactValue(item, secrets, depth + 1)); - if (value instanceof URL) return redactSecrets(value.toString(), secrets); - return value; +function read(source: object, key: string): unknown { + try { + return (source as Record)[key]; + } catch { + return undefined; + } } -/** - * A copy of `error` (same prototype, so `instanceof` still works) whose message, - * stack, string properties and whole `cause` chain have the secrets masked. - */ -export function redactError(error: T, secrets: Secrets, depth = 0): T { - if (typeof error === 'string') return redactSecrets(error, secrets) as T; - if (!(error instanceof Error) || depth > MAX_DEPTH) return error; - const copy = Object.create(Object.getPrototypeOf(error)) as Error; - for (const key of Object.getOwnPropertyNames(error)) { - const descriptor = Object.getOwnPropertyDescriptor(error, key); - if (!descriptor) continue; - if ('value' in descriptor) descriptor.value = redactValue(descriptor.value, secrets, depth); - else if (descriptor.get) { - const value = redactValue((error as any)[key], secrets, depth); - Object.defineProperty(copy, key, { value, enumerable: descriptor.enumerable, configurable: true, writable: true }); - continue; +function isPlainObject(value: object): boolean { + const proto = Object.getPrototypeOf(value); + return proto === Object.prototype || proto === null; +} + +class Redactor { + private readonly seen = new WeakMap(); + + constructor(private readonly secrets: Secrets) {} + + value(value: unknown, depth: number): unknown { + if (typeof value === 'string') return redactSecrets(value, this.secrets); + if (value === null || typeof value !== 'object') return typeof value === 'function' ? undefined : value; + if (depth > MAX_DEPTH) return TRUNCATED; + if (this.seen.has(value)) return this.seen.get(value); + if (value instanceof Error || isErrorLike(value)) return this.error(value as Error, depth); + if (Array.isArray(value)) { + const out: unknown[] = []; + this.seen.set(value, out); + for (const item of value) out.push(this.value(item, depth + 1)); + return out; + } + if (value instanceof URL) return redactSecrets(value.toString(), this.secrets); + if (!isPlainObject(value)) { + const name = (value as object).constructor?.name ?? 'Object'; + return `[${name}]`; } - Object.defineProperty(copy, key, descriptor); + const out: Record = {}; + this.seen.set(value, out); + for (const key of Object.keys(value)) out[key] = this.value(read(value, key), depth + 1); + return out; } - return copy as T; + + /** A plain `Error` copy: same name, masked message, stack and properties, masked `cause` chain. */ + error(error: Error, depth: number): Error { + const message = read(error, 'message'); + const copy = new Error(redactSecrets(typeof message === 'string' ? message : '', this.secrets)); + this.seen.set(error, copy); + const name = read(error, 'name'); + if (typeof name === 'string') copy.name = name; + const stack = read(error, 'stack'); + Object.defineProperty(copy, 'stack', { + value: typeof stack === 'string' ? redactSecrets(stack, this.secrets) : undefined, + writable: true, + configurable: true, + }); + for (const key of ['code', 'errno', 'syscall', 'hostname', 'address', 'port', 'status', 'statusCode', 'type']) { + const value = read(error, key); + if (value !== undefined && typeof value !== 'object') (copy as any)[key] = this.value(value, depth + 1); + } + for (const key of Object.keys(error)) { + if (key in copy) continue; + (copy as any)[key] = this.value(read(error, key), depth + 1); + } + const cause = read(error, 'cause'); + if (cause !== undefined) { + Object.defineProperty(copy, 'cause', { + value: this.value(cause, depth + 1), + writable: true, + configurable: true, + }); + } + const errors = read(error, 'errors'); + if (Array.isArray(errors)) (copy as any).errors = this.value(errors, depth + 1); + return copy; + } +} + +function isErrorLike(value: object): boolean { + return typeof read(value, 'message') === 'string' && typeof read(value, 'name') === 'string' && 'stack' in value; +} + +/** + * A plain `Error` copy of `error` whose message, stack, properties and whole + * `cause` chain have the secrets masked. Strings are masked; anything else + * that is not an error, array or plain object is reduced to its type name. + */ +export function redactError(error: unknown, secrets: Secrets): unknown { + return new Redactor(secrets).value(error, 0); } diff --git a/test/redaction.test.mjs b/test/redaction.test.mjs index 96ea609..5dca971 100644 --- a/test/redaction.test.mjs +++ b/test/redaction.test.mjs @@ -59,7 +59,7 @@ describe('API key redaction', () => { const error = await client(fetch).getEvents({ sport: 'football' }).catch((e) => e); assert.ok(error instanceof NetworkError); assert.match(error.message, /apiKey=\*\*\*/); - assert.ok(error.cause instanceof TypeError); + assert.equal(error.cause.name, 'TypeError'); assert.equal(error.cause.cause.code, 'ECONNREFUSED'); assertNoKey(error); }); @@ -132,3 +132,60 @@ describe('API key redaction', () => { feed.close(); }); }); + +describe('API key redaction in causes', () => { + test('plain-object and URL causes are masked', async () => { + const fetch = async (url) => { + const error = new TypeError('fetch failed'); + error.cause = { url, request: { href: new URL(url) }, nested: [{ deep: url }] }; + error.request = { url }; + throw error; + }; + const error = await client(fetch).getEvents({ sport: 'football' }).catch((e) => e); + assert.ok(error instanceof NetworkError); + assert.match(error.cause.cause.url, /apiKey=\*\*\*/); + assertNoKey(error); + }); + + test('a very deep cause chain is cut with a placeholder, never left unmasked', async () => { + const fetch = async (url) => { + let error = new Error(`root ${url}`); + for (let i = 0; i < 30; i++) { + const outer = new Error(`level ${i}`); + outer.cause = error; + error = outer; + } + throw error; + }; + const error = await client(fetch).getEvents({ sport: 'football' }).catch((e) => e); + assertNoKey(error); + let link = error; + for (let i = 0; i < 60 && link && typeof link === 'object'; i++) link = link.cause; + assert.ok(link === undefined || typeof link === 'string'); + }); + + test('cyclic causes do not hang', async () => { + const fetch = async (url) => { + const a = new Error(`a ${url}`); + const b = new Error('b'); + a.cause = b; + b.cause = a; + throw a; + }; + const error = await client(fetch).getEvents({ sport: 'football' }).catch((e) => e); + assertNoKey(error); + }); + + test('a native AbortError cause stays readable', async () => { + const fetch = (_url, init) => + new Promise((_resolve, reject) => { + init.signal.addEventListener('abort', () => reject(init.signal.reason)); + }); + const error = await client(fetch, { timeout: 10 }).getEvents({ sport: 'football' }).catch((e) => e); + assert.ok(error instanceof TimeoutError); + assert.equal(typeof String(error.cause), 'string'); + assert.equal(error.cause.name, 'AbortError'); + assert.equal(typeof error.cause.message, 'string'); + assertNoKey(error); + }); +}); From 9ce8014925b2deb9333cfdf1d7185945ef11519b Mon Sep 17 00:00:00 2001 From: odds-api-io Date: Thu, 26 Nov 2026 09:25:12 +0100 Subject: [PATCH 3/5] fix: mask property names and credential fields in copied causes --- src/redact.ts | 13 +++++++++++-- test/redaction.test.mjs | 16 ++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/redact.ts b/src/redact.ts index 40f7fd6..1fd7c38 100644 --- a/src/redact.ts +++ b/src/redact.ts @@ -8,6 +8,8 @@ const REDACTED = '***'; const SECRET_PARAM = /(^|[^A-Za-z0-9_])(api[_-]?key|access[_-]?token|auth[_-]?token|token|secret|password|key)(=|%3D)[^&#\s'"<>()[\],;]+/gi; const SECRET_HEADER = /((?:x-)?api[_-]?key|authorization)(['"]?\s*:\s*['"]?)(?:bearer\s+|basic\s+)?[^'"\s,}&]+/gi; +const SECRET_FIELD = + /^(?:x-)?(?:api[_-]?key|access[_-]?token|auth[_-]?token|token|secret|password|authorization|proxy-authorization)$/i; const MAX_DEPTH = 8; const TRUNCATED = '[truncated]'; @@ -69,10 +71,17 @@ class Redactor { } const out: Record = {}; this.seen.set(value, out); - for (const key of Object.keys(value)) out[key] = this.value(read(value, key), depth + 1); + for (const key of Object.keys(value)) this.copyField(out, value, key, depth); return out; } + private copyField(target: object, source: object, key: string, depth: number): void { + const value = read(source, key); + const name = redactSecrets(key, this.secrets); + (target as Record)[name] = + SECRET_FIELD.test(key) && value ? REDACTED : this.value(value, depth + 1); + } + /** A plain `Error` copy: same name, masked message, stack and properties, masked `cause` chain. */ error(error: Error, depth: number): Error { const message = read(error, 'message'); @@ -92,7 +101,7 @@ class Redactor { } for (const key of Object.keys(error)) { if (key in copy) continue; - (copy as any)[key] = this.value(read(error, key), depth + 1); + this.copyField(copy, error, key, depth); } const cause = read(error, 'cause'); if (cause !== undefined) { diff --git a/test/redaction.test.mjs b/test/redaction.test.mjs index 5dca971..0d9a3ff 100644 --- a/test/redaction.test.mjs +++ b/test/redaction.test.mjs @@ -189,3 +189,19 @@ describe('API key redaction in causes', () => { assertNoKey(error); }); }); + +describe('API key redaction in structured causes', () => { + test('property names and credential fields are masked', async () => { + const fetch = async (url) => { + const error = new TypeError('fetch failed'); + error.requests = { [url]: 'failed' }; + error.request = { headers: { Authorization: 'Bearer proxy-private-token', Accept: 'application/json' } }; + throw error; + }; + const error = await client(fetch).getEvents({ sport: 'football' }).catch((e) => e); + assertNoKey(error); + assert.equal(error.cause.request.headers.Authorization, '***'); + assert.equal(error.cause.request.headers.Accept, 'application/json'); + assert.ok(!inspect(error, { depth: 20 }).includes('proxy-private-token')); + }); +}); From adfa7889204634d920ec8d1e25165bbd8d7a7c5d Mon Sep 17 00:00:00 2001 From: odds-api-io Date: Thu, 26 Nov 2026 09:29:29 +0100 Subject: [PATCH 4/5] fix: mask error names and symbol descriptions in copied causes --- src/redact.ts | 3 ++- test/redaction.test.mjs | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/redact.ts b/src/redact.ts index 1fd7c38..f5e442c 100644 --- a/src/redact.ts +++ b/src/redact.ts @@ -54,6 +54,7 @@ class Redactor { value(value: unknown, depth: number): unknown { if (typeof value === 'string') return redactSecrets(value, this.secrets); + if (typeof value === 'symbol') return redactSecrets(String(value), this.secrets); if (value === null || typeof value !== 'object') return typeof value === 'function' ? undefined : value; if (depth > MAX_DEPTH) return TRUNCATED; if (this.seen.has(value)) return this.seen.get(value); @@ -88,7 +89,7 @@ class Redactor { const copy = new Error(redactSecrets(typeof message === 'string' ? message : '', this.secrets)); this.seen.set(error, copy); const name = read(error, 'name'); - if (typeof name === 'string') copy.name = name; + if (typeof name === 'string') copy.name = redactSecrets(name, this.secrets); const stack = read(error, 'stack'); Object.defineProperty(copy, 'stack', { value: typeof stack === 'string' ? redactSecrets(stack, this.secrets) : undefined, diff --git a/test/redaction.test.mjs b/test/redaction.test.mjs index 0d9a3ff..af669bf 100644 --- a/test/redaction.test.mjs +++ b/test/redaction.test.mjs @@ -205,3 +205,17 @@ describe('API key redaction in structured causes', () => { assert.ok(!inspect(error, { depth: 20 }).includes('proxy-private-token')); }); }); + +describe('API key redaction in error names and symbols', () => { + test('an error name or symbol holding the URL is masked', async () => { + const fetch = async (url) => { + const error = new Error('failed'); + error.name = `FetchError(${url})`; + error.context = Symbol(url); + throw error; + }; + const error = await client(fetch).getEvents({ sport: 'football' }).catch((e) => e); + assertNoKey(error); + assert.match(error.cause.name, /apiKey=\*\*\*/); + }); +}); From d53ff331a84f42262bcb472c8e9a68cbf447aee1 Mon Sep 17 00:00:00 2001 From: odds-api-io Date: Thu, 26 Nov 2026 09:32:40 +0100 Subject: [PATCH 5/5] fix: extract the server message before masking the error body --- src/client.ts | 13 +++++++------ test/redaction.test.mjs | 10 ++++++++++ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/client.ts b/src/client.ts index 3b7acc2..0ccbe50 100644 --- a/src/client.ts +++ b/src/client.ts @@ -273,21 +273,22 @@ export class OddsAPIClient { private async toError(response: Response, rateLimit?: RateLimitInfo): Promise { const status = response.status; - let body = ''; + let raw = ''; try { - body = this.redact(await response.text()); + raw = await response.text(); } catch { - body = ''; + raw = ''; } - let message = body.trim() || response.statusText || `HTTP ${status}`; + let message = raw.trim() || response.statusText || `HTTP ${status}`; try { - const parsed = JSON.parse(body); + const parsed = JSON.parse(raw); if (parsed && typeof parsed.error === 'string') message = parsed.error; else if (parsed && typeof parsed.message === 'string') message = parsed.message; } catch { // not JSON: keep the raw text } - const details = { status, body, rateLimit }; + message = this.redact(message); + const details = { status, body: this.redact(raw), rateLimit }; switch (status) { case 400: diff --git a/test/redaction.test.mjs b/test/redaction.test.mjs index af669bf..c614bca 100644 --- a/test/redaction.test.mjs +++ b/test/redaction.test.mjs @@ -219,3 +219,13 @@ describe('API key redaction in error names and symbols', () => { assert.match(error.cause.name, /apiKey=\*\*\*/); }); }); + +test('the server message is still extracted when the body has an apiKey field', async () => { + const fetch = async () => + new Response(JSON.stringify({ error: 'Invalid API key', apiKey: null }), { + status: 401, + headers: { 'content-type': 'application/json' }, + }); + const error = await client(fetch).getEvents({ sport: 'football' }).catch((e) => e); + assert.equal(error.message, 'Invalid API key'); +});