Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

docs: correct the migration-table set and the batch media marker

Yudhi Armyndharisbfe0d032e113
diff --git a/.env.example b/.env.example
index 9a17c6cc9..346efc8f4 100644
--- a/.env.example
+++ b/.env.example
@@ -373,8 +373,9 @@ WEBHOOK_SSRF_PROTECT=true
# # because an unrecognised value silently means ENABLED.
# 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
+# # carry, in encoded bytes (default 8 MiB). Past it a message
+# # payload is exported as the omitted marker and a bulk-batch
+# # entry simply loses its base64, because an
# # unbounded export produces a backup the import refuses with 413
# # (it rides BODY_SIZE_LIMIT, 25mb by default). Spent on the
# # newest messages first, so a budget that cannot hold
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fbf36cd06..1d9b4cd6a 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, 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 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 an over-budget message payload exports as the omitted marker while a bulk-batch entry simply loses its `base64`; 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/05-database-design.md b/docs/05-database-design.md
index 95d043a51..88dd52833 100644
--- a/docs/05-database-design.md
+++ b/docs/05-database-design.md
@@ -55,6 +55,7 @@ OpenWA v0.2+ implements a **dual-database architecture** that separates boot con
│ │ • integration_delivery_failures │
│ │ • baileys_stored_messages (engine)│
│ │ • lid_mappings (engine) │
+│ │ • automation_rules │
└─────────────────────────────┴───────────────────────────────────┘
```
@@ -757,10 +758,10 @@ flowchart LR
OpenWA runs **two separate TypeORM connections**, each with its own migrations directory and CLI DataSource:
-| Connection | DataSource | Migrations dir | Owns |
-| ---------- | --------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| **main** | `data-source-main.ts` | `src/database/migrations-main/` | `api_keys`, `audit_logs` — always SQLite (`./data/main.sqlite` by default) |
-| **data** | `data-source.ts` | `src/database/migrations/` | `sessions`, `webhooks`, `messages`, `message_batches`, `templates`, `status_updates`, `webhook_delivery_failures`, the integration tables (`plugin_instances`, `ingress_events`, `conversation_mappings`, `integration_delivery_failures`), engine tables — SQLite **or** PostgreSQL |
+| Connection | DataSource | Migrations dir | Owns |
+| ---------- | --------------------- | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| **main** | `data-source-main.ts` | `src/database/migrations-main/` | `api_keys`, `audit_logs` — always SQLite (`./data/main.sqlite` by default) |
+| **data** | `data-source.ts` | `src/database/migrations/` | `sessions`, `webhooks`, `messages`, `message_batches`, `templates`, `status_updates`, `automation_rules`, `webhook_delivery_failures`, the integration tables (`plugin_instances`, `ingress_events`, `conversation_mappings`, `integration_delivery_failures`), engine tables — SQLite **or** PostgreSQL |
Migrations are hand-authored and idempotent (`IF NOT EXISTS`) so they are safe to adopt on a database originally created by `synchronize`. The two connections differ in how schema is managed:
@@ -797,7 +798,11 @@ src/database/migrations/ # data connection (pluggable)
├── 1784908800000-AddMessageAuthor.ts
├── 1785112230000-AddIngressEventDispatchState.ts
├── 1785123853000-AddMessagesCreatedAtIndex.ts
-└── 1785600000000-SlimIngressEventPayload.ts
+├── 1785600000000-SlimIngressEventPayload.ts
+├── 1785700000000-AddMessageMediaArchive.ts
+├── 1785800000000-AddSessionOwnership.ts
+├── 1785900000000-AddAutomationRules.ts # 14th migration table; FKs sessions ON DELETE CASCADE
+└── 1786000000000-AddSessionNodeUrl.ts
```
> [!NOTE]
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 3be161d9c..0a884ed0d 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -4996,17 +4996,17 @@ Request a graceful server restart, optionally orchestrating Docker profiles (add
#### GET /api/infra/export-data
-Export every row of the 13 migration tables from the Data DB as JSON. Read-only, but runs raw `SELECT *` on the `data` DataSource.
+Export every row of the 14 migration tables from the Data DB as JSON. Read-only, but runs raw `SELECT *` on the `data` DataSource.
**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`. 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`.
+> **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. An over-budget payload on a `messages` row arrives 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. A `messageBatches` entry carries no marker: it simply loses its `base64` and keeps `url`, `mimetype` and `caption`, which is the shape a batch already has once it reaches a terminal state. 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. 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.
-The migration set (`MigrationTables`) is, in payload-key order: `sessions`, `webhooks`, `messages`, `messageBatches`, `templates`, `baileysStoredMessages`, `lidMappings`, `pluginInstances`, `conversationMappings`, `ingressEvents`, `webhookDeliveryFailures`, `integrationDeliveryFailures`, `statusUpdates`.
+The migration set (`MigrationTables`) is, in payload-key order: `sessions`, `webhooks`, `messages`, `messageBatches`, `templates`, `baileysStoredMessages`, `lidMappings`, `pluginInstances`, `conversationMappings`, `ingressEvents`, `webhookDeliveryFailures`, `integrationDeliveryFailures`, `statusUpdates`, `automationRules`.
**Response** `200`
@@ -5042,7 +5042,8 @@ The migration set (`MigrationTables`) is, in payload-key order: `sessions`, `web
"ingressEvents": [],
"webhookDeliveryFailures": [],
"integrationDeliveryFailures": [],
- "statusUpdates": []
+ "statusUpdates": [],
+ "automationRules": []
},
"counts": {
"sessions": 1,
@@ -5057,7 +5058,8 @@ The migration set (`MigrationTables`) is, in payload-key order: `sessions`, `web
"ingressEvents": 0,
"webhookDeliveryFailures": 0,
"integrationDeliveryFailures": 0,
- "statusUpdates": 0
+ "statusUpdates": 0,
+ "automationRules": 0
},
"skippedTables": []
}
@@ -5065,7 +5067,7 @@ The migration set (`MigrationTables`) is, in payload-key order: `sessions`, `web
Rows are raw DB column shapes (e.g. `messageBatches` rows use snake_case columns: `batch_id`, `session_id`, `current_index`, `created_at`, …). **`webhooks` rows include `secret` in cleartext**, and `pluginInstances` rows carry integration secrets — treat the payload as a credential dump. On Postgres the generated `body_ts` FTS column is stripped from `messages` so archives stay dialect-neutral.
-`sessions`/`webhooks` are queried directly, so a hard DB error there yields `500`. The other 11 are queried tolerantly: a _genuinely missing_ table (an older DB that has not run the migration) exports as `[]` and its name is listed in `skippedTables`; any other error (lock, I/O, timeout) fails the export rather than reporting the table as empty. Check `skippedTables` before restoring — a skipped table is "not migrated yet", not "exported empty".
+`sessions`/`webhooks` are queried directly, so a hard DB error there yields `500`. The other 12 are queried tolerantly: a _genuinely missing_ table (an older DB that has not run the migration) exports as `[]` and its name is listed in `skippedTables`; any other error (lock, I/O, timeout) fails the export rather than reporting the table as empty. Check `skippedTables` before restoring — a skipped table is "not migrated yet", not "exported empty".
**Errors:** `401` · `403` · `500` DB error
@@ -5075,7 +5077,7 @@ Rows are raw DB column shapes (e.g. `messageBatches` rows use snake_case columns
Replace all Data DB rows with the supplied export. **Destructive and transactional (all-or-nothing).**
-> **The replace covers all 13 migration tables, not just the ones you send.** Inside the transaction every table in the migration set is emptied first and only then re-populated from the payload, so a table you omit ends up **empty**, not untouched. Always restore a payload produced by `GET /api/infra/export-data` of the same or a newer build — a hand-built body carrying only a subset silently wipes the rest.
+> **The replace covers all 14 migration tables, not just the ones you send.** Inside the transaction every table in the migration set is emptied first and only then re-populated from the payload, so a table you omit ends up **empty**, not untouched. Always restore a payload produced by `GET /api/infra/export-data` of the same or a newer build — a hand-built body carrying only a subset silently wipes the rest.
**Auth:** API key (ADMIN)
@@ -5087,7 +5089,7 @@ Replace all Data DB rows with the supplied export. **Destructive and transaction
| `tables.sessions` | `SessionRow[]` | No | Inserted first; a row whose `name` is not a safe directory name is skipped with a warning (which then rolls the whole restore back) |
| `tables.webhooks` | `WebhookRow[]` | No | Includes `secret` |
| `tables.messageBatches` | `MessageBatchRow[]` | No | snake_case columns |
-| `tables.*` (the remaining 10) | `Row[]` | No | Same keys as the export; an omitted table restores **zero** rows into an emptied table |
+| `tables.*` (the remaining 11) | `Row[]` | No | Same keys as the export; an omitted table restores **zero** rows into an emptied table |
| `stopOrphans` | boolean | No | Stop the running engines for sessions the backup does not contain, inside this request and before the replace (best-effort, time-bounded per engine). Preferred over `force` |
| `force` | boolean | No | Legacy escape hatch: proceed despite orphaned engines and leave them running until a process restart (`restartRequired: true`) |
@@ -5121,7 +5123,8 @@ Replace all Data DB rows with the supplied export. **Destructive and transaction
"ingressEvents": [],
"webhookDeliveryFailures": [],
"integrationDeliveryFailures": [],
- "statusUpdates": []
+ "statusUpdates": [],
+ "automationRules": []
},
"stopOrphans": true
}
@@ -5145,7 +5148,8 @@ Replace all Data DB rows with the supplied export. **Destructive and transaction
"ingressEvents": 0,
"webhookDeliveryFailures": 0,
"integrationDeliveryFailures": 0,
- "statusUpdates": 0
+ "statusUpdates": 0,
+ "automationRules": 0
},
"warnings": [],
"notices": [],
@@ -5162,7 +5166,7 @@ Replace all Data DB rows with the supplied export. **Destructive and transaction
Because that pre-flight runs _before_ the transaction, its teardown is not covered by the rollback. A response with `imported:false` therefore still reports the engines it really stopped, and `restartRequired` on that path means only that a teardown **failed** — a cleanly stopped orphan leaves its session row intact (restart it with `POST /sessions/{id}/start`), and an engine `force` left running was never orphaned after all, since the data that would have orphaned it was not replaced.
-Inside the transaction every migration table is emptied. `webhooks` and `sessions` are DELETEd directly, so a missing table there fails the restore; the other 11 go through a tolerant helper where a _genuinely missing_ table is skipped. Any other DELETE failure propagates to the rollback. Rows are then re-inserted, sessions first. JSON object/array fields are auto-stringified before insert, and the Postgres-form `$N` placeholders are rewritten for SQLite. Two guards return `imported:false` after a rollback: any `warnings`, and a payload that restores **zero** rows in total (a wrong/empty backup would otherwise commit a silent wipe — the response then carries `Backup contained no rows to restore; refused to replace existing data. Check the file.`). On commit the lid→phone mirror is reloaded from the restored rows.
+Inside the transaction every migration table is emptied. `webhooks` and `sessions` are DELETEd directly, so a missing table there fails the restore; 11 more go through a tolerant helper where a _genuinely missing_ table is skipped; and `automation_rules` is emptied by the `DELETE FROM sessions` cascade rather than by the helper. Any other DELETE failure propagates to the rollback. Rows are then re-inserted, sessions first. JSON object/array fields are auto-stringified before insert, and the Postgres-form `$N` placeholders are rewritten for SQLite. Two guards return `imported:false` after a rollback: any `warnings`, and a payload that restores **zero** rows in total (a wrong/empty backup would otherwise commit a silent wipe — the response then carries `Backup contained no rows to restore; refused to replace existing data. Check the file.`). On commit the lid→phone mirror is reloaded from the restored rows.
**Errors:** `401` · `403` · `409` refused, with the reason in `code` — `IMPORT_WOULD_ORPHAN_ENGINES` (live engines exist for sessions the backup does not contain; retry with `stopOrphans` or `force`), `IMPORT_ALREADY_RUNNING` (another import is running; wait for it), `IMPORT_NESTED_TRANSACTION` (another database transaction holds the connection; retry with nothing else in flight) · `500` `tables` missing/null or unrecoverable DB error
diff --git a/docs/07-api-collection.md b/docs/07-api-collection.md
index 4eb442c12..807e6fcee 100644
--- a/docs/07-api-collection.md
+++ b/docs/07-api-collection.md
@@ -1295,7 +1295,7 @@ curl "$BASE/api/infra/export-data" \
#### POST /api/infra/import-data
-Replace all Data DB rows with a prior export (destructive, all-or-nothing).
+Replace all Data DB rows with a prior export (destructive, all-or-nothing). Every one of the 14 migration tables is emptied first, so a key you omit restores **empty** rather than untouched — send a body produced by `GET /api/infra/export-data`, not a hand-built subset. All 14 keys are shown below for that reason.
```bash
curl -X POST "$BASE/api/infra/import-data" \
@@ -1304,7 +1304,9 @@ curl -X POST "$BASE/api/infra/import-data" \
-d '{
"tables": {
"sessions": [ { "id": "s1", "name": "main", "status": "READY", "phone": "15551234567", "pushName": "Me", "config": {}, "proxyUrl": null, "proxyType": null, "connectedAt": "2026-06-25T00:00:00.000Z", "lastActiveAt": "2026-06-25T00:00:00.000Z", "createdAt": "2026-06-25T00:00:00.000Z", "updatedAt": "2026-06-25T00:00:00.000Z" } ],
- "webhooks": [], "messages": [], "messageBatches": [], "templates": [], "baileysStoredMessages": []
+ "webhooks": [], "messages": [], "messageBatches": [], "templates": [], "baileysStoredMessages": [],
+ "lidMappings": [], "pluginInstances": [], "conversationMappings": [], "ingressEvents": [],
+ "webhookDeliveryFailures": [], "integrationDeliveryFailures": [], "statusUpdates": [], "automationRules": []
}
}'
```
diff --git a/docs/14-migration-guide.md b/docs/14-migration-guide.md
index 0eb6b14f7..4dc5ce935 100644
--- a/docs/14-migration-guide.md
+++ b/docs/14-migration-guide.md
@@ -142,7 +142,8 @@ curl -X POST 'http://localhost:2785/api/infra/import-data' \
"ingressEvents": [...],
"webhookDeliveryFailures": [...],
"integrationDeliveryFailures": [...],
- "statusUpdates": [...]
+ "statusUpdates": [...],
+ "automationRules": [...]
},
"counts": {
"sessions": 5,
@@ -157,7 +158,8 @@ curl -X POST 'http://localhost:2785/api/infra/import-data' \
"ingressEvents": 12,
"webhookDeliveryFailures": 0,
"integrationDeliveryFailures": 0,
- "statusUpdates": 19
+ "statusUpdates": 19,
+ "automationRules": 7
},
"skippedTables": []
}
@@ -337,6 +339,8 @@ async function migrateSqliteToPostgres(config: MigrationConfig): Promise<Migrati
'webhook_delivery_failures',
'integration_delivery_failures',
'status_updates',
+ // ON DELETE CASCADE FK to sessions, so it must follow them.
+ 'automation_rules',
];
// 4. Migrate each table