Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix: reliability & contract hardening (plugins, events, session, dashboard, baileys, infra) (#477)
Yudhi Armyndharis624f7d915194
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6992daf67..a31c75533 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed++- A plugin whose enable failed after it had already subscribed hooks no longer leaves stale hook registrations behind; a later successful enable could otherwise dispatch each event to the plugin more than once. (#477)+- The WebSocket `message.ack` event now carries the same `{ id, messageId, status, ack }` shape over the socket as the matching webhook does — the socket previously omitted `id` and the legacy `ack`. (#477)+- Reconnect timers are no longer stacked when two disconnects arrive back-to-back, and a terminal engine failure now cancels any pending reconnect so a `FAILED` session cannot be resurrected by a stale timer. (#477)+- The dashboard recovers from a stale lazy-loaded chunk after a redeploy with a single guarded reload instead of replacing the whole UI with the error screen; the Content-Security-Policy `img-src` now allows `blob:` so the outgoing image-attachment preview renders. (#477)+- The Baileys engine's number-check (`GET /sessions/:id/contacts/check/:number`) now returns a neutral `<phone>@c.us` id, matching the whatsapp-web.js engine, instead of a raw `@s.whatsapp.net` id. (#477)+- The data export/import now includes the `lid_mappings` resolution cache, so a backup/restore or a SQLite↔PostgreSQL migration no longer drops it. (#477)+## [0.7.5] - 2026-06-26### Fixeddiff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsxindex e690b4e4d..51becba75 100644--- a/dashboard/src/App.tsx+++ b/dashboard/src/App.tsx@@ -1,5 +1,6 @@-import { useState, useEffect, lazy, Suspense } from 'react';+import { useState, useEffect, Suspense } from 'react';import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';+import { lazyWithRetry as lazy } from './utils/lazyWithRetry';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { Loader2 } from 'lucide-react';import { Layout } from './components/Layout';diff --git a/dashboard/src/hooks/useWebSocket.ts b/dashboard/src/hooks/useWebSocket.tsindex a3b2129f2..40da2b4cb 100644--- a/dashboard/src/hooks/useWebSocket.ts+++ b/dashboard/src/hooks/useWebSocket.ts@@ -21,10 +21,12 @@ interface MessageEvent {interface MessageAckEvent {sessionId: string;+ id: string;messageId: string;// Neutral delivery status emitted by the backend (engine-agnostic), not a raw wwebjs ack integer.status: 'pending' | 'sent' | 'delivered' | 'read' | 'failed';- chatId?: string;+ // Deprecated legacy numeric ack kept for backward compatibility; prefer `status`.+ ack?: number;timestamp?: string;}@@ -191,9 +193,10 @@ export function useWebSocket(events: WebSocketEvents = {}) {case 'message.ack':events.onMessageAck?.({sessionId,+ id: String(data.id),messageId: String(data.messageId),status: data.status as MessageAckEvent['status'],- chatId: data.chatId as string | undefined,+ ack: typeof data.ack === 'number' ? data.ack : undefined,timestamp: msg.timestamp,});break;diff --git a/dashboard/src/pages/Dashboard.tsx b/dashboard/src/pages/Dashboard.tsxindex 634d40df8..de615e661 100644--- a/dashboard/src/pages/Dashboard.tsx+++ b/dashboard/src/pages/Dashboard.tsx@@ -1,4 +1,5 @@-import { lazy, Suspense } from 'react';+import { Suspense } from 'react';+import { lazyWithRetry as lazy } from '../utils/lazyWithRetry';import { useNavigate } from 'react-router-dom';import { useTranslation } from 'react-i18next';import { MessageSquare, Send, Webhook, Activity, ArrowUpRight, ArrowDownRight, Loader2 } from 'lucide-react';diff --git a/dashboard/src/utils/chunkReload.test.ts b/dashboard/src/utils/chunkReload.test.tsnew file mode 100644index 000000000..9b734636c--- /dev/null+++ b/dashboard/src/utils/chunkReload.test.ts@@ -0,0 +1,52 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { loadChunkWithReload } from './chunkReload.ts';++function makeStorage(initial: Record<string, string> = {}): Pick<Storage, 'getItem' | 'setItem' | 'removeItem'> {+ const m = new Map<string, string>(Object.entries(initial));+ return {+ getItem: k => m.get(k) ?? null,+ setItem: (k, v) => void m.set(k, v),+ removeItem: k => void m.delete(k),+ };+}++const flush = () => new Promise(resolve => setTimeout(resolve, 0));++test('returns the module and clears the reload flag on success', async () => {+ const storage = makeStorage({ owa_chunk_reloaded: '1' });+ const mod = { default: 'Component' };+ let reloads = 0;++ const result = await loadChunkWithReload(() => Promise.resolve(mod), { reload: () => reloads++, storage });++ assert.equal(result, mod);+ assert.equal(reloads, 0);+ assert.equal(storage.getItem('owa_chunk_reloaded'), null);+});++test('reloads exactly once on a chunk failure when no reload has happened yet', async () => {+ const storage = makeStorage();+ let reloads = 0;++ // The result never settles (Suspense holds until the reload), so don't await it.+ void loadChunkWithReload(() => Promise.reject(new Error('Loading chunk 7 failed')), {+ reload: () => reloads++,+ storage,+ });+ await flush();++ assert.equal(reloads, 1);+ assert.equal(storage.getItem('owa_chunk_reloaded'), '1');+});++test('rethrows instead of reloading again once a reload already happened (no loop)', async () => {+ const storage = makeStorage({ owa_chunk_reloaded: '1' });+ let reloads = 0;++ await assert.rejects(+ loadChunkWithReload(() => Promise.reject(new Error('still failing')), { reload: () => reloads++, storage }),+ /still failing/,+ );+ assert.equal(reloads, 0);+});diff --git a/dashboard/src/utils/chunkReload.ts b/dashboard/src/utils/chunkReload.tsnew file mode 100644index 000000000..49b218600--- /dev/null+++ b/dashboard/src/utils/chunkReload.ts@@ -0,0 +1,29 @@+// Recovery for a failed dynamic import() of a route/lazy chunk. The dominant cause is a redeploy:+// the running index.html references hashed chunk filenames that no longer exist on the server, so+// import() rejects. A one-time full reload pulls the fresh index + chunks. A sessionStorage flag+// guards against a reload loop when the failure is not deploy-related (adblock, offline, real 404).+// React-free on purpose so it is unit-testable without a DOM. See lazyWithRetry.ts for the wiring.++const RELOAD_KEY = 'owa_chunk_reloaded';++export interface ChunkReloadDeps {+ reload: () => void;+ storage: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;+}++export async function loadChunkWithReload<T>(factory: () => Promise<T>, deps: ChunkReloadDeps): Promise<T> {+ try {+ const mod = await factory();+ deps.storage.removeItem(RELOAD_KEY);+ return mod;+ } catch (err) {+ if (!deps.storage.getItem(RELOAD_KEY)) {+ deps.storage.setItem(RELOAD_KEY, '1');+ deps.reload();+ // Hold Suspense until the reload navigates away; never resolve/reject this load.+ return new Promise<T>(() => {});+ }+ // A reload already happened and it still failed → let the caller's error boundary surface it.+ throw err;+ }+}diff --git a/dashboard/src/utils/lazyWithRetry.ts b/dashboard/src/utils/lazyWithRetry.tsnew file mode 100644index 000000000..c9e5fb17e--- /dev/null+++ b/dashboard/src/utils/lazyWithRetry.ts@@ -0,0 +1,17 @@+import { lazy, type ComponentType } from 'react';+import { loadChunkWithReload } from './chunkReload';++/**+ * Drop-in replacement for React.lazy that survives a stale-chunk failure after a redeploy: a failed+ * dynamic import() triggers a one-time full reload (fresh index.html + chunks) instead of bubbling to+ * the top-level ErrorBoundary and blanking the whole dashboard. See chunkReload.ts for the guard logic.+ */+// eslint-disable-next-line @typescript-eslint/no-explicit-any+export function lazyWithRetry<T extends ComponentType<any>>(factory: () => Promise<{ default: T }>) {+ return lazy(() =>+ loadChunkWithReload(factory, {+ reload: () => window.location.reload(),+ storage: window.sessionStorage,+ }),+ );+}diff --git a/src/core/agent-tools/session-scope-invariant.spec.ts b/src/core/agent-tools/session-scope-invariant.spec.tsnew file mode 100644index 000000000..1d855cd5e--- /dev/null+++ b/src/core/agent-tools/session-scope-invariant.spec.ts@@ -0,0 +1,41 @@+import { z } from 'zod';+import { sessionTools } from './tools/session.tools';+import { messageTools } from './tools/message.tools';+import { contactTools } from './tools/contact.tools';+import { groupTools } from './tools/group.tools';+import { webhookTools } from './tools/webhook.tools';+import type { ToolDescriptor } from './tool-descriptor';++// Registry-level invariant (not a per-tool enumeration): EVERY sessionScoped tool must require a+// non-empty sessionId. tool-invoker only passes sessionId into the allowedSessions fence when it is a+// non-empty string (auth.service skips the fence on a falsy sessionId), so a sessionScoped tool whose+// schema makes sessionId optional or accepts '' would let a session-restricted key bypass scope.+// This catches a FUTURE tool authored with z.string().optional() — no test edit needed when one is added.+describe('agent-tool registry: every sessionScoped tool requires a non-empty sessionId', () => {+ // Handlers are never invoked here; stub services are fine — we only inspect the schema/flags.+ const allTools: ToolDescriptor[] = [+ ...sessionTools({} as never),+ ...messageTools({} as never),+ ...contactTools({} as never),+ ...groupTools({} as never),+ ...webhookTools({} as never),+ ];++ const sessionScoped = allTools.filter(t => t.sessionScoped === true);++ it('has sessionScoped tools to check (the guard is meaningful)', () => {+ expect(sessionScoped.length).toBeGreaterThan(0);+ });++ it.each(sessionScoped.map(t => [t.name, t] as const))(+ '%s rejects a missing and an empty sessionId',+ (_name, tool) => {+ // Isolate the sessionId field so a tool's OTHER required fields can't mask a weakened sessionId rule.+ const shape = (tool.inputSchema as unknown as z.ZodObject<{ sessionId: z.ZodType }>).shape;+ const sessionIdSchema: z.ZodType = shape.sessionId;+ expect(sessionIdSchema).toBeDefined();+ expect(sessionIdSchema.safeParse(undefined).success).toBe(false);+ expect(sessionIdSchema.safeParse('').success).toBe(false);+ },+ );+});diff --git a/src/core/plugins/plugin-loader.service.spec.ts b/src/core/plugins/plugin-loader.service.spec.tsindex c7ca0256f..1f4736331 100644--- a/src/core/plugins/plugin-loader.service.spec.ts+++ b/src/core/plugins/plugin-loader.service.spec.ts@@ -75,7 +75,7 @@ import { ConfigService } from '@nestjs/config';import { ModuleRef } from '@nestjs/core';import { HookManager } from '../hooks';import { PluginStorageService } from './plugin-storage.service';-import { IPlugin, PluginManifest, PluginStatus, PluginType } from './plugin.interfaces';+import { IPlugin, PluginContext, PluginManifest, PluginStatus, PluginType } from './plugin.interfaces';describe('PluginLoaderService.registerBuiltInPlugin config', () => {function makeLoader(): PluginLoaderService {@@ -372,3 +372,45 @@ describe('PluginLoaderService — graceful shutdown (onModuleDestroy)', () => {expect(loader.getPlugin('ok-plg')?.status).toBe(PluginStatus.DISABLED);});});++describe('PluginLoaderService — enable-failure hook cleanup', () => {+ let tmpDir: string;+ let hooks: HookManager;+ let loader: PluginLoaderService;++ beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-enfail-'));+ const config = { get: (k: string) => (k === 'dataDir' ? tmpDir : undefined) } as unknown as ConfigService;+ hooks = new HookManager();+ loader = new PluginLoaderService(config, hooks, new PluginStorageService(config), {} as unknown as ModuleRef);+ });+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));++ it('does not leak hook registrations when an enable attempt fails, so a later enable does not double-dispatch', async () => {+ let shouldThrow = true;+ const instance = {+ onEnable: (ctx: PluginContext): Promise<void> => {+ // The plugin subscribes a hook, then its enable fails (e.g. a transient connect timeout).+ ctx.registerHook('message:received', () => Promise.resolve({ continue: true }));+ return shouldThrow ? Promise.reject(new Error('transient onEnable failure')) : Promise.resolve();+ },+ } as unknown as IPlugin;+ loader.registerBuiltInPlugin(+ { id: 'flaky-plg', name: 'Flaky', version: '1.0.0', type: PluginType.EXTENSION, main: 'index.js' },+ instance,+ );++ // First enable fails AFTER the hook was registered → the registration must not survive.+ await expect(loader.enablePlugin('flaky-plg')).rejects.toThrow(/transient/);+ expect(loader.getPlugin('flaky-plg')?.status).toBe(PluginStatus.ERROR);++ // Retry succeeds.+ shouldThrow = false;+ await loader.enablePlugin('flaky-plg');+ expect(loader.getPlugin('flaky-plg')?.status).toBe(PluginStatus.ENABLED);++ // Exactly one handler — the failed attempt left nothing behind. Without cleanup this is 2,+ // and every message:received would dispatch to the plugin twice.+ expect(hooks.getHookCount('message:received')).toBe(1);+ });+});diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.tsindex 2b69d894a..1b74a1dd5 100644--- a/src/core/plugins/plugin-loader.service.ts+++ b/src/core/plugins/plugin-loader.service.ts@@ -311,6 +311,13 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {this.pluginStorage.setPluginStatus(pluginId, PluginStatus.ERROR);+ // A plugin that subscribed hooks before its onLoad/onEnable threw would otherwise leave those+ // registrations live: a later successful enable re-registers them, so each event then dispatches+ // to the plugin once per failed attempt. Drop them here. Safe on this path only — an+ // already-enabled plugin returns early above, so the catch only runs for an enable that never+ // went live, which owns no hooks worth keeping. (Idempotent: no-ops when none were registered.)+ this.hookManager.unregisterPlugin(pluginId);+throw error;} finally {this.enabling.delete(pluginId);diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 7e9bd5598..07b159c6a 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -561,10 +561,11 @@ describe('BaileysAdapter messaging', () => {expect(res).toEqual({ id: 'OUT1', timestamp: 1700000001 });});- it('getNumberId resolves via onWhatsApp and returns the jid when it exists', async () => {+ it('getNumberId resolves via onWhatsApp and returns a NEUTRAL jid (never @s.whatsapp.net)', async () => {fakeSock.onWhatsApp.mockResolvedValue([{ jid: '[email protected]', exists: true }]);const adapter = await readyAdapter();- await expect(adapter.getNumberId('628111')).resolves.toBe('[email protected]');+ // Must cross the engine boundary in the neutral dialect, matching whatsapp-web.js (<phone>@c.us).+ await expect(adapter.getNumberId('628111')).resolves.toBe('[email protected]');await expect(adapter.checkNumberExists('628111')).resolves.toBe(true);});diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex 546b67074..153e0f7d5 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -488,7 +488,10 @@ export class BaileysAdapter implements IWhatsAppEngine {this.ensureReady();const results = await this.sock!.onWhatsApp(number);const hit = results?.[0];- return hit?.exists ? hit.jid : null;+ // Baileys returns a raw `<phone>@s.whatsapp.net`; neutralize it before it crosses the engine+ // boundary so the value matches whatsapp-web.js (`<phone>@c.us`) and the IWhatsAppEngine contract+ // (no raw `@s.whatsapp.net` in a neutral field). It also round-trips back to a send on either engine.+ return hit?.exists ? this.sessionStore.toNeutralJid(hit.jid) : null;}async sendChatState(chatId: string, state: ChatState): Promise<void> {diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex 64f0351f2..738e811d2 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -421,8 +421,9 @@ export interface IWhatsAppEngine {getContactById(contactId: string): Promise<Contact | null>;checkNumberExists(number: string): Promise<boolean>;/**- * Resolve a phone number to its canonical chat id in the engine's native format, or null if the- * number is not registered. The engine owns the JID scheme, so callers never build it themselves.+ * Resolve a phone number to its canonical chat id in the neutral dialect (`<phone>@c.us`), or null+ * if the number is not registered. The engine owns the JID scheme and returns it already neutralized,+ * so the value is engine-agnostic and round-trips back to a send on any engine.*/getNumberId(number: string): Promise<string | null>;/**diff --git a/src/main.ts b/src/main.tsindex 9ab3bdfa1..861bef596 100644--- a/src/main.ts+++ b/src/main.ts@@ -162,7 +162,9 @@ async function bootstrap() {// allow those origins or the @import'd fonts are blocked and the UI falls back to system fonts.styleSrc: ["'self'", "'unsafe-inline'", 'https://fonts.googleapis.com'],scriptSrc: ["'self'"],- imgSrc: ["'self'", 'data:', 'https:'],+ // `blob:` is needed for the outgoing image-attachment preview, which the dashboard renders+ // from a URL.createObjectURL(file) blob before the message is sent (Chats.tsx).+ imgSrc: ["'self'", 'data:', 'blob:', 'https:'],// Chat media (voice notes, video) is served to the dashboard as data: URIs. Without an// explicit media-src, <audio>/<video> fall back to default-src 'self' and are blocked.// Mirror imgSrc so audio/video render the same way images already do.diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.tsindex d90a123ad..a3ba43004 100644--- a/src/modules/events/events.gateway.spec.ts+++ b/src/modules/events/events.gateway.spec.ts@@ -138,6 +138,65 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {expect(res.events).toEqual(['message.received']);expect(sock.join).toHaveBeenCalledWith(buildRoomName('sess-1', 'message.received'));});++ // Cross-tenant guard (#221): a session-scoped key must not subscribe to a foreign session or '*'.+ // The pure predicate is covered above; these drive it through handleSubscribe so a regression that+ // drops the check (or reads the stale connect-time key) is caught end-to-end.+ it('forbids a session-scoped key from subscribing to a session outside its allowlist', async () => {+ authService.validateApiKey.mockResolvedValue({ name: 'k', allowedSessions: ['sess-1'] });+ const sock = makeSocket({ apiKey: 'good' });+ await gateway.handleConnection(asSocket(sock));++ const res = (await gateway.handleMessage(asSocket(sock), subscribeMsg('sess-2', ['*']))) as WSErrorResponse;++ expect(res.type).toBe('error');+ expect(res.code).toBe('FORBIDDEN_SESSION');+ expect(sock.join).not.toHaveBeenCalled();+ });++ it('forbids a session-scoped key from subscribing to the * wildcard', async () => {+ authService.validateApiKey.mockResolvedValue({ name: 'k', allowedSessions: ['sess-1'] });+ const sock = makeSocket({ apiKey: 'good' });+ await gateway.handleConnection(asSocket(sock));++ const res = (await gateway.handleMessage(+ asSocket(sock),+ subscribeMsg('*', ['message.received']),+ )) as WSErrorResponse;++ expect(res.code).toBe('FORBIDDEN_SESSION');+ expect(sock.join).not.toHaveBeenCalled();+ });++ it('allows a session-scoped key to subscribe to a session in its allowlist', async () => {+ authService.validateApiKey.mockResolvedValue({ name: 'k', allowedSessions: ['sess-1'] });+ const sock = makeSocket({ apiKey: 'good' });+ await gateway.handleConnection(asSocket(sock));++ const res = (await gateway.handleMessage(+ asSocket(sock),+ subscribeMsg('sess-1', ['message.received']),+ )) as WSSubscribedResponse;++ expect(res.type).toBe('subscribed');+ expect(sock.join).toHaveBeenCalledWith(buildRoomName('sess-1', 'message.received'));+ });++ it('enforces scope using the FRESH re-validated key, not the connect-time key', async () => {+ // Connect with an unrestricted key, but the key is narrowed to ['sess-1'] by the subscribe re-check.+ authService.validateApiKey.mockResolvedValueOnce({ name: 'k', allowedSessions: null }); // connect+ const sock = makeSocket({ apiKey: 'good' });+ await gateway.handleConnection(asSocket(sock));++ authService.validateApiKey.mockResolvedValueOnce({ name: 'k', allowedSessions: ['sess-1'] }); // subscribe re-check+ const res = (await gateway.handleMessage(+ asSocket(sock),+ subscribeMsg('sess-2', ['message.received']),+ )) as WSErrorResponse;++ expect(res.code).toBe('FORBIDDEN_SESSION');+ expect(sock.join).not.toHaveBeenCalled();+ });});// A capturing, chainable Socket.IO server stub: server.to(r1).to(r2)...emit(...) alldiff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex 45f2ec8c5..894f0adde 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -303,9 +303,11 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate}/**- * Emit a live delivery-status update (neutral DeliveryStatus, e.g. delivered/read/failed).+ * Emit a live delivery-status update. The payload mirrors the `message.ack` webhook exactly+ * (`id`, `messageId`, neutral `status`, and the deprecated legacy numeric `ack`) so a socket+ * client and a webhook consumer see the same shape.*/- emitMessageAck(sessionId: string, data: { messageId: string; status: DeliveryStatus }) {+ emitMessageAck(sessionId: string, data: { id: string; messageId: string; status: DeliveryStatus; ack: number }) {this.emitToRooms(sessionId, 'message.ack', data);}diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.tsindex d3fe76504..21cf85b60 100644--- a/src/modules/infra/infra.controller.spec.ts+++ b/src/modules/infra/infra.controller.spec.ts@@ -36,6 +36,7 @@ import { Message, MessageDirection, MessageStatus } from '../message/entities/meimport { MessageBatch, BatchStatus } from '../message/entities/message-batch.entity';import { Template } from '../template/entities/template.entity';import { BaileysStoredMessage } from '../../engine/adapters/baileys-stored-message.entity';+import { LidMapping } from '../../engine/identity/lid-mapping.entity';describe('InfraController access control (Vuln 2)', () => {const reflector = new Reflector();@@ -469,7 +470,7 @@ describe('InfraController.import/export preserves every data-DB table', () => {ds = new DataSource({type: 'sqlite',database: ':memory:',- entities: [Session, Webhook, Message, MessageBatch, Template, BaileysStoredMessage],+ entities: [Session, Webhook, Message, MessageBatch, Template, BaileysStoredMessage, LidMapping],synchronize: true,});await ds.initialize();@@ -496,6 +497,28 @@ describe('InfraController.import/export preserves every data-DB table', () => {}),);+ // lid_mappings is the persisted lid->phone cache; it is NOT a FK to sessions, so the sessions DELETE+ // never touches it — but export omitted it, so a backup→restore into a fresh DB dropped it entirely.+ it('restores lid_mappings instead of dropping them on a backup→restore', async () => {+ await seedSession('s1');+ const lidRepo = ds.getRepository(LidMapping);+ await lidRepo.save(lidRepo.create({ lid: '111', phone: '628111', sessionId: 's1' }));+ await lidRepo.save(lidRepo.create({ lid: '222', phone: null, sessionId: 's1' })); // negative cache++ const dump = await controller.exportData();+ expect((dump.tables as unknown as { lidMappings?: unknown[] }).lidMappings).toHaveLength(2);++ // Simulate restoring into a fresh data DB (the documented backend-migration flow).+ await lidRepo.clear();+ const res = await controller.importData({ tables: dump.tables });++ expect(res.warnings).toEqual([]);+ expect(res.imported).toBe(true);+ expect(await lidRepo.count()).toBe(2);+ expect((await lidRepo.findOneByOrFail({ lid: '111' })).phone).toBe('628111');+ expect((await lidRepo.findOneByOrFail({ lid: '222' })).phone).toBeNull();+ });+// 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 () => {diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.tsindex efe204291..ed5b5ed50 100644--- a/src/modules/infra/infra.controller.ts+++ b/src/modules/infra/infra.controller.ts@@ -160,6 +160,16 @@ interface BaileysStoredMessageRow {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 MigrationTables {sessions: SessionRow[];webhooks: WebhookRow[];@@ -167,6 +177,7 @@ interface MigrationTables {messageBatches: MessageBatchRow[];templates: TemplateRow[];baileysStoredMessages: BaileysStoredMessageRow[];+ lidMappings: LidMappingRow[];}// Saved infrastructure config returned to the dashboard form for hydration. Secret@@ -641,6 +652,7 @@ export class InfraController {messageBatches: number;templates: number;baileysStoredMessages: number;+ lidMappings: number;};}> {// Get all entities from Data DB@@ -652,6 +664,7 @@ export class InfraController {let messageBatches: MessageBatchRow[] = [];let templates: TemplateRow[] = [];let baileysStoredMessages: BaileysStoredMessageRow[] = [];+ let lidMappings: LidMappingRow[] = [];try {messages = await this.dataDataSource.query<MessageRow[]>('SELECT * FROM messages');@@ -679,6 +692,12 @@ export class InfraController {this.logger.debug('Baileys stored messages table not available for export', { error: String(error) });}+ try {+ lidMappings = await this.dataDataSource.query<LidMappingRow[]>('SELECT * FROM lid_mappings');+ } catch (error) {+ this.logger.debug('Lid mappings table not available for export', { error: String(error) });+ }+return {exportedAt: new Date().toISOString(),dataDbType: this.configService.get<string>('dataDatabase.type', 'sqlite'),@@ -689,6 +708,7 @@ export class InfraController {messageBatches,templates,baileysStoredMessages,+ lidMappings,},counts: {sessions: sessions.length,@@ -697,6 +717,7 @@ export class InfraController {messageBatches: messageBatches.length,templates: templates.length,baileysStoredMessages: baileysStoredMessages.length,+ lidMappings: lidMappings.length,},};}@@ -736,6 +757,7 @@ export class InfraController {messageBatches: number;templates: number;baileysStoredMessages: number;+ lidMappings: number;};warnings: string[];}> {@@ -754,6 +776,9 @@ export class InfraController {await queryRunner.query('DELETE FROM message_batches').catch(() => {});await queryRunner.query('DELETE FROM templates').catch(() => {});await queryRunner.query('DELETE FROM baileys_stored_messages').catch(() => {});+ // lid_mappings is not a FK to sessions, so the sessions DELETE below won't clear it; clear it+ // explicitly so a restore replaces the cache rather than colliding on existing lid PKs.+ await queryRunner.query('DELETE FROM lid_mappings').catch(() => {});await queryRunner.query('DELETE FROM sessions');// Import sessions first@@ -941,6 +966,22 @@ export class InfraController {}}+ // Import lid mappings (optional; not a FK, restored as a standalone cache table)+ let lidMappingsCount = 0;+ if (data.tables.lidMappings?.length) {+ for (const lm of data.tables.lidMappings) {+ try {+ await queryRunner.query(+ `INSERT INTO lid_mappings (lid, phone, "sessionId", "updatedAt") VALUES ($1, $2, $3, $4)`,+ [lm.lid, lm.phone ?? null, lm.sessionId ?? null, lm.updatedAt],+ );+ lidMappingsCount++;+ } catch (err) {+ warnings.push(`Failed to import lid mapping ${lm.lid}: ${err}`);+ }+ }+ }+const counts = {sessions: sessionsCount,webhooks: webhooksCount,@@ -948,6 +989,7 @@ export class InfraController {messageBatches: messageBatchesCount,templates: templatesCount,baileysStoredMessages: baileysStoredMessagesCount,+ lidMappings: lidMappingsCount,};// "Replace all data" must be all-or-nothing: the import already DELETEd every row, so if anydiff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex e9bd69c86..6ebbdacd6 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -504,6 +504,30 @@ describe('SessionService', () => {jest.useRealTimers();}});++ it('does not stack reconnect timers when scheduled twice back-to-back', () => {+ jest.useFakeTimers();+ try {+ const i = service as unknown as {+ reconnectStates: Map<+ string,+ { attempts: number; timer: NodeJS.Timeout | null; maxAttempts: number; baseDelay: number }+ >;+ scheduleReconnect: (id: string, s: Session) => void;+ };+ i.reconnectStates.set('sess-uuid-1', { attempts: 0, timer: null, maxAttempts: 5, baseDelay: 5000 });++ // Two disconnect events in a row each schedule a reconnect. The second must clear the+ // first timer, leaving exactly one pending — otherwise both fire and double-init the engine.+ i.scheduleReconnect('sess-uuid-1', createMockSession());+ i.scheduleReconnect('sess-uuid-1', createMockSession());++ expect(jest.getTimerCount()).toBe(1);+ } finally {+ jest.clearAllTimers();+ jest.useRealTimers();+ }+ });});describe('engine onError', () => {@@ -556,6 +580,25 @@ describe('SessionService', () => {expect(result.lastError).toBeUndefined();});++ it('cancels a pending reconnect timer when the engine then errors terminally', async () => {+ const callbacks = await startAndCapture();+ jest.useFakeTimers();+ try {+ const i = service as unknown as { scheduleReconnect: (id: string, s: Session) => void };+ // A prior onDisconnected scheduled a reconnect…+ i.scheduleReconnect('sess-uuid-1', createMockSession());+ expect(jest.getTimerCount()).toBe(1);++ // …then a terminal failure arrives. It must cancel the pending reconnect so the timer+ // can't resurrect a session the operator has to manually restart.+ callbacks.onError?.('fatal browser crash');+ expect(jest.getTimerCount()).toBe(0);+ } finally {+ jest.clearAllTimers();+ jest.useRealTimers();+ }+ });});// ── engine-identity guard: stale-callback isolation ───────────────@@ -777,6 +820,22 @@ describe('SessionService', () => {expect(dispatchedEvents('message.sent')).toHaveLength(0);});+ it('emits an identical message.ack payload over the socket and the webhook (parity)', async () => {+ const callbacks = await startAndCaptureCallbacks();++ callbacks.onMessageAck!('wa-out-1', 'read');+ await flush();++ const ackCalls = (eventsGateway.emitMessageAck as jest.Mock).mock.calls as unknown[][];+ const socketPayload = ackCalls[0][1] as Record<string, unknown>;+ const webhookPayload = dispatchedEvents('message.ack')[0][2] as Record<string, unknown>;++ // A socket client coded against the webhook/doc ack shape must see the same fields.+ expect(socketPayload).toEqual(webhookPayload);+ expect(socketPayload).toMatchObject({ id: 'wa-out-1', messageId: 'wa-out-1', status: 'read' });+ expect(socketPayload.ack).toBeDefined();+ });+it("reflects delivery on the stored message: 'delivered' updates status to DELIVERED (#220)", async () => {const callbacks = await startAndCaptureCallbacks();diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 3f517c2af..d86b9becf 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -792,29 +792,24 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat.catch(onAckError);}- // Push the live delivery/read tick to the dashboard over the websocket (neutral status).- this.eventsGateway.emitMessageAck(id, { messageId, status });+ // One ack payload, emitted identically over the socket and the webhook so a client coded+ // against either channel sees the same shape. `id` mirrors the field every other message.*+ // event carries (and the idempotency-key resolver reads). `ack` is a deprecated legacy field+ // kept for backward compatibility — new consumers should read the neutral `status`.+ const ackPayload = { id: messageId, messageId, status, ack: deliveryStatusToAck(status) };++ // Push the live delivery/read tick to the dashboard over the websocket.+ this.eventsGateway.emitMessageAck(id, ackPayload);// Dispatch the delivery/read receipt to webhooks (#155). Outgoing `message.sent` is handled// solely by `onMessageCreate`, so the ack path deliberately does NOT emit `message.sent`.- // `id` mirrors the field every other message.* webhook carries (and the idempotency key- // resolver reads). `ack` is a deprecated legacy field kept for backward compatibility —- // new consumers should read the neutral `status`.- void this.webhookService.dispatch(id, 'message.ack', {- id: messageId,- messageId,- status,- ack: deliveryStatusToAck(status),- });+ void this.webhookService.dispatch(id, 'message.ack', ackPayload);- // Surface delivery failures actively so consumers don't have to poll for them (#220).+ // Surface delivery failures actively so consumers don't have to poll for them (#220). Use a+ // distinct object (not the shared ackPayload) so this separate event can't be perturbed by an+ // in-place payload mutation in the concurrent message.ack dispatch's webhook:before hook.if (status === 'failed') {- void this.webhookService.dispatch(id, 'message.failed', {- id: messageId,- messageId,- status,- ack: deliveryStatusToAck(status),- });+ void this.webhookService.dispatch(id, 'message.failed', { ...ackPayload });}// Notify plugins of the delivery/read receipt. The `message:ack` hook event was declared in@@ -926,6 +921,11 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// scheduled (unlike onDisconnected), since re-scanning is required.this.sessionErrors.set(id, reason);+ // A prior onDisconnected may have scheduled a reconnect. This failure is terminal+ // (re-scan required), so cancel it — otherwise the pending timer would resurrect a+ // session the operator must manually restart.+ this.cancelReconnect(id);+void this.hookManager.execute('session:error',{ reason },@@ -1005,6 +1005,9 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat},);+ // Clear any timer a prior scheduleReconnect left pending so two back-to-back disconnects+ // don't stack two timers (which would run executeReconnect twice and double-init the engine).+ if (state.timer) clearTimeout(state.timer);state.timer = setTimeout(() => {void this.executeReconnect(id, session, state);}, delay);diff --git a/src/modules/stats/stats.service.spec.ts b/src/modules/stats/stats.service.spec.tsindex e517bcd29..ab669451f 100644--- a/src/modules/stats/stats.service.spec.ts+++ b/src/modules/stats/stats.service.spec.ts@@ -108,6 +108,45 @@ describe('StatsService time-series + hourly activity on SQLite (end-to-end regre}});+ it('no analytics query groups/orders by a bare reserved word — on the Postgres dialect shape too', async () => {+ await ds+ .getRepository(Session)+ .save(ds.getRepository(Session).create({ id: 's1', name: 'n', status: SessionStatus.READY, config: {} }));+ await seedMessage({ direction: MessageDirection.OUTGOING });++ // Force the Postgres SQL shape and capture the generated SQL WITHOUT executing (SQLite can't run+ // to_char/EXTRACT). groupBy/orderBy arguments are emitted verbatim, so this sweeps every grouped+ // analytics query for a reserved-word alias on the dialect the SQLite test DB can't exercise —+ // the exact #476 blindness class, extended beyond the single time-series query.+ // Shadow the (prototype) getter on this fresh per-test instance so it can't leak to other tests.+ Object.defineProperty(service, 'dataDbType', { get: () => 'postgres', configurable: true });++ const captured: string[] = [];+ const repo = ds.getRepository(Message);+ const origCreate = repo.createQueryBuilder.bind(repo);+ jest.spyOn(repo, 'createQueryBuilder').mockImplementation((alias?: string) => {+ const qb = origCreate(alias);+ jest.spyOn(qb, 'getRawMany').mockImplementation(() => {+ captured.push(qb.getQuery());+ return Promise.resolve([]);+ });+ return qb;+ });++ await service.getMessageStats('24h'); // time-series (bucket) + byType + bySession + topChats+ await service.getSessionStats('s1'); // hourly activity (hour)++ expect(captured.length).toBeGreaterThan(0);+ // A small set of PostgreSQL reserved type/keywords that a naive alias could collide with.+ const PG_RESERVED = ['timestamp', 'user', 'order', 'end', 'all', 'column', 'table'];+ for (const sql of captured) {+ for (const kw of PG_RESERVED) {+ expect(sql).not.toMatch(new RegExp(`GROUP BY\\s+["']?${kw}["']?\\s*(,|$|\\s)`, 'i'));+ expect(sql).not.toMatch(new RegExp(`ORDER BY\\s+["']?${kw}["']?\\s*(,|$|\\s|ASC|DESC)`, 'i'));+ }+ }+ });+it('getSessionStats returns 24 hourly buckets with the right counts', async () => {await ds.getRepository(Session)