Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(sdk): recognise the error envelope a production gateway sends
Yudhi Armyndharisd4a809200637
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex eeaa3f780..6e72a0015 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -43,6 +43,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- A WhatsApp Web build that cannot be resolved from the wa-version registry is now reported (`web_version_resolve_failed`) with the reason, the registry URL and the remedy. A host that cannot reach the registry — a proxy, a firewalled VPS, regional blocking — silently continued without a pin and let whatsapp-web.js pick the build itself, which is the "authenticates then never reaches ready" class the pin exists to prevent; nothing was logged, so there was nothing to grep for. The existing one-minute backoff already bounds how often the warning can repeat.- `POST /sessions/:id/pairing-code` answers `409` while a whatsapp-web.js session is still starting up, instead of a `500` carrying a raw `TypeError`. The engine stored its client before launching Chromium, so for the whole launch — seconds on a modest host — the route passed its only guard and reached into a browser page that did not exist yet. Requesting a code straight after `POST /start`, which is what the dashboard's linking modal invites, landed in exactly that window. The request is now accepted only once the session reaches `qr_ready`, the state the pairing flow needs anyway.- A burst of inbound media messages no longer loses the media of everything past the eighth. The Baileys adapter capped the download queue at its active slots, and an upsert is submitted in one synchronous pass, so admission was a constant 8 whatever the batch size — a 40-message upsert arrived with 32 of its files replaced by an omitted-media marker. The queue is now unbounded and a burst parks instead of shedding; the concurrent-download bound is unchanged.+- The JavaScript SDK reports why a production gateway rejected a request instead of ending the error message in `[object Object]`. NestJS omits `error` from the envelope whenever the exception carried no explicit message, which is what the global ValidationPipe does under `disableErrorMessages` — the default whenever `NODE_ENV=production` and `VALIDATION_ERROR_DETAIL` is unset — so every rejected request in a stock production deployment answers `{ statusCode, message }`. The SDK required all three keys to recognise the envelope; the PHP, Python and Go clients already treated `error` as optional.### Securitydiff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.mdindex aa63007e6..50384197a 100644--- a/docs/18-sdk-design.md+++ b/docs/18-sdk-design.md@@ -338,7 +338,7 @@ Media bodies share the `SendMediaRequest` shape: `{ chatId, url? | base64?, mime### Error Handling-On a non-2xx response the SDK throws a typed `OpenWAApiError` subclass carrying `.status` (HTTP status), `.body` (parsed JSON error envelope, or raw text), and `.errorKind` (the NestJS `error` field). All error classes extend `OpenWAError` and are exported, so they are `instanceof`-checkable. A timeout throws `OpenWATimeoutError`, which extends `OpenWAError` directly (not `OpenWAApiError`).+On a non-2xx response the SDK throws a typed `OpenWAApiError` subclass carrying `.status` (HTTP status), `.body` (parsed JSON error envelope, or raw text), and `.errorKind` (the NestJS `error` field, `undefined` when the gateway omits it — which is the norm for a validation rejection in production, where `disableErrorMessages` is on). All error classes extend `OpenWAError` and are exported, so they are `instanceof`-checkable. A timeout throws `OpenWATimeoutError`, which extends `OpenWAError` directly (not `OpenWAApiError`).| Error class | HTTP status | Meaning || ------------------------------- | ----------- | --------------------------------------------------------------------------------------------- |diff --git a/sdk/javascript/src/errors.ts b/sdk/javascript/src/errors.tsindex 1fc2ba389..ae09257b6 100644--- a/sdk/javascript/src/errors.ts+++ b/sdk/javascript/src/errors.ts@@ -2,8 +2,9 @@* Typed error hierarchy for the OpenWA SDK.** The OpenWA API returns NestJS-default errors of the shape:- * `{ statusCode: number, message: string | string[], error: string }`- * This module maps that to a typed, ergonomic error tree so callers can+ * `{ statusCode: number, message: string | string[], error?: string }`+ * `error` is absent whenever the exception carried no explicit message, so it is never required to+ * recognise the envelope. This module maps that to a typed, ergonomic error tree so callers can* `instanceof`-check or branch on `.status`.** @packageDocumentation@@ -123,15 +124,22 @@ export function classifyApiError(status: number, message: string, body: unknown,}}-/** Narrow the NestJS error envelope shape: `{ statusCode, message, error }`. */+/**+ * Narrow the NestJS error envelope shape: `{ statusCode, message, error }`.+ *+ * `error` is optional. NestJS omits it whenever the exception was constructed without an explicit+ * message — which is what the global ValidationPipe does under `disableErrorMessages`, the default+ * when `NODE_ENV=production` and `VALIDATION_ERROR_DETAIL` is unset. Every rejected request in a+ * stock production deployment therefore answers `{ statusCode, message }` and nothing else.+ */interface NestErrorEnvelope {statusCode: number;message: string | string[];- error: string;+ error?: string;}function isNestEnvelope(body: unknown): body is NestErrorEnvelope {- return typeof body === 'object' && body !== null && 'statusCode' in body && 'message' in body && 'error' in body;+ return typeof body === 'object' && body !== null && 'statusCode' in body && 'message' in body;}function describeMessage(message: string | string[] | unknown): string {diff --git a/sdk/javascript/test/client.test.ts b/sdk/javascript/test/client.test.tsindex 0c2f9db6a..da2c2ffc5 100644--- a/sdk/javascript/test/client.test.ts+++ b/sdk/javascript/test/client.test.ts@@ -152,6 +152,39 @@ describe('OpenWAClient', () => {);});+ // A stock production gateway runs the ValidationPipe with `disableErrorMessages`, so NestJS omits+ // `error` and answers `{ statusCode, message }`. Every case above sends the three-key development+ // shape, which is why the suite stayed green while this body rendered as "[object Object]".+ it('parses the envelope a production gateway actually sends, with no `error` key', async () => {+ const t = new MockTransport().on('POST', '/api/sessions', {+ status: 400,+ body: { message: 'Bad Request', statusCode: 400 },+ });+ const err = await client(t)+ .sessions.create({ name: 'x' })+ .catch((e: unknown) => e);++ expect(err).toBeInstanceOf(OpenWAApiError);+ expect((err as OpenWAApiError).message).toContain('Bad Request');+ expect((err as OpenWAApiError).message).not.toContain('[object Object]');+ expect((err as OpenWAApiError).status).toBe(400);+ // No `error` key was sent, so there is no kind to report — undefined, not a stringified object.+ expect((err as OpenWAApiError).errorKind).toBeUndefined();+ });++ it('still reads `error` as the kind when the gateway sends one', async () => {+ const t = new MockTransport().on('POST', '/api/sessions', {+ status: 400,+ body: { message: ['name must be a string'], error: 'Bad Request', statusCode: 400 },+ });+ const err = await client(t)+ .sessions.create({ name: 'x' })+ .catch((e: unknown) => e);++ expect((err as OpenWAApiError).errorKind).toBe('Bad Request');+ expect((err as OpenWAApiError).message).toContain('name must be a string');+ });+it('maps each status code to its typed error subclass', async () => {const cases: Array<[number, new (...a: never[]) => OpenWAApiError]> = [[401, OpenWAAuthError],