Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(message): bound the inline media a message list returns

Yudhi Armyndharis8bedda85c538
diff --git a/.env.example b/.env.example
index 45fd70520..1d412214d 100644
--- a/.env.example
+++ b/.env.example
@@ -421,6 +421,13 @@ WEBHOOK_SSRF_PROTECT=true
# # keeps the most recent media. An http/https payload is never
# # counted or dropped — it is a pointer, not bytes, whatever the
# # case of its scheme. 0 omits every payload.
+
+# Aggregate budget for the inline base64 media ONE message-list response may carry
+# (GET /sessions/:id/messages and the MCP MessageList tool). The row count is clamped to
+# 1..100, but a row is not a bounded object: past the budget each payload is replaced with
+# the { omitted: true, sizeBytes } marker and stays fetchable from the per-message media
+# route. 0 omits every payload. Default: 8 MiB of encoded base64.
+# MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES=8388608
# STORE_EPHEMERAL_MESSAGES=true # Set to false to skip persisting and dispatching incoming
# # WhatsApp disappearing messages (ephemeralDuration > 0).
# # Default: true (backward compatible — store everything).
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 74ec3b2c7..8f3b910a1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- `GET /sessions/:sessionId/messages` and the MCP `MessageList` tool now bound the inline media they return, via `MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES` (8 MiB of encoded base64 by default). The row count was clamped to 1..100, but a row is not a bounded object: each carries its base64 in `metadata.media.data`, so a hundred media rows serialised to well over a hundred megabytes, and a large enough page pushed `JSON.stringify` past its ceiling and failed the read outright — permanently for the dashboard, which requests the maximum page size with no way to ask for less. The budget is spent newest-first; past it a payload is replaced with the `{ omitted: true, sizeBytes }` marker the engine already emits for skipped inbound media, and remains fetchable from the per-message media route.
+
- Bulk send now caps its rendered result at `TEMPLATE_RENDER_MAX_CHARS` (default 64 KiB), the same limit the single-send template path already enforced. `content.text` is length-validated before substitution, so caller-supplied variables inflated each item without bound while the request body stayed far below the in-flight body budget — a few hundred KiB of variables became hundreds of megabytes of heap per item, then went to the engine and the `messages.body` column. An over-cap render now fails that item with a message naming the limit, exactly as a pacing refusal does, rather than being truncated silently or sent.
- The published image's drop from root to the `openwa` user is now verified in CI. The Dockerfile carries no `USER` directive by design — `docker-entrypoint.sh` starts as root to fix named-volume ownership and then runs `exec gosu openwa` — and `scripts/smoke-test-non-root.sh` was the only check of that drop, but no workflow ran it: its sole appearance in `ci.yml` was inside a comment. A change leaving the Node process on uid 0 passed lint, every test job, the multi-arch build and the image scan, and was promoted to `latest`. The Docker job now loads a single-arch image from the cache the multi-arch build already populated and runs the smoke test against it.
diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.ts
index e3823af0c..b9761a1f0 100644
--- a/src/modules/message/message.service.spec.ts
+++ b/src/modules/message/message.service.spec.ts
@@ -2,7 +2,7 @@ import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';
import { BadRequestException, NotFoundException, PayloadTooLargeException } from '@nestjs/common';
-import { MessageService } from './message.service';
+import { MessageService, spendInlineMediaBudget } from './message.service';
import { Message, MessageDirection, MessageStatus } from './entities/message.entity';
import { SessionService } from '../session/session.service';
import { EngineRegistry } from '../../engine/engine-registry.service';
@@ -1966,4 +1966,99 @@ describe('MessageService', () => {
});
});
});
+
+ // The budget is only worth anything if the read path actually applies it: the wiring is one line and
+ // would vanish silently. This drives getMessages through a faked query builder and asserts the
+ // response is bounded, not just that the helper exists.
+ describe('MessageService.getMessages bounds its inline media', () => {
+ it('applies the budget to the rows it returns', async () => {
+ const prev = process.env.MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES;
+ process.env.MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES = '25000';
+ try {
+ const rows = Array.from(
+ { length: 100 },
+ (_, i) =>
+ ({
+ id: `m${i}`,
+ metadata: { media: { mimetype: 'image/jpeg', data: 'x'.repeat(10_000) } },
+ }) as unknown as Message,
+ );
+ const builder = {
+ where: jest.fn().mockReturnThis(),
+ andWhere: jest.fn().mockReturnThis(),
+ orderBy: jest.fn().mockReturnThis(),
+ skip: jest.fn().mockReturnThis(),
+ take: jest.fn().mockReturnThis(),
+ getManyAndCount: jest.fn().mockResolvedValue([rows, 100]),
+ };
+ (repository.createQueryBuilder as unknown as jest.Mock).mockReturnValue(builder);
+
+ const result = await service.getMessages('sess-1', { limit: 100 });
+
+ const inlineBytes = result.messages
+ .map(m => (m.metadata as { media?: { data?: unknown } }).media?.data)
+ .filter((d): d is string => typeof d === 'string')
+ .reduce((sum, d) => sum + d.length, 0);
+ expect(result.messages).toHaveLength(100); // the page is intact
+ expect(inlineBytes).toBeLessThanOrEqual(25_000); // its payload is not
+ } finally {
+ if (prev === undefined) delete process.env.MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES;
+ else process.env.MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES = prev;
+ }
+ });
+ });
+});
+
+describe('spendInlineMediaBudget', () => {
+ const row = (id: string, base64Len: number, extra: Record<string, unknown> = {}): Message =>
+ ({
+ id,
+ metadata: { media: { mimetype: 'image/jpeg', filename: 'a.jpg', data: 'x'.repeat(base64Len), ...extra } },
+ }) as unknown as Message;
+
+ const mediaOf = (m: Message): Record<string, unknown> => (m.metadata as { media: Record<string, unknown> }).media;
+
+ it('keeps payloads while the budget lasts', () => {
+ const rows = [row('a', 100), row('b', 100)];
+ spendInlineMediaBudget(rows, 1000);
+ expect(mediaOf(rows[0]).data).toHaveLength(100);
+ expect(mediaOf(rows[1]).data).toHaveLength(100);
+ });
+
+ // The rows arrive newest-first, so the budget is spent on the most recent media and older rows
+ // fall back to the marker the engine itself emits when inbound media is skipped.
+ it('replaces the payload with the omitted marker once the budget is spent', () => {
+ const rows = [row('newest', 600), row('older', 600)];
+ spendInlineMediaBudget(rows, 1000);
+
+ expect(mediaOf(rows[0]).data).toHaveLength(600);
+ expect(mediaOf(rows[1]).data).toBeUndefined();
+ expect(mediaOf(rows[1]).omitted).toBe(true);
+ expect(mediaOf(rows[1]).mimetype).toBe('image/jpeg'); // the descriptive fields survive
+ expect(typeof mediaOf(rows[1]).sizeBytes).toBe('number');
+ });
+
+ it('bounds the total inline bytes it lets through', () => {
+ const rows = Array.from({ length: 100 }, (_, i) => row(`m${i}`, 10_000));
+ spendInlineMediaBudget(rows, 25_000);
+
+ const total = rows
+ .map(m => mediaOf(m).data)
+ .filter((d): d is string => typeof d === 'string')
+ .reduce((sum, d) => sum + d.length, 0);
+ expect(total).toBeLessThanOrEqual(25_000);
+ });
+
+ it('never touches a URL pointer, which is not a payload', () => {
+ const rows = [row('pointer', 0, { data: 'https://cdn.example/a.jpg' })];
+ spendInlineMediaBudget(rows, 0);
+ expect(mediaOf(rows[0]).data).toBe('https://cdn.example/a.jpg');
+ expect(mediaOf(rows[0]).omitted).toBeUndefined();
+ });
+
+ it('reports the decoded size the caller asked about, preferring a stored sizeBytes', () => {
+ const rows = [row('a', 400, { sizeBytes: 4242 })];
+ spendInlineMediaBudget(rows, 0);
+ expect(mediaOf(rows[0]).sizeBytes).toBe(4242);
+ });
});
diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.ts
index 3f6f04cd7..6f9213135 100644
--- a/src/modules/message/message.service.ts
+++ b/src/modules/message/message.service.ts
@@ -35,6 +35,59 @@ export interface GetMessagesOptions {
/** Default cap on a rendered template's final text; overridable via TEMPLATE_RENDER_MAX_CHARS. */
export const DEFAULT_TEMPLATE_RENDER_MAX_CHARS = 64 * 1024;
+/**
+ * Aggregate budget for the inline base64 media ONE message-list response may carry, counted in the
+ * encoded bytes that actually land in the JSON body. Override with
+ * MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES; 0 omits every payload.
+ *
+ * The row count was already clamped to 1..100, but a row is not a bounded object: `metadata.media.data`
+ * holds the whole base64 payload, so a hundred media rows serialise to hundreds of megabytes — past
+ * V8's string ceiling the read fails outright, and the dashboard requests the maximum page size with
+ * no way to ask for less. Mirrors the export path's budget rather than inventing a second policy.
+ */
+export const DEFAULT_MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES = 8 * 1024 * 1024;
+
+export function resolveMessageListInlineMediaBudgetBytes(): number {
+ const parsed = Number.parseInt(process.env.MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES ?? '', 10);
+ return Number.isInteger(parsed) && parsed >= 0 ? parsed : DEFAULT_MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES;
+}
+
+/** `metadata.media.data` holds `base64 || url`, so a pointer must never be mistaken for a payload. */
+const MEDIA_URL_POINTER = /^https?:\/\//i;
+
+/**
+ * Spend the budget over an already-ordered (newest-first) page, replacing each payload past it with
+ * the engine's own `{ omitted: true, sizeBytes }` marker — the same shape `capInboundMedia` writes
+ * when inbound media is skipped on the way in, so a trimmed row is not a new shape consumers must
+ * learn. Mutates and returns the rows.
+ *
+ * A budget, not a blanket strip: the recent media a caller is most likely reading still arrives
+ * inline, and anything dropped remains fetchable from GET /:chatId/:messageId/media.
+ */
+export function spendInlineMediaBudget(messages: Message[], budgetBytes: number): Message[] {
+ let spent = 0;
+ for (const message of messages) {
+ const metadata = message.metadata as Record<string, unknown> | null | undefined;
+ if (!metadata || typeof metadata !== 'object') continue;
+ const media = metadata.media as { data?: unknown; sizeBytes?: number } | null | undefined;
+ if (!media || typeof media.data !== 'string' || MEDIA_URL_POINTER.test(media.data)) continue;
+
+ const encoded = Buffer.byteLength(media.data, 'utf8');
+ if (spent + encoded <= budgetBytes) {
+ spent += encoded;
+ continue;
+ }
+ const { data, ...withoutPayload } = media;
+ metadata.media = {
+ ...withoutPayload,
+ omitted: true,
+ // Decoded bytes, matching what capInboundMedia reports — the caller asked how big it WAS.
+ sizeBytes: media.sizeBytes ?? Buffer.byteLength(data, 'base64'),
+ };
+ }
+ return messages;
+}
+
/** Pin window applied when the caller does not choose one — WhatsApp's own default of 24h. */
export const DEFAULT_PIN_DURATION_SECONDS = 86400;
@@ -410,7 +463,10 @@ export class MessageService {
}
const [messages, total] = await query.getManyAndCount();
- return { messages, total };
+ // The 1..100 clamp above bounds the ROW COUNT, not the response: each row carries its inline
+ // base64 in metadata.media.data. Spent newest-first (the query orders createdAt DESC), so the
+ // most recently viewed media still arrives inline and the rest keeps its omitted marker.
+ return { messages: spendInlineMediaBudget(messages, resolveMessageListInlineMediaBudgetBytes()), total };
}
/**