Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): ignore obsolete QR render results

Yudhi Armyndharisbd68e22a2e52
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 2780d557d..649302a58 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -2566,6 +2566,134 @@ describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {
expect(onQRCode).toHaveBeenCalledTimes(1);
});
+ it.each([EngineStatus.AUTHENTICATING, EngineStatus.READY, EngineStatus.ACTION_REQUIRED])(
+ 'ignores a QR event while the session is %s',
+ async status => {
+ jest.useFakeTimers();
+ const encode = qrcode.toDataURL as unknown as jest.Mock;
+ encode.mockClear();
+ const adapter = newAdapter();
+ const { client, onStateChanged } = attachFakeClient(adapter);
+ const onQRCode = jest.fn();
+ (adapter as unknown as { callbacks: { onQRCode: jest.Mock } }).callbacks.onQRCode = onQRCode;
+ client.emit('authenticated');
+ if (status === EngineStatus.READY) client.emit('ready');
+ if (status === EngineStatus.ACTION_REQUIRED) {
+ (adapter as unknown as { lifecycle: { setStatus: (status: EngineStatus) => void } }).lifecycle.setStatus(
+ status,
+ );
+ }
+ onStateChanged.mockClear();
+
+ client.emit('qr', '2@buffered');
+ await Promise.resolve();
+
+ expect(encode).not.toHaveBeenCalled();
+ expect(adapter.getStatus()).toBe(status);
+ expect(adapter.getQRCode()).toBeNull();
+ expect(onQRCode).not.toHaveBeenCalled();
+ expect(onStateChanged).not.toHaveBeenCalled();
+ },
+ );
+
+ it('publishes QR rotations while the session is awaiting linking', async () => {
+ (qrcode.toDataURL as unknown as jest.Mock)
+ .mockResolvedValueOnce('data:image/png;base64,FIRSTQR')
+ .mockResolvedValueOnce('data:image/png;base64,NEXTQR');
+ const adapter = newAdapter();
+ const { client } = attachFakeClient(adapter);
+ const onQRCode = jest.fn();
+ (adapter as unknown as { callbacks: { onQRCode: jest.Mock } }).callbacks.onQRCode = onQRCode;
+
+ client.emit('qr', '2@first');
+ await Promise.resolve();
+ expect(adapter.getQRCode()).toBe('data:image/png;base64,FIRSTQR');
+ client.emit('qr', '2@next');
+ await Promise.resolve();
+
+ expect(adapter.getStatus()).toBe(EngineStatus.QR_READY);
+ expect(adapter.getQRCode()).toBe('data:image/png;base64,NEXTQR');
+ expect(onQRCode.mock.calls).toEqual([['data:image/png;base64,FIRSTQR'], ['data:image/png;base64,NEXTQR']]);
+ });
+
+ it.each(['failed', 'replaced', 'teardown'])(
+ 'drops a QR whose encode finishes after the client is %s',
+ async state => {
+ let finishEncode!: (value: string) => void;
+ (qrcode.toDataURL as unknown as jest.Mock).mockReturnValueOnce(
+ new Promise<string>(resolve => {
+ finishEncode = resolve;
+ }),
+ );
+ const adapter = newAdapter();
+ const { client, onStateChanged } = attachFakeClient(adapter);
+ const onQRCode = jest.fn();
+ (adapter as unknown as { callbacks: { onQRCode: jest.Mock } }).callbacks.onQRCode = onQRCode;
+ client.emit('qr', '2@rendering');
+ if (state === 'failed') {
+ (adapter as unknown as { lifecycle: { setStatus: (status: EngineStatus) => void } }).lifecycle.setStatus(
+ EngineStatus.FAILED,
+ );
+ } else if (state === 'replaced') {
+ attachFakeClient(adapter);
+ (adapter as unknown as { callbacks: { onQRCode: jest.Mock } }).callbacks.onQRCode = onQRCode;
+ } else {
+ client.destroy = jest.fn().mockResolvedValue(undefined);
+ await adapter.disconnect();
+ }
+ const status = adapter.getStatus();
+ onStateChanged.mockClear();
+
+ finishEncode('data:image/png;base64,LATEQR');
+ await Promise.resolve();
+
+ expect(adapter.getStatus()).toBe(status);
+ expect(adapter.getQRCode()).toBeNull();
+ expect(onQRCode).not.toHaveBeenCalled();
+ expect(onStateChanged).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([EngineStatus.AUTHENTICATING, EngineStatus.READY, EngineStatus.ACTION_REQUIRED])(
+ 'drops a QR whose encode finishes after the session becomes %s',
+ async status => {
+ jest.useFakeTimers();
+ let finishEncode!: (value: string) => void;
+ (qrcode.toDataURL as unknown as jest.Mock).mockReturnValueOnce(
+ new Promise<string>(resolve => {
+ finishEncode = resolve;
+ }),
+ );
+ const adapter = newAdapter();
+ const { client, onReady, onStateChanged } = attachFakeClient(adapter, { eventsAttached: true });
+ const onQRCode = jest.fn();
+ (adapter as unknown as { callbacks: { onQRCode: jest.Mock } }).callbacks.onQRCode = onQRCode;
+
+ client.emit('qr', '2@rendering');
+ client.emit('authenticated');
+ if (status === EngineStatus.READY) client.emit('ready');
+ if (status === EngineStatus.ACTION_REQUIRED) {
+ (adapter as unknown as { lifecycle: { setStatus: (status: EngineStatus) => void } }).lifecycle.setStatus(
+ status,
+ );
+ }
+ expect(adapter.getStatus()).toBe(status);
+ onStateChanged.mockClear();
+ finishEncode('data:image/png;base64,LATEQR');
+ await Promise.resolve();
+
+ expect(adapter.getStatus()).toBe(status);
+ expect(adapter.getQRCode()).toBeNull();
+ expect(onQRCode).not.toHaveBeenCalled();
+ expect(onStateChanged).not.toHaveBeenCalled();
+ expect(onReady).toHaveBeenCalledTimes(status === EngineStatus.READY ? 1 : 0);
+ if (status === EngineStatus.READY) {
+ client.pupPage.evaluate.mockResolvedValue([]);
+ await expect(adapter.getChats()).resolves.toEqual([]);
+ }
+ },
+ );
+
// The cached QR belongs to the page that produced it. A Chromium crash or tab close while the operator
// is looking at the QR is the reachable vector: handlePuppeteerDeath fires at QR_READY, the session
// keeps the engine registered across its reconnect backoff, and GET /qr kept answering 200 with a code
diff --git a/src/engine/adapters/wwebjs-lifecycle.ts b/src/engine/adapters/wwebjs-lifecycle.ts
index e48d18ac1..3365e65a6 100644
--- a/src/engine/adapters/wwebjs-lifecycle.ts
+++ b/src/engine/adapters/wwebjs-lifecycle.ts
@@ -567,6 +567,13 @@ export class WwebjsLifecycle {
// this.client while the old page can still flush a buffered event through its bindings, so the
// qr, authenticated and ready listeners fence on this identity before touching this.client.
const source = this.client;
+ const canPublishQr = (): boolean =>
+ this.client === source &&
+ !this.tearingDown &&
+ !this.disconnectReported &&
+ ![EngineStatus.AUTHENTICATING, EngineStatus.READY, EngineStatus.ACTION_REQUIRED, EngineStatus.FAILED].includes(
+ this.getStatus(),
+ );
// eslint-disable-next-line @typescript-eslint/no-misused-promises
this.client.on('qr', async (qr: string) => {
@@ -577,14 +584,7 @@ export class WwebjsLifecycle {
// 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.client !== source ||
- this.tearingDown ||
- this.disconnectReported ||
- this.status === EngineStatus.FAILED
- ) {
- return;
- }
+ if (!canPublishQr()) return;
this.qrShown = true;
// qrcode.toDataURL() is an awaited macrotask: a 'disconnected' (or a teardown nulling this.client)
// that lands during the encode leaves the pre-await guard stale. Encode to a LOCAL so the stored
@@ -594,17 +594,9 @@ export class WwebjsLifecycle {
// Post-await fence: the encode resolved, but the source client may have disconnected or been
// replaced while we were waiting. Re-check the live client identity and the finished flags before
// assigning state, publishing a QR, or driving any downstream callback/webhook — a late encode for
- // a dead/finished adapter must be dropped, not resurrected. The status is read through getStatus()
- // (not `this.status`) so the pre-await guard's narrowing does not elide this comparison:
- // setStatus(FAILED) can run on another tick during the await.
- if (
- this.client !== source ||
- this.tearingDown ||
- this.disconnectReported ||
- this.getStatus() === EngineStatus.FAILED
- ) {
- return;
- }
+ // a dead/finished adapter must be dropped. Authentication or an operator-required state reached
+ // during encoding also makes this QR obsolete.
+ if (!canPublishQr()) return;
this.qrCode = encodedQr;
this.setStatus(EngineStatus.QR_READY);
this.host.getCallbacks().onQRCode?.(this.qrCode);