Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(message): bound the rendered size of template and bulk sends

Yudhi Armyndharis358f83e8b994
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index c467b48ec..c0a039f82 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -2411,7 +2411,7 @@ Each item must carry what its `type` sends: a non-empty `chatId` of at most 255
Each item's base64 media is checked against the media byte cap (`MEDIA_DOWNLOAD_MAX_BYTES`) twice: at batch creation, and again per item after `variables` and the `message:sending` plugin gate are applied. An item that outgrows the cap only after rendering fails individually (`failed` in `results`, with `message:failed` fired) instead of being sent. `totalMessages` in the response reflects the de-duplicated item count.
-The rendered text is bounded the same way, by `TEMPLATE_RENDER_MAX_CHARS` (default 64 KiB) — the limit the single-send template path already applied. `content.text` and `content.caption` are length-validated _before_ substitution, so caller-supplied `variables` could otherwise inflate each item without bound while the request body stayed far below the in-flight body budget. An item whose `text` or `caption` exceeds the limit after substitution fails individually with a message naming it, rather than being truncated silently or sent. Media is not bounded by this cap — `MEDIA_DOWNLOAD_MAX_BYTES` governs it, three orders of magnitude higher, because a 100 KB image is already ~137,000 base64 characters and would fail the character limit on every personalised media send.
+The rendered text is bounded the same way, by `TEMPLATE_RENDER_MAX_CHARS` (default 64 KiB) — the limit the single-send template path already applied. `content.text` and `content.caption` are length-validated _before_ substitution, so caller-supplied `variables` could otherwise inflate each item without bound while the request body stayed far below the in-flight body budget. An item whose `text` or `caption` exceeds the limit after substitution fails individually with a message naming it, rather than being truncated silently or sent. Media is not bounded by this cap — `MEDIA_DOWNLOAD_MAX_BYTES` governs it, three orders of magnitude higher, because a 100 KB image is already ~137,000 base64 characters and would fail the character limit on every personalised media send. Sizes are measured before an item is rendered, so an item that would render to something enormous fails without being built. A `url`, `filename` or other string that carries a placeholder may grow the item by no more than the same limit in total, and a `base64` that would render past the media limit fails with the media size message.
```json
{
diff --git a/src/common/utils/template-render.spec.ts b/src/common/utils/template-render.spec.ts
index bacf1792e..3f7d5c2f5 100644
--- a/src/common/utils/template-render.spec.ts
+++ b/src/common/utils/template-render.spec.ts
@@ -1,4 +1,4 @@
-import { renderTemplate } from './template-render';
+import { renderedLength, renderTemplate, TemplateRenderError } from './template-render';
describe('renderTemplate', () => {
describe('canonical double-brace {{name}}', () => {
@@ -58,5 +58,62 @@ describe('renderTemplate', () => {
// hasOwnProperty semantics: an explicit '' substitutes to '' (the legacy `||` renderer left it literal).
expect(renderTemplate('[{name}]', { name: '' })).toBe('[]');
});
+
+ it('renders a numeric value sent where a string was typed', () => {
+ expect(renderTemplate('#{{n}}', { n: 42 as unknown as string })).toBe('#42');
+ });
+
+ it('rejects a value that has no text form instead of throwing a TypeError', () => {
+ const unprintable = { toString: 1 } as unknown as string;
+ expect(() => renderTemplate('{{v}}', { v: unprintable })).toThrow(TemplateRenderError);
+ expect(() => renderedLength('{{v}}', { v: unprintable })).toThrow(TemplateRenderError);
+ const noPrototype = Object.create(null) as string;
+ expect(() => renderTemplate('{v}', { v: noPrototype })).toThrow("Variable 'v' cannot be rendered as text");
+ });
+ });
+});
+
+describe('renderedLength', () => {
+ const cases: Array<[string, string, Record<string, string>]> = [
+ ['double and single braces', 'Hi {{name}}, {greeting}!', { name: 'Sam', greeting: 'Hello' }],
+ ['spaced keys', '{{ first.name }}-{{order-id}}', { 'first.name': 'A', 'order-id': '1234567' }],
+ ['a missing key stays literal', 'Hi {{name}} {other}', { name: 'Sam' }],
+ ['a null value stays literal', 'x{{a}}y', { a: null as unknown as string }],
+ ['a value shorter than its placeholder', '{{a_long_placeholder_name}}', { a_long_placeholder_name: '' }],
+ ['non-placeholder braces', 'a { b } c {{ }}', { b: 'X' }],
+ ['a body with no brace at all', 'plain text', { a: 'X' }],
+ ['an empty body', '', { a: 'X' }],
+ ];
+
+ it.each(cases)('equals the length renderTemplate returns: %s', (_name, body, vars) => {
+ expect(renderedLength(body, vars)).toBe(renderTemplate(body, vars).length);
+ });
+
+ it('measures a huge expansion without building it', () => {
+ // 1365 single-brace placeholders fit in a 4 KiB body; one 393 KB value makes half a gigabyte.
+ const body = '{a}'.repeat(1365);
+ const vars = { a: 'x'.repeat(393_000) };
+ expect(renderedLength(body, vars)).toBe(1365 * 393_000);
+ });
+});
+
+describe('a variable that is not a string', () => {
+ // A request may carry an array or object as a variable. Turning a large one into text for every repeat of
+ // its placeholder would cost its size times the repeats before any limit is applied.
+ const counting = () => {
+ const toString = jest.fn(() => 'x'.repeat(10));
+ return { toString, value: { toString } as unknown as string };
+ };
+
+ it('is turned into text once per render, however often its placeholder repeats', () => {
+ const { toString, value } = counting();
+ expect(renderTemplate('{a}'.repeat(1000), { a: value })).toBe('x'.repeat(10_000));
+ expect(toString).toHaveBeenCalledTimes(1);
+ });
+
+ it('is turned into text once per measurement, however often its placeholder repeats', () => {
+ const { toString, value } = counting();
+ expect(renderedLength('{{a}}-'.repeat(1000), { a: value })).toBe(11_000);
+ expect(toString).toHaveBeenCalledTimes(1);
});
});
diff --git a/src/common/utils/template-render.ts b/src/common/utils/template-render.ts
index e7b2effae..917dcd8d2 100644
--- a/src/common/utils/template-render.ts
+++ b/src/common/utils/template-render.ts
@@ -15,6 +15,34 @@
// surrounding whitespace — so existing single-brace bulk content renders bit-for-bit as before.
const PLACEHOLDER_PATTERN = /\{\{\s*([\w.-]+)\s*\}\}|\{(\w+)\}/g;
+/** A template that cannot be rendered for a reason the caller can report, such as a value with no text form. */
+export class TemplateRenderError extends Error {}
+
+/**
+ * The text a placeholder is replaced with, or undefined when it stays literal (key absent or null). A value
+ * is turned into text once per render, kept in `seen`: a request may carry an array or object as a variable,
+ * and converting a large one for every repeat of its placeholder would cost its size times the repeats.
+ */
+function substitution(
+ vars: Record<string, string>,
+ key: string | undefined,
+ seen: Map<string, string | undefined>,
+): string | undefined {
+ if (key === undefined) return undefined;
+ if (seen.has(key)) return seen.get(key);
+ let text: string | undefined;
+ if (Object.prototype.hasOwnProperty.call(vars, key) && vars[key] != null) {
+ try {
+ text = String(vars[key]);
+ } catch {
+ // An object without a usable toString, such as `{ toString: 1 }` or a null-prototype object.
+ throw new TemplateRenderError(`Variable '${key}' cannot be rendered as text`);
+ }
+ }
+ seen.set(key, text);
+ return text;
+}
+
/**
* Render a template body by replacing `{{key}}` (canonical) or `{key}` (legacy) placeholders with
* `vars[key]`.
@@ -23,18 +51,40 @@ const PLACEHOLDER_PATTERN = /\{\{\s*([\w.-]+)\s*\}\}|\{(\w+)\}/g;
* @param vars Map of placeholder keys to substitution values.
* @returns The rendered text with known placeholders substituted and unknown placeholders left
* literal.
+ * @throws TemplateRenderError when a value has no text form.
*/
export function renderTemplate(body: string, vars: Record<string, string> = {}): string {
- if (!body) {
+ if (!body || !body.includes('{')) {
return body;
}
- return body.replace(PLACEHOLDER_PATTERN, (match, doubleKey: string | undefined, singleKey: string | undefined) => {
- const key = doubleKey ?? singleKey;
- if (key !== undefined && Object.prototype.hasOwnProperty.call(vars, key) && vars[key] != null) {
- return String(vars[key]);
- }
- // Leave unmatched placeholders literal so missing variables stay visible.
- return match;
- });
+ // Unmatched placeholders stay literal so missing variables stay visible.
+ const seen = new Map<string, string | undefined>();
+ return body.replace(
+ PLACEHOLDER_PATTERN,
+ (match, doubleKey: string | undefined, singleKey: string | undefined) =>
+ substitution(vars, doubleKey ?? singleKey, seen) ?? match,
+ );
+}
+
+/**
+ * The exact length of `renderTemplate(body, vars)`, computed without building the result.
+ *
+ * One placeholder repeated through a small body multiplies a large value (1365 `{a}` fit in a 4 KiB body,
+ * and one 393 KB value then renders to half a gigabyte), so a caller with a size limit measures first and
+ * refuses an oversized render instead of allocating it and checking afterwards.
+ *
+ * @throws TemplateRenderError when a value has no text form.
+ */
+export function renderedLength(body: string, vars: Record<string, string> = {}): number {
+ if (!body || !body.includes('{')) {
+ return body ? body.length : 0;
+ }
+ let length = body.length;
+ const seen = new Map<string, string | undefined>();
+ for (const match of body.matchAll(PLACEHOLDER_PATTERN)) {
+ const text = substitution(vars, match[1] ?? match[2], seen);
+ if (text !== undefined) length += text.length - match[0].length;
+ }
+ return length;
}
diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.ts
index ee9bc6c1a..7aa8cb3e2 100644
--- a/src/modules/message/bulk-message.service.spec.ts
+++ b/src/modules/message/bulk-message.service.spec.ts
@@ -917,6 +917,98 @@ describe('BulkMessageService.processBatch', () => {
expect(finalPartial.results[0].error?.message).toMatch(/caption/i);
});
+ it('fails an item that would render to hundreds of megabytes without building it', async () => {
+ // 1365 single-brace placeholders fit in a 4096-character text and one 394 KB variable fills each of them:
+ // 537 MB, past the longest string V8 can build, so a render-then-check could only have thrown a RangeError.
+ repo.findOne.mockResolvedValue(batchWithVariables('{a}'.repeat(1365), { a: 'x'.repeat(394_000) }));
+
+ await runProcessBatch();
+
+ expect(engine.sendTextMessage).not.toHaveBeenCalled();
+ const finalPartial = (repo.update.mock.calls as Array<[unknown, { results: BatchMessageResult[] }]>).at(-1)![1];
+ expect(finalPartial.results[0].status).toBe(BatchMessageStatus.FAILED);
+ expect(finalPartial.results[0].error?.message).toContain(`Rendered text is ${1365 * 394_000} characters`);
+ });
+
+ // A personalised media send puts its placeholder in `base64`; a 100 KB image is about 137,000 characters.
+ const mediaBatch = (content: Record<string, unknown>, variables: Record<string, string>) => ({
+ ...makeBatch(1),
+ messages: [{ chatId: '[email protected]', type: 'image', content, variables }],
+ });
+
+ it('sends a media item whose base64 comes from a variable, past the text cap', async () => {
+ engine.sendImageMessage = jest.fn().mockResolvedValue({ id: 'waimg', timestamp: 222 });
+ const picture = Buffer.alloc(100_000, 7).toString('base64');
+ repo.findOne.mockResolvedValue(
+ mediaBatch({ image: { base64: '{{pic}}', mimetype: 'image/png' } }, { pic: picture }),
+ );
+
+ await runProcessBatch();
+
+ expect(picture.length).toBeGreaterThan(65_536);
+ expect(engine.sendImageMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('bounds text and caption one by one, not as a total', async () => {
+ engine.sendImageMessage = jest.fn().mockResolvedValue({ id: 'waimg', timestamp: 222 });
+ const grown = 'x'.repeat(40 * 1024);
+ repo.findOne.mockResolvedValue(
+ mediaBatch({ text: '{{v}}', caption: '{{v}}', image: { base64: 'AAAA', mimetype: 'image/png' } }, { v: grown }),
+ );
+
+ await runProcessBatch();
+
+ // Each is 40 KiB, under the 64 KiB cap; together they are not, and nothing asks for them together.
+ expect(engine.sendImageMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('fails a media item whose base64 would render past the media cap without building it', async () => {
+ // 1000 repeats of a 1 MB variable are a billion characters, past what V8 can build as one string.
+ repo.findOne.mockResolvedValue(
+ mediaBatch({ image: { base64: '{{p}}'.repeat(1000), mimetype: 'image/png' } }, { p: 'A'.repeat(1_000_000) }),
+ );
+
+ await runProcessBatch();
+
+ expect(engine.sendImageMessage).not.toHaveBeenCalled();
+ const finalPartial = (repo.update.mock.calls as Array<[unknown, { results: BatchMessageResult[] }]>).at(-1)![1];
+ expect(finalPartial.results[0].status).toBe(BatchMessageStatus.FAILED);
+ expect(finalPartial.results[0].error?.message).toContain('exceeds the maximum allowed size');
+ });
+
+ it('bounds what the other strings of an item may grow by, together', async () => {
+ // Neither the URL nor the filename is text or caption, and each grows by 40 KB, under the cap on its own.
+ const grown = 'x'.repeat(40 * 1024);
+ repo.findOne.mockResolvedValue({
+ ...makeBatch(1),
+ messages: [
+ {
+ chatId: '[email protected]',
+ type: 'image',
+ content: { image: { url: 'https://cdn.example/{{v}}.jpg', filename: '{{v}}.jpg', mimetype: 'image/jpeg' } },
+ variables: { v: grown },
+ },
+ ],
+ });
+
+ await runProcessBatch();
+
+ const finalPartial = (repo.update.mock.calls as Array<[unknown, { results: BatchMessageResult[] }]>).at(-1)![1];
+ expect(finalPartial.results[0].status).toBe(BatchMessageStatus.FAILED);
+ expect(finalPartial.results[0].error?.message).toMatch(/grows by \d+ characters, over the 65536-character limit/);
+ });
+
+ it('fails an item whose variable has no text form with the reason, not a TypeError', async () => {
+ repo.findOne.mockResolvedValue(batchWithVariables('hi {{v}}', { v: { toString: 1 } as unknown as string }));
+
+ await runProcessBatch();
+
+ expect(engine.sendTextMessage).not.toHaveBeenCalled();
+ const finalPartial = (repo.update.mock.calls as Array<[unknown, { results: BatchMessageResult[] }]>).at(-1)![1];
+ expect(finalPartial.results[0].status).toBe(BatchMessageStatus.FAILED);
+ expect(finalPartial.results[0].error?.message).toBe("Variable 'v' cannot be rendered as text");
+ });
+
it('still sends an item whose render stays under the cap', async () => {
repo.findOne.mockResolvedValue(batchWithVariables('hello {{v}}', { v: 'world' }));
diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.ts
index ab1ae3fab..89c6960be 100644
--- a/src/modules/message/bulk-message.service.ts
+++ b/src/modules/message/bulk-message.service.ts
@@ -40,9 +40,9 @@ import {
} from './send-pacing.service';
import { SessionOwnershipService } from '../session/session-ownership.service';
import { HookManager } from '../../core/hooks';
-import { assertBase64WithinMediaCap, stripBase64DataUri } from './media-cap.util';
+import { assertBase64LengthWithinMediaCap, assertBase64WithinMediaCap, stripBase64DataUri } from './media-cap.util';
import { SsrfBlockedError, SSRF_BLOCKED_CLIENT_MESSAGE } from '../../common/security/ssrf-guard';
-import { renderTemplate } from '../../common/utils/template-render';
+import { renderedLength, renderTemplate, TemplateRenderError } from '../../common/utils/template-render';
import { IWhatsAppEngine, MessageResult } from '../../engine/interfaces/whatsapp-engine.interface';
import { resolveNonNegativeIntEnv } from '../../config/configuration';
import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
@@ -988,23 +988,62 @@ export class BulkMessageService implements OnModuleInit, OnApplicationBootstrap,
return value;
};
- const rendered = processValue(content) as BulkMessageContent;
+ // Sizes are measured before anything is rendered. One placeholder repeated through a small string
+ // multiplies a large variable (see renderedLength), so checking the finished text would mean
+ // allocating it first, for every string of the item at once.
+ const lengthOf = (str: string): number => {
+ try {
+ return renderedLength(str, variables);
+ } catch (error) {
+ throw error instanceof TemplateRenderError ? new BadRequestException(error.message) : error;
+ }
+ };
+ // The strings with a cap of their own, which the growth total below leaves out.
+ const hasOwnCap = /^(text|caption|(image|video|audio|document)\.base64)$/;
+ const forEachOtherString = (value: unknown, visit: (str: string) => void, path = ''): void => {
+ if (typeof value === 'string') {
+ if (!hasOwnCap.test(path)) visit(value);
+ } else if (Array.isArray(value)) {
+ value.forEach(item => forEachOtherString(item, visit, path));
+ } else if (typeof value === 'object' && value !== null) {
+ for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
+ forEachOtherString(item, visit, path ? `${path}.${key}` : key);
+ }
+ }
+ };
// Cap the MESSAGE, not the payload. Substitution runs over the whole content tree (a URL or a
- // filename may carry a placeholder too), but only the text-bearing fields are bounded: `base64`
- // holds media, which `assertBase64WithinMediaCap` governs at up to MEDIA_DOWNLOAD_MAX_BYTES —
- // three orders of magnitude above this cap. Capping every string rejected the most natural bulk
- // request there is, a personalised media send, because a 100 KB image is ~137,000 base64
- // characters.
+ // filename may carry a placeholder too), but this cap bounds the text-bearing fields: `base64` holds
+ // media, which has the media byte cap (MEDIA_DOWNLOAD_MAX_BYTES), three orders of magnitude above this
+ // one. Capping every string rejected the most natural bulk request there is, a personalised media send,
+ // because a 100 KB image is ~137,000 base64 characters.
for (const field of ['text', 'caption'] as const) {
- const value = rendered[field];
- if (typeof value === 'string' && value.length > maxChars) {
+ const value = content[field];
+ const length = typeof value === 'string' ? lengthOf(value) : 0;
+ if (length > maxChars) {
throw new BadRequestException(
- `Rendered ${field} is ${value.length} characters, over the ${maxChars}-character limit`,
+ `Rendered ${field} is ${length} characters, over the ${maxChars}-character limit`,
);
}
}
- return rendered;
+ // Media is held to its own cap on the length it will render to: the exact check on the finished string
+ // (assertContentMediaWithinCap) runs after the render, which would already have built it.
+ for (const kind of ['image', 'video', 'audio', 'document'] as const) {
+ const base64 = content[kind]?.base64;
+ if (typeof base64 === 'string') assertBase64LengthWithinMediaCap(lengthOf(base64));
+ }
+ // The remaining strings (a URL, a filename) are not bounded one by one, but together they may not grow the
+ // item by more than the text cap.
+ let added = 0;
+ forEachOtherString(content, str => {
+ added += Math.max(0, lengthOf(str) - str.length);
+ });
+ if (added > maxChars) {
+ throw new BadRequestException(
+ `Rendered content grows by ${added} characters, over the ${maxChars}-character limit`,
+ );
+ }
+ return processValue(content) as BulkMessageContent;
}
/**
diff --git a/src/modules/message/media-cap.util.ts b/src/modules/message/media-cap.util.ts
index 6513654f5..b433a769a 100644
--- a/src/modules/message/media-cap.util.ts
+++ b/src/modules/message/media-cap.util.ts
@@ -34,6 +34,22 @@ export function assertBase64WithinMediaCap(base64: string | null | undefined): v
}
}
+/** Room for a `data:<mime>;base64,` prefix, which the exact check strips, when only the length is known. */
+const DATA_URI_PREFIX_ALLOWANCE_CHARS = 256;
+
+/**
+ * The same refusal as {@link assertBase64WithinMediaCap}, for a base64 string that has not been built yet and
+ * is known only by its length (a template renders to it). Refuses only a length certain to decode past the cap,
+ * after allowing for a data URI prefix; whatever is borderline passes, and the exact check on the finished
+ * string decides.
+ */
+export function assertBase64LengthWithinMediaCap(chars: number): void {
+ const maxBytes = inboundMediaMaxBytes();
+ if (Math.floor(((chars - DATA_URI_PREFIX_ALLOWANCE_CHARS) * 3) / 4) > maxBytes) {
+ throw new PayloadTooLargeException(`Base64 media exceeds the maximum allowed size of ${maxBytes} bytes`);
+ }
+}
+
/** A request body that carries media as a URL, as base64, or as both. */
export interface MediaBody {
url?: string;
diff --git a/src/modules/message/message-send.service.spec.ts b/src/modules/message/message-send.service.spec.ts
index 1afc77f72..80a30e13a 100644
--- a/src/modules/message/message-send.service.spec.ts
+++ b/src/modules/message/message-send.service.spec.ts
@@ -583,6 +583,47 @@ describe('MessageSendService', () => {
expect(mockEngine.sendTextMessage).not.toHaveBeenCalled();
});
+ it('answers a 400 from the measured length, without building a render of hundreds of megabytes', async () => {
+ // 341 + 1365 + 341 placeholders fit in a header, body and footer at their size limits. One 393 KB value
+ // would build ~800 MB (a RangeError at the join, or an out-of-memory abort in a small container).
+ (templateService.resolve as jest.Mock).mockResolvedValue(
+ mockTemplate({ header: '{a}'.repeat(341), body: '{a}'.repeat(1365), footer: '{a}'.repeat(341) }),
+ );
+
+ const error = await service
+ .sendTemplate('sess-1', { chatId: '[email protected]', templateId: 'tpl-1', vars: { a: 'x'.repeat(393_000) } })
+ .catch((e: unknown) => e);
+
+ expect(error).toBeInstanceOf(BadRequestException);
+ expect((error as Error).message).toContain(`Rendered template is ${2047 * 393_000 + 4} characters`);
+ expect(mockEngine.sendTextMessage).not.toHaveBeenCalled();
+ });
+
+ it('answers a 400, not a 500, for a variable that has no text form', async () => {
+ (templateService.resolve as jest.Mock).mockResolvedValue(mockTemplate({ body: 'Hi {{customer}}' }));
+
+ await expect(
+ service.sendTemplate('sess-1', {
+ chatId: '[email protected]',
+ templateId: 'tpl-1',
+ vars: { customer: { toString: 1 } as unknown as string },
+ }),
+ ).rejects.toThrow(new BadRequestException("Variable 'customer' cannot be rendered as text"));
+ expect(mockEngine.sendTextMessage).not.toHaveBeenCalled();
+ });
+
+ it('still renders a number sent for a variable', async () => {
+ (templateService.resolve as jest.Mock).mockResolvedValue(mockTemplate({ body: 'Order {{orderId}}' }));
+
+ await service.sendTemplate('sess-1', {
+ chatId: '[email protected]',
+ templateId: 'tpl-1',
+ vars: { orderId: 1234 as unknown as string },
+ });
+
+ expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'Order 1234');
+ });
+
it('renders at-or-under the cap unchanged', async () => {
(templateService.resolve as jest.Mock).mockResolvedValue(mockTemplate({ body: 'Hi {{customer}}' }));
// 'Hi ' + name lands exactly on the 64 KiB default cap — at the cap is NOT over it.
diff --git a/src/modules/message/message-send.service.ts b/src/modules/message/message-send.service.ts
index 5beebca5a..60c821b1f 100644
--- a/src/modules/message/message-send.service.ts
+++ b/src/modules/message/message-send.service.ts
@@ -15,7 +15,7 @@ import { Message, MessageDirection, MessageStatus } from './entities/message.ent
import { HookManager, applySendingGate } from '../../core/hooks';
import { SendPacingService, SettleAdmission, countsTowardSendBreaker } from './send-pacing.service';
import { TemplateService } from '../template/template.service';
-import { renderTemplate } from '../../common/utils/template-render';
+import { renderedLength, renderTemplate, TemplateRenderError } from '../../common/utils/template-render';
import { createLogger } from '../../common/services/logger.service';
import { SsrfBlockedError, SSRF_BLOCKED_CLIENT_MESSAGE } from '../../common/security/ssrf-guard';
import { resolveFeatureFlags } from '../../config/feature-flags';
@@ -275,7 +275,8 @@ export class MessageSendService {
*
* The FINAL rendered text is capped at template.renderMaxChars (default 64 KiB): caller-supplied
* variables can inflate a small template unboundedly, so an over-cap render is rejected with a
- * 400 naming the limit rather than truncated silently or pushed to the engine/DB as-is.
+ * 400 naming the limit rather than truncated silently or pushed to the engine/DB as-is. The length
+ * is measured before anything is rendered, so a refused request never allocates the oversized text.
*/
async sendTemplate(sessionId: string, dto: SendTemplateMessageDto): Promise<MessageResponseDto> {
const template = await this.templateService.resolve(sessionId, {
@@ -284,18 +285,28 @@ export class MessageSendService {
});
const vars = dto.vars ?? {};
- const segments = [template.header, template.body, template.footer]
- .filter((segment): segment is string => segment != null && segment.length > 0)
- .map(segment => renderTemplate(segment, vars));
- const text = segments.join('\n\n');
+ const parts = [template.header, template.body, template.footer].filter(
+ (segment): segment is string => segment != null && segment.length > 0,
+ );
+ const separator = '\n\n';
const maxChars =
this.configService?.get<number>('template.renderMaxChars', DEFAULT_TEMPLATE_RENDER_MAX_CHARS) ??
DEFAULT_TEMPLATE_RENDER_MAX_CHARS;
- if (text.length > maxChars) {
- throw new BadRequestException(
- `Rendered template is ${text.length} characters, over the ${maxChars}-character limit`,
- );
+ let text: string;
+ try {
+ const length =
+ parts.reduce((sum, part) => sum + renderedLength(part, vars), 0) +
+ separator.length * Math.max(0, parts.length - 1);
+ if (length > maxChars) {
+ throw new BadRequestException(
+ `Rendered template is ${length} characters, over the ${maxChars}-character limit`,
+ );
+ }
+ text = parts.map(part => renderTemplate(part, vars)).join(separator);
+ } catch (error) {
+ if (error instanceof TemplateRenderError) throw new BadRequestException(error.message);
+ throw error;
}
return this.sendText(sessionId, {