Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(sdk-js): refuse a timeoutMs that is not a number of milliseconds
Yudhi Armyndharis2e4d7ee35a70
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 96887dac4..35e6227ef 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -88,7 +88,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Dashboard: clearing an optional plugin config field clears the stored value, and the API Keys page shows a load or permission error instead of an empty list when the keys cannot be read.- Dashboard: the page search boxes show keyboard focus, the Infrastructure storage badge is translated, and the signed-in role is kept per browser tab with its API key instead of in storage shared by every tab.- Dashboard: the session proxy settings and the partial-export media warning are translated in 11 locales, the Telugu status composer and channel messages are translated, and counts that are exact multiples of a million render in the plural in French, Spanish, Italian and Portuguese.-- JavaScript SDK: requests no longer fail with "Illegal invocation" in browsers and Workers, with or without an injected fetch; `timeoutMs` 0 or `Infinity` turns the timeout off instead of aborting every request after 1 ms; and an error body without the usual envelope is shown as JSON instead of `[object Object]`.+- JavaScript SDK: requests no longer fail with "Illegal invocation" in browsers and Workers, with or without an injected fetch; `timeoutMs` 0 or `Infinity` turns the timeout off instead of aborting every request after 1 ms, and a value that is not a non-negative number (an empty variable, `30s`) throws a `TypeError`; and an error body without the usual envelope is shown as JSON instead of `[object Object]`.- SDKs: a caller header that differs only in letter case from `X-API-Key` or `Content-Type` no longer goes out next to the SDK's own value.- PHP SDK: the readiness `503` throws `OpenWAServiceUnavailableException` instead of an "Array to string conversion" error, and an `http://` base URL is logged with `error_log()` instead of raising a PHP warning; `allowInsecureHttp` silences it.- Java SDK: `CatalogProduct.price` is a nullable `Double`, so a product without a price no longer breaks `catalog.products()`.diff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.mdindex b1d138e98..19509ce20 100644--- a/docs/18-sdk-design.md+++ b/docs/18-sdk-design.md@@ -105,13 +105,13 @@ const { OpenWAClient } = require('@rmyndharis/openwa');The constructor takes a single `OpenWAClientOptions` object. `baseUrl` and `apiKey` are required (the constructor throws synchronously if either is missing).-| Option | Type | Required | Default | Description |-| ---------------- | ------------------------ | -------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| `baseUrl` | `string` | yes | — | Base URL of the OpenWA API, e.g. `http://localhost:2785`. A trailing slash is trimmed; a path prefix (e.g. `https://host/v1`) is preserved. |-| `apiKey` | `string` | yes | — | API key sent as the `X-API-Key` header on every request. |-| `timeoutMs` | `number` | no | `30000` | Per-request timeout in milliseconds; `0` or `Infinity` turns it off. Overridable per call via `RequestOptions.timeoutMs` on the raw `request()` method. |-| `defaultHeaders` | `Record<string, string>` | no | `{}` | Headers merged onto every request. The `Content-Type: application/json` and `X-API-Key` headers always take precedence. |-| `fetch` | `FetchLike` | no | `globalThis.fetch` | Injectable transport (the WHATWG `fetch` signature). Use this to wrap requests with retry/observability middleware, or to supply a `fetch` on runtimes that lack a global one. |+| Option | Type | Required | Default | Description |+| ---------------- | ------------------------ | -------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `baseUrl` | `string` | yes | — | Base URL of the OpenWA API, e.g. `http://localhost:2785`. A trailing slash is trimmed; a path prefix (e.g. `https://host/v1`) is preserved. |+| `apiKey` | `string` | yes | — | API key sent as the `X-API-Key` header on every request. |+| `timeoutMs` | `number` | no | `30000` | Per-request timeout in milliseconds; `0` or `Infinity` turns it off, and a value that is not a non-negative number throws a `TypeError`. Overridable per call via `RequestOptions.timeoutMs` on the raw `request()` method. |+| `defaultHeaders` | `Record<string, string>` | no | `{}` | Headers merged onto every request. The `Content-Type: application/json` and `X-API-Key` headers always take precedence. |+| `fetch` | `FetchLike` | no | `globalThis.fetch` | Injectable transport (the WHATWG `fetch` signature). Use this to wrap requests with retry/observability middleware, or to supply a `fetch` on runtimes that lack a global one. |### Resources & Methodsdiff --git a/sdk/javascript/src/client.ts b/sdk/javascript/src/client.tsindex 59f362897..2bdb6a7a6 100644--- a/sdk/javascript/src/client.ts+++ b/sdk/javascript/src/client.ts@@ -25,7 +25,7 @@* @packageDocumentation*/-import { request, requestBytes, encodeSegment, warnIfInsecureHttpUrl, type BinaryResponse, type ClientConfig, type FetchLike, type RequestOptions } from './http.js';+import { request, requestBytes, encodeSegment, toTimeoutMs, warnIfInsecureHttpUrl, type BinaryResponse, type ClientConfig, type FetchLike, type RequestOptions } from './http.js';import { CallsResource } from './resources/calls.js';import { MediaResource } from './resources/media.js';import { CatalogResource } from './resources/catalog.js';@@ -67,7 +67,7 @@ export class OpenWAClient {this.config = {baseUrl: options.baseUrl,apiKey: options.apiKey,- timeoutMs: options.timeoutMs ?? 30000,+ timeoutMs: toTimeoutMs(options.timeoutMs ?? 30000),defaultHeaders: options.defaultHeaders ?? {},// Looked up on each call rather than captured here, so a fetch installed on globalThis after// the client is built (a polyfill or a test stub) is the one used.diff --git a/sdk/javascript/src/http.ts b/sdk/javascript/src/http.tsindex 2d2a22f8e..ea7a3fe94 100644--- a/sdk/javascript/src/http.ts+++ b/sdk/javascript/src/http.ts@@ -113,6 +113,21 @@ export async function requestBytes(});}+/**+ * A timeout in milliseconds, coerced once: untyped JS config can pass a numeric string (process.env).+ * `0` or `Infinity` turns the timeout off, so any other value that is not a non-negative number (an+ * empty variable, `30s`) is refused rather than read as "off", which would let a request hang forever.+ */+export function toTimeoutMs(value: unknown): number {+ const ms = typeof value === 'string' && value.trim() === '' ? NaN : Number(value);+ if (Number.isNaN(ms) || ms < 0) {+ throw new TypeError(+ `OpenWA: timeoutMs must be a non-negative number of milliseconds, got ${JSON.stringify(value)}`,+ );+ }+ return ms;+}+/*** Shared transport for {@link request} and {@link requestBytes}: builds the* URL/headers, performs the fetch under the per-request timeout, translates a@@ -125,12 +140,10 @@ async function send<T>(consume: (res: Response) => Promise<T>,): Promise<T> {const url = buildUrl(config.baseUrl, options.path, options.query);- // Coerced once: untyped JS config can pass a numeric string (process.env), which Number.isFinite- // below would otherwise read as "no timeout".- const timeoutMs = Number(options.timeoutMs ?? config.timeoutMs);+ const timeoutMs = toTimeoutMs(options.timeoutMs ?? config.timeoutMs);const controller = new AbortController();- // 0, Infinity or NaN means no client timeout. setTimeout fires after 1 ms for a delay that is not+ // 0 or Infinity means no client timeout. setTimeout fires after 1 ms for a delay that is not// finite or exceeds 2^31-1, so cap it rather than abort every request.const timer =Number.isFinite(timeoutMs) && timeoutMs > 0diff --git a/sdk/javascript/test/client.test.ts b/sdk/javascript/test/client.test.tsindex 7436581ec..d4351ba67 100644--- a/sdk/javascript/test/client.test.ts+++ b/sdk/javascript/test/client.test.ts@@ -290,6 +290,16 @@ describe('OpenWAClient', () => {await expect(c.sessions.list()).rejects.toThrow(new OpenWATimeoutError(5));});+ it('refuses a timeout that is not a number of milliseconds instead of turning it off', () => {+ // An environment variable that is set but empty, or carries a unit, would otherwise let a+ // stalled request hang forever.+ for (const timeoutMs of ['', ' ', '30s', 'abc', -1]) {+ expect(+ () => new OpenWAClient({ baseUrl: 'http://localhost', apiKey: 'k', timeoutMs: timeoutMs as unknown as number }),+ ).toThrow(TypeError);+ }+ });+it('keeps X-API-Key winning over defaultHeaders', async () => {const t = new MockTransport().on('GET', '/api/sessions', { body: [] });const c = new OpenWAClient({