Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(webhook): bound media fan-out with per-session caps and size-gated payload shedding (#948)
Yudhi Armyndharis91d2b064415f
diff --git a/.env.example b/.env.exampleindex 892acdaf9..700f3721b 100644--- a/.env.example+++ b/.env.example@@ -248,6 +248,13 @@ WEBHOOK_TIMEOUT=10000 # Timeout in millisecondsWEBHOOK_RETRY_DELAY=5000 # Delay between retries in ms# WEBHOOK_DISPATCH_CONCURRENCY=16 # max active inline webhook deliveries per process# WEBHOOK_DISPATCH_MAX_QUEUED=1000 # max inline deliveries parked behind the concurrency cap+# WEBHOOK_MAX_PER_SESSION=16 # max webhooks registered per session; new registrations 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 }+ # 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 large# Days to keep webhook delivery-failure records before pruning them (default 90; set <= 0 to disable).# WEBHOOK_FAILURE_RETENTION_DAYS=90# Block outbound WEBHOOK deliveries to internal/reserved addresses (SSRFdiff --git a/docs/04-security-design.md b/docs/04-security-design.mdindex abcc234c6..08b819617 100644--- a/docs/04-security-design.md+++ b/docs/04-security-design.md@@ -417,6 +417,22 @@ function verifySignature(}```+### Fan-out and Payload Bounds++A single inbound event is delivered to **every** matching webhook of the session, and media arrives+from unauthenticated WhatsApp senders — so the copy amplification is bounded at four points:++| Bound | Knob | Default | Behavior |+| --- | --- | --- | --- |+| 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 |+| 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 }` |+| 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 |++Each webhook still receives its own copy of the event data — a `webhook:before` hook may mutate+`payload.data` in place and must not bleed into sibling deliveries — but the copy is taken after+media shedding, so it is small. The HMAC signature is computed over the exact shed bytes sent.+## 4.9 Security Headers### Recommended Headersdiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 2b7bd9bc9..206392d6f 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -3243,7 +3243,7 @@ Create a webhook for the session.`secret` and `headers` are deliberately excluded from the response. `active` defaults to `true`, `lastTriggeredAt` is `null` on create.-**Errors:** `400` validation failure, unknown body field (whitelist), or SSRF URL rejection · `401` missing/invalid API key · `403` insufficient role+**Errors:** `400` validation failure, unknown body field (whitelist), SSRF URL rejection, or the per-session webhook limit (`WEBHOOK_MAX_PER_SESSION`, default 16 — delete an existing webhook before registering another; webhooks already above the cap are grandfathered and keep working) · `401` missing/invalid API key · `403` insufficient role#### PUT /api/sessions/:sessionId/webhooks/:id@@ -4914,6 +4914,8 @@ These are the events OpenWA actually emits. A webhook is registered with an `eve> **`STORE_EPHEMERAL_MESSAGES=false` affects `message.received`.** When `STORE_EPHEMERAL_MESSAGES` is set to `false`, incoming disappearing messages (those with `ephemeralDuration > 0`) are **not** persisted nor dispatched — no DB insert, no webhook delivery, and no websocket event. Downstream consumers and the dashboard both stop seeing them. Default is `true` (backward compatible — store and dispatch everything).+> **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.+> There is **no** `contact.update` or `presence.update` event, and no `call.accepted` / `call.terminated` lifecycle event yet — only `call.received` is emitted.> **Group-event timing caveat (Baileys).** Membership/metadata changes that occurred while a Baileys session was offline are replayed by WhatsApp on reconnect and are dispatched like live events — but the engine does not forward their original occurrence time, so they carry the **receipt time** as `timestamp`. Treat `group.*` payloads as change notifications rather than a precise clock; stale offline *calls* are never emitted this way (they are filtered by the `offline` flag).diff --git a/src/config/configuration.spec.ts b/src/config/configuration.spec.tsindex 4c7c6052d..d2c29ab8f 100644--- a/src/config/configuration.spec.ts+++ b/src/config/configuration.spec.ts@@ -164,6 +164,44 @@ describe('configuration — in-flight body budget', () => {});});+describe('configuration — webhook fan-out knobs are fail-safe', () => {+ const keys = ['WEBHOOK_MAX_PER_SESSION', 'WEBHOOK_MEDIA_INLINE_MAX_BYTES'];+ const orig: Record<string, string | undefined> = {};+ beforeEach(() => keys.forEach(k => (orig[k] = process.env[k])));+ afterEach(() =>+ keys.forEach(k => {+ if (orig[k] === undefined) delete process.env[k];+ else process.env[k] = orig[k];+ }),+ );++ it('defaults: 16 webhooks per session, 1 MiB inline media', () => {+ keys.forEach(k => delete process.env[k]);+ expect(configuration().webhook.maxPerSession).toBe(16);+ expect(configuration().webhook.mediaInlineMaxBytes).toBe(1024 * 1024);+ });++ it('honors valid non-negative overrides (0 = cap disabled / never inline)', () => {+ process.env.WEBHOOK_MAX_PER_SESSION = '0';+ process.env.WEBHOOK_MEDIA_INLINE_MAX_BYTES = '0';+ expect(configuration().webhook.maxPerSession).toBe(0);+ expect(configuration().webhook.mediaInlineMaxBytes).toBe(0);+ process.env.WEBHOOK_MAX_PER_SESSION = '32';+ process.env.WEBHOOK_MEDIA_INLINE_MAX_BYTES = '262144';+ expect(configuration().webhook.maxPerSession).toBe(32);+ expect(configuration().webhook.mediaInlineMaxBytes).toBe(262144);+ });++ it('falls back to the defaults on garbage or negative values (never silently unlimited)', () => {+ for (const bad of ['', 'abc', '-1']) {+ process.env.WEBHOOK_MAX_PER_SESSION = bad;+ process.env.WEBHOOK_MEDIA_INLINE_MAX_BYTES = bad;+ expect(configuration().webhook.maxPerSession).toBe(16);+ expect(configuration().webhook.mediaInlineMaxBytes).toBe(1024 * 1024);+ }+ });+});+describe('configuration search namespace', () => {// Save/restore the SEARCH_* env vars so a CI .env that sets them cannot flake the default-value// assertions below (mirrors the mutate-and-restore pattern used for PLUGIN_DOWNLOAD_MAX_BYTES etc.).diff --git a/src/config/configuration.ts b/src/config/configuration.tsindex 5199dcccf..6418add53 100644--- a/src/config/configuration.ts+++ b/src/config/configuration.ts@@ -158,6 +158,23 @@ export default () => ({// Upper bound on the serialized webhook body after webhook:before hooks ran; oversize payloads// are recorded as undelivered instead of being sent/persisted. Default 1 MiB.maxPayloadBytes: parseInt(process.env.WEBHOOK_MAX_PAYLOAD_BYTES || '1048576', 10),+ // Max webhooks registered per session. One inbound event fans out to every registered webhook+ // of the session, so an unbounded count multiplies per-event copies of the payload. Creating a+ // NEW webhook above the cap is rejected with 400; existing ones are grandfathered (never+ // deleted). Default 16; 0 disables the cap. Garbage falls back to the default.+ maxPerSession: (() => {+ const n = parseInt(process.env.WEBHOOK_MAX_PER_SESSION ?? '', 10);+ return Number.isFinite(n) && n >= 0 ? n : 16;+ })(),+ // Inline base64 media cap for webhook payloads (decoded bytes). A media blob larger than this+ // is replaced with the { omitted: true, sizeBytes } marker BEFORE the payload is cloned per+ // webhook / queued into Redis, so fan-out and failed-job retention never copy the blob. Media+ // at or under the cap stays inline (unchanged). Default 1 MiB; 0 = never inline media. Garbage+ // falls back to the default.+ mediaInlineMaxBytes: (() => {+ const n = parseInt(process.env.WEBHOOK_MEDIA_INLINE_MAX_BYTES ?? '', 10);+ return Number.isFinite(n) && n >= 0 ? n : 1024 * 1024;+ })(),// How long shutdown waits for in-flight direct deliveries to finish before abandoning them.shutdownDrainMs: parseInt(process.env.WEBHOOK_SHUTDOWN_DRAIN_MS || '5000', 10),},diff --git a/src/config/env.validation.spec.ts b/src/config/env.validation.spec.tsindex d79503f34..54f630f98 100644--- a/src/config/env.validation.spec.ts+++ b/src/config/env.validation.spec.ts@@ -99,6 +99,14 @@ describe('validateEnv', () => {expect(() => validateEnv({ INFLIGHT_BODY_BUDGET_BYTES: '104857600' })).not.toThrow();});+ it('rejects a negative/non-integer webhook fan-out knob (0 is a documented escape hatch)', () => {+ expect(() => validateEnv({ WEBHOOK_MAX_PER_SESSION: '-1' })).toThrow(/WEBHOOK_MAX_PER_SESSION/);+ expect(() => validateEnv({ WEBHOOK_MAX_PER_SESSION: '1.5' })).toThrow(/WEBHOOK_MAX_PER_SESSION/);+ expect(() => validateEnv({ WEBHOOK_MEDIA_INLINE_MAX_BYTES: 'abc' })).toThrow(/WEBHOOK_MEDIA_INLINE_MAX_BYTES/);+ // 0 is meaningful for both: unlimited registrations / never inline media.+ expect(() => validateEnv({ WEBHOOK_MAX_PER_SESSION: '0', WEBHOOK_MEDIA_INLINE_MAX_BYTES: '0' })).not.toThrow();+ });+it('rejects a non-canonical boolean feature flag instead of silently disabling the feature', () => {// QUEUE_ENABLED / MCP_ENABLED / SERVE_DASHBOARD are read at module-eval with `=== 'true'` /// `!== 'false'`, so a typo silently (dis)ables the feature with zero diagnostics. Boot must reject it.diff --git a/src/config/env.validation.ts b/src/config/env.validation.tsindex 8efd69150..613a4bdad 100644--- a/src/config/env.validation.ts+++ b/src/config/env.validation.ts@@ -128,6 +128,8 @@ export function validateEnv(config: EnvConfig): EnvConfig {'INGRESS_INSTANCE_TTL','WEBHOOK_DISPATCH_MAX_QUEUED','STATS_CACHE_TTL_MS', // 0 = memo disabled+ 'WEBHOOK_MAX_PER_SESSION', // 0 = unlimited+ 'WEBHOOK_MEDIA_INLINE_MAX_BYTES', // 0 = never inline media]) {checkNonNegativeInt(key);}diff --git a/src/modules/queue/processors/webhook.processor.ts b/src/modules/queue/processors/webhook.processor.tsindex 7724f5052..6a91ba4ee 100644--- a/src/modules/queue/processors/webhook.processor.ts+++ b/src/modules/queue/processors/webhook.processor.ts@@ -197,7 +197,9 @@ export class WebhookProcessor extends WorkerHost {* failure channel — no dead-letter row, no metric, no webhook:error hook. Normal delivery failures* are already recorded by process() on the final attempt (and non-final ones are retried), so this* handler MUST ignore anything but the stall-exhaustion sentinel, or every failure is recorded- * twice. `job` can be undefined if removeOnFail deleted it first (we never set removeOnFail).+ * twice. `job` can be undefined when the queue's bounded `removeOnFail` window (see QueueModule's+ * WEBHOOK_QUEUE_JOB_OPTIONS) pruned it before this event fired — that window keeps failed-job+ * retention bounded, and each retained payload was size-gated before enqueue.*/@OnWorkerEvent('failed')async onWorkerFailed(job: Job<WebhookJobData> | undefined, error: Error): Promise<void> {diff --git a/src/modules/queue/queue.module.spec.ts b/src/modules/queue/queue.module.spec.tsnew file mode 100644index 000000000..0b6c2d17d--- /dev/null+++ b/src/modules/queue/queue.module.spec.ts@@ -0,0 +1,23 @@+import { WEBHOOK_QUEUE_JOB_OPTIONS } from './queue.module';++/**+ * Failed webhook jobs retain their full payload in Redis until eviction, so the retention window+ * must stay bounded on BOTH axes (count and age). The durable record of a lost delivery is the+ * webhook_delivery_failures row written on the final attempt — Redis is only a debugging window.+ * Payload bytes are bounded separately: media is shed before enqueue (see WebhookService).+ */+describe('WEBHOOK_QUEUE_JOB_OPTIONS', () => {+ it('auto-evicts completed jobs on a bounded count and age', () => {+ const opts = WEBHOOK_QUEUE_JOB_OPTIONS.removeOnComplete;+ expect(typeof opts).toBe('object'); // a bounded window, not `false` (keep forever) / `true` (drop all)+ expect(opts.count).toBeGreaterThan(0);+ expect(opts.age).toBeGreaterThan(0);+ });++ it('auto-evicts failed jobs on a bounded count and age', () => {+ const opts = WEBHOOK_QUEUE_JOB_OPTIONS.removeOnFail;+ expect(typeof opts).toBe('object');+ expect(opts.count).toBeGreaterThan(0);+ expect(opts.age).toBeGreaterThan(0);+ });+});diff --git a/src/modules/queue/queue.module.ts b/src/modules/queue/queue.module.tsindex 877b17285..6a3795734 100644--- a/src/modules/queue/queue.module.ts+++ b/src/modules/queue/queue.module.ts@@ -17,6 +17,17 @@ import { PluginsModule } from '../../core/plugins/plugins.module';// Re-export for backward compatibilityexport { QUEUE_NAMES } from './queue-names';+/**+ * Bounded retention for finished webhook-queue jobs. Failed webhook jobs carry their full payload in+ * Redis until eviction, so the window must stay small — the durable record of a lost delivery is the+ * webhook_delivery_failures row written on the final attempt, not the Redis job. The payload itself+ * is additionally size-gated (media shed) before enqueue, so count × bytes both stay bounded.+ */+export const WEBHOOK_QUEUE_JOB_OPTIONS = {+ removeOnComplete: { age: 3600, count: 1000 },+ removeOnFail: { age: 86400, count: 5000 },+} as const;+@Module({imports: [// Required for WebhookProcessor to inject Repository<Webhook> + Repository<WebhookDeliveryFailure>;@@ -45,10 +56,7 @@ export { QUEUE_NAMES } from './queue-names';name: QUEUE_NAMES.WEBHOOK,// Auto-evict finished jobs so completed/failed webhook payloads don't accumulate in Redis// unbounded. Keep a small recent window for debugging; cap age too.- defaultJobOptions: {- removeOnComplete: { age: 3600, count: 1000 },- removeOnFail: { age: 86400, count: 5000 },- },+ defaultJobOptions: WEBHOOK_QUEUE_JOB_OPTIONS,}),BullModule.registerQueue({name: QUEUE_NAMES.INGRESS,diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.tsindex d24d18891..e581b4b58 100644--- a/src/modules/webhook/webhook.service.spec.ts+++ b/src/modules/webhook/webhook.service.spec.ts@@ -18,7 +18,7 @@ import { NotFoundException } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import * as crypto from 'crypto';import { fetch as undiciFetch } from 'undici';-import { WebhookService, WebhookPayload } from './webhook.service';+import { WebhookService, WebhookPayload, WebhookJobData } from './webhook.service';import { Webhook } from './entities/webhook.entity';import { WebhookDeliveryFailure } from './entities/webhook-delivery-failure.entity';import { WebhookFilters } from './filters/filter-types';@@ -65,6 +65,7 @@ describe('WebhookService', () => {save: jest.fn(),remove: jest.fn(),update: jest.fn(),+ count: jest.fn().mockResolvedValue(0),};failureRepository = {@@ -186,6 +187,59 @@ describe('WebhookService', () => {else process.env.WEBHOOK_SSRF_PROTECT = origProtect;}});++ // ── per-session fan-out cap ───────────────────────────++ it('rejects a NEW webhook with 400 once the session is at the per-session cap (default 16)', async () => {+ (repository.count as jest.Mock).mockResolvedValue(16);++ await expect(service.create('sess-1', { url: 'https://example.com/webhook' })).rejects.toMatchObject({+ status: 400,+ });+ await expect(service.create('sess-1', { url: 'https://example.com/webhook' })).rejects.toThrow(+ /Webhook limit reached/,+ );+ // Refused BEFORE persisting — and grandfathered rows are never deleted to make room.+ expect(repository.create).not.toHaveBeenCalled();+ expect(repository.save).not.toHaveBeenCalled();+ expect(repository.remove).not.toHaveBeenCalled();+ });++ it('creates the webhook while the session is under the cap', async () => {+ (repository.count as jest.Mock).mockResolvedValue(15);+ const webhook = createMockWebhook();+ (repository.create as jest.Mock).mockReturnValue(webhook);+ (repository.save as jest.Mock).mockResolvedValue(webhook);++ await expect(service.create('sess-1', { url: 'https://example.com/webhook' })).resolves.toBeDefined();+ expect(repository.count).toHaveBeenCalledWith({ where: { sessionId: 'sess-1' } });+ });++ it('honors a custom WEBHOOK_MAX_PER_SESSION', async () => {+ (configService.get as jest.Mock).mockImplementation(<T>(key: string, def?: T): T | boolean | number => {+ if (key === 'webhook.maxPerSession') return 2;+ return def as T;+ });+ (repository.count as jest.Mock).mockResolvedValue(2);++ await expect(service.create('sess-1', { url: 'https://example.com/webhook' })).rejects.toMatchObject({+ status: 400,+ });+ });++ it('WEBHOOK_MAX_PER_SESSION=0 disables the cap (legacy unlimited behavior)', async () => {+ (configService.get as jest.Mock).mockImplementation(<T>(key: string, def?: T): T | boolean | number => {+ if (key === 'webhook.maxPerSession') return 0;+ return def as T;+ });+ (repository.count as jest.Mock).mockResolvedValue(9999);+ const webhook = createMockWebhook();+ (repository.create as jest.Mock).mockReturnValue(webhook);+ (repository.save as jest.Mock).mockResolvedValue(webhook);++ await expect(service.create('sess-1', { url: 'https://example.com/webhook' })).resolves.toBeDefined();+ expect(repository.count).not.toHaveBeenCalled(); // no count query when the cap is off+ });});// ── findBySession / findAll / findOne ──────────────────────────────@@ -663,6 +717,103 @@ describe('WebhookService', () => {expect(hookManager.execute).toHaveBeenCalledWith('webhook:error', expect.anything(), expect.anything());});+ it('replaces over-threshold inline media with the omitted marker before fan-out (input not mutated)', async () => {+ (configService.get as jest.Mock).mockImplementation(<T>(key: string, def?: T): T | boolean | number => {+ if (key === 'queue.enabled') return false;+ if (key === 'webhook.mediaInlineMaxBytes') return 1024;+ return def as T;+ });+ const webhook = createMockWebhook({ events: ['message.received'] });+ (repository.find as jest.Mock).mockResolvedValue([webhook]);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });++ const base64 = Buffer.alloc(2048, 7).toString('base64'); // 2048 decoded bytes > 1024 cap+ const data: Record<string, unknown> = {+ from: '[email protected]',+ media: { mimetype: 'image/jpeg', data: base64 },+ };+ await service.dispatch('sess-1', 'message.received', data);++ expect(mockFetch).toHaveBeenCalledTimes(1);+ const body = JSON.parse((mockFetch.mock.calls[0] as [unknown, { body: string }])[1].body) as {+ data: { media: Record<string, unknown> };+ };+ // The documented marker shape — the blob itself never reaches the wire.+ expect(body.data.media).toEqual({ mimetype: 'image/jpeg', omitted: true, sizeBytes: 2048 });+ // The caller's event data keeps its media — shedding works on a copy.+ expect((data.media as { data?: string }).data).toBe(base64);+ expect(failureRepository.insert).not.toHaveBeenCalled();+ });++ it('keeps under-threshold media inline, unchanged', async () => {+ const webhook = createMockWebhook({ events: ['message.received'] });+ (repository.find as jest.Mock).mockResolvedValue([webhook]);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });++ const base64 = Buffer.alloc(512, 3).toString('base64'); // default inline cap is 1 MiB+ await service.dispatch('sess-1', 'message.received', {+ from: '[email protected]',+ media: { mimetype: 'image/jpeg', data: base64 },+ });++ const body = JSON.parse((mockFetch.mock.calls[0] as [unknown, { body: string }])[1].body) as {+ data: { media: { data?: string; omitted?: boolean } };+ };+ expect(body.data.media.data).toBe(base64);+ expect(body.data.media.omitted).toBeUndefined();+ });++ it('sheds inline media to fit the payload budget instead of recording the event undelivered', async () => {+ (configService.get as jest.Mock).mockImplementation(<T>(key: string, def?: T): T | boolean | number => {+ if (key === 'queue.enabled') return false;+ if (key === 'webhook.maxPayloadBytes') return 1024;+ if (key === 'webhook.mediaInlineMaxBytes') return 50 * 1024 * 1024; // pre-fan-out shed stays out of the way+ return def as T;+ });+ const webhook = createMockWebhook({ events: ['message.received'] });+ (repository.find as jest.Mock).mockResolvedValue([webhook]);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });++ // 2048 decoded bytes → ~2.7 KB base64 → serialized payload over the 1024-byte budget.+ const base64 = Buffer.alloc(2048, 9).toString('base64');+ await service.dispatch('sess-1', 'message.received', {+ from: '[email protected]',+ media: { mimetype: 'image/jpeg', filename: 'photo.jpg', data: base64 },+ });++ // Delivered with the marker (filename preserved) — NOT dropped as undelivered.+ expect(mockFetch).toHaveBeenCalledTimes(1);+ const body = JSON.parse((mockFetch.mock.calls[0] as [unknown, { body: string }])[1].body) as {+ data: { media: Record<string, unknown> };+ };+ expect(body.data.media).toEqual({+ mimetype: 'image/jpeg',+ filename: 'photo.jpg',+ omitted: true,+ sizeBytes: 2048,+ });+ expect(failureRepository.insert).not.toHaveBeenCalled();+ });++ it('still records undelivered when an over-budget payload has no inline media to shed', async () => {+ (configService.get as jest.Mock).mockImplementation(<T>(key: string, def?: T): T | boolean | number => {+ if (key === 'queue.enabled') return false;+ if (key === 'webhook.maxPayloadBytes') return 1024;+ return def as T;+ });+ const webhook = createMockWebhook({ events: ['message.received'] });+ (repository.find as jest.Mock).mockResolvedValue([webhook]);+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });++ await service.dispatch('sess-1', 'message.received', { from: '[email protected]', body: 'y'.repeat(4096) });++ expect(mockFetch).not.toHaveBeenCalled();+ expect(failureRepository.insert).toHaveBeenCalledTimes(1);+ });+it('does not retry or record a failure when lastTriggeredAt bookkeeping fails after a 2xx', async () => {const webhook = createMockWebhook({ events: ['message.received'] });(repository.find as jest.Mock).mockResolvedValue([webhook]);@@ -1175,6 +1326,50 @@ describe('WebhookService', () => {describe('dispatch (queue mode)', () => {afterEach(() => (undiciFetch as jest.Mock).mockReset());+ const buildQueueService = async (configGet: (key: string, def?: unknown) => unknown): Promise<WebhookService> => {+ const queueModule: TestingModule = await Test.createTestingModule({+ providers: [+ WebhookService,+ { provide: getRepositoryToken(Webhook, 'data'), useValue: repository },+ { provide: getRepositoryToken(WebhookDeliveryFailure, 'data'), useValue: failureRepository },+ { provide: ConfigService, useValue: { get: jest.fn().mockImplementation(configGet) } },+ { provide: HookManager, useValue: hookManager },+ { provide: getQueueToken(QUEUE_NAMES.WEBHOOK), useValue: webhookQueue },+ ],+ }).compile();+ return queueModule.get<WebhookService>(WebhookService);+ };++ it('enqueues a small, media-shed job when the event carries over-threshold media', async () => {+ const queueService = await buildQueueService((key: string, def?: unknown) => {+ if (key === 'queue.enabled') return true;+ if (key === 'webhook.retryDelay') return 5000;+ if (key === 'webhook.mediaInlineMaxBytes') return 1024;+ return def;+ });+ const webhook = createMockWebhook({ events: ['message.received'] });+ (repository.find as jest.Mock).mockResolvedValue([webhook]);+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });++ const base64 = Buffer.alloc(2048, 5).toString('base64'); // 2048 decoded bytes > 1024 cap+ await queueService.dispatch('sess-1', 'message.received', {+ from: '[email protected]',+ media: { mimetype: 'image/jpeg', data: base64 },+ });++ expect(webhookQueue.add).toHaveBeenCalledTimes(1);+ const addCalls = (webhookQueue.add as jest.Mock).mock.calls as Array<[string, WebhookJobData]>;+ const jobData = addCalls[0][1];+ // The blob is shed BEFORE enqueue: a failed job retains only the marker in Redis, and the+ // bounded removeOnFail window (WEBHOOK_QUEUE_JOB_OPTIONS) keeps count × bytes bounded.+ expect((jobData.payload.data as { media: Record<string, unknown> }).media).toEqual({+ mimetype: 'image/jpeg',+ omitted: true,+ sizeBytes: 2048,+ });+ expect(JSON.stringify(jobData).length).toBeLessThan(2048);+ });+it('should add job to queue when queue is enabled', async () => {// Create a new service with queue enabledconst queueModule: TestingModule = await Test.createTestingModule({diff --git a/src/modules/webhook/webhook.service.ts b/src/modules/webhook/webhook.service.tsindex 4a50f6748..8b362dd10 100644--- a/src/modules/webhook/webhook.service.ts+++ b/src/modules/webhook/webhook.service.ts@@ -63,6 +63,22 @@ export interface WebhookJobData {*/const DEFAULT_WEBHOOK_MAX_PAYLOAD_BYTES = 1024 * 1024;+/**+ * Upper bound on how many webhooks one session can register. One inbound event fans out to EVERY+ * registered webhook of the session, so an unbounded count multiplies per-event payload copies+ * (clones, outbound sockets, queued jobs). Default 16; override with WEBHOOK_MAX_PER_SESSION+ * (0 disables). Only NEW registrations above the cap are refused — existing ones are grandfathered.+ */+const DEFAULT_WEBHOOK_MAX_PER_SESSION = 16;++/**+ * 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;+/*** How long shutdown waits for in-flight direct deliveries (and their dead-letter bookkeeping) to* finish before abandoning them. Default 5s; override with WEBHOOK_SHUTDOWN_DRAIN_MS.@@ -218,6 +234,18 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {async create(sessionId: string, dto: CreateWebhookDto): Promise<Webhook> {await this.validateWebhookUrl(dto.url);+ // Per-session fan-out cap. Soft by design: a concurrent create can race the count check — the+ // cap bounds amplification, it is not a hard invariant. Webhooks already above the cap are left+ // alone; only NEW registrations are refused.+ const maxPerSession = this.configService.get<number>('webhook.maxPerSession', DEFAULT_WEBHOOK_MAX_PER_SESSION);+ if (maxPerSession > 0) {+ const existing = await this.webhookRepository.count({ where: { sessionId } });+ if (existing >= maxPerSession) {+ throw new BadRequestException(+ `Webhook limit reached for this session (${existing}/${maxPerSession}); delete one before registering another`,+ );+ }+ }const webhook = this.webhookRepository.create({sessionId,url: dto.url,@@ -388,6 +416,18 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {const occurredAt = new Date().toISOString();const baseIdempotencyKey = generateIdempotencyKey(event, { ...data, sessionId }, occurredAt);+ // Fan-out amplification bound: shed an over-cap inline media blob ONCE here, before the+ // per-webhook structuredClone below, so N matching webhooks (and the queued jobs retained in+ // Redis) never copy the blob. The per-webhook clone stays — a webhook:before hook may mutate+ // payload.data in place and must not bleed into siblings — but after shedding it is small.+ const baseData =+ matchingWebhooks.length > 0+ ? this.shedInlineMedia(+ data,+ this.configService.get<number>('webhook.mediaInlineMaxBytes', DEFAULT_WEBHOOK_MEDIA_INLINE_MAX_BYTES),+ )+ : data;+const recordUndelivered = async (webhook: Webhook,deliveryId: string,@@ -433,6 +473,7 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {// recursive retry with backoff sleeps).const deliverOne = async (webhook: Webhook, deliveryId: string, idempotencyKey: string): Promise<void> => {let finalPayload: WebhookPayload;+ let body: string;let headers: Record<string, string>;try {const payload: WebhookPayload = {@@ -443,7 +484,7 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {deliveryId,// Give each webhook its own copy of the event data: a webhook:before hook that mutates// payload.data in place would otherwise bleed that change into sibling webhooks.- data: structuredClone(data),+ data: structuredClone(baseData),};// Captured BEFORE the hook chain: a hook may return the same payload object mutated in// place, so reading the canonical timestamp off the hook result afterwards is not safe.@@ -478,11 +519,25 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {// Bound what a hook mutation can make us send. Serializing here also catches a poisoned// (BigInt/circular) hook result as a preflight failure, on BOTH the queued and direct paths.+ // The bytes are serialized ONCE and reused for the size gate, the HMAC signature, and the+ // direct-delivery body (BullMQ re-serializes jobData itself — unavoidable).const maxPayloadBytes = this.configService.get<number>('webhook.maxPayloadBytes',DEFAULT_WEBHOOK_MAX_PAYLOAD_BYTES,);- const payloadBytes = Buffer.byteLength(JSON.stringify(finalPayload), 'utf8');+ body = JSON.stringify(finalPayload);+ let payloadBytes = Buffer.byteLength(body, 'utf8');+ if (payloadBytes > maxPayloadBytes) {+ // 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);+ if (shedData !== finalPayload.data) {+ finalPayload.data = shedData;+ body = JSON.stringify(finalPayload);+ payloadBytes = Buffer.byteLength(body, 'utf8');+ }+ }if (payloadBytes > maxPayloadBytes) {await recordUndelivered(webhook,@@ -513,11 +568,10 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {// Use queue if available, otherwise fallback to direct deliveryif (this.queueEnabled && this.webhookQueue) {try {- // finalPayload comes from the (untrusted) webhook:before hook result, so JSON.stringify can- // throw (BigInt / circular). Keep serialization + signing INSIDE the try so a poisoned payload- // is caught here (one webhook dropped + logged) instead of aborting the whole dispatch loop- // and rejecting the fire-and-forget dispatch() promise.- const signature = webhook.secret ? this.generateSignature(JSON.stringify(finalPayload), webhook.secret) : '';+ // Sign the exact pre-serialized body from preflight. The processor re-serializes the same+ // payload object at delivery time (JSON key order survives the Redis round-trip), so the+ // signature stays valid over the bytes the receiver sees.+ const signature = webhook.secret ? this.generateSignature(body, webhook.secret) : '';if (webhook.secret) {headers['X-OpenWA-Signature'] = signature;@@ -573,7 +627,7 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {// Redis before rejecting, the queued job AND this fallback may both POST. Both paths carry the// same X-OpenWA-Idempotency-Key / X-OpenWA-Delivery-Id, so a conformant receiver dedupes.try {- await this.deliverWebhook(webhook, finalPayload, headers);+ await this.deliverWebhook(webhook, finalPayload, headers, body);await this.hookManager.execute('webhook:delivered',@@ -607,7 +661,7 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {} else {// Direct delivery when queue is disabledtry {- await this.deliverWebhook(webhook, finalPayload, headers);+ await this.deliverWebhook(webhook, finalPayload, headers, body);// Execute hook after successful deliveryawait this.hookManager.execute(@@ -685,15 +739,16 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {/*** @deprecated Use job queue dispatch instead. This is kept for fallback.+ * `body` is the pre-serialized payload from preflight — the exact bytes the size gate checked and+ * (when a secret is set) the signature covers — so it is never re-serialized here.*/private async deliverWebhook(webhook: Webhook,payload: WebhookPayload,headers: Record<string, string>,+ body: string,attempt = 1,): Promise<void> {- const body = JSON.stringify(payload);-// Update retry count headerheaders['X-OpenWA-Retry-Count'] = String(attempt - 1);@@ -751,7 +806,7 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {if (attempt < webhook.retryCount) {const delay = this.configService.get<number>('webhook.retryDelay', 5000);await this.delay(delay * attempt);- return this.deliverWebhook(webhook, payload, headers, attempt + 1);+ return this.deliverWebhook(webhook, payload, headers, body, attempt + 1);}// All direct-path retries exhausted — persist a durable failure record before giving up, mirroring// the queued processor's final-attempt path so the queue-disabled path isn't a blind spot.@@ -772,6 +827,34 @@ export class WebhookService 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/idempotencydiff --git a/test/webhooks.e2e-spec.ts b/test/webhooks.e2e-spec.tsindex 998b4f3cc..236c98158 100644--- a/test/webhooks.e2e-spec.ts+++ b/test/webhooks.e2e-spec.ts@@ -38,6 +38,8 @@ describe('Webhooks (e2e)', () => {let receiver: http.Server;let receiverUrl: string;const prevSsrf = process.env.WEBHOOK_SSRF_PROTECT;+ const prevMaxPerSession = process.env.WEBHOOK_MAX_PER_SESSION;+ const prevMediaInlineMax = process.env.WEBHOOK_MEDIA_INLINE_MAX_BYTES;// Webhooks carry a CASCADE foreign key to a session row, and dispatch looks them up by sessionId.// Persisting one real session per test both satisfies the FK and isolates each case (and prior@@ -73,6 +75,10 @@ describe('Webhooks (e2e)', () => {beforeAll(async () => {process.env.WEBHOOK_SSRF_PROTECT = 'false';+ // Small bounds so the payload-bounds cases below exercise them without bulky setups. Read once+ // at module load, so they must be set before AppModule compiles.+ process.env.WEBHOOK_MAX_PER_SESSION = '3';+ process.env.WEBHOOK_MEDIA_INLINE_MAX_BYTES = '1024';const moduleFixture: TestingModule = await Test.createTestingModule({imports: [AppModule],@@ -107,6 +113,10 @@ describe('Webhooks (e2e)', () => {await new Promise<void>(resolve => receiver.close(() => resolve()));if (prevSsrf === undefined) delete process.env.WEBHOOK_SSRF_PROTECT;else process.env.WEBHOOK_SSRF_PROTECT = prevSsrf;+ if (prevMaxPerSession === undefined) delete process.env.WEBHOOK_MAX_PER_SESSION;+ else process.env.WEBHOOK_MAX_PER_SESSION = prevMaxPerSession;+ if (prevMediaInlineMax === undefined) delete process.env.WEBHOOK_MEDIA_INLINE_MAX_BYTES;+ else process.env.WEBHOOK_MEDIA_INLINE_MAX_BYTES = prevMediaInlineMax;try {await app?.close();} catch {@@ -367,6 +377,68 @@ describe('Webhooks (e2e)', () => {});});+ // ── payload bounds (per-session cap + inline-media shedding) ──────++ describe('payload bounds', () => {+ it('rejects the (cap+1)-th webhook with 400 while the grandfathered ones keep working', async () => {+ const session = await nextSession();+ // WEBHOOK_MAX_PER_SESSION=3 for this suite (set in beforeAll).+ for (let i = 0; i < 3; i++) {+ await createWebhook(session);+ }+ const res = await request(app.getHttpServer())+ .post(`/api/sessions/${session}/webhooks`)+ .set('X-API-Key', apiKey)+ .send({ url: receiverUrl, events: ['*'] })+ .expect(400);+ expect((res.body as { message: string }).message).toMatch(/Webhook limit reached/);++ // The webhooks registered before the cap are unaffected: every one of them still receives.+ await webhookService.dispatch(session, 'message.received', { from: '[email protected]', body: 'hi' });+ await waitFor(() => received.length === 3);+ });++ it('delivers over-threshold media as an omitted marker, signed over the exact shed bytes', async () => {+ const session = await nextSession();+ const secret = 'media-secret';+ await createWebhook(session, { secret });++ const base64 = Buffer.alloc(2048, 11).toString('base64'); // 2048 decoded bytes > 1024 inline cap+ await webhookService.dispatch(session, 'message.received', {+ from: '[email protected]',+ media: { mimetype: 'image/jpeg', filename: 'big.jpg', data: base64 },+ });+ await waitFor(() => received.length === 1);++ const { headers, raw, body } = received[0];+ expect((body as { data: { media: Record<string, unknown> } }).data.media).toEqual({+ mimetype: 'image/jpeg',+ filename: 'big.jpg',+ omitted: true,+ sizeBytes: 2048,+ });+ // The signature verifies over the exact marker-form bytes the receiver got.+ const expected = `sha256=${crypto.createHmac('sha256', secret).update(raw).digest('hex')}`;+ expect(headers['x-openwa-signature']).toBe(expected);+ });++ it('keeps under-threshold media inline end-to-end', async () => {+ const session = await nextSession();+ await createWebhook(session);++ const base64 = Buffer.alloc(512, 4).toString('base64'); // 512 decoded bytes < 1024 inline cap+ await webhookService.dispatch(session, 'message.received', {+ from: '[email protected]',+ media: { mimetype: 'image/jpeg', data: base64 },+ });+ await waitFor(() => received.length === 1);++ const media = (received[0].body as { data: { media: { data?: string; omitted?: boolean } } }).data.media;+ expect(media.data).toBe(base64);+ expect(media.omitted).toBeUndefined();+ });+ });+// ── the test endpoint ─────────────────────────────────────────────describe('test endpoint', () => {