Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(openapi): publish the error body and auth refusals per operation
Yudhi Armyndharis1b7b8090e186
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 93131d0ca..61e38738c 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -82,7 +82,7 @@ Session `status` wire values are **lowercase**: `created | initializing | qr_rea### Error Response-Errors use the NestJS default shape. The HTTP status is on the status line and mirrored in `statusCode`; there is no application-specific `code` field:+Errors use the NestJS default shape, published in `openapi.json` as the `ErrorResponse` schema. The HTTP status is on the status line and mirrored in `statusCode`:```json{@@ -92,6 +92,19 @@ Errors use the NestJS default shape. The HTTP status is on the status line and m}```+A few refusals add a stable machine-readable `code`, so a client can branch without parsing `message`:++| `code` | Status | Meaning |+| ------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------- |+| `SESSION_NAME_TEARDOWN_PENDING` | `409` | The previous session's credential teardown under that name is still in flight; retry once it settles |+| `SESSION_STOP_INCOMPLETE` | `502` | The engine did not confirm the stop; retryable |+| `SESSION_LOGOUT_INCOMPLETE` | `502` | The engine did not confirm the logout; retryable |+| `SEND_PACING_LIMITED` | `429` | Send pacing refused the send; the body also carries `retryAfterSeconds` |+| `ENGINE_PAGE_ERROR` | `500` | whatsapp-web.js: WhatsApp Web rejected the operation in the page; the body also carries `pageError` and, when the page could read it, `build` |+| `IMPORT_ALREADY_RUNNING` | `409` | Another data import is in progress |+| `IMPORT_WOULD_ORPHAN_ENGINES` | `409` | The backup lacks sessions whose engines are running; retry with `stopOrphans=true` or `force=true` |+| `IMPORT_NESTED_TRANSACTION` | `409` | Another database transaction is open on the connection; retry with no other data operation in flight |+Validation failures (`statusCode: 400`) return `message` as an **array** of field-level strings, with `error: "Bad Request"`, when field detail is enabled: by default outside production, or anywhere with `VALIDATION_ERROR_DETAIL=true`. Under `NODE_ENV=production` (the Docker image, compose and Helm default) detail is off unless that variable is set, and the body is only `{ "statusCode": 400, "message": "Bad Request" }`. Clients should accept `message` as either a string or an array of strings. A global `ValidationPipe` runs with `whitelist` + `forbidNonWhitelisted`, so any request-body field not declared on the DTO is rejected with `400`.### General Error Codesdiff --git a/scripts/export-openapi.ts b/scripts/export-openapi.tsindex f6d4bb516..9bfef6e69 100644--- a/scripts/export-openapi.ts+++ b/scripts/export-openapi.ts@@ -12,7 +12,12 @@ import { SwaggerModule } from '@nestjs/swagger';import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { createSwaggerConfig, dropUnexpressibleOperations, exemptPublicOperations } from '../src/config/swagger.config';+import {+ createSwaggerConfig,+ documentErrorResponses,+ dropUnexpressibleOperations,+ exemptPublicOperations,+} from '../src/config/swagger.config';// Pin a hermetic env BEFORE AppModule is imported. AppModule reads QUEUE_ENABLED / MCP_ENABLED at// module top-level (its conditional module mounts) and TypeORM reads the DB settings during@@ -64,6 +69,7 @@ async function main() {// Before the exemption pass, so it never spends work on an operation about to be removed.dropUnexpressibleOperations(doc);exemptPublicOperations(doc);+ documentErrorResponses(doc);writeFileSync(out, JSON.stringify(doc, null, 2) + '\n');console.log(`✓ OpenAPI snapshot written to ${out} (version ${doc.info.version}, ${Object.keys(doc.paths).length} paths)`,diff --git a/src/config/inflight-body-budget.spec.ts b/src/config/inflight-body-budget.spec.tsindex 25f6a54be..d55d802ed 100644--- a/src/config/inflight-body-budget.spec.ts+++ b/src/config/inflight-body-budget.spec.ts@@ -132,7 +132,11 @@ describe('createInflightBodyBudget middleware', () => {expect(state.code).toBe(503);expect(headers['retry-after']).toBe('1');expect(headers['connection']).toBe('close');- expect((state.payload as { statusCode: number }).statusCode).toBe(503);+ expect(state.payload).toEqual({+ statusCode: 503,+ message: 'Too much request body data in flight; retry later',+ error: 'Service Unavailable',+ });// Nothing was reserved for the rejected request and its stream was never tapped.expect(budget.currentBytes()).toBe(800);expect(rejected.listenerCount('data')).toBe(0);diff --git a/src/config/inflight-body-budget.ts b/src/config/inflight-body-budget.tsindex fee1c7c81..62ea3318b 100644--- a/src/config/inflight-body-budget.ts+++ b/src/config/inflight-body-budget.ts@@ -206,11 +206,11 @@ export function createInflightBodyBudget(budgetBytes: number, options?: Inflightreq.destroy();return;}- res- .status(503)- .set('Retry-After', retryAfter)- .set('Connection', 'close')- .json({ statusCode: 503, message: 'Too much request body data in flight; retry later' });+ res.status(503).set('Retry-After', retryAfter).set('Connection', 'close').json({+ statusCode: 503,+ message: 'Too much request body data in flight; retry later',+ error: 'Service Unavailable',+ });};/** Same never-read-the-body disposal as rejectBusy; only the reason and status differ. */diff --git a/src/config/openapi-contract.spec.ts b/src/config/openapi-contract.spec.tsindex d0bd65d5b..ded025fff 100644--- a/src/config/openapi-contract.spec.ts+++ b/src/config/openapi-contract.spec.ts@@ -167,6 +167,26 @@ describe('openapi.json structural invariants', () => {expect(undeclared).toEqual([]);});+ it('gives every API-key operation its auth refusals and an error body schema', () => {+ const doc = snapshot();+ type Op = { security?: unknown; responses?: Record<string, { content?: unknown; $ref?: string }> };+ let checked = 0;+ const gaps: string[] = [];+ for (const [route, item] of Object.entries(doc.paths as unknown as Record<string, Record<string, Op>>)) {+ for (const [method, op] of Object.entries(item)) {+ if (!OPERATION_KEYS.has(method) || op.security !== undefined) continue;+ checked++;+ const responses = op.responses ?? {};+ for (const status of ['401', '403']) if (!responses[status]) gaps.push(`${method} ${route} lacks ${status}`);+ for (const [status, response] of Object.entries(responses)) {+ if (Number(status) >= 400 && !response.$ref && !response.content) gaps.push(`${method} ${route} ${status}`);+ }+ }+ }+ expect(checked).toBeGreaterThan(150);+ expect(gaps).toEqual([]);+ });+it('gives each route exactly one path key, whatever its parameters are named', () => {const doc = snapshot();// A path template variable is positional: `/x/{id}` and `/x/{sessionId}` are the same URL. Two@@ -189,7 +209,7 @@ describe('openapi.json structural invariants', () => {// running gateway kept serving a document that fails validation while the artifact was clean. A// structural check, because neither producer is reachable from a unit test.describe('both OpenAPI producers apply the same passes', () => {- const PASSES = ['dropUnexpressibleOperations', 'exemptPublicOperations'];+ const PASSES = ['dropUnexpressibleOperations', 'exemptPublicOperations', 'documentErrorResponses'];const producers = ['src/main.ts', 'scripts/export-openapi.ts'];it.each(PASSES)('%s runs in every producer', pass => {@@ -206,9 +226,10 @@ describe('both OpenAPI producers apply the same passes', () => {text.indexOf(`${p}(document`) >= 0 ? text.indexOf(`${p}(document`) : text.indexOf(`${p}(doc`),);// drop must precede exempt: exempting an operation about to be deleted is wasted work, and the- // reverse order would leave a security exemption attached to nothing.+ // reverse order would leave a security exemption attached to nothing. The error pass reads+ // the exemption, so it runs last.expect(order[0]).toBeGreaterThan(-1);- expect(order[1]).toBeGreaterThan(order[0]);+ for (let i = 1; i < order.length; i++) expect(order[i]).toBeGreaterThan(order[i - 1]);}});});diff --git a/src/config/swagger.config.spec.ts b/src/config/swagger.config.spec.tsindex ad5c2502b..99164206c 100644--- a/src/config/swagger.config.spec.ts+++ b/src/config/swagger.config.spec.ts@@ -2,12 +2,15 @@ import * as fs from 'fs';import * as path from 'path';import {createSwaggerConfig,+ documentErrorResponses,dropUnexpressibleOperations,+ ERROR_RESPONSE_SCHEMA,exemptPublicOperations,PUBLIC_PATHS,METRICS_BEARER_SCHEME,} from './swagger.config';import type { OpenAPIObject } from '@nestjs/swagger';+import { EnginePageError } from '../common/errors/engine-page.error';describe('createSwaggerConfig', () => {// Regression test for issue #104: Swagger UI returned "Unauthorized" because the@@ -89,6 +92,79 @@ describe('exemptPublicOperations', () => {});});+describe('documentErrorResponses', () => {+ const ref = { 'application/json': { schema: { $ref: `#/components/schemas/${ERROR_RESPONSE_SCHEMA}` } } };+ function fixtureDoc(): OpenAPIObject {+ return {+ openapi: '3.0.0',+ info: { title: 't', version: '0' },+ paths: {+ '/api/sessions': {+ post: {+ responses: {+ '201': { description: 'Created' },+ '403': { description: 'Session-scoped keys cannot create sessions' },+ '404': { description: 'Not found' },+ },+ },+ },+ '/api/health': { get: { security: [], responses: { '503': { description: 'Not ready' } } } },+ '/api/metrics': { get: { security: [{ 'metrics-bearer': [] }], responses: { '200': { description: 'ok' } } } },+ },+ };+ }++ it('adds 401 and 403 to an API-key operation and a schema to each of its error responses', () => {+ const responses = documentErrorResponses(fixtureDoc()).paths['/api/sessions'].post!.responses as Record<+ string,+ { description: string; content?: unknown }+ >;+ expect(Object.keys(responses)).toEqual(['201', '401', '403', '404']);+ expect(responses['403'].description).toBe('Session-scoped keys cannot create sessions');+ for (const status of ['401', '403', '404']) expect(responses[status].content).toEqual(ref);+ expect(responses['201']).toEqual({ description: 'Created' });+ });++ it('leaves operations with their own security as they were', () => {+ const before = fixtureDoc();+ const after = documentErrorResponses(fixtureDoc());+ expect(after.paths['/api/health']).toEqual(before.paths['/api/health']);+ expect(after.paths['/api/metrics']).toEqual(before.paths['/api/metrics']);+ });++ it('keeps 401 for a dead key and names the IP allow-list under 403, as the auth guard answers', () => {+ const doc = fixtureDoc();+ doc.paths['/api/sessions'].get = { responses: { '200': { description: 'ok' } } };+ const responses = documentErrorResponses(doc).paths['/api/sessions'].get!.responses as Record<+ string,+ { description: string }+ >;+ expect(responses['401'].description).toBe('The API key is missing, unknown, revoked, or expired');+ expect(responses['403'].description).toMatch(/IP allow-list/);+ });++ it('describes every field and the code of the ENGINE_PAGE_ERROR body', () => {+ const schema = documentErrorResponses(fixtureDoc()).components?.schemas?.[ERROR_RESPONSE_SCHEMA] as {+ properties: Record<string, { description?: string }>;+ };+ const body = new EnginePageError(+ { name: 'Error', message: 'boom', build: '2.3000' },+ new Error('boom'),+ ).getResponse();+ expect(Object.keys(body).filter(key => !(key in schema.properties))).toEqual([]);+ expect(schema.properties.code.description).toContain('ENGINE_PAGE_ERROR');+ });++ it('registers the schema and is idempotent', () => {+ const once = documentErrorResponses(fixtureDoc());+ const schema = once.components?.schemas?.[ERROR_RESPONSE_SCHEMA] as { required?: string[] };+ expect(schema.required).toEqual(['statusCode', 'message']);+ expect(documentErrorResponses(JSON.parse(JSON.stringify(once)) as OpenAPIObject)).toEqual(+ JSON.parse(JSON.stringify(once)),+ );+ });+});+// PUBLIC_PATHS mirrors the @Public() decorator so the published spec does not falsely advertise a// public route as requiring an API key. Two tripwires catch drift:// (1) the set of files with a real @Public() decorator must match EXPECTED_PUBLIC_CONTROLLERS —diff --git a/src/config/swagger.config.ts b/src/config/swagger.config.tsindex c0f3f1dcd..5ef55b560 100644--- a/src/config/swagger.config.ts+++ b/src/config/swagger.config.ts@@ -1,4 +1,11 @@-import { DocumentBuilder, OpenAPIObject } from '@nestjs/swagger';+import {+ DocumentBuilder,+ type OpenAPIObject,+ type OperationObject,+ type ReferenceObject,+ type ResponseObject,+ type SchemaObject,+} from '@nestjs/swagger';/*** Security scheme name for the API key, used both when defining the scheme and@@ -91,6 +98,80 @@ export function exemptPublicOperations(document: OpenAPIObject): OpenAPIObject {return document;}+/** Component name of the error body every API-key operation answers with. */+export const ERROR_RESPONSE_SCHEMA = 'ErrorResponse';++const ERROR_RESPONSE: SchemaObject = {+ type: 'object',+ required: ['statusCode', 'message'],+ properties: {+ statusCode: { type: 'integer', description: 'The HTTP status, mirrored from the status line.' },+ message: {+ oneOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }],+ description: 'What went wrong. A detailed validation 400 carries one string per rejected field.',+ },+ error: {+ type: 'string',+ description:+ 'The status reason phrase, e.g. "Not Found". Not always present: a body built from a bare message ' ++ 'omits it, including an unexpected 500, an oversized-body 413, the throttler 429, ' ++ 'a production validation 400, and some errors raised with a plain message, such as the session start 504.',+ },+ code: {+ type: 'string',+ description:+ 'A stable machine-readable reason, on some errors only: SESSION_NAME_TEARDOWN_PENDING (409), ' ++ 'SESSION_STOP_INCOMPLETE and SESSION_LOGOUT_INCOMPLETE (502), SEND_PACING_LIMITED (429), ' ++ 'ENGINE_PAGE_ERROR (500, whatsapp-web.js: WhatsApp Web threw inside the page during a send or status post), ' ++ 'IMPORT_ALREADY_RUNNING, IMPORT_WOULD_ORPHAN_ENGINES and IMPORT_NESTED_TRANSACTION (409).',+ },+ retryAfterSeconds: {+ type: 'integer',+ description: 'With SEND_PACING_LIMITED: seconds until the session accepts sends again.',+ },+ pageError: {+ type: 'object',+ required: ['name', 'message'],+ properties: { name: { type: 'string' }, message: { type: 'string' } },+ description: 'With ENGINE_PAGE_ERROR: the name and message WhatsApp Web threw.',+ },+ build: {+ type: 'string',+ description: 'With ENGINE_PAGE_ERROR, when the page could read it: the running WhatsApp Web build.',+ },+ },+};++/**+ * Give every API-key operation its auth refusals and a schema for its error bodies. An operation+ * with its own `security` (the @Public routes and the metrics scrape) is skipped: those answer+ * their own shapes, such as the health probe's 503. Existing responses keep their descriptions;+ * only missing ones are added. Idempotent. Mutates and returns the document.+ */+export function documentErrorResponses(document: OpenAPIObject): OpenAPIObject {+ document.components ??= {};+ document.components.schemas ??= {};+ document.components.schemas[ERROR_RESPONSE_SCHEMA] = ERROR_RESPONSE;+ for (const item of Object.values(document.paths ?? {})) {+ for (const method of HTTP_METHODS) {+ const op = (item as Record<string, OperationObject | undefined>)[method];+ if (!op || op.security !== undefined) continue;+ op.responses['401'] ??= { description: 'The API key is missing, unknown, revoked, or expired' };+ op.responses['403'] ??= {+ description: "The API key's role, session or chat scope, or IP allow-list does not allow this operation",+ };+ for (const [status, response] of Object.entries(op.responses) as [string, ResponseObject | ReferenceObject][]) {+ if (Number(status) >= 400 && !('$ref' in response) && !response.content) {+ response.content = {+ 'application/json': { schema: { $ref: `#/components/schemas/${ERROR_RESPONSE_SCHEMA}` } },+ };+ }+ }+ }+ }+ return document;+}+/*** Builds the OpenAPI document configuration for the OpenWA API.*/@@ -114,7 +195,12 @@ export function createSwaggerConfig(): Omit<OpenAPIObject, 'paths'> {'body would be admitted on its compressed size and then inflated past the memory it is ' +'meant to bound. Send the body uncompressed.\n' +'- `503 Service Unavailable` with `Retry-After` — the gateway already has too much ' +- 'request body data in flight. The body is not read; retry after the given delay.',+ 'request body data in flight. The body is not read; retry after the given delay.\n\n' ++ 'Every operation that takes an API key can also answer `429 Too Many Requests` (the per-IP ' ++ 'rate-limit windows; with send pacing on, a send can also be refused with `code: ' ++ 'SEND_PACING_LIMITED` and `retryAfterSeconds`) and `500 Internal Server Error` (an ' ++ 'unexpected failure, or `code: ENGINE_PAGE_ERROR` when WhatsApp Web threw inside the page ' ++ 'during a whatsapp-web.js send or status post). Error bodies follow the `ErrorResponse` schema.',).setVersion(version).addApiKey({ type: 'apiKey', name: 'X-API-Key', in: 'header' }, API_KEY_SECURITY_SCHEME)diff --git a/src/main.ts b/src/main.tsindex 671cd3cb3..492421ba9 100644--- a/src/main.ts+++ b/src/main.ts@@ -9,7 +9,12 @@ import { SwaggerModule } from '@nestjs/swagger';import { AppModule, DASHBOARD_DIST, dashboardServingEnabled, dashboardBuildPresent } from './app.module';import { ShutdownService } from './common/services/shutdown.service';import { LoggerService, LogLevel, createLogger } from './common/services/logger.service';-import { createSwaggerConfig, dropUnexpressibleOperations, exemptPublicOperations } from './config/swagger.config';+import {+ createSwaggerConfig,+ documentErrorResponses,+ dropUnexpressibleOperations,+ exemptPublicOperations,+} from './config/swagger.config';import { registerUncaughtExceptionMonitor, registerUnhandledRejectionHandler } from './config/process-error-monitor';import { runBootstrapOrExit } from './config/bootstrap-fatal';import { validateEnv } from './config/env.validation';@@ -190,11 +195,12 @@ async function bootstrap() {if (swaggerEnabled) {const config = createSwaggerConfig();const document = SwaggerModule.createDocument(app, config);- // Same two passes, in the same order, as scripts/export-openapi.ts. The document is produced in+ // Same passes, in the same order, as scripts/export-openapi.ts. The document is produced in// TWO places — here for the live /api/docs and there for the committed snapshot — and fixing only// the snapshot leaves a running gateway serving a document that fails schema validation.dropUnexpressibleOperations(document);exemptPublicOperations(document);+ documentErrorResponses(document);SwaggerModule.setup('api/docs', app, document);}diff --git a/test/configure-app.e2e-spec.ts b/test/configure-app.e2e-spec.tsindex 87eb4dc52..a294a6e87 100644--- a/test/configure-app.e2e-spec.ts+++ b/test/configure-app.e2e-spec.ts@@ -23,6 +23,7 @@ import { configureApp } from '../src/configure-app';import { applyGlobalValidation } from '../src/config/app-validation';import { DASHBOARD_CSP_NONCE_PLACEHOLDER } from '../src/config/dashboard-csp';import { ActiveKeyIndex } from '../src/modules/auth/active-key-index';+import { documentErrorResponses, ERROR_RESPONSE_SCHEMA } from '../src/config/swagger.config';/*** The production HTTP surface, run for real. Every other e2e builds a bare Nest app, so the stack@@ -174,6 +175,28 @@ describe('production HTTP surface (configureApp)', () => {expect(res.status).toBe(413);});+ it('sends the error field on a malformed-JSON 400 but not on the 413, as the ErrorResponse schema says', async () => {+ const malformed = await request(app.getHttpServer())+ .post('/api/echo')+ .set('Content-Type', 'application/json')+ .send('{bad');+ expect(malformed.status).toBe(400);+ expect(malformed.body).toMatchObject({ statusCode: 400, error: 'Bad Request' });++ const oversized = await request(app.getHttpServer())+ .post('/api/echo')+ .set('Content-Type', 'application/json')+ .send({ blob: 'x'.repeat(1100 * 1024) });+ expect(oversized.status).toBe(413);+ expect(oversized.body).not.toHaveProperty('error');++ const schema = documentErrorResponses({ openapi: '3.0.0', info: { title: 't', version: '0' }, paths: {} })+ .components?.schemas?.[ERROR_RESPONSE_SCHEMA] as { properties: { error: { description: string } } };+ const omittedOn = schema.properties.error.description.split('omits it')[1];+ expect(omittedOn).toContain('oversized-body 413');+ expect(omittedOn).not.toMatch(/malformed/i);+ });+it('refuses a declared body over the aggregate in-flight budget with 503, a different layer', async () => {// The budget is a PRE-guard: it answers on the DECLARED length, before the parser reads a byte,// which is what stops slow-body memory pinning that no route guard can reach. Asserting it by