Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(api-docs): OpenAPI snapshot export + auth-accurate Swagger metadata (#665)

Yudhi Armyndharis7175bb3a5104
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f82e8e3ba..faec4378c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Global message search across sessions.** `GET /api/search` finds messages across all sessions through an open `SearchProvider` contract, with a built-in database full-text provider (PostgreSQL `tsvector`/`GIN`, SQLite `FTS5`) as the zero-dependency default — no external service required. Search works out of the box on both SQLite and PostgreSQL and survives repeated dialect switching and export/import round-trips; a non-FTS5 SQLite build skips the index gracefully and the route returns `501` instead of crashing boot. Set `SEARCH_ENABLED=false` to disable the route and module entirely (the index is DB-maintained per-write regardless, at negligible in-process cost). Advanced backends (typo-tolerance, CJK word-segmentation, large-scale relevance) will be available as provider plugins.
- **`message:persisted` plugin hook.** A new general extension point fired when a message is durably persisted — on outbound send (from `MessageService`) and on inbound receive (from `SessionService`, where both engine adapters converge on the single persist) — so plugins can react to persisted messages (e.g. an external search indexer) without coupling to the message/session services. The built-in FTS search provider is DB-synced and does not consume this hook; it exists for plugin providers and general use. Fire-and-forget: a handler error is swallowed and never breaks the send/receive path.
- **Redis authentication via username.** Added support for `REDIS_USERNAME` to configure the Redis cache connection and BullMQ queue connections that require a username. Thanks @muhfalihr.
+- **OpenAPI/Swagger snapshot export + enriched, auth-accurate API docs.** The published spec (served at `/api/docs` and exportable via `scripts/export-openapi.ts`) now mirrors the runtime auth model: `@Public()` routes (`/api/health*`, `/api/infra/health`, and the integration ingress wildcard) are marked as not requiring an `X-API-Key`, matching what the `ApiKeyGuard` actually enforces. The `webhook` `events` enum now advertises the `*` subscribe-all wildcard the dispatch layer already honors, and request/response schemas are filled in across the catalog, status, stats, integration-instance, and auth endpoints — notably typing the integration `InstanceView` (and its `IngressUrl` entries) as real schemas so generated clients no longer receive opaque objects. The export script pins a hermetic environment (in-memory SQLite, queue/MCP off) so it is safe to run anywhere without touching a real database or opening a Redis connection.
## [0.8.11] - 2026-07-08
diff --git a/scripts/export-openapi.ts b/scripts/export-openapi.ts
new file mode 100644
index 000000000..bbb8c9db3
--- /dev/null
+++ b/scripts/export-openapi.ts
@@ -0,0 +1,60 @@
+// Generates the committed OpenAPI snapshot by bootstrapping the Nest app WITHOUT listening,
+// then calling SwaggerModule.createDocument(). The script pins a hermetic environment below
+// (in-memory SQLite, queue/MCP off) so it is safe to run anywhere: no DB files are created or
+// touched, no Redis connection is opened, no engines start, no sessions run. The version is
+// sourced from package.json via swagger.config.ts, so the snapshot tracks releases automatically.
+//
+// Usage: npx ts-node scripts/export-openapi.ts <output-path>
+import '../src/config/load-env';
+import { NestFactory } from '@nestjs/core';
+import { SwaggerModule } from '@nestjs/swagger';
+import { writeFileSync } from 'node:fs';
+import { createSwaggerConfig, 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
+// NestFactory.create() below — so these pins must win over whatever the loader applied above. That
+// is why AppModule is imported dynamically inside main(), after these assignments. (NestFactory.create
+// never calls init(), so onModuleInit / onApplicationBootstrap hooks — session autostart, the
+// PROCESSING-batch and message-type backfills — do not fire regardless; the pins are belt-and-braces.)
+process.env.QUEUE_ENABLED = 'false';
+process.env.MCP_ENABLED = 'false';
+process.env.AUTO_START_SESSIONS = 'false';
+process.env.DATABASE_TYPE = 'sqlite';
+process.env.DATABASE_NAME = ':memory:';
+process.env.MAIN_DATABASE_NAME = ':memory:';
+
+async function main() {
+ // Operator-supplied CLI path — this is a local dev/CI tool, not a network service, so there is
+ // no trust boundary to enforce (the caller already has full filesystem access). No path
+ // validation is applied by design; restricting writes to cwd would break legitimate out-of-tree
+ // snapshot writes, which the documented usage explicitly allows.
+ const out = process.argv[2];
+ if (!out) {
+ console.error('Usage: npx ts-node scripts/export-openapi.ts <output-path>');
+ process.exit(1);
+ }
+ // Imported after the env pins above so AppModule's top-level reads the hermetic values. Uses
+ // require() (not a dynamic import()) so ts-node's CommonJS hook resolves the .ts directly — a
+ // native import() would fail with ERR_MODULE_NOT_FOUND under ts-node CJS.
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const { AppModule } = require('../src/app.module');
+ // Bootstrap the full DI graph so every controller/DTO is discovered, but never listen.
+ // Errors/warns only — bootstrap is chatty and we only need the document.
+ const app = await NestFactory.create(AppModule, { logger: ['error', 'warn'] });
+ // Mirror main.ts: the global /api prefix is part of the real route paths the docs publish.
+ app.setGlobalPrefix('api');
+ try {
+ const doc = SwaggerModule.createDocument(app, createSwaggerConfig());
+ 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)`);
+ } finally {
+ await app.close();
+ }
+}
+
+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.ts
index b5e532410..b7e6cd4e1 100644
--- a/src/config/swagger.config.spec.ts
+++ b/src/config/swagger.config.spec.ts
@@ -1,4 +1,7 @@
-import { createSwaggerConfig } from './swagger.config';
+import * as fs from 'fs';
+import * as path from 'path';
+import { createSwaggerConfig, exemptPublicOperations, PUBLIC_PATHS } from './swagger.config';
+import type { OpenAPIObject } from '@nestjs/swagger';
describe('createSwaggerConfig', () => {
// Regression test for issue #104: Swagger UI returned "Unauthorized" because the
@@ -10,3 +13,87 @@ describe('createSwaggerConfig', () => {
expect(config.security).toContainEqual({ 'X-API-Key': [] });
});
});
+
+describe('exemptPublicOperations', () => {
+ // Minimal fixture: one listed public path with two operations, one protected path.
+ function fixtureDoc(): OpenAPIObject {
+ return {
+ openapi: '3.0.0',
+ info: { title: 't', version: '0' },
+ paths: {
+ '/api/health': { get: {}, post: {} },
+ '/api/sessions': { get: {} },
+ },
+ components: {},
+ } as unknown as OpenAPIObject;
+ }
+
+ it('clears security on every operation of a listed public path', () => {
+ const doc = exemptPublicOperations(fixtureDoc());
+
+ expect(doc.paths['/api/health'].get?.security).toEqual([]);
+ expect(doc.paths['/api/health'].post?.security).toEqual([]);
+ });
+
+ it('leaves non-public paths untouched (they inherit the global requirement)', () => {
+ const doc = exemptPublicOperations(fixtureDoc());
+
+ expect(doc.paths['/api/sessions'].get?.security).toBeUndefined();
+ });
+
+ it('does not throw when a listed path is absent from the document (stale entry is skipped)', () => {
+ const doc = fixtureDoc();
+ delete doc.paths['/api/health'];
+
+ expect(() => exemptPublicOperations(doc)).not.toThrow();
+ });
+});
+
+// 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 —
+// add a controller here AND its path(s) to PUBLIC_PATHS when you mark a new route @Public();
+// (2) PUBLIC_PATHS must contain the expected entries (catches a typo or accidental removal).
+// MetricsController is @Public() but uses @ApiExcludeEndpoint, so it never appears in the spec and
+// is intentionally exempt from PUBLIC_PATHS.
+describe('PUBLIC_PATHS drift guard', () => {
+ const EXPECTED_PUBLIC_CONTROLLERS = [
+ 'src/modules/health/health.controller.ts',
+ 'src/modules/infra/infra.controller.ts',
+ 'src/modules/integration/ingress.controller.ts',
+ 'src/modules/metrics/metrics.controller.ts',
+ ];
+
+ function listTsFiles(dir: string, out: string[] = []): string[] {
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const full = path.join(dir, entry.name).replace(/\\/g, '/');
+ if (entry.isDirectory()) listTsFiles(full, out);
+ else if (entry.name.endsWith('.ts')) out.push(full);
+ }
+ return out;
+ }
+
+ it('every controller using @Public() is accounted for in EXPECTED_PUBLIC_CONTROLLERS', () => {
+ const srcRoot = path.resolve(__dirname, '..').replace(/\\/g, '/');
+ // Match only a line that is exactly `@Public()` — ignores the decorator's doc comment
+ // (`@example @Public()`) and test/string occurrences.
+ const usingPublic = listTsFiles(srcRoot)
+ .filter(f => /^\s*@Public\(\)\s*$/m.test(fs.readFileSync(f, 'utf8')))
+ .map(f => f.replace(/^.*\/src\//, 'src/'))
+ .sort();
+
+ expect(usingPublic).toEqual([...EXPECTED_PUBLIC_CONTROLLERS].sort());
+ });
+
+ it('PUBLIC_PATHS contains the expected @Public route paths', () => {
+ expect(PUBLIC_PATHS).toEqual(
+ expect.arrayContaining([
+ '/api/health',
+ '/api/health/live',
+ '/api/health/ready',
+ '/api/infra/health',
+ '/api/ingress/{pluginId}/{instanceId}/{path}',
+ ]),
+ );
+ });
+});
diff --git a/src/config/swagger.config.ts b/src/config/swagger.config.ts
index ce683d33c..c952f9f54 100644
--- a/src/config/swagger.config.ts
+++ b/src/config/swagger.config.ts
@@ -6,6 +6,38 @@ import { DocumentBuilder, OpenAPIObject } from '@nestjs/swagger';
*/
export const API_KEY_SECURITY_SCHEME = 'X-API-Key';
+// Routes whose controllers are @Public() — the ApiKeyGuard skips them at runtime, but the
+// global X-API-Key requirement applied below would otherwise make the spec claim they need a
+// key. Mirror the @Public() decorators: add a path here when you add one there.
+export const PUBLIC_PATHS = [
+ '/api/health',
+ '/api/health/live',
+ '/api/health/ready',
+ '/api/infra/health',
+ '/api/ingress/{pluginId}/{instanceId}/{path}',
+];
+
+const HTTP_METHODS = ['get', 'post', 'put', 'delete', 'patch', 'options', 'head', 'trace', 'search'] as const;
+
+type PathItem = Record<string, { security?: unknown } | undefined>;
+
+/**
+ * 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
+ * X-API-Key requirement per OpenAPI 3). Mutates and returns the document.
+ */
+export function exemptPublicOperations(document: OpenAPIObject): OpenAPIObject {
+ for (const path of PUBLIC_PATHS) {
+ const item = document.paths?.[path] as PathItem | undefined;
+ if (!item) continue;
+ for (const method of HTTP_METHODS) {
+ const op = item[method];
+ if (op) op.security = [];
+ }
+ }
+ return document;
+}
+
/**
* Builds the OpenAPI document configuration for the OpenWA API.
*/
@@ -22,6 +54,7 @@ export function createSwaggerConfig(): Omit<OpenAPIObject, 'paths'> {
// Apply the scheme globally so Swagger UI sends the key with every request
// (mirrors the global ApiKeyGuard). Without this, "Authorize" is cosmetic.
.addSecurityRequirements(API_KEY_SECURITY_SCHEME)
+ .setContact('OpenWA', 'https://github.com/rmyndharis/OpenWA', '[email protected]')
.addTag('sessions', 'WhatsApp session management')
.addTag('messages', 'Send and manage messages')
.addTag('webhooks', 'Webhook configuration')
diff --git a/src/main.ts b/src/main.ts
index 7c7947cae..d89df4894 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -10,7 +10,7 @@ import helmet from 'helmet';
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 } from './config/swagger.config';
+import { createSwaggerConfig, exemptPublicOperations } from './config/swagger.config';
import { registerUncaughtExceptionMonitor } from './config/process-error-monitor';
import {
resolveCorsPolicy,
@@ -222,6 +222,7 @@ async function bootstrap() {
if (swaggerEnabled) {
const config = createSwaggerConfig();
const document = SwaggerModule.createDocument(app, config);
+ exemptPublicOperations(document);
SwaggerModule.setup('api/docs', app, document);
}
diff --git a/src/modules/auth/auth.controller.ts b/src/modules/auth/auth.controller.ts
index 7d7704b5b..aba764ccd 100644
--- a/src/modules/auth/auth.controller.ts
+++ b/src/modules/auth/auth.controller.ts
@@ -67,7 +67,11 @@ export class AuthController {
@Get()
@RequireRole(ApiKeyRole.ADMIN)
@ApiOperation({ summary: 'List all API keys (admin only)' })
- @ApiResponse({ status: 200, type: [ApiKeyResponseDto] })
+ @ApiResponse({
+ status: 200,
+ description: 'All API keys (the plaintext key is never returned; only the keyPrefix).',
+ type: [ApiKeyResponseDto],
+ })
async findAll(): Promise<ApiKeyResponseDto[]> {
const keys = await this.authService.findAll();
return keys.map(k => ({
@@ -88,7 +92,11 @@ export class AuthController {
@Get(':id')
@RequireRole(ApiKeyRole.ADMIN)
@ApiOperation({ summary: 'Get API key details (admin only)' })
- @ApiResponse({ status: 200, type: ApiKeyResponseDto })
+ @ApiResponse({
+ status: 200,
+ description: 'The API key (plaintext never returned; only the keyPrefix).',
+ type: ApiKeyResponseDto,
+ })
async findOne(@Param('id') id: string): Promise<ApiKeyResponseDto> {
const k = await this.authService.findOne(id);
return {
@@ -109,7 +117,7 @@ export class AuthController {
@Put(':id')
@RequireRole(ApiKeyRole.ADMIN)
@ApiOperation({ summary: 'Update API key (admin only)' })
- @ApiResponse({ status: 200, type: ApiKeyResponseDto })
+ @ApiResponse({ status: 200, description: 'The updated API key.', type: ApiKeyResponseDto })
async update(@Param('id') id: string, @Body() dto: UpdateApiKeyDto): Promise<ApiKeyResponseDto> {
const k = await this.authService.update(id, dto);
return {
@@ -144,7 +152,7 @@ export class AuthController {
@Post(':id/revoke')
@RequireRole(ApiKeyRole.ADMIN)
@ApiOperation({ summary: 'Revoke API key (admin only)' })
- @ApiResponse({ status: 200, type: ApiKeyResponseDto })
+ @ApiResponse({ status: 200, description: 'The revoked API key (isActive now false).', type: ApiKeyResponseDto })
async revoke(
@Param('id') id: string,
@Req() req: Request,
diff --git a/src/modules/catalog/catalog.controller.ts b/src/modules/catalog/catalog.controller.ts
index 9d24548d3..c243d0e61 100644
--- a/src/modules/catalog/catalog.controller.ts
+++ b/src/modules/catalog/catalog.controller.ts
@@ -1,5 +1,5 @@
import { Controller, Get, Post, Param, Body, Query } from '@nestjs/common';
-import { ApiTags, ApiOperation } from '@nestjs/swagger';
+import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { CatalogService } from './catalog.service';
import { SendProductDto, SendCatalogDto, ProductQueryDto } from './dto/send-product.dto';
import { RequireRole } from '../auth/decorators/auth.decorators';
@@ -12,18 +12,21 @@ export class CatalogController {
@Get('catalog')
@ApiOperation({ summary: 'Get business catalog info' })
+ @ApiResponse({ status: 200, description: 'Business catalog metadata for the session.' })
async getCatalog(@Param('sessionId') sessionId: string) {
return this.catalogService.getCatalog(sessionId);
}
@Get('catalog/products')
@ApiOperation({ summary: 'List catalog products' })
+ @ApiResponse({ status: 200, description: 'Paginated list of catalog products.' })
async getProducts(@Param('sessionId') sessionId: string, @Query() query: ProductQueryDto) {
return this.catalogService.getProducts(sessionId, query.page, query.limit);
}
@Get('catalog/products/:productId')
@ApiOperation({ summary: 'Get a specific product' })
+ @ApiResponse({ status: 200, description: 'The requested catalog product.' })
async getProduct(@Param('sessionId') sessionId: string, @Param('productId') productId: string) {
return this.catalogService.getProduct(sessionId, productId);
}
@@ -31,6 +34,7 @@ export class CatalogController {
@Post('messages/send-product')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Send a product message' })
+ @ApiResponse({ status: 201, description: 'Product message sent.' })
async sendProduct(@Param('sessionId') sessionId: string, @Body() dto: SendProductDto) {
return this.catalogService.sendProduct(sessionId, dto.chatId, dto.productId, dto.body);
}
@@ -38,6 +42,7 @@ export class CatalogController {
@Post('messages/send-catalog')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Send catalog link' })
+ @ApiResponse({ status: 201, description: 'Catalog link sent.' })
async sendCatalog(@Param('sessionId') sessionId: string, @Body() dto: SendCatalogDto) {
return this.catalogService.sendCatalog(sessionId, dto.chatId, dto.body);
}
diff --git a/src/modules/catalog/dto/send-product.dto.ts b/src/modules/catalog/dto/send-product.dto.ts
index b4594fbdb..ed66240be 100644
--- a/src/modules/catalog/dto/send-product.dto.ts
+++ b/src/modules/catalog/dto/send-product.dto.ts
@@ -1,34 +1,45 @@
import { IsString, IsOptional, IsInt, Min } from 'class-validator';
import { Type } from 'class-transformer';
+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
export class SendProductDto {
+ @ApiProperty({ description: 'Chat to send the product card to (@c.us or @g.us).', example: '[email protected]' })
@IsString()
chatId: string;
+ @ApiProperty({ description: 'Catalog product id to send.', example: 'product-42' })
@IsString()
productId: string;
+ @ApiPropertyOptional({ description: 'Optional body text accompanying the product card.', example: 'Back in stock!' })
@IsOptional()
@IsString()
body?: string;
}
export class SendCatalogDto {
+ @ApiProperty({ description: 'Chat to send the catalog to (@c.us or @g.us).', example: '[email protected]' })
@IsString()
chatId: string;
+ @ApiPropertyOptional({
+ description: 'Optional body text accompanying the catalog.',
+ example: 'Browse our full catalog',
+ })
@IsOptional()
@IsString()
body?: string;
}
export class ProductQueryDto {
+ @ApiPropertyOptional({ description: 'Result page (1-based).', example: 1, minimum: 1 })
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
page?: number = 1;
+ @ApiPropertyOptional({ description: 'Page size.', example: 20, minimum: 1 })
@IsOptional()
@Type(() => Number)
@IsInt()
diff --git a/src/modules/group/group.controller.ts b/src/modules/group/group.controller.ts
index cead7bd87..60551094a 100644
--- a/src/modules/group/group.controller.ts
+++ b/src/modules/group/group.controller.ts
@@ -1,32 +1,19 @@
-import { Controller, Get, Post, Put, Delete, Param, Query, Body, HttpCode, HttpStatus } from '@nestjs/common';
-import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiBody, ApiQuery } from '@nestjs/swagger';
+import { Controller, Get, Post, Put, Delete, Param, Body, HttpCode, HttpStatus } from '@nestjs/common';
+import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiBody } from '@nestjs/swagger';
import { GroupService } from './group.service';
import { CreateGroupDto, ParticipantsDto, GroupSubjectDto, GroupDescriptionDto } from './dto/group.dto';
import { RequireRole } from '../auth/decorators/auth.decorators';
import { ApiKeyRole } from '../auth/entities/api-key.entity';
+// NOTE: the session→groups LIST lives on the SessionController at GET /sessions/:id/groups (it
+// registered first and owns the canonical narrow projection). A bare @Get() here would collide on
+// the same path pattern (/sessions/{x}/groups) and be shadowed, so this controller owns only the
+// group sub-resource routes (:groupId/...) under the same mount.
@ApiTags('groups')
@Controller('sessions/:sessionId/groups')
export class GroupController {
constructor(private readonly groupService: GroupService) {}
- @Get()
- @ApiOperation({ summary: 'Get all groups for a session' })
- @ApiParam({ name: 'sessionId', description: 'Session ID' })
- @ApiResponse({ status: 200, description: 'List of groups' })
- @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 findAll(
- @Param('sessionId') sessionId: string,
- @Query('limit') limit?: string,
- @Query('offset') offset?: string,
- ) {
- return this.groupService.getGroups(sessionId, {
- limit: limit ? parseInt(limit, 10) : undefined,
- offset: offset ? parseInt(offset, 10) : undefined,
- });
- }
-
@Get(':groupId')
@ApiOperation({ summary: 'Get detailed group info' })
@ApiParam({ name: 'sessionId', description: 'Session ID' })
diff --git a/src/modules/integration/dto/instance.dto.ts b/src/modules/integration/dto/instance.dto.ts
index 50d2a2390..f0d9435fa 100644
--- a/src/modules/integration/dto/instance.dto.ts
+++ b/src/modules/integration/dto/instance.dto.ts
@@ -1,20 +1,34 @@
import { IsBoolean, IsNotEmpty, IsObject, IsOptional, IsString, Matches, MaxLength, MinLength } from 'class-validator';
+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IngressUrl } from '../ingress-url';
// Safe charset: also prevents an instanceId containing ':' (which would collide the P1 ordering key).
const INSTANCE_ID_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
export class CreateInstanceDto {
+ @ApiProperty({
+ description:
+ 'Operator-chosen instance id (unique within the plugin). Namespaces the ingress URL and the instance secret.',
+ example: 'chatwoot-prod-1',
+ })
@IsString()
@Matches(INSTANCE_ID_PATTERN, { message: 'instanceId must match ^[a-zA-Z0-9_-]{1,64}$' })
instanceId: string;
+ @ApiPropertyOptional({
+ description: 'Session id the instance is scoped to. Omit for all sessions.',
+ example: '8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a',
+ })
@IsOptional()
@IsString()
@IsNotEmpty({ message: 'sessionScope must not be empty (omit it for all sessions)' })
@MaxLength(256)
sessionScope?: string;
+ @ApiPropertyOptional({
+ description: 'Token echoed back for the provider webhook verification handshake. Auto-generated when omitted.',
+ example: 'a1b2c3d4e5f6',
+ })
@IsOptional()
@IsString()
@MaxLength(512)
@@ -23,44 +37,100 @@ export class CreateInstanceDto {
// Operator-supplied ingress HMAC secret (e.g. the provider's webhook secret). When present it must be
// a real value (>= 16 chars) — an empty/short secret would make the public ingress signature forgeable.
// Omit to auto-generate a random 64-hex secret.
+ @ApiPropertyOptional({
+ description:
+ 'Ingress HMAC secret shared with the provider. Omit to auto-generate a random 64-hex secret. Masked (****) on every read.',
+ writeOnly: true,
+ example: 'super-secret-provider-webhook-key',
+ })
@IsOptional()
@IsString()
@MinLength(16, { message: 'secret must be at least 16 characters' })
@MaxLength(512)
secret?: string;
+ @ApiPropertyOptional({
+ description: 'Per-instance config slice passed to the adapter (shape defined by the plugin).',
+ example: { apiKey: 'chatwoot-key', inboxId: 42 },
+ })
@IsOptional()
@IsObject()
config?: Record<string, unknown>;
}
export class UpdateInstanceDto {
+ @ApiPropertyOptional({
+ description: 'Whether the instance is enabled (ingress accepted, dispatch active).',
+ example: true,
+ })
@IsOptional()
@IsBoolean()
enabled?: boolean;
+ @ApiPropertyOptional({ description: 'Session id the instance is scoped to. Omit for all sessions.' })
@IsOptional()
@IsString()
@IsNotEmpty({ message: 'sessionScope must not be empty (omit it for all sessions)' })
@MaxLength(256)
sessionScope?: string;
+ @ApiPropertyOptional({ description: 'Per-instance config slice passed to the adapter.' })
@IsOptional()
@IsObject()
config?: Record<string, unknown>;
}
-export interface InstanceView {
+// A class (not an interface) so @nestjs/swagger can reflect it into the published spec — the
+// integration-instance responses are otherwise opaque to generated clients.
+export class InstanceView {
+ @ApiProperty({ description: 'Instance row id.' })
id: string;
+
+ @ApiProperty({ description: 'Plugin id this instance belongs to.' })
pluginId: string;
+
+ @ApiProperty({ description: 'Operator-chosen instance id (unique within the plugin).' })
instanceId: string;
+
+ @ApiPropertyOptional({
+ description: 'Session id the instance is scoped to, or null for all sessions.',
+ nullable: true,
+ })
sessionScope: string | null;
- secret: string; // masked ('***') on reads
- verifyToken: string | null; // masked ('***') on reads when set
+
+ @ApiProperty({
+ description:
+ "Ingress HMAC secret. Masked ('***') on every read; plaintext returned only once on create/regenerate-secret.",
+ })
+ secret: string;
+
+ @ApiPropertyOptional({
+ description: "Provider verify-token. Masked ('***') on reads when set; plaintext on create/regenerate-secret.",
+ nullable: true,
+ })
+ verifyToken: string | null;
+
+ @ApiPropertyOptional({
+ description: 'Per-instance config slice passed to the adapter, or null.',
+ nullable: true,
+ type: Object,
+ })
config: Record<string, unknown> | null;
+
+ @ApiProperty({ description: 'Whether ingress is accepted and dispatch is active.' })
enabled: boolean;
+
+ @ApiProperty({ description: 'Creation timestamp.' })
createdAt: Date;
+
+ @ApiProperty({ description: 'Last update timestamp.' })
updatedAt: Date;
+
+ @ApiProperty({
+ description: 'Ingress URLs the provider posts webhook deliveries to.',
+ type: () => IngressUrl,
+ isArray: true,
+ })
ingressUrls: IngressUrl[];
}
diff --git a/src/modules/integration/ingress-url.ts b/src/modules/integration/ingress-url.ts
index 60fa24032..1603ee79e 100644
--- a/src/modules/integration/ingress-url.ts
+++ b/src/modules/integration/ingress-url.ts
@@ -1,5 +1,12 @@
-export interface IngressUrl {
+import { ApiProperty } from '@nestjs/swagger';
+
+export class IngressUrl {
+ @ApiProperty({ description: 'Plugin-declared route segment the provider posts to.' })
route: string;
+
+ @ApiProperty({
+ description: 'Full ingress URL (BASE_URL + plugin/instance/route), or a relative path when BASE_URL is unset.',
+ })
url: string;
}
diff --git a/src/modules/integration/ingress.controller.ts b/src/modules/integration/ingress.controller.ts
index 37add8cc6..6f2901a95 100644
--- a/src/modules/integration/ingress.controller.ts
+++ b/src/modules/integration/ingress.controller.ts
@@ -1,5 +1,5 @@
import { All, Controller, Param, Query, Req, Res, UseGuards } from '@nestjs/common';
-import { ApiTags } from '@nestjs/swagger';
+import { ApiTags, ApiOkResponse, ApiResponse } from '@nestjs/swagger';
import type { Request, Response } from 'express';
import { Public } from '../auth/decorators/auth.decorators';
import { IngressService } from './ingress.service';
@@ -28,6 +28,19 @@ export class IngressController {
// InstanceThrottlerGuard's onModuleInit for how it keeps its tier fully independent.
@UseGuards(InstanceThrottlerGuard)
@All(':pluginId/:instanceId/*path')
+ @ApiOkResponse({
+ description:
+ 'GET verification challenge echo, or a duplicate delivery already persisted (idempotent re-delivery). Not the primary success path — see 202.',
+ })
+ @ApiResponse({
+ status: 202,
+ description: 'Webhook accepted and queued for async plugin processing (the primary success path).',
+ })
+ @ApiResponse({ status: 401, description: 'Signature verification failed (missing, stale, or wrong secret).' })
+ @ApiResponse({ status: 403, description: 'GET verification challenge failed (verifyToken mismatch).' })
+ @ApiResponse({ status: 404, description: 'Unknown pluginId/instanceId, or no route claimed by the plugin.' })
+ @ApiResponse({ status: 413, description: 'Request body exceeds the route maxBodyBytes limit.' })
+ @ApiResponse({ status: 429, description: 'Per-instance rate limit exceeded (INGRESS_INSTANCE_LIMIT).' })
async receive(
@Param('pluginId') pluginId: string,
@Param('instanceId') instanceId: string,
diff --git a/src/modules/integration/integration-instance.controller.ts b/src/modules/integration/integration-instance.controller.ts
index 49fb227c1..50928b408 100644
--- a/src/modules/integration/integration-instance.controller.ts
+++ b/src/modules/integration/integration-instance.controller.ts
@@ -21,7 +21,7 @@ import { ScopeBindingService } from './scope-binding.service';
import { PluginInstance } from './entities/plugin-instance.entity';
import { buildIngressUrls } from './ingress-url';
import { CreateInstanceDto, InstanceView, UpdateInstanceDto } from './dto/instance.dto';
-import { ApiTags } from '@nestjs/swagger';
+import { ApiTags, ApiResponse } from '@nestjs/swagger';
// ADMIN-only provisioning surface for per-plugin instances (e.g. one Chatwoot account). Only plugins
// that declare an ingress route AND the webhook:ingress permission can have instances; everything
@@ -39,6 +39,12 @@ export class IntegrationInstanceController {
@Post()
@HttpCode(201)
+ @ApiResponse({
+ status: 201,
+ description:
+ 'Instance created. The plaintext ingress secret and verifyToken are revealed once in this response — store them immediately (both masked on every later read).',
+ type: InstanceView,
+ })
async create(@Param('pluginId') pluginId: string, @Body() dto: CreateInstanceDto): Promise<InstanceView> {
const routes = this.assertIngressCapable(pluginId);
try {
@@ -60,6 +66,7 @@ export class IntegrationInstanceController {
}
@Get()
+ @ApiResponse({ status: 200, description: 'Instances for the plugin (secrets masked).', type: [InstanceView] })
async list(@Param('pluginId') pluginId: string): Promise<InstanceView[]> {
const routes = this.pluginRoutes(pluginId);
const rows = await this.instances.list(pluginId);
@@ -67,6 +74,7 @@ export class IntegrationInstanceController {
}
@Get(':instanceId')
+ @ApiResponse({ status: 200, description: 'The instance (secret masked).', type: InstanceView })
async getOne(@Param('pluginId') pluginId: string, @Param('instanceId') instanceId: string): Promise<InstanceView> {
const inst = await this.instances.resolve(pluginId, instanceId);
if (!inst) throw new NotFoundException('instance not found');
@@ -75,6 +83,12 @@ export class IntegrationInstanceController {
@Post(':instanceId/regenerate-secret')
@HttpCode(200)
+ @ApiResponse({
+ status: 200,
+ description:
+ 'Secret regenerated. The new plaintext secret is revealed once in this response; the verifyToken is also shown (unchanged).',
+ type: InstanceView,
+ })
async regenerate(
@Param('pluginId') pluginId: string,
@Param('instanceId') instanceId: string,
@@ -88,6 +102,7 @@ export class IntegrationInstanceController {
}
@Patch(':instanceId')
+ @ApiResponse({ status: 200, description: 'Instance updated (secret masked).', type: InstanceView })
async patch(
@Param('pluginId') pluginId: string,
@Param('instanceId') instanceId: string,
@@ -118,6 +133,7 @@ export class IntegrationInstanceController {
@Delete(':instanceId')
@HttpCode(204)
+ @ApiResponse({ status: 204, description: 'Instance deleted and its session scope torn down.' })
async remove(@Param('pluginId') pluginId: string, @Param('instanceId') instanceId: string): Promise<void> {
const inst = await this.instances.resolve(pluginId, instanceId);
if (!inst) throw new NotFoundException('instance not found');
diff --git a/src/modules/integration/redrive.controller.ts b/src/modules/integration/redrive.controller.ts
index cb00a1bcf..f818a33c8 100644
--- a/src/modules/integration/redrive.controller.ts
+++ b/src/modules/integration/redrive.controller.ts
@@ -1,5 +1,5 @@
import { Controller, Param, Post } from '@nestjs/common';
-import { ApiTags } from '@nestjs/swagger';
+import { ApiTags, ApiResponse } from '@nestjs/swagger';
import { RequireRole } from '../auth/decorators/auth.decorators';
import { ApiKeyRole } from '../auth/entities/api-key.entity';
import { RedriveService } from './redrive.service';
@@ -14,6 +14,10 @@ export class RedriveController {
constructor(private readonly redrive: RedriveService) {}
@Post(':pluginId/:instanceId/redrive')
+ @ApiResponse({
+ status: 201,
+ description: 'Dead-lettered ingress deliveries for the instance re-dispatched. Returns the count redriven.',
+ })
redriveInstance(
@Param('pluginId') pluginId: string,
@Param('instanceId') instanceId: string,
diff --git a/src/modules/session/dto/session-response.dto.ts b/src/modules/session/dto/session-response.dto.ts
index d16f99c5f..7c7a75a4e 100644
--- a/src/modules/session/dto/session-response.dto.ts
+++ b/src/modules/session/dto/session-response.dto.ts
@@ -12,16 +12,16 @@ export class SessionResponseDto {
@ApiProperty({ enum: SessionStatus, example: SessionStatus.READY })
status: SessionStatus;
- @ApiPropertyOptional({ example: '628123456789' })
+ @ApiPropertyOptional({ type: String, example: '628123456789', nullable: true })
phone?: string | null;
- @ApiPropertyOptional({ example: 'John Doe' })
+ @ApiPropertyOptional({ type: String, example: 'John Doe', nullable: true })
pushName?: string | null;
- @ApiPropertyOptional({ example: '2025-02-02T10:00:00Z' })
+ @ApiPropertyOptional({ type: String, format: 'date-time', example: '2025-02-02T10:00:00Z', nullable: true })
connectedAt?: Date | null;
- @ApiPropertyOptional({ example: '2025-02-02T10:30:00Z' })
+ @ApiPropertyOptional({ type: String, format: 'date-time', example: '2025-02-02T10:30:00Z', nullable: true })
lastActive?: Date | null;
@ApiProperty({ example: '2025-02-02T09:00:00Z' })
@@ -31,8 +31,10 @@ export class SessionResponseDto {
updatedAt: Date;
@ApiPropertyOptional({
+ type: String,
description: 'Human-readable reason for the most recent terminal engine failure (only set when status is FAILED).',
example: 'Failed to launch the browser process: spawn /usr/bin/chromium ENOENT',
+ nullable: true,
})
lastError?: string | null;
diff --git a/src/modules/stats/stats.controller.ts b/src/modules/stats/stats.controller.ts
index 2e60436a6..68a83df0e 100644
--- a/src/modules/stats/stats.controller.ts
+++ b/src/modules/stats/stats.controller.ts
@@ -1,5 +1,5 @@
import { Controller, Get, Param, Query } from '@nestjs/common';
-import { ApiTags, ApiOperation } from '@nestjs/swagger';
+import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { StatsService } from './stats.service';
import { StatsQueryDto } from './dto/stats-query.dto';
import { RequireRole } from '../auth/decorators/auth.decorators';
@@ -15,6 +15,7 @@ export class StatsController {
@Get('overview')
@RequireRole(ApiKeyRole.ADMIN)
@ApiOperation({ summary: 'Get overall statistics' })
+ @ApiResponse({ status: 200, description: 'Cross-session aggregate statistics (sessions, messages, etc.).' })
async getOverview() {
return this.statsService.getOverview();
}
@@ -22,12 +23,14 @@ export class StatsController {
@Get('messages')
@RequireRole(ApiKeyRole.ADMIN)
@ApiOperation({ summary: 'Get message statistics with time series' })
+ @ApiResponse({ status: 200, description: 'Message statistics with a time series for the requested period.' })
async getMessageStats(@Query() query: StatsQueryDto) {
return this.statsService.getMessageStats(query.period || '24h');
}
@Get('sessions/:sessionId')
@ApiOperation({ summary: 'Get statistics for a specific session' })
+ @ApiResponse({ status: 200, description: 'Per-session statistics for the requested session.' })
async getSessionStats(@Param('sessionId') sessionId: string) {
return this.statsService.getSessionStats(sessionId);
}
diff --git a/src/modules/status/dto/send-media-status.dto.ts b/src/modules/status/dto/send-media-status.dto.ts
index 3ff5dfcee..d10ef1b3f 100644
--- a/src/modules/status/dto/send-media-status.dto.ts
+++ b/src/modules/status/dto/send-media-status.dto.ts
@@ -9,31 +9,51 @@ import {
MaxLength,
} from 'class-validator';
import { Type } from 'class-transformer';
+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
class StatusMediaInput {
+ @ApiPropertyOptional({
+ description: 'Public http(s) URL of the media (server-fetched, SSRF-guarded).',
+ example: 'https://example.com/banner.jpg',
+ })
@IsOptional()
@IsString()
url?: string;
+ @ApiPropertyOptional({
+ description: 'Base64-encoded media. Requires mimetype.',
+ example: 'data:image/jpeg;base64,...',
+ })
@IsOptional()
@IsString()
base64?: string;
+ @ApiPropertyOptional({ description: 'MIME type. Required when sending base64.', example: 'image/jpeg' })
@IsOptional()
@IsString()
mimetype?: string;
}
export class SendImageStatusDto {
+ @ApiProperty({ description: 'Image source (URL or base64).', type: StatusMediaInput })
@ValidateNested()
@Type(() => StatusMediaInput)
image: StatusMediaInput;
+ @ApiPropertyOptional({ description: 'Optional caption.', example: 'New drop!', maxLength: 1024 })
@IsOptional()
@IsString()
@MaxLength(1024)
caption?: string;
+ @ApiProperty({
+ description: 'Recipient JIDs (1–256), @c.us or @lid.',
+ type: String,
+ isArray: true,
+ example: ['[email protected]'],
+ minItems: 1,
+ maxItems: 256,
+ })
@IsArray()
@ArrayMinSize(1)
@ArrayMaxSize(256)
@@ -43,15 +63,25 @@ export class SendImageStatusDto {
}
export class SendVideoStatusDto {
+ @ApiProperty({ description: 'Video source (URL or base64).', type: StatusMediaInput })
@ValidateNested()
@Type(() => StatusMediaInput)
video: StatusMediaInput;
+ @ApiPropertyOptional({ description: 'Optional caption.', example: 'Demo', maxLength: 1024 })
@IsOptional()
@IsString()
@MaxLength(1024)
caption?: string;
+ @ApiProperty({
+ description: 'Recipient JIDs (1–256), @c.us or @lid.',
+ type: String,
+ isArray: true,
+ example: ['[email protected]'],
+ minItems: 1,
+ maxItems: 256,
+ })
@IsArray()
@ArrayMinSize(1)
@ArrayMaxSize(256)
diff --git a/src/modules/status/dto/send-text-status.dto.ts b/src/modules/status/dto/send-text-status.dto.ts
index 598182f85..10b7963eb 100644
--- a/src/modules/status/dto/send-text-status.dto.ts
+++ b/src/modules/status/dto/send-text-status.dto.ts
@@ -10,23 +10,35 @@ import {
ArrayMinSize,
ArrayMaxSize,
} from 'class-validator';
+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
export class SendTextStatusDto {
+ @ApiProperty({ description: 'Status text body.', example: 'Out for delivery 📦', maxLength: 4096 })
@IsString()
@MaxLength(4096)
text: string;
+ @ApiPropertyOptional({ description: 'Background color (hex).', example: '#25D366' })
@IsOptional()
@IsString()
@Matches(/^#[0-9A-Fa-f]{6}$/, { message: 'backgroundColor must be a hex color (e.g., #25D366)' })
backgroundColor?: string;
+ @ApiPropertyOptional({ description: 'Font family index (0–5).', example: 0, minimum: 0, maximum: 5 })
@IsOptional()
@IsInt()
@Min(0)
@Max(5)
font?: number;
+ @ApiProperty({
+ description: 'Recipient JIDs (1–256). WhatsApp Status is not posted to a group — use @c.us or @lid individuals.',
+ type: String,
+ isArray: true,
+ example: ['[email protected]'],
+ minItems: 1,
+ maxItems: 256,
+ })
@IsArray()
@ArrayMinSize(1)
@ArrayMaxSize(256)
diff --git a/src/modules/status/status.controller.ts b/src/modules/status/status.controller.ts
index 127514dba..5e612f1cc 100644
--- a/src/modules/status/status.controller.ts
+++ b/src/modules/status/status.controller.ts
@@ -1,5 +1,5 @@
import { Controller, Get, Post, Delete, Param, Body } from '@nestjs/common';
-import { ApiTags, ApiOperation } from '@nestjs/swagger';
+import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { StatusService } from './status.service';
import { SendTextStatusDto } from './dto/send-text-status.dto';
import { SendImageStatusDto, SendVideoStatusDto } from './dto/send-media-status.dto';
@@ -13,12 +13,14 @@ export class StatusController {
@Get()
@ApiOperation({ summary: 'Get all contact status updates' })
+ @ApiResponse({ status: 200, description: 'Status updates visible to the session, grouped by contact.' })
async getStatuses(@Param('sessionId') sessionId: string) {
return { statuses: await this.statusService.getStatuses(sessionId) };
}
@Get(':contactId')
@ApiOperation({ summary: 'Get status updates from a specific contact' })
+ @ApiResponse({ status: 200, description: 'Status updates from the requested contact.' })
async getContactStatus(@Param('sessionId') sessionId: string, @Param('contactId') contactId: string) {
return { statuses: await this.statusService.getContactStatus(sessionId, contactId) };
}
@@ -26,6 +28,7 @@ export class StatusController {
@Post('send-text')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Post a text status (Baileys only)' })
+ @ApiResponse({ status: 201, description: 'Text status posted to the specified recipients.' })
async sendTextStatus(@Param('sessionId') sessionId: string, @Body() dto: SendTextStatusDto) {
return this.statusService.postTextStatus(sessionId, dto.text, {
recipients: dto.recipients,
@@ -37,6 +40,7 @@ export class StatusController {
@Post('send-image')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Post an image status (Baileys only)' })
+ @ApiResponse({ status: 201, description: 'Image status posted to the specified recipients.' })
async sendImageStatus(@Param('sessionId') sessionId: string, @Body() dto: SendImageStatusDto) {
return this.statusService.postImageStatus(sessionId, dto.image, {
recipients: dto.recipients,
@@ -47,6 +51,7 @@ export class StatusController {
@Post('send-video')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Post a video status (Baileys only)' })
+ @ApiResponse({ status: 201, description: 'Video status posted to the specified recipients.' })
async sendVideoStatus(@Param('sessionId') sessionId: string, @Body() dto: SendVideoStatusDto) {
return this.statusService.postVideoStatus(sessionId, dto.video, {
recipients: dto.recipients,
@@ -57,6 +62,7 @@ export class StatusController {
@Delete(':statusId')
@RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({ summary: 'Delete own status' })
+ @ApiResponse({ status: 200, description: 'Status deleted.' })
async deleteStatus(@Param('sessionId') sessionId: string, @Param('statusId') statusId: string) {
await this.statusService.deleteStatus(sessionId, statusId);
return { message: 'Status deleted successfully' };
diff --git a/src/modules/template/dto/template.dto.ts b/src/modules/template/dto/template.dto.ts
index 794fb13eb..2f4f5d195 100644
--- a/src/modules/template/dto/template.dto.ts
+++ b/src/modules/template/dto/template.dto.ts
@@ -88,10 +88,10 @@ export class TemplateResponseDto {
@ApiProperty()
body: string;
- @ApiPropertyOptional({ nullable: true })
+ @ApiPropertyOptional({ type: String, nullable: true })
header?: string | null;
- @ApiPropertyOptional({ nullable: true })
+ @ApiPropertyOptional({ type: String, nullable: true })
footer?: string | null;
@ApiProperty()
diff --git a/src/modules/webhook/dto/webhook.dto.ts b/src/modules/webhook/dto/webhook.dto.ts
index ee3c4aacf..c1c7c7cea 100644
--- a/src/modules/webhook/dto/webhook.dto.ts
+++ b/src/modules/webhook/dto/webhook.dto.ts
@@ -61,7 +61,10 @@ export class CreateWebhookDto {
@ApiPropertyOptional({
description: "Event types to subscribe to. '*' subscribes to all events.",
example: ['message.received', 'session.status'],
- enum: WEBHOOK_EVENTS,
+ enum: [...WEBHOOK_EVENTS, '*'],
+ type: String,
+ isArray: true,
+ minItems: 1,
})
@IsOptional()
@IsArray()
@@ -111,7 +114,13 @@ export class UpdateWebhookDto {
@IsUrl({ require_tld: false })
url?: string;
- @ApiPropertyOptional({ description: "Event types to subscribe to. '*' subscribes to all events." })
+ @ApiPropertyOptional({
+ description: "Event types to subscribe to. '*' subscribes to all events.",
+ enum: [...WEBHOOK_EVENTS, '*'],
+ type: String,
+ isArray: true,
+ minItems: 1,
+ })
@IsOptional()
@IsArray()
@ArrayMinSize(1)