Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix: hardening pack — SSRF range, MCP session fence, audit page cap, migration reverts, bulk marker (#536)
Yudhi Armyndharisf862d80b3b31
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 45354d313..cbae9ad28 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,12 +13,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **A message arriving while a session is being deleted is no longer persisted as an orphan.** The inbound-message handler re-checks that the session is still live after its asynchronous processing, so a message that races a session deletion can't leave behind a `messages` row (which has no cascade) for a session that no longer exists. (#531)- **Per-session stats return a consistent `lastActive` timestamp on SQLite and PostgreSQL.** `GET /stats/sessions/:id` previously emitted a different `topChats[].lastActive` format depending on the database (an ISO date-time on PostgreSQL versus the stored text on SQLite); it is now formatted to a stable `YYYY-MM-DD HH:MM:SS` on both. (#533)- **The uuid id default now works on PostgreSQL 12 and older.** Id generation relies on a `gen_random_uuid()` column default, which is a core built-in only from PostgreSQL 13; on older servers it lives in the `pgcrypto` extension. The migration now enables `pgcrypto` first, so a fresh deploy against PostgreSQL ≤ 12 no longer fails on startup or first insert. (#533)+- **The audit-log listing no longer loads the whole table for a large `limit`.** `GET /audit` clamps its page size to a maximum of 200, so an oversized `limit` can't pull the entire `audit_logs` table into a single response. (#536)+- **Migration reverts are idempotent on a synchronize-bootstrapped database.** The `baileys_stored_messages` and `webhook_delivery_failures` migrations now drop their indexes with `IF EXISTS`, so a `down()` no longer errors when the named indexes were never created. (#536)+- **Bulk send always releases its in-flight marker.** A batch whose session engine was missing, or that threw mid-processing, previously left a stale entry in an in-memory tracking map; the marker is now released on every exit path. (#536)### Security- **Hook re-entrancy is now blocked for sandboxed plugins too.** A plugin running in the worker-thread sandbox could re-fire the hook it was handling by issuing a capability call (for example, sending a message from within a `message:sending` handler), because the re-entrancy guard did not span the worker boundary — looping the event back into the plugin without bound. The host now runs each worker-initiated capability call inside the in-flight hook context, so such a re-fire is short-circuited exactly as it already was for in-process plugins. (#532)- **Docker container teardown is constrained to OpenWA-managed services.** The `POST /infra/restart` endpoint passed its `profilesToRemove` list straight to container removal, which resolved containers by a name substring — so an unrecognized or empty profile could stop and remove an unrelated container. Teardown is now restricted to the managed allowlist (`postgres`, `redis`, `minio`) and container resolution requires an exact `openwa-<service>` name match. (#534)- **Failed API-key authentication attempts are now recorded in the audit log.** Rejected or denied keys (invalid, disabled/expired, IP- or session-scope-denied, or insufficient role) previously left no audit entry; the gateway now logs an `api_key_auth_failed` event with the client IP, method, path, and reason, giving administrators a forensic trail for credential probing. Audit logging stays best-effort and never affects the request outcome. (#535)+- **The SSRF guard blocks the deprecated IPv6 site-local range (`fec0::/10`).** Webhook and server-side media URLs are now rejected when they resolve into `fec0::/10`, closing a gap alongside the already-blocked unique-local and link-local ranges. (#536)+- **Session-scoped MCP tools require a session id before authorization.** A session-scoped tool invoked without a session id is now rejected, so a session-restricted API key can't be used to drive such a tool against a session outside its scope. (#536)## [0.7.12] - 2026-06-29diff --git a/src/common/security/ssrf-guard.spec.ts b/src/common/security/ssrf-guard.spec.tsindex 432053b0d..d1c8eee57 100644--- a/src/common/security/ssrf-guard.spec.ts+++ b/src/common/security/ssrf-guard.spec.ts@@ -38,6 +38,8 @@ describe('isBlockedAddress', () => {['fc00::1', 'IPv6 ULA fc00::/7'],['fd12:3456::1', 'IPv6 ULA fd'],['fe80::1', 'IPv6 link-local'],+ ['fec0::1', 'IPv6 site-local fec0::/10 (deprecated, RFC 3879)'],+ ['feff::1', 'IPv6 site-local upper bound feff'],['::ffff:127.0.0.1', 'IPv4-mapped loopback (dotted)'],['::ffff:7f00:1', 'IPv4-mapped loopback (hex)'],['::ffff:0a00:0001', 'IPv4-mapped RFC1918 (hex, zero-padded)'],diff --git a/src/common/security/ssrf-guard.ts b/src/common/security/ssrf-guard.tsindex 35db8a5b7..4684ee41e 100644--- a/src/common/security/ssrf-guard.ts+++ b/src/common/security/ssrf-guard.ts@@ -133,6 +133,7 @@ export function isBlockedAddress(ip: string): boolean {const firstHextet = lower.split(':')[0];if (firstHextet.startsWith('fc') || firstHextet.startsWith('fd')) return true; // ULA fc00::/7if (/^fe[89ab]/.test(firstHextet)) return true; // link-local fe80::/10+ if (/^fe[c-f]/.test(firstHextet)) return true; // deprecated site-local fec0::/10 (RFC 3879)// IPv6 forms that embed an IPv4 — 6to4 (2002::/16), NAT64 (64:ff9b::/96), and the deprecated// IPv4-compatible ::/96 — are classified by the embedded address so they reach the IPv4 blocklist,diff --git a/src/core/agent-tools/tool-invoker.spec.ts b/src/core/agent-tools/tool-invoker.spec.tsindex c99626395..c0a58abf0 100644--- a/src/core/agent-tools/tool-invoker.spec.ts+++ b/src/core/agent-tools/tool-invoker.spec.ts@@ -52,6 +52,22 @@ describe('invokeTool', () => {expect(a.validateApiKey).toHaveBeenCalledWith('rawkey', undefined, 's1');});+ it('fails closed for a sessionScoped tool when no sessionId is supplied (no auth with an unscoped id)', async () => {+ const a = auth();+ // A sessionScoped tool whose input omits sessionId (e.g. an optional/loose schema): the per-key+ // allowedSessions check would be skipped if undefined reached validateApiKey, so fence it here.+ const scoped: ToolDescriptor = {+ ...readTool,+ sessionScoped: true,+ inputSchema: z.object({ sessionId: z.string().optional() }),+ handler: () => Promise.resolve('ok'),+ };+ await expect(invokeTool(scoped, {}, 'rawkey', a as unknown as AuthService)).rejects.toBeInstanceOf(+ BadRequestException,+ );+ expect(a.validateApiKey).not.toHaveBeenCalled();+ });+it('rejects when validateApiKey throws for an out-of-scope session', async () => {const a = auth();(a.validateApiKey as jest.Mock).mockRejectedValueOnce(diff --git a/src/core/agent-tools/tool-invoker.ts b/src/core/agent-tools/tool-invoker.tsindex c9c4427d5..ed95f8216 100644--- a/src/core/agent-tools/tool-invoker.ts+++ b/src/core/agent-tools/tool-invoker.ts@@ -30,6 +30,14 @@ export async function invokeTool(const probe = (rawInput ?? {}) as Record<string, unknown>;const sessionId = tool.sessionScoped && typeof probe.sessionId === 'string' ? probe.sessionId : undefined;+ // Fail closed: a sessionScoped tool MUST carry a non-empty sessionId before auth. Otherwise an+ // undefined scope would skip the per-key allowedSessions check inside validateApiKey, letting a+ // session-restricted key drive the tool against any session. This enforces the fence at the runtime+ // boundary regardless of an individual tool's input schema.+ if (tool.sessionScoped && !sessionId) {+ throw new BadRequestException('sessionId is required for this tool');+ }+const apiKey = await authService.validateApiKey(rawKey, undefined, sessionId);onAuthenticated?.(apiKey.id);diff --git a/src/database/migrations/1781000000000-AddBaileysStoredMessages.ts b/src/database/migrations/1781000000000-AddBaileysStoredMessages.tsindex cb6ebc772..37192c124 100644--- a/src/database/migrations/1781000000000-AddBaileysStoredMessages.ts+++ b/src/database/migrations/1781000000000-AddBaileysStoredMessages.ts@@ -31,8 +31,10 @@ export class AddBaileysStoredMessages1781000000000 implements MigrationInterface}public async down(queryRunner: QueryRunner): Promise<void> {- await queryRunner.query(`DROP INDEX "IDX_baileys_stored_messages_session_created"`);- await queryRunner.query(`DROP INDEX "UQ_baileys_stored_messages_session_wamsg"`);- await queryRunner.query(`DROP TABLE "baileys_stored_messages"`);+ // IF EXISTS so revert is idempotent on a synchronize-bootstrapped DB, where this migration was+ // recorded via the up() hasTable early-return and the named indexes were never created.+ await queryRunner.query(`DROP INDEX IF EXISTS "IDX_baileys_stored_messages_session_created"`);+ await queryRunner.query(`DROP INDEX IF EXISTS "UQ_baileys_stored_messages_session_wamsg"`);+ await queryRunner.query(`DROP TABLE IF EXISTS "baileys_stored_messages"`);}}diff --git a/src/database/migrations/1781700000000-AddWebhookDeliveryFailures.ts b/src/database/migrations/1781700000000-AddWebhookDeliveryFailures.tsindex b5f2da60c..280f53692 100644--- a/src/database/migrations/1781700000000-AddWebhookDeliveryFailures.ts+++ b/src/database/migrations/1781700000000-AddWebhookDeliveryFailures.ts@@ -30,7 +30,9 @@ export class AddWebhookDeliveryFailures1781700000000 implements MigrationInterfa}public async down(queryRunner: QueryRunner): Promise<void> {- await queryRunner.query(`DROP INDEX "IDX_webhook_delivery_failures_sessionId"`);- await queryRunner.query(`DROP TABLE "webhook_delivery_failures"`);+ // IF EXISTS so revert is idempotent on a synchronize-bootstrapped DB, where this migration was+ // recorded via the up() hasTable early-return and the named index was never created.+ await queryRunner.query(`DROP INDEX IF EXISTS "IDX_webhook_delivery_failures_sessionId"`);+ await queryRunner.query(`DROP TABLE IF EXISTS "webhook_delivery_failures"`);}}diff --git a/src/database/migrations/__tests__/1781000000000-AddBaileysStoredMessages.spec.ts b/src/database/migrations/__tests__/1781000000000-AddBaileysStoredMessages.spec.tsindex b12da56bd..ce66949a3 100644--- a/src/database/migrations/__tests__/1781000000000-AddBaileysStoredMessages.spec.ts+++ b/src/database/migrations/__tests__/1781000000000-AddBaileysStoredMessages.spec.ts@@ -27,4 +27,11 @@ describe('AddBaileysStoredMessages migration', () => {await runner.release();});++ it('down() does not throw when the named indexes were never created (synchronize-bootstrapped DB)', async () => {+ const runner = ds.createQueryRunner();+ // No up(): the named indexes never existed (a synchronize-built schema uses hash-named ones).+ await expect(new AddBaileysStoredMessages1781000000000().down(runner)).resolves.toBeUndefined();+ await runner.release();+ });});diff --git a/src/database/migrations/__tests__/1781700000000-AddWebhookDeliveryFailures.spec.ts b/src/database/migrations/__tests__/1781700000000-AddWebhookDeliveryFailures.spec.tsindex 8dc882e18..d3ba56b74 100644--- a/src/database/migrations/__tests__/1781700000000-AddWebhookDeliveryFailures.spec.ts+++ b/src/database/migrations/__tests__/1781700000000-AddWebhookDeliveryFailures.spec.ts@@ -38,4 +38,10 @@ describe('AddWebhookDeliveryFailures migration', () => {await migration.down(runner);expect(await tableExists()).toBe(false);});++ it('down() does not throw when the index was never created (synchronize-bootstrapped DB)', async () => {+ const runner = ds.createQueryRunner();+ // No up(): the named index never existed, so a bare DROP INDEX would error — down() must tolerate it.+ await expect(new AddWebhookDeliveryFailures1781700000000().down(runner)).resolves.toBeUndefined();+ });});diff --git a/src/modules/audit/audit.service.spec.ts b/src/modules/audit/audit.service.spec.tsindex c3463019c..4d2e625f8 100644--- a/src/modules/audit/audit.service.spec.ts+++ b/src/modules/audit/audit.service.spec.ts@@ -52,6 +52,12 @@ describe('AuditService', () => {);});+ it('findAll clamps an oversized limit to the max page size (prevents whole-table loads)', async () => {+ await service.findAll({ limit: 99_999_999 });+ const arg = (repo.findAndCount.mock.calls as unknown[][])[0][0] as { take: number };+ expect(arg.take).toBe(200);+ });+it('findAll uses Between only when BOTH dates are present', async () => {const start = new Date('2026-01-01T00:00:00Z');const end = new Date('2026-02-01T00:00:00Z');diff --git a/src/modules/audit/audit.service.ts b/src/modules/audit/audit.service.tsindex affe47787..d47c115eb 100644--- a/src/modules/audit/audit.service.ts+++ b/src/modules/audit/audit.service.ts@@ -5,6 +5,9 @@ import { AuditLog, AuditAction, AuditSeverity } from './entities/audit-log.entitimport { ApiKey } from '../auth/entities/api-key.entity';import { createLogger } from '../../common/services/logger.service';+/** Upper bound on a single audit-log page, so a large `limit` can't load the whole table at once. */+export const MAX_AUDIT_PAGE_SIZE = 200;+interface AuditContext {apiKey?: ApiKey;sessionId?: string;@@ -131,10 +134,14 @@ export class AuditService implements OnModuleInit, OnModuleDestroy {where.createdAt = Between(options.startDate, options.endDate);}+ // Clamp the page size so an arbitrarily large `limit` can't load the whole table into one response.+ const requested = options.limit && options.limit > 0 ? options.limit : 50;+ const take = Math.min(requested, MAX_AUDIT_PAGE_SIZE);+const [data, total] = await this.auditRepository.findAndCount({where,order: { createdAt: 'DESC' },- take: options.limit || 50,+ take,skip: options.offset || 0,});diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.tsindex 3989e1782..6dcedd038 100644--- a/src/modules/message/bulk-message.service.spec.ts+++ b/src/modules/message/bulk-message.service.spec.ts@@ -134,6 +134,27 @@ describe('BulkMessageService.processBatch', () => {const runProcessBatch = (): Promise<void> =>(service as unknown as { processBatch: (id: string) => Promise<void> }).processBatch('b1');+ const inFlightMarkers = (): Map<string, boolean> =>+ (service as unknown as { processingBatches: Map<string, boolean> }).processingBatches;++ it('releases the in-flight marker when the engine is missing (no processingBatches leak)', async () => {+ repo.findOne.mockResolvedValue(makeBatch(1));+ sessionService.getEngine.mockReturnValue(undefined); // engine-not-found → early-return path++ await runProcessBatch();++ expect(inFlightMarkers().has('b1')).toBe(false);+ });++ it('releases the in-flight marker when processing throws (no processingBatches leak)', async () => {+ repo.findOne.mockResolvedValue(makeBatch(1));+ repo.save.mockRejectedValueOnce(new Error('db down')); // the first save (→ PROCESSING) throws++ await runProcessBatch().catch(() => undefined);++ expect(inFlightMarkers().has('b1')).toBe(false);+ });+it('persists every sent message so it appears in chat history / stats', async () => {repo.findOne.mockResolvedValue(makeBatch(1));diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.tsindex 10cabf232..14492a914 100644--- a/src/modules/message/bulk-message.service.ts+++ b/src/modules/message/bulk-message.service.ts@@ -196,7 +196,16 @@ export class BulkMessageService implements OnApplicationBootstrap {if (!batch) return;this.processingBatches.set(batch.id, true);+ // Always release the in-flight marker on every exit path (engine-not-found early return, a thrown+ // save/send, or normal completion) — otherwise the map leaks an entry per such batch.+ try {+ await this.executeBatch(batch);+ } finally {+ this.processingBatches.delete(batch.id);+ }+ }+ private async executeBatch(batch: MessageBatch): Promise<void> {// Update status to processingbatch.status = BatchStatus.PROCESSING;batch.startedAt = new Date();@@ -315,7 +324,6 @@ export class BulkMessageService implements OnApplicationBootstrap {this.stripBatchMediaPayloads(batch.messages);await this.batchRepository.save(batch);- this.processingBatches.delete(batch.id);this.logger.log(`Batch ${batch.batchId} completed: ${batch.progress.sent} sent, ${batch.progress.failed} failed`);}