Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(infra): drop inline media bytes from the data export

Yudhi Armyndharisa6283efa6523
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ad88c0d57..a9ca5dd4e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **A WhatsApp-initiated unlink now clears a session's stored credentials once rather than twice** — whatsapp-web.js can raise the logout event more than once for a single unlink and nothing deduplicated it, so the repeats raced each other and a still-open browser into the `ENOTEMPTY` failure the removal now carries the retry budget to survive.
- **A reaction to a message the gateway never stored no longer vanishes** — the `message.reaction` webhook and the dashboard stream were both gated on the stored row, so a reaction to an ephemeral message, or to one that arrived before the session went live, was dropped with no error and no log.
- **`MEDIA_DOWNLOAD_ENABLED` is now validated at boot** — it is read as "anything that is not `false`/`0`/`no`", so a typo left inbound media being decrypted and base64-inlined into every message row instead of disabling it.
+- **A data export no longer carries inline media bytes** — base64 inflates a single 50 MiB attachment to 66 MiB, past the import's own 25mb request-body limit, so a backup could export cleanly and then be refused with `413` on restore.
- **A data import now carries each session's ownership lease by its remaining time instead of its original deadline** — a restore re-applied the deadline unchanged, so one that ran longer than a claim had left committed that claim as expired, including claims held by other nodes whose engines never stopped.
- **A refused data import no longer offers a retry that stops live engines** — the one refusal whose retry is destructive now carries `IMPORT_WOULD_ORPHAN_ENGINES` and the dashboard matches it positively, so a refusal that only asks the operator to wait can no longer present a confirm whose OK re-runs the replace-all with `stopOrphans=true`.
- **A data import is refused with `409` when another transaction holds the connection** — on SQLite it would otherwise nest inside that transaction and commit into it rather than to disk, so a restore reported as successful could vanish with that transaction's rollback.
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index bfb6cdbfb..7092a947d 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -5000,6 +5000,8 @@ Export every row of the 13 migration tables from the Data DB as JSON. Read-only,
**Auth:** API key (ADMIN)
+> **Inline media bytes are not in the export.** A message row's `metadata.media` keeps its shape but arrives as the omitted marker — `{ mimetype, filename?, omitted: true, sizeBytes }`, the same one the engine emits when an inbound payload is over `MEDIA_DOWNLOAD_MAX_BYTES`. Without this, one media message could exceed the import's own request-body limit (`BODY_SIZE_LIMIT`, 25mb by default), producing a backup this gateway refuses to restore with `413`. Restored messages therefore render without their pictures. The files themselves are not part of this endpoint in either direction: back them up with the storage tree (see `scripts/backup.sh`, which copies it unconditionally), and note that the export never carried them even before the bytes were dropped.
+
The migration set (`MigrationTables`) is, in payload-key order: `sessions`, `webhooks`, `messages`, `messageBatches`, `templates`, `baileysStoredMessages`, `lidMappings`, `pluginInstances`, `conversationMappings`, `ingressEvents`, `webhookDeliveryFailures`, `integrationDeliveryFailures`, `statusUpdates`.
**Response** `200`
diff --git a/src/modules/infra/infra-data.controller.spec.ts b/src/modules/infra/infra-data.controller.spec.ts
index e8c3011db..e5dc9971e 100644
--- a/src/modules/infra/infra-data.controller.spec.ts
+++ b/src/modules/infra/infra-data.controller.spec.ts
@@ -528,6 +528,65 @@ 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.
+ const base64 = Buffer.from('not really a jpeg, but bytes all the same').toString('base64');
+ await seedSession('s1');
+ await ds.getRepository(Message).save(
+ ds.getRepository(Message).create({
+ id: 'm-media',
+ sessionId: 's1',
+ waMessageId: 'WA-MEDIA',
+ chatId: '[email protected]',
+ body: null as never,
+ type: 'image',
+ direction: MessageDirection.INCOMING,
+ timestamp: 1700000000,
+ metadata: { media: { mimetype: 'image/jpeg', filename: 'holiday.jpg', data: base64 }, ack: 2 },
+ status: MessageStatus.DELIVERED,
+ }),
+ );
+
+ const 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;
+ };
+
+ expect(meta.media).not.toHaveProperty('data');
+ expect(meta.media).toEqual({
+ mimetype: 'image/jpeg',
+ filename: 'holiday.jpg',
+ omitted: true,
+ sizeBytes: Buffer.byteLength(base64, 'base64'),
+ });
+ // Everything else on the row, and everything else in metadata, is untouched.
+ expect(meta.ack).toBe(2);
+ expect(exported?.type).toBe('image');
+ expect(exported?.waMessageId).toBe('WA-MEDIA');
+
+ // And the backup still restores.
+ const res = await controller.importData({ tables: dump.tables });
+ expect(res.imported).toBe(true);
+ const restored = await ds.getRepository(Message).findOneByOrFail({ id: 'm-media' });
+ expect(restored.metadata).toEqual({
+ media: {
+ mimetype: 'image/jpeg',
+ filename: 'holiday.jpg',
+ omitted: true,
+ sizeBytes: Buffer.byteLength(base64, 'base64'),
+ },
+ ack: 2,
+ });
+ });
+
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 57415db3b..89e579f6f 100644
--- a/src/modules/infra/infra-data.controller.ts
+++ b/src/modules/infra/infra-data.controller.ts
@@ -131,6 +131,51 @@ 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.
+ *
+ * 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.
+ *
+ * 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.
+ *
+ * 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 {
+ 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 };
+ }
+ const media = parsed.media as { data?: unknown; sizeBytes?: number } | null | undefined;
+ if (!media || typeof media.data !== 'string') return;
+ const { data, ...withoutPayload } = media;
+ parsed.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;
+}
+
@ApiTags('infrastructure')
@Controller('infra')
// Every route here is deployment-global (data export/import, infra config, service orchestration),
@@ -231,6 +276,7 @@ export class InfraDataController {
// (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);
}
const messageBatches = await queryOptionalTable<MessageBatchRow>('message_batches');
const templates = await queryOptionalTable<TemplateRow>('templates');