Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): require complete baileys unlink and credential cleanup
Yudhi Armyndharis024a78e6d22e
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 36f21cb3c..786b08fd9 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -22,6 +22,11 @@ class FakeSock extends EventEmitter {public requestPairingCode = jest.fn().mockResolvedValue('ABCD-EFGH');public end = jest.fn();public logout = jest.fn().mockResolvedValue(undefined);+ // IQ query surface used by logout(): sends a BinaryNode and resolves the tagged response.+ // Default returns a truthy IQ result (a successful acknowledgement) so tests that don't care can+ // just await logout(); individual tests override the implementation to simulate failure.+ public query = jest.fn().mockResolvedValue({ tag: 'iq', attrs: { type: 'result' } });+ public generateMessageTag = jest.fn().mockReturnValue('TAG-1');public sendMessage = jest.fn();public onWhatsApp = jest.fn();public sendPresenceUpdate = jest.fn().mockResolvedValue(undefined);@@ -88,6 +93,8 @@ jest.mock('@whiskeysockets/baileys', () => ({),// Identity passthrough by default; individual tests may override to simulate unwrapping.normalizeMessageContent: jest.fn((c: unknown) => c),+ // The pinned protocol node targets this JID; exported from the real module's WABinary surface.+ S_WHATSAPP_NET: '@s.whatsapp.net',DisconnectReason: { loggedOut: 401, forbidden: 403, restartRequired: 515, connectionReplaced: 440 },proto: {Message: {@@ -196,19 +203,27 @@ describe('BaileysAdapter lifecycle & status', () => {});it('on a logged-out close: DISCONNECTED, onDisconnected, and NO reconnect', async () => {- const onDisconnected = jest.fn();- const adapter = newAdapter();- await adapter.initialize(noopCallbacks({ onDisconnected }));- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access- const makeWASocket = jest.requireMock('@whiskeysockets/baileys').default as jest.Mock;- makeWASocket.mockClear();- fakeSock.fire('connection.update', {- connection: 'close',- lastDisconnect: { error: { output: { statusCode: 401 } } },- });- expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);- expect(onDisconnected).toHaveBeenCalled();- expect(makeWASocket).not.toHaveBeenCalled(); // no reconnect+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);+ try {+ const onDisconnected = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({ onDisconnected }));+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ const makeWASocket = jest.requireMock('@whiskeysockets/baileys').default as jest.Mock;+ makeWASocket.mockClear();+ fakeSock.fire('connection.update', {+ connection: 'close',+ lastDisconnect: { error: { output: { statusCode: 401 } } },+ });+ // The status/socket teardown is synchronous; onDisconnected fires only after the deferred auth+ // removal settles (see handleRemoteLoggedOut).+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);+ await new Promise(r => setImmediate(r));+ expect(onDisconnected).toHaveBeenCalledWith('logged out');+ expect(makeWASocket).not.toHaveBeenCalled(); // no reconnect+ } finally {+ rmSpy.mockRestore();+ }});it('on a logged-out close: clears the on-disk auth dir so a fresh connect shows a new QR', async () => {@@ -233,12 +248,124 @@ describe('BaileysAdapter lifecycle & status', () => {}});- it('logout() clears the on-disk auth dir (stale creds would otherwise block re-linking)', async () => {+ it('on a logged-out close: moves DISCONNECTED synchronously, registers the teardown, fires onDisconnected only after the rm resolves', async () => {+ // The WhatsApp-originated cleanup runs as an awaited async helper. The status/socket/live-call+ // teardown must land SYNCHRONOUSLY before any await so the watchdog never processes a READY socket+ // that is already dead; onCredentialTeardownStarted must register the cleanup promise; and+ // onDisconnected fires only after the strict auth removal succeeds.+ let releaseRm!: () => void;+ const rmPromise = new Promise<void>(res => {+ releaseRm = res;+ });+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockReturnValue(rmPromise);+ const onCredentialTeardownStarted = jest.fn((op: Promise<void>) => {+ void op.catch(() => undefined);+ });+ const onDisconnected = jest.fn();+ const onError = jest.fn();+ try {+ const adapter = newAdapter();+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ const makeWASocket = jest.requireMock('@whiskeysockets/baileys').default as jest.Mock;+ await adapter.initialize(noopCallbacks({ onCredentialTeardownStarted, onDisconnected, onError }));+ makeWASocket.mockClear(); // only count makeWASocket calls originating from the logged-out path++ fakeSock.fire('connection.update', {+ connection: 'close',+ lastDisconnect: { error: { output: { statusCode: 401 } } },+ });++ // SYNCHRONOUSLY (before the deferred rm settles): DISCONNECTED, socket nulled, live calls clear.+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);+ expect((adapter as unknown as { sock: unknown }).sock).toBeNull();+ expect(onCredentialTeardownStarted).toHaveBeenCalledTimes(1);+ // The registered argument is the same promise the adapter is about to await.+ const registeredOp = onCredentialTeardownStarted.mock.calls[0][0];+ expect(typeof registeredOp.then).toBe('function');+ expect(makeWASocket).not.toHaveBeenCalled(); // no reconnect scheduled+ // onDisconnected has NOT fired yet — the rm is still pending.+ expect(onDisconnected).not.toHaveBeenCalled();+ expect(onError).not.toHaveBeenCalled();++ releaseRm();+ await new Promise(r => setImmediate(r)); // let the awaited helper settle++ expect(rmSpy).toHaveBeenCalledWith(+ path.join('./data/baileys', 'sess-1'),+ expect.objectContaining({ recursive: true, force: true }),+ );+ expect(onDisconnected).toHaveBeenCalledWith('logged out');+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED); // still DISCONNECTED on success+ expect(onError).not.toHaveBeenCalled();+ } finally {+ rmSpy.mockRestore();+ }+ });++ it('on a logged-out close: a failed auth removal becomes terminal FAILED + onError (NOT disconnected/reconnect)', async () => {+ // A clearAuthState() that rethrows must surface as a terminal error so the operator learns the+ // credentials did not actually get wiped. It must not look like a clean disconnect or schedule a+ // reconnect with known-invalid auth.+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockRejectedValueOnce(new Error('disk error'));+ const onDisconnected = jest.fn();+ const onError = jest.fn();+ try {+ const adapter = newAdapter();+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ const makeWASocket = jest.requireMock('@whiskeysockets/baileys').default as jest.Mock;+ await adapter.initialize(noopCallbacks({ onDisconnected, onError }));+ makeWASocket.mockClear(); // only count makeWASocket calls originating from the logged-out path++ fakeSock.fire('connection.update', {+ connection: 'close',+ lastDisconnect: { error: { output: { statusCode: 401 } } },+ });+ await new Promise(r => setImmediate(r)); // let the awaited helper settle on the rejection++ expect(adapter.getStatus()).toBe(EngineStatus.FAILED);+ expect(onError).toHaveBeenCalledTimes(1);+ expect(onError).toHaveBeenCalledWith(expect.stringContaining('disk error'));+ expect(onDisconnected).not.toHaveBeenCalled(); // success path did not run+ expect(makeWASocket).not.toHaveBeenCalled(); // no reconnect+ } finally {+ rmSpy.mockRestore();+ }+ });++ it('logout() clears the on-disk auth dir only AFTER an IQ result acknowledges the unlink', async () => {+ // 200 = engine-native unlink completed AND required local credential cleanup completed. The auth+ // dir must be removed only after a valid IQ response; removing it earlier would leave the device+ // linked server-side with no local credentials to retry with.const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);try {const adapter = newAdapter();await adapter.initialize(noopCallbacks({}));+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };+await adapter.logout();++ // remove-companion-device IQ went out through query() with the pinned protocol node and the+ // 8s acknowledgement timeout. Auth dir removal happened only after the truthy IQ result.+ expect(fakeSock.query).toHaveBeenCalledTimes(1);+ const [node, timeoutMs] = fakeSock.query.mock.calls[0] as [+ {+ tag: string;+ attrs: { to: string; type: string; id: string; xmlns: string };+ content: Array<{ tag: string; attrs: { jid: string; reason: string } }>;+ },+ number,+ ];+ expect(node.tag).toBe('iq');+ expect(node.attrs).toEqual({+ to: '@s.whatsapp.net',+ type: 'set',+ id: 'TAG-1',+ xmlns: 'md',+ });+ expect(node.content).toEqual([+ { tag: 'remove-companion-device', attrs: { jid: '628999:[email protected]', reason: 'user_initiated' } },+ ]);+ expect(timeoutMs).toBe(8_000);expect(rmSpy).toHaveBeenCalledWith(path.join('./data/baileys', 'sess-1'),expect.objectContaining({ recursive: true, force: true }),@@ -248,18 +375,106 @@ describe('BaileysAdapter lifecycle & status', () => {}});- it('logout() rejects and keeps the on-disk auth dir when the server unlink fails', async () => {- // Wiping the auth dir on a failed unlink would leave the device linked server-side with no- // local way to retry — the worst of both worlds. Failure must surface and keep the creds.+ it('logout() never calls sock.logout() — the IQ query is the unlink contract', async () => {+ // Baileys sock.logout() resolves on WebSocket write flush (NOT an IQ ack) and transmits nothing+ // when creds.me is unset, so it is intentionally NOT used.const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);try {const adapter = newAdapter();await adapter.initialize(noopCallbacks({}));- fakeSock.logout.mockRejectedValueOnce(new Error('stream errored out'));+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };- await expect(adapter.logout()).rejects.toThrow('stream errored out');+ await adapter.logout();++ expect(fakeSock.logout).not.toHaveBeenCalled();+ } finally {+ rmSpy.mockRestore();+ }+ });++ it('logout() with missing companion identity rejects, sends nothing, preserves auth, and stops locally', async () => {+ // No creds.me.id → the unlink cannot be addressed. The promise must reject, query()/rm() must NOT+ // run, and the live socket must be torn down locally so no engine orphan remains.+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);+ try {+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({}));+ fakeSock.user = undefined; // no linked companion identity+ (adapter as unknown as { sock: unknown }).sock = fakeSock;++ await expect(adapter.logout()).rejects.toThrow(/no linked companion identity/i);++ expect(fakeSock.query).not.toHaveBeenCalled();expect(rmSpy).not.toHaveBeenCalled();- expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED); // socket still ended locally+ // Failure still stops the socket locally: end() called, status DISCONNECTED, socket nulled.+ expect(fakeSock.end).toHaveBeenCalled();+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);+ expect((adapter as unknown as { sock: unknown }).sock).toBeNull();+ } finally {+ rmSpy.mockRestore();+ }+ });++ it('logout() with an undefined IQ response rejects, preserves auth, and stops locally', async () => {+ // WhatsApp returned no result for the unlink request — completion requires a truthy response, so+ // this is an incomplete operation (502 at the service). Auth survives; the socket still dies.+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);+ try {+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({}));+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };+ fakeSock.query.mockResolvedValueOnce(undefined);++ await expect(adapter.logout()).rejects.toThrow(/did not acknowledge the unlink/i);++ expect(fakeSock.query).toHaveBeenCalledTimes(1);+ expect(rmSpy).not.toHaveBeenCalled();+ expect(fakeSock.end).toHaveBeenCalled();+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);+ expect((adapter as unknown as { sock: unknown }).sock).toBeNull();+ } finally {+ rmSpy.mockRestore();+ }+ });++ it('logout() with a query rejection/timeout rejects, preserves auth, and stops locally', async () => {+ // A transport error or 8s timeout from query() is an incomplete operation. Auth must NOT be+ // removed (the link may still be valid server-side); the socket still ends locally.+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);+ try {+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({}));+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };+ fakeSock.query.mockRejectedValueOnce(new Error('Timed Out'));++ await expect(adapter.logout()).rejects.toThrow('Timed Out');++ expect(fakeSock.query).toHaveBeenCalledTimes(1);+ expect(rmSpy).not.toHaveBeenCalled();+ expect(fakeSock.end).toHaveBeenCalled();+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);+ expect((adapter as unknown as { sock: unknown }).sock).toBeNull();+ } finally {+ rmSpy.mockRestore();+ }+ });++ it('logout() with an acknowledged IQ but fs.rm failure STILL rejects', async () => {+ // Completion requires auth dir removal too. Even after a valid IQ result, a failed credential+ // removal propagates (the operation is incomplete), so 200 is never reported.+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockRejectedValueOnce(new Error('disk full'));+ try {+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({}));+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };++ await expect(adapter.logout()).rejects.toThrow('disk full');++ expect(fakeSock.query).toHaveBeenCalledTimes(1);+ expect(rmSpy).toHaveBeenCalledWith(+ path.join('./data/baileys', 'sess-1'),+ expect.objectContaining({ recursive: true, force: true }),+ );} finally {rmSpy.mockRestore();}@@ -277,7 +492,7 @@ describe('BaileysAdapter lifecycle & status', () => {(adapter as unknown as { sock: unknown }).sock = null;await expect(adapter.logout()).rejects.toThrow(/no live whatsapp socket/i);- expect(fakeSock.logout).not.toHaveBeenCalled();+ expect(fakeSock.query).not.toHaveBeenCalled();expect(rmSpy).not.toHaveBeenCalled();} finally {rmSpy.mockRestore();@@ -816,17 +1031,24 @@ describe('BaileysAdapter status honesty across the reconnect backoff', () => {});it('a logged-out close still reports DISCONNECTED (terminal behavior unchanged)', async () => {- const onDisconnected = jest.fn();- const adapter = await initReady({ onDisconnected });+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);+ try {+ const onDisconnected = jest.fn();+ const adapter = await initReady({ onDisconnected });- fakeSock.fire('connection.update', {- connection: 'close',- lastDisconnect: { error: { output: { statusCode: 401 } } },- });+ fakeSock.fire('connection.update', {+ connection: 'close',+ lastDisconnect: { error: { output: { statusCode: 401 } } },+ });- expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);- expect(onDisconnected).toHaveBeenCalledWith('logged out');- await expect(adapter.probeLiveness()).resolves.toBe(false);+ // The status is DISCONNECTED synchronously; onDisconnected fires after the deferred auth removal.+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);+ await new Promise(r => setImmediate(r));+ expect(onDisconnected).toHaveBeenCalledWith('logged out');+ await expect(adapter.probeLiveness()).resolves.toBe(false);+ } finally {+ rmSpy.mockRestore();+ }});});diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex f5e72ceb5..ef7468175 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -81,6 +81,15 @@ const BAILEYS_BROWSER: [string, string, string] = ['120.0.0',];+/**+ * How long logout() waits for WhatsApp to acknowledge the `remove-companion-device` IQ. Completion of+ * an engine-native unlink requires a tagged IQ result from the server (NOT a WebSocket write flush),+ * so this bound is the difference between a 502 (operation incomplete) and a 200 (unlink completed).+ * Set above the typical round-trip but well under the service's 10s teardown deadline so a wedged+ * transport surfaces as a retryable 502 instead of wedging the session.+ */+const BAILEYS_LOGOUT_ACK_TIMEOUT_MS = 8_000;+/*** Build the Node-layer agent for a session egress proxy (#859). Both the WhatsApp WebSocket* (`agent`) and media up/downloads (`fetchAgent`) ride it; credentials stay in the URL and are@@ -431,13 +440,7 @@ export class BaileysAdapter implements IWhatsAppEngine {// Credentials invalidated — terminal. Re-linking requires a fresh QR/pairing, so the now-dead// multi-file auth dir MUST be wiped: otherwise the next connect() reloads the stale creds and// Baileys silently retries them instead of emitting a new QR, leaving the session stuck (no QR).- this.setStatus(EngineStatus.DISCONNECTED);- this.sock = null;- // Cached call handles die with the connection — drop them so a later rejectCall() reports- // not-found (404) instead of acting on a dead socket (mirrors disconnect/logout/destroy).- this.liveCalls.clear();- void this.clearAuthState();- this.callbacks.onDisconnected?.('logged out');+ void this.handleRemoteLoggedOut();return;}@@ -560,46 +563,137 @@ export class BaileysAdapter implements IWhatsAppEngine {clearTimeout(this.reconnectTimer);this.reconnectTimer = undefined;}- // Without a socket the unlink cannot be sent, and `this.sock?.logout()` would resolve as though it- // had been — reporting a confirmed unlink, writing the audit row, and then wiping the on-disk- // credentials below, leaving the device linked server-side with no way left to retry. Fail instead- // so the caller surfaces it and the credentials survive. Reachable: a WhatsApp-side logout nulls- // the socket while the engine stays registered for the whole reconnect backoff.- if (!this.sock) {+ // Capture the exact live socket. Without one the unlink cannot be sent, and an optional-chained+ // send would resolve as though it had been — reporting a confirmed unlink, writing the audit row,+ // and then wiping the on-disk credentials, leaving the device linked server-side with nothing+ // left to retry with. Reachable: a WhatsApp-side logout nulls the socket while the engine stays+ // registered for the whole reconnect backoff.+ const sourceSock = this.sock;+ if (!sourceSock) {throw new Error('No live WhatsApp socket — the unlink was not sent');}try {- // Baileys' sock.logout() resolves once the WebSocket write has flushed — WhatsApp sends no- // iq ack for the unlink — and it transmits nothing at all when authState.creds.me is unset.- // A resolved promise therefore means "sent (or nothing to send)", not "unlink acknowledged".- await this.sock.logout();+ // Completion of an engine-native unlink requires a tagged IQ result from WhatsApp — Baileys'+ // own sock.logout() resolves on a WebSocket write flush (NOT an IQ ack) and transmits nothing+ // at all when creds.me is unset, so a resolved promise proves nothing about the unlink. Use+ // the public query() surface against the pinned `remove-companion-device` node instead.+ const b = await this.loadLib();+ const jid = sourceSock.user?.id;+ if (!jid) {+ // The companion identity is required to address the unlink; without it nothing is sent.+ throw new Error('No linked companion identity — the unlink was not sent');+ }+ const response: unknown = await sourceSock.query(+ {+ tag: 'iq',+ attrs: { to: b.S_WHATSAPP_NET, type: 'set', id: sourceSock.generateMessageTag(), xmlns: 'md' },+ content: [{ tag: 'remove-companion-device', attrs: { jid, reason: 'user_initiated' } }],+ },+ BAILEYS_LOGOUT_ACK_TIMEOUT_MS,+ );+ if (!response) {+ // query() resolved without a result — WhatsApp did not acknowledge the unlink request.+ throw new Error('WhatsApp did not acknowledge the unlink request');+ }++ // Acknowledged. End/null the captured socket, clear live call handles, and drop to+ // DISCONNECTED before the awaited cleanup so no send/path observes a half-torn-down socket.+ this.localSocketShutdown(sourceSock);+ await this.config.messageStore?.clearSession(this.config.dbSessionId).catch(() => undefined);+ // Wipe the multi-file auth dir so a fresh link starts clean — stale creds would otherwise be+ // reloaded on the next connect() and block re-linking (Baileys retries them, no QR emitted).+ // A removal failure propagates: completion requires cleanup, so the operation is incomplete.+ await this.clearAuthState();} catch (err) {- // End the socket so the session still dies locally, but keep the on-disk creds: wiping- // them now would leave the device linked server-side with no local way to retry the- // unlink. Rethrow so the caller learns the unlink was not confirmed.- this.logger.warn('Baileys logout failed; ending socket', {- error: err instanceof Error ? err.message : String(err),- });- void this.sock?.end(undefined);- this.sock = null;- this.liveCalls.clear();- this.setStatus(EngineStatus.DISCONNECTED);+ // EVERY failure exit (missing identity, query rejection/timeout, empty response, OR a later+ // auth removal failure) still stops sourceSock locally so no engine/socket orphan is left in+ // the service map after it evicts the engine on 502. Failure before acknowledgement must NOT+ // remove auth state — the link may still be valid server-side, and the creds are needed to+ // retry. localSocketShutdown is identity-safe: it only nulls this.sock if it still points at+ // sourceSock (a concurrent reconnect may have already swapped in a fresh socket).+ this.localSocketShutdown(sourceSock);throw err;}- this.sock = null;+ }++ /**+ * Identity-safe local shutdown of a captured socket: clears the reconnect timer, ends the socket,+ * clears cached live call handles, drops to DISCONNECTED, and nulls `this.sock` ONLY if it still+ * points at the same object (a concurrent reconnect could have swapped in a fresh one). Called at+ * every logout exit so the service's 502 genuinely means "stopped locally, operation incomplete".+ */+ private localSocketShutdown(sourceSock: WASocket): void {+ if (this.reconnectTimer) {+ clearTimeout(this.reconnectTimer);+ this.reconnectTimer = undefined;+ }+ try {+ void sourceSock.end(undefined);+ } catch {+ // end() may already have run from Baileys' own close handler — a safe no-op.+ }+ // Cached call handles die with the connection — drop them so a later rejectCall() reports+ // not-found (404) instead of acting on a dead socket (mirrors disconnect/destroy).this.liveCalls.clear();+ if (this.sock === sourceSock) {+ this.sock = null;+ }this.setStatus(EngineStatus.DISCONNECTED);- await this.config.messageStore?.clearSession(this.config.dbSessionId).catch(() => undefined);- // Wipe the multi-file auth dir so a fresh link starts clean — stale creds would otherwise be- // reloaded on the next connect() and block re-linking (Baileys retries them, no QR emitted).- await this.clearAuthState();+ }++ /**+ * Handle a WhatsApp-originated `loggedOut` (401) close: the credentials were invalidated server-side+ * and re-linking requires a fresh QR/pairing, so the now-dead multi-file auth dir MUST be wiped —+ * otherwise the next connect() reloads the stale creds and Baileys silently retries them instead of+ * emitting a QR, leaving the session stuck (no QR).+ *+ * The status/socket/live-call teardown happens SYNCHRONOUSLY before any await so the session+ * watchdog never processes a READY socket that is already dead. The strict auth removal is then+ * awaited as a tracked cleanup (Task 5's onCredentialTeardownStarted registers it under the session+ * NAME). On success the engine reports DISCONNECTED + onDisconnected('logged out'); on failure it+ * reports FAILED + onError (terminal — a reconnect with known-invalid auth would loop forever).+ */+ private async handleRemoteLoggedOut(): Promise<void> {+ // Synchronous teardown BEFORE any await.+ this.setStatus(EngineStatus.DISCONNECTED);+ const dead = this.sock;+ this.sock = null;+ // Cached call handles die with the connection — drop them so a later rejectCall() reports+ // not-found (404) instead of acting on a dead socket (mirrors disconnect/logout/destroy).+ this.liveCalls.clear();+ void dead?.end(undefined);++ const cleanup = (async (): Promise<void> => {+ try {+ await this.clearAuthState();+ } catch (err) {+ // A failed credential removal is terminal: report FAILED + onError instead of looking like a+ // clean disconnect (the credentials did not actually get wiped).+ this.setStatus(EngineStatus.FAILED);+ this.callbacks.onError?.(+ `Logged out by WhatsApp, but the local credential cleanup failed: ${+ err instanceof Error ? err.message : String(err)+ }`,+ );+ return;+ }+ this.callbacks.onDisconnected?.('logged out');+ })();+ // Register the destructive promise the instant it begins (NOT guarded on this engine still being+ // live): the rm targets the session NAME's auth dir and would race a (re)created session under+ // that same name. tracked under the captured name, settled regardless of the outcome.+ this.callbacks.onCredentialTeardownStarted?.(cleanup);+ await cleanup;}/*** Delete this session's on-disk multi-file auth state (`authDir/sessionId`). Required after a terminal* logout: Baileys would otherwise reload the now-invalid creds on the next connect() and retry them* instead of emitting a fresh QR, leaving re-linking stuck. `force` makes a missing dir a no-op.+ * Logs the outcome and RETHROWS on failure: completion of an engine-native unlink (logout 200) AND+ * the loggedOut close path both require cleanup, so a removal failure must propagate (the operation+ * is incomplete), not be swallowed.*/private async clearAuthState(): Promise<void> {try {@@ -609,6 +703,7 @@ export class BaileysAdapter implements IWhatsAppEngine {this.logger.warn('Failed to clear Baileys auth state', {error: err instanceof Error ? err.message : String(err),});+ throw err;}}diff --git a/src/modules/session/session.controller.spec.ts b/src/modules/session/session.controller.spec.tsindex 5692d8fde..8e29050ad 100644--- a/src/modules/session/session.controller.spec.ts+++ b/src/modules/session/session.controller.spec.ts@@ -4,6 +4,8 @@ import { SessionStatus } from './entities/session.entity';import type { Session } from './entities/session.entity';import type { SessionService } from './session.service';import type { AuditService } from '../audit/audit.service';+import { AuditAction } from '../audit/entities/audit-log.entity';+import { BadGatewayException } from '@nestjs/common';// POST /sessions declared a SessionResponseDto in its Swagger metadata but returned the raw// TypeORM entity, leaking internal columns (config, proxyUrl, proxyType) and the entity-only@@ -73,3 +75,62 @@ describe('SessionController — create() response contract', () => {);});});++// POST /sessions/:id/logout audits SESSION_LOGGED_OUT only after the service resolves — an+// incomplete engine-backed attempt (502 SESSION_LOGOUT_INCOMPLETE) must NOT record a success+// audit row, and the service's structured rejection must be forwarded verbatim.+describe('SessionController — logout() audit + error forwarding contract', () => {+ const loggedOutEntity: Session = {+ id: 'sess-uuid-1',+ name: 'test-session',+ status: SessionStatus.DISCONNECTED,+ phone: null,+ pushName: null,+ config: {},+ proxyUrl: null,+ proxyType: null,+ connectedAt: null,+ lastActiveAt: null,+ createdAt: new Date('2026-01-01T00:00:00Z'),+ updatedAt: new Date('2026-01-01T00:00:00Z'),+ };++ let sessionService: { logout: jest.Mock };+ let auditService: { logInfo: jest.Mock };+ let controller: SessionController;++ beforeEach(() => {+ sessionService = { logout: jest.fn() };+ auditService = { logInfo: jest.fn().mockResolvedValue(undefined) };+ controller = new SessionControllerClass(+ sessionService as unknown as SessionService,+ auditService as unknown as AuditService,+ );+ });++ it('on a completed engine-backed unlink: returns a row carrying phone:null and writes exactly one SESSION_LOGGED_OUT audit row', async () => {+ sessionService.logout.mockResolvedValue({ ...loggedOutEntity, phone: null });++ const result = await controller.logout('sess-uuid-1');++ expect(result.phone).toBeNull();+ expect(auditService.logInfo).toHaveBeenCalledTimes(1);+ expect(auditService.logInfo).toHaveBeenCalledWith(+ AuditAction.SESSION_LOGGED_OUT,+ expect.objectContaining({ sessionId: loggedOutEntity.id, sessionName: loggedOutEntity.name }),+ );+ });++ it('on an incomplete engine-backed unlink (502): forwards the service rejection verbatim and does NOT write the SESSION_LOGGED_OUT audit row', async () => {+ // The service throws the structured 502 with the stable code; the controller must NOT swallow it+ // and must NOT record a success audit row for an unlink that never completed.+ const incomplete = new BadGatewayException({+ code: 'SESSION_LOGOUT_INCOMPLETE',+ message: 'Session was stopped locally, but the logout operation did not complete.',+ });+ sessionService.logout.mockRejectedValue(incomplete);++ await expect(controller.logout('sess-uuid-1')).rejects.toBe(incomplete);+ expect(auditService.logInfo).not.toHaveBeenCalled();+ });+});diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 06fed7376..43b3f4451 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -324,23 +324,35 @@ describe('SessionService', () => {// Stop-mark stays set, like stop()/forceKill(): it blocks an in-flight reconnect// from resurrecting a session we just unlinked; a later start() clears it.expect(stoppingOf().has('sess-uuid-1')).toBe(true);- // A confirmed unlink wipes the stored credentials, so the session can never reach READY- // without a fresh QR — clearing phone takes it out of the boot auto-start query- // (phone IS NOT NULL) instead of resurrecting it into a QR it can never pass.+ // A completed engine-backed unlink wipes the stored credentials on both engines, so the+ // session can never reach READY without a fresh QR — clearing phone takes it out of the boot+ // auto-start query (phone IS NOT NULL) instead of resurrecting it into a QR it can never pass.expect(repository.update).toHaveBeenCalledWith('sess-uuid-1', { phone: null });+ // The returned row reflects the cleared phone.expect(result).toBeDefined();+ expect(result.phone).toBeNull();});- it('logout() rejects with 502 when the unlink is unconfirmed — but the session is still torn down locally', async () => {+ it('logout() rejects with 502 + stable code SESSION_LOGOUT_INCOMPLETE when the unlink is incomplete — but still tears down locally AND clears phone', async () => {(repository.findOne as jest.Mock).mockResolvedValue(createMockSession());(repository.update as jest.Mock).mockResolvedValue({ affected: 1 });const engine = { logout: jest.fn().mockRejectedValue(new Error('socket already gone')) };enginesOf().set('sess-uuid-1', engine);- // The distinction that matters: an unconfirmed unlink must surface as an error so the- // controller skips the SESSION_LOGGED_OUT audit row, instead of reporting a success- // that never reached WhatsApp. The local teardown still completes.- await expect(service.logout('sess-uuid-1')).rejects.toBeInstanceOf(BadGatewayException);+ // An incomplete engine-backed attempt must surface as a retryable 502 carrying a stable+ // machine code so the dashboard can branch on origin without guessing from the message. The+ // local teardown still completes, and phone is cleared AFTER the attempt (before the throw) so+ // the boot auto-start does not resurrect the session into an uncertain credential state.+ const thrown = await service.logout('sess-uuid-1').catch((e: unknown) => e);++ expect(thrown).toBeInstanceOf(BadGatewayException);+ // Nest serializes the object response body into `response`; the stable code lives there.+ const response = (thrown as BadGatewayException).getResponse() as { code?: string; message?: string };+ expect(response.code).toBe('SESSION_LOGOUT_INCOMPLETE');+ expect(response.message).toMatch(/operation.*incomplete/i);+ // The message must not pin the cause to "WhatsApp did not confirm" alone — the operation could+ // be incomplete for several reasons (no identity/no send/no ack/timeout/cleanup failure).+ expect(response.message).not.toMatch(/^WhatsApp did not confirm/);expect(engine.logout).toHaveBeenCalledTimes(1);expect(enginesOf().has('sess-uuid-1')).toBe(false); // map reconciled@@ -348,20 +360,23 @@ describe('SessionService', () => {'sess-uuid-1',expect.objectContaining({ status: SessionStatus.DISCONNECTED }),);- // The unlink was NOT confirmed — the device may still be linked server-side, so the session- // must stay eligible for the boot auto-start (which is the "start and retry" automation).- expect(repository.update).not.toHaveBeenCalledWith('sess-uuid-1', { phone: null });+ // phone IS cleared after the engine-backed attempt even on the incomplete path: the local+ // credentials were torn down, so re-entering boot auto-start would only resurrect a session+ // that can no longer reach READY.+ expect(repository.update).toHaveBeenCalledWith('sess-uuid-1', { phone: null });});- it('logout() rejects with 400 when no engine is loaded (session already stopped)', async () => {+ it('logout() rejects with 400 when no engine is loaded (session already stopped) and does NOT clear phone', async () => {(repository.findOne as jest.Mock).mockResolvedValue(createMockSession());enginesOf().delete('sess-uuid-1');- // With no engine there is nothing to send the unlink through — reporting success- // would record a SESSION_LOGGED_OUT audit row for an unlink that never happened.+ // With no engine there is nothing to send the unlink through — reporting success would record+ // a SESSION_LOGGED_OUT audit row for an unlink that never happened. A 400 (no engine) does NOT+ // change the row: phone stays exactly as it was.await expect(service.logout('sess-uuid-1')).rejects.toBeInstanceOf(BadRequestException);// The rejection happens before any teardown side effects: no stop-mark left behind.expect(stoppingOf().has('sess-uuid-1')).toBe(false);+ expect(repository.update).not.toHaveBeenCalledWith('sess-uuid-1', { phone: null });});const pendingTeardownsOf = () =>diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex fda1fabe8..27ce4d7a3 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -2423,31 +2423,37 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat}/**- * Log out of WhatsApp — unlinks this device from the account — then tear the session down.+ * Log out of WhatsApp — attempts an engine-native unlink of this device, then tears the session+ * down locally regardless of the unlink outcome.*- * Differs from stop() in the one way that matters to a user: logout() asks WhatsApp to remove- * the companion device, so the entry disappears from the phone's Linked Devices list. stop() and- * delete() only release things locally (delete also purges the on-disk auth dirs), which leaves- * the device listed on the phone indefinitely — there is currently no way to clear it from the- * API, only by hand on the handset.+ * Differs from stop() in the one way that matters to a user: logout() asks WhatsApp to remove the+ * companion device, so a completed unlink eventually makes the entry disappear from the account+ * holder's Linked Devices list. stop() and delete() only release things locally (delete also+ * purges the on-disk auth dirs).*- * Both engines implement a real unlink, so this is not a best-effort approximation: Baileys sends- * <remove-companion-device reason="user_initiated"/> to s.whatsapp.net, and whatsapp-web.js calls- * WAWebSocketModel.Socket.logout() in the page.+ * Completion (HTTP 200) means the engine-native unlink operation completed AND the required local+ * credential cleanup completed — for Baileys, a valid companion identity, an acknowledged+ * `remove-companion-device` IQ response, and removal of the on-disk auth dir; for whatsapp-web.js,+ * `Client.logout()` including `LocalAuth.logout()` settled. 200 is NOT an independent observation+ * that the handset UI no longer shows the linked device — only the linked-device canary observes+ * that, and the dashboard must not claim otherwise.** Must run while the engine is still live — logout is a network round-trip to WhatsApp, so it* cannot be performed after destroy()/forceDestroy(). Mirrors stop()'s lifecycle otherwise* (stop-mark + cancel-reconnect + bounded, isolated teardown + Map reconciliation).** Requires a started session: with no engine loaded there is nothing to send the unlink through,- * so the request is rejected rather than reporting an unlink that never happened (the on-disk- * credentials would also survive, letting a later start() reconnect with no QR). To just release- * a stopped session locally, use stop()/delete().+ * so the request is rejected with 400 rather than reporting an unlink that never happened. A 400+ * does NOT change the row. To just release a stopped session locally, use stop()/delete().*- * Throws BadGatewayException when the engine's logout does not complete: the session is still- * torn down locally (map reconciled, status updated), but the unlink was not confirmed by- * WhatsApp, so reporting success would record a SESSION_LOGGED_OUT audit row for an unlink- * that never happened. The operator can start the session and retry the logout.+ * Throws a retryable BadGatewayException (502) carrying a stable `code: 'SESSION_LOGOUT_INCOMPLETE'`+ * when an accepted engine-backed attempt stopped locally but the unlink operation did NOT complete+ * — no identity/no send, no IQ acknowledgement, timeout/transport error, OR local credential+ * cleanup failure. After EVERY engine-backed attempt (200 OR 502) the session is torn down locally+ * (map reconciled, status DISCONNECTED) and `phone` is cleared so the boot auto-start does not+ * resurrect the session into an uncertain/invalid credential state. No success audit is written on+ * the 502 path (the controller audits SESSION_LOGGED_OUT only after the service resolves). The+ * operator can start the session and retry the logout.*/async logout(id: string): Promise<Session> {const session = await this.findOne(id);@@ -2473,18 +2479,28 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatawait this.updateStatus(id, SessionStatus.DISCONNECTED);if (!unlinked) {- this.logger.warn(`Session stopped locally but the unlink was not confirmed: ${session.name}`, {+ this.logger.warn(`Session stopped locally but the logout operation did not complete: ${session.name}`, {sessionId: id,- action: 'logout_unconfirmed',+ action: 'logout_incomplete',+ });+ // The local teardown already ran (map reconciled, status DISCONNECTED), but the unlink operation+ // did not complete. Clear `phone` AFTER the attempt and BEFORE throwing so the boot auto-start+ // does not resurrect the session into a credential state that can no longer reach READY — the+ // local credentials were torn down, so re-entering auto-start would only wedge it. The retryable+ // 502 carries a stable machine code so the dashboard can branch on origin without guessing from+ // the status/message; no success audit is written on this path.+ await this.sessionRepository.update(id, { phone: null });+ throw new BadGatewayException({+ statusCode: HttpStatus.BAD_GATEWAY,+ message:+ 'Session was stopped locally, but the logout operation is incomplete — the device may ' ++ 'still be linked. Start the session and retry the logout.',+ error: 'Bad Gateway',+ code: 'SESSION_LOGOUT_INCOMPLETE',});- throw new BadGatewayException(- 'Session was stopped locally, but WhatsApp did not confirm the device unlink — the ' +- 'device may still be listed under Linked Devices on the phone. Start the session and ' +- 'retry the logout to confirm it.',- );}- // A confirmed unlink wipes the stored credentials on both engines, so this session can never+ // A completed engine-backed unlink wipes the stored credentials, so this session can never// reach READY again without a fresh QR/pairing. Clear `phone` to take it out of the boot// auto-start query (phone IS NOT NULL) instead of resurrecting it into a QR it can never pass// on every restart. onReady rewrites it on the next successful link.