Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): record the credential deletion the stuck-auth self-heal performs (#986)

Yudhi Armyndharis517a4dc5f17f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 923563cf5..e479308b5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -26,6 +26,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
neighbouring engine options, so an unset value still resolves to the documented opt-out default and
only an explicit `true` starts sessions at boot.
+- **Deleting a session's stored WhatsApp credentials is now recorded when it happens** (#981). The
+ whatsapp-web.js adapter clears a session's auth directory to recover one that authenticated but never
+ reached runtime readiness within 90 seconds, and that directory holds the only copy of the
+ credentials — once removed, no restart can restore the link and every later start can do nothing but
+ present a fresh QR. The adapter logged only the *failure* to remove it, so a successful wipe left no
+ trace at all: the sole symptom was a session that quietly stopped reconnecting, indistinguishable in
+ the logs from a WhatsApp-side logout or a profile nothing had touched. The removal now logs a warning
+ naming the directory and the session, and the readiness-timeout warning that precedes it carries the
+ session id too — on a multi-session host that is what separates "one session timed out" from "every
+ session did", which have very different causes. No behaviour changes; this closes a blind spot that
+ made the destructive path impossible to confirm from a deployment's own logs.
+
- **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
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index f47569765..566ee8080 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -1302,6 +1302,53 @@ describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {
rmSpy.mockRestore();
});
+ // #981: clearing the auth dir destroys the ONLY copy of the session's WhatsApp credentials, and the
+ // loss is permanent — every later start finds an empty profile and can only show a QR. Until now the
+ // adapter logged only the FAILURE to delete, so a successful wipe left no trace at all and triage
+ // could not tell an OpenWA self-heal apart from a WhatsApp-side logout or an untouched profile.
+ it('records the credential deletion, naming the session and the directory removed', async () => {
+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);
+ const adapter = newAdapter();
+ const logger = (adapter as unknown as { logger: { warn: jest.Mock } }).logger;
+ const warnSpy = jest.spyOn(logger, 'warn').mockImplementation(() => undefined);
+
+ await (adapter as unknown as { clearLocalAuth: () => Promise<void> }).clearLocalAuth.call(adapter);
+
+ expect(rmSpy).toHaveBeenCalled();
+ const deletion = warnSpy.mock.calls.find(([message]) => /deleted/i.test(String(message)));
+ expect(deletion).toBeDefined();
+ expect(String(deletion?.[0])).toContain('session-sess-1'); // which profile is gone
+ expect(deletion?.[1]).toMatchObject({ sessionId: 'sess-1' }); // which session, for a multi-session host
+
+ warnSpy.mockRestore();
+ rmSpy.mockRestore();
+ });
+
+ // #981: the reporter saw "all sessions" come back as QR. Without a sessionId on the timeout warning
+ // there is no way to tell from the logs whether one session timed out or every one of them did.
+ it('identifies the session in the readiness-timeout warning that precedes the deletion', async () => {
+ jest.useFakeTimers();
+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);
+
+ const adapter = newAdapter();
+ const logger = (adapter as unknown as { logger: { warn: jest.Mock } }).logger;
+ const warnSpy = jest.spyOn(logger, 'warn').mockImplementation(() => undefined);
+ const { client } = attachFakeClient(adapter, {
+ getState: jest.fn().mockReturnValue(new Promise<never>(() => {})),
+ destroy: jest.fn().mockResolvedValue(undefined),
+ });
+
+ client.emit('authenticated');
+ await jest.advanceTimersByTimeAsync(95_000); // past the 90s give-up deadline
+
+ const timeout = warnSpy.mock.calls.find(([message]) => /Timed out waiting/i.test(String(message)));
+ expect(timeout).toBeDefined();
+ expect(timeout?.[1]).toMatchObject({ sessionId: 'sess-1' });
+
+ warnSpy.mockRestore();
+ 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 572616041..f87ccc4a1 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -1107,6 +1107,9 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
'is stuck after the QR scan (usually the auto-selected WhatsApp Web build is incompatible). ' +
'Clearing it to re-pair; pin a known-good version via WWEBJS_WEB_VERSION (see ' +
'docs/12-troubleshooting-faq.md) if it keeps recurring.',
+ // Name the session: on a multi-session host this warning is the only way to tell whether one
+ // session timed out or every one of them did, and the two have very different causes.
+ { sessionId: this.config.sessionId, action: 'ready_reconcile_timeout' },
);
this.clearReadyReconcile();
// Self-heal: don't leave the session stuck at "authenticating" forever — clear the broken auth
@@ -1180,9 +1183,26 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
/** Remove this session's LocalAuth directory so the next start re-pairs from a clean slate. */
private async clearLocalAuth(): Promise<void> {
const dir = path.join(path.resolve(this.config.sessionDataPath), `session-${this.config.sessionId}`);
- await fs.promises.rm(dir, { recursive: true, force: true }).catch((error: unknown) => {
- this.logger.warn(`Could not clear stale auth at ${dir}`, { error: String(error) });
- });
+ await fs.promises
+ .rm(dir, { recursive: true, force: true })
+ .then(() => {
+ // #981: this is the only copy of the session's WhatsApp credentials, and removing it is not
+ // recoverable — every later start finds an empty profile and can do nothing but show a QR. Say
+ // so at the moment it happens: otherwise the sole trace is a session that silently stops
+ // reconnecting, indistinguishable from a WhatsApp-side logout or an untouched profile.
+ this.logger.warn(
+ `Deleted this session's stored WhatsApp credentials at ${dir}. That was the only copy, so the ` +
+ 'next start cannot restore the link and comes back with a fresh QR to scan.',
+ { sessionId: this.config.sessionId, dir, action: 'auth_cleared' },
+ );
+ })
+ .catch((error: unknown) => {
+ this.logger.warn(`Could not clear stale auth at ${dir}`, {
+ sessionId: this.config.sessionId,
+ dir,
+ error: String(error),
+ });
+ });
}
/**