Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(media): enforce a size limit on outbound base64 media (#394)

Yudhi Armyndharis01b34456c594
diff --git a/.env.example b/.env.example
index fefac6402..3890700fb 100644
--- a/.env.example
+++ b/.env.example
@@ -175,7 +175,7 @@ WEBHOOK_SSRF_PROTECT=true
# store or a sidecar webhook receiver).
# SSRF_ALLOWED_HOSTS=localhost,minio
# Server-side media size/time limits:
-# MEDIA_DOWNLOAD_MAX_BYTES=52428800 # cap remote-URL sends AND inbound media (default 50 MiB; oversized inbound media is dropped, message kept)
+# MEDIA_DOWNLOAD_MAX_BYTES=52428800 # cap remote-URL sends, inbound media, AND outbound base64 sends (default 50 MiB; oversized inbound media is dropped, message kept; oversized base64 is rejected with 400)
# MEDIA_DOWNLOAD_TIMEOUT_MS=30000 # abort a slow media download (default 30s)
# Storage import/export limits (ADMIN /infra/storage/* endpoints):
# STORAGE_IMPORT_MAX_BYTES=209715200 # per-entry cap for a tar.gz import; aborts on overflow (default 200 MiB)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 021819b19..d2fdae6f2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -33,6 +33,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
the 30000ms default. Both compose files now pass it through (unset still means the default). The
value is also validated as a positive safe integer, so an accidental huge or overflowing value falls
back to the default instead of making the engine's first-boot wait run effectively unbounded. (#393)
+- **Outbound base64 media is now size-limited.** Sending media as a base64 string (single and bulk
+ sends) was bounded only by the coarse whole-request `BODY_SIZE_LIMIT`, unlike remote-URL and inbound
+ media which already enforce `MEDIA_DOWNLOAD_MAX_BYTES`. The decoded size of an outbound base64 blob
+ is now checked against the same `MEDIA_DOWNLOAD_MAX_BYTES` cap (default 50 MiB) before it is sent or
+ persisted; an oversized blob is rejected with `400`. The bulk-send nested media payloads are now
+ validated as typed objects, so unknown or malformed media fields are rejected rather than silently
+ persisted — bulk requests carrying junk inside a media object will now get a `400`. (#394)
## [0.4.7] - 2026-06-21
diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.ts
index 7c72b30ed..187afe05a 100644
--- a/src/modules/message/bulk-message.service.spec.ts
+++ b/src/modules/message/bulk-message.service.spec.ts
@@ -1,8 +1,10 @@
import { Test, TestingModule } from '@nestjs/testing';
+import { BadRequestException } from '@nestjs/common';
import { getRepositoryToken } from '@nestjs/typeorm';
import { BulkMessageService, resolveFinalBatchStatus, sanitizeBatchError } from './bulk-message.service';
import { MessageBatch, BatchStatus } from './entities/message-batch.entity';
import { MessageStatus } from './entities/message.entity';
+import { SendBulkMessageDto } from './dto/bulk-message.dto';
import { SessionService } from '../session/session.service';
import { MessageService } from './message.service';
import { SsrfBlockedError } from '../../common/security/ssrf-guard';
@@ -171,3 +173,44 @@ describe('BulkMessageService.processBatch', () => {
expect(savedStatuses[savedStatuses.length - 1]).toBe(BatchStatus.CANCELLED);
});
});
+
+describe('BulkMessageService.createBatch base64 media cap', () => {
+ let service: BulkMessageService;
+ let repo: { findOne: jest.Mock; save: jest.Mock };
+
+ beforeEach(async () => {
+ repo = {
+ findOne: jest.fn().mockResolvedValue(undefined),
+ save: jest.fn().mockImplementation(b => Promise.resolve(b)),
+ };
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ BulkMessageService,
+ { provide: getRepositoryToken(MessageBatch, 'data'), useValue: repo },
+ { provide: SessionService, useValue: { getEngine: jest.fn().mockReturnValue({}) } },
+ { provide: MessageService, useValue: { saveOutgoingMessage: jest.fn() } },
+ ],
+ }).compile();
+ service = module.get<BulkMessageService>(BulkMessageService);
+ });
+
+ it('rejects a message whose base64 media exceeds the cap, before persisting the batch', async () => {
+ process.env.MEDIA_DOWNLOAD_MAX_BYTES = '1024';
+ try {
+ await expect(
+ service.createBatch('s1', {
+ messages: [
+ {
+ chatId: '[email protected]',
+ type: 'image',
+ content: { image: { base64: Buffer.alloc(1025).toString('base64'), mimetype: 'image/png' } },
+ },
+ ],
+ } as unknown as SendBulkMessageDto),
+ ).rejects.toBeInstanceOf(BadRequestException);
+ expect(repo.save).not.toHaveBeenCalled();
+ } finally {
+ delete process.env.MEDIA_DOWNLOAD_MAX_BYTES;
+ }
+ });
+});
diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.ts
index c36b707e6..bef47fffe 100644
--- a/src/modules/message/bulk-message.service.ts
+++ b/src/modules/message/bulk-message.service.ts
@@ -13,6 +13,7 @@ import { SendBulkMessageDto } from './dto/bulk-message.dto';
import { MessageStatus } from './entities/message.entity';
import { SessionService } from '../session/session.service';
import { MessageService } from './message.service';
+import { assertBase64WithinMediaCap } from './media-cap.util';
import { SsrfBlockedError } from '../../common/security/ssrf-guard';
import { IWhatsAppEngine, MessageResult } from '../../engine/interfaces/whatsapp-engine.interface';
@@ -93,6 +94,16 @@ export class BulkMessageService implements OnApplicationBootstrap {
throw new BadRequestException(`Session '${sessionId}' is not active`);
}
+ // Bound every outbound base64 blob to the media byte cap before the whole messages array (with
+ // its base64 payloads) is persisted into the batch row. Mirrors the single-send cap in
+ // MessageService.buildMediaInput.
+ for (const { content } of dto.messages) {
+ assertBase64WithinMediaCap(content?.image?.base64);
+ assertBase64WithinMediaCap(content?.video?.base64);
+ assertBase64WithinMediaCap(content?.audio?.base64);
+ assertBase64WithinMediaCap(content?.document?.base64);
+ }
+
const batchId = dto.batchId || `batch_${randomUUID().split('-')[0]}`;
// Check if batchId already exists
diff --git a/src/modules/message/dto/bulk-message.dto.spec.ts b/src/modules/message/dto/bulk-message.dto.spec.ts
new file mode 100644
index 000000000..3747a68a8
--- /dev/null
+++ b/src/modules/message/dto/bulk-message.dto.spec.ts
@@ -0,0 +1,28 @@
+import { plainToInstance } from 'class-transformer';
+import { validate } from 'class-validator';
+import { SendBulkMessageDto } from './bulk-message.dto';
+
+// Mirror the global ValidationPipe (main.ts): whitelist + forbidNonWhitelisted strip/reject unknown
+// props. Before the nested media objects were typed DTOs they were bare object literals, so these
+// options could not reach inside a media object — junk in `content.image` passed straight through
+// and was persisted verbatim.
+const validateBulk = (obj: unknown) =>
+ validate(plainToInstance(SendBulkMessageDto, obj), { whitelist: true, forbidNonWhitelisted: true });
+
+const imageItem = (image: unknown) => ({
+ messages: [{ chatId: '[email protected]', type: 'image', content: { image } }],
+});
+
+describe('SendBulkMessageDto nested media validation', () => {
+ it('accepts a well-formed base64 media object', async () => {
+ expect(await validateBulk(imageItem({ base64: 'AAAA', mimetype: 'image/png' }))).toHaveLength(0);
+ });
+
+ it('rejects an unknown property inside a media object', async () => {
+ expect((await validateBulk(imageItem({ base64: 'AAAA', evil: 'x' }))).length).toBeGreaterThan(0);
+ });
+
+ it('rejects a non-string base64 inside a media object', async () => {
+ expect((await validateBulk(imageItem({ base64: 12345 }))).length).toBeGreaterThan(0);
+ });
+});
diff --git a/src/modules/message/dto/bulk-message.dto.ts b/src/modules/message/dto/bulk-message.dto.ts
index 76a062cc8..f5c129678 100644
--- a/src/modules/message/dto/bulk-message.dto.ts
+++ b/src/modules/message/dto/bulk-message.dto.ts
@@ -13,27 +13,60 @@ import {
} from 'class-validator';
import { Type } from 'class-transformer';
+class BulkMediaDto {
+ @ApiPropertyOptional({ description: 'Media URL (http/https)' })
+ @IsOptional()
+ @IsString()
+ url?: string;
+
+ @ApiPropertyOptional({ description: 'Base64-encoded media data' })
+ @IsOptional()
+ @IsString()
+ base64?: string;
+
+ @ApiPropertyOptional({ description: 'Media MIME type' })
+ @IsOptional()
+ @IsString()
+ mimetype?: string;
+
+ @ApiPropertyOptional({ description: 'Filename (documents only)' })
+ @IsOptional()
+ @IsString()
+ filename?: string;
+}
+
class BulkMessageContentDto {
@ApiPropertyOptional({ description: 'Text content for text messages' })
@IsOptional()
@IsString()
text?: string;
- @ApiPropertyOptional({ description: 'Image URL or base64' })
+ // Typed nested DTOs (not bare object literals) so the global ValidationPipe's whitelist /
+ // forbidNonWhitelisted actually reaches their fields — otherwise unknown props inside a media
+ // object pass straight through and are persisted verbatim.
+ @ApiPropertyOptional({ description: 'Image URL or base64', type: BulkMediaDto })
@IsOptional()
- image?: { url?: string; base64?: string; mimetype?: string };
+ @ValidateNested()
+ @Type(() => BulkMediaDto)
+ image?: BulkMediaDto;
- @ApiPropertyOptional({ description: 'Video URL or base64' })
+ @ApiPropertyOptional({ description: 'Video URL or base64', type: BulkMediaDto })
@IsOptional()
- video?: { url?: string; base64?: string; mimetype?: string };
+ @ValidateNested()
+ @Type(() => BulkMediaDto)
+ video?: BulkMediaDto;
- @ApiPropertyOptional({ description: 'Audio URL or base64' })
+ @ApiPropertyOptional({ description: 'Audio URL or base64', type: BulkMediaDto })
@IsOptional()
- audio?: { url?: string; base64?: string; mimetype?: string };
+ @ValidateNested()
+ @Type(() => BulkMediaDto)
+ audio?: BulkMediaDto;
- @ApiPropertyOptional({ description: 'Document URL or base64' })
+ @ApiPropertyOptional({ description: 'Document URL or base64', type: BulkMediaDto })
@IsOptional()
- document?: { url?: string; base64?: string; mimetype?: string; filename?: string };
+ @ValidateNested()
+ @Type(() => BulkMediaDto)
+ document?: BulkMediaDto;
@ApiPropertyOptional({ description: 'Caption for media messages' })
@IsOptional()
diff --git a/src/modules/message/media-cap.util.spec.ts b/src/modules/message/media-cap.util.spec.ts
new file mode 100644
index 000000000..5ee286772
--- /dev/null
+++ b/src/modules/message/media-cap.util.spec.ts
@@ -0,0 +1,35 @@
+import { BadRequestException } from '@nestjs/common';
+import { assertBase64WithinMediaCap } from './media-cap.util';
+
+describe('assertBase64WithinMediaCap', () => {
+ const orig = process.env.MEDIA_DOWNLOAD_MAX_BYTES;
+ afterEach(() => {
+ if (orig === undefined) delete process.env.MEDIA_DOWNLOAD_MAX_BYTES;
+ else process.env.MEDIA_DOWNLOAD_MAX_BYTES = orig;
+ });
+
+ /** A base64 string that decodes to exactly `bytes` bytes. */
+ const base64OfBytes = (bytes: number): string => Buffer.alloc(bytes).toString('base64');
+
+ it('does nothing for an empty or missing value', () => {
+ expect(() => assertBase64WithinMediaCap(undefined)).not.toThrow();
+ expect(() => assertBase64WithinMediaCap(null)).not.toThrow();
+ expect(() => assertBase64WithinMediaCap('')).not.toThrow();
+ });
+
+ it('accepts a base64 payload at the cap', () => {
+ process.env.MEDIA_DOWNLOAD_MAX_BYTES = '1024';
+ expect(() => assertBase64WithinMediaCap(base64OfBytes(1024))).not.toThrow();
+ });
+
+ it('rejects a base64 payload over the cap with a 400', () => {
+ process.env.MEDIA_DOWNLOAD_MAX_BYTES = '1024';
+ expect(() => assertBase64WithinMediaCap(base64OfBytes(1025))).toThrow(BadRequestException);
+ });
+
+ it('honors the MEDIA_DOWNLOAD_MAX_BYTES override (shared with the URL/inbound caps)', () => {
+ process.env.MEDIA_DOWNLOAD_MAX_BYTES = '2048';
+ expect(() => assertBase64WithinMediaCap(base64OfBytes(2000))).not.toThrow();
+ expect(() => assertBase64WithinMediaCap(base64OfBytes(4096))).toThrow(BadRequestException);
+ });
+});
diff --git a/src/modules/message/media-cap.util.ts b/src/modules/message/media-cap.util.ts
new file mode 100644
index 000000000..6f76cc441
--- /dev/null
+++ b/src/modules/message/media-cap.util.ts
@@ -0,0 +1,21 @@
+import { BadRequestException } from '@nestjs/common';
+import { inboundMediaMaxBytes } from '../../engine/adapters/inbound-media-cap';
+
+/**
+ * Reject an outbound base64 media blob whose DECODED size exceeds the shared media byte cap
+ * (`MEDIA_DOWNLOAD_MAX_BYTES`, default 50 MiB) — the same limit the remote-URL download and inbound
+ * media paths already enforce. This closes the asymmetry where base64 sends were bounded only by the
+ * coarse whole-request `BODY_SIZE_LIMIT`.
+ *
+ * `Buffer.byteLength(_, 'base64')` derives the decoded length from the string length and padding, so
+ * the check never allocates the decoded buffer (no +33% heap copy of an oversized payload).
+ */
+export function assertBase64WithinMediaCap(base64: string | null | undefined): void {
+ if (!base64) {
+ return;
+ }
+ const maxBytes = inboundMediaMaxBytes();
+ if (Buffer.byteLength(base64, 'base64') > maxBytes) {
+ throw new BadRequestException(`Base64 media exceeds the maximum allowed size of ${maxBytes} bytes`);
+ }
+}
diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.ts
index 3a74cdd0a..3414585e6 100644
--- a/src/modules/message/message.service.spec.ts
+++ b/src/modules/message/message.service.spec.ts
@@ -302,6 +302,22 @@ describe('MessageService', () => {
service.sendImage('sess-1', { chatId: '[email protected]', url: 'http://127.0.0.1/x.png' }),
).rejects.toBeInstanceOf(BadRequestException);
});
+
+ it('rejects a base64 image over the media cap before sending or persisting', async () => {
+ process.env.MEDIA_DOWNLOAD_MAX_BYTES = '1024';
+ try {
+ await expect(
+ service.sendImage('sess-1', {
+ chatId: '[email protected]',
+ base64: Buffer.alloc(1025).toString('base64'),
+ mimetype: 'image/png',
+ }),
+ ).rejects.toBeInstanceOf(BadRequestException);
+ expect(mockEngine.sendImageMessage).not.toHaveBeenCalled();
+ } finally {
+ delete process.env.MEDIA_DOWNLOAD_MAX_BYTES;
+ }
+ });
});
// ── getMessages pagination guard ──────────────────────────────────
diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.ts
index 58522a08a..285a6a363 100644
--- a/src/modules/message/message.service.ts
+++ b/src/modules/message/message.service.ts
@@ -4,6 +4,7 @@ import { Repository } from 'typeorm';
import { SessionService } from '../session/session.service';
import { SendTextMessageDto, SendMediaMessageDto, MessageResponseDto } from './dto';
import { SendTemplateMessageDto } from './dto/send-template.dto';
+import { assertBase64WithinMediaCap } from './media-cap.util';
import { MediaInput, IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
import { Message, MessageDirection, MessageStatus } from './entities/message.entity';
import { HookManager } from '../../core/hooks';
@@ -647,6 +648,10 @@ export class MessageService {
throw new BadRequestException('mimetype is required when using base64 data');
}
+ // Bound an outbound base64 payload to the same byte cap as URL/inbound media, before it is
+ // persisted or handed to the engine. URL media is already capped while streaming.
+ assertBase64WithinMediaCap(dto.base64);
+
return {
mimetype: dto.mimetype || 'application/octet-stream',
data: dto.url || dto.base64!,