Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): normalize imported active statuses instead of restoring them verbatim
Yudhi Armyndharis5647056bf50f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2aa521f2d..5c568e919 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- import-data restores an active session status from the backup as `disconnected` (scoped to claimable rows; a notice counts them), so migrated sessions are startable without a process restart.- The engine parity gate reads any single-quoted throw literal (a parenthesized site like sendText(customPreview) escaped the identifier-only regex), rejects construction sites it cannot see (template literals, variable arguments, literals naming no method), and pins conditional refusals in an explicit list; docs/29 states the refinements.- The Baileys adapter builds one shared host object for its nine delegates instead of nine overlapping closure bags; a new cross-cutting member is added once. No behavior change.- A transient whatsapp-web.js lid-to-phone lookup failure (dead page, rate limit) no longer overwrites a valid stored mapping with a definitive null; the engine method rejects on failure and the HTTP boundary keeps its null-on-failure contract.diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 26398d8eb..7d344776c 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -5437,15 +5437,15 @@ Replace all Data DB rows with the supplied export. **Destructive and transaction**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`. 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 | Export rows omit `secret`/`headers`; an absent key restores as `null`/`{}` |-| `tables.messageBatches` | `MessageBatchRow[]` | No | snake_case columns |-| `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`) |+| Field | Type | Required | Description |+| ----------------------------- | ------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `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). An ACTIVE status in the backup (`ready`, `initializing`, ...) describes the source host's engines: restored as `disconnected` (a notice counts them), unless the session is held by a live peer whose claim the import preserves |+| `tables.webhooks` | `WebhookRow[]` | No | Export rows omit `secret`/`headers`; an absent key restores as `null`/`{}` |+| `tables.messageBatches` | `MessageBatchRow[]` | No | snake_case columns |+| `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`) |```json{diff --git a/docs/14-migration-guide.md b/docs/14-migration-guide.mdindex 886b07385..b5b92b86a 100644--- a/docs/14-migration-guide.md+++ b/docs/14-migration-guide.md@@ -120,6 +120,13 @@ curl -X POST 'http://localhost:2785/api/infra/import-data' \> (`EXPORT_INLINE_MEDIA_BUDGET_BYTES`, 8 MiB by default); for a byte-exact copy including media, use> `scripts/backup.sh`, which snapshots the database file itself.+> [!NOTE]+> **Session statuses in the backup describe the source host.** An active status (`ready`,+> `initializing`, ...) is restored as `disconnected` (the import response counts them in a notice),+> so the migrated sessions are immediately startable - via `POST /api/sessions/:id/start`, or by+> the auto-start/takeover paths - without restarting the process. A session held by a live peer+> whose claim the import preserves keeps the backup's status.+> [!NOTE]> **Dual-Database Architecture**>diff --git a/src/modules/infra/infra-data.controller.spec.ts b/src/modules/infra/infra-data.controller.spec.tsindex fcf6978f4..41ad37079 100644--- a/src/modules/infra/infra-data.controller.spec.ts+++ b/src/modules/infra/infra-data.controller.spec.ts@@ -22,7 +22,7 @@ jest.mock('fs', () => {};});-import { DataSource, QueryFailedError } from 'typeorm';+import { DataSource, IsNull, QueryFailedError } from 'typeorm';import { ConflictException } from '@nestjs/common';import { InfraDataController } from './infra-data.controller';import { InfraDataService, restoreSessionOwnership } from './infra-data.service';@@ -236,6 +236,7 @@ describe('InfraDataController.importData round-trips export-data (no silent messevents.push('release');};},+ claimableWhere: () => [],heldByOtherNodes: () => Promise.resolve([]),};// Observe from inside the transaction: the token must already be held by the time rows move.@@ -346,6 +347,7 @@ describe('InfraDataController.importData round-trips export-data (no silent mess};},heldByOtherNodes: () => Promise.resolve([]),+ claimableWhere: () => [],};// Stubbed rather than provoked: TypeORM nests a second startTransaction as SAVEPOINT, so no// dialect here rejects it today. What is pinned is the STRUCTURE — the pre-body span sits@@ -378,6 +380,7 @@ describe('InfraDataController.importData round-trips export-data (no silent mess};},heldByOtherNodes: () => Promise.resolve([]),+ claimableWhere: () => [],};jest.spyOn(ds, 'createQueryRunner').mockImplementation(() => {throw new Error('no connection available');@@ -401,6 +404,7 @@ describe('InfraDataController.importData round-trips export-data (no silent messreturn () => {};},heldByOtherNodes: () => Promise.resolve([]),+ claimableWhere: () => [],};// Postgres hands every runner a dedicated pooled client, so the heartbeat cannot see the// import's uncommitted DELETE. Suspending there would disable genuine loss detection in exactly@@ -1616,6 +1620,44 @@ describe('InfraDataController.importData status_updates + runtime reconciliation// automation_rules FKs sessions ON DELETE CASCADE, so the import's `DELETE FROM sessions` takes// every rule with it — on SQLite too, where better-sqlite3 enforces foreign keys. Without export +// re-insert the documented backup/restore silently destroyed every autoreply rule.+ it('restores an active session status as disconnected: the backup describes the source host engines', async () => {+ await seedSession('s1');+ const repo = ds.getRepository(Session);+ const dump = await build().exportData();+ // seedSession writes READY; the export carries it. With no ownership service (single-node+ // default), every row is claimable, so the import must normalize it.+ expect(dump.tables.sessions?.[0]?.status).toBe(SessionStatus.READY);++ const res = await build().importData({ tables: dump.tables });++ expect(res.imported).toBe(true);+ await expect(repo.findOneByOrFail({ id: 's1' })).resolves.toMatchObject({ status: SessionStatus.DISCONNECTED });+ expect(res.notices?.some(n => n.includes('restored as disconnected'))).toBe(true);+ });++ it('keeps the backup status of a session held by a PEER (its live engine backs the row)', async () => {+ await seedSession('held');+ const repo = ds.getRepository(Session);+ // A peer's unexpired claim: not claimable by this node, so the normalization must skip it.+ // The import re-applies the preserved claim after the inserts (restoreSessionOwnership), which+ // is what keeps the row excluded when the normalization runs.+ await repo.update({ id: 'held' }, { nodeId: 'node-b', leaseExpiresAt: new Date(Date.now() + 60_000) });+ const dump = await build().exportData();++ const ownership = {+ nodeId: 'node-a',+ heldByOtherNodes: () => Promise.resolve(['held']),+ suspendLossDetection: () => () => undefined,+ claimableWhere: () => [{ nodeId: IsNull() }, { nodeId: 'node-a' }],+ };+ const res = await new InfraDataController(+ new InfraDataService(cfg as never, ds, undefined, undefined, undefined, ownership as never),+ ).importData({ tables: dump.tables });++ expect(res.imported).toBe(true);+ await expect(repo.findOneByOrFail({ id: 'held' })).resolves.toMatchObject({ status: SessionStatus.READY });+ });+it('exports and restores automation_rules, which the session wipe would otherwise cascade away', async () => {await seedSession('s1');const ruleRepo = ds.getRepository(AutomationRule);diff --git a/src/modules/infra/infra-data.service.ts b/src/modules/infra/infra-data.service.tsindex 2fe6b178b..9571807fd 100644--- a/src/modules/infra/infra-data.service.ts+++ b/src/modules/infra/infra-data.service.ts@@ -9,6 +9,8 @@ import { AuditAction } from '../audit/entities/audit-log.entity';import { SessionService } from '../session/session.service';import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';import { SessionOwnershipService } from '../session/session-ownership.service';+import { Session as SessionEntity, SessionStatus } from '../session/entities/session.entity';+import { In } from 'typeorm';import type { MigrationTables, TableCounts } from './migration-tables.types';import { EXPORT_TABLES, EXPORT_TABLE_EXCLUSIONS } from './export-tables';import { TABLE_IMPORTERS } from './table-importers';@@ -667,6 +669,36 @@ export class InfraDataService {);}+ // Normalize imported statuses the same way boot does: an ACTIVE status (ready,+ // initializing, ...) in a backup describes the SOURCE host's engines, and restoring it+ // verbatim leaves rows reading ready with no engine anywhere - invisible to auto-start+ // (selects disconnected) and to the takeover sweep, until a process restart. Scoped to+ // CLAIMABLE rows only, so a session whose ownership claim was just re-applied to this+ // node or a peer (a live engine still backs it) keeps the backup's status.+ const ACTIVE_STATUSES = [+ SessionStatus.READY,+ SessionStatus.INITIALIZING,+ SessionStatus.QR_READY,+ SessionStatus.AUTHENTICATING,+ SessionStatus.ACTION_REQUIRED,+ ];+ const claimable = this.ownership?.claimableWhere() ?? [{}];+ // An empty clause list means nothing is claimable (no rows to normalize). TypeORM also+ // rejects empty update criteria, so skip rather than build an empty OR.+ const normalized =+ claimable.length === 0+ ? { affected: 0 }+ : await queryRunner.manager.getRepository(SessionEntity).update(+ claimable.map(clause => ({ ...clause, status: In(ACTIVE_STATUSES) })),+ { status: SessionStatus.DISCONNECTED },+ );+ if (normalized.affected && normalized.affected > 0) {+ notices.push(+ `${normalized.affected} imported session(s) carried an active status (the source host's engines): ` ++ 'restored as disconnected - start them via POST /api/sessions/:id/start or let auto-start adopt them.',+ );+ }+// "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