Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(openapi): give each route one path key in the contract
Yudhi Armyndharisc609743311cc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 13fec9de9..1aae9ecb3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed- A webhook's `lastTriggeredAt` is published as a nullable date-time string instead of an object, so a client generated from the contract no longer rejects both of the values the field actually carries. The response itself is unchanged.+- The group-list and status routes no longer appear twice in the OpenAPI contract under different path-parameter names, so a client generated from it gets one method per endpoint; the parameters are now `sessionId` and `id`. The URLs themselves are unchanged.### Securitydiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 7fbceb21c..24ae88e0d 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -296,7 +296,7 @@ Get the QR code (PNG data URL) for session authentication.**Errors:** `400` session not started / QR not ready yet / already authenticated · `401` · `403` · `404` not found-#### GET /api/sessions/:id/groups+#### GET /api/sessions/:sessionId/groupsGet all groups the session is a member of (paginated).@@ -3562,7 +3562,7 @@ create and update are the same operation and there is no server-assigned id to hwhy the route is `PUT /labels/:labelId` rather than `POST /labels`. Reusing an existing id **rewritesthat label** instead of failing, because the protocol has no create-only form.-**Reads are store-backed, not engine-direct.** `GET /status` and `GET /status/:contactId` no longer call the engine — they read from an OpenWA-side store that ingests inbound status/story broadcasts as they arrive (plus a best-effort backfill of currently-active stories on session connect), with a 24h TTL matching WhatsApp's own story expiry. This makes reads **identical on both engines**: `whatsapp-web.js` (which had a native `getBroadcasts()`/`getBroadcastById()` path) and Baileys (which never had one — `fetchStatus` only returns the _about_ text, not stories, so the raw engine methods still throw `501` if called directly, they're just no longer on the read path) now return the same shape from the same source. A status older than 24h, or received before the store existed, will not appear.+**Reads are store-backed, not engine-direct.** `GET /status` and `GET /status/:id` no longer call the engine — they read from an OpenWA-side store that ingests inbound status/story broadcasts as they arrive (plus a best-effort backfill of currently-active stories on session connect), with a 24h TTL matching WhatsApp's own story expiry. This makes reads **identical on both engines**: `whatsapp-web.js` (which had a native `getBroadcasts()`/`getBroadcastById()` path) and Baileys (which never had one — `fetchStatus` only returns the _about_ text, not stories, so the raw engine methods still throw `501` if called directly, they're just no longer on the read path) now return the same shape from the same source. A status older than 24h, or received before the store existed, will not appear.#### GET /api/sessions/:sessionId/labels@@ -3786,7 +3786,7 @@ The controller wraps the store array in `{ statuses }`, ordered newest-first. `t**Errors:** `401` missing/invalid API key, or key not scoped to this session-#### GET /api/sessions/:sessionId/status/:contactId+#### GET /api/sessions/:sessionId/status/:idGet status updates posted by a specific contact, read from the store (24h TTL, both engines).@@ -3839,7 +3839,7 @@ Stream a stored status's media bytes (the file behind a `mediaUrl` returned abov**Errors:** `401` missing/invalid API key, or key not scoped to this session · `404` `Status media not found or expired` — the status is text-only, its media was omitted (e.g. over the configured size cap), or the 24h TTL has since purged the row-Note: `:statusId/media` is a two-path-segment route, so it never collides with the single-segment `GET /status/:contactId` above regardless of declaration order.+Note: `:statusId/media` is a two-path-segment route, so it never collides with the single-segment `GET /status/:id` above regardless of declaration order.#### POST /api/sessions/:sessionId/status/send-text@@ -4019,7 +4019,7 @@ There is **no `caption`**: WhatsApp has nowhere to render one on a status voice**Errors:** `400` validation failure, or neither `url` nor `base64` supplied · `401` missing/invalid API key · `403` key lacks `OPERATOR` role · `404` session not found / not connected · `413` base64 media exceeds `MEDIA_DOWNLOAD_MAX_BYTES`-#### DELETE /api/sessions/:sessionId/status/:statusId+#### DELETE /api/sessions/:sessionId/status/:idDelete one of the session's own posted statuses.diff --git a/docs/07-api-collection.md b/docs/07-api-collection.mdindex 67a478d4e..628f4ed7b 100644--- a/docs/07-api-collection.md+++ b/docs/07-api-collection.md@@ -69,7 +69,7 @@ curl -X GET "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/qr" \-H "X-API-Key: $API_KEY"```-#### GET /api/sessions/:id/groups+#### GET /api/sessions/:sessionId/groupsList groups the session belongs to (paginated).diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.mdindex deb2c8154..2b4cba895 100644--- a/docs/12-troubleshooting-faq.md+++ b/docs/12-troubleshooting-faq.md@@ -1035,7 +1035,7 @@ docker exec openwa-api curl http://host.docker.internal:8080```bash# Get group listcurl -H "X-API-Key: $API_KEY" \- http://localhost:2785/api/sessions/{id}/groups+ http://localhost:2785/api/sessions/{sessionId}/groups# Send to groupcurl -X POST http://localhost:2785/api/sessions/{id}/messages/send-text \diff --git a/openapi.json b/openapi.jsonindex 2ecdf7feb..b2025f48b 100644--- a/openapi.json+++ b/openapi.json@@ -820,12 +820,12 @@]}},- "/api/sessions/{id}/groups": {+ "/api/sessions/{sessionId}/groups": {"get": {"operationId": "SessionController_getGroups","parameters": [{- "name": "id",+ "name": "sessionId","required": true,"in": "path","description": "Session ID",@@ -873,6 +873,52 @@"tags": ["sessions"]+ },+ "post": {+ "operationId": "GroupController_create",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateGroupDto"+ }+ }+ }+ },+ "responses": {+ "201": {+ "description": "Group created",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GroupSummaryDto"+ }+ }+ }+ },+ "403": {+ "description": "WhatsApp refused the operation. The request was well formed — the refusal happened WhatsApp-side, most often because the account lacks the admin rights the operation requires."+ },+ "409": {+ "description": "The session is not connected — an engine exists for it but is not `ready`: disconnected, reconnecting, or still initializing, so the request never reached WhatsApp. Wait for `ready` and retry. A session that was never started answers `400` instead, and the session lifecycle routes answer `409` for a conflicting state rather than this. One window answers this while the session still reads `ready`: WhatsApp Web periodically reloads its own page and the engine re-injects into it — for those few seconds the answer is a `409` naming the reload; retry shortly."+ }+ },+ "summary": "Create a new group",+ "tags": [+ "groups"+ ]}},"/api/sessions/{id}/chats": {@@ -4758,54 +4804,6 @@]}},- "/api/sessions/{sessionId}/groups": {- "post": {- "operationId": "GroupController_create",- "parameters": [- {- "name": "sessionId",- "required": true,- "in": "path",- "description": "Session ID",- "schema": {- "type": "string"- }- }- ],- "requestBody": {- "required": true,- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/CreateGroupDto"- }- }- }- },- "responses": {- "201": {- "description": "Group created",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/GroupSummaryDto"- }- }- }- },- "403": {- "description": "WhatsApp refused the operation. The request was well formed — the refusal happened WhatsApp-side, most often because the account lacks the admin rights the operation requires."- },- "409": {- "description": "The session is not connected — an engine exists for it but is not `ready`: disconnected, reconnecting, or still initializing, so the request never reached WhatsApp. Wait for `ready` and retry. A session that was never started answers `400` instead, and the session lifecycle routes answer `409` for a conflicting state rather than this. One window answers this while the session still reads `ready`: WhatsApp Web periodically reloads its own page and the engine re-injects into it — for those few seconds the answer is a `409` naming the reload; retry shortly."- }- },- "summary": "Create a new group",- "tags": [- "groups"- ]- }- },"/api/sessions/{sessionId}/groups/{groupId}/participants": {"post": {"operationId": "GroupController_addParticipants",@@ -6905,7 +6903,7 @@]}},- "/api/sessions/{sessionId}/status/{contactId}": {+ "/api/sessions/{sessionId}/status/{id}": {"get": {"operationId": "StatusController_getContactStatus","parameters": [@@ -6918,9 +6916,10 @@}},{- "name": "contactId",+ "name": "id","required": true,"in": "path",+ "description": "Contact ID","schema": {"type": "string"}@@ -6942,6 +6941,50 @@"tags": ["status"]+ },+ "delete": {+ "operationId": "StatusController_deleteStatus",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "id",+ "required": true,+ "in": "path",+ "description": "Status ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Status deleted.",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StatusDeletedResponseDto"+ }+ }+ }+ },+ "404": {+ "description": "No session is running under that id — it was never started, was stopped, or does not exist. These routes report an unstarted session as `404`, where the message and group routes report it as `400`."+ },+ "409": {+ "description": "The session is not connected — an engine exists for it but is not `ready`: disconnected, reconnecting, or still initializing, so the request never reached WhatsApp. Wait for `ready` and retry. A session that was never started answers `400` instead, and the session lifecycle routes answer `409` for a conflicting state rather than this. One window answers this while the session still reads `ready`: WhatsApp Web periodically reloads its own page and the engine re-injects into it — for those few seconds the answer is a `409` naming the reload; retry shortly."+ }+ },+ "summary": "Delete own status",+ "tags": [+ "status"+ ]}},"/api/sessions/{sessionId}/status/{statusId}/media": {@@ -7196,51 +7239,6 @@]}},- "/api/sessions/{sessionId}/status/{statusId}": {- "delete": {- "operationId": "StatusController_deleteStatus",- "parameters": [- {- "name": "sessionId",- "required": true,- "in": "path",- "schema": {- "type": "string"- }- },- {- "name": "statusId",- "required": true,- "in": "path",- "schema": {- "type": "string"- }- }- ],- "responses": {- "200": {- "description": "Status deleted.",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/StatusDeletedResponseDto"- }- }- }- },- "404": {- "description": "No session is running under that id — it was never started, was stopped, or does not exist. These routes report an unstarted session as `404`, where the message and group routes report it as `400`."- },- "409": {- "description": "The session is not connected — an engine exists for it but is not `ready`: disconnected, reconnecting, or still initializing, so the request never reached WhatsApp. Wait for `ready` and retry. A session that was never started answers `400` instead, and the session lifecycle routes answer `409` for a conflicting state rather than this. One window answers this while the session still reads `ready`: WhatsApp Web periodically reloads its own page and the engine re-injects into it — for those few seconds the answer is a `409` naming the reload; retry shortly."- }- },- "summary": "Delete own status",- "tags": [- "status"- ]- }- },"/api/sessions/{sessionId}/media/convert": {"get": {"operationId": "MediaController_conversionStatus",diff --git a/src/config/openapi-contract.spec.ts b/src/config/openapi-contract.spec.tsindex 662f4cafe..cecb12da2 100644--- a/src/config/openapi-contract.spec.ts+++ b/src/config/openapi-contract.spec.ts@@ -138,6 +138,22 @@ describe('openapi.json structural invariants', () => {expect(scanned.length).toBeGreaterThan(20);expect(bare).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+ // keys for one route split its operations across two Path Items, and a generator emits two+ // endpoints where the gateway has one.+ const byShape = new Map<string, string[]>();+ for (const route of Object.keys(doc.paths)) {+ const shape = route.replace(/\{[^}]*\}/g, '{}');+ byShape.set(shape, [...(byShape.get(shape) ?? []), route]);+ }++ // Guard the grouping: a document that somehow parsed to nothing must not pass silently.+ expect(byShape.size).toBeGreaterThan(100);+ expect([...byShape.values()].filter(routes => routes.length > 1)).toEqual([]);+ });});// The document is produced in TWO places: scripts/export-openapi.ts for the committed snapshot, anddiff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex ce6f398da..9fdeef0a6 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -369,9 +369,11 @@ export class SessionController {return this.sessionService.requestPairingCode(id, dto.phoneNumber);}- @Get(':id/groups')+ // `:sessionId`, not `:id`, so this shares a Path Item with GroupController's POST on the same+ // route. Two names for one positional segment split it into two contract entries.+ @Get(':sessionId/groups')@ApiOperation({ summary: 'Get all groups for a session' })- @ApiParam({ name: 'id', description: 'Session ID' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiResponse({status: 200,description: 'List of groups the session is a member of',@@ -389,7 +391,7 @@ export class SessionController {@ApiQuery({ name: 'limit', required: false, description: 'Max groups to return (1–1000, default 1000)' })@ApiQuery({ name: 'offset', required: false, description: 'Number of groups to skip (for paging)' })async getGroups(- @Param('id', ParseUUIDPipe) id: string,+ @Param('sessionId', ParseUUIDPipe) id: string,@Query('limit') limit?: string,@Query('offset') offset?: string,): Promise<{ id: string; name: string; linkedParentJID?: string | null }[]> {diff --git a/src/modules/status/status.controller.ts b/src/modules/status/status.controller.tsindex e5b8f89fd..62b6f299d 100644--- a/src/modules/status/status.controller.ts+++ b/src/modules/status/status.controller.ts@@ -1,6 +1,6 @@import { Controller, Get, Post, Delete, Param, Body, Res, StreamableFile } from '@nestjs/common';import type { Response } from 'express';-import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';+import { ApiTags, ApiOperation, ApiParam, ApiResponse } from '@nestjs/swagger';import { StatusDeletedResponseDto, StatusListResponseDto, StatusResultDto } from './dto/status-response.dto';import { StatusService } from './status.service';import { SendTextStatusDto } from './dto/send-text-status.dto';@@ -25,14 +25,18 @@ export class StatusController {return { statuses: await this.statusService.getStatuses(sessionId) };}- @Get(':contactId')+ // The segment is `:id` on both verbs because GET reads a contact's statuses and DELETE removes one+ // of our own. Naming it per verb gave the same route two contract entries; the meaning belongs in+ // @ApiParam, which is per-operation.+ @Get(':id')@ApiOperation({ summary: 'Get status updates from a specific contact' })+ @ApiParam({ name: 'id', description: 'Contact ID' })@ApiResponse({ status: 200, description: 'Status updates from the requested contact.', type: StatusListResponseDto })- async getContactStatus(@Param('sessionId') sessionId: string, @Param('contactId') contactId: string) {+ async getContactStatus(@Param('sessionId') sessionId: string, @Param('id') contactId: string) {return { statuses: await this.statusService.getContactStatus(sessionId, contactId) };}- // Two path segments (`:statusId/media`) never collides with the single-segment `:contactId`+ // Two path segments (`:statusId/media`) never collides with the single-segment `:id`// route above regardless of declaration order — Nest/Express match on segment count.@Get(':statusId/media')@ApiOperation({ summary: 'Stream a stored status media file' })@@ -146,13 +150,14 @@ export class StatusController {});}- @Delete(':statusId')+ @Delete(':id')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Delete own status' })+ @ApiParam({ name: 'id', description: 'Status ID' })@ApiResponse({ status: 200, description: 'Status deleted.', type: StatusDeletedResponseDto })@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiResponse({ status: 404, description: SESSION_NOT_STARTED_404 })- async deleteStatus(@Param('sessionId') sessionId: string, @Param('statusId') statusId: string) {+ async deleteStatus(@Param('sessionId') sessionId: string, @Param('id') statusId: string) {await this.statusService.deleteStatus(sessionId, statusId);return { message: 'Status deleted successfully' };}