Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(infra): accept the export envelope on import-data

Yudhi Armyndharis443d54f57b6e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index debd2a288..68d524539 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,7 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- The dashboard bundled all thirteen locales into one 476 KB chunk the page preloaded, so every visitor downloaded twelve languages to read one; each is now fetched on demand.
- `check:sdk-routes` scanned the JavaScript client for backtick-delimited paths only, while its PHP and Python rules already accepted every quote style, so the nine routes that client writes as single-quoted strings were never compared to the contract — `/api/health/ready` among them, which is also the container healthcheck and Kubernetes readiness path. Renaming one of those server-side passed every gate and the JS suite, and the published client would have 404'd with CI green.
- The JavaScript, Python, Go and Java SDKs omitted `contact`, `call` and `ephemeralDuration` from their chat-history message type, so a typed client had to cast to read three fields the endpoint returns; all four now mirror the engine payload.
-- `POST /api/infra/import-data` bound its body to an inline type, which erases at runtime, so on the replace-all restore the global ValidationPipe's `whitelist` and `forbidNonWhitelisted` never ran: a body carrying no `tables` failed as a 500 from inside the import, and a misspelled key was accepted in silence. It now takes a DTO — a missing `tables` answers 400 naming the field, an unknown key is refused, and `force`/`stopOrphans` accept only a real boolean or an exact `'true'`/`'false'`, so an ambiguous spelling cannot open the orphan-engine escape.
+- `POST /api/infra/import-data` bound its body to an inline type, which erases at runtime, so on the replace-all restore the global ValidationPipe's `whitelist` and `forbidNonWhitelisted` never ran: a body carrying no `tables` failed as a 500 from inside the import, and a misspelled key was accepted in silence. It now takes a DTO — a missing `tables` answers 400 instead, naming the field outside production, where field-level detail is suppressed unless `VALIDATION_ERROR_DETAIL=true`; an unknown key is refused, and `force`/`stopOrphans` accept only a real boolean or an exact `'true'`/`'false'`, so an ambiguous spelling cannot open the orphan-engine escape. The export file still posts back verbatim: the five metadata fields it wraps `tables` in are accepted and ignored, and a spec probes every field the export publishes so a new one cannot start failing the restore.
- The engine parity gate took an adapter file's engine from its filename prefix and credited the rest to whatsapp-web.js, so a `501` added to one of the five unprefixed modules would be blamed on the wrong engine — and the invariant would then demand that the engine which really refuses be marked `supported`. Those files are now attributed explicitly, and one that is neither prefixed nor attributed fails the spec by name.
- Replying with an attachment in the dashboard composer silently dropped the quote: the media branch never carried the quoted id, the optimistic bubble's metadata took the same either/or, and the reply banner was cleared regardless — so it looked exactly like a quoted reply had been sent. Both payloads now carry the quote, and the two builders moved to a tested utility module.
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 302d2859d..538c1fecd 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -5080,7 +5080,7 @@ Unlike the other list routes this one is **not** a bare array: `data` is the pag
Admin-facing operations: infrastructure status & config, the data/storage migration tooling, plugin lifecycle, and the optional MCP transport. Almost every route is **API key (ADMIN)**; the two exceptions are the public `GET /api/infra/health` and the `POST /mcp` JSON-RPC endpoint (see end of section).
-> Note on the infra/MCP request bodies: the `POST /api/infra/import-data` body and the entire `POST /mcp` envelope (mounted as a raw Express handler, outside the Nest pipe chain) are **plain TS interfaces, not class-validator DTOs** — the global `whitelist`/`forbidNonWhitelisted` ValidationPipe does **not** run on them. Unknown fields pass through silently and no type/constraint checks happen, except the few field-level guards noted per endpoint. The other infra bodies — `SaveConfigDto` (`PUT /api/infra/config`), `RestartDto` (`POST /api/infra/restart`), `ImportStorageDto` (`POST /api/infra/storage/import`) — and the plugin DTOs (`InstallFromUrlDto`, `PluginConfigDto`, `PluginSessionsDto`) _are_ class-validated and reject unknown fields with `400`.
+> Note on the MCP request body: the entire `POST /mcp` envelope (mounted as a raw Express handler, outside the Nest pipe chain) is a **plain TS interface, not a class-validator DTO** — the global `whitelist`/`forbidNonWhitelisted` ValidationPipe does **not** run on it. Unknown fields pass through silently and no type/constraint checks happen, except the few field-level guards noted per endpoint. The infra bodies — `ImportDataDto` (`POST /api/infra/import-data`), `SaveConfigDto` (`PUT /api/infra/config`), `RestartDto` (`POST /api/infra/restart`), `ImportStorageDto` (`POST /api/infra/storage/import`) — and the plugin DTOs (`InstallFromUrlDto`, `PluginConfigDto`, `PluginSessionsDto`) _are_ class-validated and reject unknown fields with `400`. `ImportDataDto` additionally accepts, and ignores, the five metadata fields the export wraps `tables` in, so the backup file posts back unmodified.
---
@@ -5432,11 +5432,11 @@ Replace all Data DB rows with the supplied export. **Destructive and transaction
**Auth:** API key (ADMIN)
-**Request body** — inline `{ tables: Partial<MigrationTables>; force?: boolean; stopOrphans?: boolean }` (plain interface, not class-validated)
+**Request body** — `ImportDataDto`. Post the whole export file: alongside `tables`, `force` and `stopOrphans`, the DTO accepts and ignores the export's `exportedAt`, `dataDbType`, `counts`, `skippedTables` and `omittedInlineMedia`. Any other property is rejected with `400`.
| Field | Type | Required | Description |
| ----------------------------- | ------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `tables` | object | Yes | Container of per-table row arrays, keyed exactly as the export's `tables`. Accessing `data.tables` directly means a missing/null value throws `500` |
+| `tables` | object | Yes | Container of per-table row arrays, keyed exactly as the export's `tables`. Absent, `null` or not an object is rejected `400` before the restore runs |
| `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 |
@@ -5519,7 +5519,7 @@ Because that pre-flight runs _before_ the transaction, its teardown is not cover
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
+**Errors:** `400` `tables` absent/not an object, a flag spelled as anything but a boolean or exact `true`/`false`, or a property the route does not accept — nothing is written, and field-level detail is suppressed in production unless `VALIDATION_ERROR_DETAIL=true` · `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/openapi.json b/openapi.json
index e0e982596..2c9ca6877 100644
--- a/openapi.json
+++ b/openapi.json
@@ -3988,6 +3988,9 @@
}
}
},
+ "400": {
+ "description": "Body rejected before the restore ran: `tables` absent or not an object, a flag spelled as anything but a boolean or exact `true`/`false`, or a property this route does not accept. Nothing was written. Field-level detail is suppressed in production unless VALIDATION_ERROR_DETAIL=true."
+ },
"409": {
"description": "Refused, with the reason in `code`. IMPORT_ALREADY_RUNNING: another import is running — wait for it. IMPORT_NESTED_TRANSACTION: another database transaction holds this connection, so a restore could not be made durable — retry with nothing else in flight. IMPORT_WOULD_ORPHAN_ENGINES: live engines exist for sessions the backup would remove — retry with stopOrphans=true to stop them in-request, or force=true to proceed and restart after. Only the last of these is retryable with stopOrphans; the others leave nothing to decide"
}
@@ -12610,6 +12613,35 @@
"stopOrphans": {
"type": "boolean",
"description": "Stop the running engines for sessions the backup does not contain, inside this request and before the replace runs. Supersedes force for the orphan case: with stopOrphans the engines no longer need a process restart to reconcile, so restartRequired stays false on the success path."
+ },
+ "exportedAt": {
+ "type": "string",
+ "description": "Ignored. Present so the export file posts back unmodified."
+ },
+ "dataDbType": {
+ "type": "string",
+ "description": "Ignored. Present so the export file posts back unmodified."
+ },
+ "counts": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "number"
+ },
+ "description": "Ignored. Present so the export file posts back unmodified."
+ },
+ "skippedTables": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Ignored. Present so the export file posts back unmodified."
+ },
+ "omittedInlineMedia": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "number"
+ },
+ "description": "Ignored. Present so the export file posts back unmodified."
}
},
"required": [
diff --git a/src/modules/infra/dto/import-data.dto.spec.ts b/src/modules/infra/dto/import-data.dto.spec.ts
index d9bf9b170..ce31294e5 100644
--- a/src/modules/infra/dto/import-data.dto.spec.ts
+++ b/src/modules/infra/dto/import-data.dto.spec.ts
@@ -1,4 +1,6 @@
import 'reflect-metadata';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';
import { ImportDataDto } from './import-data.dto';
@@ -21,6 +23,26 @@ function fullTables(): Record<string, unknown[]> {
return Object.fromEntries(TABLE_IMPORTERS.map(importer => [importer.key, []]));
}
+/** Top-level property names of a published schema, read from the committed contract. */
+function publishedProperties(schema: string): string[] {
+ const snapshot = JSON.parse(readFileSync(join(__dirname, '..', '..', '..', '..', 'openapi.json'), 'utf8')) as {
+ components: { schemas: Record<string, { properties?: Record<string, unknown> }> };
+ };
+ return Object.keys(snapshot.components.schemas[schema]?.properties ?? {});
+}
+
+/** The export file exactly as GET /api/infra/export-data returns it, tables filled in. */
+function exportEnvelope(): Record<string, unknown> {
+ return {
+ exportedAt: '2026-08-12T00:00:00.000Z',
+ dataDbType: 'sqlite',
+ tables: { ...fullTables(), sessions: [{ id: 's1', name: 'main' }] },
+ counts: { sessions: 1 },
+ skippedTables: [],
+ omittedInlineMedia: { messages: 0, messageBatches: 0 },
+ };
+}
+
describe('ImportDataDto', () => {
it('rejects a body with no tables, naming the field', async () => {
const { errors } = await run({ force: true });
@@ -34,6 +56,37 @@ describe('ImportDataDto', () => {
expect(errors.map(e => e.property)).toEqual(['stopOrphan']);
});
+ it('accepts the export file posted back verbatim', async () => {
+ // docs/14 tells the operator to post the whole backup (`-d @data-backup.json`), and the export
+ // wraps `tables` in five metadata fields. When this DTO named only `tables`, forbidNonWhitelisted
+ // rejected all five and the documented restore answered 400 — a bare "Bad Request" in production,
+ // where field-level detail is suppressed. Nothing caught it: the round-trip specs call
+ // controller.importData({ tables }) directly and never reach the pipe.
+ const { instance, errors } = await run(exportEnvelope());
+ expect(errors).toEqual([]);
+ expect(Object.keys(instance.tables as object)).toHaveLength(TABLE_IMPORTERS.length);
+ });
+
+ it('accepts every top-level field the export publishes', async () => {
+ // The real gate: bind the accepted set to the export contract instead of trusting that whoever
+ // adds a field to the export remembers this file. A new export field fails here, naming itself,
+ // rather than 400ing an operator's restore.
+ //
+ // It probes ACCEPTANCE, one field at a time, rather than comparing the two published schemas.
+ // Publication and acceptance are different mechanisms — @ApiPropertyOptional puts a field in the
+ // contract, @Allow is what makes forbidNonWhitelisted admit it — so a field carrying only the
+ // former would pass a schema-to-schema comparison while still 400ing the restore.
+ const exported = publishedProperties('InfraExportDataResponseDto');
+ expect(exported.length).toBeGreaterThanOrEqual(6); // non-vacuous: the contract was really read
+ const rejected: string[] = [];
+ for (const field of exported) {
+ if (field === 'tables') continue; // carries its own constraints, covered above
+ const { errors } = await run({ tables: fullTables(), [field]: exportEnvelope()[field] });
+ if (errors.length) rejected.push(field);
+ }
+ expect(rejected).toEqual([]);
+ });
+
it('accepts a valid body and leaves every table array intact', async () => {
// Load-bearing: whitelist strips undecorated properties from the object it validates, and every
// table key omitted from a restore is written EMPTY. If validation reached inside `tables`, a
diff --git a/src/modules/infra/dto/import-data.dto.ts b/src/modules/infra/dto/import-data.dto.ts
index c49d0d0e7..a333603a5 100644
--- a/src/modules/infra/dto/import-data.dto.ts
+++ b/src/modules/infra/dto/import-data.dto.ts
@@ -1,5 +1,5 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
-import { IsBoolean, IsObject, IsOptional } from 'class-validator';
+import { Allow, IsBoolean, IsObject, IsOptional } from 'class-validator';
import { ToStrictBoolean } from '../../../common/utils/strict-boolean';
import type { MigrationTables } from '../migration-tables.types';
import { TABLE_IMPORTERS } from '../table-importers';
@@ -30,6 +30,14 @@ const TABLE_PROPERTIES: Record<string, { type: 'array' }> = Object.fromEntries(
* a caller who spelled the opposite. @ToStrictBoolean accepts only a real boolean or an exact
* 'true'/'false' and leaves anything else to be refused. An absent flag stays absent, so the default
* path is still the visible 409 IMPORT_WOULD_ORPHAN_ENGINES.
+ *
+ * The body IS the export file: `docs/14` tells the operator to post it whole, and the export wraps
+ * `tables` in five metadata fields. They are declared with @Allow — accepted, never read — because
+ * `forbidNonWhitelisted` rejects any property the class does not name, and rejecting the product's
+ * own backup would break the restore this route exists for. They carry no constraints on purpose: a
+ * restore must not fail over the shape of a field it ignores, including one written by an older
+ * release. `import-data.dto.spec.ts` binds this list to the export contract, so a field added to the
+ * export cannot silently start failing the import again.
*/
export class ImportDataDto {
@ApiProperty({
@@ -58,4 +66,43 @@ export class ImportDataDto {
@IsOptional()
@IsBoolean()
stopOrphans?: boolean;
+
+ // ---- Export-envelope metadata: accepted so the backup posts back verbatim, never read. ----
+
+ // Each carries an explicit published `type` matching what the export sends. The declared TS type is
+ // `unknown` because the restore never reads them, but an untyped @ApiPropertyOptional over `unknown`
+ // publishes `type: object`, which for `exportedAt` breaks the contract invariant that a timestamp
+ // property is never a bare object (`openapi-contract.spec.ts`).
+
+ @ApiPropertyOptional({ type: 'string', description: 'Ignored. Present so the export file posts back unmodified.' })
+ @Allow()
+ exportedAt?: unknown;
+
+ @ApiPropertyOptional({ type: 'string', description: 'Ignored. Present so the export file posts back unmodified.' })
+ @Allow()
+ dataDbType?: unknown;
+
+ @ApiPropertyOptional({
+ type: 'object',
+ additionalProperties: { type: 'number' },
+ description: 'Ignored. Present so the export file posts back unmodified.',
+ })
+ @Allow()
+ counts?: unknown;
+
+ @ApiPropertyOptional({
+ type: 'array',
+ items: { type: 'string' },
+ description: 'Ignored. Present so the export file posts back unmodified.',
+ })
+ @Allow()
+ skippedTables?: unknown;
+
+ @ApiPropertyOptional({
+ type: 'object',
+ additionalProperties: { type: 'number' },
+ description: 'Ignored. Present so the export file posts back unmodified.',
+ })
+ @Allow()
+ omittedInlineMedia?: unknown;
}
diff --git a/src/modules/infra/infra-data.controller.ts b/src/modules/infra/infra-data.controller.ts
index ed1f7a05a..f6877a0e6 100644
--- a/src/modules/infra/infra-data.controller.ts
+++ b/src/modules/infra/infra-data.controller.ts
@@ -479,6 +479,11 @@ export class InfraDataController {
// parameter type — it publishes `{"type": "string"}` for the whole body.
@ApiBody({ description: 'Exported data from export-data endpoint', type: ImportDataDto })
@ApiResponse({ status: 200, description: 'Data imported successfully', type: InfraImportDataResponseDto })
+ @ApiResponse({
+ status: 400,
+ description:
+ 'Body rejected before the restore ran: `tables` absent or not an object, a flag spelled as anything but a boolean or exact `true`/`false`, or a property this route does not accept. Nothing was written. Field-level detail is suppressed in production unless VALIDATION_ERROR_DETAIL=true.',
+ })
@ApiResponse({
status: 409,
description: