Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(webhook): validate custom headers as a control-char-free string map (#403)
Yudhi Armyndharisdfa5f9fde20b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 984180b0c..bfbb91496 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -51,6 +51,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Security+- **Custom webhook headers are now validated as a flat, control-character-free string map.** The+ `headers` field accepted any object shape with no per-value checks, so a value containing `CR`/`LF`+ could attempt header injection into the outbound webhook request, and non-string values silently+ broke delivery. Creation/update now reject invalid header names, non-string or control-character+ values, and over-large maps (max 50 entries, value max 1024 chars). The delivery-time reserved-name+ filter is unchanged. (#403)- **Swagger UI (`/api/docs`) now defaults OFF in production.** The interactive API schema was servedunauthenticated by default everywhere; it is reconnaissance surface. It remains on outsideproduction and can be re-enabled in production with `ENABLE_SWAGGER=true` (and is still disableddiff --git a/src/modules/webhook/dto/is-header-map.validator.ts b/src/modules/webhook/dto/is-header-map.validator.tsnew file mode 100644index 000000000..c5344ca9e--- /dev/null+++ b/src/modules/webhook/dto/is-header-map.validator.ts@@ -0,0 +1,46 @@+import { registerDecorator, ValidationOptions } from 'class-validator';++const HEADER_NAME = /^[A-Za-z0-9-]+$/;+const MAX_HEADERS = 50;+const MAX_VALUE_LENGTH = 1024;++/** Reject C0 control chars + DEL — notably CR/LF, the header-injection vector. */+function hasControlChar(s: string): boolean {+ for (let i = 0; i < s.length; i++) {+ const c = s.charCodeAt(i);+ if (c < 0x20 || c === 0x7f) return true;+ }+ return false;+}++/**+ * 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), and over-large maps (≤50 entries, value ≤1024 chars). 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 {+ registerDecorator({+ name: 'isHeaderMap',+ target: target.constructor,+ propertyName,+ options,+ validator: {+ validate(value: unknown): boolean {+ if (value === undefined || value === null) return true; // @IsOptional handles absence+ if (typeof value !== 'object' || Array.isArray(value)) return false;+ const entries = Object.entries(value as Record<string, unknown>);+ if (entries.length > MAX_HEADERS) return false;+ return entries.every(+ ([k, v]) =>+ HEADER_NAME.test(k) && typeof v === 'string' && v.length <= MAX_VALUE_LENGTH && !hasControlChar(v),+ );+ },+ defaultMessage(): string {+ return 'headers must be a flat map of valid header names to string values (no control characters, 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 c1477a401..bee10cf01 100644--- a/src/modules/webhook/dto/webhook.dto.spec.ts+++ b/src/modules/webhook/dto/webhook.dto.spec.ts@@ -34,6 +34,45 @@ describe('webhook DTO event validation', () => {});});+describe('webhook DTO custom-header validation', () => {+ it('accepts a flat string->string header map', async () => {+ const errs = await errorsFor(CreateWebhookDto, {+ url: 'https://x.example/hook',+ headers: { 'X-Custom-Header': 'value', Authorization: 'Bearer abc' },+ });+ expect(errs.some(e => e.property === 'headers')).toBe(false);+ });++ it('rejects a header value containing CR/LF (header injection)', async () => {+ const errs = await errorsFor(CreateWebhookDto, {+ url: 'https://x.example/hook',+ headers: { 'X-Evil': 'a\r\nX-Injected: 1' },+ });+ expect(errs.some(e => e.property === 'headers')).toBe(true);+ });++ it('rejects a non-string header value', async () => {+ const errs = await errorsFor(CreateWebhookDto, {+ url: 'https://x.example/hook',+ headers: { 'X-Num': 123 as unknown as string },+ });+ expect(errs.some(e => e.property === 'headers')).toBe(true);+ });++ it('rejects an invalid header name', async () => {+ const errs = await errorsFor(CreateWebhookDto, {+ url: 'https://x.example/hook',+ headers: { 'Bad Header!': 'v' },+ });+ expect(errs.some(e => e.property === 'headers')).toBe(true);+ });++ 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);+ });+});+describe('webhook DTO filter validation', () => {const withFilters = (conditions: unknown) => ({ url: 'https://x.example/hook', filters: { conditions } });diff --git a/src/modules/webhook/dto/webhook.dto.ts b/src/modules/webhook/dto/webhook.dto.tsindex 22cc217b1..57bde9b3d 100644--- a/src/modules/webhook/dto/webhook.dto.ts+++ b/src/modules/webhook/dto/webhook.dto.ts@@ -11,12 +11,12 @@ import {MaxLength,ArrayMinSize,IsIn,- IsObject,} from 'class-validator';import { Expose, plainToInstance } from 'class-transformer';import { Webhook } from '../entities/webhook.entity';import { WebhookFilters } from '../filters/filter-types';import { IsValidWebhookFilters } from '../filters/filter-validation';+import { IsHeaderMap } from './is-header-map.validator';const FILTERS_API_DESCRIPTION ='Optional smart pre-filter. When set, every condition must match (AND) for the webhook to fire. Omit or null to fire on every subscribed event.';@@ -82,7 +82,7 @@ export class CreateWebhookDto {example: { 'X-Custom-Header': 'value' },})@IsOptional()- @IsObject()+ @IsHeaderMap()headers?: Record<string, string>;@ApiPropertyOptional({ description: FILTERS_API_DESCRIPTION, example: FILTERS_API_EXAMPLE })@@ -124,7 +124,7 @@ export class UpdateWebhookDto {@ApiPropertyOptional({ description: 'Custom headers' })@IsOptional()- @IsObject()+ @IsHeaderMap()headers?: Record<string, string>;@ApiPropertyOptional({ description: FILTERS_API_DESCRIPTION, example: FILTERS_API_EXAMPLE })