Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(validation): bound unvalidated request inputs + escape vCard structural chars (#545)
Yudhi Armyndharis9a41f34b33a9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b0a0f52b9..d0e322ed5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Security+- **Contact-card names escape vCard structural characters.** A contact whose name contained a backslash, semicolon, or comma could alter the structure of the generated vCard's `FN` field; those characters are now escaped per the vCard spec, complementing the existing CR/LF stripping. (#545)+- **Request inputs are bounded against oversized payloads.** Several endpoints accepted unbounded strings or arrays: bulk message `text`/`caption` now match the single-send caps (4096 / 1024), bulk `variables` must be an object, the `mentions` array is capped in size and per-entry length, group name/subject/description, status text/caption, contact name/number, reply text, and reaction emoji now have length limits, and `POST /infra/storage/import` validates its body through a DTO so the global whitelist applies. (#545)++### Fixed++- **The audit-log listing rejects a negative offset.** `GET /audit?offset=-N` previously passed a negative skip to the query driver; the offset is now clamped to a non-negative value. (#545)- **API-key lifecycle operations are now recorded in the audit log.** Creating, deleting, and revoking an API key previously left no audit entry (only failed authentication was logged). Each now writes an `api_key_created` / `api_key_deleted` / `api_key_revoked` event with the acting admin key, the client IP, and the target key — giving administrators a forensic trail for credential management. (#546)### Fixeddiff --git a/src/engine/adapters/vcard.spec.ts b/src/engine/adapters/vcard.spec.tsindex c51b5a265..c6825cb72 100644--- a/src/engine/adapters/vcard.spec.ts+++ b/src/engine/adapters/vcard.spec.ts@@ -27,4 +27,14 @@ describe('buildVCard', () => {'END:VCARD',]);});++ it('escapes vCard structural characters (backslash, semicolon, comma) in FN', () => {+ // name = Acme;Corp,Ltd\X (one literal backslash before X)+ const vcard = buildVCard({ name: 'Acme;Corp,Ltd\\X', number: '628123' });+ const fnLine = vcard.split('\n').find(l => l.startsWith('FN:'));+ // backslash escaped first, then ; and , — so the value carries a literal backslash before each.+ expect(fnLine).toBe('FN:Acme\\;Corp\\,Ltd\\\\X');+ // the bare (unescaped) structural sequence must not survive — proves the escape isn't a JS no-op.+ expect(fnLine?.includes('Acme;Corp')).toBe(false);+ });});diff --git a/src/engine/adapters/vcard.ts b/src/engine/adapters/vcard.tsindex 5f9750b56..45d45aed1 100644--- a/src/engine/adapters/vcard.ts+++ b/src/engine/adapters/vcard.ts@@ -9,13 +9,18 @@ import { ContactCard } from '../interfaces/whatsapp-engine.interface';*/export function buildVCard(contact: ContactCard): string {const clean = (s: string): string => s.replace(/[\r\n]+/g, ' ');+ // Escape the vCard structural characters in a text value (RFC 6350 §3.4). Backslash MUST be escaped+ // first so the backslashes we add for ; and , are not themselves doubled. NOTE: the source literals+ // are double-backslashed on purpose — `'\\;'` is a literal backslash+semicolon, whereas `'\;'` would+ // be a JS no-op (the unknown escape collapses to just `;`).+ const esc = (s: string): string => s.replace(/\\/g, '\\\\').replace(/;/g, '\\;').replace(/,/g, '\\,');const name = clean(contact.name);const number = clean(contact.number);const waid = number.replace(/\D/g, '');return ['BEGIN:VCARD','VERSION:3.0',- `FN:${name}`,+ `FN:${esc(name)}`,`TEL;type=CELL;type=VOICE;waid=${waid}:${number}`,'END:VCARD',].join('\n');diff --git a/src/modules/audit/audit.service.spec.ts b/src/modules/audit/audit.service.spec.tsindex 4d2e625f8..2c360212d 100644--- a/src/modules/audit/audit.service.spec.ts+++ b/src/modules/audit/audit.service.spec.ts@@ -58,6 +58,12 @@ describe('AuditService', () => {expect(arg.take).toBe(200);});+ it('findAll clamps a negative offset to 0 (no negative skip reaches the query)', async () => {+ await service.findAll({ offset: -5 });+ const arg = (repo.findAndCount.mock.calls as unknown[][])[0][0] as { skip: number };+ expect(arg.skip).toBe(0);+ });+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 d47c115eb..fb8c23df5 100644--- a/src/modules/audit/audit.service.ts+++ b/src/modules/audit/audit.service.ts@@ -142,7 +142,9 @@ export class AuditService implements OnModuleInit, OnModuleDestroy {where,order: { createdAt: 'DESC' },take,- skip: options.offset || 0,+ // Clamp to a non-negative skip: a negative offset (e.g. from an unvalidated `?offset=-5`) would+ // otherwise reach the query driver verbatim.+ skip: options.offset && options.offset > 0 ? options.offset : 0,});return { data, total };diff --git a/src/modules/group/dto/group.dto.spec.ts b/src/modules/group/dto/group.dto.spec.tsindex 67cf5be2b..e1abb7ec9 100644--- a/src/modules/group/dto/group.dto.spec.ts+++ b/src/modules/group/dto/group.dto.spec.ts@@ -1,7 +1,7 @@import 'reflect-metadata';import { validate, ValidationError } from 'class-validator';import { plainToInstance } from 'class-transformer';-import { ParticipantsDto, CreateGroupDto, GroupSubjectDto } from './group.dto';+import { ParticipantsDto, CreateGroupDto, GroupSubjectDto, GroupDescriptionDto } from './group.dto';// Mirror the global ValidationPipe options (src/main.ts): whitelist + forbidNonWhitelisted.const PIPE_OPTS = { whitelist: true, forbidNonWhitelisted: true };@@ -40,4 +40,9 @@ describe('group DTO validation', () => {const errors = await errorsFor(GroupSubjectDto, { subject: '' });expect(errors.length).toBeGreaterThan(0);});++ it('caps the group description length (accepts 1024, rejects beyond)', async () => {+ expect(await errorsFor(GroupDescriptionDto, { description: 'a'.repeat(1024) })).toHaveLength(0);+ expect((await errorsFor(GroupDescriptionDto, { description: 'a'.repeat(1025) })).length).toBeGreaterThan(0);+ });});diff --git a/src/modules/group/dto/group.dto.ts b/src/modules/group/dto/group.dto.tsindex c15a677d1..050719e56 100644--- a/src/modules/group/dto/group.dto.ts+++ b/src/modules/group/dto/group.dto.ts@@ -1,10 +1,11 @@import { ApiProperty } from '@nestjs/swagger';-import { IsArray, ArrayNotEmpty, IsString, IsNotEmpty } from 'class-validator';+import { IsArray, ArrayNotEmpty, IsString, IsNotEmpty, MaxLength } from 'class-validator';export class CreateGroupDto {- @ApiProperty({ description: 'Group subject/name' })+ @ApiProperty({ description: 'Group subject/name', maxLength: 100 })@IsString()@IsNotEmpty()+ @MaxLength(100)name: string;@ApiProperty({ description: 'Participant WhatsApp IDs (e.g. [email protected])', type: [String] })@@ -23,14 +24,16 @@ export class ParticipantsDto {}export class GroupSubjectDto {- @ApiProperty({ description: 'New group subject/name' })+ @ApiProperty({ description: 'New group subject/name', maxLength: 100 })@IsString()@IsNotEmpty()+ @MaxLength(100)subject: string;}export class GroupDescriptionDto {- @ApiProperty({ description: 'New group description (may be empty to clear it)' })+ @ApiProperty({ description: 'New group description (may be empty to clear it)', maxLength: 1024 })@IsString()+ @MaxLength(1024)description: string;}diff --git a/src/modules/infra/dto/import-storage.dto.ts b/src/modules/infra/dto/import-storage.dto.tsnew file mode 100644index 000000000..353e06e5e--- /dev/null+++ b/src/modules/infra/dto/import-storage.dto.ts@@ -0,0 +1,14 @@+import { ApiProperty } from '@nestjs/swagger';+import { IsString, IsNotEmpty } from 'class-validator';++/**+ * Body for POST /infra/storage/import. A class (not an inline object literal) so the global+ * ValidationPipe's whitelist/forbidNonWhitelisted actually runs — rejecting a non-string or extra+ * property before the handler's data-directory path check.+ */+export class ImportStorageDto {+ @ApiProperty({ description: 'Path to the tar.gz file to import (must be inside the data directory)' })+ @IsString()+ @IsNotEmpty()+ filePath: string;+}diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.tsindex 1bfa52694..fc33bcfc9 100644--- a/src/modules/infra/infra.controller.ts+++ b/src/modules/infra/infra.controller.ts@@ -14,6 +14,7 @@ import { CacheService } from '../../common/cache/cache.service';import { StorageService } from '../../common/storage/storage.service';import { ShutdownService } from '../../common/services/shutdown.service';import { createLogger } from '../../common/services/logger.service';+import { ImportStorageDto } from './dto/import-storage.dto';import * as fs from 'fs';import * as path from 'path';import { randomUUID } from 'crypto';@@ -1190,7 +1191,7 @@ export class InfraController {@ApiBody({ description: 'Path to tar.gz file to import' })@ApiResponse({ status: 200, description: 'Import result' })async importStorage(- @Body() body: { filePath: string },+ @Body() body: ImportStorageDto,): Promise<{ imported: boolean; count: number; storageType: string }> {const { filePath } = body;diff --git a/src/modules/message/dto/bulk-message.dto.spec.ts b/src/modules/message/dto/bulk-message.dto.spec.tsindex 3747a68a8..3f3ba6892 100644--- a/src/modules/message/dto/bulk-message.dto.spec.ts+++ b/src/modules/message/dto/bulk-message.dto.spec.ts@@ -26,3 +26,20 @@ describe('SendBulkMessageDto nested media validation', () => {expect((await validateBulk(imageItem({ base64: 12345 }))).length).toBeGreaterThan(0);});});++const textItem = (text: string, extra: Record<string, unknown> = {}) => ({+ messages: [{ chatId: '[email protected]', type: 'text', content: { text }, ...extra }],+});++describe('SendBulkMessageDto content length + variables validation', () => {+ it('accepts text at the 4096 cap and rejects beyond it (parity with single-send)', async () => {+ expect(await validateBulk(textItem('a'.repeat(4096)))).toHaveLength(0);+ expect((await validateBulk(textItem('a'.repeat(4097)))).length).toBeGreaterThan(0);+ });++ it('accepts an object variables map and rejects a non-object', async () => {+ expect(await validateBulk(textItem('hi', { variables: { name: 'Alice' } }))).toHaveLength(0);+ expect((await validateBulk(textItem('hi', { variables: 'oops' }))).length).toBeGreaterThan(0);+ expect((await validateBulk(textItem('hi', { variables: [1, 2, 3] }))).length).toBeGreaterThan(0);+ });+});diff --git a/src/modules/message/dto/bulk-message.dto.ts b/src/modules/message/dto/bulk-message.dto.tsindex f5c129678..8a61294ef 100644--- a/src/modules/message/dto/bulk-message.dto.ts+++ b/src/modules/message/dto/bulk-message.dto.ts@@ -3,10 +3,12 @@ import {IsString,IsIn,IsArray,+ IsObject,IsOptional,IsNumber,IsBoolean,ValidateNested,+ MaxLength,Min,Max,ArrayMaxSize,@@ -36,9 +38,10 @@ class BulkMediaDto {}class BulkMessageContentDto {- @ApiPropertyOptional({ description: 'Text content for text messages' })+ @ApiPropertyOptional({ description: 'Text content for text messages', maxLength: 4096 })@IsOptional()@IsString()+ @MaxLength(4096)text?: string;// Typed nested DTOs (not bare object literals) so the global ValidationPipe's whitelist /@@ -68,9 +71,10 @@ class BulkMessageContentDto {@Type(() => BulkMediaDto)document?: BulkMediaDto;- @ApiPropertyOptional({ description: 'Caption for media messages' })+ @ApiPropertyOptional({ description: 'Caption for media messages', maxLength: 1024 })@IsOptional()@IsString()+ @MaxLength(1024)caption?: string;}@@ -90,6 +94,7 @@ class BulkMessageItemDto {@ApiPropertyOptional({ description: 'Variables for template substitution' })@IsOptional()+ @IsObject()variables?: Record<string, string>;}diff --git a/src/modules/message/dto/message-actions.dto.ts b/src/modules/message/dto/message-actions.dto.tsindex af14d30ec..a8e97d65b 100644--- a/src/modules/message/dto/message-actions.dto.ts+++ b/src/modules/message/dto/message-actions.dto.ts@@ -1,5 +1,5 @@import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';-import { IsString, IsNotEmpty, IsOptional, IsLatitude, IsLongitude, IsBoolean } from 'class-validator';+import { IsString, IsNotEmpty, IsOptional, IsLatitude, IsLongitude, IsBoolean, MaxLength } from 'class-validator';/*** Validated DTOs for the message action endpoints. These replaced inline@@ -21,14 +21,16 @@ export class SendLocationDto {@IsLongitude()longitude: number;- @ApiPropertyOptional()+ @ApiPropertyOptional({ maxLength: 1024 })@IsOptional()@IsString()+ @MaxLength(1024)description?: string;- @ApiPropertyOptional()+ @ApiPropertyOptional({ maxLength: 1024 })@IsOptional()@IsString()+ @MaxLength(1024)address?: string;}@@ -38,14 +40,16 @@ export class SendContactDto {@IsNotEmpty()chatId: string;- @ApiProperty()+ @ApiProperty({ maxLength: 255 })@IsString()@IsNotEmpty()+ @MaxLength(255)contactName: string;- @ApiProperty()+ @ApiProperty({ maxLength: 30 })@IsString()@IsNotEmpty()+ @MaxLength(30)contactNumber: string;}@@ -60,9 +64,10 @@ export class ReplyMessageDto {@IsNotEmpty()quotedMessageId: string;- @ApiProperty()+ @ApiProperty({ maxLength: 4096 })@IsString()@IsNotEmpty()+ @MaxLength(4096)text: string;}@@ -95,8 +100,9 @@ export class ReactMessageDto {messageId: string;// Empty string is VALID — it removes the reaction (endpoint contract). So @IsString, not @IsNotEmpty.- @ApiProperty({ description: 'Emoji to react with. Send an empty string to remove the reaction.' })+ @ApiProperty({ description: 'Emoji to react with. Send an empty string to remove the reaction.', maxLength: 32 })@IsString()+ @MaxLength(32)emoji: string;}diff --git a/src/modules/message/dto/send-message.dto.spec.ts b/src/modules/message/dto/send-message.dto.spec.tsindex a0122c4ab..1bf2040f4 100644--- a/src/modules/message/dto/send-message.dto.spec.ts+++ b/src/modules/message/dto/send-message.dto.spec.ts@@ -29,6 +29,24 @@ describe('SendTextMessageDto mentions', () => {});expect(errors.length).toBeGreaterThan(0);});++ it('rejects an oversized mentions array (> 1024 entries)', async () => {+ const errors = await validateDto(SendTextMessageDto, {+ chatId: '[email protected]',+ text: 'hi',+ mentions: Array.from({ length: 1025 }, (_, i) => `${i}@c.us`),+ });+ expect(errors.length).toBeGreaterThan(0);+ });++ it('rejects a mention WID longer than the per-element cap', async () => {+ const errors = await validateDto(SendTextMessageDto, {+ chatId: '[email protected]',+ text: 'hi',+ mentions: ['a'.repeat(65) + '@c.us'],+ });+ expect(errors.length).toBeGreaterThan(0);+ });});describe('SendMediaMessageDto mentions', () => {diff --git a/src/modules/message/dto/send-message.dto.ts b/src/modules/message/dto/send-message.dto.tsindex e4f897c36..dec254d50 100644--- a/src/modules/message/dto/send-message.dto.ts+++ b/src/modules/message/dto/send-message.dto.ts@@ -1,5 +1,5 @@import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';-import { IsString, IsNotEmpty, IsOptional, MaxLength, IsUrl, ValidateIf, IsArray } from 'class-validator';+import { IsString, IsNotEmpty, IsOptional, MaxLength, IsUrl, ValidateIf, IsArray, ArrayMaxSize } from 'class-validator';const MENTIONS_DESCRIPTION ='WIDs to @mention (e.g. ["[email protected]"]). The text/caption must also contain the @<number> token.';@@ -26,7 +26,9 @@ export class SendTextMessageDto {@ApiPropertyOptional({ description: MENTIONS_DESCRIPTION, example: ['[email protected]'], type: [String] })@IsOptional()@IsArray()+ @ArrayMaxSize(1024)@IsString({ each: true })+ @MaxLength(64, { each: true })mentions?: string[];}@@ -86,7 +88,9 @@ export class SendMediaMessageDto {@ApiPropertyOptional({ description: MENTIONS_DESCRIPTION, example: ['[email protected]'], type: [String] })@IsOptional()@IsArray()+ @ArrayMaxSize(1024)@IsString({ each: true })+ @MaxLength(64, { each: true })mentions?: string[];}diff --git a/src/modules/status/dto/send-media-status.dto.ts b/src/modules/status/dto/send-media-status.dto.tsindex 6626da3bc..3ff5dfcee 100644--- a/src/modules/status/dto/send-media-status.dto.ts+++ b/src/modules/status/dto/send-media-status.dto.ts@@ -1,4 +1,13 @@-import { IsString, IsOptional, ValidateNested, IsArray, ArrayMinSize, ArrayMaxSize, Matches } from 'class-validator';+import {+ IsString,+ IsOptional,+ ValidateNested,+ IsArray,+ ArrayMinSize,+ ArrayMaxSize,+ Matches,+ MaxLength,+} from 'class-validator';import { Type } from 'class-transformer';class StatusMediaInput {@@ -22,6 +31,7 @@ export class SendImageStatusDto {@IsOptional()@IsString()+ @MaxLength(1024)caption?: string;@IsArray()@@ -39,6 +49,7 @@ export class SendVideoStatusDto {@IsOptional()@IsString()+ @MaxLength(1024)caption?: string;@IsArray()diff --git a/src/modules/status/dto/send-text-status.dto.ts b/src/modules/status/dto/send-text-status.dto.tsindex df804cb38..598182f85 100644--- a/src/modules/status/dto/send-text-status.dto.ts+++ b/src/modules/status/dto/send-text-status.dto.ts@@ -1,7 +1,19 @@-import { IsString, IsOptional, IsInt, Min, Max, Matches, IsArray, ArrayMinSize, ArrayMaxSize } from 'class-validator';+import {+ IsString,+ IsOptional,+ IsInt,+ Min,+ Max,+ Matches,+ MaxLength,+ IsArray,+ ArrayMinSize,+ ArrayMaxSize,+} from 'class-validator';export class SendTextStatusDto {@IsString()+ @MaxLength(4096)text: string;@IsOptional()