fix: prevent duplicate ready events on SPA re-injection (#201653)

* fix: prevent duplicate ready events on SPA re-injection

1. Add _injectInProgress concurrency guard
2. Replace polling loops with waitForFunction
3. Deduplicate Backbone listeners via tuple array with cleanup
4. Atomic hasSynced check after listener registration
5. isMainFrame guard and storeAvailable SPA skip in framenavigated

co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: add robustness fixes from fork PR #41

- try/finally around inject() to always reset _injectInProgress
- Atomic hasSynced check inside listener registration evaluate()
- Fix framenavigated: capture isLogout before async, skip re-inject
  only when not logout AND store available
- try/catch around obj.off() in listener cleanup
- Null guard in QR ref change handler
- Reset qrRetries on LOADING_SCREEN event
- Add exposeFunctionIfAbsent in requestPairingCode()

co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: remove QR listener on auth success

extract named onRefChange handler so it can be removed via
socket.on('change:hasSynced') once authentication succeeds,
matching PR #41's cleanup behavior.

co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: remove exposeFunctionIfAbsent from requestPairingCode

* fix: run refreshQR in browser context via pupPage.evaluate

the onAuthAppStateChangedEvent callback is registered with
exposefunctionifabsent, so it runs in Node.js context, not the browser.
calling window.require() there throws ReferenceError: window is not defined,
which means the QR code was never refreshed on UNPAIRED_IDLE state.

* fix: remove unnecessary try/catch around Backbone .off()

backbone's .off() never throws - verified on a live WhatsApp Web
instance with non-existent listeners, fake events, and double-off.
the try/catch was defensive but unnecessary.

* fix: remove unnecessary try/catch blocks in framenavigated handler

- storeAvailable: evaluate() always succeeds after framenavigated
  because Puppeteer waits for the execution context automatically
  (verified via CDP event order and Puppeteer source)
- inject(): matches upstream behavior - let errors surface instead
  of silently swallowing them

* fix: use AbortController to cancel inject on page navigation

when WhatsApp Web does location.reload() during inject (e.g. after
viewer context auth), puppeteer's waitForFunction hangs for 30s on
a dead execution context. After the timeout, no recovery is possible.

fix:
- Replace _injectInProgress flag with AbortController pattern: new
  inject() calls automatically cancel any previous in-progress inject
- Pass signal to waitForFunction for immediate cancellation
- Move framenavigated handler registration before first inject() in
  initialize(), so navigation during startup triggers re-inject
- Abort inject on destroy() to prevent spurious errors

* chore: ignore *.d.ts in eslint

upstream added TypeScript declaration changes that ESLint cannot parse.

* chore: revert index.d.ts and .eslintignore changes

* fix: reset _framenavigatedRegistered flag on destroy

* fix: revert unintended setCurrentIndexHtml refactor from lint auto-fix

* fix: replace async listener with waitForResponse for index cache

the response listener used an async handler on EventEmitter. mitt
ignores returned Promises, so when res.text() rejected on CDP
disconnect the promise was orphaned - causing unhandledRejection.

replace with page.waitForResponse() which returns a proper Promise
chain. Use .catch((_) => _) following the existing convention in
this codebase (see waitForNavigation on line 386).

* Revert "fix: replace async listener with waitForResponse for index cache"

This reverts commit 8cfd915ee5331d8b828c74ca8306dc72517bb0f1.

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Adi1231234 2026-06-25 05:49:54 +03:00 • committed by GitHub
commit 1780711a1c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -112,27 +112,23 @@ class Client extends EventEmitter {
* Private function
*/
async inject() {
if (
this.options.authTimeoutMs === undefined ||
this.options.authTimeoutMs == 0
) {
this.options.authTimeoutMs = 30000;
}
let start = Date.now();
let timeout = this.options.authTimeoutMs;
let res = false;
while (start > Date.now() - timeout) {
res = await this.pupPage.evaluate(
'window.Debug?.VERSION != undefined',
);
if (res) {
break;
}
await new Promise((r) => setTimeout(r, 200));
}
if (!res) {
// Cancel any previous inject still running
if (this._injectAbort) this._injectAbort.abort();
const abort = new AbortController();
this._injectAbort = abort;
try {
const authTimeout = this.options.authTimeoutMs || 30000;
await this.pupPage
.waitForFunction('window.Debug?.VERSION != undefined', {
timeout: authTimeout,
signal: abort.signal,
})
.catch((err) => {
if (abort.signal.aborted) throw err;
throw 'auth timeout';
}
});
if (abort.signal.aborted) return;
await this.setDeviceName(
this.options.deviceName,
this.options.browserName,
@ -140,43 +136,28 @@ class Client extends EventEmitter {
const pairWithPhoneNumber = this.options.pairWithPhoneNumber;
const version = await this.getWWebVersion();
const needAuthentication = await this.pupPage.evaluate(async () => {
let state = window.require('WAWebSocketModel').Socket.state;
const needAuthHandle = await this.pupPage.waitForFunction(
() => {
const state =
window.require?.('WAWebSocketModel')?.Socket?.state;
if (
!state ||
state === 'OPENING' ||
state === 'UNLAUNCHED' ||
state === 'PAIRING'
) {
// wait till state changes
await new Promise((r) => {
window
.require('WAWebSocketModel')
.Socket.on(
'change:state',
function waitTillInit(_AppState, state) {
if (
state !== 'OPENING' &&
state !== 'UNLAUNCHED' &&
state !== 'PAIRING'
) {
window
.require('WAWebSocketModel')
.Socket.off(
'change:state',
waitTillInit,
);
r();
return false;
}
return {
need: state === 'UNPAIRED' || state === 'UNPAIRED_IDLE',
state,
};
},
{ timeout: authTimeout },
);
});
}
state = window.require('WAWebSocketModel').Socket.state;
return state == 'UNPAIRED' || state == 'UNPAIRED_IDLE';
});
const needAuthentication = await needAuthHandle.jsonValue();
if (needAuthentication) {
if (needAuthentication.need) {
const { failed, failureEventPayload, restart } =
await this.authStrategy.onAuthenticationNeeded();
@ -186,7 +167,10 @@ class Client extends EventEmitter {
* @event Client#auth_failure
* @param {string} message
*/
this.emit(Events.AUTHENTICATION_FAILURE, failureEventPayload);
this.emit(
Events.AUTHENTICATION_FAILURE,
failureEventPayload,
);
await this.destroy();
if (restart) {
// session restore failed so try again but without session to force new authentication
@ -197,20 +181,6 @@ class Client extends EventEmitter {
// Register qr/code events
if (pairWithPhoneNumber.phoneNumber) {
await exposeFunctionIfAbsent(
this.pupPage,
'onCodeReceivedEvent',
async (code) => {
/**
* Emitted when a pairing code is received
* @event Client#code
* @param {string} code Code
* @returns {string} Code that was just received
*/
this.emit(Events.CODE_RECEIVED, code);
return code;
},
);
this.requestPairingCode(
pairWithPhoneNumber.phoneNumber,
pairWithPhoneNumber.showNotification,
@ -218,6 +188,11 @@ class Client extends EventEmitter {
);
} else {
let qrRetries = 0;
this.on(Events.LOADING_SCREEN, () => {
qrRetries = 0;
});
await exposeFunctionIfAbsent(
this.pupPage,
'onQRChangedEvent',
@ -254,6 +229,9 @@ class Client extends EventEmitter {
const identityKeyB64 = window
.require('WABase64')
.encodeB64(registrationInfo.identityKeyPair.pubKey);
const advSecretKey = await window
.require('WAWebUserPrefsMultiDevice')
.getADVSecretKey();
const platform = window.require(
'WAWebCompanionRegClientUtils',
).DEVICE_PLATFORM;
@ -264,19 +242,30 @@ class Client extends EventEmitter {
',' +
identityKeyB64 +
',' +
window
.require('WAWebUserPrefsMultiDevice')
.getADVSecretKey() +
advSecretKey +
',' +
platform;
const onRefChange = (_, ref) => {
if (ref == null) return;
window.onQRChangedEvent(getQR(ref));
};
window.onQRChangedEvent(
getQR(window.require('WAWebConnModel').Conn.ref),
); // initial qr
window
.require('WAWebConnModel')
.Conn.on('change:ref', (_, ref) => {
window.onQRChangedEvent(getQR(ref));
}); // future QR changes
.Conn.on('change:ref', onRefChange); // future QR changes
// Remove QR listener once authentication succeeds
window
.require('WAWebSocketModel')
.Socket.on('change:hasSynced', () => {
window
.require('WAWebConnModel')
.Conn.off('change:ref', onRefChange);
});
});
}
}
@ -290,7 +279,9 @@ class Client extends EventEmitter {
!pairWithPhoneNumber.phoneNumber
) {
// refresh qr code
await this.pupPage.evaluate(() => {
window.require('WAWebCmd').Cmd.refreshQR();
});
}
},
);
@ -323,27 +314,23 @@ class Client extends EventEmitter {
webCacheOptions,
);
await webCache.persist(this.currentIndexHtml, version);
await webCache.persist(
this.currentIndexHtml,
version,
);
}
// Load util functions (serializers, helper functions)
await this.pupPage.evaluate(LoadUtils);
let start = Date.now();
let res = false;
while (start > Date.now() - 30000) {
// Check window.WWebJS Injection
res = await this.pupPage.evaluate(
'window.WWebJS != undefined',
);
if (res) {
break;
}
await new Promise((r) => setTimeout(r, 200));
}
if (!res) {
await this.pupPage
.waitForFunction(
'typeof window.WWebJS !== "undefined"',
{ timeout: 30000 },
)
.catch(() => {
throw 'ready timeout';
}
});
/**
* Current connection information
@ -401,31 +388,79 @@ class Client extends EventEmitter {
},
);
await this.pupPage.evaluate(() => {
window
.require('WAWebSocketModel')
.Socket.on('change:state', (_AppState, state) => {
window.onAuthAppStateChangedEvent(state);
});
window
.require('WAWebSocketModel')
.Socket.on('change:hasSynced', () => {
window.onAppStateHasSyncedEvent();
});
const Socket = window.require('WAWebSocketModel').Socket;
const Cmd = window.require('WAWebCmd').Cmd;
Cmd.on('offline_progress_update_from_bridge', () => {
const listeners = [
[
Socket,
'change:state',
(_AppState, state) => {
window.onAuthAppStateChangedEvent(state);
},
],
[
Socket,
'change:hasSynced',
() => {
window.onAppStateHasSyncedEvent();
},
],
[
Cmd,
'offline_progress_update_from_bridge',
() => {
window.onOfflineProgressUpdateEvent(
window
.require('WAWebOfflineHandler')
.OfflineMessageHandler.getOfflineDeliveryProgress(),
);
});
Cmd.on('logout', async () => {
},
],
[
Cmd,
'logout',
async () => {
await window.onLogoutEvent();
});
Cmd.on('logout_from_bridge', async () => {
},
],
[
Cmd,
'logout_from_bridge',
async () => {
await window.onLogoutEvent();
},
],
];
// Clean up old listeners to prevent accumulation on re-inject
if (window._wwjsListeners) {
for (const [obj, event, handler] of window._wwjsListeners) {
obj.off(event, handler);
}
}
for (const [obj, event, handler] of listeners) {
obj.on(event, handler);
}
window._wwjsListeners = listeners;
// Atomic hasSynced check in the same synchronous block as listener registration.
// If hasSynced is already true, Backbone won't fire change:hasSynced (no transition).
// If hasSynced is false, the listener above will catch the future transition.
const storeInjected = typeof window.WWebJS !== 'undefined';
if (Socket.hasSynced === true && !storeInjected) {
window.onAppStateHasSyncedEvent();
}
});
});
} catch (err) {
if (abort.signal.aborted) return; // superseded by newer inject
throw err;
} finally {
if (this._injectAbort === abort) {
this._injectAbort = null;
}
}
}
/**
@ -495,16 +530,37 @@ class Client extends EventEmitter {
referer: 'https://whatsapp.com/',
});
// Register framenavigated BEFORE inject so that if navigation
// interrupts inject, the handler triggers a fresh inject.
this._registerFramenavigatedHandler();
await this.inject();
}
_registerFramenavigatedHandler() {
if (this._framenavigatedRegistered) return;
this._framenavigatedRegistered = true;
this.pupPage.on('framenavigated', async (frame) => {
if (frame.url().includes('post_logout=1') || this.lastLoggedOut) {
if (frame.parentFrame() !== null) return;
const isLogout =
frame.url().includes('post_logout=1') || this.lastLoggedOut;
if (isLogout) {
this.emit(Events.DISCONNECTED, 'LOGOUT');
await this.authStrategy.logout();
await this.authStrategy.beforeBrowserInitialized();
await this.authStrategy.afterBrowserInitialized();
this.lastLoggedOut = false;
}
const storeAvailable = await this.pupPage.evaluate(() => {
return typeof window.WWebJS !== 'undefined';
});
if (!isLogout && storeAvailable) return;
await this.inject();
});
}
@ -1276,6 +1332,9 @@ class Client extends EventEmitter {
* Closes the client
*/
async destroy() {
if (this._injectAbort) this._injectAbort.abort();
this._framenavigatedRegistered = false;
const browser = this.pupBrowser;
const isConnected = browser?.isConnected?.();
if (isConnected) {