Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(infra): choose which media a bounded export keeps
Yudhi Armyndharis2a38a3b241ed
diff --git a/.env.example b/.env.exampleindex 5c9ae7802..9a17c6cc9 100644--- a/.env.example+++ b/.env.example@@ -376,9 +376,11 @@ WEBHOOK_SSRF_PROTECT=true# # 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+# # (it rides BODY_SIZE_LIMIT, 25mb by default). Spent on the+# # newest messages first, so a budget that cannot hold+# # everything keeps the most recent media. A URL-referenced# # payload is never counted or dropped — it is a pointer, not-# # bytes. 0 omits every payload.+# # bytes, whatever the case of its scheme. 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/CHANGELOG.md b/CHANGELOG.mdindex 8405c896e..fbf36cd06 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,7 +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. Only `true`/`false`/`1`/`0`/`yes`/`no` are accepted now, so a spelling like `on` that used to work will fail startup until it is changed.-- **A data export now bounds the inline media it carries** — 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. `EXPORT_INLINE_MEDIA_BUDGET_BYTES` (8 MiB by default) caps the total across messages and bulk batches, and payloads past it export as the omitted marker; a URL-referenced payload is never dropped, and a large enough text-only history can still exceed the limit.+- **A data export now bounds the inline media it carries** — 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. `EXPORT_INLINE_MEDIA_BUDGET_BYTES` (8 MiB by default) caps the total across messages and bulk batches, spending it on the newest media first, and payloads past it export as the omitted marker; a URL-referenced payload is never dropped whatever the case of its scheme, and a large enough text-only history can still exceed the limit.- **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.mdindex d95eab9db..3be161d9c 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -5000,9 +5000,9 @@ Export every row of the 13 migration tables from the Data DB as JSON. Read-only,**Auth:** API key (ADMIN)-> **Inline media is carried up to a budget, then omitted.** `EXPORT_INLINE_MEDIA_BUDGET_BYTES` (8 MiB of encoded base64 by default) bounds how much inline media one export may hold, counted across both `messages` and `messageBatches`. Payloads past it arrive as the omitted marker — `{ mimetype, filename?, omitted: true, sizeBytes }`, the same shape the engine emits when an inbound payload exceeds `MEDIA_DOWNLOAD_MAX_BYTES` — so those messages restore without their pictures. Without the bound, one 50 MiB attachment becomes 66 MiB of base64 and exceeds the import's own request-body limit (`BODY_SIZE_LIMIT`, 25mb by default), producing a backup this gateway refuses to restore with `413`.+> **Inline media is carried up to a budget, then omitted.** `EXPORT_INLINE_MEDIA_BUDGET_BYTES` (8 MiB of encoded base64 by default) bounds how much inline media one export may hold, counted across both `messages` and `messageBatches`. It is spent on the newest messages first, so an export that cannot carry everything keeps the most recent media rather than whatever the database happened to return first. Payloads past it arrive as the omitted marker — `{ mimetype, filename?, omitted: true, sizeBytes }`, the same shape the engine emits when an inbound payload exceeds `MEDIA_DOWNLOAD_MAX_BYTES` — so those messages restore without their pictures. Without the bound, one 50 MiB attachment becomes 66 MiB of base64 and exceeds the import's own request-body limit (`BODY_SIZE_LIMIT`, 25mb by default), producing a backup this gateway refuses to restore with `413`.>-> A **URL-referenced** payload is never counted or dropped: `metadata.media.data` holds either base64 or the URL a send was given, and a URL is a pointer worth a few dozen bytes.+> A **URL-referenced** payload is never counted or dropped: `metadata.media.data` holds either base64 or the URL a send was given, and a URL is a pointer worth a few dozen bytes. The scheme is matched case-insensitively, as both engine adapters do when they fetch it.>> This bounds the media, not the export — a large enough text-only history still exceeds the import limit, because every row costs a few hundred bytes of scaffolding whatever was said. For a backup that keeps everything, use `scripts/backup.sh`: it snapshots the database file itself (and `pg_dump`s Postgres), so inline media rides along regardless of this budget.diff --git a/src/modules/infra/infra-data.controller.spec.ts b/src/modules/infra/infra-data.controller.spec.tsindex 45db8517c..8cf5f6a6b 100644--- a/src/modules/infra/infra-data.controller.spec.ts+++ b/src/modules/infra/infra-data.controller.spec.ts@@ -607,6 +607,70 @@ describe('InfraDataController.importData round-trips export-data (no silent mess});});+ it('never strips a URL whose scheme is uppercase — both engines fetch it, so it is a pointer too', async () => {+ // `@IsUrl()` accepts it and both adapters match the scheme case-insensitively (wwebjs-messaging.ts+ // `isHttpUrl`, baileys-messaging.ts `resolveMediaBuffer`), so this URL sends successfully and the+ // row is its only record. Classifying it as bytes destroys that reference for good.+ const url = 'HTTPS://cdn.example.com/PROMO.png';+ await seedSession('s1');+ await ds.getRepository(Message).save(+ ds.getRepository(Message).create({+ id: 'm-url-upper',+ sessionId: 's1',+ waMessageId: 'WA-URL-UPPER',+ chatId: '[email protected]',+ from: '[email protected]',+ to: '[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,+ }),+ );++ await withBudget(0, async () => {+ const meta = exportedMeta(await controller.exportData(), 'm-url-upper');+ expect(meta.media).toEqual({ mimetype: 'image/png', filename: 'promo.png', data: url });+ });+ });++ it('spends the export budget on the newest media first', async () => {+ // `SELECT *` has no ORDER BY, so the rows arrive in rowid order on SQLite — oldest first, the+ // exact inverse of what a backup wants. Both photos fit alone; only one fits the budget.+ const olderPhoto = Buffer.from('o'.repeat(600)).toString('base64');+ const newerPhoto = Buffer.from('n'.repeat(600)).toString('base64');+ await seedSession('s1');+ const seedPhoto = async (id: string, timestamp: number, data: string): Promise<void> => {+ await ds.getRepository(Message).save(+ ds.getRepository(Message).create({+ id,+ sessionId: 's1',+ waMessageId: `WA-${id}`,+ chatId: '[email protected]',+ from: '[email protected]',+ to: '[email protected]',+ body: null as never,+ type: 'image',+ direction: MessageDirection.INCOMING,+ timestamp,+ metadata: { media: { mimetype: 'image/jpeg', data } },+ status: MessageStatus.DELIVERED,+ }),+ );+ };+ // Inserted oldest-first, which is also how SQLite hands them back.+ await seedPhoto('m-older', 1700000000, olderPhoto);+ await seedPhoto('m-newer', 1800000000, newerPhoto);++ await withBudget(Buffer.byteLength(newerPhoto, 'utf8'), async () => {+ const dump = await controller.exportData();+ expect(exportedMeta(dump, 'm-newer').media).toEqual({ mimetype: 'image/jpeg', data: newerPhoto });+ expect(exportedMeta(dump, 'm-older').media).toMatchObject({ omitted: true });+ });+ });+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.diff --git a/src/modules/infra/infra-data.controller.ts b/src/modules/infra/infra-data.controller.tsindex 628d68a3a..3136bb87e 100644--- a/src/modules/infra/infra-data.controller.ts+++ b/src/modules/infra/infra-data.controller.ts@@ -160,7 +160,20 @@ function exportInlineMediaBudgetBytes(): number {* 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://');+ // Case-insensitive to match the two adapters that actually fetch these (`isHttpUrl` in+ // wwebjs-messaging.ts, `resolveMediaBuffer` in baileys-messaging.ts). `@IsUrl()` accepts an+ // uppercase scheme, so a row can hold one; disagreeing with the senders here would destroy a+ // reference to media they had just delivered.+ return /^https?:\/\//i.test(data);+}++/**+ * Sort key for the media budget: newest first, so a budget that cannot hold everything keeps the+ * most recent media. `Number(null)` is 0, which sorts an undated row last — the least worth keeping.+ */+function newestFirstKey(row: MessageRow): number {+ const timestamp = Number(row.timestamp);+ return Number.isFinite(timestamp) ? timestamp : 0;}/** Spends the shared budget. Returns true when this payload does not fit and must be dropped. */@@ -350,6 +363,13 @@ 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;+ }+ // Spend the budget newest-first. `SELECT *` carries no ORDER BY, so rows arrive in rowid order on+ // SQLite — oldest first, so an exhausted budget would keep the oldest photos and omit every recent+ // one — and in physical-tuple order on Postgres, which routine UPDATEs (ack, edits, reactions,+ // archive pointers) reshuffle, so two exports of an unchanged DB need not agree on which media+ // they carry. Sorting a COPY leaves the exported array's own order untouched.+ for (const row of [...messages].sort((a, b) => newestFirstKey(b) - newestFirstKey(a))) {stripInlineMediaPayload(row, exceedsBudget);}const messageBatches = await queryOptionalTable<MessageBatchRow>('message_batches');