Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): stop a superseded whatsapp-web.js client from publishing a stale QR (#983)

Yudhi Armyndharis3ffe44bddcaa
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 52311f5d2..81384f897 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
npm registry tarball (published from the same commit previously fetched over Git SSH), avoiding
npm 12's `EALLOWGIT` default without weakening its project security policy.
+- **A whatsapp-web.js session no longer publishes a QR belonging to the browser it is about to
+ replace** (#982). On `LOGOUT`, whatsapp-web.js deletes the auth profile and re-runs its injection
+ against the same browser, so the old client keeps serving QR codes while the session lifecycle waits
+ out the reconnect backoff before tearing it down. The adapter suppressed such events only once
+ teardown had begun, so throughout that window — five seconds by default, as long as the configured
+ `reconnectBaseDelay` at most — a stale QR reached the dashboard and the `session.qr` webhook seconds
+ ahead of the real one; scanning it linked a phantom device and left the session unauthenticated. An
+ adapter that has reported a disconnect is now treated as finished for `qr` and `authenticated`
+ alike, matching the guard that already covered teardown.
+
+- **A `LOGOUT` disconnect now says what it means in the logs** (#982). The reason reached operators as
+ the bare engine token, reading like any other transient drop, when in fact WhatsApp Web itself ran a
+ logout and whatsapp-web.js deleted the session's stored credentials before the event was even
+ handed over — so no reconnect can restore the link and the device must be re-scanned. The adapter
+ now states that once, alongside a pointer to check Linked devices on the phone. The
+ `session.disconnected` payload is unchanged.
+
+- **The expected Puppeteer rejection that follows an engine teardown no longer logs as an error with a
+ raw stack** (#982). whatsapp-web.js re-runs its injection from an async listener it never awaits, so
+ closing that browser leaves a pending page evaluate to reject with no owner. It is expected and
+ self-healing, so it is now a warning naming the cause instead of an `Unhandled promise rejection`
+ error that reads like a crash. Nothing is muted: the full reason is still logged, and the actionable
+ variant of the same message — a browser profile left stale by a Chromium-binary change (#663/#708) —
+ is raised inside `initialize()`, caught by the adapter, and keeps its existing advisory.
+
## [0.11.1] - 2026-07-28
### Added
diff --git a/src/config/process-error-monitor.spec.ts b/src/config/process-error-monitor.spec.ts
index bd9b397d0..8686bfb1e 100644
--- a/src/config/process-error-monitor.spec.ts
+++ b/src/config/process-error-monitor.spec.ts
@@ -1,4 +1,4 @@
-import { registerUncaughtExceptionMonitor } from './process-error-monitor';
+import { registerUncaughtExceptionMonitor, registerUnhandledRejectionHandler } from './process-error-monitor';
const EVENT = 'uncaughtExceptionMonitor';
@@ -48,3 +48,54 @@ describe('registerUncaughtExceptionMonitor', () => {
expect(calls[0][1]).toContain('a bare string');
});
});
+
+describe('registerUnhandledRejectionHandler', () => {
+ const EVENT = 'unhandledRejection';
+ const added: Array<(...args: unknown[]) => void> = [];
+
+ type Call = [string, string | undefined];
+ const register = (): { handler: (r: unknown) => void; errors: Call[]; warns: Call[] } => {
+ const errors: Call[] = [];
+ const warns: Call[] = [];
+ const before = process.listeners(EVENT);
+ registerUnhandledRejectionHandler({
+ error: (m, d) => errors.push([m, d]),
+ warn: (m, d) => warns.push([m, d]),
+ });
+ const fresh = process.listeners(EVENT).filter(l => !before.includes(l)) as Array<(...a: unknown[]) => void>;
+ added.push(...fresh);
+ return { handler: fresh[fresh.length - 1], errors, warns };
+ };
+
+ afterEach(() => {
+ added.splice(0).forEach(l => process.removeListener(EVENT, l));
+ });
+
+ it('logs an ordinary rejection as an error carrying its stack', () => {
+ const { handler, errors, warns } = register();
+ handler(new Error('something genuinely broke'));
+ expect(warns).toHaveLength(0);
+ expect(errors).toHaveLength(1);
+ expect(errors[0][1]).toContain('something genuinely broke');
+ });
+
+ // #982: whatsapp-web.js re-runs inject() from an async 'framenavigated' listener it never awaits, so
+ // when the lifecycle closes that browser the pending page evaluate rejects with nowhere to be caught.
+ // It is expected and self-healing, and logging it as an error with a raw Puppeteer stack reads like a
+ // crash. The actionable variant of this message (#708, a stale browser profile) is thrown from inside
+ // initialize() and caught by the adapter, so it never reaches this handler.
+ it('downgrades the Puppeteer teardown rejection to a warning that explains it', () => {
+ const { handler, errors, warns } = register();
+ handler(new Error('Execution context was destroyed'));
+ expect(errors).toHaveLength(0);
+ expect(warns).toHaveLength(1);
+ expect(warns[0][0]).toMatch(/engine teardown/i);
+ expect(warns[0][1]).toContain('Execution context was destroyed'); // nothing is hidden, only the severity drops
+ });
+
+ it('stringifies a non-Error rejection without throwing', () => {
+ const { handler, errors } = register();
+ expect(() => handler('a bare string')).not.toThrow();
+ expect(errors[0][1]).toContain('a bare string');
+ });
+});
diff --git a/src/config/process-error-monitor.ts b/src/config/process-error-monitor.ts
index 6c6f4d394..bdda32092 100644
--- a/src/config/process-error-monitor.ts
+++ b/src/config/process-error-monitor.ts
@@ -3,6 +3,17 @@ interface FatalLogger {
error: (message: string, detail?: string) => void;
}
+/** As FatalLogger, plus the warn level the rejection handler downgrades to. */
+interface RejectionLogger extends FatalLogger {
+ warn: (message: string, detail?: string) => void;
+}
+
+/**
+ * Puppeteer raises this when an isolated world is disposed while an `evaluate` is still waiting for an
+ * execution context — i.e. the browser was closed underneath it.
+ */
+const ENGINE_TEARDOWN_REJECTION = /execution context was destroyed/i;
+
/**
* Register an `uncaughtExceptionMonitor` that routes an otherwise-fatal uncaught exception through the
* structured logger BEFORE Node's default handling.
@@ -30,3 +41,35 @@ export function registerUncaughtExceptionMonitor(logger: FatalLogger): void {
}
});
}
+
+/**
+ * Backstop for promise rejections that escaped a local handler. Node terminates the process on an
+ * unhandled rejection by default; for a long-running self-hosted gateway we log it and stay up rather
+ * than let one stray rejection kill every session.
+ *
+ * One class is logged at WARN instead of ERROR: a Puppeteer context-disposal raised while an engine is
+ * being torn down. whatsapp-web.js re-runs `inject()` from an async `framenavigated` listener it never
+ * awaits, so after a LOGOUT — which navigates the page, then re-injects on the SAME browser — the
+ * lifecycle's teardown turns that still-pending page evaluate into a rejection with no owner (#982).
+ * It is expected and self-healing, and an ERROR with a raw Puppeteer stack reads like a crash.
+ *
+ * Deliberately scoped so nothing actionable is muted: the ACTIONABLE variant of the same message — a
+ * browser profile left stale by an upgrade that changed the Chromium binary (#663/#708) — is thrown
+ * from inside `engine.initialize()`, where the adapter catches it and logs its own advisory, so it
+ * never reaches this handler. And only the severity changes: the full reason is still logged.
+ */
+export function registerUnhandledRejectionHandler(logger: RejectionLogger): void {
+ process.on('unhandledRejection', (reason: unknown) => {
+ const message = reason instanceof Error ? reason.message : String(reason);
+ const detail = reason instanceof Error ? reason.stack : String(reason);
+ if (ENGINE_TEARDOWN_REJECTION.test(message)) {
+ logger.warn(
+ 'Puppeteer rejection during an engine teardown — expected; the session recovers on its own. ' +
+ "Check the session's own disconnect/failure logs for the outcome.",
+ detail,
+ );
+ return;
+ }
+ logger.error('Unhandled promise rejection', detail);
+ });
+}
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 4c4af9216..f47569765 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -1200,6 +1200,79 @@ describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {
expect(onQRCode).toHaveBeenCalledTimes(1);
});
+ // #982: whatsapp-web.js does NOT destroy the client on LOGOUT — it deletes the auth profile and
+ // re-runs inject() on the SAME browser, which re-arms the QR handler. The session lifecycle only
+ // tears the engine down after the reconnect backoff (~5s by default, operator-raisable to 300s), so
+ // there is a window where the adapter is DISCONNECTED but NOT tearing down. A QR emitted then belongs
+ // to a browser about to be killed: scanning it links a phantom device and the real QR arrives seconds
+ // later. Same short-circuit-before-encode check as the teardown case above.
+ it('ignores a qr event fired after a LOGOUT disconnect (before teardown starts)', async () => {
+ (qrcode.toDataURL as unknown as jest.Mock).mockClear();
+ const adapter = newAdapter();
+ const { client } = attachFakeClient(adapter);
+ const onQRCode = jest.fn();
+ (adapter as unknown as { callbacks: { onQRCode: jest.Mock } }).callbacks.onQRCode = onQRCode;
+
+ client.emit('disconnected', 'LOGOUT');
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+ // The distinguishing property of this window: no teardown has begun, so `tearingDown` is still
+ // false and cannot be what suppresses the stale QR.
+ expect((adapter as unknown as { tearingDown: boolean }).tearingDown).toBe(false);
+
+ client.emit('qr', '2@stale-after-logout');
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(qrcode.toDataURL as unknown as jest.Mock).not.toHaveBeenCalled(); // guard short-circuits before the encode
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+ expect(onQRCode).not.toHaveBeenCalled();
+ });
+
+ // #982: 'LOGOUT' is not a transient drop and the lifecycle cannot recover the link from it —
+ // whatsapp-web.js has already deleted the auth profile by the time the event arrives. The opaque
+ // engine token alone left operators reading it as an ordinary disconnect, so the adapter explains it.
+ it('explains a LOGOUT disconnect (credentials deleted, re-scan required)', () => {
+ const adapter = newAdapter();
+ const logger = (adapter as unknown as { logger: { warn: (m: string) => void } }).logger;
+ const warnSpy = jest.spyOn(logger, 'warn').mockImplementation(() => undefined);
+ const { client } = attachFakeClient(adapter);
+
+ client.emit('disconnected', 'LOGOUT');
+
+ expect(warnSpy).toHaveBeenCalledTimes(1);
+ expect(warnSpy.mock.calls[0][0]).toMatch(/re-scan/i);
+ expect(warnSpy.mock.calls[0][0]).toMatch(/credential/i);
+ });
+
+ // Guards against over-explaining: an ordinary transient reason must not gain the re-scan advisory.
+ it('does not explain an ordinary transient disconnect reason', () => {
+ const adapter = newAdapter();
+ const logger = (adapter as unknown as { logger: { warn: (m: string) => void } }).logger;
+ const warnSpy = jest.spyOn(logger, 'warn').mockImplementation(() => undefined);
+ const { client } = attachFakeClient(adapter);
+
+ client.emit('disconnected', 'CONFLICT');
+
+ expect(warnSpy).not.toHaveBeenCalled();
+ });
+
+ // The same #982 window for 'authenticated': the re-injected client can re-authenticate on the browser
+ // that is about to be replaced. Reviving to AUTHENTICATING would also re-arm the 90s ready-reconcile
+ // probe against it.
+ it('ignores an authenticated event fired after a LOGOUT disconnect (before teardown starts)', () => {
+ jest.useFakeTimers();
+
+ const adapter = newAdapter();
+ const { client } = attachFakeClient(adapter);
+
+ client.emit('disconnected', 'LOGOUT');
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+
+ client.emit('authenticated');
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+ expect(jest.getTimerCount()).toBe(0); // no ready-reconcile armed on an engine about to be replaced
+ });
+
// A wedged page can make getState() hang (the exact #251/#273 condition). The probe must keep its
// own cadence (a hung probe can't stall the loop) and still honor the 90s give-up deadline.
it('keeps probing and self-heals (clears auth + disconnects) when getState hangs past the deadline', async () => {
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 12176ec02..572616041 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -366,6 +366,12 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
// Set once teardown begins so a late 'authenticated' can't resurrect a disconnecting adapter. Not
// reset — an adapter is single-use after teardown (the session creates a fresh one to reconnect).
private tearingDown = false;
+ // Set once the adapter ACTIVELY transitions to DISCONNECTED (engine disconnect, puppeteer death,
+ // stuck-auth recovery, teardown). Same single-use contract as `tearingDown`, but it latches earlier:
+ // on LOGOUT whatsapp-web.js keeps the browser and re-runs inject(), while the lifecycle only replaces
+ // the engine after the reconnect backoff — so for those seconds the old client can still emit a QR or
+ // re-authenticate, and neither belongs to the session any more (#982).
+ private disconnectReported = false;
constructor(private readonly config: WhatsAppWebJsConfig) {
super();
@@ -609,11 +615,14 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
// eslint-disable-next-line @typescript-eslint/no-misused-promises
this.client.on('qr', async (qr: string) => {
- // A 'qr' buffered by a wedged page can flush during the awaited client.destroy() (teardown sets
- // tearingDown + DISCONNECTED first) or after recoverFromStuckAuth() nulls this.client. Ignore it so a
- // late event can't resurrect a disconnecting adapter to QR_READY and re-emit a stale QR. Mirrors the
- // 'authenticated' guard below; the normal first QR is unaffected (not tearing down, not FAILED, client set).
- if (this.tearingDown || this.status === EngineStatus.FAILED || !this.client) {
+ // A 'qr' buffered by a wedged page can flush during the awaited client.destroy(), after
+ // recoverFromStuckAuth() nulls this.client, or from a client that whatsapp-web.js re-injected
+ // after a LOGOUT (#982) — in the last case the browser is still alive and will keep serving QRs
+ // until the lifecycle replaces the engine. Ignore all of them so a late event can't resurrect a
+ // finished adapter to QR_READY and publish a QR that links a phantom device. Mirrors the
+ // 'authenticated' guard below; the normal first QR is unaffected (initialize() moves the status to
+ // INITIALIZING before any client exists, so the latch is still clear).
+ if (this.tearingDown || this.disconnectReported || this.status === EngineStatus.FAILED || !this.client) {
return;
}
try {
@@ -628,10 +637,12 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
this.client.on('authenticated', () => {
// Only the first authentication starts the reconcile window. Ignore a re-fired 'authenticated'
// while already AUTHENTICATING (so it can't restart the 90s deadline), once READY/FAILED, or any
- // time during/after teardown (so a late event can't resurrect a disconnecting adapter). The
- // initial status is DISCONNECTED, so teardown is distinguished by the flag, not by DISCONNECTED.
+ // time after the adapter is finished — teardown, or a reported disconnect the lifecycle has not
+ // replaced the engine for yet (#982). The initial status is DISCONNECTED too, so "finished" is
+ // carried by the flags, never by the status alone.
if (
this.tearingDown ||
+ this.disconnectReported ||
this.status === EngineStatus.AUTHENTICATING ||
this.status === EngineStatus.READY ||
this.status === EngineStatus.FAILED
@@ -859,6 +870,19 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
this.client.on('disconnected', reason => {
this.clearReadyReconcile();
+ // #982: LOGOUT is not a transient drop. whatsapp-web.js emits it when WhatsApp Web itself ran a
+ // logout (its in-page `Cmd` logout bus), and by then it has ALREADY deleted this session's
+ // credentials — LocalAuth.logout() removes the profile dir before the event reaches us. So the
+ // lifecycle's reconnect cannot restore the link; it can only come back with a fresh QR. Say that
+ // here rather than leaving the operator with an opaque engine token that reads like any other drop.
+ if (reason === 'LOGOUT') {
+ this.logger.warn(
+ 'WhatsApp unlinked this device (LOGOUT). whatsapp-web.js has already deleted the stored ' +
+ 'credentials for this session, so reconnecting cannot restore the link — the session comes ' +
+ 'back with a fresh QR and must be re-scanned. If this was not expected, check Linked devices ' +
+ 'on the phone.',
+ );
+ }
this.setStatus(EngineStatus.DISCONNECTED);
this.callbacks.onDisconnected?.(reason);
});
@@ -1253,6 +1277,12 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
}
private setStatus(status: EngineStatus): void {
+ // Latch before anything observes the transition. The constructor's initial DISCONNECTED is a field
+ // initializer and never reaches here, so this only ever fires on a real transition — startup is
+ // unaffected while a finished adapter is marked finished for good.
+ if (status === EngineStatus.DISCONNECTED) {
+ this.disconnectReported = true;
+ }
this.status = status;
this.callbacks.onStateChanged?.(status);
this.emit('stateChanged', status);
diff --git a/src/main.ts b/src/main.ts
index 391800ea1..1897ce2b4 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -11,7 +11,7 @@ import { AppModule, DASHBOARD_DIST, dashboardServingEnabled, dashboardBuildPrese
import { ShutdownService } from './common/services/shutdown.service';
import { LoggerService, LogLevel, createLogger } from './common/services/logger.service';
import { createSwaggerConfig, exemptPublicOperations } from './config/swagger.config';
-import { registerUncaughtExceptionMonitor } from './config/process-error-monitor';
+import { registerUncaughtExceptionMonitor, registerUnhandledRejectionHandler } from './config/process-error-monitor';
import { runBootstrapOrExit } from './config/bootstrap-fatal';
import { applyHttpTimeouts, HttpTimeoutConfig, HttpTimeoutSink } from './config/http-timeouts';
import { createInflightBodyBudget, resolveInflightBodyBudgetBytes } from './config/inflight-body-budget';
@@ -48,12 +48,9 @@ async function bootstrap() {
}
// Backstop for promise rejections that escaped a local handler (e.g. a fire-and-forget engine-event
- // dispatch). Node terminates the process on an unhandled rejection by default; for a long-running
- // self-hosted gateway we'd rather log it and stay up than let one stray rejection kill all sessions.
+ // dispatch), including the expected engine-teardown case it downgrades to a warning (see the helper).
const bootstrapLogger = createLogger('Bootstrap');
- process.on('unhandledRejection', (reason: unknown) => {
- bootstrapLogger.error('Unhandled promise rejection', reason instanceof Error ? reason.stack : String(reason));
- });
+ registerUnhandledRejectionHandler(bootstrapLogger);
// A synchronous throw from a non-promise context (e.g. a sync timer callback) is fatal — Node prints a
// raw stack to stderr, bypassing the structured log pipeline, and exits(1). Route the stack through the