Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): ignore engine callbacks from a superseded or torn-down engine (#410)

Yudhi Armyndharis4c43c398ac4d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e09af1ace..ff4b01815 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- **A session is no longer mutated by callbacks from an engine it has already replaced or torn
+ down.** Each engine's lifecycle/message callbacks (QR, ready, disconnect, state, ack, message,
+ reaction, …) now no-op once that engine is no longer the live one for the session. This closes a
+ race where a late callback from a stopped engine — or from a previous engine after a
+ restart/reconnect — could write a stale status (e.g. flip a stopped session back to `ready`),
+ schedule a reconnect for a session meant to be down, or persist a stray message/ack against the
+ wrong engine generation. The guard is a no-op for the live engine and for ordinary network-drop
+ reconnects. (#410)
+
## [0.5.0] - 2026-06-21
A security & reliability hardening release. **One behavior change** (the reason for the minor bump):
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index e3915f058..917ca94bb 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -533,6 +533,79 @@ describe('SessionService', () => {
});
});
+ // ── engine-identity guard: stale-callback isolation ───────────────
+ // A callback can fire after its engine was torn down (post-stop) or after a newer engine
+ // replaced it for the same id (post-restart / reconnect). Such a stale callback must not
+ // mutate the session that now belongs to a different (or no) engine.
+ describe('stale engine callback isolation', () => {
+ const enginesOf = () => (service as unknown as { engines: Map<string, unknown> }).engines;
+
+ const startAndCapture = async (): Promise<EngineEventCallbacks> => {
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ await service.start('sess-uuid-1');
+ const calls = mockEngine.initialize.mock.calls as [EngineEventCallbacks][];
+ return calls[0][0];
+ };
+
+ it('lets the live engine drive status (guard is a no-op for the active engine)', async () => {
+ const callbacks = await startAndCapture();
+ (repository.update as jest.Mock).mockClear();
+
+ callbacks.onReady?.('628123', 'Tester');
+
+ expect(repository.update).toHaveBeenCalledWith(
+ 'sess-uuid-1',
+ expect.objectContaining({ status: SessionStatus.READY }),
+ );
+ });
+
+ it('ignores onReady from an engine that was torn down (post-stop window)', async () => {
+ const callbacks = await startAndCapture();
+ enginesOf().delete('sess-uuid-1'); // stop()/forceKill() removes the engine from the live map
+ (repository.update as jest.Mock).mockClear();
+
+ callbacks.onReady?.('628123', 'Tester');
+
+ expect(repository.update).not.toHaveBeenCalled();
+ });
+
+ it('ignores onDisconnected from a superseded engine after restart (stale generation)', async () => {
+ const callbacks = await startAndCapture(); // engine A captured
+ enginesOf().set('sess-uuid-1', { marker: 'engine-B' }); // a newer engine now owns the id
+ (repository.update as jest.Mock).mockClear();
+ (webhookService.dispatch as jest.Mock).mockClear();
+
+ callbacks.onDisconnected?.('socket closed');
+
+ expect(repository.update).not.toHaveBeenCalled();
+ expect(webhookService.dispatch).not.toHaveBeenCalled();
+ });
+
+ it('ignores onMessage from a superseded engine (no persist, no webhook)', async () => {
+ const callbacks = await startAndCapture();
+ enginesOf().set('sess-uuid-1', { marker: 'engine-B' });
+ (messageRepository.save as jest.Mock).mockClear();
+ (webhookService.dispatch as jest.Mock).mockClear();
+
+ callbacks.onMessage?.({
+ id: 'wa-1',
+ chatId: '[email protected]',
+ body: 'hi',
+ type: 'text',
+ timestamp: 1,
+ fromMe: false,
+ isGroup: false,
+ });
+ await new Promise(resolve => setImmediate(resolve));
+
+ expect(messageRepository.save).not.toHaveBeenCalled();
+ expect(webhookService.dispatch).not.toHaveBeenCalled();
+ });
+ });
+
// ── engine message-event webhook dispatch ─────────────────────────
describe('engine message-event webhook dispatch', () => {
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 9b9c20e8f..0c3ccc407 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -419,6 +419,19 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
}
}
+ /**
+ * True only while `engine` is still the live engine registered for `id`. Each callback below
+ * captures its own engine instance; once the session is stopped (engine removed from the map) or
+ * restarted/reconnected (engine replaced), a late callback from the superseded engine must not
+ * mutate the session that now belongs to a different — or no — engine. `this.engines` is the
+ * single source of truth for the active engine, so identity comparison closes both the
+ * post-stop and the stale-generation (stop→start / reconnect-replace) windows the one-shot
+ * post-init guard does not cover.
+ */
+ private isLiveEngine(id: string, engine: IWhatsAppEngine): boolean {
+ return this.engines.get(id) === engine;
+ }
+
private async initializeEngine(id: string, session: Session): Promise<void> {
this.logger.log(`Initializing engine for session: ${session.name}`, {
sessionId: id,
@@ -442,6 +455,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
await engine.initialize({
onQRCode: (qr: string): void => {
+ if (!this.isLiveEngine(id, engine)) return;
this.logger.log('QR code generated', {
sessionId: id,
action: 'qr_generated',
@@ -462,6 +476,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
void this.updateStatus(id, SessionStatus.QR_READY);
},
onReady: (phone: string, pushName: string): void => {
+ if (!this.isLiveEngine(id, engine)) return;
this.logger.log(`Session ready: ${phone}`, {
sessionId: id,
phone,
@@ -497,6 +512,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
});
},
onMessage: (message): void => {
+ if (!this.isLiveEngine(id, engine)) return;
// Status/Story posts arrive via the inbound path for some engines; don't persist or webhook them.
// Mirrors the isStatusBroadcast guard in onMessageCreate below.
if (message.isStatusBroadcast) {
@@ -569,6 +585,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
.catch(err => this.logger.error(`onMessage handler failed for ${id}`, String(err)));
},
onMessageCreate: (message): void => {
+ if (!this.isLiveEngine(id, engine)) return;
// `message_create` fires for every message the account creates, including sends composed on a
// linked phone — which the `message`/`onMessage` event never delivers. Incoming messages are
// already handled by `onMessage`, so only outgoing (`fromMe`) ones produce `message.sent` here.
@@ -617,6 +634,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
.catch(err => this.logger.error(`onMessageCreate handler failed for ${id}`, String(err)));
},
onMessageAck: (messageId, status: DeliveryStatus): void => {
+ if (!this.isLiveEngine(id, engine)) return;
this.logger.debug(`Message ack: ${messageId} -> ${status}`, {
sessionId: id,
messageId,
@@ -697,6 +715,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
}
},
onMessageRevoked: (message): void => {
+ if (!this.isLiveEngine(id, engine)) return;
this.logger.debug(`Message revoked: ${message.id}`, {
sessionId: id,
messageId: message.id,
@@ -719,6 +738,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
this.eventsGateway.emitMessageRevoked(id, revokedPayload);
},
onMessageReaction: (event): void => {
+ if (!this.isLiveEngine(id, engine)) return;
this.logger.debug(`Message reaction received: ${event.messageId} -> ${event.reaction}`, {
sessionId: id,
messageId: event.messageId,
@@ -739,6 +759,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
});
},
onDisconnected: (reason: string): void => {
+ if (!this.isLiveEngine(id, engine)) return;
this.logger.warn(`Session disconnected: ${reason}`, {
sessionId: id,
reason,
@@ -763,6 +784,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
this.scheduleReconnect(id, session);
},
onStateChanged: (engineState: EngineStatus): void => {
+ if (!this.isLiveEngine(id, engine)) return;
const statusMap: Record<EngineStatus, SessionStatus> = {
[EngineStatus.DISCONNECTED]: SessionStatus.DISCONNECTED,
[EngineStatus.INITIALIZING]: SessionStatus.INITIALIZING,
@@ -777,6 +799,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
}
},
onError: (reason: string): void => {
+ if (!this.isLiveEngine(id, engine)) return;
this.logger.error(`Session engine failed: ${reason}`, undefined, {
sessionId: id,
reason,