Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): clear a session's credentials once per WhatsApp unlink
Yudhi Armyndharis19d05fed8ff4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9e1d4bad3..f0b647fb9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **A WhatsApp-initiated unlink now clears a session's stored credentials once rather than twice** — whatsapp-web.js can raise the logout event more than once for a single unlink and nothing deduplicated it, so the repeats raced each other and a still-open browser into the `ENOTEMPTY` failure the removal now carries the retry budget to survive.- **A data import now carries each session's ownership lease by its remaining time instead of its original deadline** — a restore re-applied the deadline unchanged, so one that ran longer than a claim had left committed that claim as expired, including claims held by other nodes whose engines never stopped.- **A refused data import no longer offers a retry that stops live engines** — the one refusal whose retry is destructive now carries `IMPORT_WOULD_ORPHAN_ENGINES` and the dashboard matches it positively, so a refusal that only asks the operator to wait can no longer present a confirm whose OK re-runs the replace-all with `stopOrphans=true`.- **A data import is refused with `409` when another transaction holds the connection** — on SQLite it would otherwise nest inside that transaction and commit into it rather than to disk, so a restore reported as successful could vanish with that transaction's rollback.diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 74b41339b..f95e82c64 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -1245,6 +1245,7 @@ describe('WhatsAppWebJsAdapter credential-teardown observation', () => {expect(rmSpy).toHaveBeenCalledWith(expect.stringContaining('session-sess-1'), {recursive: true,force: true,+ maxRetries: 4,});});@@ -1260,6 +1261,57 @@ describe('WhatsAppWebJsAdapter credential-teardown observation', () => {expect(onCredentialTeardownStarted).toHaveBeenCalledTimes(1);});+ // #1072: whatsapp-web.js emits 'disconnected' from a `.on('framenavigated')` listener with no guard+ // of its own — it resets `lastLoggedOut` only after three awaits and never filters on the main frame+ // — so one unlink can raise the event more than once. The registration above is keyed on+ // `logoutInitiated`, which stays false throughout a WhatsApp-initiated unlink, and it sits ABOVE the+ // duplicate-event latch on purpose (#994), so every repeat used to start another rm of the same+ // profile. The reporter's log is that signature exactly: two deletion lines, one disconnect, one+ // reconnect — with the two rms racing each other and a still-open Chromium.+ it('removes the credentials once for a repeated WhatsApp LOGOUT (one unlink can raise the event twice)', () => {+ const adapter = newAdapter();+ const { client, onCredentialTeardownStarted } = attach(adapter);++ client.emit('disconnected', 'LOGOUT');+ client.emit('disconnected', 'LOGOUT');++ // One unlink, one removal — and one fence for the lifecycle to await.+ expect(onCredentialTeardownStarted).toHaveBeenCalledTimes(1);+ expect(rmSpy).toHaveBeenCalledTimes(1);+ });++ // The latch is one-shot per adapter, not a coalescing window: it must hold even when the repeat+ // arrives after the rest of the handler has latched, which is the ordering the reporter hit.+ it('holds the once-only removal when the repeat lands after the disconnect was reported', () => {+ const adapter = newAdapter();+ const { client, onCredentialTeardownStarted } = attach(adapter);++ client.emit('disconnected', 'LOGOUT');+ (adapter as unknown as { disconnectReported: boolean }).disconnectReported = true;+ client.emit('disconnected', 'LOGOUT');++ expect(onCredentialTeardownStarted).toHaveBeenCalledTimes(1);+ expect(rmSpy).toHaveBeenCalledTimes(1);+ });++ // #1072: the reporter's second cycle logged ENOTEMPTY on the leveldb dir. On a WhatsApp-initiated+ // unlink whatsapp-web.js does NOT close the browser first (Client.js emits from `framenavigated`;+ // only the explicit Client.logout() closes it), so Chromium is still rotating IndexedDB files while+ // the removal walks the tree. LocalAuth's own rm survives that with `rmMaxRetries ?? 4`; ours passed+ // no budget at all, leaving Node's default of 0 — which is why the error surfaced on ours and not+ // the library's.+ it('gives the removal the retry budget LocalAuth uses, so a live Chromium cannot fail it', async () => {+ const adapter = newAdapter();++ await (adapter as unknown as { clearLocalAuth: () => Promise<void> }).clearLocalAuth.call(adapter);++ expect(rmSpy).toHaveBeenCalledWith(expect.stringContaining('session-sess-1'), {+ recursive: true,+ force: true,+ maxRetries: 4,+ });+ });+it('still reports nothing else for a latched LOGOUT — no status change and no onDisconnected', () => {// Registering the rm must NOT resurrect the rest of the handler: a finished adapter still must// not drive a status transition or schedule a reconnect for its replacement.@@ -1906,7 +1958,11 @@ describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {expect(jest.getTimerCount()).toBe(0); // gave up at the 90s deadlineexpect(client.getState).toHaveBeenCalledTimes(1); // at-most-one-in-flight guard held// Self-heal: the broken auth is cleared and a disconnect surfaced so the lifecycle re-pairs (QR).- expect(rmSpy).toHaveBeenCalledWith(expect.stringContaining('session-sess-1'), { recursive: true, force: true });+ expect(rmSpy).toHaveBeenCalledWith(expect.stringContaining('session-sess-1'), {+ recursive: true,+ force: true,+ maxRetries: 4,+ });expect(onDisconnected).toHaveBeenCalled();rmSpy.mockRestore();diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 678c1899e..cd29e321f 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -215,6 +215,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin// registering one for a WhatsApp-initiated logout, including one that lands after another teardown// path has already latched the flags below.private logoutInitiated = false;+ // Set once a WhatsApp-initiated LOGOUT has started this session's credential removal, so a repeat of+ // the same unlink cannot start a second one (#1072). Never reset — an adapter is single-use, and the+ // profile is gone after the first removal either way.+ private credentialTeardownStarted = false;// Set once the adapter ACTIVELY transitions to DISCONNECTED (engine disconnect, puppeteer death,// stuck-auth recovery, teardown). Same single-use contract as `tearingDown`, but it latches earlier:// on LOGOUT whatsapp-web.js keeps the browser and re-runs inject(), while the lifecycle only replaces@@ -602,18 +606,23 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginthis.client.on('call', call => this.handleIncomingCall(call));this.client.on('disconnected', reason => {- // A LOGOUT means whatsapp-web.js is ABOUT to delete this session's profile: `Client.logout()`- // ends in `authStrategy.logout()` → `LocalAuth.logout()` → `fs.rm(userDataDir)`, and the- // library emits this event BEFORE that await (Client.js: emit DISCONNECTED 'LOGOUT', then- // `pupBrowser.close()`, then `authStrategy.logout()`). That rm happens whatever this listener- // does, so it MUST be surfaced to the lifecycle before the latch check below can drop out —- // otherwise a stop()/destroy() that latched first hides an in-flight rm, the name fence sees- // nothing pending, and a later start() under the same name can have its freshly written- // profile deleted by it (the #994 hazard, through a narrower window).+ // A LOGOUT means whatsapp-web.js is ABOUT to delete this session's profile. The only site that+ // emits this reason is the `framenavigated` listener, which emits and THEN awaits+ // `authStrategy.logout()` → `LocalAuth.logout()` → `fs.rm(userDataDir)` — with the browser still+ // open (only the explicit `Client.logout()` closes it first, and that path emits nothing). That+ // rm happens whatever this listener does, so it MUST be surfaced to the lifecycle before the+ // latch check below can drop out — otherwise a stop()/destroy() that latched first hides an+ // in-flight rm, the name fence sees nothing pending, and a later start() under the same name can+ // have its freshly written profile deleted by it (the #994 hazard, through a narrower window).//- // Skipped only when THIS adapter's logout() started it: that path already registered the real- // `client.logout()` promise, which covers the same rm and settles no earlier.- if (reason === 'LOGOUT' && !this.logoutInitiated) {+ // Skipped when THIS adapter's logout() started it: that path already registered the real+ // `client.logout()` promise, which covers the same rm and settles no earlier. Skipped again on+ // every repeat, because the listener above carries no guard of its own — it resets its+ // `lastLoggedOut` flag only after three awaits and never checks for the main frame, so one unlink+ // can raise this event more than once (#1072). Sitting above the duplicate-event latch is what+ // makes that reachable, so the guard has to be its own one-shot rather than that latch.+ if (reason === 'LOGOUT' && !this.logoutInitiated && !this.credentialTeardownStarted) {+ this.credentialTeardownStarted = true;// Idempotent stand-in for the library's own rm, which we cannot get a handle on:// `fs.rm(force: true)` races it safely and gives the lifecycle something to await.this.callbacks.onCredentialTeardownStarted?.(this.clearLocalAuth());@@ -1173,7 +1182,11 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginprivate 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 })+ // maxRetries mirrors LocalAuth's own default: on a WhatsApp-initiated unlink the library never+ // closes the browser, so Chromium is still rotating IndexedDB files while this walks the tree and+ // a bare rm reports ENOTEMPTY (#1072). Node's default is 0 retries, which is why the failure+ // surfaced here and never on the library's removal of the same directory.+ .rm(dir, { recursive: true, force: true, maxRetries: 4 }).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