Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(openapi): publish a schema-valid document
Yudhi Armyndharis37caf8e55fdf
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c943c762c..0e47be012 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed- **A post-connect group-name hydration WhatsApp never answered no longer finishes without a word** — the read shared the ambiguity `GET /sessions/{id}/groups` was bounded against in 0.14.5, where an unanswered query and an account with no groups both yield an empty result, but only the REST caller got a clock: the hydration step logged neither its success line nor its failure line, so group chats stayed unnamed with nothing to explain it.+- **The published OpenAPI document is schema-valid again** — `@nestjs/swagger` expands an `@All()` route over its own method list, which includes `search`, and the 3.0 Path Item Object has no field for it, so the ingress route contributed a key that made strict validators reject the whole 150-path document rather than just that route; the export now drops operations the specification cannot express, and nothing in the repository validated the document to catch it.## [0.14.5] - 2026-08-08diff --git a/openapi.json b/openapi.jsonindex 73a3ddf19..cde44950d 100644--- a/openapi.json+++ b/openapi.json@@ -7631,54 +7631,6 @@"integration"],"security": []- },- "search": {- "operationId": "IngressController_receive_search",- "parameters": [- {- "name": "pluginId",- "required": true,- "in": "path",- "schema": {- "type": "string"- }- },- {- "name": "instanceId",- "required": true,- "in": "path",- "schema": {- "type": "string"- }- }- ],- "responses": {- "200": {- "description": "GET verification challenge echo, or a duplicate delivery already persisted (idempotent re-delivery). Not the primary success path — see 202."- },- "202": {- "description": "Webhook accepted and queued for async plugin processing (the primary success path)."- },- "401": {- "description": "Signature verification failed (missing, stale, or wrong secret)."- },- "403": {- "description": "GET verification challenge failed (verifyToken mismatch)."- },- "404": {- "description": "Unknown pluginId/instanceId, or no route claimed by the plugin."- },- "413": {- "description": "Request body exceeds the route maxBodyBytes limit."- },- "429": {- "description": "Per-instance rate limit exceeded (INGRESS_INSTANCE_LIMIT)."- }- },- "tags": [- "integration"- ],- "security": []}},"/api/integration/instances/{pluginId}/{instanceId}/redrive": {diff --git a/scripts/export-openapi.ts b/scripts/export-openapi.tsindex 18f02efd6..f6d4bb516 100644--- a/scripts/export-openapi.ts+++ b/scripts/export-openapi.ts@@ -12,7 +12,7 @@ import { SwaggerModule } from '@nestjs/swagger';import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { createSwaggerConfig, exemptPublicOperations } from '../src/config/swagger.config';+import { createSwaggerConfig, 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@@ -61,16 +61,20 @@ async function main() {app.setGlobalPrefix('api');try {const doc = SwaggerModule.createDocument(app, createSwaggerConfig());+ // Before the exemption pass, so it never spends work on an operation about to be removed.+ dropUnexpressibleOperations(doc);exemptPublicOperations(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)`);+ console.log(+ `✓ OpenAPI snapshot written to ${out} (version ${doc.info.version}, ${Object.keys(doc.paths).length} paths)`,+ );} finally {await app.close();rmSync(exportDataDir, { recursive: true, force: true });}}-void main().catch((e) => {+void main().catch(e => {console.error(e);process.exit(1);});diff --git a/src/config/swagger.config.spec.ts b/src/config/swagger.config.spec.tsindex 89f2c60aa..ad5c2502b 100644--- a/src/config/swagger.config.spec.ts+++ b/src/config/swagger.config.spec.ts@@ -1,6 +1,12 @@import * as fs from 'fs';import * as path from 'path';-import { createSwaggerConfig, exemptPublicOperations, PUBLIC_PATHS, METRICS_BEARER_SCHEME } from './swagger.config';+import {+ createSwaggerConfig,+ dropUnexpressibleOperations,+ exemptPublicOperations,+ PUBLIC_PATHS,+ METRICS_BEARER_SCHEME,+} from './swagger.config';import type { OpenAPIObject } from '@nestjs/swagger';describe('createSwaggerConfig', () => {@@ -139,3 +145,74 @@ describe('PUBLIC_PATHS drift guard', () => {);});});++describe('dropUnexpressibleOperations', () => {+ const docWith = (item: Record<string, unknown>): OpenAPIObject =>+ ({ paths: { '/api/thing': item } }) as unknown as OpenAPIObject;++ it('removes an operation OpenAPI 3.0 has no field for', () => {+ // `@nestjs/swagger` expands `@All()` over its own method list, which includes `search`. Nest routes+ // SEARCH at runtime; the 3.0 Path Item Object simply cannot describe it.+ const doc = docWith({ get: { operationId: 'a' }, search: { operationId: 'b' } });++ dropUnexpressibleOperations(doc);++ expect(Object.keys(doc.paths['/api/thing'])).toEqual(['get']);+ });++ it('keeps every field the 3.0 Path Item Object defines', () => {+ const item = {+ summary: 's',+ description: 'd',+ parameters: [],+ servers: [],+ get: {},+ put: {},+ post: {},+ delete: {},+ options: {},+ head: {},+ patch: {},+ trace: {},+ };++ const doc = docWith({ ...item });+ dropUnexpressibleOperations(doc);++ expect(Object.keys(doc.paths['/api/thing']).sort()).toEqual(Object.keys(item).sort());+ });++ it('keeps specification extensions', () => {+ const doc = docWith({ get: {}, 'x-internal': true });++ dropUnexpressibleOperations(doc);++ expect(Object.keys(doc.paths['/api/thing']).sort()).toEqual(['get', 'x-internal']);+ });++ it('removes a method upstream has not added yet', () => {+ // The allowlist is the point: a denylist naming `search` would pass the next WebDAV verb straight+ // through. RequestMethod already defines PROPFIND, MKCOL, COPY, MOVE, LOCK and UNLOCK.+ const doc = docWith({ get: {}, propfind: {}, mkcol: {} });++ dropUnexpressibleOperations(doc);++ expect(Object.keys(doc.paths['/api/thing'])).toEqual(['get']);+ });++ it('leaves the committed snapshot with no unexpressible operation', () => {+ const snapshot = JSON.parse(+ fs.readFileSync(path.join(__dirname, '..', '..', 'openapi.json'), 'utf8'),+ ) as OpenAPIObject;++ const offenders = Object.entries(snapshot.paths).flatMap(([route, item]) => {+ const before = Object.keys(item);+ const after = Object.keys(+ dropUnexpressibleOperations({ paths: { [route]: { ...item } } } as OpenAPIObject).paths[route],+ );+ return before.length === after.length ? [] : [route];+ });++ expect(offenders).toEqual([]);+ });+});diff --git a/src/config/swagger.config.ts b/src/config/swagger.config.tsindex 8dd663271..c0f3f1dcd 100644--- a/src/config/swagger.config.ts+++ b/src/config/swagger.config.ts@@ -29,6 +29,51 @@ const HTTP_METHODS = ['get', 'post', 'put', 'delete', 'patch', 'options', 'head'type PathItem = Record<string, { security?: unknown } | undefined>;+/**+ * The complete field set an OpenAPI 3.0 Path Item Object may carry. The 3.0 schema declares the object+ * `additionalProperties: false` apart from `^x-`, so anything outside this set makes the whole document+ * fail schema validation — not just the path it appears on.+ */+const OPENAPI_3_PATH_ITEM_FIELDS = new Set([+ '$ref',+ 'summary',+ 'description',+ 'get',+ 'put',+ 'post',+ 'delete',+ 'options',+ 'head',+ 'patch',+ 'trace',+ 'servers',+ 'parameters',+]);++/**+ * Drop path-item entries OpenAPI 3.0 cannot express, so the published document validates.+ *+ * `@nestjs/swagger` expands an `@All()` route over its own hardcoded method list, which includes+ * `search` (`swagger-explorer.js`). SEARCH is a real HTTP method Nest routes at runtime — `RequestMethod`+ * defines it, along with the WebDAV verbs — but OpenAPI 3.0 has no field for it, so publishing the+ * operation trades a documented method for an invalid document. The route keeps answering it; only the+ * unexpressible description of it goes.+ *+ * Written as an allowlist rather than a denylist on purpose: upstream is free to widen its expansion+ * list again (PROPFIND, MKCOL, …), and a denylist would silently let the next one through. Mutates and+ * returns the document.+ */+export function dropUnexpressibleOperations(document: OpenAPIObject): OpenAPIObject {+ for (const item of Object.values(document.paths ?? {})) {+ for (const field of Object.keys(item)) {+ if (!OPENAPI_3_PATH_ITEM_FIELDS.has(field) && !field.startsWith('x-')) {+ delete (item as Record<string, unknown>)[field];+ }+ }+ }+ return document;+}+/*** Set `security: []` on every operation of a @Public route so the published spec reflects* that no API key is required (an empty `security` array overrides the document's global