Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(events): cap inline media on WebSocket message events like webhooks
Yudhi Armyndharise18e62b5aa25
diff --git a/.env.example b/.env.exampleindex 3d9c2707d..67d5baa34 100644--- a/.env.example+++ b/.env.example@@ -377,7 +377,8 @@ WEBHOOK_RETRY_DELAY=5000 # Delay between retries in ms# AUTOMATION_MAX_PER_SESSION=32 # max autoreply rules per session; new rules at/over the cap get# 400 (existing ones are grandfathered); 0 = unlimited# WEBHOOK_MEDIA_INLINE_MAX_BYTES=1048576 # decoded-byte cap for inline base64 media in webhook- # payloads; larger media is delivered as { omitted: true, sizeBytes }+ # payloads AND the WebSocket message.received/.sent events;+ # larger media is delivered as { omitted: true, sizeBytes }# instead (0 = never inline media)# WEBHOOK_MAX_PAYLOAD_BYTES=1048576 # max serialized webhook body; over-budget payloads shed inline# media first, then are recorded undelivered if still too largediff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2c46339f9..68dc1e01d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- `message.received` / `message.sent` WebSocket events shed inline media over `WEBHOOK_MEDIA_INLINE_MAX_BYTES` with the same omitted marker as webhooks; a large blob was broadcast in full to every subscribed socket (and across Redis pub/sub in multi-node).- Both bundled Compose files forward every documented runtime knob; `WEBHOOK_SSRF_REDIRECTS`, `PLUGIN_INSTALL_REQUIRE_PIN` and ~75 other `.env` settings were unreachable in the container. A spec now derives the required list from `.env.example`.- Ingress delivery ids BullMQ refuses at enqueue (numeric, `redrive:<uuid>`, `0:`-led) are hashed to a legal job id, namespaced by plugin/instance; the old refusal read as a Redis failure and silently degraded the delivery to inline dispatch with no retry.- One precise unique-violation predicate (`23505`, `SQLITE_CONSTRAINT_UNIQUE`/`_PRIMARYKEY`): the old prefix match treated every SQLite constraint failure (FK/NOT NULL/CHECK) as a duplicate, swallowing genuine persistence failures and answering misleading 409s.diff --git a/docs/04-security-design.md b/docs/04-security-design.mdindex 9320a2dac..699d8e2f6 100644--- a/docs/04-security-design.md+++ b/docs/04-security-design.md@@ -371,7 +371,7 @@ from unauthenticated WhatsApp senders — so the copy amplification is bounded a| ----------------------------- | ----------------------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ || Webhooks per session | `WEBHOOK_MAX_PER_SESSION` | 16 (`0` = unlimited) | Creating a NEW webhook at/over the cap is rejected with `400`; existing webhooks are grandfathered || Autoreply rules per session | `AUTOMATION_MAX_PER_SESSION` | 32 (`0` = unlimited) | Creating a NEW rule at/over the cap is rejected with `400`; existing rules are grandfathered. Every inbound message is evaluated against every rule of its session |-| Inline media in payloads | `WEBHOOK_MEDIA_INLINE_MAX_BYTES` | 1 MiB (`0` = never inline) | Larger media is replaced once, before per-webhook cloning, with `media: { mimetype, filename?, omitted: true, sizeBytes }` |+| Inline media in payloads | `WEBHOOK_MEDIA_INLINE_MAX_BYTES` | 1 MiB (`0` = never inline) | Larger media is replaced once, before per-webhook cloning and WebSocket broadcast, with `media: { mimetype, filename?, omitted: true, sizeBytes }` || Serialized body size | `WEBHOOK_MAX_PAYLOAD_BYTES` | 1 MiB | Over-budget bodies shed any remaining inline media (marker form) and are re-checked; still over budget → recorded as undelivered, never sent/queued || Failed-job retention in Redis | queue `removeOnComplete` / `removeOnFail` | 1h/1000 completed, 24h/5000 failed | Finished jobs auto-evict; payloads were already media-shed before enqueue, so retained jobs stay small. The durable record of a lost delivery is the `webhook_delivery_failures` row |diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 973164ef4..fb68df3e2 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -6754,7 +6754,7 @@ These are the events OpenWA actually emits. A webhook is registered with an `eve> **`contact` on `message.received` is minimal unless you opt in (`WEBHOOK_CONTACT_DETAILS`).** By default the payload carries only `contact { name?, pushName? }`. Setting `WEBHOOK_CONTACT_DETAILS=true` adds `id`, `number`, `shortName`, `type`, `isMyContact`, `isWAContact`, `isBusiness`, `isEnterprise`, `verifiedName`, `verifiedLevel`, `isBlocked` and `labels`, each present only when the engine has a value for it. Every field is copied from the contact record the engine has already loaded for the message, so opting in costs no extra WhatsApp lookup and cannot add rate-limiting pressure. The same enrichment reaches the websocket event, since both are dispatched from one payload. `contact` itself is omitted entirely when the engine has no value for any of its fields, so treat the whole object as optional rather than just its members. **whatsapp-web.js only** — the Baileys path emits `contact { pushName }` when a push name is available, and never reads this flag.-> **Large media is not inlined into webhook payloads.** A `media` blob whose decoded size exceeds `WEBHOOK_MEDIA_INLINE_MAX_BYTES` (default **1 MiB**; `0` = never inline) is replaced — before the payload is fanned out to your webhook — with the marker form `media: { mimetype, filename?, omitted: true, sizeBytes }`, the same shape the engine emits for capped inbound media. Media at or under the cap stays inline unchanged. Additionally, if the serialized body still exceeds `WEBHOOK_MAX_PAYLOAD_BYTES` (default **1 MiB**) after `webhook:before` hooks ran, any remaining inline media is shed the same way so the event is still delivered; only a payload that is over budget _without_ inline media is dropped (recorded in `GET /api/webhooks/delivery-failures`). Because shedding happens before enqueue, queued and failed BullMQ jobs in Redis never carry the blob either — failed-job retention is bounded by the queue's `removeOnComplete`/`removeOnFail` windows (1h/1000 completed, 24h/5000 failed). Fetch the media itself afterwards via `GET /api/sessions/:sessionId/messages/:chatId/history?includeMedia=true` when you need it.+> **Large media is not inlined into webhook payloads.** A `media` blob whose decoded size exceeds `WEBHOOK_MEDIA_INLINE_MAX_BYTES` (default **1 MiB**; `0` = never inline) is replaced — before the payload is fanned out to your webhook — with the marker form `media: { mimetype, filename?, omitted: true, sizeBytes }`, the same shape the engine emits for capped inbound media. Media at or under the cap stays inline unchanged. Additionally, if the serialized body still exceeds `WEBHOOK_MAX_PAYLOAD_BYTES` (default **1 MiB**) after `webhook:before` hooks ran, any remaining inline media is shed the same way so the event is still delivered; only a payload that is over budget _without_ inline media is dropped (recorded in `GET /api/webhooks/delivery-failures`). Because shedding happens before enqueue, queued and failed BullMQ jobs in Redis never carry the blob either — failed-job retention is bounded by the queue's `removeOnComplete`/`removeOnFail` windows (1h/1000 completed, 24h/5000 failed). Fetch the media itself afterwards via `GET /api/sessions/:sessionId/messages/:chatId/history?includeMedia=true` when you need it. The **WebSocket** `message.received` / `message.sent` events apply the same cap and the same marker: an over-cap blob is never broadcast to subscribed sockets (or, with the Redis adapter enabled, replicated across every replica's pub/sub link), and the media stays fetchable via that same history route.> There is **no** `contact.update` event. `presence.update` is emitted only for chats you have subscribed to (see the presence-subscription endpoint); call outcomes are reported as `call.accepted`, `call.rejected` and `call.missed` alongside `call.received`.diff --git a/src/common/utils/inline-media.ts b/src/common/utils/inline-media.tsnew file mode 100644index 000000000..e004b74b4--- /dev/null+++ b/src/common/utils/inline-media.ts@@ -0,0 +1,33 @@+/**+ * Decoded-byte cap for inline base64 media in outbound event payloads. Shared by the webhook+ * delivery path and the WebSocket gateway so both sinks emit the SAME contract for an over-cap+ * blob. 1 MiB; override with WEBHOOK_MEDIA_INLINE_MAX_BYTES (0 = never inline media).+ */+export const DEFAULT_WEBHOOK_MEDIA_INLINE_MAX_BYTES = 1024 * 1024;++/**+ * Replace an over-cap inline base64 `media.data` blob with the declared-only omitted marker+ * ({ mimetype, filename?, omitted: true, sizeBytes }), the same contract the inbound media cap+ * and the status store already emit, so the multi-MB blob is never cloned per webhook, queued+ * into Redis, or POSTed. Returns the ORIGINAL object when nothing was shed (zero-copy fast path);+ * otherwise a shallow copy with only `media` replaced, so the caller's event data is never+ * mutated. `maxBytes` compares against the DECODED size; 0 sheds any inline blob.+ */+export function shedInlineMedia(data: Record<string, unknown>, maxBytes: number): Record<string, unknown> {+ if (!data || typeof data !== 'object') return data;+ const media = data.media as { mimetype?: unknown; filename?: unknown; data?: unknown; omitted?: unknown } | undefined;+ if (!media || typeof media !== 'object' || typeof media.data !== 'string' || media.data.length === 0) {+ return data;+ }+ const sizeBytes = Buffer.byteLength(media.data, 'base64');+ if (sizeBytes <= maxBytes) return data;+ return {+ ...data,+ media: {+ mimetype: media.mimetype,+ ...(typeof media.filename === 'string' ? { filename: media.filename } : {}),+ omitted: true,+ sizeBytes,+ },+ };+}diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.tsindex 368d2f4a8..47a247bb7 100644--- a/src/modules/events/events.gateway.spec.ts+++ b/src/modules/events/events.gateway.spec.ts@@ -1,4 +1,8 @@import { UnauthorizedException } from '@nestjs/common';+import type { ConfigService } from '@nestjs/config';++// ConfigService stub for the media-shed knob: no override means the default cap applies.+const asConfig = (): { get: jest.Mock } => ({ get: jest.fn((_key: string, defaultValue?: unknown) => defaultValue) });import { Socket } from 'socket.io';import { EventsGateway, isSessionSubscriptionAllowed } from './events.gateway';import { AuthService } from '../auth/auth.service';@@ -68,7 +72,11 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {beforeEach(() => {authService = { validateApiKey: jest.fn() };auditService = { logWarn: jest.fn().mockResolvedValue(null) };- gateway = new EventsGateway(authService as unknown as AuthService, auditService as unknown as AuditService);+ gateway = new EventsGateway(+ authService as unknown as AuthService,+ auditService as unknown as AuditService,+ asConfig() as unknown as ConfigService,+ );});it('rejects a connection with no API key (and never calls validate)', async () => {@@ -379,11 +387,84 @@ const makeCapturingServer = () => {return { server, emit, rooms };};+describe('EventsGateway inline-media shedding on message events', () => {+ const gwWithCap = (cap?: number) => {+ const config = {+ get: jest.fn((_key: string, defaultValue?: unknown) => (cap === undefined ? defaultValue : cap)),+ };+ return new EventsGateway(+ { validateApiKey: jest.fn() } as unknown as AuthService,+ { logWarn: jest.fn().mockResolvedValue(null) } as unknown as AuditService,+ config as unknown as ConfigService,+ );+ };+ const bigMedia = (): Record<string, unknown> => ({+ id: 'm1',+ media: { mimetype: 'image/jpeg', filename: 'big.jpg', data: 'A'.repeat(1024 * 1024 * 2) }, // ~1.5 MB decoded+ });++ it('replaces an over-cap inline media blob with the omitted marker on message.received', () => {+ const gateway = gwWithCap();+ const { server, emit } = makeCapturingServer();+ (gateway as unknown as { server: unknown }).server = server;+ const message = bigMedia();++ gateway.emitMessage('sess-1', message);++ const [, sent] = emit.mock.calls[0] as [string, WSEventMessage];+ expect(sent.payload.event).toBe('message.received');+ const media = (sent.payload.data as Record<string, unknown>).media as Record<string, unknown>;+ expect(media.omitted).toBe(true);+ expect(media.data).toBeUndefined();+ expect(media.mimetype).toBe('image/jpeg');+ expect(media.filename).toBe('big.jpg');+ expect(typeof media.sizeBytes).toBe('number');+ // The caller's event object is never mutated: the webhook fan-out receives the same object.+ expect((message.media as Record<string, unknown>).data).toHaveLength(1024 * 1024 * 2);+ });++ it('sheds on message.sent with the same contract', () => {+ const gateway = gwWithCap();+ const { server, emit } = makeCapturingServer();+ (gateway as unknown as { server: unknown }).server = server;++ gateway.emitMessageSent('sess-1', bigMedia());++ const [, sent] = emit.mock.calls[0] as [string, WSEventMessage];+ expect(sent.payload.event).toBe('message.sent');+ expect(((sent.payload.data as Record<string, unknown>).media as Record<string, unknown>).omitted).toBe(true);+ });++ it('passes small inline media through untouched', () => {+ const gateway = gwWithCap();+ const { server, emit } = makeCapturingServer();+ (gateway as unknown as { server: unknown }).server = server;+ const small = { id: 'm2', media: { mimetype: 'image/png', data: 'aGk=' } };++ gateway.emitMessage('sess-1', small);++ const [, sent] = emit.mock.calls[0] as [string, WSEventMessage];+ expect((sent.payload.data as Record<string, unknown>).media).toEqual({ mimetype: 'image/png', data: 'aGk=' });+ });++ it('honors a tightened cap (0 sheds every inline blob, matching the webhook knob semantics)', () => {+ const gateway = gwWithCap(0);+ const { server, emit } = makeCapturingServer();+ (gateway as unknown as { server: unknown }).server = server;++ gateway.emitMessage('sess-1', { id: 'm3', media: { mimetype: 'image/png', data: 'aGk=' } });++ const [, sent] = emit.mock.calls[0] as [string, WSEventMessage];+ expect(((sent.payload.data as Record<string, unknown>).media as Record<string, unknown>).omitted).toBe(true);+ });+});+describe('EventsGateway.emitToRooms fan-out', () => {const gw = () =>new EventsGateway({ validateApiKey: jest.fn() } as unknown as AuthService,{ logWarn: jest.fn().mockResolvedValue(null) } as unknown as AuditService,+ asConfig() as unknown as ConfigService,);it('delivers one event with a single broadcast across all four rooms (no per-room duplicate emit)', () => {@@ -420,6 +501,7 @@ describe('event catalog ⇔ emitter invariants (drift guard)', () => {const gateway = new EventsGateway({ validateApiKey: jest.fn() } as unknown as AuthService,{ logWarn: jest.fn().mockResolvedValue(null) } as unknown as AuditService,+ asConfig() as unknown as ConfigService,);const captured: string[] = [];const op: { to: () => unknown; emit: (ch: string, msg: WSEventMessage) => boolean } = {@@ -502,7 +584,11 @@ describe('EventsGateway rate limiting', () => {});const buildGateway = (): EventsGateway => {- gateway = new EventsGateway(authService as unknown as AuthService, auditService as unknown as AuditService);+ gateway = new EventsGateway(+ authService as unknown as AuthService,+ auditService as unknown as AuditService,+ asConfig() as unknown as ConfigService,+ );return gateway;};diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex 664c6df0b..348dd76fd 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -10,11 +10,13 @@ import {} from '@nestjs/websockets';import { Server, Socket } from 'socket.io';import { Logger, OnModuleDestroy } from '@nestjs/common';+import { ConfigService } from '@nestjs/config';import { AuthService } from '../auth/auth.service';import { AuditService } from '../audit/audit.service';import { AuditAction } from '../audit/entities/audit-log.entity';import { resolveCorsPolicy } from '../../config/bootstrap-security';import { resolveClientIp as resolveRequestClientIp, type RequestLike } from '../../common/utils/ip';+import { DEFAULT_WEBHOOK_MEDIA_INLINE_MAX_BYTES, shedInlineMedia } from '../../common/utils/inline-media';import type { ApiKey } from '../auth/entities/api-key.entity';import {readWsRateLimitConfig,@@ -129,6 +131,7 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGateconstructor(private readonly authService: AuthService,private readonly auditService: AuditService,+ private readonly configService: ConfigService,) {this.rateLimits = readWsRateLimitConfig();this.frameLimiter = new TokenBucketLimiter(this.rateLimits.framePerSecond, this.rateLimits.frameBurst);@@ -584,18 +587,33 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatethis.emitToRooms(sessionId, 'session.qr', { qrCode });}+ /**+ * Cap for inline base64 media on the message events, shared with the webhook delivery path so+ * both outbound sinks emit the same omitted-marker contract for an over-cap blob. Without this,+ * every subscribed socket (and, with the Redis adapter, every replica's pub/sub link) receives a+ * full copy of a payload that can carry media up to MEDIA_DOWNLOAD_MAX_BYTES (~67 MB base64 for+ * the 50 MiB cap); status.received already keeps its events media-free.+ */+ private messageMediaInlineMaxBytes(): number {+ return this.configService.get<number>('webhook.mediaInlineMaxBytes', DEFAULT_WEBHOOK_MEDIA_INLINE_MAX_BYTES);+ }+/*** Emit new message notification*/emitMessage(sessionId: string, message: Record<string, unknown>) {- this.emitToRooms(sessionId, 'message.received', message);+ this.emitToRooms(sessionId, 'message.received', this.shedMessageMedia(message));}/*** Emit message sent notification*/emitMessageSent(sessionId: string, message: Record<string, unknown>) {- this.emitToRooms(sessionId, 'message.sent', message);+ this.emitToRooms(sessionId, 'message.sent', this.shedMessageMedia(message));+ }++ private shedMessageMedia(message: Record<string, unknown>): Record<string, unknown> {+ return shedInlineMedia(message, this.messageMediaInlineMaxBytes());}/**diff --git a/src/modules/webhook/webhook-delivery.service.ts b/src/modules/webhook/webhook-delivery.service.tsindex 5e5337f74..3f0c3e62a 100644--- a/src/modules/webhook/webhook-delivery.service.ts+++ b/src/modules/webhook/webhook-delivery.service.ts@@ -10,6 +10,7 @@ import { Webhook } from './entities/webhook.entity';import { WebhookDeliveryFailure } from './entities/webhook-delivery-failure.entity';import { recordWebhookDeliveryFailure, statusCodeFromError } from './utils/record-delivery-failure';import { createLogger } from '../../common/services/logger.service';+import { DEFAULT_WEBHOOK_MEDIA_INLINE_MAX_BYTES, shedInlineMedia } from '../../common/utils/inline-media';import { incrementWebhookDeliveryFailures } from '../../common/metrics/webhook-delivery-metrics';import { QUEUE_NAMES } from '../queue/queue-names';import { generateIdempotencyKey, generateDeliveryId } from './utils/idempotency.util';@@ -46,13 +47,9 @@ export interface WebhookJobData {*/const DEFAULT_WEBHOOK_MAX_PAYLOAD_BYTES = 1024 * 1024;-/**- * Decoded-byte cap for inline base64 media in webhook payloads. A larger blob is replaced with the- * engine's omitted-marker shape ({ mimetype, filename?, omitted: true, sizeBytes }) before the- * payload is cloned per webhook or queued, so fan-out and Redis retention never copy it. Default- * 1 MiB; override with WEBHOOK_MEDIA_INLINE_MAX_BYTES (0 = never inline media).- */-const DEFAULT_WEBHOOK_MEDIA_INLINE_MAX_BYTES = 1024 * 1024;+// Decoded-byte cap for inline base64 media and the shed helper live in common/utils/inline-media:+// the WebSocket gateway sheds message-event payloads with the SAME cap and marker, so the two+// outbound sinks stay one contract./*** How long shutdown waits for in-flight direct deliveries (and their dead-letter bookkeeping) to@@ -184,7 +181,7 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {// payload.data in place and must not bleed into siblings — but after shedding it is small.const baseData =matchingWebhooks.length > 0- ? this.shedInlineMedia(+ ? shedInlineMedia(data,this.configService.get<number>('webhook.mediaInlineMaxBytes', DEFAULT_WEBHOOK_MEDIA_INLINE_MAX_BYTES),)@@ -348,7 +345,7 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {// Size-gated body shedding: over budget, strip ANY remaining inline media blob (threshold// 0 — the marker form keeps the event deliverable) and re-check, instead of dropping the// event or queueing a giant payload.- const shedData = this.shedInlineMedia(finalPayload.data, 0);+ const shedData = shedInlineMedia(finalPayload.data, 0);if (shedData !== finalPayload.data) {finalPayload.data = shedData;body = JSON.stringify(finalPayload);@@ -715,34 +712,6 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {}}- /**- * Replace an over-size inline base64 blob on `data.media` with the engine's omitted-marker shape- * ({ mimetype, filename?, omitted: true, sizeBytes }) — the same contract the inbound media cap- * and the status store already emit — so the multi-MB blob is never cloned per webhook, queued- * into Redis, or POSTed. Returns the ORIGINAL object when nothing was shed (zero-copy fast path);- * otherwise a shallow copy with only `media` replaced, so the caller's event data is never- * mutated. `maxBytes` compares against the DECODED size; 0 sheds any inline blob.- */- private shedInlineMedia(data: Record<string, unknown>, maxBytes: number): Record<string, unknown> {- if (!data || typeof data !== 'object') return data;- const media = data.media as- { mimetype?: unknown; filename?: unknown; data?: unknown; omitted?: unknown } | undefined;- if (!media || typeof media !== 'object' || typeof media.data !== 'string' || media.data.length === 0) {- return data;- }- const sizeBytes = Buffer.byteLength(media.data, 'base64');- if (sizeBytes <= maxBytes) return data;- return {- ...data,- media: {- mimetype: media.mimetype,- ...(typeof media.filename === 'string' ? { filename: media.filename } : {}),- omitted: true,- sizeBytes,- },- };- }-/*** Drop operator-supplied custom headers that target reserved names (Content-Type or any* X-OpenWA-* header) so a webhook config cannot forge the signature/event/idempotency