Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(message): cap the rendered result of a bulk send
Yudhi Armyndharisbbebff37fdcc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 73889451c..74ec3b2c7 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+- 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.- The dashboard's dependency tree is now audited on both the PR and the tag path. It went unscanned by every job: `npm audit` ran against the root tree only, and the image scan sees OS packages and the built bundle rather than the npm graph behind it — so a HIGH advisory in a dependency that reaches an operator's browser could ride a release undetected. Two were present at this baseline: `socket.io-parser` (bundled into `dashboard/dist` via `socket.io-client`) and `brace-expansion` (dev-only, via ESLint), the latter pinned to a vulnerable version by an override that had not been bumped. Both are now overridden to patched releases.diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.tsindex 8bb31e16b..f7c13aa51 100644--- a/src/modules/message/bulk-message.service.spec.ts+++ b/src/modules/message/bulk-message.service.spec.ts@@ -322,6 +322,39 @@ describe('BulkMessageService.processBatch', () => {}});+ // `content.text` is @MaxLength(4096)-validated BEFORE substitution, and the single-send template+ // path caps its FINAL render at template.renderMaxChars — the bulk path capped neither, so+ // caller-supplied variables inflated each item without bound.+ const batchWithVariables = (text: string, variables: Record<string, string>): MessageBatch => ({+ ...makeBatch(1),+ messages: [{ chatId: '[email protected]', type: 'text', content: { text }, variables }],+ });++ it('fails an item whose rendered text exceeds the cap instead of sending it', async () => {+ // Comfortably over the 64 KiB default the un-configured service falls back to.+ const huge = 'x'.repeat(70 * 1024);+ repo.findOne.mockResolvedValue(batchWithVariables('{{v}}', { v: huge }));++ await runProcessBatch();++ expect(engine.sendTextMessage).not.toHaveBeenCalled();+ const finalPartial = (+ repo.update.mock.calls as Array<[unknown, { status: BatchStatus; results: BatchMessageResult[] }]>+ ).at(-1)![1];+ expect(finalPartial.results[0].status).toBe(BatchMessageStatus.FAILED);+ expect(finalPartial.results[0].error?.message).toMatch(/character limit/i);+ });++ it('still sends an item whose render stays under the cap', async () => {+ repo.findOne.mockResolvedValue(batchWithVariables('hello {{v}}', { v: 'world' }));++ await runProcessBatch();++ expect(engine.sendTextMessage).toHaveBeenCalledTimes(1);+ const sendArgs = engine.sendTextMessage.mock.calls[0] as [string, string];+ expect(sendArgs[1]).toBe('hello world');+ });+it('releases the in-flight marker when the engine is missing (no processingBatches leak)', async () => {repo.findOne.mockResolvedValue(makeBatch(1));engines.delete('s1'); // engine-not-found → early-return pathdiff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.tsindex 579df560d..c5189b0ed 100644--- a/src/modules/message/bulk-message.service.ts+++ b/src/modules/message/bulk-message.service.ts@@ -6,6 +6,7 @@ import {Optional,OnApplicationBootstrap,} from '@nestjs/common';+import { ConfigService } from '@nestjs/config';import { InjectRepository } from '@nestjs/typeorm';import { In, Not, QueryDeepPartialEntity, Repository } from 'typeorm';import { createHash, randomUUID } from 'crypto';@@ -19,7 +20,7 @@ import {import { SendBulkMessageDto } from './dto/bulk-message.dto';import { MessageStatus } from './entities/message.entity';import { EngineRegistry } from '../../engine/engine-registry.service';-import { MessageService } from './message.service';+import { MessageService, DEFAULT_TEMPLATE_RENDER_MAX_CHARS } from './message.service';import {SendPacingService,isPacingLimitedError,@@ -113,6 +114,10 @@ export class BulkMessageService implements OnApplicationBootstrap {// node's — which is exactly a single-process deployment.@Optional()private readonly ownership?: SessionOwnershipService,+ // Same trailing-@Optional convention: supplies template.renderMaxChars for the substitution cap+ // below. Absent in direct-construction unit tests, which then fall back to the shared default.+ @Optional()+ private readonly configService?: ConfigService,) {}/**@@ -643,10 +648,28 @@ export class BulkMessageService implements OnApplicationBootstrap {private applyVariables(content: BulkMessageContent, variables?: Record<string, string>): BulkMessageContent {if (!variables) return content;+ // Cap the RENDERED result, mirroring the single-send template path. `content.text` is+ // @MaxLength(4096)-validated on the way in, but that runs BEFORE substitution, so a caller-supplied+ // variable inflates a small item without bound: the request body stays far under the in-flight body+ // budget while each rendered item does not. Rejected (never truncated), which fails this item the+ // way a pacing refusal does rather than handing the engine and the messages.body column a string+ // of arbitrary size.+ const maxChars =+ this.configService?.get<number>('template.renderMaxChars', DEFAULT_TEMPLATE_RENDER_MAX_CHARS) ??+ DEFAULT_TEMPLATE_RENDER_MAX_CHARS;+// Delegate to the shared renderer so the gateway exposes one templating syntax (#69). It// substitutes canonical `{{name}}` placeholders and still honors the legacy single-brace// `{name}` this endpoint historically used (deprecated — prefer `{{name}}`).- const replaceVars = (str: string): string => renderTemplate(str, variables);+ const replaceVars = (str: string): string => {+ const rendered = renderTemplate(str, variables);+ if (rendered.length > maxChars) {+ throw new BadRequestException(+ `Rendered content is ${rendered.length} characters, over the ${maxChars}-character limit`,+ );+ }+ return rendered;+ };const processValue = (value: unknown): unknown => {if (typeof value === 'string') {