Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix: Baileys QR data URL, graceful-shutdown DataSource, migration idempotency (#315)
Yudhi Armyndharis3f4e7b13fb2d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 13bd61563..e41c62840 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed++- **Baileys QR code is now scannable from the dashboard.** The Baileys engine returned the raw WhatsApp QR+ ref string from `GET /sessions/:id/qr`, while the dashboard (and the whatsapp-web.js engine) expect a PNG+ data URL — so the dashboard's `<img>` showed a broken image and Baileys sessions could not be linked via+ the UI. The Baileys adapter now renders the QR to a `data:image/png` URL, matching the whatsapp-web.js+ engine's contract (the REST response shape is now consistent across engines).+- **Adopting migrations over a `synchronize`-created SQLite data DB no longer crashes on boot.** A data DB+ whose schema was created by `DATABASE_SYNCHRONIZE=true` has an empty migrations table, so the baseline+ migration re-ran `CREATE TABLE "sessions"` and aborted startup with `table "sessions" already exists`. The+ baseline migration is now idempotent (it skips when the schema already exists, mirroring the other+ migrations), so switching a SQLite data DB from synchronize to migration-managed boots cleanly and the DB+ becomes migration-managed going forward (existing rows preserved). Fresh deployments are unaffected.+- **Graceful shutdown no longer logs "could not find DataSource" on SIGTERM.** With two named TypeORM+ connections (`main` + `data`), `@nestjs/typeorm`'s shutdown hook resolved the default (unnamed) DataSource+ token and threw `Nest could not find DataSource element`, leaving the DataSources undestroyed and the+ process exiting non-zero. The connection factories now carry their `name`, so the shutdown hook resolves+ the correct named DataSource and the app shuts down cleanly (exit 0).++### Changed++- Internal: the SQLite data-DB configuration comment and a dead `synchronize` default in `app.module.ts` now+ reflect the actual behavior (the data DB is migration-managed by default; `DATABASE_SYNCHRONIZE=true` opts+ into synchronize). No runtime behavior change.+## [0.4.0] - 2026-06-18Single-port deployment. The API now serves the bundled dashboard SPA itself, and the bundled Traefikdiff --git a/src/app.module.ts b/src/app.module.tsindex 22009cad4..0138fc400 100644--- a/src/app.module.ts+++ b/src/app.module.ts@@ -85,6 +85,7 @@ if (dashboardServingEnabled && dashboardBuildPresent) {// api_keys/audit_logs schema instead — never both at once.const synchronize = configService.get<boolean>('database.synchronize', true);return {+ name: 'main',type: 'sqlite' as const,database: configService.get<string>('database.database', './data/main.sqlite'),entities: [@@ -123,6 +124,7 @@ if (dashboardServingEnabled && dashboardBuildPresent) {if (dbType === 'postgres') {return {...baseConfig,+ name: 'data',type: 'postgres' as const,host: configService.get<string>('dataDatabase.host'),port: configService.get<number>('dataDatabase.port'),@@ -147,15 +149,18 @@ if (dashboardServingEnabled && dashboardBuildPresent) {};}- // SQLite: zero-config. Default to synchronize=true so the embedded- // database "just works" on first boot without a separate migration step.- // Users can opt out with DATABASE_SYNCHRONIZE=false to use migrations instead.+ // SQLite data DB: schema is MIGRATION-managed by default (DATABASE_SYNCHRONIZE unset/false),+ // matching configuration.ts and .env.example ("Set false in production"). Set+ // DATABASE_SYNCHRONIZE=true for zero-config synchronize instead. Computed once: the resolved+ // value is always a boolean, so a get(..., true) fallback would never fire (and would be a trap).+ const synchronize = configService.get<boolean>('dataDatabase.synchronize', false);return {...baseConfig,+ name: 'data',type: 'sqlite' as const,database: configService.get<string>('dataDatabase.database', './data/openwa.sqlite'),- synchronize: configService.get<boolean>('dataDatabase.synchronize', true),- migrationsRun: !configService.get<boolean>('dataDatabase.synchronize', true),+ synchronize,+ migrationsRun: !synchronize,};},}),diff --git a/src/database/migrations/1770108659848-AddMessageStatus.ts b/src/database/migrations/1770108659848-AddMessageStatus.tsindex f6e68ba9e..3496280be 100644--- a/src/database/migrations/1770108659848-AddMessageStatus.ts+++ b/src/database/migrations/1770108659848-AddMessageStatus.ts@@ -4,6 +4,16 @@ export class AddMessageStatus1770108659848 implements MigrationInterface {name = 'AddMessageStatus1770108659848';public async up(queryRunner: QueryRunner): Promise<void> {+ // Idempotency guard for the synchronize -> migrations adoption path. A DB whose schema was+ // created by `synchronize` has an empty migrations tracking table, so TypeORM tries to run this+ // baseline from scratch and collides on the already-existing tables ("table sessions already+ // exists"). If the schema is already present, skip the creates (TypeORM still records this+ // migration as applied). The webhooks CASCADE FK is declared on the entity, so a synchronize-built+ // schema already matches. Mirrors the hasTable guard in AddTemplates / AddBaileysStoredMessages.+ if (await queryRunner.hasTable('sessions')) {+ return;+ }+const isPostgres = queryRunner.connection.options.type === 'postgres';if (isPostgres) {diff --git a/src/database/migrations/__tests__/1770108659848-AddMessageStatus.spec.ts b/src/database/migrations/__tests__/1770108659848-AddMessageStatus.spec.tsnew file mode 100644index 000000000..a26e7ff5a--- /dev/null+++ b/src/database/migrations/__tests__/1770108659848-AddMessageStatus.spec.ts@@ -0,0 +1,40 @@+import { DataSource } from 'typeorm';+import { AddMessageStatus1770108659848 } from '../1770108659848-AddMessageStatus';++describe('AddMessageStatus baseline migration', () => {+ let ds: DataSource;++ beforeEach(async () => {+ ds = new DataSource({ type: 'sqlite', database: ':memory:' });+ await ds.initialize();+ });++ afterEach(async () => {+ await ds.destroy();+ });++ it('creates the full baseline schema on an empty DB (fresh deploy)', async () => {+ const runner = ds.createQueryRunner();+ await new AddMessageStatus1770108659848().up(runner);++ expect(await runner.hasTable('sessions')).toBe(true);+ expect(await runner.hasTable('webhooks')).toBe(true);+ expect(await runner.hasTable('messages')).toBe(true);+ expect(await runner.hasTable('message_batches')).toBe(true);++ await runner.release();+ });++ it('is a no-op when sessions already exists (synchronize-created DB adopting migrations)', async () => {+ const runner = ds.createQueryRunner();+ // Simulate a synchronize-created DB: the schema is already present, but the+ // migrations tracking table is empty, so TypeORM tries to run this baseline.+ await runner.query(`CREATE TABLE "sessions" ("id" varchar PRIMARY KEY NOT NULL)`);++ // Must NOT throw "table sessions already exists" — the baseline should detect the+ // existing schema and skip (TypeORM still records it as applied).+ await expect(new AddMessageStatus1770108659848().up(runner)).resolves.toBeUndefined();++ await runner.release();+ });+});diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 2132702cb..81c194715 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -92,14 +92,23 @@ describe('BaileysAdapter lifecycle & status', () => {expect(newAdapter().getStatus()).toBe(EngineStatus.DISCONNECTED);});- it('emits onQRCode and moves to QR_READY on a connection.update with a qr', async () => {- const onQRCode = jest.fn();+ it('renders the QR to a PNG data URL and moves to QR_READY on a connection.update with a qr', async () => {+ // QR rendering (qrcode.toDataURL) is async, so await the real completion signal — the onQRCode+ // callback — rather than guessing tick counts.+ let resolveQr!: (url: string) => void;+ const qrPublished = new Promise<string>(resolve => {+ resolveQr = resolve;+ });+ const onQRCode = jest.fn((url: string) => resolveQr(url));const adapter = newAdapter();await adapter.initialize(noopCallbacks({ onQRCode }));fakeSock.fire('connection.update', { qr: 'QR-STRING' });- expect(onQRCode).toHaveBeenCalledWith('QR-STRING');++ const rendered = await qrPublished;+ // The dashboard renders <img src={qrCode}>, so engines must emit a data URL, not the raw ref.+ expect(rendered).toMatch(/^data:image\/png;base64,/);expect(adapter.getStatus()).toBe(EngineStatus.QR_READY);- expect(adapter.getQRCode()).toBe('QR-STRING');+ expect(adapter.getQRCode()).toBe(rendered);});it('captures phone/pushName and fires onReady on connection open', async () => {diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex a32206fb3..9f64d3519 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -1,4 +1,5 @@import * as path from 'path';+import * as qrcode from 'qrcode';import type * as BaileysLib from '@whiskeysockets/baileys';import type { AnyMessageContent, MiscMessageGenerationOptions, WAMessage, WASocket } from '@whiskeysockets/baileys';import { buildIncomingMessageFromBaileys, mapBaileysStatus } from './baileys-message-mapper';@@ -169,9 +170,9 @@ export class BaileysAdapter implements IWhatsAppEngine {const { connection, qr, lastDisconnect } = update;if (qr) {- this.qrCode = qr;- this.setStatus(EngineStatus.QR_READY);- this.callbacks.onQRCode?.(qr);+ // Baileys hands us the raw QR ref string; render it to a PNG data URL so the stored+ // value matches the whatsapp-web.js engine's contract (the dashboard does <img src={qrCode}>).+ void this.handleQrCode(qr);}if (connection === 'connecting') {@@ -234,6 +235,17 @@ export class BaileysAdapter implements IWhatsAppEngine {}}+ /** Render the raw Baileys QR ref to a PNG data URL, then publish it (mirrors the whatsapp-web.js engine). */+ private async handleQrCode(qr: string): Promise<void> {+ try {+ this.qrCode = await qrcode.toDataURL(qr);+ this.setStatus(EngineStatus.QR_READY);+ this.callbacks.onQRCode?.(this.qrCode);+ } catch (error) {+ this.logger.error('Error generating QR code', String(error));+ }+ }+disconnect(): Promise<void> {this.intentionalClose = true;if (this.reconnectTimer) {