Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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`: 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)

### Fixed
Expand Down
4 changes: 2 additions & 2 deletions CITATION.cff
Original file line number Diff line number Diff line change
Expand Up @@ -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: "[email protected]"
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
28 changes: 18 additions & 10 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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;
Expand All @@ -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));
Expand All @@ -266,21 +273,22 @@ export class OddsAPIClient {

private async toError(response: Response, rateLimit?: RateLimitInfo): Promise<OddsAPIError> {
const status = response.status;
let body = '';
let raw = '';
try {
body = 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:
Expand Down
14 changes: 10 additions & 4 deletions src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,26 @@ 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. */
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);
this.name = 'OddsAPIError';
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);
}
}
Expand Down Expand Up @@ -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';
}
}
132 changes: 132 additions & 0 deletions src/redact.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
/**
* 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 SECRET_FIELD =
/^(?:x-)?(?:api[_-]?key|access[_-]?token|auth[_-]?token|token|secret|password|authorization|proxy-authorization)$/i;
const MAX_DEPTH = 8;
const TRUNCATED = '[truncated]';

type Secrets = readonly (string | undefined)[];

function variants(secrets: Secrets): string[] {
const found = new Set<string>();
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 read(source: object, key: string): unknown {
try {
return (source as Record<string, unknown>)[key];
} catch {
return undefined;
}
}

function isPlainObject(value: object): boolean {
const proto = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}

class Redactor {
private readonly seen = new WeakMap<object, unknown>();

constructor(private readonly secrets: Secrets) {}

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);
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}]`;
}
const out: Record<string, unknown> = {};
this.seen.set(value, out);
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<string, unknown>)[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');
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 = redactSecrets(name, this.secrets);
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;
this.copyField(copy, error, key, depth);
}
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);
}
2 changes: 1 addition & 1 deletion src/version.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export const VERSION = '1.6.2';
export const VERSION = '1.6.3';
17 changes: 13 additions & 4 deletions src/websocket.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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) => {
Expand Down Expand Up @@ -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);
Expand All @@ -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;
Expand Down
Loading
Loading