Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(infra): make data export/import lossless across all tables (#459)
Yudhi Armyndharis05d065be36ce
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8a08861a3..b280ba6ce 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Security- Infrastructure: configuration values saved from the dashboard are now rejected if they contain a line break, which could otherwise write an extra `KEY=value` line into `data/.env.generated` and inject an arbitrary environment variable on the next boot.+- Infrastructure: data export/import (the documented backup and SQLite↔PostgreSQL migration flow) is now complete. It previously exported and restored only sessions, webhooks, messages, and message batches — so a restore silently lost all message templates and stored Baileys messages (cascade-deleted with the old sessions and never re-imported) and dropped every webhook's filters, causing a filtered webhook to come back firing on all events. Templates, stored Baileys messages, and webhook filters now round-trip intact.## [0.7.1] - 2026-06-24diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.tsindex 4d08ed8a0..8dc13a32f 100644--- a/src/modules/infra/infra.controller.spec.ts+++ b/src/modules/infra/infra.controller.spec.ts@@ -34,6 +34,8 @@ import { Session, SessionStatus } from '../session/entities/session.entity';import { Webhook } from '../webhook/entities/webhook.entity';import { Message, MessageDirection, MessageStatus } from '../message/entities/message.entity';import { MessageBatch, BatchStatus } from '../message/entities/message-batch.entity';+import { Template } from '../template/entities/template.entity';+import { BaileysStoredMessage } from '../../engine/adapters/baileys-stored-message.entity';describe('InfraController access control (Vuln 2)', () => {const reflector = new Reflector();@@ -456,6 +458,103 @@ describe('InfraController.importData round-trips export-data (no silent message/});});+describe('InfraController.import/export preserves every data-DB table', () => {+ let ds: DataSource;+ let controller: InfraController;+ const cfg = { get: (key: string, def?: unknown) => (key === 'dataDatabase.type' ? 'sqlite' : def) };+ const newController = () =>+ new InfraController(cfg as never, {} as never, ds, {} as never, {} as never, {} as never, {} as never, {} as never);++ beforeEach(async () => {+ ds = new DataSource({+ type: 'sqlite',+ database: ':memory:',+ entities: [Session, Webhook, Message, MessageBatch, Template, BaileysStoredMessage],+ synchronize: true,+ });+ await ds.initialize();+ controller = newController();+ });++ afterEach(async () => {+ await ds.destroy();+ });++ const seedSession = (id: string) =>+ ds.getRepository(Session).save(+ ds.getRepository(Session).create({+ id,+ name: `session-${id}`,+ status: SessionStatus.READY,+ phone: null,+ pushName: null,+ config: {},+ proxyUrl: null,+ proxyType: null,+ connectedAt: null,+ lastActiveAt: null,+ }),+ );++ // DELETE FROM sessions cascades to templates + baileys_stored_messages (both FK ON DELETE CASCADE),+ // so an import that never re-inserts them permanently wipes both on the documented backup flow.+ it('restores templates and baileys_stored_messages instead of cascade-wiping them', async () => {+ await seedSession('s1');+ await ds+ .getRepository(Template)+ .save(ds.getRepository(Template).create({ id: 't1', sessionId: 's1', name: 'greet', body: 'Hi {{name}}' }));+ await ds.getRepository(BaileysStoredMessage).save(+ ds.getRepository(BaileysStoredMessage).create({+ id: 'bsm1',+ sessionId: 's1',+ waMessageId: 'WA1',+ serializedMessage: '{"k":"v"}',+ }),+ );++ const dump = await controller.exportData();+ const res = await controller.importData({ tables: dump.tables });++ expect(res.warnings).toEqual([]);+ expect(res.imported).toBe(true);+ expect(await ds.getRepository(Template).count()).toBe(1);+ expect(await ds.getRepository(BaileysStoredMessage).count()).toBe(1);+ expect((await ds.getRepository(Template).findOneByOrFail({ id: 't1' })).body).toBe('Hi {{name}}');+ expect((await ds.getRepository(BaileysStoredMessage).findOneByOrFail({ id: 'bsm1' })).serializedMessage).toBe(+ '{"k":"v"}',+ );+ });++ // The webhooks INSERT omitted the `filters` column, so a filtered webhook came back firing on+ // every event after a restore (over-delivery / PII fan-out).+ it('preserves webhook filters across a round-trip', async () => {+ await seedSession('s1');+ await ds.getRepository(Webhook).save(+ ds.getRepository(Webhook).create({+ id: 'w1',+ sessionId: 's1',+ url: 'https://example.com/hook',+ events: ['message'],+ secret: null,+ headers: {},+ active: true,+ retryCount: 3,+ filters: { conditions: [{ field: 'sender', operator: 'equals', value: '[email protected]' }] },+ }),+ );++ const dump = await controller.exportData();+ const res = await controller.importData({ tables: dump.tables });++ expect(res.imported).toBe(true);+ expect((await ds.getRepository(Webhook).findOneByOrFail({ id: 'w1' })).filters).toEqual({+ conditions: [{ field: 'sender', operator: 'equals', value: '[email protected]' }],+ });+ // The active flag (exported as integer 1 from SQLite) must round-trip as a real boolean.+ expect((await ds.getRepository(Webhook).findOneByOrFail({ id: 'w1' })).active).toBe(true);+ });+});+describe('InfraController.getConfig (#226)', () => {it('returns the saved config shape without echoing secrets', () => {(fs.existsSync as jest.Mock).mockReturnValue(true);diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.tsindex 5d83acfba..a5034972d 100644--- a/src/modules/infra/infra.controller.ts+++ b/src/modules/infra/infra.controller.ts@@ -94,7 +94,8 @@ interface WebhookRow {events: string | string[];secret: string | null;headers: string | Record<string, string>;- active: boolean;+ filters: string | Record<string, unknown> | null;+ active: boolean | number;retryCount: number;lastTriggeredAt: string | null;createdAt: string;@@ -137,11 +138,35 @@ interface MessageBatchRow {completed_at: string | null;}+// templates + baileys_stored_messages both FK sessions ON DELETE CASCADE, so import's+// `DELETE FROM sessions` wipes them; they must be exported and re-inserted or the documented+// backup flow loses them permanently.+interface TemplateRow {+ id: string;+ sessionId: string;+ name: string;+ body: string;+ header: string | null;+ footer: string | null;+ createdAt: string;+ updatedAt: string;+}++interface BaileysStoredMessageRow {+ id: string;+ sessionId: string;+ waMessageId: string;+ serializedMessage: string;+ createdAt: string;+}+interface MigrationTables {sessions: SessionRow[];webhooks: WebhookRow[];messages: MessageRow[];messageBatches: MessageBatchRow[];+ templates: TemplateRow[];+ baileysStoredMessages: BaileysStoredMessageRow[];}// Saved infrastructure config returned to the dashboard form for hydration. Secret@@ -607,15 +632,24 @@ export class InfraController {exportedAt: string;dataDbType: string;tables: MigrationTables;- counts: { sessions: number; webhooks: number; messages: number; messageBatches: number };+ counts: {+ sessions: number;+ webhooks: number;+ messages: number;+ messageBatches: number;+ templates: number;+ baileysStoredMessages: number;+ };}> {// Get all entities from Data DBconst sessions = await this.dataDataSource.query<SessionRow[]>('SELECT * FROM sessions');const webhooks = await this.dataDataSource.query<WebhookRow[]>('SELECT * FROM webhooks');- // Messages table may not exist yet or be empty+ // These tables may not exist yet (older DB) or be empty.let messages: MessageRow[] = [];let messageBatches: MessageBatchRow[] = [];+ let templates: TemplateRow[] = [];+ let baileysStoredMessages: BaileysStoredMessageRow[] = [];try {messages = await this.dataDataSource.query<MessageRow[]>('SELECT * FROM messages');@@ -629,6 +663,20 @@ export class InfraController {this.logger.debug('Message batches table not available for export', { error: String(error) });}+ try {+ templates = await this.dataDataSource.query<TemplateRow[]>('SELECT * FROM templates');+ } catch (error) {+ this.logger.debug('Templates table not available for export', { error: String(error) });+ }++ try {+ baileysStoredMessages = await this.dataDataSource.query<BaileysStoredMessageRow[]>(+ 'SELECT * FROM baileys_stored_messages',+ );+ } catch (error) {+ this.logger.debug('Baileys stored messages table not available for export', { error: String(error) });+ }+return {exportedAt: new Date().toISOString(),dataDbType: this.configService.get<string>('dataDatabase.type', 'sqlite'),@@ -637,12 +685,16 @@ export class InfraController {webhooks,messages,messageBatches,+ templates,+ baileysStoredMessages,},counts: {sessions: sessions.length,webhooks: webhooks.length,messages: messages.length,messageBatches: messageBatches.length,+ templates: templates.length,+ baileysStoredMessages: baileysStoredMessages.length,},};}@@ -675,7 +727,14 @@ export class InfraController {},): Promise<{imported: boolean;- counts: { sessions: number; webhooks: number; messages: number; messageBatches: number };+ counts: {+ sessions: number;+ webhooks: number;+ messages: number;+ messageBatches: number;+ templates: number;+ baileysStoredMessages: number;+ };warnings: string[];}> {const warnings: string[] = [];@@ -684,10 +743,15 @@ export class InfraController {await queryRunner.startTransaction();try {- // Clear existing data (in correct order due to foreign keys)+ // Clear existing data (in correct order due to foreign keys). templates and+ // baileys_stored_messages FK sessions ON DELETE CASCADE, so the sessions DELETE would clear+ // them too; clearing them explicitly first keeps the order correct on engines where the+ // cascade is not enforced, and is a no-op when the table doesn't exist.await queryRunner.query('DELETE FROM webhooks');await queryRunner.query('DELETE FROM messages').catch(() => {});await queryRunner.query('DELETE FROM message_batches').catch(() => {});+ await queryRunner.query('DELETE FROM templates').catch(() => {});+ await queryRunner.query('DELETE FROM baileys_stored_messages').catch(() => {});await queryRunner.query('DELETE FROM sessions');// Import sessions first@@ -726,8 +790,8 @@ export class InfraController {for (const webhook of data.tables.webhooks) {try {await queryRunner.query(- `INSERT INTO webhooks (id, "sessionId", url, events, secret, headers, active, "retryCount", "lastTriggeredAt", "createdAt", "updatedAt")- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,+ `INSERT INTO webhooks (id, "sessionId", url, events, secret, headers, filters, active, "retryCount", "lastTriggeredAt", "createdAt", "updatedAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,[webhook.id,webhook.sessionId,@@ -735,6 +799,11 @@ export class InfraController {typeof webhook.events === 'string' ? webhook.events : JSON.stringify(webhook.events || []),webhook.secret,typeof webhook.headers === 'string' ? webhook.headers : JSON.stringify(webhook.headers || {}),+ webhook.filters == null+ ? null+ : typeof webhook.filters === 'string'+ ? webhook.filters+ : JSON.stringify(webhook.filters),webhook.active,webhook.retryCount,webhook.lastTriggeredAt,@@ -827,11 +896,56 @@ export class InfraController {}}+ // Import templates (optional; FK -> sessions, restored above)+ let templatesCount = 0;+ if (data.tables.templates?.length) {+ for (const tpl of data.tables.templates) {+ try {+ await queryRunner.query(+ `INSERT INTO templates (id, "sessionId", name, body, header, footer, "createdAt", "updatedAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,+ [+ tpl.id,+ tpl.sessionId,+ tpl.name,+ tpl.body,+ tpl.header ?? null,+ tpl.footer ?? null,+ tpl.createdAt,+ tpl.updatedAt,+ ],+ );+ templatesCount++;+ } catch (err) {+ warnings.push(`Failed to import template ${tpl.id}: ${err}`);+ }+ }+ }++ // Import baileys stored messages (optional; FK -> sessions, restored above)+ let baileysStoredMessagesCount = 0;+ if (data.tables.baileysStoredMessages?.length) {+ for (const bsm of data.tables.baileysStoredMessages) {+ try {+ await queryRunner.query(+ `INSERT INTO baileys_stored_messages (id, "sessionId", "waMessageId", "serializedMessage", "createdAt")+ VALUES ($1, $2, $3, $4, $5)`,+ [bsm.id, bsm.sessionId, bsm.waMessageId, bsm.serializedMessage, bsm.createdAt],+ );+ baileysStoredMessagesCount++;+ } catch (err) {+ warnings.push(`Failed to import baileys stored message ${bsm.id}: ${err}`);+ }+ }+ }+const counts = {sessions: sessionsCount,webhooks: webhooksCount,messages: messagesCount,messageBatches: messageBatchesCount,+ templates: templatesCount,+ baileysStoredMessages: baileysStoredMessagesCount,};// "Replace all data" must be all-or-nothing: the import already DELETEd every row, so if any