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 * Private function
*/ */
async inject() { async inject() {
if ( // Cancel any previous inject still running
this.options.authTimeoutMs === undefined || if (this._injectAbort) this._injectAbort.abort();
this.options.authTimeoutMs == 0 const abort = new AbortController();
) { this._injectAbort = abort;
this.options.authTimeoutMs = 30000;
} try {
let start = Date.now(); const authTimeout = this.options.authTimeoutMs || 30000;
let timeout = this.options.authTimeoutMs; await this.pupPage
let res = false; .waitForFunction('window.Debug?.VERSION != undefined', {
while (start > Date.now() - timeout) { timeout: authTimeout,
res = await this.pupPage.evaluate( signal: abort.signal,
'window.Debug?.VERSION != undefined', })
); .catch((err) => {
if (res) { if (abort.signal.aborted) throw err;
break;
}
await new Promise((r) => setTimeout(r, 200));
}
if (!res) {
throw 'auth timeout'; throw 'auth timeout';
} });
if (abort.signal.aborted) return;
await this.setDeviceName( await this.setDeviceName(
this.options.deviceName, this.options.deviceName,
this.options.browserName, this.options.browserName,
@ -140,43 +136,28 @@ class Client extends EventEmitter {
const pairWithPhoneNumber = this.options.pairWithPhoneNumber; const pairWithPhoneNumber = this.options.pairWithPhoneNumber;
const version = await this.getWWebVersion(); const version = await this.getWWebVersion();
const needAuthentication = await this.pupPage.evaluate(async () => { const needAuthHandle = await this.pupPage.waitForFunction(
let state = window.require('WAWebSocketModel').Socket.state; () => {
const state =
window.require?.('WAWebSocketModel')?.Socket?.state;
if ( if (
!state ||
state === 'OPENING' || state === 'OPENING' ||
state === 'UNLAUNCHED' || state === 'UNLAUNCHED' ||
state === 'PAIRING' state === 'PAIRING'
) { ) {
// wait till state changes return false;
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 {
need: state === 'UNPAIRED' || state === 'UNPAIRED_IDLE',
state,
};
}, },
{ timeout: authTimeout },
); );
}); const needAuthentication = await needAuthHandle.jsonValue();
}
state = window.require('WAWebSocketModel').Socket.state;
return state == 'UNPAIRED' || state == 'UNPAIRED_IDLE';
});
if (needAuthentication) { if (needAuthentication.need) {
const { failed, failureEventPayload, restart } = const { failed, failureEventPayload, restart } =
await this.authStrategy.onAuthenticationNeeded(); await this.authStrategy.onAuthenticationNeeded();
@ -186,7 +167,10 @@ class Client extends EventEmitter {
* @event Client#auth_failure * @event Client#auth_failure
* @param {string} message * @param {string} message
*/ */
this.emit(Events.AUTHENTICATION_FAILURE, failureEventPayload); this.emit(
Events.AUTHENTICATION_FAILURE,
failureEventPayload,
);
await this.destroy(); await this.destroy();
if (restart) { if (restart) {
// session restore failed so try again but without session to force new authentication // 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 // Register qr/code events
if (pairWithPhoneNumber.phoneNumber) { 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( this.requestPairingCode(
pairWithPhoneNumber.phoneNumber, pairWithPhoneNumber.phoneNumber,
pairWithPhoneNumber.showNotification, pairWithPhoneNumber.showNotification,
@ -218,6 +188,11 @@ class Client extends EventEmitter {
); );
} else { } else {
let qrRetries = 0; let qrRetries = 0;
this.on(Events.LOADING_SCREEN, () => {
qrRetries = 0;
});
await exposeFunctionIfAbsent( await exposeFunctionIfAbsent(
this.pupPage, this.pupPage,
'onQRChangedEvent', 'onQRChangedEvent',
@ -254,6 +229,9 @@ class Client extends EventEmitter {
const identityKeyB64 = window const identityKeyB64 = window
.require('WABase64') .require('WABase64')
.encodeB64(registrationInfo.identityKeyPair.pubKey); .encodeB64(registrationInfo.identityKeyPair.pubKey);
const advSecretKey = await window
.require('WAWebUserPrefsMultiDevice')
.getADVSecretKey();
const platform = window.require( const platform = window.require(
'WAWebCompanionRegClientUtils', 'WAWebCompanionRegClientUtils',
).DEVICE_PLATFORM; ).DEVICE_PLATFORM;
@ -264,19 +242,30 @@ class Client extends EventEmitter {
',' + ',' +
identityKeyB64 + identityKeyB64 +
',' + ',' +
window advSecretKey +
.require('WAWebUserPrefsMultiDevice')
.getADVSecretKey() +
',' + ',' +
platform; platform;
const onRefChange = (_, ref) => {
if (ref == null) return;
window.onQRChangedEvent(getQR(ref));
};
window.onQRChangedEvent( window.onQRChangedEvent(
getQR(window.require('WAWebConnModel').Conn.ref), getQR(window.require('WAWebConnModel').Conn.ref),
); // initial qr ); // initial qr
window window
.require('WAWebConnModel') .require('WAWebConnModel')
.Conn.on('change:ref', (_, ref) => { .Conn.on('change:ref', onRefChange); // future QR changes
window.onQRChangedEvent(getQR(ref));
}); // 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 !pairWithPhoneNumber.phoneNumber
) { ) {
// refresh qr code // refresh qr code
await this.pupPage.evaluate(() => {
window.require('WAWebCmd').Cmd.refreshQR(); window.require('WAWebCmd').Cmd.refreshQR();
});
} }
}, },
); );
@ -323,27 +314,23 @@ class Client extends EventEmitter {
webCacheOptions, webCacheOptions,
); );
await webCache.persist(this.currentIndexHtml, version); await webCache.persist(
this.currentIndexHtml,
version,
);
} }
// Load util functions (serializers, helper functions) // Load util functions (serializers, helper functions)
await this.pupPage.evaluate(LoadUtils); await this.pupPage.evaluate(LoadUtils);
let start = Date.now(); await this.pupPage
let res = false; .waitForFunction(
while (start > Date.now() - 30000) { 'typeof window.WWebJS !== "undefined"',
// Check window.WWebJS Injection { timeout: 30000 },
res = await this.pupPage.evaluate( )
'window.WWebJS != undefined', .catch(() => {
);
if (res) {
break;
}
await new Promise((r) => setTimeout(r, 200));
}
if (!res) {
throw 'ready timeout'; throw 'ready timeout';
} });
/** /**
* Current connection information * Current connection information
@ -401,31 +388,79 @@ class Client extends EventEmitter {
}, },
); );
await this.pupPage.evaluate(() => { await this.pupPage.evaluate(() => {
window const Socket = window.require('WAWebSocketModel').Socket;
.require('WAWebSocketModel')
.Socket.on('change:state', (_AppState, state) => {
window.onAuthAppStateChangedEvent(state);
});
window
.require('WAWebSocketModel')
.Socket.on('change:hasSynced', () => {
window.onAppStateHasSyncedEvent();
});
const Cmd = window.require('WAWebCmd').Cmd; 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.onOfflineProgressUpdateEvent(
window window
.require('WAWebOfflineHandler') .require('WAWebOfflineHandler')
.OfflineMessageHandler.getOfflineDeliveryProgress(), .OfflineMessageHandler.getOfflineDeliveryProgress(),
); );
}); },
Cmd.on('logout', async () => { ],
[
Cmd,
'logout',
async () => {
await window.onLogoutEvent(); await window.onLogoutEvent();
}); },
Cmd.on('logout_from_bridge', async () => { ],
[
Cmd,
'logout_from_bridge',
async () => {
await window.onLogoutEvent(); 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/', 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(); await this.inject();
}
_registerFramenavigatedHandler() {
if (this._framenavigatedRegistered) return;
this._framenavigatedRegistered = true;
this.pupPage.on('framenavigated', async (frame) => { 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'); this.emit(Events.DISCONNECTED, 'LOGOUT');
await this.authStrategy.logout(); await this.authStrategy.logout();
await this.authStrategy.beforeBrowserInitialized(); await this.authStrategy.beforeBrowserInitialized();
await this.authStrategy.afterBrowserInitialized(); await this.authStrategy.afterBrowserInitialized();
this.lastLoggedOut = false; this.lastLoggedOut = false;
} }
const storeAvailable = await this.pupPage.evaluate(() => {
return typeof window.WWebJS !== 'undefined';
});
if (!isLogout && storeAvailable) return;
await this.inject(); await this.inject();
}); });
} }
@ -1276,6 +1332,9 @@ class Client extends EventEmitter {
* Closes the client * Closes the client
*/ */
async destroy() { async destroy() {
if (this._injectAbort) this._injectAbort.abort();
this._framenavigatedRegistered = false;
const browser = this.pupBrowser; const browser = this.pupBrowser;
const isConnected = browser?.isConnected?.(); const isConnected = browser?.isConnected?.();
if (isConnected) { if (isConnected) {