Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(docs,api): correct drift between documented and actual contracts (#953)
Yudhi Armyndharis17e35a47a897
diff --git a/README.md b/README.mdindex 7b1920579..cc28e2608 100644--- a/README.md+++ b/README.md@@ -125,7 +125,7 @@ For any deployment where ethical, legal, or regulatory compliance matters (healt| Proxy Support | ✅ | Per-session proxy configuration || Rate Limiting | ✅ | Configurable request limits || CIDR Whitelisting | ✅ | IP-based access control |-| Audit Logging | ✅ | Track all API operations |+| Audit Logging | ✅ | Audit trail for API-key, session, integration-instance, and infra admin operations (message sends and webhook deliveries are tracked in their own tables, not the audit log) |### Infrastructurediff --git a/docs/04-security-design.md b/docs/04-security-design.mdindex 08b819617..4c28cf8a9 100644--- a/docs/04-security-design.md+++ b/docs/04-security-design.md@@ -331,7 +331,14 @@ TTL values are in milliseconds. The `/api/metrics` and `/api/health*` routes are### Response on limit-Exceeding any window returns `429 Too Many Requests` with a `Retry-After` header. The `ThrottlerGuard` also sets `X-RateLimit-*` response headers (limit / remaining / reset) by default, and the API exposes them via CORS — but with three named windows in play, the `429` + `Retry-After` is the simplest backpressure signal to act on.+Exceeding a window returns `429 Too Many Requests`. Because the windows are **named** throttlers (`short` / `medium` / `long`), `@nestjs/throttler` suffixes every rate-limit header with the throttler name — there are no unsuffixed `Retry-After` or `X-RateLimit-*` headers:++- On success, each response carries one header triple per window: `X-RateLimit-Limit-short` / `-Remaining-short` / `-Reset-short`, plus the `-medium` and `-long` equivalents.+- On `429`, the exceeded window sets `Retry-After-short`, `Retry-After-medium`, or `Retry-After-long` (seconds until the block expires) — read whichever is present rather than a plain `Retry-After`.++The ingress route (`ALL /api/ingress/:pluginId/:instanceId/*path`) additionally evaluates a per-instance window named `instance` (env: `INGRESS_INSTANCE_LIMIT`, default 120, per `INGRESS_INSTANCE_TTL`, default 60000 ms), so its responses carry `X-RateLimit-*-instance` and, on saturation, `Retry-After-instance`.++The API exposes the rate-limit headers via CORS (`exposedHeaders`) so browser clients can read them. The simplest backpressure signal remains the `429` status itself, with the suffixed `Retry-After-*` as the retry delay.### WebSocket (`/events`) limits@@ -367,7 +374,9 @@ const corsOptions = {credentials: true,methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],allowedHeaders: ['Content-Type', 'X-API-Key', 'X-Request-ID'],- exposedHeaders: ['X-RateLimit-Limit', 'X-RateLimit-Remaining'],+ // Throttlers are named, so rate-limit headers carry a per-window suffix+ // (see "Response on limit" above); there are no unsuffixed variants.+ exposedHeaders: ['X-RateLimit-Limit-short', 'X-RateLimit-Remaining-short', '...'],maxAge: 86400, // 24 hours};```diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 206392d6f..aaa7bac63 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -184,7 +184,7 @@ Every path below is prefixed with `/api`. Unless marked **public**, send `X-API-### 6.4.1 Sessions-Base path `/api/sessions`. Read routes return data shaped by `SessionResponseDto.fromEntity` (via `transformSession`), which **strips** `config`, `proxyUrl`, and `proxyType` and renames the entity field `lastActiveAt` to `lastActive`. The one exception is `POST /api/sessions`, which returns the **raw `Session` entity** and therefore *does* expose `config`/`proxyUrl`/`proxyType`/`lastActiveAt`. Session `status` wire values are lowercase: `created | initializing | qr_ready | authenticating | ready | disconnected | failed`.+Base path `/api/sessions`. All routes that return a session return data shaped by `SessionResponseDto.fromEntity` (via `transformSession`), which **strips** `config`, `proxyUrl`, and `proxyType` and renames the entity field `lastActiveAt` to `lastActive`. Session `status` wire values are lowercase: `created | initializing | qr_ready | authenticating | ready | disconnected | failed`.#### GET /api/sessions@@ -382,7 +382,7 @@ Create a new WhatsApp session.| Field | Type | Required | Constraints | Description || --- | --- | --- | --- | --- || `name` | string | Yes | `@IsString`; length 3–50; `@Matches(/^[a-zA-Z0-9-]+$/)` (letters, numbers, hyphens only) | Unique session name; duplicate → `409` |-| `config` | object | No | `@IsOptional` (arbitrary object, no shape validation) | Opaque engine config; defaults to `{}`; never returned by read routes |+| `config` | object | No | `@IsOptional` (arbitrary object, no shape validation) | Opaque engine config; defaults to `{}`; never returned in responses || `proxyUrl` | string | No | `@IsOptional`; `@IsString`; max 255; `@IsUrl` (protocols `http`/`https`/`socks4`/`socks5`, `require_protocol`, `require_tld:false`, `allow_underscores`) | Per-session proxy egress; credentialed `http://user:pass@host` and single-label hosts allowed; not SSRF-blocked. ⚠ **Must be a real, reachable proxy** — an unreachable value silently blocks the WhatsApp WebSocket (no QR, start → `504`); leave unset unless you need it. See "Per-session egress proxy" below. || `proxyType` | `http` \| `https` \| `socks4` \| `socks5` | No | `@IsOptional`; `@IsIn([...])` | Proxy protocol |@@ -420,17 +420,15 @@ network cannot reach WhatsApp directly. Set `proxyUrl`/`proxyType` on the same r"status": "created","phone": null,"pushName": null,- "config": { "autoReconnect": true },- "proxyUrl": null,- "proxyType": null,"connectedAt": null,- "lastActiveAt": null,+ "lastActive": null,"createdAt": "2026-06-25T09:00:00.000Z",- "updatedAt": "2026-06-25T09:00:00.000Z"+ "updatedAt": "2026-06-25T09:00:00.000Z",+ "lastError": null}```-This route returns the **raw `Session` entity** (not via `fromEntity`), so `config`/`proxyUrl`/`proxyType`/`lastActiveAt` are present here only. Newly created `status` is `created`.+Like every other session route, this returns the `SessionResponseDto` shape (via `fromEntity`), so `config`/`proxyUrl`/`proxyType` are stripped and `lastActiveAt` appears as `lastActive`. Newly created `status` is `created`.**Errors:** `400` validation (bad `name`/`proxyUrl`/`proxyType`, or an extra non-whitelisted field) · `401` · `403` key lacks OPERATOR role · `409` session name already existsdiff --git a/docs/09-testing-strategy.md b/docs/09-testing-strategy.mdindex 9d15cdb5b..32cdb32bc 100644--- a/docs/09-testing-strategy.md+++ b/docs/09-testing-strategy.md@@ -124,7 +124,9 @@ test/├── integration-fabric.e2e-spec.ts├── integration-instance.e2e-spec.ts├── mcp-auth.e2e-spec.ts+├── search.e2e-spec.ts├── serve-static.e2e-spec.ts+├── session-scope.e2e-spec.ts├── webhooks.e2e-spec.ts├── jest-e2e.json└── setup-e2e.ts@@ -156,6 +158,7 @@ authoritative gate. Current policy:| `src/core/hooks/` | 80% | 70% | 82% | 81% || `src/modules/session/` | 50% | 63% | 74% | 72% || `src/modules/webhook/` | 65% | 83% | 84% | 80% |+| `src/modules/search/` | 58% | 72% | 58% | 58% |The stricter scoped gates protect security-sensitive code and high-risk boundary layers. When addingsecurity, engine-adapter, or integration-fabric behavior, add focused regression tests instead of relying@@ -167,11 +170,13 @@ Main CI is defined in `.github/workflows/ci.yml`.| Job | Checks || --------------- | ----------------------------------------------------------------------------------------------- |-| `lint` | security audit, backend ESLint, full-program TypeScript check, formatting, version consistency, OpenAPI snapshot |+| `lint` | backend ESLint, full-program TypeScript check, formatting, version consistency, OpenAPI snapshot |+| `audit` | dependency security audit || `test` | backend coverage run, e2e smoke tests, Codecov upload || `test-postgres` | real PostgreSQL 16 service, backend build, migration smoke, and PostgreSQL FTS provider spec || `dashboard` | dashboard install, lint, test type-check, unit tests, i18n parity, build |-| `build` | backend build after lint/test/dashboard jobs pass |+| `scripts-smoke` | shellcheck on the backup/restore scripts plus the backup/restore smoke test |+| `build` | backend build after lint/audit/test/dashboard/scripts-smoke jobs pass || `docker` | multi-arch Docker build on pushes and pull requests; publish only where workflow permissions allow |SDK CI is defined in `.github/workflows/sdk-ci.yml` and is path-filtered to SDK sources plus serverdiff --git a/docs/10-devops-infrastructure.md b/docs/10-devops-infrastructure.mdindex de197dfed..34527e258 100644--- a/docs/10-devops-infrastructure.md+++ b/docs/10-devops-infrastructure.md@@ -133,8 +133,15 @@ services:- "2785:2785"environment:- NODE_ENV=development- - DATABASE_URL=postgresql://openwa:openwa@postgres:5432/openwa- - REDIS_URL=redis://redis:6379+ - DATABASE_TYPE=postgres+ - DATABASE_HOST=postgres+ - DATABASE_PORT=5432+ - DATABASE_NAME=openwa+ - DATABASE_USERNAME=openwa+ - DATABASE_PASSWORD=openwa+ - REDIS_ENABLED=true+ - REDIS_HOST=redis+ - REDIS_PORT=6379# The env var is API_MASTER_KEY (not API_KEY_MASTER); never hardcode a key — set a# strong secret. Production refuses to boot with a placeholder/default.- API_MASTER_KEY=@@ -194,8 +201,15 @@ services:memory: 1Genvironment:- NODE_ENV=production- - DATABASE_URL=${DATABASE_URL}- - REDIS_URL=${REDIS_URL}+ - DATABASE_TYPE=postgres+ - DATABASE_HOST=${DATABASE_HOST}+ - DATABASE_PORT=${DATABASE_PORT}+ - DATABASE_NAME=${DATABASE_NAME}+ - DATABASE_USERNAME=${DATABASE_USERNAME}+ - DATABASE_PASSWORD=${DATABASE_PASSWORD}+ - REDIS_ENABLED=true+ - REDIS_HOST=${REDIS_HOST}+ - REDIS_PORT=${REDIS_PORT}- API_MASTER_KEY=${API_MASTER_KEY}volumes:- session-data:/app/.wwebjs_auth@@ -287,7 +301,12 @@ jobs:- name: Run testsrun: npm run test:covenv:- DATABASE_URL: postgresql://test:test@localhost:5432/test+ DATABASE_TYPE: postgres+ DATABASE_HOST: localhost+ DATABASE_PORT: '5432'+ DATABASE_USERNAME: test+ DATABASE_PASSWORD: test+ DATABASE_NAME: test- name: Upload coverageuses: codecov/codecov-action@v3@@ -447,13 +466,18 @@ LOG_FORMAT=json# DATABASE (choose one)# ===========================================# Option 1: SQLite (for minimal deployments)+# For SQLite, DATABASE_NAME is the database FILE PATH.DATABASE_TYPE=sqlite-DATABASE_SQLITE_PATH=./data/openwa.db+DATABASE_NAME=./data/openwa.sqlite-# Option 2: PostgreSQL (for production)+# Option 2: PostgreSQL (for production) — DATABASE_NAME is the database NAME here# DATABASE_TYPE=postgres-# DATABASE_URL=postgresql://user:pass@localhost:5432/openwa-# DATABASE_POOL_MAX=20+# DATABASE_HOST=localhost+# DATABASE_PORT=5432+# DATABASE_NAME=openwa+# DATABASE_USERNAME=user+# DATABASE_PASSWORD=pass+# DATABASE_POOL_SIZE=20# DATABASE_SSL=false# ===========================================@@ -534,20 +558,36 @@ RATE_LIMIT_MEDIUM_LIMIT=100### Configuration Service```typescript-// config/configuration.ts+// config/configuration.ts (shape abbreviated — see src/config/configuration.ts for the real file)export default () => ({port: parseInt(process.env.PORT, 10) || 3000,+ // Main boot DB: always SQLite (auth/audit)database: {- url: process.env.DATABASE_URL,+ type: 'sqlite',+ database: process.env.MAIN_DATABASE_NAME || './data/main.sqlite',+ },+ // Data DB: pluggable backend+ dataDatabase: {+ type: process.env.DATABASE_TYPE || 'sqlite',+ // SQLite file path when type is sqlite; PostgreSQL database name when type is postgres+ database: process.env.DATABASE_NAME || './data/openwa.sqlite',+ name: process.env.DATABASE_NAME || 'openwa',+ host: process.env.DATABASE_HOST || 'localhost',+ port: parseInt(process.env.DATABASE_PORT || '5432', 10),+ username: process.env.DATABASE_USERNAME,+ password: process.env.DATABASE_PASSWORD,},redis: {- url: process.env.REDIS_URL,+ host: process.env.REDIS_HOST || 'localhost',+ port: parseInt(process.env.REDIS_PORT || '6379', 10),+ username: process.env.REDIS_USERNAME,+ password: process.env.REDIS_PASSWORD,},security: {masterApiKey: process.env.API_MASTER_KEY,},session: {- dataPath: process.env.SESSION_DATA_PATH || './.wwebjs_auth',+ dataPath: process.env.SESSION_DATA_PATH || './data/sessions',},webhook: {timeout: parseInt(process.env.WEBHOOK_TIMEOUT || '10000', 10),diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.mdindex b70d713fd..a33d6755a 100644--- a/docs/12-troubleshooting-faq.md+++ b/docs/12-troubleshooting-faq.md@@ -721,20 +721,20 @@ cache:**Solutions:**```bash-# Check for long-running queries-sqlite3 ./data/openwa.db ".timeout 30000"--# Increase timeout in configuration-DATABASE_SQLITE_BUSY_TIMEOUT=30000+# Check for long-running queries (default SQLite file; override with DATABASE_NAME)+sqlite3 ./data/openwa.sqlite ".timeout 30000"# Check WAL mode-sqlite3 ./data/openwa.db "PRAGMA journal_mode;"-# Should return: wal+sqlite3 ./data/openwa.sqlite "PRAGMA journal_mode;"+# Default is: delete (rollback journal) — OpenWA does not force WAL-# Enable WAL mode-sqlite3 ./data/openwa.db "PRAGMA journal_mode=WAL;"+# Optionally enable WAL mode to reduce writer/reader lock contention+sqlite3 ./data/openwa.sqlite "PRAGMA journal_mode=WAL;"```+There is no `DATABASE_SQLITE_BUSY_TIMEOUT`-style env knob — busy handling comes from the+`better-sqlite3` driver defaults. If locks persist under concurrent sessions, migrate to PostgreSQL.+**When to Migrate to PostgreSQL:**```mermaiddiff --git a/docs/14-migration-guide.md b/docs/14-migration-guide.mdindex a424244fa..5dd8e4d6e 100644--- a/docs/14-migration-guide.md+++ b/docs/14-migration-guide.md@@ -254,6 +254,11 @@ docker compose up -d> **Note:** This example uses the standalone `sqlite3` npm package, which is no longer part of> OpenWA's dependencies (the app itself uses `better-sqlite3`). Install it ad hoc before running:> `npm install --no-save sqlite3`.+>+> The `SQLITE_PATH` / `DATABASE_URL` variables below are inputs to this standalone script only —+> they are **not** OpenWA configuration. The application itself reads `DATABASE_TYPE` plus+> `DATABASE_NAME` / `DATABASE_HOST` / `DATABASE_PORT` / `DATABASE_USERNAME` / `DATABASE_PASSWORD`+> (see `src/config/configuration.ts`).```typescript// scripts/migrate-sqlite-to-postgres.ts@@ -406,7 +411,7 @@ function getSqliteTables(db: sqlite3.Database): Promise<string[]> {// CLI Entry pointconst config: MigrationConfig = {- sqlitePath: process.env.SQLITE_PATH || './data/openwa.db',+ sqlitePath: process.env.SQLITE_PATH || './data/openwa.sqlite',postgresUrl: process.env.DATABASE_URL || 'postgresql://user:pass@localhost:5432/openwa',batchSize: parseInt(process.env.BATCH_SIZE || '1000'),};@@ -443,12 +448,16 @@ docker compose -f docker-compose.postgres.yml up -d postgresnpx ts-node scripts/migrate-sqlite-to-postgres.ts# Step 5: Update environment-export DATABASE_ADAPTER=postgresql-export DATABASE_URL=postgresql://user:pass@localhost:5432/openwa+export DATABASE_TYPE=postgres+export DATABASE_HOST=localhost+export DATABASE_PORT=5432+export DATABASE_NAME=openwa+export DATABASE_USERNAME=user+export DATABASE_PASSWORD=pass# Step 6: Verify migration-psql $DATABASE_URL -c "SELECT COUNT(*) FROM sessions;"-psql $DATABASE_URL -c "SELECT COUNT(*) FROM messages;"+psql -h "$DATABASE_HOST" -U "$DATABASE_USERNAME" -d "$DATABASE_NAME" -c "SELECT COUNT(*) FROM sessions;"+psql -h "$DATABASE_HOST" -U "$DATABASE_USERNAME" -d "$DATABASE_NAME" -c "SELECT COUNT(*) FROM messages;"# Step 7: Start with PostgreSQLdocker compose -f docker-compose.postgres.yml up -d@@ -533,13 +542,13 @@ rsync -avz --progress \# Copy database recordecho "📄 Exporting session record..."-ssh old-server "sqlite3 /data/openwa.db \+ssh old-server "sqlite3 /data/openwa.sqlite \\"SELECT * FROM sessions WHERE id='${SESSION_ID}'\" \-csv" > session_record.csv# Import to new databaseecho "📥 Importing session record..."-ssh new-server "sqlite3 /data/openwa.db \+ssh new-server "sqlite3 /data/openwa.sqlite \\".import session_record.csv sessions\""# Start new server@@ -721,7 +730,7 @@ breaking_changes:- auth: Basic Auth → API Keyconfig:- - DATABASE_PATH → DATABASE_URL (for PostgreSQL)+ - DATABASE_PATH → DATABASE_TYPE + discrete connection vars (DATABASE_HOST, DATABASE_PORT, DATABASE_NAME, DATABASE_USERNAME, DATABASE_PASSWORD) for PostgreSQL- WEBHOOK_URL → Managed via APIdatabase:@@ -755,7 +764,8 @@ docker compose downecho "🔄 Running migrations..."docker run --rm \-v $(pwd)/data:/app/data \- -e DATABASE_URL=sqlite:///app/data/openwa.db \+ -e DATABASE_TYPE=sqlite \+ -e DATABASE_NAME=/app/data/openwa.sqlite \ghcr.io/rmyndharis/openwa:0.2.0 \npm run migration:run:prod # the prod image strips ts-node/TS source — use :prod@@ -765,8 +775,8 @@ cat > .env.new << 'EOF'# OpenWA v0.2.x Configuration# Database (unchanged if using SQLite)-DATABASE_ADAPTER=sqlite-DATABASE_URL=sqlite:./data/openwa.db+DATABASE_TYPE=sqlite+DATABASE_NAME=./data/openwa.sqlite# New in v0.2: API Key AuthenticationAPI_KEY_ENABLED=true@@ -850,10 +860,10 @@ BACKUP_DIR="./backups/v02-$(date +%Y%m%d-%H%M%S)"mkdir -p "$BACKUP_DIR"# Backup database-if [ "$DATABASE_ADAPTER" = "postgresql" ]; then- pg_dump $DATABASE_URL > "$BACKUP_DIR/database.sql"+if [ "$DATABASE_TYPE" = "postgres" ]; then+ pg_dump -h "$DATABASE_HOST" -U "$DATABASE_USERNAME" "$DATABASE_NAME" > "$BACKUP_DIR/database.sql"else- cp ./data/openwa.db "$BACKUP_DIR/"+ cp ./data/openwa.sqlite "$BACKUP_DIR/"fi# Backup auth sessions@@ -963,10 +973,10 @@ docker compose downecho "📥 Restoring database..."if [ -f "$BACKUP_DIR/database.sql" ]; then# PostgreSQL- psql $DATABASE_URL < "$BACKUP_DIR/database.sql"+ psql -h "$DATABASE_HOST" -U "$DATABASE_USERNAME" -d "$DATABASE_NAME" < "$BACKUP_DIR/database.sql"else# SQLite- cp "$BACKUP_DIR/openwa.db" ./data/+ cp "$BACKUP_DIR/openwa.sqlite" ./data/fi# 3. Restore auth sessions@@ -1142,8 +1152,8 @@ async function fullExport(options: ExportOptions): Promise<void> {version: process.env.npm_package_version,exportedAt: new Date().toISOString(),settings: {- DATABASE_ADAPTER: process.env.DATABASE_ADAPTER,- STORAGE_ADAPTER: process.env.STORAGE_ADAPTER,+ DATABASE_TYPE: process.env.DATABASE_TYPE,+ STORAGE_TYPE: process.env.STORAGE_TYPE,ENGINE_TYPE: process.env.ENGINE_TYPE,},};@@ -1277,20 +1287,20 @@ docker compose up -d```bash# Check database integrity-sqlite3 ./data/openwa.db "PRAGMA integrity_check;"+sqlite3 ./data/openwa.sqlite "PRAGMA integrity_check;"# Verify auth session filesls -la ./data/.wwebjs_auth/session-*/# Check file permissions-stat ./data/openwa.db+stat ./data/openwa.sqlitestat ./data/.wwebjs_auth# Verify PostgreSQL connection-psql $DATABASE_URL -c "SELECT version();"+psql -h "$DATABASE_HOST" -U "$DATABASE_USERNAME" -d "$DATABASE_NAME" -c "SELECT version();"# Check migration status-npm run migration:status+npm run migration:show# Force re-run specific migrationnpm run migration:run -- --name CreateApiKeysTablediff --git a/openapi.json b/openapi.jsonindex 6394a9ff8..3da9d509c 100644--- a/openapi.json+++ b/openapi.json@@ -4206,6 +4206,32 @@]}},+ "/api/metrics": {+ "get": {+ "operationId": "MetricsController_scrape",+ "parameters": [],+ "responses": {+ "200": {+ "description": "Prometheus exposition text"+ },+ "401": {+ "description": "METRICS_TOKEN is configured but the bearer is missing or wrong"+ },+ "404": {+ "description": "Metrics endpoint is disabled (METRICS_TOKEN unset)"+ }+ },+ "security": [+ {+ "metrics-bearer": []+ }+ ],+ "summary": "Prometheus metrics (requires METRICS_TOKEN bearer)",+ "tags": [+ "metrics"+ ]+ }+ },"/api/sessions/{sessionId}/status": {"get": {"operationId": "StatusController_getStatuses",@@ -5836,6 +5862,18 @@"name": "status","description": "Status/Stories"},+ {+ "name": "calls",+ "description": "Call handling"+ },+ {+ "name": "profile",+ "description": "Own profile management"+ },+ {+ "name": "search",+ "description": "Global message search"+ },{"name": "statistics","description": "Usage statistics"@@ -5884,6 +5922,12 @@"type": "apiKey","in": "header","name": "X-API-Key"+ },+ "metrics-bearer": {+ "scheme": "bearer",+ "bearerFormat": "opaque",+ "type": "http",+ "description": "METRICS_TOKEN for the GET /api/metrics scrape endpoint"}},"schemas": {diff --git a/scripts/export-openapi.ts b/scripts/export-openapi.tsindex cdef791bf..18f02efd6 100644--- a/scripts/export-openapi.ts+++ b/scripts/export-openapi.ts@@ -24,6 +24,13 @@ process.env.QUEUE_ENABLED = 'false';process.env.MCP_ENABLED = 'false';process.env.AUTO_START_SESSIONS = 'false';process.env.DATABASE_TYPE = 'sqlite';+// Keep the throttler storage in-memory: with REDIS_ENABLED=true in the caller's env the export+// would open a Redis connection for no benefit (the document doesn't change either way).+process.env.REDIS_ENABLED = 'false';+// The search module mounts conditionally on SEARCH_ENABLED (app.module.ts top-level), so an+// export run with SEARCH_ENABLED=false in the caller's env would silently drop /api/search from+// the snapshot. Pin it on — the committed snapshot documents the full default surface.+process.env.SEARCH_ENABLED = 'true';// The 'data' connection must use a real SQLite file path to satisfy env-validation (an in-memory or// bare value is rejected to catch PostgreSQL db-name leaks — see env.validation.ts). Use a temp dir// so the export stays hermetic; the whole dir is removed in main()'s finally, and recursive rmSyncdiff --git a/src/config/openapi-export-pins.spec.ts b/src/config/openapi-export-pins.spec.tsnew file mode 100644index 000000000..4715f5f45--- /dev/null+++ b/src/config/openapi-export-pins.spec.ts@@ -0,0 +1,38 @@+import { readFileSync } from 'node:fs';+import { join } from 'node:path';++/**+ * Structural gate for scripts/export-openapi.ts: the committed OpenAPI snapshot must be+ * deterministic, which holds only because the script pins every env var that changes the+ * document (conditional module mounts, storage backends) BEFORE requiring AppModule. If a pin+ * is dropped — or AppModule gets required above the pins — two exports under different+ * environments can diverge and `npm run openapi:check` turns flaky. Verified end-to-end by+ * running the export twice under different env; this spec keeps the mechanism intact.+ */+const SCRIPT_PATH = join(__dirname, '..', '..', 'scripts', 'export-openapi.ts');+const source = readFileSync(SCRIPT_PATH, 'utf8');++// Env vars that alter the generated document or the export's hermeticity.+const REQUIRED_PINS = [+ 'QUEUE_ENABLED',+ 'MCP_ENABLED',+ 'AUTO_START_SESSIONS',+ 'DATABASE_TYPE',+ 'DATABASE_NAME',+ 'MAIN_DATABASE_NAME',+ 'REDIS_ENABLED',+ // The search module mounts conditionally on SEARCH_ENABLED — without this pin an export run+ // with SEARCH_ENABLED=false in the caller's env silently drops /api/search from the snapshot.+ 'SEARCH_ENABLED',+];++describe('openapi export env pins', () => {+ it.each(REQUIRED_PINS)('pins %s before AppModule is required', name => {+ const pinIndex = source.indexOf(`process.env.${name} =`);+ const requireIndex = source.indexOf("require('../src/app.module')");++ expect(pinIndex).toBeGreaterThanOrEqual(0);+ expect(requireIndex).toBeGreaterThanOrEqual(0);+ expect(pinIndex).toBeLessThan(requireIndex);+ });+});diff --git a/src/config/swagger.config.spec.ts b/src/config/swagger.config.spec.tsindex b7e6cd4e1..90369ded7 100644--- a/src/config/swagger.config.spec.ts+++ b/src/config/swagger.config.spec.ts@@ -1,6 +1,6 @@import * as fs from 'fs';import * as path from 'path';-import { createSwaggerConfig, exemptPublicOperations, PUBLIC_PATHS } from './swagger.config';+import { createSwaggerConfig, exemptPublicOperations, PUBLIC_PATHS, METRICS_BEARER_SCHEME } from './swagger.config';import type { OpenAPIObject } from '@nestjs/swagger';describe('createSwaggerConfig', () => {@@ -12,6 +12,18 @@ describe('createSwaggerConfig', () => {expect(config.security).toContainEqual({ 'X-API-Key': [] });});++ it('defines the METRICS_TOKEN bearer scheme without applying it globally', () => {+ const config = createSwaggerConfig();++ expect(config.components?.securitySchemes?.[METRICS_BEARER_SCHEME]).toMatchObject({+ type: 'http',+ scheme: 'bearer',+ });+ // Only the scrape endpoint uses it (per-operation @ApiSecurity) — a global bearer+ // requirement would falsely claim every route accepts it.+ expect(config.security).not.toContainEqual({ [METRICS_BEARER_SCHEME]: [] });+ });});describe('exemptPublicOperations', () => {@@ -54,8 +66,9 @@ describe('exemptPublicOperations', () => {// (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.+// MetricsController is @Public() but gates scrapes on the METRICS_TOKEN bearer instead, so its+// operation carries the metrics-bearer security scheme (which overrides the global API-key+// requirement) rather than a PUBLIC_PATHS security: [] exemption.describe('PUBLIC_PATHS drift guard', () => {const EXPECTED_PUBLIC_CONTROLLERS = ['src/modules/health/health.controller.ts',diff --git a/src/config/swagger.config.ts b/src/config/swagger.config.tsindex c952f9f54..fc7747fa3 100644--- a/src/config/swagger.config.ts+++ b/src/config/swagger.config.ts@@ -6,6 +6,14 @@ import { DocumentBuilder, OpenAPIObject } from '@nestjs/swagger';*/export const API_KEY_SECURITY_SCHEME = 'X-API-Key';+/**+ * Security scheme name for the METRICS_TOKEN bearer that gates `GET /api/metrics`.+ * The endpoint is @Public() at the API-key guard and enforces the token itself, so the+ * operation carries this scheme (which overrides the document's global X-API-Key+ * requirement per OpenAPI 3) instead of the API-key one.+ */+export const METRICS_BEARER_SCHEME = 'metrics-bearer';+// 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.@@ -51,6 +59,17 @@ export function createSwaggerConfig(): Omit<OpenAPIObject, 'paths'> {.setDescription('Open Source WhatsApp API Gateway - Free, Self-Hosted HTTP API').setVersion(version).addApiKey({ type: 'apiKey', name: 'X-API-Key', in: 'header' }, API_KEY_SECURITY_SCHEME)+ // The METRICS_TOKEN bearer gates only GET /api/metrics (applied per-operation there —+ // NOT as a global requirement, since every other route uses the API key).+ .addBearerAuth(+ {+ type: 'http',+ scheme: 'bearer',+ bearerFormat: 'opaque',+ description: 'METRICS_TOKEN for the GET /api/metrics scrape endpoint',+ },+ METRICS_BEARER_SCHEME,+ )// 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)@@ -64,6 +83,9 @@ export function createSwaggerConfig(): Omit<OpenAPIObject, 'paths'> {.addTag('channels', 'Channel/Newsletter management').addTag('catalog', 'Product catalog (WhatsApp Business)').addTag('status', 'Status/Stories')+ .addTag('calls', 'Call handling')+ .addTag('profile', 'Own profile management')+ .addTag('search', 'Global message search').addTag('statistics', 'Usage statistics').addTag('templates', 'Message templates').addTag('plugins', 'Plugin management')diff --git a/src/main.ts b/src/main.tsindex 56a4f0d67..697fd333e 100644--- a/src/main.ts+++ b/src/main.ts@@ -268,7 +268,27 @@ async function bootstrap() {credentials: corsPolicy.credentials,methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],allowedHeaders: ['Content-Type', 'X-API-Key', 'Authorization', 'X-Request-ID'],- exposedHeaders: ['X-RateLimit-Limit', 'X-RateLimit-Remaining', 'X-RateLimit-Reset'],+ // The throttlers are named (short/medium/long, plus instance on ingress), so @nestjs/throttler+ // suffixes every rate-limit header with the throttler name — the unsuffixed variants are never+ // sent. Expose the suffixed names so browser clients can actually read them.+ exposedHeaders: [+ 'X-RateLimit-Limit-short',+ 'X-RateLimit-Remaining-short',+ 'X-RateLimit-Reset-short',+ 'X-RateLimit-Limit-medium',+ 'X-RateLimit-Remaining-medium',+ 'X-RateLimit-Reset-medium',+ 'X-RateLimit-Limit-long',+ 'X-RateLimit-Remaining-long',+ 'X-RateLimit-Reset-long',+ 'X-RateLimit-Limit-instance',+ 'X-RateLimit-Remaining-instance',+ 'X-RateLimit-Reset-instance',+ 'Retry-After-short',+ 'Retry-After-medium',+ 'Retry-After-long',+ 'Retry-After-instance',+ ],maxAge: 86400, // 24 hours});diff --git a/src/modules/metrics/metrics.controller.ts b/src/modules/metrics/metrics.controller.tsindex fb569e28f..bc1fdedbc 100644--- a/src/modules/metrics/metrics.controller.ts+++ b/src/modules/metrics/metrics.controller.ts@@ -1,8 +1,10 @@-import { Controller, Get, Header, Headers } from '@nestjs/common';-import { ApiTags, ApiOperation, ApiResponse, ApiExcludeEndpoint } from '@nestjs/swagger';+import { Controller, Get, Header, Req } from '@nestjs/common';+import { ApiTags, ApiOperation, ApiResponse, ApiSecurity } from '@nestjs/swagger';import { SkipThrottle } from '@nestjs/throttler';+import type { Request } from 'express';import { Public } from '../auth/decorators/auth.decorators';import { MetricsService } from './metrics.service';+import { METRICS_BEARER_SCHEME } from '../../config/swagger.config';/*** Prometheus scrape endpoint. `@Public()` bypasses the API-key guard and@@ -17,13 +19,17 @@ export class MetricsController {constructor(private readonly metricsService: MetricsService) {}@Get()- @ApiExcludeEndpoint()@ApiOperation({ summary: 'Prometheus metrics (requires METRICS_TOKEN bearer)' })+ @ApiSecurity(METRICS_BEARER_SCHEME)@ApiResponse({ status: 200, description: 'Prometheus exposition text' })+ @ApiResponse({ status: 401, description: 'METRICS_TOKEN is configured but the bearer is missing or wrong' })+ @ApiResponse({ status: 404, description: 'Metrics endpoint is disabled (METRICS_TOKEN unset)' })@Header('Content-Type', 'text/plain; version=0.0.4; charset=utf-8')@Header('Cache-Control', 'no-store')- async scrape(@Headers('authorization') authorization?: string): Promise<string> {- this.metricsService.assertScrapeAuthorized(authorization);+ // @Req (not @Headers('authorization')) so the OpenAPI op doesn't sprout a spurious required+ // `authorization` header parameter — the bearer is expressed via the security scheme above.+ async scrape(@Req() req: Request): Promise<string> {+ this.metricsService.assertScrapeAuthorized(req.headers.authorization);return this.metricsService.render();}}diff --git a/src/modules/session/session.controller.spec.ts b/src/modules/session/session.controller.spec.tsnew file mode 100644index 000000000..5692d8fde--- /dev/null+++ b/src/modules/session/session.controller.spec.ts@@ -0,0 +1,75 @@+import type { SessionController } from './session.controller';+import { SessionController as SessionControllerClass } from './session.controller';+import { SessionStatus } from './entities/session.entity';+import type { Session } from './entities/session.entity';+import type { SessionService } from './session.service';+import type { AuditService } from '../audit/audit.service';++// POST /sessions declared a SessionResponseDto in its Swagger metadata but returned the raw+// TypeORM entity, leaking internal columns (config, proxyUrl, proxyType) and the entity-only+// lastActiveAt name. The response must go through the same SessionResponseDto.fromEntity mapping+// as every sibling endpoint.+describe('SessionController — create() response contract', () => {+ const entity: Session = {+ id: 'sess-uuid-1',+ name: 'test-session',+ status: SessionStatus.CREATED,+ phone: null,+ pushName: null,+ config: { engine: 'whatsapp-web.js', webhook: 'https://internal.example/hook' },+ proxyUrl: 'http://user:[email protected]:8080',+ proxyType: 'http',+ connectedAt: null,+ lastActiveAt: null,+ createdAt: new Date('2026-01-01T00:00:00Z'),+ updatedAt: new Date('2026-01-01T00:00:00Z'),+ };++ let sessionService: { create: jest.Mock };+ let auditService: { logInfo: jest.Mock };+ let controller: SessionController;++ beforeEach(() => {+ sessionService = { create: jest.fn().mockResolvedValue({ ...entity }) };+ auditService = { logInfo: jest.fn().mockResolvedValue(undefined) };+ controller = new SessionControllerClass(+ sessionService as unknown as SessionService,+ auditService as unknown as AuditService,+ );+ });++ it('strips internal entity fields from the response', async () => {+ const result = await controller.create({ name: 'test-session' });++ expect(result).not.toHaveProperty('config');+ expect(result).not.toHaveProperty('proxyUrl');+ expect(result).not.toHaveProperty('proxyType');+ expect(result).not.toHaveProperty('lastActiveAt');+ });++ it('keeps every documented SessionResponseDto field', async () => {+ const result = await controller.create({ name: 'test-session' });++ expect(result).toEqual({+ id: entity.id,+ name: entity.name,+ status: entity.status,+ phone: entity.phone,+ pushName: entity.pushName,+ connectedAt: entity.connectedAt,+ lastActive: entity.lastActiveAt,+ createdAt: entity.createdAt,+ updatedAt: entity.updatedAt,+ lastError: null,+ });+ });++ it('still audits the creation with the session id and name', async () => {+ await controller.create({ name: 'test-session' });++ expect(auditService.logInfo).toHaveBeenCalledWith(+ 'session_created',+ expect.objectContaining({ sessionId: entity.id, sessionName: entity.name }),+ );+ });+});diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex 8c5fcda59..81bfa2fe9 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -43,13 +43,13 @@ export class SessionController {type: SessionResponseDto,})@ApiResponse({ status: 409, description: 'Session name already exists' })- async create(@Body() dto: CreateSessionDto): Promise<Session> {+ async create(@Body() dto: CreateSessionDto): Promise<SessionResponseDto> {const session = await this.sessionService.create(dto);await this.auditService.logInfo(AuditAction.SESSION_CREATED, {sessionId: session.id,sessionName: session.name,});- return session;+ return this.transformSession(session);}@Get()