Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): keep stuck-auth recovery budget across reconnects
Yudhi Armyndharis9b37ac170d26
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex db77f421f..b6af9baa0 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -1602,6 +1602,113 @@ describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {expect(rmSpy).toHaveBeenCalledTimes(1); // auth cleared only oncermSpy.mockRestore();});++ // Stuck-auth recovery budget is now owned by the SESSION, not the adapter. The adapter asks the+ // session's synchronous claim callback before any destructive I/O; a DENIAL is terminal and must+ // never touch the auth dir. (The instance-local boolean above remains as the fallback for standalone+ // adapter use/test where no callback is supplied.)+ describe('stuck-auth recovery claim/deny path', () => {+ const newAdapter = (): WhatsAppWebJsAdapter =>+ new WhatsAppWebJsAdapter({ sessionId: 'sess-1', sessionDataPath: './data/sessions', puppeteer: {} });++ // Failing assertions throw before the per-test rmSpy.mockRestore() runs, which would leave the+ // fs.promises.rm spy installed and let its call count leak into the next test. Restore every spy+ // after each test so each starts from a clean fs.+ afterEach(() => {+ jest.restoreAllMocks();+ });++ it('does NOT clear auth and goes terminal FAILED when the claim callback DENIES (budget already spent by an earlier generation)', async () => {+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);+ const adapter = newAdapter();+ const onError = jest.fn();+ const onDisconnected = jest.fn();+ // The session denies: a prior generation already used the one-shot budget.+ (adapter as unknown as { callbacks: unknown }).callbacks = {+ onError,+ onDisconnected,+ claimStuckAuthRecovery: () => false,+ };+ const recover = (adapter as unknown as { recoverFromStuckAuth: () => Promise<void> }).recoverFromStuckAuth.bind(+ adapter,+ );++ await recover();++ // The destructive rm must NEVER run — denial is terminal before any I/O.+ expect(rmSpy).not.toHaveBeenCalled();+ expect(adapter.getStatus()).toBe(EngineStatus.FAILED);+ expect(onError).toHaveBeenCalledTimes(1);+ expect(onError).toHaveBeenCalledWith(expect.stringMatching(/could not reach readiness after re-pairing/i));+ // A denied claim does NOT drive the reconnect path: no disconnect, no re-pair.+ expect(onDisconnected).not.toHaveBeenCalled();+ rmSpy.mockRestore();+ });++ it('clears auth and disconnects when the claim callback GRANTS (the recovery is allowed to proceed)', async () => {+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);+ const adapter = newAdapter();+ const onDisconnected = jest.fn();+ (adapter as unknown as { callbacks: unknown }).callbacks = {+ onDisconnected,+ claimStuckAuthRecovery: () => true,+ };+ const recover = (adapter as unknown as { recoverFromStuckAuth: () => Promise<void> }).recoverFromStuckAuth.bind(+ adapter,+ );++ await recover();++ expect(rmSpy).toHaveBeenCalledTimes(1);+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);+ expect(onDisconnected).toHaveBeenCalledWith(expect.stringContaining('cleared for re-pairing'));+ rmSpy.mockRestore();+ });++ it('still grants only once via the fallback instance-local boolean when NO claim callback is supplied (standalone adapter use stays one-shot)', async () => {+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);+ const adapter = newAdapter();+ const onError = jest.fn();+ // No claimStuckAuthRecovery callback — standalone adapter (no session lifecycle).+ (adapter as unknown as { callbacks: { onError?: jest.Mock } }).callbacks = { onError };+ const recover = (adapter as unknown as { recoverFromStuckAuth: () => Promise<void> }).recoverFromStuckAuth.bind(+ adapter,+ );++ await recover(); // fallback grants: clears + disconnects+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);+ await recover(); // fallback denies: terminal+ expect(adapter.getStatus()).toBe(EngineStatus.FAILED);+ expect(onError).toHaveBeenCalled();+ expect(rmSpy).toHaveBeenCalledTimes(1);+ rmSpy.mockRestore();+ });++ it('treats a claim callback that THROWS as a denial (fail-closed: never wipe credentials on an unsettled claim)', async () => {+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);+ const adapter = newAdapter();+ const onError = jest.fn();+ const onDisconnected = jest.fn();+ (adapter as unknown as { callbacks: unknown }).callbacks = {+ onError,+ onDisconnected,+ claimStuckAuthRecovery: () => {+ throw new Error('claim blew up');+ },+ };+ const recover = (adapter as unknown as { recoverFromStuckAuth: () => Promise<void> }).recoverFromStuckAuth.bind(+ adapter,+ );++ await recover();++ expect(rmSpy).not.toHaveBeenCalled();+ expect(adapter.getStatus()).toBe(EngineStatus.FAILED);+ expect(onError).toHaveBeenCalled();+ expect(onDisconnected).not.toHaveBeenCalled();+ rmSpy.mockRestore();+ });+ });});describe('WhatsAppWebJsAdapter.resolveContactPhone (@lid -> phone, #263)', () => {diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex f21a0d700..abf389a5a 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -1377,18 +1377,38 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin/*** Recover a session that authenticated but never reached runtime readiness (stale/incompatible auth* or a wedged page). Clear the broken LocalAuth and disconnect so the session lifecycle re-pairs (a- * fresh QR) instead of hanging at "authenticating". Runs at most once per engine — a re-paired session- * that still can't reach readiness fails terminally rather than looping.+ * fresh QR) instead of hanging at "authenticating". Runs at most ONCE per reconnect episode: the+ * one-shot budget lives on the session (via the synchronous `claimStuckAuthRecovery` callback), so+ * an automatic reconnect that builds a fresh adapter cannot reset it and wipe LocalAuth every+ * generation. A re-paired session that still can't reach readiness fails terminally rather than looping.+ *+ * When the callback is ABSENT (standalone adapter use/test, no session lifecycle) the adapter falls+ * back to its own instance-local boolean so standalone behavior stays one-shot.*/private async recoverFromStuckAuth(): Promise<void> {- if (this.stuckAuthRecoveryAttempted) {+ // The one-shot budget is decided SYNCHRONOUSLY before any destructive I/O. The session-owned+ // callback is authoritative when present; the instance-local boolean is the standalone fallback.+ // Fail-closed: a callback that throws (or already-spent budget) makes this terminal WITHOUT+ // touching the auth dir, so a wedged claim path can never wipe the only copy of the credentials.+ const claim = this.callbacks.claimStuckAuthRecovery;+ let granted: boolean;+ if (claim) {+ try {+ granted = claim();+ } catch {+ granted = false;+ }+ } else {+ granted = !this.stuckAuthRecoveryAttempted;+ this.stuckAuthRecoveryAttempted = true;+ }+ if (!granted) {this.setStatus(EngineStatus.FAILED);this.callbacks.onError?.('WhatsApp Web could not reach readiness after re-pairing. Pin WWEBJS_WEB_VERSION to a known-good build and try again.',);return;}- this.stuckAuthRecoveryAttempted = true;const client = this.client;this.client = null;diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex bb537cac6..ef1a50041 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -566,6 +566,23 @@ export interface EngineEventCallbacks {* WhatsApp-originated cleanup) simply never invoke this.*/onCredentialTeardownStarted?: (operation: Promise<void>) => void;+ /**+ * Synchronous atomic claim for ONE automatic credential-reset attempt within a single reconnect+ * episode. The adapter calls this BEFORE it begins the destructive credential reset that ends in+ * an `fs.rm` of this session's on-disk auth dir (the stuck-auth recovery path: a session that+ * authenticated but never reached readiness). Returns `true` exactly once per episode — the claim+ * is owned by the session lifecycle, so it survives an automatic reconnect that builds a FRESH+ * adapter (which would otherwise reset an instance-local budget and wipe LocalAuth every+ * generation, looping forever). Returns `false` once the budget is spent, and the adapter MUST+ * then fail terminally (FAILED + `onError`) WITHOUT touching the auth dir.+ *+ * SYNCHRONOUS by contract: the race between the stuck-auth timeout and any concurrent+ * start()/reconnect is resolved within a single event-loop turn. The adapter does NOT await it.+ *+ * Optional: when absent (standalone adapter use/test, no session lifecycle) the adapter falls back+ * to its own instance-local one-shot boolean so standalone behavior is unchanged.+ */+ claimStuckAuthRecovery?: () => boolean;}export interface IWhatsAppEngine {diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 43b3f4451..559bacccf 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -2103,6 +2103,204 @@ describe('SessionService', () => {});});+ // ── stuck-auth recovery budget (hoisted to session lifecycle) ─────+ // The budget for ONE automatic credential-reset per reconnect episode used to live on the adapter+ // instance, so every automatic reconnect (which builds a fresh adapter) reset it and the loop wiped+ // LocalAuth forever. It now lives on the session as a one-shot claim, so a second generation that+ // never reached READY cannot clear credentials again.+ describe('stuck-auth recovery budget (cross-generation claim)', () => {+ type Intern = {+ engines: Map<string, unknown>;+ stuckAuthRecoveryUsed: Set<string>;+ initializeEngine: (id: string, s: Session) => Promise<void>;+ };+ const intern = () => service as unknown as Intern;+ const flush = () => new Promise(resolve => setImmediate(resolve));++ // Build a fresh mock engine so each generation is a DISTINCT object (the lifecycle keys liveness+ // on identity). Returns the engine plus a getter for the callbacks handed to initialize().+ const freshEngine = (): Record<string, jest.Mock> & {+ callbacks: () => EngineEventCallbacks;+ } => {+ const calls: EngineEventCallbacks[] = [];+ const engine: Record<string, jest.Mock> = {+ initialize: jest.fn().mockImplementation((cb: EngineEventCallbacks) => {+ calls.push(cb);+ return Promise.resolve();+ }),+ destroy: jest.fn().mockResolvedValue(undefined),+ forceDestroy: jest.fn().mockResolvedValue(undefined),+ disconnect: jest.fn().mockResolvedValue(undefined),+ logout: jest.fn().mockResolvedValue(undefined),+ getQRCode: jest.fn().mockReturnValue(null),+ };+ return Object.assign(engine, { callbacks: () => calls[calls.length - 1] });+ };++ // Drive initializeEngine directly (the same private method start()/executeReconnect call) so the+ // test controls generation boundaries precisely without timers/reconnect backoff.+ const initGeneration = async (engine: ReturnType<typeof freshEngine>): Promise<EngineEventCallbacks> => {+ (engineFactory.create as jest.Mock).mockReturnValueOnce(engine);+ await intern().initializeEngine('sess-uuid-1', createMockSession());+ await flush();+ return engine.callbacks();+ };++ beforeEach(() => {+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());+ });++ it('grants the first claim within a generation', async () => {+ const callbacks = await initGeneration(freshEngine());+ expect(callbacks.claimStuckAuthRecovery?.()).toBe(true);+ });++ it('denies a second claim within the SAME generation (one-shot per episode)', async () => {+ const callbacks = await initGeneration(freshEngine());+ expect(callbacks.claimStuckAuthRecovery?.()).toBe(true);+ expect(callbacks.claimStuckAuthRecovery?.()).toBe(false);+ });++ it('denies a claim from a NEW generation that replaced the old one without reaching READY (no fresh budget per reconnect)', async () => {+ const engineA = freshEngine();+ const callbacksA = await initGeneration(engineA);+ expect(callbacksA.claimStuckAuthRecovery?.()).toBe(true); // generation A spent the budget++ // Automatic reconnect: old engine torn down, fresh engine B takes the slot. B is NOT READY and no+ // manual start() happened — the episode is still the same recovery attempt.+ const engineB = freshEngine();+ intern().engines.delete('sess-uuid-1');+ const callbacksB = await initGeneration(engineB);++ expect(callbacksB.claimStuckAuthRecovery?.()).toBe(false);+ });++ it('denies a stale claim from a superseded engine after replacement', async () => {+ const engineA = freshEngine();+ const callbacksA = await initGeneration(engineA);+ const engineB = freshEngine();+ intern().engines.delete('sess-uuid-1');+ await initGeneration(engineB); // B is now the live owner++ // A is stale (not the live engine) — its claim must be denied regardless of the budget.+ expect(callbacksA.claimStuckAuthRecovery?.()).toBe(false);+ });++ it('re-arms the budget after the recovering generation reaches READY (recovery proved successful)', async () => {+ const engineA = freshEngine();+ const callbacksA = await initGeneration(engineA);+ expect(callbacksA.claimStuckAuthRecovery?.()).toBe(true);++ // The recovering generation reaches READY — onReady clears the budget, so a later generation+ // may claim again.+ callbacksA.onReady?.('628123', 'Tester');+ await flush();++ const engineB = freshEngine();+ intern().engines.delete('sess-uuid-1');+ const callbacksB = await initGeneration(engineB);+ expect(callbacksB.claimStuckAuthRecovery?.()).toBe(true);+ });++ it('an accepted top-level start() re-arms the budget after a terminal failure', async () => {+ // Generation A spends the budget, then fails terminally (onError). The session is left without a+ // live engine. A later ACCEPTED start() (the operator re-scans) must re-arm the budget.+ const engineA = freshEngine();+ const callbacksA = await initGeneration(engineA);+ expect(callbacksA.claimStuckAuthRecovery?.()).toBe(true);+ callbacksA.onError?.('WhatsApp Web could not reach readiness after re-pairing.');+ await flush();+ expect(intern().engines.has('sess-uuid-1')).toBe(false);++ // Accepted top-level start(): a fresh engine is created and initialized.+ const engineB = freshEngine();+ (engineFactory.create as jest.Mock).mockReturnValueOnce(engineB);+ await service.start('sess-uuid-1');+ await flush();++ expect(engineB.callbacks().claimStuckAuthRecovery?.()).toBe(true);+ });++ it('does NOT re-arm on a rejected duplicate start() (session already started)', async () => {+ // Spend the budget via initializeEngine, then a duplicate start() must reject WITHOUT re-arming.+ const callbacksA = await initGeneration(freshEngine());+ expect(callbacksA.claimStuckAuthRecovery?.()).toBe(true);++ await expect(service.start('sess-uuid-1')).rejects.toThrow(BadRequestException);+ // The budget is still spent — a fresh generation via initializeEngine is still denied.+ const engineB = freshEngine();+ intern().engines.delete('sess-uuid-1');+ const callbacksB = await initGeneration(engineB);+ expect(callbacksB.claimStuckAuthRecovery?.()).toBe(false);+ });++ it('does NOT re-arm on a start() rejected by the concurrent-sessions cap', async () => {+ // Spend the budget first.+ const callbacksA = await initGeneration(freshEngine());+ expect(callbacksA.claimStuckAuthRecovery?.()).toBe(true);+ intern().engines.delete('sess-uuid-1'); // clear so the cap check is what rejects, not "already started"++ // Two OTHER sessions fill the cap (max=2). The session under test must be rejected by the cap.+ (configService.get as jest.Mock).mockImplementation(<T>(key: string, def?: T): T => {+ if (key === 'sessions.maxConcurrent') return 2 as unknown as T;+ return def as T;+ });+ intern().engines.set('other-1', {});+ intern().engines.set('other-2', {});++ await expect(service.start('sess-uuid-1')).rejects.toThrow(/Maximum concurrent sessions reached/);++ // Budget untouched: a fresh generation is still denied.+ const engineB = freshEngine();+ intern().engines.delete('other-1');+ intern().engines.delete('other-2');+ const callbacksB = await initGeneration(engineB);+ expect(callbacksB.claimStuckAuthRecovery?.()).toBe(false);+ });++ it('clears the budget only on a COMMITTED delete (a failed/409 delete keeps it)', async () => {+ const callbacksA = await initGeneration(freshEngine());+ expect(callbacksA.claimStuckAuthRecovery?.()).toBe(true);+ intern().engines.delete('sess-uuid-1');++ // Simulate a delete that FAILS inside the transaction (parent row not removed → parentDeleted=false).+ (dataSource.transaction as jest.Mock).mockImplementationOnce(async (cb: (m: unknown) => Promise<unknown>) => {+ await cb({+ save: jest.fn(),+ remove: jest.fn().mockRejectedValue(new Error('db write failed')),+ delete: jest.fn().mockResolvedValue({ affected: 0 }),+ });+ });+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());++ await expect(service.delete('sess-uuid-1')).rejects.toThrow();++ // A failed delete must NOT clear the budget — the session still exists.+ const engineB = freshEngine();+ const callbacksB = await initGeneration(engineB);+ expect(callbacksB.claimStuckAuthRecovery?.()).toBe(false);++ // Now a COMMITTED delete clears the budget: a later start() may claim again.+ intern().engines.delete('sess-uuid-1');+ (dataSource.transaction as jest.Mock).mockImplementationOnce(async (cb: (m: unknown) => Promise<unknown>) => {+ await cb({+ save: jest.fn(),+ remove: jest.fn().mockResolvedValue(undefined),+ delete: jest.fn().mockResolvedValue({ affected: 0 }),+ });+ });+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());+ await service.delete('sess-uuid-1');++ const engineC = freshEngine();+ (engineFactory.create as jest.Mock).mockReturnValueOnce(engineC);+ await service.start('sess-uuid-1');+ await flush();+ expect(engineC.callbacks().claimStuckAuthRecovery?.()).toBe(true);+ });+ });+// ── engine message-event webhook dispatch ─────────────────────────describe('engine message-event webhook dispatch', () => {diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 27ce4d7a3..f98db1fff 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -256,6 +256,19 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// engine B the control action did not capture.private readonly pendingInitialStatuses = new Map<string, { engine: IWhatsAppEngine; promise: Promise<void> }>();+ // The ONE-SHOT budget for an automatic stuck-auth credential reset, hoisted out of the adapter+ // instance and keyed by session id. recoverFromStuckAuth() (a generation that authenticated but+ // never reached readiness) claims this synchronously before it wipes LocalAuth; a claim returns true+ // EXACTLY once per episode. Automatic reconnects build a FRESH adapter, so an instance-local budget+ // would reset every generation and wipe credentials forever (the QR -> timeout -> clear loop). The+ // session owns the budget so it survives across reconnect generations within one episode.+ //+ // Cleared ONLY on: an accepted top-level start() (after the duplicate/cap/name-fence checks pass,+ // just before initializeEngine — boot auto-start uses the same method); onReady (recovery proved+ // successful); and a COMMITTED delete (after the parent transaction). NOT cleared on a rejected+ // start, executeReconnect, disconnect, QR, auth failure, engine replacement, or a failed/409 delete.+ private readonly stuckAuthRecoveryUsed = new Set<string>();+constructor(@InjectRepository(Session, 'data')private readonly sessionRepository: Repository<Session>,@@ -723,6 +736,10 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// Drop the FAILED-reason entry too: it's keyed by a now-deleted UUID that can never be read// again, so leaving it would grow the map without bound across create/fail/delete churn.this.sessionErrors.delete(id);+ // The stuck-auth recovery budget is keyed by id; a committed delete frees it (and a recreated+ // session under the same name gets a fresh UUID + fresh budget). Left only on a committed+ // delete so a failed/409 delete — the session still exists — keeps the budget intact.+ this.stuckAuthRecoveryUsed.delete(id);}// NOTE: pendingTeardowns is intentionally NOT cleared here. It is keyed by session NAME and// its entries self-remove on settlement (identity-checked). A delete that refused at either@@ -801,6 +818,13 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatconst { maxAttempts, baseDelay } = resolveReconnectConfig(session.config);this.reconnectStates.set(id, { attempts: 0, timer: null, maxAttempts, baseDelay });+ // An accepted top-level start() re-arms the stuck-auth recovery budget: every fence above+ // (duplicate-start, cap, credential-teardown) passed, so this is a deliberate, operator-initiated+ // (re)start — not an automatic reconnect. The budget is hoisted to the session so an automatic+ // reconnect can't reset it per generation; only a fresh top-level episode may spend it again.+ // Boot auto-start reaches here through this same method, so it re-arms too.+ this.stuckAuthRecoveryUsed.delete(id);+try {await this.initializeEngine(id, session);} catch (err) {@@ -1167,6 +1191,9 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// A fresh READY stretch starts the watchdog's failure budget clean too.this.livenessFailures.delete(id);this.sessionErrors.delete(id);+ // READY proves any in-flight stuck-auth recovery succeeded (or none was needed), so the+ // one-shot recovery budget is re-armed for a future episode.+ this.stuckAuthRecoveryUsed.delete(id);void this.sessionRepository.update(id, {@@ -1762,6 +1789,21 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// initializeEngine entry, so a row delete/recreate under the same name cannot poison the key.this.trackPendingCredentialTeardown(session.name, operation);},+ claimStuckAuthRecovery: (): boolean => {+ // SYNCHRONOUS atomic claim for the one-shot automatic credential-reset budget. The adapter+ // calls this right before it would wipe LocalAuth (recoverFromStuckAuth); a denial makes the+ // adapter fail terminally WITHOUT touching the auth dir. Two guards, in order:+ // 1. the captured engine must still be the live owner — a stale generation (superseded by a+ // reconnect/restart) must never spend the budget for the current owner;+ // 2. the session id must not already be in the Set — the budget is one claim per episode.+ // Synchronous on purpose: the race between the stuck-auth timeout and a concurrent+ // start()/reconnect is decided within a single event-loop turn (no await between the checks+ // and the Set mutation).+ if (!this.isLiveEngine(id, engine)) return false;+ if (this.stuckAuthRecoveryUsed.has(id)) return false;+ this.stuckAuthRecoveryUsed.add(id);+ return true;+ },});// engine.initialize() launches Chromium and navigates to WhatsApp Web with no internal timeout: