Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(infra): correct import-data column mapping; make a partial restore non-destructive (#321)
Yudhi Armyndharisfa9b2b0ebba3
diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.tsindex 4dcadb330..d27ecdac3 100644--- a/src/modules/infra/infra.controller.spec.ts+++ b/src/modules/infra/infra.controller.spec.ts@@ -20,9 +20,14 @@ jest.mock('fs', () => {};});+import { DataSource } from 'typeorm';import { InfraController } from './infra.controller';import { REQUIRED_ROLE_KEY } from '../auth/decorators/auth.decorators';import { ApiKeyRole } from '../auth/entities/api-key.entity';+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';describe('InfraController access control (Vuln 2)', () => {const reflector = new Reflector();@@ -197,6 +202,144 @@ describe('InfraController.saveConfig env-name correctness and merge (#226)', ()});});+describe('InfraController.importData round-trips export-data (no silent message/batch loss)', () => {+ let ds: DataSource;+ let controller: InfraController;+ // exportData only reads dataDatabase.type off the config; everything else is unused here.+ 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],+ 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,+ }),+ );++ it('restores messages and message_batches faithfully — not silently to zero', async () => {+ await seedSession('s1');+ await ds.getRepository(Message).save(+ ds.getRepository(Message).create({+ id: 'm1',+ sessionId: 's1',+ waMessageId: 'WA1',+ chatId: '[email protected]',+ from: '[email protected]',+ to: '[email protected]',+ body: 'hello',+ type: 'text',+ direction: MessageDirection.INCOMING,+ timestamp: 1700000000,+ metadata: { ack: 2 },+ status: MessageStatus.DELIVERED,+ }),+ );+ await ds.getRepository(MessageBatch).save(+ ds.getRepository(MessageBatch).create({+ id: 'b1',+ batchId: 'BATCH1',+ sessionId: 's1',+ status: BatchStatus.COMPLETED,+ messages: [{ chatId: 'c1', type: 'text', content: {} }],+ options: null as never,+ progress: null as never,+ results: null as never,+ currentIndex: 0,+ startedAt: null,+ completedAt: null,+ }),+ );++ const dump = await controller.exportData();+ expect(dump.counts.messages).toBe(1);+ expect(dump.counts.messageBatches).toBe(1);++ const res = await controller.importData({ tables: dump.tables });++ // The whole point of the bug: a valid backup must restore with no warnings and imported:true.+ expect(res.warnings).toEqual([]);+ expect(res.imported).toBe(true);+ expect(res.counts.messages).toBe(1);+ expect(res.counts.messageBatches).toBe(1);++ // ...and the rows must actually be present after the DELETE+reinsert, with fields intact.+ expect(await ds.getRepository(Message).count()).toBe(1);+ expect(await ds.getRepository(MessageBatch).count()).toBe(1);+ const m = await ds.getRepository(Message).findOneByOrFail({ id: 'm1' });+ expect(m.body).toBe('hello');+ expect(m.waMessageId).toBe('WA1');+ expect(m.from).toBe('[email protected]');+ expect(m.to).toBe('[email protected]');+ expect(m.metadata).toEqual({ ack: 2 });+ const b = await ds.getRepository(MessageBatch).findOneByOrFail({ id: 'b1' });+ expect(b.batchId).toBe('BATCH1');+ expect(b.status).toBe(BatchStatus.COMPLETED);+ });++ it('rolls back and reports imported:false when a row fails — existing data is preserved', async () => {+ // Pre-existing data that must survive a failed import.+ await seedSession('s1');+ await ds.getRepository(Message).save(+ ds.getRepository(Message).create({+ id: 'm1',+ sessionId: 's1',+ waMessageId: 'WA1',+ chatId: 'c1',+ from: 'a',+ to: 'b',+ body: 'keep me',+ type: 'text',+ direction: MessageDirection.INCOMING,+ status: MessageStatus.DELIVERED,+ }),+ );++ // A backup whose message row is malformed (missing the non-null from/to) must fail the whole import.+ const res = await controller.importData({+ tables: {+ sessions: [{ id: 's2', name: 'imported', status: 'ready' }] as never,+ messages: [+ { id: 'mX', sessionId: 's2', chatId: 'c', type: 'text', direction: 'incoming', status: 'sent' },+ ] as never,+ },+ });++ expect(res.imported).toBe(false);+ expect(res.warnings.length).toBeGreaterThan(0);++ // The destructive DELETE must have been rolled back — original data intact, nothing from the bad import.+ expect(await ds.getRepository(Message).count()).toBe(1);+ expect((await ds.getRepository(Message).findOneByOrFail({ id: 'm1' })).body).toBe('keep me');+ expect(await ds.getRepository(Session).findOneBy({ id: 's2' })).toBeNull();+ });+});+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 179f8cfff..24ab07863 100644--- a/src/modules/infra/infra.controller.ts+++ b/src/modules/infra/infra.controller.ts@@ -98,34 +98,40 @@ interface WebhookRow {updatedAt: string;}+// Shapes mirror the REAL table columns as returned by `SELECT *` (export-data), not the+// camelCase TypeORM entity properties. `messages` columns are the property names; `message_batches`+// columns are snake_case (the entity maps them via `name:`). Keeping these accurate is what keeps+// the import column lists below from drifting back into "no such column" failures.interface MessageRow {id: string;sessionId: string;- messageId: string;+ waMessageId: string | null;chatId: string;- direction: string;+ from: string;+ to: string;+ body: string | null;type: string;- content: string | Record<string, unknown>;+ direction: string;+ timestamp: number | string | null;+ metadata: string | Record<string, unknown> | null;status: string;- metadata: string | Record<string, unknown>;createdAt: string;- updatedAt: string;}interface MessageBatchRow {id: string;- batchId: string;- sessionId: string;+ batch_id: string;+ session_id: string;status: string;messages: string | unknown[];- options: string | Record<string, unknown>;- progress: string | Record<string, unknown>;- results: string | unknown[];- currentIndex: number;- createdAt: string;- updatedAt: string;- startedAt: string | null;- completedAt: string | null;+ options: string | Record<string, unknown> | null;+ progress: string | Record<string, unknown> | null;+ results: string | unknown[] | null;+ current_index: number;+ created_at: string;+ updated_at: string;+ started_at: string | null;+ completed_at: string | null;}interface MigrationTables {@@ -723,20 +729,26 @@ export class InfraController {for (const msg of data.tables.messages) {try {await queryRunner.query(- `INSERT INTO messages (id, "sessionId", "messageId", "chatId", direction, type, content, status, metadata, "createdAt", "updatedAt")- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,+ `INSERT INTO messages (id, "sessionId", "waMessageId", "chatId", "from", "to", body, type, direction, "timestamp", metadata, status, "createdAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)`,[msg.id,msg.sessionId,- msg.messageId,+ msg.waMessageId ?? null,msg.chatId,- msg.direction,+ msg.from,+ msg.to,+ msg.body ?? null,msg.type,- typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content || {}),+ msg.direction,+ msg.timestamp ?? null,+ msg.metadata == null+ ? null+ : typeof msg.metadata === 'string'+ ? msg.metadata+ : JSON.stringify(msg.metadata),msg.status,- typeof msg.metadata === 'string' ? msg.metadata : JSON.stringify(msg.metadata || {}),msg.createdAt,- msg.updatedAt,],);messagesCount++;@@ -752,22 +764,34 @@ export class InfraController {for (const batch of data.tables.messageBatches) {try {await queryRunner.query(- `INSERT INTO message_batches (id, "batchId", "sessionId", status, messages, options, progress, results, "currentIndex", "createdAt", "updatedAt", "startedAt", "completedAt")+ `INSERT INTO message_batches (id, batch_id, session_id, status, messages, options, progress, results, current_index, created_at, updated_at, started_at, completed_at)VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)`,[batch.id,- batch.batchId,- batch.sessionId,+ batch.batch_id,+ batch.session_id,batch.status,- typeof batch.messages === 'string' ? batch.messages : JSON.stringify(batch.messages || []),- typeof batch.options === 'string' ? batch.options : JSON.stringify(batch.options || {}),- typeof batch.progress === 'string' ? batch.progress : JSON.stringify(batch.progress || {}),- typeof batch.results === 'string' ? batch.results : JSON.stringify(batch.results || []),- batch.currentIndex,- batch.createdAt,- batch.updatedAt,- batch.startedAt,- batch.completedAt,+ typeof batch.messages === 'string' ? batch.messages : JSON.stringify(batch.messages ?? []),+ batch.options == null+ ? null+ : typeof batch.options === 'string'+ ? batch.options+ : JSON.stringify(batch.options),+ batch.progress == null+ ? null+ : typeof batch.progress === 'string'+ ? batch.progress+ : JSON.stringify(batch.progress),+ batch.results == null+ ? null+ : typeof batch.results === 'string'+ ? batch.results+ : JSON.stringify(batch.results),+ batch.current_index,+ batch.created_at,+ batch.updated_at,+ batch.started_at,+ batch.completed_at,],);messageBatchesCount++;@@ -777,18 +801,24 @@ export class InfraController {}}- await queryRunner.commitTransaction();-- return {- imported: true,- counts: {- sessions: sessionsCount,- webhooks: webhooksCount,- messages: messagesCount,- messageBatches: messageBatchesCount,- },- warnings,+ const counts = {+ sessions: sessionsCount,+ webhooks: webhooksCount,+ messages: messagesCount,+ messageBatches: messageBatchesCount,};++ // "Replace all data" must be all-or-nothing: the import already DELETEd every row, so if any+ // INSERT failed we must roll back (restoring the pre-import data) rather than commit a+ // half-wiped DB and report success. A partial restore reported as imported:true was how+ // message history could silently vanish on a SQLite->Postgres migration.+ if (warnings.length > 0) {+ await queryRunner.rollbackTransaction();+ return { imported: false, counts, warnings };+ }++ await queryRunner.commitTransaction();+ return { imported: true, counts, warnings };} catch (error) {await queryRunner.rollbackTransaction();throw error;