Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): watch a session awaiting operator action, and tidy three lifecycle edges
Yudhi Armyndharis732cafa29560
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0a1996933..7011aadd3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -35,6 +35,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **A session awaiting operator action is watched again, without being taken over.** The liveness+ watchdog skipped every non-`ready` session, so once a session moved to `action_required` its page+ was never probed again — if it died while waiting for a human, nothing recorded that anywhere. It is+ now probed, but the result is observed only: a failure is logged and never accrues toward the+ disconnect threshold, never publishes a `session.disconnected`, and never schedules a reconnect.+ Acting on it would hand the session to the reconnect path and silently clear the very status that+ asked for attention, which stays the operator's to clear with a stop and a start. The warning is+ emitted once per unresponsive stretch rather than once per probe, since a session can legitimately+ sit in that state until someone reaches it, and a recovery is logged so an earlier warning is not+ left as the last word.++- **A delete refused while a credential teardown is in flight no longer leaves a status it cannot+ honour.** That refusal (`409 SESSION_NAME_TEARDOWN_PENDING`) happens after the engine has already+ been destroyed and evicted, so the surviving row kept reading `ready` — or whatever it was — for a+ session with nothing behind it, until something else wrote the status. The row is now reconciled to+ `disconnected` before the refusal propagates. The earlier of the two fences needs no such handling:+ nothing has run by then, so its status is still accurate.+- **A WhatsApp-initiated logout that arrives during an unrelated teardown no longer hides itscredential removal.** whatsapp-web.js emits `disconnected: LOGOUT` and then runs`authStrategy.logout()` → `fs.rm` of the session's profile directory, and that removal happens@@ -56,6 +74,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Removed two session statuses from the dashboard that the gateway never emits (`connecting`, `idle`),along with the dead branches that tested for them.+- Internal tidying with no behaviour change: a caller-initiated logout no longer registers its+ credential removal twice (the lifecycle already tracks the whole `engine.logout()` promise, which is+ the only registration that covers both engines), and a duplicated engine-ownership check in the+ pre-initialize window is gone — it sat behind a synchronous check that cannot change the answer, so+ it could never disagree with the one before it.+## [0.12.0] - 2026-07-30The session-lifecycle security hardening release. Lifecycle endpoints, thediff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.mdindex 817303a92..5647575a1 100644--- a/docs/12-troubleshooting-faq.md+++ b/docs/12-troubleshooting-faq.md@@ -489,6 +489,12 @@ once, so the session stops instead of being silently unlinked by WhatsApp about> in a browser signed in as that account, then scan the QR. It does not recur — the modal is shown> once per account.+> **While a session sits in `action_required`** the liveness watchdog keeps probing it, but only to+> report: a failed probe is logged (`action: watchdog_probe_failed_observe_only`, once per+> unresponsive stretch) and never reconnects the session or changes its status. So a page that died+> while waiting for you is visible in the logs, and the status still means what it says. If you see+> that warning, the page is gone and the stop → start below is required rather than optional.+**Fix:** acknowledge the modal once (open WhatsApp Web in the account holder's own browser and clickthrough the "What's new" screen), **then restart the session** (`POST /sessions/:id/stop` →`POST /sessions/:id/start`). Acknowledging alone does not return the session to `ready` — the statusdiff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 142c50460..dfb63f56a 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -957,29 +957,40 @@ describe('WhatsAppWebJsAdapter credential-teardown observation', () => {jest.useRealTimers();});- it('logout() registers the client.logout() promise via onCredentialTeardownStarted before awaiting it', async () => {+ // A caller-initiated logout is tracked from OUTSIDE the adapter: SessionService hands the session+ // name to teardownEngineSafely, which registers the whole engine.logout() promise — a superset of+ // the in-page unlink and the profile rm that follows it — and that is the single owner for both+ // engines (the Baileys adapter reports nothing here either). Registering again from inside would+ // add a second, narrower promise for the same removal.+ it('logout() does not register a credential teardown — the lifecycle already tracks this call', async () => {const adapter = newAdapter();- let resolveLogout!: () => void;- const logoutPromise = new Promise<void>(res => {- resolveLogout = res;- });const { onCredentialTeardownStarted } = attach(adapter, {- logout: jest.fn().mockReturnValue(logoutPromise),+ logout: jest.fn().mockResolvedValue(undefined),destroy: jest.fn().mockResolvedValue(undefined),});- // Fire logout but do NOT settle it yet — the callback must already have been handed the promise.- const logoutCall = adapter.logout();- await Promise.resolve(); // flush the synchronous portion of logout()+ await expect(adapter.logout()).resolves.toBeUndefined();- expect(onCredentialTeardownStarted).toHaveBeenCalledTimes(1);- const [tracked] = onCredentialTeardownStarted.mock.calls[0] as [Promise<void>];- expect(tracked).toBeInstanceOf(Promise);- // The tracked promise is the SAME destructive operation the adapter is awaiting: settling it- // settles logout().- resolveLogout();- await expect(tracked).resolves.toBeUndefined();- await expect(logoutCall).resolves.toBeUndefined();+ expect(onCredentialTeardownStarted).not.toHaveBeenCalled();+ });++ // …and the stand-in the 'disconnected' handler adds for a WhatsApp-initiated logout must not fire+ // for this one either, or the same removal would be registered twice from two directions.+ it('logout() suppresses the disconnected-LOGOUT stand-in for its own unlink', async () => {+ const adapter = newAdapter();+ const { client, onCredentialTeardownStarted } = attach(adapter, {+ // client.logout() triggers the in-page logout, which surfaces as disconnected:LOGOUT while the+ // adapter is still awaiting it.+ logout: jest.fn().mockImplementation(() => {+ client.emit('disconnected', 'LOGOUT');+ return Promise.resolve();+ }),+ destroy: jest.fn().mockResolvedValue(undefined),+ });++ await adapter.logout();++ expect(onCredentialTeardownStarted).not.toHaveBeenCalled();});it('a WhatsApp-originated disconnected:LOGOUT registers the credential-teardown promise synchronously before the event loop can run', async () => {diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 485600c14..4f71f1f50 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -1651,9 +1651,14 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin}async logout(): Promise<void> {- // Claim the LOGOUT credential registration before anything can emit 'disconnected': the native- // unlink below registers the real promise, so the event handler must not add a stand-in for it.- // Set even if there is no live client — the throw path sends nothing, so no event can arrive.+ // Mark the credential removal as caller-owned before anything can emit 'disconnected'. The+ // lifecycle tracks this call's removal from the outside — SessionService passes the session name+ // to teardownEngineSafely, which registers the whole engine.logout() promise (a superset of the+ // in-page unlink AND the profile rm that follows it), and that is the single owner for BOTH+ // engines, since the Baileys adapter reports nothing here either. So this method must NOT+ // register a second, narrower promise for the same removal, and the 'disconnected' LOGOUT handler+ // must not add its stand-in on top. Set even with no live client: the throw path sends nothing,+ // so no event can arrive, and a caller-initiated logout is still what happened.this.logoutInitiated = true;const client = this.beginClientTeardown();// No live client means there is nothing to send the unlink through. Resolving here would report a@@ -1665,22 +1670,11 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginthrow new Error('No live WhatsApp Web client — the unlink was not sent');}- // client.logout() chains authStrategy.logout() (LocalAuth) → fs.rm of this session's profile dir.- // Surface that destructive operation to the lifecycle SYNCHRONOUSLY, before the await, so a- // concurrent start()/delete()/reconnect for the same session NAME observes the in-flight rm and- // waits for it instead of re-creating/purging credentials the rm is about to delete. Register- // BEFORE awaiting so the callback fires even if the await never settles.- const logoutOp = client.logout();- this.callbacks.onCredentialTeardownStarted?.(- logoutOp.then(- () => undefined,- () => undefined,- ),- );-try {- // Logout clears session data - user will need to scan QR again- await logoutOp;+ // client.logout() chains authStrategy.logout() (LocalAuth) → fs.rm of this session's profile+ // dir. The lifecycle already tracks that removal through this method's own promise (see the+ // note above logoutInitiated), so nothing is registered here.+ await client.logout();} catch (error) {this.logger.warn('Logout failed:', { error: String(error) });// Fall back to destroy so the session still dies locally — but rethrow so the callerdiff --git a/src/modules/session/logout-teardown-race.spec.ts b/src/modules/session/logout-teardown-race.spec.tsindex 2128f5dc0..a712b803d 100644--- a/src/modules/session/logout-teardown-race.spec.ts+++ b/src/modules/session/logout-teardown-race.spec.ts@@ -336,6 +336,14 @@ describe('SessionService logout() name-scoped teardown fence', () => {expect(engineFactory.purgeSessionData).not.toHaveBeenCalled();// Row/name still reserved: the second fence refused before the transaction.expect(pendingOf().has(SESSION_NAME)).toBe(true);+ // The engine was already destroyed and evicted before this fence, so the surviving row must not+ // keep advertising a status it can no longer honour — the retry this 409 asks for should not have+ // to look past a session that still reads READY with nothing behind it.+ expect(enginesOf().has(SESSION_UUID)).toBe(false);+ expect(repository.update).toHaveBeenCalledWith(+ SESSION_UUID,+ expect.objectContaining({ status: SessionStatus.DISCONNECTED }),+ );// After the raw teardown settles, the name is released.releaseLogout();diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 559bacccf..c2b61bbdd 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -14,6 +14,7 @@ import {SessionService,ACK_RECONCILE_DELAY_MS,SESSION_WATCHDOG_INTERVAL_MS,+ SESSION_WATCHDOG_MAX_FAILURES,SESSION_WATCHDOG_PROBE_TIMEOUT_MS,} from './session.service';import { Session, SessionStatus } from './entities/session.entity';@@ -1751,6 +1752,71 @@ describe('SessionService', () => {}});+ // ACTION_REQUIRED is probed for observability, but the result must never drive the lifecycle: the+ // status says a human has to act, and reconnecting the session would silently clear it.+ it('probes an ACTION_REQUIRED engine but never acts on a failure', async () => {+ jest.useFakeTimers();+ try {+ const engine = {+ getStatus: jest.fn().mockReturnValue(EngineStatus.ACTION_REQUIRED),+ probeLiveness: jest.fn().mockResolvedValue(false),+ };+ seedReadySession(engine);+ const scheduleSpy = jest.spyOn(internals(), 'scheduleReconnect');++ await service.onApplicationBootstrap();+ // Well past the 2-failure threshold that would disconnect a READY session.+ await jest.advanceTimersByTimeAsync(SESSION_WATCHDOG_INTERVAL_MS * 4);++ // Probed — that is the point; the page dying while the operator is away is now visible.+ expect(engine.probeLiveness).toHaveBeenCalled();+ // …but nothing was acted on.+ expect(scheduleSpy).not.toHaveBeenCalled();+ expect(webhookService.dispatch).not.toHaveBeenCalledWith(+ expect.anything(),+ 'session.disconnected',+ expect.anything(),+ );+ expect(repository.update).not.toHaveBeenCalledWith(+ 'sess-uuid-1',+ expect.objectContaining({ status: SessionStatus.DISCONNECTED }),+ );+ // The count keeps rising so a later recovery can be distinguished from "never failed".+ expect(internals().livenessFailures.get('sess-uuid-1')).toBeGreaterThan(SESSION_WATCHDOG_MAX_FAILURES);+ } finally {+ jest.clearAllTimers();+ jest.useRealTimers();+ }+ });++ // A session can sit in ACTION_REQUIRED until someone gets to it. At one tick per minute an+ // unbounded warning would bury every other log line.+ it('warns once per unresponsive stretch while ACTION_REQUIRED, not once per tick', async () => {+ jest.useFakeTimers();+ try {+ const engine = {+ getStatus: jest.fn().mockReturnValue(EngineStatus.ACTION_REQUIRED),+ probeLiveness: jest.fn().mockResolvedValue(false),+ };+ seedReadySession(engine);+ const warnSpy = jest.spyOn(+ (service as unknown as { logger: { warn: (...a: unknown[]) => void } }).logger,+ 'warn',+ );++ await service.onApplicationBootstrap();+ await jest.advanceTimersByTimeAsync(SESSION_WATCHDOG_INTERVAL_MS * 5);++ const observeWarnings = warnSpy.mock.calls.filter(+ ([, ctx]) => (ctx as { action?: string } | undefined)?.action === 'watchdog_probe_failed_observe_only',+ );+ expect(observeWarnings).toHaveLength(1);+ } finally {+ jest.clearAllTimers();+ jest.useRealTimers();+ }+ });+it('counts a hung probe (timeout) as a failure and clears it on the next successful probe', async () => {jest.useFakeTimers();try {diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex f98db1fff..8df4b912c 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -678,7 +678,21 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// onCredentialTeardownStarted callback), so this fence sees it and refuses — the row/name stay// reserved and the transaction does not run. After eviction a NEW logout can't create a// destructive promise (no live engine); one that already captured the engine is observed here.- await this.awaitPendingTeardown(session.name);+ //+ // Unlike fence #1, a refusal HERE leaves the row behind with its engine already destroyed, so+ // the persisted status would keep reading whatever it was (READY, authenticating, …) for a+ // session that can no longer answer anything. Reconcile it to DISCONNECTED before propagating+ // the 409 — the retry the message asks for should not have to look past a status that lies.+ // Fence #1 needs none of this: nothing has run there yet, so its status is still accurate.+ // Best-effort: a failed status write must not mask the 409 the caller has to act on.+ try {+ await this.awaitPendingTeardown(session.name);+ } catch (fenceError) {+ if (engine) {+ await this.updateStatus(id, SessionStatus.DISCONNECTED).catch(() => undefined);+ }+ throw fenceError;+ }// Execute hook BEFORE delete so plugins can access session dataawait this.hookManager.execute(@@ -1124,16 +1138,16 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// write, so checking it here (no DB read on the healthy path) closes the pre-initialize window// without changing reconnect-when-reload-fails semantics. isLiveEngine guards the stop-mark-less// timeout path and any replacement. There is intentionally NO await between these checks and- // engine.initialize() below — an intervening await would re-open the retirement window.+ // engine.initialize() below — an intervening await would re-open the retirement window, and it is+ // also why ONE isLiveEngine check is enough: the two guards are separated by a synchronous Set+ // lookup, so nothing can swap the engine between them (a second, identical check used to sit+ // after the stop mark and could never disagree with this one).if (!this.isLiveEngine(id, engine)) {return;}if (this.stoppingSessions.has(id)) {return;}- if (!this.isLiveEngine(id, engine)) {- return;- }const initPromise = engine.initialize({onQRCode: (qr: string): void => {@@ -2152,11 +2166,22 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat* Actively probe one engine. Only READY sessions are expected to answer (anything else is owned by* the QR/reconnect flows); engines without `probeLiveness` keep relying on engine events alone.* MAX_FAILURES consecutive failures treat the session exactly like an engine-reported disconnect.+ *+ * ACTION_REQUIRED is probed too, but OBSERVE-ONLY: the engine is still running and a human has to+ * act, and clearing that status is theirs to do (stop, then start). Acting on a failed probe would+ * hand the session to the reconnect path and silently drop the very status that asked for+ * attention — so the probe result only reaches the log. Without probing at all, a page that dies+ * while waiting for the operator left no trace anywhere, which is what this closes.*/private async probeSessionLiveness(id: string, engine: IWhatsAppEngine): Promise<void> {- if (engine.getStatus() !== EngineStatus.READY) {+ const status = engine.getStatus();+ const observeOnly = status === EngineStatus.ACTION_REQUIRED;+ if (status !== EngineStatus.READY && !observeOnly) {// Not expected to answer right now — and any accrued failures belong to a previous READY- // stretch, so the next one starts clean.+ // stretch, so the next one starts clean. This also self-cleans the observe-only counter below:+ // every path out of ACTION_REQUIRED passes through a status that lands here (or through+ // onReady, which clears it), so an observe-only count can never be inherited by a READY+ // stretch and push it over MAX_FAILURES early.this.livenessFailures.delete(id);return;}@@ -2192,11 +2217,34 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat}if (alive) {+ // Note a recovery on the observe-only path, so the log shows the page came back rather than+ // leaving the earlier warning as the last word.+ if (observeOnly && this.livenessFailures.has(id)) {+ this.logger.log('Liveness probe answering again while the session awaits operator action', {+ sessionId: id,+ action: 'watchdog_probe_recovered',+ });+ }this.livenessFailures.delete(id);return;}const failures = (this.livenessFailures.get(id) ?? 0) + 1;+ if (observeOnly) {+ this.livenessFailures.set(id, failures);+ // One warning per unresponsive stretch, not one per tick: a session can sit in+ // ACTION_REQUIRED until a human gets to it, and at a 60s interval an unbounded log would bury+ // everything else. The count keeps rising so the recovery branch above can tell it happened.+ if (failures === 1) {+ this.logger.warn(+ 'Liveness probe failed while the session awaits operator action; not reconnecting it — ' ++ 'the status is operator-owned. If the page is gone, stop and start the session.',+ { sessionId: id, action: 'watchdog_probe_failed_observe_only' },+ );+ }+ return;+ }+if (failures < SESSION_WATCHDOG_MAX_FAILURES) {this.livenessFailures.set(id, failures);this.logger.warn('Liveness probe failed; will treat the session as dead after repeated failures', {