Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(webhook): refuse custom header names that differ only in case
Yudhi Armyndharisba6f5302e52e
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex d984a55c6..e222a0ab2 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -4647,7 +4647,7 @@ Create a webhook for the session.| url | string | yes | `@IsUrl({ require_tld: false })` (allows hostnames without a dot, e.g. `http://localhost:3000`); also run through the SSRF guard, which can reject with `400`. Entity column max 2048 chars. | Webhook URL to receive events. || events | string[] | no | `@IsArray`, `@ArrayMinSize(1)`, `@IsIn([...WEBHOOK_EVENTS, '*'], { each: true })` | Event names to subscribe to (see allowed set above). Defaults to `["message.received"]` when omitted. || secret | string | no | `@IsString`, `@MinLength(16)`, `@MaxLength(255)` | HMAC-SHA256 signing key. **Write-only** — never returned by a webhook route (not returned by `GET /api/infra/export-data` either). Used for `X-OpenWA-Signature`. Defaults to `null`. |-| headers | Record<string,string> | no | `@IsHeaderMap()`: flat object (not array), ≤50 entries, names match `/^[A-Za-z0-9-]+$/`, values are strings ≤1024 chars with no C0 control/DEL (CR/LF injection guard) and nothing above U+00FF (Latin-1 only). | Custom headers added to deliveries. **Write-only** — never returned by a webhook route (not returned by `GET /api/infra/export-data` either). At delivery, `content-type` and `x-openwa-*` names are stripped, and so are the connection-level names the HTTP client owns: `connection`, `content-length`, `expect`, `keep-alive`, `te`, `trailer`, `transfer-encoding` and `upgrade`. Defaults to `{}`. |+| headers | Record<string,string> | no | `@IsHeaderMap()`: flat object (not array), ≤50 entries, names match `/^[A-Za-z0-9-]+$/` and are unique ignoring case, values are strings ≤1024 chars with no C0 control/DEL (CR/LF injection guard) and nothing above U+00FF (Latin-1 only). | Custom headers added to deliveries. **Write-only** — never returned by a webhook route (not returned by `GET /api/infra/export-data` either). At delivery, `content-type`, `user-agent` and `x-openwa-*` names are stripped, and so are the connection-level names the HTTP client owns: `connection`, `content-length`, `expect`, `keep-alive`, `te`, `trailer`, `transfer-encoding` and `upgrade`. Defaults to `{}`. || filters | WebhookFilters \| null | no | `@IsValidWebhookFilters()`, i.e. `{ conditions: [...] }`; each condition `{ field, operator('is'\|'isNot'\|'contains'\|'equals'), value(string\|string[]\|boolean), caseSensitive?:boolean }`; bounds: max 20 conditions, 100 values/condition, 1000-char text values. Message fields: `sender`, `recipient`, `chatId`, `body`, `type`, `isGroup`, `kind`, `fromMe`, `hasMedia`, `mentions`. An id-valued condition accepts a bare phone number, but a group must be written as its full `<id>@g.us` JID: bare digits canonicalise to `@c.us` and match no group. | Optional AND pre-filter; **all** conditions must match for the webhook to fire. Omit/null = fire on every subscribed event. Defaults to `null`. ⚠️ A condition whose field is DEFINED for the event family but absent from that event's payload does not scope the event, it decides it outright: an `is`, `contains` or `equals` condition cannot match and suppresses the event, while an `isNot` condition passes it, and so does a boolean field compared with `false`, because an absent boolean reads as `false` (a field with no definition for the family is skipped instead). `message.ack`/`message.failed` carry `{ id, messageId, status, ack }` and `message.reaction` carries `{ messageId, chatId, reaction, senderId }`, none of which has a sender or body, so a `sender` `is` filter silently drops all three and a `sender` `isNot` filter delivers all three. `message.ack`/`message.failed` carry no `chatId` either, so a `chatId` `isNot` exclusion does not keep that chat's acks and failures out. Scope the subscription with `events[]` rather than relying on a filter to be inert. Set `LOG_LEVEL=debug` to see each suppression and the payload fields that were available. || retryCount | number (int) | no | `@IsInt`, `@Min(0)`, `@Max(5)` | Total delivery attempts per event, including the first: `0` and `1` both mean a single attempt with no retry. An event that exhausts them is recorded in `GET /api/webhooks/delivery-failures`; the webhook stays active. Defaults to `3`. |@@ -7145,4 +7145,4 @@ When the queue is enabled, a non-2xx response, timeout (`WEBHOOK_TIMEOUT`, defau### SSRF guard on registration-Webhook URLs are validated at **registration time**, not just at delivery. When SSRF protection is enabled (the default), creating or updating a webhook with a URL that resolves to a private/internal/loopback address is rejected synchronously with `400 Bad Request` instead of failing silently later at delivery. The `SSRF_ALLOWED_HOSTS` escape-hatch applies equally to registration and delivery. Independently of the SSRF flag, a URL embedding credentials (`https://user:pass@host/hook`) is rejected with `400` — such credentials would otherwise be persisted and echoed into delivery logs and dead-letter rows. Operator-supplied custom headers that target reserved names (`Content-Type` or any `X-OpenWA-*`) are stripped, so a webhook config cannot forge the signature, event, or idempotency headers. The connection-level names the HTTP client owns (`Connection`, `Content-Length`, `Expect`, `Keep-Alive`, `TE`, `Trailer`, `Transfer-Encoding`, `Upgrade`) are stripped as well, since setting one would fail or corrupt the delivery.+Webhook URLs are validated at **registration time**, not just at delivery. When SSRF protection is enabled (the default), creating or updating a webhook with a URL that resolves to a private/internal/loopback address is rejected synchronously with `400 Bad Request` instead of failing silently later at delivery. The `SSRF_ALLOWED_HOSTS` escape-hatch applies equally to registration and delivery. Independently of the SSRF flag, a URL embedding credentials (`https://user:pass@host/hook`) is rejected with `400` — such credentials would otherwise be persisted and echoed into delivery logs and dead-letter rows. Operator-supplied custom headers that target reserved names (`Content-Type`, `User-Agent` or any `X-OpenWA-*`, in any letter case) are stripped, so a webhook config cannot forge the signature, event, or idempotency headers. A header map with two names that differ only in case is rejected with `400`. The connection-level names the HTTP client owns (`Connection`, `Content-Length`, `Expect`, `Keep-Alive`, `TE`, `Trailer`, `Transfer-Encoding`, `Upgrade`) are stripped as well, since setting one would fail or corrupt the delivery.diff --git a/src/modules/webhook/dto/is-header-map.validator.ts b/src/modules/webhook/dto/is-header-map.validator.tsindex b5946e61f..59727a8ed 100644--- a/src/modules/webhook/dto/is-header-map.validator.ts+++ b/src/modules/webhook/dto/is-header-map.validator.ts@@ -20,9 +20,10 @@ function hasInvalidValueChar(s: string): boolean {/*** Validate operator-supplied webhook custom headers as a flat map of valid header names to string* values: rejects non-object shapes, invalid header names, non-string or control-character values- * (CR/LF header injection), values outside Latin-1, and over-large maps (≤50 entries, value ≤1024- * chars). Reserved-name stripping still happens at delivery time (sanitizeCustomHeaders); this is the- * input-side guard.+ * (CR/LF header injection), values outside Latin-1, over-large maps (≤50 entries, value ≤1024+ * chars), and two names that differ only in case: the HTTP client joins those into one+ * comma-separated value instead of sending either as written. Reserved-name stripping still happens+ * at delivery time (sanitizeCustomHeaders); this is the input-side guard.*/export function IsHeaderMap(options?: ValidationOptions) {return function (target: object, propertyName: string): void {@@ -37,13 +38,14 @@ export function IsHeaderMap(options?: ValidationOptions) {if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;const entries = Object.entries(value as Record<string, unknown>);if (entries.length > MAX_HEADERS) return false;+ if (new Set(entries.map(([k]) => k.toLowerCase())).size !== entries.length) return false;return entries.every(([k, v]) =>HEADER_NAME.test(k) && typeof v === 'string' && v.length <= MAX_VALUE_LENGTH && !hasInvalidValueChar(v),);},defaultMessage(): string {- return 'headers must be a flat map of valid header names to string values (no control characters or characters outside Latin-1, max 50 entries, value max 1024 chars)';+ return 'headers must be a flat map of valid header names to string values (names unique ignoring case, no control characters or characters outside Latin-1, max 50 entries, value max 1024 chars)';},},});diff --git a/src/modules/webhook/dto/webhook.dto.spec.ts b/src/modules/webhook/dto/webhook.dto.spec.tsindex 3a07cc289..93c52b80f 100644--- a/src/modules/webhook/dto/webhook.dto.spec.ts+++ b/src/modules/webhook/dto/webhook.dto.spec.ts@@ -99,6 +99,17 @@ describe('webhook DTO custom-header validation', () => {expect(errs.some(e => e.property === 'headers')).toBe(true);});+ // The HTTP client joins case-variant names into one comma-separated value, so neither value is+ // sent as written and a receiver checking one credential sees both.+ it('rejects two header names that differ only in case, on create and update', async () => {+ const headers = { Authorization: 'Bearer a', authorization: 'Bearer b' };+ const create = await errorsFor(CreateWebhookDto, { url: 'https://x.example/hook', headers });+ expect(create.some(e => e.property === 'headers')).toBe(true);+ const update = await errorsFor(UpdateWebhookDto, { headers });+ expect(update.some(e => e.property === 'headers')).toBe(true);+ expect(await errorsFor(UpdateWebhookDto, { headers: { 'X-A': '1', 'X-B': '2' } })).toHaveLength(0);+ });+it('UpdateWebhookDto applies the same header validation', async () => {const errs = await errorsFor(UpdateWebhookDto, { headers: { 'X-Evil': 'a\nb' } });expect(errs.some(e => e.property === 'headers')).toBe(true);diff --git a/src/modules/webhook/dto/webhook.dto.ts b/src/modules/webhook/dto/webhook.dto.tsindex 3d8179d02..c7661bfbe 100644--- a/src/modules/webhook/dto/webhook.dto.ts+++ b/src/modules/webhook/dto/webhook.dto.ts@@ -148,8 +148,9 @@ export class CreateWebhookDto {@ApiPropertyOptional({description:- 'Custom headers to include in webhook requests. Never returned by any webhook route. At delivery, ' +- '`content-type` and `x-openwa-*` names are stripped so a custom header cannot shadow a system one, ' ++ 'Custom headers to include in webhook requests. Names must be unique ignoring case. Never returned by ' ++ 'any webhook route. At delivery, `content-type`, `user-agent` and `x-openwa-*` names are stripped so a ' ++ 'custom header cannot shadow a system one, ' +'and so are the connection-level names the HTTP client owns (`connection`, `content-length`, ' +'`expect`, `keep-alive`, `te`, `trailer`, `transfer-encoding`, `upgrade`).',example: { 'X-Custom-Header': 'value' },diff --git a/src/modules/webhook/utils/deliver-once.spec.ts b/src/modules/webhook/utils/deliver-once.spec.tsindex 2052f2c3e..8648129dd 100644--- a/src/modules/webhook/utils/deliver-once.spec.ts+++ b/src/modules/webhook/utils/deliver-once.spec.ts@@ -1,4 +1,5 @@-import { postWebhookPayload, sanitizeCustomHeaders } from './deliver-once';+import { Headers } from 'undici';+import { buildDeliveryHeaders, postWebhookPayload, sanitizeCustomHeaders } from './deliver-once';/*** Direct coverage for the shared delivery core both paths (direct and queued processor) now route@@ -59,6 +60,23 @@ describe('sanitizeCustomHeaders', () => {).toEqual({ 'X-Custom': 'v', Authorization: 'Bearer t' });});+ it('drops a custom User-Agent in any spelling', () => {+ expect(sanitizeCustomHeaders({ 'user-agent': 'x', 'USER-AGENT': 'y', 'User-Agent': 'z', 'X-Keep': 'v' })).toEqual({+ 'X-Keep': 'v',+ });+ });++ it('keeps a custom header whose name only starts with User-Agent', () => {+ expect(sanitizeCustomHeaders({ 'User-Agent-Version': '2' })).toEqual({ 'User-Agent-Version': '2' });+ });++ // Asserted through undici's Headers, which is what goes on the wire: a case-variant key there is+ // joined with the system value rather than replaced by it.+ it('sends only the system User-Agent when the custom map carries a lowercase one', () => {+ const headers = buildDeliveryHeaders({ headers: { 'user-agent': 'custom' } }, 'message.received', 'k', 'd', '{}');+ expect(new Headers(headers).get('user-agent')).toBe('OpenWA-Webhook/1.0.0');+ });+// undici throws on several of these (every delivery then fails with "fetch failed") and a wrong// Content-Length breaks the request framing; the HTTP client owns all of them.it('drops connection-level and framing headers the HTTP client owns', () => {diff --git a/src/modules/webhook/utils/deliver-once.ts b/src/modules/webhook/utils/deliver-once.tsindex c3dcb188a..7f7e6c14f 100644--- a/src/modules/webhook/utils/deliver-once.ts+++ b/src/modules/webhook/utils/deliver-once.ts@@ -6,18 +6,19 @@ import { WebhookDeliveryFailure } from '../entities/webhook-delivery-failure.entimport { recordWebhookDeliveryFailure, statusCodeFromError } from './record-delivery-failure';/**- * 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- * headers. Spread the result BEFORE the system headers so system always wins. Connection-level- * and framing headers are dropped too: the HTTP client owns them, undici throws on several- * (failing every delivery) and a wrong Content-Length breaks the request.+ * Drop operator-supplied custom headers that target the names the system sets (Content-Type,+ * User-Agent or any X-OpenWA-* header, in any spelling) so a webhook config cannot forge the+ * signature/event/idempotency headers. Dropping, not overriding, is what makes the system value+ * win: the HTTP client joins a case variant with the system one instead of replacing it.+ * Connection-level and framing headers are dropped too: the HTTP client owns them, undici throws on+ * several (failing every delivery) and a wrong Content-Length breaks the request.*/export function sanitizeCustomHeaders(custom: Record<string, string> | null | undefined): Record<string, string> {const safe: Record<string, string> = {};for (const [key, value] of Object.entries(custom ?? {})) {if (!/^(content-type|x-openwa-)/i.test(key) &&- !/^(connection|content-length|expect|keep-alive|te|trailer|transfer-encoding|upgrade)$/i.test(key)+ !/^(user-agent|connection|content-length|expect|keep-alive|te|trailer|transfer-encoding|upgrade)$/i.test(key)) {safe[key] = value;}