Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
refactor(infra): move the migration types and table importers out of the data controller
Yudhi Armyndharis9d911dd3d559
diff --git a/src/modules/infra/infra-data.controller.ts b/src/modules/infra/infra-data.controller.tsindex c8d853acd..0f69fbdb8 100644--- a/src/modules/infra/infra-data.controller.ts+++ b/src/modules/infra/infra-data.controller.ts@@ -5,560 +5,30 @@ import { DataSource } from 'typeorm';import { InjectDataSource } from '@nestjs/typeorm';import { RequireRole, RequireUnscopedKey } from '../auth/decorators/auth.decorators';import { ApiKeyRole } from '../auth/entities/api-key.entity';-import { isSafeSessionName } from '../../common/utils/path-safety';import { createLogger } from '../../common/services/logger.service';import { isMissingTableError } from '../../common/utils/db-errors';import { AuditService } from '../audit/audit.service';import { AuditAction } from '../audit/entities/audit-log.entity';import { SessionService } from '../session/session.service';import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';--// Database migration types for export/import-interface SessionRow {- id: string;- name: string;- status: string;- phone: string | null;- pushName: string | null;- config: string | Record<string, unknown>;- proxyUrl: string | null;- proxyType: string | null;- connectedAt: string | null;- lastActiveAt: string | null;- createdAt: string;- updatedAt: string;-}--interface WebhookRow {- id: string;- sessionId: string;- url: string;- events: string | string[];- secret: string | null;- headers: string | Record<string, string>;- filters: string | Record<string, unknown> | null;- active: boolean | number;- retryCount: number;- lastTriggeredAt: string | null;- createdAt: string;- 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;- waMessageId: string | null;- chatId: string;- chatName: string | null;- /** Group participant JID (nullable; added to messages after chatName — keep the import list in sync). */- author: string | null;- from: string;- to: string;- body: string | null;- type: string;- direction: string;- timestamp: number | string | null;- metadata: string | Record<string, unknown> | null;- status: string;- createdAt: string;- /**- * Postgres-only STORED generated tsvector (FTS). Present in `SELECT *` rows read from a Postgres- * source (and in backups made before it was stripped) but never a real payload column: export drops- * it, and the import's explicit column list ignores it. Declared so both directions type-check.- */- body_ts?: unknown;-}--interface MessageBatchRow {- id: string;- batch_id: string;- session_id: string;- status: string;- messages: string | unknown[];- 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;-}--// 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;-}--// The persisted lid->phone resolution cache. Not a FK to sessions (provenance only), so the import's-// `DELETE FROM sessions` never clears it — it must be exported + re-inserted explicitly or a-// backup→restore into a fresh DB loses the whole cache (it self-heals via re-lookup, but lossily).-interface LidMappingRow {- lid: string;- phone: string | null;- sessionId: string | null;- updatedAt: string;-}--interface PluginInstanceRow {- id: string;- pluginId: string;- instanceId: string;- sessionScope: string | null;- secret: string;- verifyToken: string | null;- config: string | Record<string, unknown> | null;- enabled: boolean | number;- createdAt: string;- updatedAt: string;-}--interface ConversationMappingRow {- id: string;- sessionId: string;- chatId: string;- pluginId: string;- instanceId: string;- providerConversationId: string;- handoverState: string;- metadata: string | Record<string, unknown> | null;- updatedAt: string;-}--interface IngressEventRow {- id: string;- instanceId: string;- pluginId: string;- providerDeliveryId: string;- route: string;- // Retired to NULL once the dispatch outcome is recorded; only 'pending' rows still carry one.- payload: string | Record<string, unknown> | null;- payloadHash?: string | null;- // Dispatch lifecycle (the AddIngressEventDispatchState migration). A restored 'pending' row must- // keep these or the reconciler never replays it while the dedup row still blocks the provider's- // retry. Optional because backups exported before the columns existed don't carry them.- dispatchState?: 'pending' | 'dispatched' | 'failed' | null;- dispatchAttempts?: number;- lastDispatchAt?: string | null;- sessionId: string | null;- createdAt: string;-}--interface WebhookDeliveryFailureRow {- id: string;- webhookId: string;- sessionId: string;- event: string;- url: string;- idempotencyKey: string | null;- deliveryId: string | null;- attempts: number;- lastStatusCode: number | null;- lastError: string;- createdAt: string;-}--interface IntegrationDeliveryFailureRow {- id: string;- direction: string;- pluginId: string;- instanceId: string;- sessionId: string | null;- deliveryId: string | null;- attempts: number;- lastError: string;- payload: string | Record<string, unknown> | null;- redriven: boolean | number;- createdAt: string;-}--// status_updates has no FK to sessions (plain columns), so the import's `DELETE FROM sessions` never-// clears it — it must be exported + re-inserted explicitly like lid_mappings. postedAt/expiresAt are-// bigint epoch-ms: raw queries bypass the entity transformer, so Postgres returns them as strings.-interface StatusUpdateRow {- id: string;- sessionId: string;- contactJid: string;- contactName: string | null;- contactPushName: string | null;- waStatusId: string;- type: string;- caption: string | null;- mediaPath: string | null;- mediaMimetype: string | null;- mediaOmitted: boolean | number;- omitReason: string | null;- backgroundColor: string | null;- font: number | null;- postedAt: number | string;- expiresAt: number | string;-}--interface MigrationTables {- sessions: SessionRow[];- webhooks: WebhookRow[];- messages: MessageRow[];- messageBatches: MessageBatchRow[];- templates: TemplateRow[];- baileysStoredMessages: BaileysStoredMessageRow[];- lidMappings: LidMappingRow[];- pluginInstances: PluginInstanceRow[];- conversationMappings: ConversationMappingRow[];- ingressEvents: IngressEventRow[];- webhookDeliveryFailures: WebhookDeliveryFailureRow[];- integrationDeliveryFailures: IntegrationDeliveryFailureRow[];- statusUpdates: StatusUpdateRow[];-}--type TableCounts = { [K in keyof MigrationTables]: number };--// A per-table restore step for importData: which backup key to read, the exact INSERT text (kept in-// Postgres' `$N` placeholder form; the insert() helper rewrites it for SQLite), the param mapping,-// and an optional per-row skip guard. key/label/id also drive the counts object and the failure-// warnings, so the import loop below stays table-agnostic.-interface TableImporter<K extends keyof MigrationTables = keyof MigrationTables> {- key: K;- /** Singular noun used in the per-row failure warning: `Failed to import <label> <id>: <err>`. */- label: string;- /** Full INSERT ... VALUES ($1, ...) text, verbatim per table. */- sql: string;- /** The id interpolated into the failure warning (lid_mappings rows key on lid, not id). */- id: (row: MigrationTables[K][number]) => string;- map: (row: MigrationTables[K][number]) => unknown[];- /** Per-row veto: returns the warning to record (the row is skipped) or null to import the row. */- skip?: (row: MigrationTables[K][number]) => string | null;-}--// Registers one concrete descriptor into the union-keyed TABLE_IMPORTERS array. The return type-// widens the row-specific id/map/skip to the union of all row types; sound because the import loop-// only ever feeds a descriptor rows read from data.tables[its own key].-function defineTableImporter<K extends keyof MigrationTables>(importer: TableImporter<K>): TableImporter {- return importer;-}--// Restore order is FK order: sessions first (webhooks/messages/templates/etc. reference it), the-// standalone cache/DLQ tables after. The per-block comments from the former inline import blocks-// live on their descriptor entries.-const TABLE_IMPORTERS: TableImporter[] = [- // Import sessions first- defineTableImporter({- key: 'sessions',- label: 'session',- sql: `INSERT INTO sessions (id, name, status, phone, "pushName", config, "proxyUrl", "proxyType", "connectedAt", "lastActiveAt", "createdAt", "updatedAt")- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,- id: (session: SessionRow) => session.id,- // A session name becomes the engine auth-directory key, so an unvalidated imported name (this- // path bypasses CreateSessionDto) could traverse the filesystem. Skip + warn instead of- // throwing, so one bad row doesn't 500 the whole restore.- skip: (session: SessionRow) => {- if (isSafeSessionName(session.name)) return null;- return `Skipped session ${session.id}: unsafe name ${JSON.stringify(session.name)}`;- },- map: (session: SessionRow) => [- session.id,- session.name,- session.status,- session.phone,- session.pushName,- typeof session.config === 'string' ? session.config : JSON.stringify(session.config || {}),- session.proxyUrl,- session.proxyType,- session.connectedAt,- session.lastActiveAt,- session.createdAt,- session.updatedAt,- ],- }),-- // Import webhooks- defineTableImporter({- key: 'webhooks',- label: 'webhook',- sql: `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)`,- id: (webhook: WebhookRow) => webhook.id,- map: (webhook: WebhookRow) => [- webhook.id,- webhook.sessionId,- webhook.url,- 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,- webhook.createdAt,- webhook.updatedAt,- ],- }),-- // Import messages (optional)- defineTableImporter({- key: 'messages',- label: 'message',- sql: `INSERT INTO messages (id, "sessionId", "waMessageId", "chatId", "chatName", author, "from", "to", body, type, direction, "timestamp", metadata, status, "createdAt")- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)`,- id: (msg: MessageRow) => msg.id,- map: (msg: MessageRow) => [- msg.id,- msg.sessionId,- msg.waMessageId ?? null,- msg.chatId,- msg.chatName ?? null,- // Rows exported before the author column existed simply restore to NULL (legacy- // behavior) instead of failing the whole import on an unknown key.- msg.author ?? null,- msg.from,- msg.to,- msg.body ?? null,- msg.type,- msg.direction,- msg.timestamp ?? null,- msg.metadata == null ? null : typeof msg.metadata === 'string' ? msg.metadata : JSON.stringify(msg.metadata),- msg.status,- msg.createdAt,- ],- }),-- // Import message batches (optional)- defineTableImporter({- key: 'messageBatches',- label: 'message batch',- sql: `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)`,- id: (batch: MessageBatchRow) => batch.id,- map: (batch: MessageBatchRow) => [- batch.id,- batch.batch_id,- batch.session_id,- batch.status,- 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,- ],- }),-- // Import templates (optional; FK -> sessions, restored above)- defineTableImporter({- key: 'templates',- label: 'template',- sql: `INSERT INTO templates (id, "sessionId", name, body, header, footer, "createdAt", "updatedAt")- VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,- id: (tpl: TemplateRow) => tpl.id,- map: (tpl: TemplateRow) => [- tpl.id,- tpl.sessionId,- tpl.name,- tpl.body,- tpl.header ?? null,- tpl.footer ?? null,- tpl.createdAt,- tpl.updatedAt,- ],- }),-- // Import baileys stored messages (optional; FK -> sessions, restored above)- defineTableImporter({- key: 'baileysStoredMessages',- label: 'baileys stored message',- sql: `INSERT INTO baileys_stored_messages (id, "sessionId", "waMessageId", "serializedMessage", "createdAt")- VALUES ($1, $2, $3, $4, $5)`,- id: (bsm: BaileysStoredMessageRow) => bsm.id,- map: (bsm: BaileysStoredMessageRow) => [- bsm.id,- bsm.sessionId,- bsm.waMessageId,- bsm.serializedMessage,- bsm.createdAt,- ],- }),-- // Import lid mappings (optional; not a FK, restored as a standalone cache table)- defineTableImporter({- key: 'lidMappings',- label: 'lid mapping',- sql: `INSERT INTO lid_mappings (lid, phone, "sessionId", "updatedAt") VALUES ($1, $2, $3, $4)`,- id: (lm: LidMappingRow) => lm.lid,- map: (lm: LidMappingRow) => [lm.lid, lm.phone ?? null, lm.sessionId ?? null, lm.updatedAt],- }),-- // Import plugin instances (Integration Fabric config + ingress HMAC secret)- defineTableImporter({- key: 'pluginInstances',- label: 'plugin instance',- sql: `INSERT INTO plugin_instances (id, "pluginId", "instanceId", "sessionScope", secret, "verifyToken", config, enabled, "createdAt", "updatedAt")- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,- id: (pi: PluginInstanceRow) => pi.id,- map: (pi: PluginInstanceRow) => [- pi.id,- pi.pluginId,- pi.instanceId,- pi.sessionScope,- pi.secret,- pi.verifyToken,- pi.config == null ? null : typeof pi.config === 'string' ? pi.config : JSON.stringify(pi.config),- pi.enabled,- pi.createdAt,- pi.updatedAt,- ],- }),-- // Import conversation mappings (handover state; sessionId is non-FK provenance)- defineTableImporter({- key: 'conversationMappings',- label: 'conversation mapping',- sql: `INSERT INTO conversation_mappings (id, "sessionId", "chatId", "pluginId", "instanceId", "providerConversationId", "handoverState", metadata, "updatedAt")- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,- id: (cm: ConversationMappingRow) => cm.id,- map: (cm: ConversationMappingRow) => [- cm.id,- cm.sessionId,- cm.chatId,- cm.pluginId,- cm.instanceId,- cm.providerConversationId,- cm.handoverState,- cm.metadata == null ? null : typeof cm.metadata === 'string' ? cm.metadata : JSON.stringify(cm.metadata),- cm.updatedAt,- ],- }),-- // Import ingress events (durable inbound dedup oracle; payload is JSON). The dispatch-lifecycle- // columns ride along: dropping them would strand a restored 'pending' row (NULL dispatchState is- // never swept by the reconciler) while its dedup key still blocks the provider's retry. Columns- // absent from a pre-lifecycle backup import as NULL/0 — the same "not watched" reading legacy- // rows have by design. dispatchAttempts is NOT NULL, so it coalesces to 0 rather than NULL.- defineTableImporter({- key: 'ingressEvents',- label: 'ingress event',- sql: `INSERT INTO ingress_events (id, "instanceId", "pluginId", "providerDeliveryId", route, payload, "payloadHash", "sessionId", "dispatchState", "dispatchAttempts", "lastDispatchAt", "createdAt")- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,- id: (ie: IngressEventRow) => ie.id,- map: (ie: IngressEventRow) => [- ie.id,- ie.instanceId,- ie.pluginId,- ie.providerDeliveryId,- ie.route,- // A retired (NULL) payload must stay NULL — re-materializing it as '{}' would make a- // slimmed dedup row read as a pending event with an empty body.- ie.payload == null ? null : typeof ie.payload === 'string' ? ie.payload : JSON.stringify(ie.payload),- ie.payloadHash ?? null,- ie.sessionId,- ie.dispatchState ?? null,- ie.dispatchAttempts ?? 0,- ie.lastDispatchAt ?? null,- ie.createdAt,- ],- }),-- // Import webhook delivery failures (webhook DLQ)- defineTableImporter({- key: 'webhookDeliveryFailures',- label: 'webhook delivery failure',- sql: `INSERT INTO webhook_delivery_failures (id, "webhookId", "sessionId", event, url, "idempotencyKey", "deliveryId", attempts, "lastStatusCode", "lastError", "createdAt")- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,- id: (wf: WebhookDeliveryFailureRow) => wf.id,- map: (wf: WebhookDeliveryFailureRow) => [- wf.id,- wf.webhookId,- wf.sessionId,- wf.event,- wf.url,- wf.idempotencyKey,- wf.deliveryId,- wf.attempts,- wf.lastStatusCode,- wf.lastError,- wf.createdAt,- ],- }),-- // Import integration delivery failures (inbound + outbound DLQ)- defineTableImporter({- key: 'integrationDeliveryFailures',- label: 'integration delivery failure',- sql: `INSERT INTO integration_delivery_failures (id, direction, "pluginId", "instanceId", "sessionId", "deliveryId", attempts, "lastError", payload, redriven, "createdAt")- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,- id: (df: IntegrationDeliveryFailureRow) => df.id,- map: (df: IntegrationDeliveryFailureRow) => [- df.id,- df.direction,- df.pluginId,- df.instanceId,- df.sessionId,- df.deliveryId,- df.attempts,- df.lastError,- df.payload == null ? null : typeof df.payload === 'string' ? df.payload : JSON.stringify(df.payload),- df.redriven,- df.createdAt,- ],- }),-- // Import status updates (24h-TTL status/story store; sessionId is non-FK provenance)- defineTableImporter({- key: 'statusUpdates',- label: 'status update',- sql: `INSERT INTO status_updates (id, "sessionId", "contactJid", "contactName", "contactPushName", "waStatusId", type, caption, "mediaPath", "mediaMimetype", "mediaOmitted", "omitReason", "backgroundColor", font, "postedAt", "expiresAt")- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)`,- id: (su: StatusUpdateRow) => su.id,- map: (su: StatusUpdateRow) => [- su.id,- su.sessionId,- su.contactJid,- su.contactName ?? null,- su.contactPushName ?? null,- su.waStatusId,- su.type,- su.caption ?? null,- su.mediaPath ?? null,- su.mediaMimetype ?? null,- su.mediaOmitted ?? false,- su.omitReason ?? null,- su.backgroundColor ?? null,- su.font ?? null,- su.postedAt,- su.expiresAt,- ],- }),-];+import type {+ MigrationTables,+ TableCounts,+ SessionRow,+ WebhookRow,+ MessageRow,+ MessageBatchRow,+ TemplateRow,+ BaileysStoredMessageRow,+ LidMappingRow,+ PluginInstanceRow,+ ConversationMappingRow,+ IngressEventRow,+ WebhookDeliveryFailureRow,+ IntegrationDeliveryFailureRow,+ StatusUpdateRow,+} from './migration-tables.types';+import { TABLE_IMPORTERS } from './table-importers';@ApiTags('infrastructure')@Controller('infra')diff --git a/src/modules/infra/migration-tables.types.ts b/src/modules/infra/migration-tables.types.tsnew file mode 100644index 000000000..9257d8a31--- /dev/null+++ b/src/modules/infra/migration-tables.types.ts@@ -0,0 +1,219 @@+// Database migration types for export/import+export interface SessionRow {+ id: string;+ name: string;+ status: string;+ phone: string | null;+ pushName: string | null;+ config: string | Record<string, unknown>;+ proxyUrl: string | null;+ proxyType: string | null;+ connectedAt: string | null;+ lastActiveAt: string | null;+ createdAt: string;+ updatedAt: string;+}++export interface WebhookRow {+ id: string;+ sessionId: string;+ url: string;+ events: string | string[];+ secret: string | null;+ headers: string | Record<string, string>;+ filters: string | Record<string, unknown> | null;+ active: boolean | number;+ retryCount: number;+ lastTriggeredAt: string | null;+ createdAt: string;+ 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.+export interface MessageRow {+ id: string;+ sessionId: string;+ waMessageId: string | null;+ chatId: string;+ chatName: string | null;+ /** Group participant JID (nullable; added to messages after chatName — keep the import list in sync). */+ author: string | null;+ from: string;+ to: string;+ body: string | null;+ type: string;+ direction: string;+ timestamp: number | string | null;+ metadata: string | Record<string, unknown> | null;+ status: string;+ createdAt: string;+ /**+ * Postgres-only STORED generated tsvector (FTS). Present in `SELECT *` rows read from a Postgres+ * source (and in backups made before it was stripped) but never a real payload column: export drops+ * it, and the import's explicit column list ignores it. Declared so both directions type-check.+ */+ body_ts?: unknown;+}++export interface MessageBatchRow {+ id: string;+ batch_id: string;+ session_id: string;+ status: string;+ messages: string | unknown[];+ 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;+}++// 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.+export interface TemplateRow {+ id: string;+ sessionId: string;+ name: string;+ body: string;+ header: string | null;+ footer: string | null;+ createdAt: string;+ updatedAt: string;+}++export interface BaileysStoredMessageRow {+ id: string;+ sessionId: string;+ waMessageId: string;+ serializedMessage: string;+ createdAt: string;+}++// The persisted lid->phone resolution cache. Not a FK to sessions (provenance only), so the import's+// `DELETE FROM sessions` never clears it — it must be exported + re-inserted explicitly or a+// backup→restore into a fresh DB loses the whole cache (it self-heals via re-lookup, but lossily).+export interface LidMappingRow {+ lid: string;+ phone: string | null;+ sessionId: string | null;+ updatedAt: string;+}++export interface PluginInstanceRow {+ id: string;+ pluginId: string;+ instanceId: string;+ sessionScope: string | null;+ secret: string;+ verifyToken: string | null;+ config: string | Record<string, unknown> | null;+ enabled: boolean | number;+ createdAt: string;+ updatedAt: string;+}++export interface ConversationMappingRow {+ id: string;+ sessionId: string;+ chatId: string;+ pluginId: string;+ instanceId: string;+ providerConversationId: string;+ handoverState: string;+ metadata: string | Record<string, unknown> | null;+ updatedAt: string;+}++export interface IngressEventRow {+ id: string;+ instanceId: string;+ pluginId: string;+ providerDeliveryId: string;+ route: string;+ // Retired to NULL once the dispatch outcome is recorded; only 'pending' rows still carry one.+ payload: string | Record<string, unknown> | null;+ payloadHash?: string | null;+ // Dispatch lifecycle (the AddIngressEventDispatchState migration). A restored 'pending' row must+ // keep these or the reconciler never replays it while the dedup row still blocks the provider's+ // retry. Optional because backups exported before the columns existed don't carry them.+ dispatchState?: 'pending' | 'dispatched' | 'failed' | null;+ dispatchAttempts?: number;+ lastDispatchAt?: string | null;+ sessionId: string | null;+ createdAt: string;+}++export interface WebhookDeliveryFailureRow {+ id: string;+ webhookId: string;+ sessionId: string;+ event: string;+ url: string;+ idempotencyKey: string | null;+ deliveryId: string | null;+ attempts: number;+ lastStatusCode: number | null;+ lastError: string;+ createdAt: string;+}++export interface IntegrationDeliveryFailureRow {+ id: string;+ direction: string;+ pluginId: string;+ instanceId: string;+ sessionId: string | null;+ deliveryId: string | null;+ attempts: number;+ lastError: string;+ payload: string | Record<string, unknown> | null;+ redriven: boolean | number;+ createdAt: string;+}++// status_updates has no FK to sessions (plain columns), so the import's `DELETE FROM sessions` never+// clears it — it must be exported + re-inserted explicitly like lid_mappings. postedAt/expiresAt are+// bigint epoch-ms: raw queries bypass the entity transformer, so Postgres returns them as strings.+export interface StatusUpdateRow {+ id: string;+ sessionId: string;+ contactJid: string;+ contactName: string | null;+ contactPushName: string | null;+ waStatusId: string;+ type: string;+ caption: string | null;+ mediaPath: string | null;+ mediaMimetype: string | null;+ mediaOmitted: boolean | number;+ omitReason: string | null;+ backgroundColor: string | null;+ font: number | null;+ postedAt: number | string;+ expiresAt: number | string;+}++export interface MigrationTables {+ sessions: SessionRow[];+ webhooks: WebhookRow[];+ messages: MessageRow[];+ messageBatches: MessageBatchRow[];+ templates: TemplateRow[];+ baileysStoredMessages: BaileysStoredMessageRow[];+ lidMappings: LidMappingRow[];+ pluginInstances: PluginInstanceRow[];+ conversationMappings: ConversationMappingRow[];+ ingressEvents: IngressEventRow[];+ webhookDeliveryFailures: WebhookDeliveryFailureRow[];+ integrationDeliveryFailures: IntegrationDeliveryFailureRow[];+ statusUpdates: StatusUpdateRow[];+}++export type TableCounts = { [K in keyof MigrationTables]: number };diff --git a/src/modules/infra/table-importers.ts b/src/modules/infra/table-importers.tsnew file mode 100644index 000000000..232a6bcdd--- /dev/null+++ b/src/modules/infra/table-importers.ts@@ -0,0 +1,370 @@+import { isSafeSessionName } from '../../common/utils/path-safety';+import type {+ MigrationTables,+ SessionRow,+ WebhookRow,+ MessageRow,+ MessageBatchRow,+ TemplateRow,+ BaileysStoredMessageRow,+ LidMappingRow,+ PluginInstanceRow,+ ConversationMappingRow,+ IngressEventRow,+ WebhookDeliveryFailureRow,+ IntegrationDeliveryFailureRow,+ StatusUpdateRow,+} from './migration-tables.types';++// A per-table restore step for importData: which backup key to read, the exact INSERT text (kept in+// Postgres' `$N` placeholder form; the insert() helper rewrites it for SQLite), the param mapping,+// and an optional per-row skip guard. key/label/id also drive the counts object and the failure+// warnings, so the import loop below stays table-agnostic.+export interface TableImporter<K extends keyof MigrationTables = keyof MigrationTables> {+ key: K;+ /** Singular noun used in the per-row failure warning: `Failed to import <label> <id>: <err>`. */+ label: string;+ /** Full INSERT ... VALUES ($1, ...) text, verbatim per table. */+ sql: string;+ /** The id interpolated into the failure warning (lid_mappings rows key on lid, not id). */+ id: (row: MigrationTables[K][number]) => string;+ map: (row: MigrationTables[K][number]) => unknown[];+ /** Per-row veto: returns the warning to record (the row is skipped) or null to import the row. */+ skip?: (row: MigrationTables[K][number]) => string | null;+}++// Registers one concrete descriptor into the union-keyed TABLE_IMPORTERS array. The return type+// widens the row-specific id/map/skip to the union of all row types; sound because the import loop+// only ever feeds a descriptor rows read from data.tables[its own key].+function defineTableImporter<K extends keyof MigrationTables>(importer: TableImporter<K>): TableImporter {+ return importer;+}++// Restore order is FK order: sessions first (webhooks/messages/templates/etc. reference it), the+// standalone cache/DLQ tables after. The per-block comments from the former inline import blocks+// live on their descriptor entries.+export const TABLE_IMPORTERS: TableImporter[] = [+ // Import sessions first+ defineTableImporter({+ key: 'sessions',+ label: 'session',+ sql: `INSERT INTO sessions (id, name, status, phone, "pushName", config, "proxyUrl", "proxyType", "connectedAt", "lastActiveAt", "createdAt", "updatedAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,+ id: (session: SessionRow) => session.id,+ // A session name becomes the engine auth-directory key, so an unvalidated imported name (this+ // path bypasses CreateSessionDto) could traverse the filesystem. Skip + warn instead of+ // throwing, so one bad row doesn't 500 the whole restore.+ skip: (session: SessionRow) => {+ if (isSafeSessionName(session.name)) return null;+ return `Skipped session ${session.id}: unsafe name ${JSON.stringify(session.name)}`;+ },+ map: (session: SessionRow) => [+ session.id,+ session.name,+ session.status,+ session.phone,+ session.pushName,+ typeof session.config === 'string' ? session.config : JSON.stringify(session.config || {}),+ session.proxyUrl,+ session.proxyType,+ session.connectedAt,+ session.lastActiveAt,+ session.createdAt,+ session.updatedAt,+ ],+ }),++ // Import webhooks+ defineTableImporter({+ key: 'webhooks',+ label: 'webhook',+ sql: `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)`,+ id: (webhook: WebhookRow) => webhook.id,+ map: (webhook: WebhookRow) => [+ webhook.id,+ webhook.sessionId,+ webhook.url,+ 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,+ webhook.createdAt,+ webhook.updatedAt,+ ],+ }),++ // Import messages (optional)+ defineTableImporter({+ key: 'messages',+ label: 'message',+ sql: `INSERT INTO messages (id, "sessionId", "waMessageId", "chatId", "chatName", author, "from", "to", body, type, direction, "timestamp", metadata, status, "createdAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)`,+ id: (msg: MessageRow) => msg.id,+ map: (msg: MessageRow) => [+ msg.id,+ msg.sessionId,+ msg.waMessageId ?? null,+ msg.chatId,+ msg.chatName ?? null,+ // Rows exported before the author column existed simply restore to NULL (legacy+ // behavior) instead of failing the whole import on an unknown key.+ msg.author ?? null,+ msg.from,+ msg.to,+ msg.body ?? null,+ msg.type,+ msg.direction,+ msg.timestamp ?? null,+ msg.metadata == null ? null : typeof msg.metadata === 'string' ? msg.metadata : JSON.stringify(msg.metadata),+ msg.status,+ msg.createdAt,+ ],+ }),++ // Import message batches (optional)+ defineTableImporter({+ key: 'messageBatches',+ label: 'message batch',+ sql: `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)`,+ id: (batch: MessageBatchRow) => batch.id,+ map: (batch: MessageBatchRow) => [+ batch.id,+ batch.batch_id,+ batch.session_id,+ batch.status,+ 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,+ ],+ }),++ // Import templates (optional; FK -> sessions, restored above)+ defineTableImporter({+ key: 'templates',+ label: 'template',+ sql: `INSERT INTO templates (id, "sessionId", name, body, header, footer, "createdAt", "updatedAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,+ id: (tpl: TemplateRow) => tpl.id,+ map: (tpl: TemplateRow) => [+ tpl.id,+ tpl.sessionId,+ tpl.name,+ tpl.body,+ tpl.header ?? null,+ tpl.footer ?? null,+ tpl.createdAt,+ tpl.updatedAt,+ ],+ }),++ // Import baileys stored messages (optional; FK -> sessions, restored above)+ defineTableImporter({+ key: 'baileysStoredMessages',+ label: 'baileys stored message',+ sql: `INSERT INTO baileys_stored_messages (id, "sessionId", "waMessageId", "serializedMessage", "createdAt")+ VALUES ($1, $2, $3, $4, $5)`,+ id: (bsm: BaileysStoredMessageRow) => bsm.id,+ map: (bsm: BaileysStoredMessageRow) => [+ bsm.id,+ bsm.sessionId,+ bsm.waMessageId,+ bsm.serializedMessage,+ bsm.createdAt,+ ],+ }),++ // Import lid mappings (optional; not a FK, restored as a standalone cache table)+ defineTableImporter({+ key: 'lidMappings',+ label: 'lid mapping',+ sql: `INSERT INTO lid_mappings (lid, phone, "sessionId", "updatedAt") VALUES ($1, $2, $3, $4)`,+ id: (lm: LidMappingRow) => lm.lid,+ map: (lm: LidMappingRow) => [lm.lid, lm.phone ?? null, lm.sessionId ?? null, lm.updatedAt],+ }),++ // Import plugin instances (Integration Fabric config + ingress HMAC secret)+ defineTableImporter({+ key: 'pluginInstances',+ label: 'plugin instance',+ sql: `INSERT INTO plugin_instances (id, "pluginId", "instanceId", "sessionScope", secret, "verifyToken", config, enabled, "createdAt", "updatedAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,+ id: (pi: PluginInstanceRow) => pi.id,+ map: (pi: PluginInstanceRow) => [+ pi.id,+ pi.pluginId,+ pi.instanceId,+ pi.sessionScope,+ pi.secret,+ pi.verifyToken,+ pi.config == null ? null : typeof pi.config === 'string' ? pi.config : JSON.stringify(pi.config),+ pi.enabled,+ pi.createdAt,+ pi.updatedAt,+ ],+ }),++ // Import conversation mappings (handover state; sessionId is non-FK provenance)+ defineTableImporter({+ key: 'conversationMappings',+ label: 'conversation mapping',+ sql: `INSERT INTO conversation_mappings (id, "sessionId", "chatId", "pluginId", "instanceId", "providerConversationId", "handoverState", metadata, "updatedAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,+ id: (cm: ConversationMappingRow) => cm.id,+ map: (cm: ConversationMappingRow) => [+ cm.id,+ cm.sessionId,+ cm.chatId,+ cm.pluginId,+ cm.instanceId,+ cm.providerConversationId,+ cm.handoverState,+ cm.metadata == null ? null : typeof cm.metadata === 'string' ? cm.metadata : JSON.stringify(cm.metadata),+ cm.updatedAt,+ ],+ }),++ // Import ingress events (durable inbound dedup oracle; payload is JSON). The dispatch-lifecycle+ // columns ride along: dropping them would strand a restored 'pending' row (NULL dispatchState is+ // never swept by the reconciler) while its dedup key still blocks the provider's retry. Columns+ // absent from a pre-lifecycle backup import as NULL/0 — the same "not watched" reading legacy+ // rows have by design. dispatchAttempts is NOT NULL, so it coalesces to 0 rather than NULL.+ defineTableImporter({+ key: 'ingressEvents',+ label: 'ingress event',+ sql: `INSERT INTO ingress_events (id, "instanceId", "pluginId", "providerDeliveryId", route, payload, "payloadHash", "sessionId", "dispatchState", "dispatchAttempts", "lastDispatchAt", "createdAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,+ id: (ie: IngressEventRow) => ie.id,+ map: (ie: IngressEventRow) => [+ ie.id,+ ie.instanceId,+ ie.pluginId,+ ie.providerDeliveryId,+ ie.route,+ // A retired (NULL) payload must stay NULL — re-materializing it as '{}' would make a+ // slimmed dedup row read as a pending event with an empty body.+ ie.payload == null ? null : typeof ie.payload === 'string' ? ie.payload : JSON.stringify(ie.payload),+ ie.payloadHash ?? null,+ ie.sessionId,+ ie.dispatchState ?? null,+ ie.dispatchAttempts ?? 0,+ ie.lastDispatchAt ?? null,+ ie.createdAt,+ ],+ }),++ // Import webhook delivery failures (webhook DLQ)+ defineTableImporter({+ key: 'webhookDeliveryFailures',+ label: 'webhook delivery failure',+ sql: `INSERT INTO webhook_delivery_failures (id, "webhookId", "sessionId", event, url, "idempotencyKey", "deliveryId", attempts, "lastStatusCode", "lastError", "createdAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,+ id: (wf: WebhookDeliveryFailureRow) => wf.id,+ map: (wf: WebhookDeliveryFailureRow) => [+ wf.id,+ wf.webhookId,+ wf.sessionId,+ wf.event,+ wf.url,+ wf.idempotencyKey,+ wf.deliveryId,+ wf.attempts,+ wf.lastStatusCode,+ wf.lastError,+ wf.createdAt,+ ],+ }),++ // Import integration delivery failures (inbound + outbound DLQ)+ defineTableImporter({+ key: 'integrationDeliveryFailures',+ label: 'integration delivery failure',+ sql: `INSERT INTO integration_delivery_failures (id, direction, "pluginId", "instanceId", "sessionId", "deliveryId", attempts, "lastError", payload, redriven, "createdAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,+ id: (df: IntegrationDeliveryFailureRow) => df.id,+ map: (df: IntegrationDeliveryFailureRow) => [+ df.id,+ df.direction,+ df.pluginId,+ df.instanceId,+ df.sessionId,+ df.deliveryId,+ df.attempts,+ df.lastError,+ df.payload == null ? null : typeof df.payload === 'string' ? df.payload : JSON.stringify(df.payload),+ df.redriven,+ df.createdAt,+ ],+ }),++ // Import status updates (24h-TTL status/story store; sessionId is non-FK provenance)+ defineTableImporter({+ key: 'statusUpdates',+ label: 'status update',+ sql: `INSERT INTO status_updates (id, "sessionId", "contactJid", "contactName", "contactPushName", "waStatusId", type, caption, "mediaPath", "mediaMimetype", "mediaOmitted", "omitReason", "backgroundColor", font, "postedAt", "expiresAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)`,+ id: (su: StatusUpdateRow) => su.id,+ map: (su: StatusUpdateRow) => [+ su.id,+ su.sessionId,+ su.contactJid,+ su.contactName ?? null,+ su.contactPushName ?? null,+ su.waStatusId,+ su.type,+ su.caption ?? null,+ su.mediaPath ?? null,+ su.mediaMimetype ?? null,+ su.mediaOmitted ?? false,+ su.omitReason ?? null,+ su.backgroundColor ?? null,+ su.font ?? null,+ su.postedAt,+ su.expiresAt,+ ],+ }),+];++// The `as TableCounts` cast in importData means a dropped or mis-keyed descriptor is invisible to+// the compiler: the table would silently never import and would vanish from the restored-row total+// that guards against wiping a database with an empty payload. Assert the set at module load.+const EXPECTED_TABLE_KEYS: ReadonlyArray<keyof MigrationTables> = [+ 'sessions',+ 'webhooks',+ 'messages',+ 'messageBatches',+ 'templates',+ 'baileysStoredMessages',+ 'lidMappings',+ 'pluginInstances',+ 'conversationMappings',+ 'ingressEvents',+ 'webhookDeliveryFailures',+ 'integrationDeliveryFailures',+ 'statusUpdates',+];+const importerKeys = TABLE_IMPORTERS.map(importer => importer.key);+for (const key of EXPECTED_TABLE_KEYS) {+ if (!importerKeys.includes(key)) throw new Error(`table-importers: missing descriptor for "${key}"`);+}+if (importerKeys.length !== EXPECTED_TABLE_KEYS.length) {+ throw new Error(`table-importers: expected ${EXPECTED_TABLE_KEYS.length} descriptors, found ${importerKeys.length}`);+}