Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(wwebjs): keep a restored session's credentials at the ready deadline

Yudhi Armyndharis0526d6b47f7b
diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.md
index 0d3583350..0544ea0e1 100644
--- a/docs/12-troubleshooting-faq.md
+++ b/docs/12-troubleshooting-faq.md
@@ -371,6 +371,15 @@ the pin did not cover that page load, and a session that works on that build nee
Whether the service worker answers can differ from one page load to the next, so a later restart may
load the pin. When you report a problem with the session, include both builds.
+If the session is still `authenticating` 90 s after the link, OpenWA stops waiting. If WhatsApp Web
+reports the session connected but its event bridge never attached, the session is marked `failed` with
+the credentials kept (action `ready_reconcile_bridge_dead`), whether it was linked in that start or
+restored: restart it to relaunch the browser. Otherwise, a session linked by a QR or pairing code in
+that start has its saved credentials cleared once and comes back with a fresh QR. A session restored
+from saved credentials is marked `failed` with the credentials kept (action
+`ready_reconcile_timeout_restored`): restart it; to pair again, delete it (which clears the saved
+credentials) and create it anew; or pin `WWEBJS_WEB_VERSION`.
+
### Issue: QR generation times out on slow first boot (WSL2 / low-resource)
> **Engine:** This issue applies to the `whatsapp-web.js` engine only. If you are using `ENGINE_TYPE=baileys`, skip this section.
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index f5f5d4d64..308e0f0f9 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -1892,6 +1892,10 @@ describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {
return { client, onReady, onStateChanged };
};
+ // The readiness deadline clears credentials only for a pairing this engine showed a QR for.
+ const markFreshPairing = (adapter: WhatsAppWebJsAdapter): void => {
+ (adapter as unknown as { lifecycle: { qrShown: boolean } }).lifecycle.qrShown = true;
+ };
const deferredVoid = (): { promise: Promise<void>; resolve: () => void } => {
let resolve = (): void => undefined;
const promise = new Promise<void>(res => {
@@ -2338,7 +2342,7 @@ describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {
client.emit('authenticated'); // re-fire 80s in — must not restart the window
await jest.advanceTimersByTimeAsync(11_000); // 91s total since the FIRST authenticated
- expect(adapter.getStatus()).toBe(EngineStatus.AUTHENTICATING);
+ expect(adapter.getStatus()).toBe(EngineStatus.FAILED); // a restore gives up at the deadline
expect(jest.getTimerCount()).toBe(0); // gave up at 90s; not reset by the re-fire
});
@@ -2627,6 +2631,7 @@ describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {
});
const onDisconnected = jest.fn();
(adapter as unknown as { callbacks: { onDisconnected?: jest.Mock } }).callbacks.onDisconnected = onDisconnected;
+ markFreshPairing(adapter);
client.emit('authenticated');
await jest.advanceTimersByTimeAsync(50_000);
@@ -2739,6 +2744,7 @@ describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {
getState: jest.fn().mockReturnValue(new Promise<never>(() => {})),
destroy: jest.fn().mockResolvedValue(undefined),
});
+ markFreshPairing(adapter);
client.emit('authenticated');
await jest.advanceTimersByTimeAsync(95_000); // past the 90s give-up deadline
@@ -2751,6 +2757,112 @@ describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {
rmSpy.mockRestore();
});
+ // A restore never showed a QR, so nothing says its saved credentials are bad; a stuck restore is
+ // usually an incompatible WhatsApp Web build, which deleting the only copy of the link cannot fix.
+ it('keeps the saved credentials of a restored session stuck past the deadline and marks it failed', async () => {
+ jest.useFakeTimers();
+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);
+
+ const adapter = newAdapter();
+ const logger = (adapter as unknown as { logger: { error: jest.Mock } }).logger;
+ const errorSpy = jest.spyOn(logger, 'error').mockImplementation(() => undefined);
+ const { client } = attachFakeClient(adapter, {
+ getState: jest.fn().mockReturnValue(new Promise<never>(() => {})),
+ destroy: jest.fn().mockResolvedValue(undefined),
+ });
+ const onError = jest.fn();
+ const onDisconnected = jest.fn();
+ Object.assign((adapter as unknown as { callbacks: object }).callbacks, { onError, onDisconnected });
+
+ client.emit('authenticated'); // no 'qr' first: a restore of saved credentials
+ await jest.advanceTimersByTimeAsync(95_000);
+
+ expect(rmSpy).not.toHaveBeenCalled();
+ expect(adapter.getStatus()).toBe(EngineStatus.FAILED);
+ expect(onError).toHaveBeenCalledWith(expect.stringContaining('credentials were kept'));
+ // A FAILED session has no engine, so a logout answers 400; only a delete clears the credentials.
+ expect(onError).toHaveBeenCalledWith(expect.stringContaining('to pair again, delete it'));
+ expect(onError).not.toHaveBeenCalledWith(expect.stringContaining('log it out'));
+ expect(onDisconnected).not.toHaveBeenCalled();
+ expect(jest.getTimerCount()).toBe(0);
+ const failed = errorSpy.mock.calls.find(
+ ([, , meta]) => (meta as { action?: string })?.action === 'ready_reconcile_timeout_restored',
+ );
+ expect(failed?.[2]).toMatchObject({ sessionId: 'sess-1' });
+
+ errorSpy.mockRestore();
+ rmSpy.mockRestore();
+ });
+
+ it('records a shown QR as a fresh pairing, but not one dropped by a finished adapter', () => {
+ const adapter = newAdapter();
+ const lifecycle = (adapter as unknown as { lifecycle: { qrShown: boolean } }).lifecycle;
+ const { client } = attachFakeClient(adapter);
+
+ client.emit('qr', '2@abc');
+ expect(lifecycle.qrShown).toBe(true);
+
+ const finished = newAdapter();
+ const finishedLifecycle = (finished as unknown as { lifecycle: { qrShown: boolean; disconnectReported: boolean } })
+ .lifecycle;
+ const { client: finishedClient } = attachFakeClient(finished);
+ finishedLifecycle.disconnectReported = true;
+
+ finishedClient.emit('qr', '2@abc');
+ expect(finishedLifecycle.qrShown).toBe(false);
+ });
+
+ it('drops a qr from a client that is no longer the live one', async () => {
+ (qrcode.toDataURL as unknown as jest.Mock).mockClear();
+ const adapter = newAdapter();
+ const lifecycle = (adapter as unknown as { lifecycle: { qrShown: boolean } }).lifecycle;
+ const { client: stale } = attachFakeClient(adapter);
+ const onQRCode = jest.fn();
+ (adapter as unknown as { callbacks: { onQRCode: jest.Mock } }).callbacks.onQRCode = onQRCode;
+ // A replacement client is live while the old one still has its listeners.
+ (adapter as unknown as { client: unknown }).client = new EventEmitter();
+
+ stale.emit('qr', '2@stale');
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(qrcode.toDataURL as unknown as jest.Mock).not.toHaveBeenCalled();
+ expect(lifecycle.qrShown).toBe(false);
+ expect(adapter.getStatus()).not.toBe(EngineStatus.QR_READY);
+ expect(onQRCode).not.toHaveBeenCalled();
+ });
+
+ // The wedged Chromium still writes into the profile being removed; killing it first stops that. The
+ // kill fires the browser's 'disconnected', which must not report a second disconnect mid-removal.
+ it('kills the browser before clearing the saved session, and reports the disconnect once', async () => {
+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);
+ const adapter = newAdapter();
+ const pupBrowser = new EventEmitter();
+ const kill = jest.fn(() => pupBrowser.emit('disconnected'));
+ Object.assign(pupBrowser, { process: () => ({ kill }) });
+ attachFakeClient(adapter, {
+ pupBrowser,
+ pupPage: Object.assign(new EventEmitter(), { evaluate: jest.fn().mockResolvedValue(true) }),
+ destroy: jest.fn().mockResolvedValue(undefined),
+ } as never);
+ (adapter as unknown as { lifecycle: { status: EngineStatus } }).lifecycle.status = EngineStatus.AUTHENTICATING;
+ (adapter as unknown as { attachPuppeteerLifecycleListeners: () => void }).attachPuppeteerLifecycleListeners();
+ const onDisconnected = jest.fn();
+ Object.assign((adapter as unknown as { callbacks: object }).callbacks, {
+ onDisconnected,
+ claimStuckAuthRecovery: () => true,
+ });
+
+ await (adapter as unknown as { recoverFromStuckAuth: () => Promise<void> }).recoverFromStuckAuth.call(adapter);
+
+ expect(kill).toHaveBeenCalledWith('SIGKILL');
+ expect(kill.mock.invocationCallOrder[0]).toBeLessThan(rmSpy.mock.invocationCallOrder[0]);
+ expect(onDisconnected).toHaveBeenCalledTimes(1);
+ expect(onDisconnected).toHaveBeenCalledWith(expect.stringContaining('cleared for re-pairing'));
+
+ rmSpy.mockRestore();
+ });
+
it('fails terminally on a second stuck-auth cycle (no QR -> timeout -> clear loop)', async () => {
const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);
const adapter = newAdapter();
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index a48088210..de3f03d8d 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -238,6 +238,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
setStatus: status => this.lifecycle.setStatus(status),
getCallbacks: () => this.callbacks,
markReadyFromClientInfo: () => this.lifecycle.markReadyFromClientInfo(),
+ wasFreshPairing: () => this.lifecycle.qrShown,
recoverFromStuckAuth: () => this.recoverFromStuckAuth(),
});
this.stuckAuth = new WwebjsStuckAuth({
diff --git a/src/engine/adapters/wwebjs-lifecycle.ts b/src/engine/adapters/wwebjs-lifecycle.ts
index 2ff36a190..804a55b29 100644
--- a/src/engine/adapters/wwebjs-lifecycle.ts
+++ b/src/engine/adapters/wwebjs-lifecycle.ts
@@ -236,6 +236,10 @@ export class WwebjsLifecycle {
* re-authenticate, and neither belongs to the session any more (#982). Aliased by the adapter's
* `disconnectReported` accessor. */
disconnectReported = false;
+ /** Set when this engine's page asked for a QR (whatsapp-web.js emits 'qr' only for an UNPAIRED page,
+ * and a pairing code needs QR_READY), so it tells a fresh pairing from a restore of saved
+ * credentials. The readiness deadline may clear credentials only for a fresh pairing. */
+ qrShown = false;
// Navigation re-inject window (#1081): stamped by our framenavigated listener, closed by the
// library's re-emitted 'ready' and by teardown. Timestamps, never timers — several suites pin
// exact jest timer counts, and a timer would also outlive the single-use adapter.
@@ -562,14 +566,18 @@ 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.tearingDown || this.disconnectReported || this.status === EngineStatus.FAILED || !this.client) {
+ if (
+ this.client !== source ||
+ this.tearingDown ||
+ this.disconnectReported ||
+ this.status === EngineStatus.FAILED
+ ) {
return;
}
- // Capture the source client so the post-await fence can prove THIS client is still the live one.
+ 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
// qrCode is only touched once the fence re-proves the source client and the finished flags.
- const sourceClient = this.client;
try {
const encodedQr = await qrcode.toDataURL(qr);
// Post-await fence: the encode resolved, but the source client may have disconnected or been
@@ -579,7 +587,7 @@ export class WwebjsLifecycle {
// (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 !== sourceClient ||
+ this.client !== source ||
this.tearingDown ||
this.disconnectReported ||
this.getStatus() === EngineStatus.FAILED
@@ -769,7 +777,14 @@ export class WwebjsLifecycle {
* signal wins, no double-report).
*/
private handlePuppeteerDeath(reason: string): void {
- if (this.tearingDown || this.status === EngineStatus.DISCONNECTED || this.status === EngineStatus.FAILED) {
+ // No client means the stuck-auth recovery (or an init retry) already let go of this browser and
+ // killed it on purpose; that recovery reports the disconnect itself once the profile is cleared.
+ if (
+ this.tearingDown ||
+ !this.client ||
+ this.status === EngineStatus.DISCONNECTED ||
+ this.status === EngineStatus.FAILED
+ ) {
return;
}
this.host.clearReadyReconcile();
diff --git a/src/engine/adapters/wwebjs-reconcile.ts b/src/engine/adapters/wwebjs-reconcile.ts
index a1a1b5efa..76d59264c 100644
--- a/src/engine/adapters/wwebjs-reconcile.ts
+++ b/src/engine/adapters/wwebjs-reconcile.ts
@@ -20,7 +20,9 @@ export interface WwebjsReadyReconcileHost {
getCallbacks(): EngineEventCallbacks;
/** Promote to READY off the live client's info — the lifecycle's own ready path. */
markReadyFromClientInfo(): void;
- /** The deadline's non-bridge branch: clear the broken auth and let the lifecycle re-pair. */
+ /** Whether this engine showed a QR before authenticating: a fresh pairing, not a restored session. */
+ wasFreshPairing(): boolean;
+ /** The deadline's fresh-pairing branch: clear the broken auth and let the lifecycle re-pair. */
recoverFromStuckAuth(): Promise<void>;
}
@@ -89,6 +91,27 @@ export class WwebjsReadyReconcile {
);
return;
}
+ // A session restored from saved credentials never showed a QR, so nothing says those
+ // credentials are bad: a stuck restore is far more often an incompatible WhatsApp Web build,
+ // which a re-pair does not fix. Clearing them is not reversible, so keep them and fail loudly.
+ if (!this.host.wasFreshPairing()) {
+ this.host.logger.error(
+ 'WhatsApp Web restored the saved session but it never became ready within the readiness ' +
+ 'deadline; the session is marked failed and the saved credentials were kept.',
+ undefined,
+ { sessionId: this.host.config.sessionId, action: 'ready_reconcile_timeout_restored' },
+ );
+ this.clearReadyReconcile();
+ this.host.setStatus(EngineStatus.FAILED);
+ this.host
+ .getCallbacks()
+ .onError?.(
+ 'WhatsApp Web restored the saved session but never became ready; the saved credentials were kept. ' +
+ 'Restart the session; to pair again, delete it (which clears the saved credentials) and create ' +
+ 'it anew. Pin WWEBJS_WEB_VERSION if it keeps recurring.',
+ );
+ return;
+ }
this.host.logger.warn(
'Timed out waiting for WhatsApp Web runtime readiness after authentication — the saved session ' +
'is stuck after the QR scan (usually the auto-selected WhatsApp Web build is incompatible). ' +
diff --git a/src/engine/adapters/wwebjs-stuck-auth.ts b/src/engine/adapters/wwebjs-stuck-auth.ts
index 9d1a22a75..e488c6798 100644
--- a/src/engine/adapters/wwebjs-stuck-auth.ts
+++ b/src/engine/adapters/wwebjs-stuck-auth.ts
@@ -22,6 +22,9 @@ export interface WwebjsStuckAuthHost {
getCallbacks(): EngineEventCallbacks;
}
+/** The Puppeteer Browser whatsapp-web.js keeps on the client; `process()` is null once Chromium is gone. */
+type BrowserHandle = { pupBrowser?: { process?: () => { kill?: (sig: string) => void } | null } };
+
export class WwebjsStuckAuth {
// Guards the stuck-auth self-heal so it runs at most once per engine: a re-paired session that still
// can't reach readiness fails terminally instead of looping QR -> timeout -> clear forever.
@@ -69,8 +72,19 @@ export class WwebjsStuckAuth {
const client = this.host.getClient();
this.host.setClient(null);
- // Clear auth + disconnect FIRST (the recovery path), then tear the wedged client down in the
- // background so a hung Chromium destroy can't block (or skip) the recovery.
+ // Kill the wedged Chromium before removing its profile: a live browser keeps writing into the
+ // directory being removed, which can exhaust the rm retries and leave half a profile behind.
+ try {
+ const browser = (client as unknown as BrowserHandle | null)?.pupBrowser;
+ browser?.process?.()?.kill?.('SIGKILL');
+ } catch (err) {
+ this.host.logger.warn('Could not kill the browser before clearing the saved session', {
+ sessionId: this.host.config.sessionId,
+ error: String(err),
+ });
+ }
+ // Clear auth + disconnect (the recovery path), then finish the client teardown in the background
+ // so a hung destroy can't block (or skip) the recovery.
await this.clearLocalAuth();
this.host.setStatus(EngineStatus.DISCONNECTED);
// onDisconnected drives the lifecycle's reconnect, which re-creates the engine with no saved auth