Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
Reliability and correctness hardening batch (7 fixes) (#689)
Yudhi Armyndharis3143c8218cca
diff --git a/.github/workflows/sdk-ci.yml b/.github/workflows/sdk-ci.ymlindex c5bd4c3b4..c364e17f0 100644--- a/.github/workflows/sdk-ci.yml+++ b/.github/workflows/sdk-ci.yml@@ -7,10 +7,10 @@ name: SDK CIon:push:branches: [main, develop]- paths: ['sdk/**', '.github/workflows/sdk-ci.yml', 'src/**/dto/**', 'src/engine/interfaces/whatsapp-engine.interface.ts']+ paths: ['sdk/**', '.github/workflows/sdk-ci.yml', 'src/**/dto/**', 'src/**/*.controller.ts', 'src/**/*.service.ts', 'src/engine/interfaces/whatsapp-engine.interface.ts']pull_request:branches: [main, develop]- paths: ['sdk/**', '.github/workflows/sdk-ci.yml', 'src/**/dto/**', 'src/engine/interfaces/whatsapp-engine.interface.ts']+ paths: ['sdk/**', '.github/workflows/sdk-ci.yml', 'src/**/dto/**', 'src/**/*.controller.ts', 'src/**/*.service.ts', 'src/engine/interfaces/whatsapp-engine.interface.ts']jobs:javascript:diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bc8666042..aa678e190 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **Dashboard Korean (ko) locale polish.** Refined several ko strings for consistency, fluency, and accuracy (follow-up to #679): "Create New Session" → `새 세션 생성` (aligns with `생성` used elsewhere in the create flow); the plugin "Configuration" tab → `설정` (matches the rest of the config UI); "Start messaging" → `대화 시작하기` (idiomatic — in Korean one starts a conversation, not a "message"); the WhatsApp Web build "current known-good" now reads `현재` instead of `최신` (latest), which had inverted the version-pinning intent; the "New" session status → `신규` (the conventional Korean status label); and the template placeholder example re-phrases the `{{orderId}}` clause so the interpolation reads naturally.+- **Reliability and correctness hardening batch.** A set of fixes across the engine, session, auth, infra, dashboard, and SDK layers:+ - The inbound media concurrency limiter now bounds its waiter queue and rejects when full; both engines route a rejected download to their existing emit-without-media path, so a burst of inbound media can no longer grow heap without bound.+ - `start()` now cancels any pending reconnect timer before recreating the engine, so a stale timer left by a failed reconnect can no longer destroy the engine or orphan the Chromium process.+ - The dashboard chat thread now refetches after a WebSocket reconnect, so messages that arrived during a transient gap (and ack/reaction/revoke updates) are no longer silently missing until the chat is reopened.+ - Updating an API key's role, allowed sessions, allowed IPs, or expiry now disconnects the key's already-connected WebSocket sockets, so a narrowed key stops streaming realtime events for sessions/IPs it just lost. A benign rename leaves connected sockets alone.+ - The SQLite→PostgreSQL export/import path now covers every data-owned table (plugin instances + ingress HMAC secrets, conversation mappings, ingress events, both dead-letter queues) instead of only seven, so a migration no longer silently drops the Integration Fabric and the DLQs. The main connection (API keys, audit logs) stays excluded; existing seven-table exports still import unchanged.+ - The bundled `docker-compose.yml` no longer shadows dashboard-saved Puppeteer headless / session-data-path / browser-args with pinned container defaults — those are blank-forwarded so a dashboard (or `data/.env.generated`) selection applies, with the sane container defaults supplied by the application config layer (headless, `./data/sessions`, the full `--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage --disable-gpu` flag set). **Upgrade note:** if you previously saved engine config in the dashboard, re-save it (or set `PUPPETEER_ARGS`) so the full Docker sandbox flag set is retained.+ - The PHP SDK `messages.list()` and `catalog.products()` docblocks now match the real `{messages, total}` / `{products, pagination}` envelopes the server returns (consistent with the JS/Python/Java SDKs), and the SDK CI path-filter now covers backend controllers and services so response-shape drift re-runs the SDK suites.+## [0.8.14] - 2026-07-10### Addeddiff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxindex 5df8679bb..ff08a44eb 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -1,6 +1,7 @@import { useState, useEffect, useCallback, useRef, useMemo, useLayoutEffect } from 'react';import { useQueryClient } from '@tanstack/react-query';import { Trans, useTranslation } from 'react-i18next';+import { nextReconnectState } from '../utils/reconnectState';import {Search,Send,@@ -357,6 +358,25 @@ export function Chats() {onMessageRevoked: handleIncomingMessageRevoked,});+ // A transient WebSocket gap means message.received/ack/revoke events were missed, and the chat+ // cache uses staleTime: Infinity so it won't refetch on its own. On a reconnect (isConnected+ // false→true after a prior connect), invalidate the active session's messages so the thread the+ // gap left stale refreshes. The transition logic is unit-tested in utils/reconnectState.+ const reconnectHadConnected = useRef(false);+ const reconnectWasDisconnected = useRef(false);+ useEffect(() => {+ const decision = nextReconnectState({+ isConnected,+ hadConnected: reconnectHadConnected.current,+ wasDisconnected: reconnectWasDisconnected.current,+ });+ reconnectHadConnected.current = decision.hadConnected;+ reconnectWasDisconnected.current = decision.wasDisconnected;+ if (decision.invalidate) {+ queryClient.invalidateQueries({ queryKey: ['messages', selectedSessionId] });+ }+ }, [isConnected, selectedSessionId, queryClient]);+useEffect(() => {if (selectedSessionId && isConnected) {subscribe(selectedSessionId, [diff --git a/dashboard/src/pages/Infrastructure.tsx b/dashboard/src/pages/Infrastructure.tsxindex 18e20a3fa..0ee32a2e7 100644--- a/dashboard/src/pages/Infrastructure.tsx+++ b/dashboard/src/pages/Infrastructure.tsx@@ -132,7 +132,7 @@ export function Infrastructure() {type: 'whatsapp-web.js',headless: true,sessionDataPath: './data/sessions',- browserArgs: '--no-sandbox --disable-gpu',+ browserArgs: '--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage --disable-gpu',});const [redisEnabled, setRedisEnabled] = useState(false);diff --git a/dashboard/src/utils/reconnectState.test.ts b/dashboard/src/utils/reconnectState.test.tsnew file mode 100644index 000000000..8dfedb8b6--- /dev/null+++ b/dashboard/src/utils/reconnectState.test.ts@@ -0,0 +1,38 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { nextReconnectState } from './reconnectState.ts';++test('initial connect (never connected before): no invalidate', () => {+ assert.deepEqual(+ nextReconnectState({ isConnected: true, hadConnected: false, wasDisconnected: false }),+ { invalidate: false, hadConnected: true, wasDisconnected: false },+ );+});++test('disconnect before any connect (noise): no gap marked, no invalidate', () => {+ assert.deepEqual(+ nextReconnectState({ isConnected: false, hadConnected: false, wasDisconnected: false }),+ { invalidate: false, hadConnected: false, wasDisconnected: false },+ );+});++test('disconnect after the first connect: mark a gap, no invalidate', () => {+ assert.deepEqual(+ nextReconnectState({ isConnected: false, hadConnected: true, wasDisconnected: false }),+ { invalidate: false, hadConnected: true, wasDisconnected: true },+ );+});++test('reconnect after a gap (wasDisconnected): invalidate', () => {+ assert.deepEqual(+ nextReconnectState({ isConnected: true, hadConnected: true, wasDisconnected: true }),+ { invalidate: true, hadConnected: true, wasDisconnected: false },+ );+});++test('stays connected: no invalidate, stays hadConnected', () => {+ assert.deepEqual(+ nextReconnectState({ isConnected: true, hadConnected: true, wasDisconnected: false }),+ { invalidate: false, hadConnected: true, wasDisconnected: false },+ );+});diff --git a/dashboard/src/utils/reconnectState.ts b/dashboard/src/utils/reconnectState.tsnew file mode 100644index 000000000..5bd2eadb2--- /dev/null+++ b/dashboard/src/utils/reconnectState.ts@@ -0,0 +1,41 @@+export interface ReconnectState {+ isConnected: boolean;+ hadConnected: boolean;+ wasDisconnected: boolean;+}++export interface ReconnectDecision {+ invalidate: boolean;+ hadConnected: boolean;+ wasDisconnected: boolean;+}++/**+ * Pure state transition that detects a WebSocket RECONNECT — a connect that follows a disconnect+ * after the initial connection. Extracted from the component so the transition is unit-testable+ * independent of React/socket.io.+ *+ * A reconnect means realtime events (message.received/ack/revoke) were missed during the gap. The+ * chat message cache uses staleTime:Infinity, so it won't refetch on its own; the caller invalidates+ * on `invalidate: true` to force a refresh of the thread the gap left stale.+ *+ * - First connect (hadConnected false): no invalidate — nothing is cached yet to refresh.+ * - Disconnect after the first connect: mark a gap (wasDisconnected), no invalidate.+ * - Connect with a marked gap: RECONNECT — invalidate, then clear the gap marker.+ * - Disconnect before any connect (transient noise on mount): no gap marked (avoid a spurious first-+ * connect invalidate if isConnected toggles false→true before the real first connect).+ */+export function nextReconnectState(state: ReconnectState): ReconnectDecision {+ if (state.isConnected) {+ return {+ invalidate: state.wasDisconnected,+ hadConnected: true,+ wasDisconnected: false,+ };+ }+ return {+ invalidate: false,+ hadConnected: state.hadConnected,+ wasDisconnected: state.hadConnected,+ };+}diff --git a/docker-compose.yml b/docker-compose.ymlindex 40039f2d2..915c48632 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -118,9 +118,14 @@ services:# ENGINE_TYPE as unset, so .env.generated wins. Set ENGINE_TYPE in your .env/host to pin an# engine (e.g. baileys) — a real value flows through here and keeps top precedence.- ENGINE_TYPE=${ENGINE_TYPE:-}- - SESSION_DATA_PATH=${SESSION_DATA_PATH:-/app/data/sessions}- - PUPPETEER_HEADLESS=${PUPPETEER_HEADLESS:-true}- - PUPPETEER_ARGS=${PUPPETEER_ARGS:---no-sandbox,--disable-setuid-sandbox,--disable-dev-shm-usage,--disable-gpu}+ # Engine launch options (session data path, headless, browser args). Forwarded EMPTY by default+ # so the dashboard (Infrastructure > Engine) selections saved to data/.env.generated apply — like+ # ENGINE_TYPE above. main.ts treats a blank value as unset (.env.generated wins), and the app+ # layer (configuration.ts) supplies the sane container default (headless, ./data/sessions, the+ # sandbox + no-dev-shm flag set) when nothing is set anywhere. Set one on the host/.env to pin it.+ - SESSION_DATA_PATH=${SESSION_DATA_PATH:-}+ - PUPPETEER_HEADLESS=${PUPPETEER_HEADLESS:-}+ - PUPPETEER_ARGS=${PUPPETEER_ARGS:-}# Optional WhatsApp Web version override. Leave empty for whatsapp-web.js auto-selection.# If a session hangs at "authenticating", set WWEBJS_WEB_VERSION to a known-good cached build# from wppconnect-team/wa-version; latest|auto|off also forces auto-selection.diff --git a/sdk/php/src/Resources/CatalogResource.php b/sdk/php/src/Resources/CatalogResource.phpindex 58f26a025..d5594d6b3 100644--- a/sdk/php/src/Resources/CatalogResource.php+++ b/sdk/php/src/Resources/CatalogResource.php@@ -30,14 +30,17 @@ class CatalogResource}/**- * List catalog products (paginated).+ * List catalog products (paginated). Returns a page shaped+ * {products: list, pagination: {page, limit, total, totalPages}} — iterate over the `products`+ * field, not the result itself. Consistent with the JavaScript, Python, and Java SDKs.** @param array<string,mixed> $query e.g. ['page' => 1, 'limit' => 20].- * @return array<int,array<string,mixed>>+ * @return array{products: array<int,array<string,mixed>>, pagination: array<string,mixed>}*/public function products(string $sessionId, array $query = []): array{- return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/catalog/products", $query) ?? [];+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/catalog/products", $query)+ ?? ['products' => [], 'pagination' => []];}/** @return array<string,mixed> */diff --git a/sdk/php/src/Resources/MessagesResource.php b/sdk/php/src/Resources/MessagesResource.phpindex 764f1bb1d..0c698bef8 100644--- a/sdk/php/src/Resources/MessagesResource.php+++ b/sdk/php/src/Resources/MessagesResource.php@@ -22,12 +22,17 @@ class MessagesResource}/**+ * List messages, optionally filtered by chat or sender. Returns a page shaped+ * {messages: list, total: count} — iterate over the `messages` field, not the+ * result itself. Consistent with the JavaScript, Python, and Java SDKs.+ ** @param array<string,mixed> $query- * @return array<int,array<string,mixed>>+ * @return array{messages: array<int,array<string,mixed>>, total: int}*/public function list(string $sessionId, array $query = []): array{- return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages", $query) ?? [];+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages", $query)+ ?? ['messages' => [], 'total' => 0];}/**diff --git a/sdk/php/tests/MessagesTest.php b/sdk/php/tests/MessagesTest.phpindex ed9fe9677..b863edc30 100644--- a/sdk/php/tests/MessagesTest.php+++ b/sdk/php/tests/MessagesTest.php@@ -20,6 +20,24 @@ class MessagesTest extends TestCase$this->assertSame(['chatId' => '[email protected]', 'text' => 'hi'], $call['body']);}+ public function testListReturnsMessagesPageEnvelope(): void+ {+ // The server responds with a {messages, total} page, not a flat array. Pin the shape so a+ // future change — or a misunderstood "fix" that unwraps it and drops `total` — is caught.+ $backend = (new MockBackend())->on(200, [+ 'messages' => [['id' => 'm1', 'body' => 'hi', 'chatId' => '[email protected]']],+ 'total' => 1,+ ]);+ $client = $backend->makeClient();+ $page = $client->messages->list('s1', ['limit' => 10]);+ $this->assertArrayHasKey('messages', $page);+ $this->assertIsArray($page['messages']);+ $this->assertSame('m1', $page['messages'][0]['id']);+ $this->assertSame(1, $page['total']);+ $this->assertStringContainsString('/messages', $backend->lastCall()['path']);+ $this->assertStringContainsString('limit=10', $backend->lastCall()['query']);+ }+public static function mediaSegments(): array{return [diff --git a/src/config/configuration.spec.ts b/src/config/configuration.spec.tsindex 195ae66a2..a2b783469 100644--- a/src/config/configuration.spec.ts+++ b/src/config/configuration.spec.ts@@ -56,9 +56,14 @@ describe('configuration — Puppeteer args delimiter', () => {expect(configuration().engine.puppeteer.args).toEqual(['--no-sandbox', '--disable-setuid-sandbox']);});- it('defaults to discrete sandbox flags when unset', () => {+ it('defaults to the Docker-relevant sandbox flag set when unset', () => {delete process.env.PUPPETEER_ARGS;- expect(configuration().engine.puppeteer.args).toEqual(['--no-sandbox', '--disable-setuid-sandbox']);+ expect(configuration().engine.puppeteer.args).toEqual([+ '--no-sandbox',+ '--disable-setuid-sandbox',+ '--disable-dev-shm-usage',+ '--disable-gpu',+ ]);});});diff --git a/src/config/configuration.ts b/src/config/configuration.tsindex ceb5b3f1d..f0f00b588 100644--- a/src/config/configuration.ts+++ b/src/config/configuration.ts@@ -93,7 +93,11 @@ export default () => ({// Accept either delimiter: .env/compose use commas, the dashboard Infrastructure form// persists space-separated. Splitting on both keeps each flag a discrete argv token —// a single glued token like "--no-sandbox --disable-gpu" silently neuters --no-sandbox.- args: (process.env.PUPPETEER_ARGS || '--no-sandbox,--disable-setuid-sandbox').split(/[\s,]+/).filter(Boolean),+ args: (+ process.env.PUPPETEER_ARGS || '--no-sandbox,--disable-setuid-sandbox,--disable-dev-shm-usage,--disable-gpu'+ )+ .split(/[\s,]+/)+ .filter(Boolean),// Optional path to a system Chromium/Chrome binary. When unset, whatsapp-web.js// uses Puppeteer's bundled Chromium. Required on hosts where the bundled binary// is missing or incompatible (Alpine, ARM, custom base images).diff --git a/src/config/env-precedence.spec.ts b/src/config/env-precedence.spec.tsindex b2545c504..7dfe3472a 100644--- a/src/config/env-precedence.spec.ts+++ b/src/config/env-precedence.spec.ts@@ -104,6 +104,12 @@ describe('blank-shadowed env keys (compose ${VAR:-} forwards the dashboard manag'REDIS_ENABLED','REDIS_HOST','REDIS_PORT',+ // Engine launch options the dashboard saves — compose blank-forwards these too, so a dashboard+ // edit isn't shadowed by a pinned container default; the app layer (configuration.ts) supplies+ // the sane default when nothing is set.+ 'PUPPETEER_HEADLESS',+ 'SESSION_DATA_PATH',+ 'PUPPETEER_ARGS',]) {expect(BLANK_SHADOWED_ENV_KEYS).toContain(key);}@@ -113,6 +119,7 @@ describe('blank-shadowed env keys (compose ${VAR:-} forwards the dashboard manag['DATABASE_TYPE', 'postgres'],['STORAGE_TYPE', 's3'],['REDIS_ENABLED', 'true'],+ ['PUPPETEER_HEADLESS', 'false'],])('lets .env.generated supply %s when the forwarded value is blank, but a host value pins', (key, fileValue) => {const prev = process.env[key];try {diff --git a/src/config/env-precedence.ts b/src/config/env-precedence.tsindex b3a34e40f..c17f11f09 100644--- a/src/config/env-precedence.ts+++ b/src/config/env-precedence.ts@@ -44,6 +44,12 @@ export const BLANK_SHADOWED_ENV_KEYS: string[] = ['REDIS_ENABLED','REDIS_HOST','REDIS_PORT',+ // Engine launch options the dashboard saves (data/.env.generated). Compose blank-forwards these so a+ // dashboard edit is not shadowed by a pinned container default; the app layer (configuration.ts)+ // supplies the sane default when nothing is set.+ 'PUPPETEER_HEADLESS',+ 'SESSION_DATA_PATH',+ 'PUPPETEER_ARGS',];export function clearBlankEnv(env: NodeJS.ProcessEnv, keys: string[]): void {diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex f7eb8b76f..64fa2d391 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -117,7 +117,12 @@ export class BaileysAdapter implements IWhatsAppEngine {private readonly logger = createLogger('BaileysAdapter');// Bound concurrent inbound media downloads: each materialises a full decrypted buffer in heap, so an// unbounded fire-and-forget loop lets a sender flood the gateway with N parallel multi-MB allocations.- private readonly inboundLimiter = new ConcurrencyLimiter(inboundMediaConcurrency());+ private readonly inboundLimiter = new ConcurrencyLimiter(+ inboundMediaConcurrency(),+ // Queue cap == active slots: beyond (active + queued) concurrent media messages, reject instead of+ // parking, so a burst can't grow heap without bound (each parked closure holds the message).+ inboundMediaConcurrency(),+ );private readonly authPath: string;private readonly sessionStore: BaileysSessionStore;private sock: WASocket | null = null;@@ -918,8 +923,17 @@ export class BaileysAdapter implements IWhatsAppEngine {}// Throttle through the limiter so a burst of media messages can't run unbounded parallel// downloads (each a full decrypted buffer in heap). Ordering stays correct — the message store- // keeps the newest by timestamp — and none are dropped (the limiter queues the overflow).- void this.inboundLimiter.run(() => this.processInboundMessage(msg));+ // keeps the newest by timestamp. When the waiter queue is saturated we REJECT instead of parking+ // forever, and re-process the message WITHOUT media: the message (body + metadata) is still+ // emitted, but we skip the heap-heavy download that the limiter exists to bound.+ void this.inboundLimiter+ .run(() => this.processInboundMessage(msg))+ .catch(() => {+ this.logger.warn('Inbound media limiter saturated; emitting message without media', {+ msgId: msg.key?.id ?? 'unknown',+ });+ return this.processInboundMessage(msg, { skipMedia: true });+ });}}@@ -946,7 +960,7 @@ export class BaileysAdapter implements IWhatsAppEngine {});}- private async processInboundMessage(msg: WAMessage): Promise<void> {+ private async processInboundMessage(msg: WAMessage, opts?: { skipMedia?: boolean }): Promise<void> {try {const b = await this.loadLib();const remoteJid = msg.key.remoteJid!;@@ -1002,7 +1016,7 @@ export class BaileysAdapter implements IWhatsAppEngine {}// --- Normal message: enrich + emit ---- const incoming = await this.mapMessage(msg, contentType);+ const incoming = await this.mapMessage(msg, contentType, { skipMediaDownload: opts?.skipMedia });if (msg.key.fromMe === true) {this.callbacks.onMessageCreate?.(incoming);} else {diff --git a/src/engine/adapters/concurrency-limiter.spec.ts b/src/engine/adapters/concurrency-limiter.spec.tsindex dfc93dc7d..a6c338e41 100644--- a/src/engine/adapters/concurrency-limiter.spec.ts+++ b/src/engine/adapters/concurrency-limiter.spec.ts@@ -75,4 +75,34 @@ describe('ConcurrencyLimiter', () => {await expect(limiter.run(() => Promise.reject(new Error('boom')))).rejects.toThrow('boom');await expect(limiter.run(() => Promise.resolve('after'))).resolves.toBe('after'); // slot was released});++ it('rejects an arrival when the waiter queue is full (bounded, no unbounded heap growth)', async () => {+ const limiter = new ConcurrencyLimiter(1, 1); // 1 active slot, 1 queued waiter max+ let release!: () => void;+ const active = limiter.run(+ () =>+ new Promise<void>(resolve => {+ release = resolve;+ }),+ ); // takes the only slot+ const queued = limiter.run(() => Promise.resolve('queued')); // parks in the 1 waiter slot+ // The (max + K)th arrival must REJECT, not park — otherwise a burst grows heap without bound.+ await expect(limiter.run(() => Promise.resolve('overflow'))).rejects.toThrow(/queue full/i);+ release();+ await Promise.all([active, queued]);+ });++ it('keeps an unbounded queue when maxQueued is omitted (backward compatible)', async () => {+ const limiter = new ConcurrencyLimiter(1);+ let release!: () => void;+ const active = limiter.run(+ () =>+ new Promise<void>(resolve => {+ release = resolve;+ }),+ );+ const parked = Array.from({ length: 50 }, () => limiter.run(() => Promise.resolve('ok')));+ release(); // drain: active finishes, then the 50 parked tasks run one at a time+ await expect(Promise.all([active, ...parked])).resolves.toHaveLength(51);+ });});diff --git a/src/engine/adapters/concurrency-limiter.ts b/src/engine/adapters/concurrency-limiter.tsindex aff272735..bf42c7bf3 100644--- a/src/engine/adapters/concurrency-limiter.ts+++ b/src/engine/adapters/concurrency-limiter.ts@@ -8,15 +8,28 @@ export class ConcurrencyLimiter {private active = 0;private readonly waiters: Array<() => void> = [];- /** `max` is clamped to at least 1 so a misconfigured 0/negative value never deadlocks the gate. */- constructor(private readonly max: number) {+ /**+ * `max` is clamped to at least 1 so a misconfigured 0/negative value never deadlocks the gate.+ * `maxQueued` bounds how many tasks may PARK waiting for a slot; an (active + queued)th arrival is+ * rejected (throws) instead of parking forever — this caps in-heap state under a burst, since each+ * parked closure holds its task (and an inbound media buffer) alive. Default Infinity preserves the+ * original unbounded-queue behavior for callers that don't opt into a cap.+ */+ constructor(+ private readonly max: number,+ private readonly maxQueued = Infinity,+ ) {this.max = Math.max(1, Math.floor(max));+ this.maxQueued = Math.max(0, Math.floor(maxQueued));}async run<T>(task: () => Promise<T>): Promise<T> {if (this.active < this.max) {this.active++;} else {+ if (this.waiters.length >= this.maxQueued) {+ throw new Error('ConcurrencyLimiter queue full');+ }// Park until a finishing task HANDS us its slot. We must not increment on wake: the count was// never released (it was transferred), so re-incrementing would over-admit when a fresh run()// raced into the microtask gap and already took a (wrongly-freed) slot.diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 5299e4d78..1b09bffe6 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -256,7 +256,12 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginprivate readonly logger = createLogger('WhatsAppWebJsAdapter');// Bound concurrent inbound media downloads: downloadMedia() materialises the full base64 blob, so an// unbounded burst could stack many multi-MB allocations.- private readonly inboundLimiter = new ConcurrencyLimiter(inboundMediaConcurrency());+ private readonly inboundLimiter = new ConcurrencyLimiter(+ inboundMediaConcurrency(),+ // Queue cap == active slots: beyond (active + queued) concurrent media messages, reject instead of+ // parking, so a burst can't grow heap without bound (each parked closure holds the message).+ inboundMediaConcurrency(),+ );/*** Download inbound media safely. downloadMedia() can't be size-bounded at the source, so (1) pre-gate@@ -317,8 +322,16 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin() => undefined,);});- // The slot-holder runs in the background; never let it surface as an unhandled rejection.- void slotHeld.catch(() => undefined);+ // The slot-holder runs in the background. It only rejects when the limiter's waiter queue is+ // saturated (queue full) — in which case the download task never ran and boundedReady would hang.+ // Resolve null so the caller unblocks and emits the message without media, matching the+ // timeout/byte-cap no-media path. Never let it surface as an unhandled rejection either.+ void slotHeld.catch(() => {+ this.logger.warn('Inbound media limiter saturated; emitting message without media', {+ msgId: msg.id._serialized,+ });+ resolveBounded(null);+ });const media = await boundedReady;if (!media) return undefined;const capped = capInboundMedia({diff --git a/src/modules/auth/auth.service.spec.ts b/src/modules/auth/auth.service.spec.tsindex cd2f9c3f9..1a3a6ed9c 100644--- a/src/modules/auth/auth.service.spec.ts+++ b/src/modules/auth/auth.service.spec.ts@@ -193,6 +193,48 @@ describe('AuthService', () => {expect(result.name).toBe('Updated');expect(result.role).toBe(ApiKeyRole.OPERATOR); // unchanged});++ it('evicts active WebSocket sockets when allowedSessions narrows', async () => {+ const evictApiKey = jest.fn();+ jest+ .spyOn((service as unknown as { moduleRef: { get: (...a: unknown[]) => unknown } }).moduleRef, 'get')+ .mockReturnValue({ evictApiKey });+ const key = createMockApiKey({ allowedSessions: ['sess-A', 'sess-B'] });+ (repository.findOne as jest.Mock).mockResolvedValue(key);+ (repository.save as jest.Mock).mockImplementation(k => Promise.resolve(k));++ await service.update('uuid-1', { allowedSessions: ['sess-A'] });++ expect(evictApiKey).toHaveBeenCalledWith('uuid-1', 'authorization_changed');+ });++ it('evicts active WebSocket sockets when the role changes', async () => {+ const evictApiKey = jest.fn();+ jest+ .spyOn((service as unknown as { moduleRef: { get: (...a: unknown[]) => unknown } }).moduleRef, 'get')+ .mockReturnValue({ evictApiKey });+ const key = createMockApiKey({ role: ApiKeyRole.OPERATOR });+ (repository.findOne as jest.Mock).mockResolvedValue(key);+ (repository.save as jest.Mock).mockImplementation(k => Promise.resolve(k));++ await service.update('uuid-1', { role: ApiKeyRole.ADMIN });++ expect(evictApiKey).toHaveBeenCalledWith('uuid-1', 'authorization_changed');+ });++ it('does not evict on a benign (name-only) update', async () => {+ const evictApiKey = jest.fn();+ jest+ .spyOn((service as unknown as { moduleRef: { get: (...a: unknown[]) => unknown } }).moduleRef, 'get')+ .mockReturnValue({ evictApiKey });+ const key = createMockApiKey({ name: 'original' });+ (repository.findOne as jest.Mock).mockResolvedValue(key);+ (repository.save as jest.Mock).mockImplementation(k => Promise.resolve(k));++ await service.update('uuid-1', { name: 'renamed' });++ expect(evictApiKey).not.toHaveBeenCalled();+ });});// ── delete / revoke ───────────────────────────────────────────────@@ -227,7 +269,7 @@ describe('AuthService', () => {await service.delete('uuid-1');expect(repository.remove).toHaveBeenCalledWith(key);- expect(evictApiKey).toHaveBeenCalledWith('uuid-1');+ expect(evictApiKey).toHaveBeenCalledWith('uuid-1', 'deleted');});});@@ -255,7 +297,7 @@ describe('AuthService', () => {await service.revoke('uuid-1');expect(key.isActive).toBe(false);- expect(evictApiKey).toHaveBeenCalledWith('uuid-1');+ expect(evictApiKey).toHaveBeenCalledWith('uuid-1', 'revoked');});it('does not roll back the revoke if WebSocket eviction throws (best-effort)', async () => {diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.tsindex 42d75aa27..51729de26 100644--- a/src/modules/auth/auth.service.ts+++ b/src/modules/auth/auth.service.ts@@ -11,7 +11,7 @@ import { hashApiKey } from './api-key-hash';import { ApiKey, ApiKeyRole } from './entities/api-key.entity';import { CreateApiKeyDto, UpdateApiKeyDto } from './dto';import { createLogger } from '../../common/services/logger.service';-import { EventsGateway } from '../events/events.gateway';+import { EventsGateway, type ApiKeyEvictionReason } from '../events/events.gateway';const API_KEY_FILE = join(process.cwd(), 'data', '.api-key');@@ -173,13 +173,38 @@ export class AuthService implements OnModuleInit {async update(id: string, dto: UpdateApiKeyDto): Promise<ApiKey> {const apiKey = await this.findOne(id);+ // Capture the authorization-relevant fields BEFORE applying the change. Only a change to role,+ // allowedIps, allowedSessions, or expiry can widen or restrict what an already-connected WebSocket+ // socket may see, so only those trigger eviction of live /events sockets — a benign rename must+ // NOT disconnect clients. REST enforces the new state immediately; without eviction a live socket+ // keeps streaming events for sessions/IPs the key just lost until it resubscribes or drops.+ const before = {+ role: apiKey.role,+ allowedIps: apiKey.allowedIps,+ allowedSessions: apiKey.allowedSessions,+ expiresAt: apiKey.expiresAt,+ };+if (dto.name) apiKey.name = dto.name;if (dto.role) apiKey.role = dto.role;if (dto.allowedIps !== undefined) apiKey.allowedIps = dto.allowedIps;if (dto.allowedSessions !== undefined) apiKey.allowedSessions = dto.allowedSessions;if (dto.expiresAt !== undefined) apiKey.expiresAt = dto.expiresAt ? new Date(dto.expiresAt) : null;- return this.apiKeyRepository.save(apiKey);+ const saved = await this.apiKeyRepository.save(apiKey);++ // Compare membership, not order: a pure reorder of allowedIps/allowedSessions is a no-op for the+ // .includes()-based enforcement, so sort before stringify to avoid a spurious eviction on a reorder.+ const ordered = (v: string[] | null) => (v ? [...v].sort() : v);+ const authzChanged =+ saved.role !== before.role ||+ saved.expiresAt?.getTime() !== before.expiresAt?.getTime() ||+ JSON.stringify(ordered(saved.allowedIps)) !== JSON.stringify(ordered(before.allowedIps)) ||+ JSON.stringify(ordered(saved.allowedSessions)) !== JSON.stringify(ordered(before.allowedSessions));+ if (authzChanged) {+ this.evictActiveSockets(id, 'authorization_changed');+ }+ return saved;}async delete(id: string): Promise<void> {@@ -187,7 +212,7 @@ export class AuthService implements OnModuleInit {// Drop any un-flushed usage accumulator so a deleted key leaves nothing behind in the Map.this.pendingUsage.delete(id);await this.apiKeyRepository.remove(apiKey);- this.evictActiveSockets(id);+ this.evictActiveSockets(id, 'deleted');this.logger.log(`API key deleted: ${apiKey.name}`, {keyId: id,action: 'api_key_deleted',@@ -203,7 +228,7 @@ export class AuthService implements OnModuleInit {const saved = await this.apiKeyRepository.save(apiKey);// Kick any WebSocket connections already authenticated with this key: without this, a revoked// key keeps receiving events on already-subscribed sockets until they happen to disconnect.- this.evictActiveSockets(id);+ this.evictActiveSockets(id, 'revoked');return saved;}@@ -213,11 +238,11 @@ export class AuthService implements OnModuleInit {* EventsModule. Best-effort: if the WS gateway isn't loaded (or has no sockets for the key),* this is a silent no-op.*/- private evictActiveSockets(keyId: string): void {+ private evictActiveSockets(keyId: string, reason: ApiKeyEvictionReason = 'revoked'): void {try {const gateway = this.moduleRef.get(EventsGateway, { strict: false });if (gateway) {- gateway.evictApiKey(keyId);+ gateway.evictApiKey(keyId, reason);}} catch (error) {// Eviction is best-effort: the key's DB state is already authoritative (validateApiKeydiff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex 6ce1895b0..8e7f61cc6 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -67,6 +67,15 @@ export function isSessionSubscriptionAllowed(allowedSessions: string[] | null |return allowedSessions.includes(sessionId);}+/** Why an API key's live WebSocket sockets are being torn down — drives the client-facing message. */+export type ApiKeyEvictionReason = 'revoked' | 'deleted' | 'authorization_changed';++const EVICTION_MESSAGES: Record<ApiKeyEvictionReason, string> = {+ revoked: 'API key has been revoked',+ deleted: 'API key has been deleted',+ authorization_changed: 'API key authorization changed; please reconnect',+};+@WebSocketGateway({cors: {origin: resolveWsCorsOrigin(),@@ -132,18 +141,20 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate}/**- * Tear down every active socket authenticated with `keyId`. Called by AuthService when a- * key is revoked or deleted so the key's already-subscribed sockets stop receiving events- * immediately instead of lingering until they disconnect on their own. Each socket gets a- * clean close (an `UNAUTHORIZED` reason) rather than a silent drop.+ * Tear down every active socket authenticated with `keyId`. Called by AuthService when a key is+ * revoked, deleted, or has its authorization (role/allowedSessions/allowedIps/expiry) narrowed, so+ * the key's already-subscribed sockets stop receiving events immediately instead of lingering until+ * they disconnect on their own. Each socket gets a clean close (an `UNAUTHORIZED` reason) reflecting+ * the actual trigger, rather than a silent drop.*/- evictApiKey(keyId: string): void {+ evictApiKey(keyId: string, reason: ApiKeyEvictionReason = 'revoked'): void {const sockets = this.socketsByKeyId.get(keyId);if (!sockets || sockets.size === 0) return;- this.logger.log(`Evicting ${sockets.size} WebSocket connection(s) for revoked key ${keyId}`);+ this.logger.log(`Evicting ${sockets.size} WebSocket connection(s) (${reason}) for key ${keyId}`);this.socketsByKeyId.delete(keyId);+ const message = EVICTION_MESSAGES[reason];for (const client of sockets) {- client.emit('message', this.createError('UNAUTHORIZED', 'API key has been revoked'));+ client.emit('message', this.createError('UNAUTHORIZED', message));client.disconnect(true);}}diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.tsindex 245e3fbe3..9f35bbd8c 100644--- a/src/modules/infra/infra.controller.spec.ts+++ b/src/modules/infra/infra.controller.spec.ts@@ -37,6 +37,11 @@ import { MessageBatch, BatchStatus } from '../message/entities/message-batch.entimport { Template } from '../template/entities/template.entity';import { BaileysStoredMessage } from '../../engine/adapters/baileys-stored-message.entity';import { LidMapping } from '../../engine/identity/lid-mapping.entity';+import { PluginInstance } from '../integration/entities/plugin-instance.entity';+import { ConversationMapping } from '../integration/entities/conversation-mapping.entity';+import { IngressEvent } from '../integration/entities/ingress-event.entity';+import { WebhookDeliveryFailure } from '../webhook/entities/webhook-delivery-failure.entity';+import { IntegrationDeliveryFailure } from '../integration/entities/integration-delivery-failure.entity';describe('InfraController access control (Vuln 2)', () => {const reflector = new Reflector();@@ -327,6 +332,14 @@ describe('InfraController.saveConfig env-name correctness and merge (#226)', ()expect(env).not.toContain('S3_SECRET_KEY=');});+ it('defaults PUPPETEER_ARGS to the full Docker sandbox flag set when browserArgs is empty', () => {+ // Once compose blank-forwards PUPPETEER_ARGS this saved value wins at runtime, so the default must+ // keep --disable-dev-shm-usage (the Docker /dev/shm tab-crash guard) — NOT the old 2-flag set.+ const env = written({ engine: { headless: true, sessionDataPath: './data/sessions', browserArgs: '' } });+ expect(env).toContain('PUPPETEER_ARGS=--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage --disable-gpu');+ expect(env).not.toContain('PUPPETEER_ARGS=--no-sandbox --disable-gpu');+ });+it('writes STORAGE_LOCAL_PATH (the name the backend reads) for local storage', () => {const env = written({ storage: { type: 'local', localPath: './data/media' } });expect(env).toContain('STORAGE_LOCAL_PATH=./data/media');@@ -467,7 +480,17 @@ describe('InfraController.importData round-trips export-data (no silent message/ds = new DataSource({type: 'sqlite',database: ':memory:',- entities: [Session, Webhook, Message, MessageBatch],+ entities: [+ Session,+ Webhook,+ Message,+ MessageBatch,+ PluginInstance,+ ConversationMapping,+ IngressEvent,+ WebhookDeliveryFailure,+ IntegrationDeliveryFailure,+ ],synchronize: true,});await ds.initialize();@@ -554,6 +577,55 @@ describe('InfraController.importData round-trips export-data (no silent message/expect(b.status).toBe(BatchStatus.COMPLETED);});+ it('round-trips plugin instances + integration delivery failures (Integration Fabric + DLQ)', async () => {+ await seedSession('s1');+ await ds.getRepository(PluginInstance).save(+ ds.getRepository(PluginInstance).create({+ id: 'chatwoot:acct1',+ pluginId: 'chatwoot',+ instanceId: 'acct1',+ sessionScope: 's1',+ secret: 'hmac-secret',+ verifyToken: null,+ config: { baseUrl: 'https://x' },+ enabled: true,+ }),+ );+ await ds.getRepository(IntegrationDeliveryFailure).save(+ ds.getRepository(IntegrationDeliveryFailure).create({+ direction: 'outbound',+ pluginId: 'chatwoot',+ instanceId: 'acct1',+ sessionId: 's1',+ deliveryId: 'd1',+ attempts: 3,+ lastError: 'boom',+ payload: { foo: 'bar' },+ redriven: false,+ }),+ );++ const dump = await controller.exportData();+ expect(dump.counts.pluginInstances).toBe(1);+ expect(dump.counts.integrationDeliveryFailures).toBe(1);++ const res = await controller.importData({ tables: dump.tables });++ expect(res.warnings).toEqual([]);+ expect(res.imported).toBe(true);+ expect(res.counts.pluginInstances).toBe(1);+ expect(res.counts.integrationDeliveryFailures).toBe(1);++ expect(await ds.getRepository(PluginInstance).count()).toBe(1);+ expect(await ds.getRepository(IntegrationDeliveryFailure).count()).toBe(1);+ const pi = await ds.getRepository(PluginInstance).findOneByOrFail({ id: 'chatwoot:acct1' });+ expect(pi.secret).toBe('hmac-secret'); // ingress HMAC secret survives a SQLite→Postgres migration+ expect(pi.config).toEqual({ baseUrl: 'https://x' });+ const dlf = await ds.getRepository(IntegrationDeliveryFailure).findOneByOrFail({ deliveryId: 'd1' });+ expect(dlf.lastError).toBe('boom');+ expect(dlf.payload).toEqual({ foo: 'bar' });+ });+it('rolls back and reports imported:false when a row fails — existing data is preserved', async () => {// Pre-existing data that must survive a failed import.await seedSession('s1');diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.tsindex 069fede84..768068659 100644--- a/src/modules/infra/infra.controller.ts+++ b/src/modules/infra/infra.controller.ts@@ -188,6 +188,70 @@ interface LidMappingRow {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;+ payload: string | Record<string, unknown>;+ 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;+}+interface MigrationTables {sessions: SessionRow[];webhooks: WebhookRow[];@@ -196,6 +260,11 @@ interface MigrationTables {templates: TemplateRow[];baileysStoredMessages: BaileysStoredMessageRow[];lidMappings: LidMappingRow[];+ pluginInstances: PluginInstanceRow[];+ conversationMappings: ConversationMappingRow[];+ ingressEvents: IngressEventRow[];+ webhookDeliveryFailures: WebhookDeliveryFailureRow[];+ integrationDeliveryFailures: IntegrationDeliveryFailureRow[];}// Saved infrastructure config returned to the dashboard form for hydration. Secret@@ -625,7 +694,11 @@ export class InfraController {}updates.PUPPETEER_HEADLESS = config.engine.headless !== false ? 'true' : 'false';updates.SESSION_DATA_PATH = config.engine.sessionDataPath || './data/sessions';- updates.PUPPETEER_ARGS = config.engine.browserArgs || '--no-sandbox --disable-gpu';+ // Must match configuration.ts's PUPPETEER_ARGS default (4 flags). Once compose blank-forwards+ // PUPPETEER_ARGS, this saved value wins at runtime — a 2-flag default here would silently drop+ // --disable-dev-shm-usage (the Docker /dev/shm tab-crash guard) after any Infrastructure save.+ updates.PUPPETEER_ARGS =+ config.engine.browserArgs || '--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage --disable-gpu';}// .env.generated is one KEY=value per line, loaded on the next boot. A value carrying a@@ -821,6 +894,11 @@ export class InfraController {templates: number;baileysStoredMessages: number;lidMappings: number;+ pluginInstances: number;+ conversationMappings: number;+ ingressEvents: number;+ webhookDeliveryFailures: number;+ integrationDeliveryFailures: number;};}> {// Get all entities from Data DB@@ -833,6 +911,11 @@ export class InfraController {let templates: TemplateRow[] = [];let baileysStoredMessages: BaileysStoredMessageRow[] = [];let lidMappings: LidMappingRow[] = [];+ let pluginInstances: PluginInstanceRow[] = [];+ let conversationMappings: ConversationMappingRow[] = [];+ let ingressEvents: IngressEventRow[] = [];+ let webhookDeliveryFailures: WebhookDeliveryFailureRow[] = [];+ let integrationDeliveryFailures: IntegrationDeliveryFailureRow[] = [];try {messages = await this.dataDataSource.query<MessageRow[]>('SELECT * FROM messages');@@ -866,6 +949,40 @@ export class InfraController {this.logger.debug('Lid mappings table not available for export', { error: String(error) });}+ // Integration Fabric + both DLQs were added after the original migration set; tolerate a genuinely+ // absent table (older DB) like the tables above rather than 500-ing the whole export.+ try {+ pluginInstances = await this.dataDataSource.query<PluginInstanceRow[]>('SELECT * FROM plugin_instances');+ } catch (error) {+ this.logger.debug('plugin_instances table not available for export', { error: String(error) });+ }+ try {+ conversationMappings = await this.dataDataSource.query<ConversationMappingRow[]>(+ 'SELECT * FROM conversation_mappings',+ );+ } catch (error) {+ this.logger.debug('conversation_mappings table not available for export', { error: String(error) });+ }+ try {+ ingressEvents = await this.dataDataSource.query<IngressEventRow[]>('SELECT * FROM ingress_events');+ } catch (error) {+ this.logger.debug('ingress_events table not available for export', { error: String(error) });+ }+ try {+ webhookDeliveryFailures = await this.dataDataSource.query<WebhookDeliveryFailureRow[]>(+ 'SELECT * FROM webhook_delivery_failures',+ );+ } catch (error) {+ this.logger.debug('webhook_delivery_failures table not available for export', { error: String(error) });+ }+ try {+ integrationDeliveryFailures = await this.dataDataSource.query<IntegrationDeliveryFailureRow[]>(+ 'SELECT * FROM integration_delivery_failures',+ );+ } catch (error) {+ this.logger.debug('integration_delivery_failures table not available for export', { error: String(error) });+ }+return {exportedAt: new Date().toISOString(),dataDbType: this.configService.get<string>('dataDatabase.type', 'sqlite'),@@ -877,6 +994,11 @@ export class InfraController {templates,baileysStoredMessages,lidMappings,+ pluginInstances,+ conversationMappings,+ ingressEvents,+ webhookDeliveryFailures,+ integrationDeliveryFailures,},counts: {sessions: sessions.length,@@ -886,6 +1008,11 @@ export class InfraController {templates: templates.length,baileysStoredMessages: baileysStoredMessages.length,lidMappings: lidMappings.length,+ pluginInstances: pluginInstances.length,+ conversationMappings: conversationMappings.length,+ ingressEvents: ingressEvents.length,+ webhookDeliveryFailures: webhookDeliveryFailures.length,+ integrationDeliveryFailures: integrationDeliveryFailures.length,},};}@@ -926,6 +1053,11 @@ export class InfraController {templates: number;baileysStoredMessages: number;lidMappings: number;+ pluginInstances: number;+ conversationMappings: number;+ ingressEvents: number;+ webhookDeliveryFailures: number;+ integrationDeliveryFailures: number;};warnings: string[];}> {@@ -958,6 +1090,13 @@ export class InfraController {// 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 clearTable('lid_mappings');+ // Integration Fabric + both DLQs: none carry an FK constraint to sessions (sessionId is provenance),+ // so clearing them here before the sessions DELETE keeps the replace-semantics complete.+ await clearTable('plugin_instances');+ await clearTable('conversation_mappings');+ await clearTable('ingress_events');+ await clearTable('webhook_delivery_failures');+ await clearTable('integration_delivery_failures');await queryRunner.query('DELETE FROM sessions');// Import sessions first@@ -1168,6 +1307,149 @@ export class InfraController {}}+ // Import plugin instances (Integration Fabric config + ingress HMAC secret)+ let pluginInstancesCount = 0;+ if (data.tables.pluginInstances?.length) {+ for (const pi of data.tables.pluginInstances) {+ try {+ await queryRunner.query(+ `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)`,+ [+ 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,+ ],+ );+ pluginInstancesCount++;+ } catch (err) {+ warnings.push(`Failed to import plugin instance ${pi.id}: ${err}`);+ }+ }+ }++ // Import conversation mappings (handover state; sessionId is non-FK provenance)+ let conversationMappingsCount = 0;+ if (data.tables.conversationMappings?.length) {+ for (const cm of data.tables.conversationMappings) {+ try {+ await queryRunner.query(+ `INSERT INTO conversation_mappings (id, "sessionId", "chatId", "pluginId", "instanceId", "providerConversationId", "handoverState", metadata, "updatedAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,+ [+ 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,+ ],+ );+ conversationMappingsCount++;+ } catch (err) {+ warnings.push(`Failed to import conversation mapping ${cm.id}: ${err}`);+ }+ }+ }++ // Import ingress events (durable inbound dedup oracle; payload is JSON)+ let ingressEventsCount = 0;+ if (data.tables.ingressEvents?.length) {+ for (const ie of data.tables.ingressEvents) {+ try {+ await queryRunner.query(+ `INSERT INTO ingress_events (id, "instanceId", "pluginId", "providerDeliveryId", route, payload, "sessionId", "createdAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,+ [+ ie.id,+ ie.instanceId,+ ie.pluginId,+ ie.providerDeliveryId,+ ie.route,+ typeof ie.payload === 'string' ? ie.payload : JSON.stringify(ie.payload ?? {}),+ ie.sessionId,+ ie.createdAt,+ ],+ );+ ingressEventsCount++;+ } catch (err) {+ warnings.push(`Failed to import ingress event ${ie.id}: ${err}`);+ }+ }+ }++ // Import webhook delivery failures (webhook DLQ)+ let webhookDeliveryFailuresCount = 0;+ if (data.tables.webhookDeliveryFailures?.length) {+ for (const wf of data.tables.webhookDeliveryFailures) {+ try {+ await queryRunner.query(+ `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)`,+ [+ wf.id,+ wf.webhookId,+ wf.sessionId,+ wf.event,+ wf.url,+ wf.idempotencyKey,+ wf.deliveryId,+ wf.attempts,+ wf.lastStatusCode,+ wf.lastError,+ wf.createdAt,+ ],+ );+ webhookDeliveryFailuresCount++;+ } catch (err) {+ warnings.push(`Failed to import webhook delivery failure ${wf.id}: ${err}`);+ }+ }+ }++ // Import integration delivery failures (inbound + outbound DLQ)+ let integrationDeliveryFailuresCount = 0;+ if (data.tables.integrationDeliveryFailures?.length) {+ for (const df of data.tables.integrationDeliveryFailures) {+ try {+ await queryRunner.query(+ `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)`,+ [+ 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,+ ],+ );+ integrationDeliveryFailuresCount++;+ } catch (err) {+ warnings.push(`Failed to import integration delivery failure ${df.id}: ${err}`);+ }+ }+ }+const counts = {sessions: sessionsCount,webhooks: webhooksCount,@@ -1176,6 +1458,11 @@ export class InfraController {templates: templatesCount,baileysStoredMessages: baileysStoredMessagesCount,lidMappings: lidMappingsCount,+ pluginInstances: pluginInstancesCount,+ conversationMappings: conversationMappingsCount,+ ingressEvents: ingressEventsCount,+ webhookDeliveryFailures: webhookDeliveryFailuresCount,+ integrationDeliveryFailures: integrationDeliveryFailuresCount,};// "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 2fc460d15..ed4bd2667 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -672,6 +672,39 @@ describe('SessionService', () => {});});+ describe('start() stale reconnect timer', () => {+ it('cancels a pending reconnect timer before recreating the engine', async () => {+ const i = service as unknown as {+ reconnectStates: Map<+ string,+ { attempts: number; timer: NodeJS.Timeout | null; maxAttempts: number; baseDelay: number }+ >;+ cancelReconnect: (id: string) => void;+ };+ // Spy clearTimeout directly so the assertion pins that the stale HANDLE was actually cleared —+ // not merely that cancelReconnect was reached (which would hold even if it forgot clearTimeout).+ const clearTimeoutSpy = jest.spyOn(globalThis, 'clearTimeout');+ const staleFired = jest.fn();+ // Seed a pending reconnect timer exactly as a failed executeReconnect leaves behind.+ // tsc resolves setTimeout to the DOM overload (number) in the spec context; force the field type.+ const staleTimer = setTimeout(staleFired, 30000) as unknown as NodeJS.Timeout;+ i.reconnectStates.set('sess-uuid-1', { attempts: 1, timer: staleTimer, maxAttempts: 5, baseDelay: 5000 });+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());++ await service.start('sess-uuid-1');++ // start() must cancel the stale timer so it can't later destroy/replace the engine start() just+ // created (or orphan a Chromium process), then install a fresh reconnect state.+ expect(staleFired).not.toHaveBeenCalled();+ expect(clearTimeoutSpy).toHaveBeenCalledWith(staleTimer);+ const after = i.reconnectStates.get('sess-uuid-1');+ expect(after?.timer).toBeNull();+ expect(after?.attempts).toBe(0);+ clearTimeout(staleTimer);+ clearTimeoutSpy.mockRestore();+ });+ });+describe('reconnect/stop race', () => {interface Internals {executeReconnect: (id: string, session: Session, state: unknown) => Promise<void>;diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 4ab1aec90..a1aa5944a 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -472,6 +472,12 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// A fresh start intentionally (re-)creates the engine — clear any stale stop/delete mark.this.stoppingSessions.delete(id);+ // Cancel any reconnect timer a prior failed executeReconnect left pending, BEFORE the awaited+ // session:starting hook and engine init — otherwise the stale timer can fire during that I/O+ // and destroy/replace the engine this start() is about to create (or orphan the Chromium+ // process). Idempotent: a no-op when no reconnect state exists (the common fresh-start case).+ this.cancelReconnect(id);+// Execute hook before startingawait this.hookManager.execute('session:starting',