Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(infra): bound exported inline media with a budget instead of dropping it

Yudhi Armyndharisde9c3d8adba0
diff --git a/.env.example b/.env.example
index 17207a252..223ce4102 100644
--- a/.env.example
+++ b/.env.example
@@ -369,6 +369,14 @@ WEBHOOK_SSRF_PROTECT=true
# # (no decryption, no memory allocation, no storage).
# # NOTE: disabling also makes hasMedia report false and removes the
# # media field from webhooks and the dashboard.
+# EXPORT_INLINE_MEDIA_BUDGET_BYTES=8388608
+# # How much inline base64 media one GET /infra/export-data may
+# # carry, in encoded bytes (default 8 MiB). Past it the remaining
+# # payloads are exported as the omitted marker, because an
+# # unbounded export produces a backup the import refuses with 413
+# # (it rides BODY_SIZE_LIMIT, 25mb by default). A URL-referenced
+# # payload is never counted or dropped — it is a pointer, not
+# # bytes. 0 omits every payload.
# 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/src/config/env.validation.ts b/src/config/env.validation.ts
index 68a6c3d5e..3a44961d0 100644
--- a/src/config/env.validation.ts
+++ b/src/config/env.validation.ts
@@ -172,6 +172,7 @@ export function validateEnv(config: EnvConfig): EnvConfig {
'WEBHOOK_MAX_PER_SESSION', // 0 = unlimited
'AUTOMATION_MAX_PER_SESSION', // 0 = unlimited
'WEBHOOK_MEDIA_INLINE_MAX_BYTES', // 0 = never inline media
+ 'EXPORT_INLINE_MEDIA_BUDGET_BYTES', // 0 = a data export carries no inline media at all
]) {
checkNonNegativeInt(key);
}
diff --git a/src/modules/infra/infra-data.controller.spec.ts b/src/modules/infra/infra-data.controller.spec.ts
index e5dc9971e..45db8517c 100644
--- a/src/modules/infra/infra-data.controller.spec.ts
+++ b/src/modules/infra/infra-data.controller.spec.ts
@@ -528,12 +528,103 @@ describe('InfraDataController.importData round-trips export-data (no silent mess
expect(b.status).toBe(BatchStatus.COMPLETED);
});
- it('drops inline media from the export, leaving the omitted marker and the rest of metadata intact', async () => {
- // The export is unbounded while the import rides the 25mb body limit, so a single media message
- // — base64 is 4/3 of a blob capped at MEDIA_DOWNLOAD_MAX_BYTES, 50 MiB by default — is enough to
- // produce a backup this gateway cannot restore. The marker shape is the engine's own
- // (capInboundMedia, inbound-media-cap.ts:148), so a restored row is indistinguishable from one
- // whose media was skipped on the way in: the schema survives, only the pixels go.
+ // The export is unbounded while the import rides the 25mb body limit, so inline base64 can produce
+ // a backup this gateway cannot restore. What bounds it is an aggregate budget, not a blanket strip:
+ // a small photo costs nothing and is the ONLY copy when the chat-media archive is off (the default),
+ // so dropping it would trade a 413 for silent data loss.
+ const withBudget = async (bytes: number, run: () => Promise<void>): Promise<void> => {
+ const prev = process.env.EXPORT_INLINE_MEDIA_BUDGET_BYTES;
+ process.env.EXPORT_INLINE_MEDIA_BUDGET_BYTES = String(bytes);
+ try {
+ await run();
+ } finally {
+ if (prev === undefined) delete process.env.EXPORT_INLINE_MEDIA_BUDGET_BYTES;
+ else process.env.EXPORT_INLINE_MEDIA_BUDGET_BYTES = prev;
+ }
+ };
+
+ const exportedMeta = (
+ dump: Awaited<ReturnType<typeof controller.exportData>>,
+ id: string,
+ ): Record<string, unknown> => {
+ const row = dump.tables.messages.find(r => r.id === id);
+ return (typeof row?.metadata === 'string' ? JSON.parse(row.metadata) : row?.metadata) as Record<string, unknown>;
+ };
+
+ it('keeps inline media that fits the export budget — it is the only copy when the archive is off', async () => {
+ const base64 = Buffer.from('a small photo, three orders of magnitude under any limit').toString('base64');
+ await seedSession('s1');
+ await ds.getRepository(Message).save(
+ ds.getRepository(Message).create({
+ id: 'm-small',
+ sessionId: 's1',
+ waMessageId: 'WA-SMALL',
+ chatId: '[email protected]',
+ body: null as never,
+ type: 'image',
+ direction: MessageDirection.INCOMING,
+ timestamp: 1700000000,
+ metadata: { media: { mimetype: 'image/jpeg', data: base64 }, ack: 2 },
+ status: MessageStatus.DELIVERED,
+ }),
+ );
+
+ await withBudget(1_000_000, async () => {
+ const meta = exportedMeta(await controller.exportData(), 'm-small');
+ expect(meta.media).toEqual({ mimetype: 'image/jpeg', data: base64 });
+ });
+ });
+
+ it('never strips a URL-referenced payload — `data` holds either base64 OR a URL', async () => {
+ // message.service.ts persists `data: base64 || dto.url!`, and the URL form is the only one the
+ // Swagger examples offer. A URL is a pointer, not bytes: stripping it destroys the reference and
+ // reports a sizeBytes that is Buffer.byteLength of URL text read as base64 — the size of nothing.
+ const url = 'https://cdn.example.com/promo.png';
+ await seedSession('s1');
+ await ds.getRepository(Message).save(
+ ds.getRepository(Message).create({
+ id: 'm-url',
+ sessionId: 's1',
+ waMessageId: 'WA-URL',
+ chatId: '[email protected]',
+ body: null as never,
+ type: 'image',
+ direction: MessageDirection.OUTGOING,
+ timestamp: 1700000000,
+ metadata: { media: { mimetype: 'image/png', filename: 'promo.png', data: url } },
+ status: MessageStatus.SENT,
+ }),
+ );
+
+ // Budget of zero: everything strippable WOULD be stripped, so surviving proves the URL guard.
+ await withBudget(0, async () => {
+ const meta = exportedMeta(await controller.exportData(), 'm-url');
+ expect(meta.media).toEqual({ mimetype: 'image/png', filename: 'promo.png', data: url });
+ });
+ });
+
+ it('does not 500 the export when a metadata column holds the JSON text `null`', async () => {
+ // The import accepts a hand-edited archive verbatim (table-importers.ts), so this row is
+ // reachable — and `JSON.parse('null')` returns null, whose `.media` read throws.
+ await seedSession('s1');
+ await ds.query(
+ `INSERT INTO messages (id, "sessionId", "waMessageId", "chatId", "from", "to", body, type, direction, timestamp, metadata, status, "createdAt")
+ VALUES ('m-null', 's1', 'WA-NULL', '[email protected]', 'a@x', 'b@x', 'hi', 'text', 'incoming', 1700000000, 'null', 'delivered', '2026-01-01T00:00:00.000Z')`,
+ );
+
+ await withBudget(0, async () => {
+ const dump = await controller.exportData();
+ expect(dump.tables.messages.find(r => r.id === 'm-null')?.metadata).toBe('null');
+ });
+ });
+
+ it('drops inline media past the export budget, leaving the omitted marker and the rest intact', async () => {
+ // The marker shape is the engine's own (capInboundMedia), so a restored row is indistinguishable
+ // from one whose media was skipped on the way in: the schema survives, only the pixels go.
const base64 = Buffer.from('not really a jpeg, but bytes all the same').toString('base64');
await seedSession('s1');
await ds.getRepository(Message).save(
@@ -553,12 +644,12 @@ describe('InfraDataController.importData round-trips export-data (no silent mess
}),
);
- const dump = await controller.exportData();
+ let dump!: Awaited<ReturnType<typeof controller.exportData>>;
+ await withBudget(0, async () => {
+ dump = await controller.exportData();
+ });
const exported = dump.tables.messages.find(r => r.id === 'm-media');
- const meta = (typeof exported?.metadata === 'string' ? JSON.parse(exported.metadata) : exported?.metadata) as {
- media: Record<string, unknown>;
- ack: number;
- };
+ const meta = exportedMeta(dump, 'm-media') as { media: Record<string, unknown>; ack: number };
expect(meta.media).not.toHaveProperty('data');
expect(meta.media).toEqual({
@@ -587,6 +678,50 @@ describe('InfraDataController.importData round-trips export-data (no silent mess
});
});
+ it('drops base64 from a bulk batch past the budget but keeps its URL and descriptive fields', async () => {
+ // message_batches carries the whole outbound list, base64 included, for the WHOLE duration of a
+ // run — stripBatchMediaPayloads only fires on the four terminal transitions. So the export has to
+ // bound it too, or the 413 the messages strip was written for simply arrives by another route.
+ await seedSession('s1');
+ await ds.getRepository(MessageBatch).save(
+ ds.getRepository(MessageBatch).create({
+ id: 'b-media',
+ batchId: 'BATCH-MEDIA',
+ sessionId: 's1',
+ status: BatchStatus.PROCESSING,
+ messages: [
+ {
+ chatId: 'c1',
+ type: 'image',
+ content: { image: { base64: 'QUJDREVG', mimetype: 'image/png', caption: 'hi' } },
+ },
+ {
+ chatId: 'c2',
+ type: 'image',
+ content: { image: { url: 'https://cdn.example.com/x.png', mimetype: 'image/png' } },
+ },
+ ] as never,
+ options: null as never,
+ progress: null as never,
+ results: null as never,
+ currentIndex: 0,
+ startedAt: null,
+ completedAt: null,
+ }),
+ );
+
+ await withBudget(0, async () => {
+ const dump = await controller.exportData();
+ const row = dump.tables.messageBatches.find(r => r.id === 'b-media');
+ const msgs = (typeof row?.messages === 'string' ? JSON.parse(row.messages) : row?.messages) as Array<{
+ content: { image: Record<string, unknown> };
+ }>;
+ expect(msgs[0].content.image).not.toHaveProperty('base64');
+ expect(msgs[0].content.image).toMatchObject({ mimetype: 'image/png', caption: 'hi' });
+ expect(msgs[1].content.image).toEqual({ url: 'https://cdn.example.com/x.png', mimetype: 'image/png' });
+ });
+ });
+
it('round-trips plugin instances + integration delivery failures (Integration Fabric + DLQ)', async () => {
await seedSession('s1');
await ds.getRepository(PluginInstance).save(
diff --git a/src/modules/infra/infra-data.controller.ts b/src/modules/infra/infra-data.controller.ts
index 89e579f6f..628d68a3a 100644
--- a/src/modules/infra/infra-data.controller.ts
+++ b/src/modules/infra/infra-data.controller.ts
@@ -132,48 +132,118 @@ export async function restoreSessionOwnership(
const SHARED_CONNECTION_DIALECTS = new Set(['better-sqlite3', 'sqlite']);
/**
- * Drop the inline base64 blob from an exported message row, leaving the engine's own omitted marker.
+ * Aggregate budget for the inline base64 media ONE export may carry, counted in the encoded bytes
+ * that actually land in the JSON body. Override with EXPORT_INLINE_MEDIA_BUDGET_BYTES; 0 omits every
+ * payload, and a garbage value falls back to the default.
*
* The export is bounded by nothing while the import rides the global request body limit (25mb by
- * default, `resolveBodyLimit`), so a single media message is enough to produce a backup this gateway
- * cannot restore: inbound media is capped at MEDIA_DOWNLOAD_MAX_BYTES (50 MiB by default) and base64
- * inflates it to 4/3 of that, well past the import's ceiling. Same reason the generated `body_ts`
- * column is stripped a few lines below — a backup has to stay restorable to be a backup.
+ * default, `resolveBodyLimit`), so unbounded inline media produces a backup this gateway then refuses
+ * with a 413 — inbound media is capped at MEDIA_DOWNLOAD_MAX_BYTES (50 MiB by default) and base64
+ * inflates that to 4/3.
*
- * The replacement is the marker `capInboundMedia` already emits for an over-cap payload
- * (`{ mimetype, filename?, omitted: true, sizeBytes }`), so a restored row is indistinguishable from
- * one whose media was skipped on the way in rather than a new shape consumers must learn: the `media`
- * field stays present and only the bytes are gone. `mediaPath`/`mediaMimetype` are untouched, and
- * `scripts/backup.sh` copies the storage tree unconditionally, so an operator on the runbook path
- * still has the files themselves.
+ * A blanket strip would trade the 413 for silent data loss, which is why this is a budget and not a
+ * flag: with the chat-media archive off — the default — `metadata.media.data` is the ONLY copy of an
+ * inbound photo, and a 180 KB one costs nothing against a 25 MiB ceiling. Mirrors
+ * CHAT_HISTORY_MEDIA_BUDGET_BYTES, which bounds the same failure on the chat-history response.
+ */
+const DEFAULT_EXPORT_INLINE_MEDIA_BUDGET_BYTES = 8 * 1024 * 1024;
+
+function exportInlineMediaBudgetBytes(): number {
+ const parsed = Number.parseInt(process.env.EXPORT_INLINE_MEDIA_BUDGET_BYTES ?? '', 10);
+ return Number.isInteger(parsed) && parsed >= 0 ? parsed : DEFAULT_EXPORT_INLINE_MEDIA_BUDGET_BYTES;
+}
+
+/**
+ * A `data` value that is a POINTER rather than bytes. `metadata.media.data` holds `base64 || dto.url!`
+ * (message.service.ts), and the URL form is the only one the send examples offer — so a URL must never
+ * be treated as a payload: dropping it destroys the reference for a few dozen bytes that were never a
+ * 413 risk, and reports a `sizeBytes` that is URL text measured as base64, the size of nothing.
+ */
+function isMediaPointer(data: string): boolean {
+ return data.startsWith('http://') || data.startsWith('https://');
+}
+
+/** Spends the shared budget. Returns true when this payload does not fit and must be dropped. */
+function createInlineMediaBudget(): (encodedBytes: number) => boolean {
+ const budget = exportInlineMediaBudgetBytes();
+ let spent = 0;
+ return (encodedBytes: number): boolean => {
+ if (spent + encodedBytes > budget) return true;
+ spent += encodedBytes;
+ return false;
+ };
+}
+
+/**
+ * Replace an over-budget inline payload on a message row with the engine's own omitted marker
+ * (`{ mimetype, filename?, omitted: true, sizeBytes }`, `capInboundMedia`), so a restored row is
+ * indistinguishable from one whose media was skipped on the way in rather than a new shape consumers
+ * must learn. `mediaPath`/`mediaMimetype` are untouched.
*
* NOTE: this bounds the media, not the export. A text-only history is still unbounded — every row
* carries a few hundred bytes of scaffolding regardless of what was said.
*/
-function stripInlineMediaPayload(row: MessageRow): void {
+function stripInlineMediaPayload(row: MessageRow, exceedsBudget: (encodedBytes: number) => boolean): void {
+ // `metadata` is TEXT on both dialects and the export reads through a raw query that never hydrates
+ // an entity, so the value is always a string here.
const raw = row.metadata;
- if (raw == null) return;
- let parsed: Record<string, unknown>;
- if (typeof raw === 'string') {
- try {
- parsed = JSON.parse(raw) as Record<string, unknown>;
- } catch {
- // Metadata we cannot parse is not ours to rewrite; the importer round-trips it verbatim.
- return;
- }
- } else {
- parsed = { ...raw };
+ if (typeof raw !== 'string') return;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(raw);
+ } catch {
+ // Metadata we cannot parse is not ours to rewrite; the importer round-trips it verbatim.
+ return;
}
- const media = parsed.media as { data?: unknown; sizeBytes?: number } | null | undefined;
- if (!media || typeof media.data !== 'string') return;
+ // `JSON.parse('null')` yields null, and the import accepts a hand-edited archive verbatim, so this
+ // is reachable — reading `.media` off it would 500 every export until the row is deleted by hand.
+ if (typeof parsed !== 'object' || parsed === null) return;
+ const bag = parsed as Record<string, unknown>;
+ const media = bag.media as { data?: unknown; sizeBytes?: number } | null | undefined;
+ if (!media || typeof media.data !== 'string' || isMediaPointer(media.data)) return;
+ if (!exceedsBudget(Buffer.byteLength(media.data, 'utf8'))) return;
const { data, ...withoutPayload } = media;
- parsed.media = {
+ bag.media = {
...withoutPayload,
omitted: true,
// Decoded bytes, matching what capInboundMedia reports — the caller asked how big it WAS.
sizeBytes: media.sizeBytes ?? Buffer.byteLength(data, 'base64'),
};
- row.metadata = typeof raw === 'string' ? JSON.stringify(parsed) : parsed;
+ row.metadata = JSON.stringify(bag);
+}
+
+/**
+ * The same budget applied to a bulk batch's stored message list.
+ *
+ * `message_batches.messages` carries the whole outbound list, base64 included, for the entire
+ * duration of a run — `stripBatchMediaPayloads` only fires on the four terminal transitions, and a
+ * batch left PROCESSING by another node keeps its payloads indefinitely. Bounding only `messages`
+ * would let the 413 arrive by this route instead. The batch shape keeps `url` in its own field, so
+ * unlike a message row there is no pointer to confuse with a payload.
+ */
+function stripBatchInlineMedia(row: MessageBatchRow, exceedsBudget: (encodedBytes: number) => boolean): void {
+ const raw = row.messages;
+ if (typeof raw !== 'string') return;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(raw);
+ } catch {
+ return;
+ }
+ if (!Array.isArray(parsed)) return;
+ let stripped = false;
+ for (const entry of parsed) {
+ const content = (entry as { content?: unknown } | null)?.content;
+ if (typeof content !== 'object' || content === null) continue;
+ for (const key of ['image', 'video', 'audio', 'document']) {
+ const media = (content as Record<string, unknown>)[key] as { base64?: unknown } | null | undefined;
+ if (!media || typeof media !== 'object' || typeof media.base64 !== 'string') continue;
+ if (!exceedsBudget(Buffer.byteLength(media.base64, 'utf8'))) continue;
+ delete media.base64;
+ stripped = true;
+ }
+ }
+ if (stripped) row.messages = JSON.stringify(parsed);
}
@ApiTags('infrastructure')
@@ -270,15 +340,22 @@ export class InfraDataController {
}
};
+ // One budget shared by both tables that can carry inline media, so the total is what is bounded
+ // rather than each table separately.
+ const exceedsBudget = createInlineMediaBudget();
+
const messages = await queryOptionalTable<MessageRow>('messages');
// Postgres carries a STORED generated tsvector column `body_ts` (FTS) that `SELECT *` picks up.
// It is a server-maintained index artifact, not payload: strip it so backups stay dialect-neutral
// (and small). The import's explicit column list already ignores it in older archives.
for (const row of messages) {
delete row.body_ts;
- stripInlineMediaPayload(row);
+ stripInlineMediaPayload(row, exceedsBudget);
}
const messageBatches = await queryOptionalTable<MessageBatchRow>('message_batches');
+ for (const row of messageBatches) {
+ stripBatchInlineMedia(row, exceedsBudget);
+ }
const templates = await queryOptionalTable<TemplateRow>('templates');
const baileysStoredMessages = await queryOptionalTable<BaileysStoredMessageRow>('baileys_stored_messages');
const lidMappings = await queryOptionalTable<LidMappingRow>('lid_mappings');