Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(session): expose POST /sessions/:id/logout to unlink the device (#984)
elwizardc3221d6c1138
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4ccb3671c..4680a20d8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- **`POST /sessions/:id/logout` unlinks the device from the WhatsApp account** (#984). Both engines+ already implemented a real protocol-level unlink — whatsapp-web.js calls `WAWebSocketModel.Socket.logout()`+ and Baileys sends `<remove-companion-device reason="user_initiated"/>` — but the method had no caller,+ so it was unreachable over the API. `stop()` disconnects while keeping the stored credentials (a later+ start reconnects without a QR), and `delete()` additionally purges the on-disk auth directories and the+ session row, but neither tells WhatsApp anything, so the device stayed listed under the account+ holder's Linked Devices on the phone until they removed it by hand. The new route mirrors `stop()`'s+ lifecycle — stop-mark, reconnection cancel, bounded and isolated teardown, engine-map reconciliation+ — while calling `engine.logout()` instead of `engine.disconnect()`, and records a `SESSION_LOGGED_OUT`+ audit action so an intentional unlink is distinguishable from a plain stop or a WhatsApp-side eviction.+ The route requires a started session: with no engine loaded there is nothing to send the unlink+ through, so it returns 400 instead of reporting an unlink that never happened (unlike `stop()`,+ which treats an already-stopped session as a successful no-op). It is additive: the stop, delete,+ and force-kill semantics are unchanged.+### Fixed- **`npm install` from source no longer fails on native Windows, and the whatsapp-web.js backportdiff --git a/openapi.json b/openapi.jsonindex d6fe170a7..e6cf90680 100644--- a/openapi.json+++ b/openapi.json@@ -23,6 +23,7 @@"session_started","session_stopped","session_force_killed",+ "session_logged_out","session_deleted","session_qr_generated","session_connected",@@ -530,6 +531,45 @@]}},+ "/api/sessions/{id}/logout": {+ "post": {+ "description": "Asks WhatsApp to remove this companion device, so it disappears from the account holder's Linked Devices list, then tears the session down. Unlike stop and delete — which only release the session locally and leave the device linked on the phone — reconnecting after a logout always requires a fresh QR scan or pairing code.",+ "operationId": "SessionController_logout",+ "parameters": [+ {+ "name": "id",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Session logged out",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SessionResponseDto"+ }+ }+ }+ },+ "400": {+ "description": "Session is not started"+ },+ "404": {+ "description": "Session not found"+ }+ },+ "summary": "Log out of WhatsApp (unlinks this device) and stop the session",+ "tags": [+ "sessions"+ ]+ }+ },"/api/sessions/{id}/force-kill": {"post": {"operationId": "SessionController_forceKill",diff --git a/src/modules/audit/entities/audit-log.entity.ts b/src/modules/audit/entities/audit-log.entity.tsindex 9ca38b109..f9c0c36e1 100644--- a/src/modules/audit/entities/audit-log.entity.ts+++ b/src/modules/audit/entities/audit-log.entity.ts@@ -21,6 +21,7 @@ export enum AuditAction {SESSION_STARTED = 'session_started',SESSION_STOPPED = 'session_stopped',SESSION_FORCE_KILLED = 'session_force_killed',+ SESSION_LOGGED_OUT = 'session_logged_out',SESSION_DELETED = 'session_deleted',SESSION_QR_GENERATED = 'session_qr_generated',SESSION_CONNECTED = 'session_connected',diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex 81bfa2fe9..5250a7599 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -148,6 +148,34 @@ export class SessionController {return this.transformSession(session);}+ @Post(':id/logout')+ @RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.OK)+ @ApiOperation({+ summary: 'Log out of WhatsApp (unlinks this device) and stop the session',+ description:+ "Asks WhatsApp to remove this companion device, so it disappears from the account holder's " ++ 'Linked Devices list, then tears the session down. Unlike stop and delete — which only ' ++ 'release the session locally and leave the device linked on the phone — reconnecting after ' ++ 'a logout always requires a fresh QR scan or pairing code.',+ })+ @ApiParam({ name: 'id', description: 'Session ID' })+ @ApiResponse({+ status: 200,+ description: 'Session logged out',+ type: SessionResponseDto,+ })+ @ApiResponse({ status: 400, description: 'Session is not started' })+ @ApiResponse({ status: 404, description: 'Session not found' })+ async logout(@Param('id', ParseUUIDPipe) id: string): Promise<SessionResponseDto> {+ const session = await this.sessionService.logout(id);+ await this.auditService.logInfo(AuditAction.SESSION_LOGGED_OUT, {+ sessionId: session.id,+ sessionName: session.name,+ });+ return this.transformSession(session);+ }+@Post(':id/force-kill')@RequireRole(ApiKeyRole.OPERATOR)@HttpCode(HttpStatus.OK)diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 56e996366..f4939616b 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -297,6 +297,51 @@ describe('SessionService', () => {expect(stoppingOf().has('sess-uuid-1')).toBe(false); // mark still cleared on failure});+ it('logout() calls the engine logout (not disconnect), reconciles the map, and marks the session stopping', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ const engine = {+ logout: jest.fn().mockResolvedValue(undefined),+ disconnect: jest.fn().mockResolvedValue(undefined),+ };+ enginesOf().set('sess-uuid-1', engine);++ const result = await service.logout('sess-uuid-1');++ // The distinction that matters: disconnect() leaves the device linked on the+ // phone, logout() asks WhatsApp to remove it.+ expect(engine.logout).toHaveBeenCalledTimes(1);+ expect(engine.disconnect).not.toHaveBeenCalled();+ expect(enginesOf().has('sess-uuid-1')).toBe(false); // map reconciled+ // 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);+ expect(result).toBeDefined();+ });++ it('logout() completes when engine.logout() rejects — map reconciled, status updated', 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);++ await expect(service.logout('sess-uuid-1')).resolves.toBeDefined();++ expect(engine.logout).toHaveBeenCalledTimes(1);+ expect(enginesOf().has('sess-uuid-1')).toBe(false);+ });++ it('logout() rejects with 400 when no engine is loaded (session already stopped)', 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.+ 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);+ });+it('forceKill() force-destroys the engine, reconciles the map, and marks the session stopping', async () => {(repository.findOne as jest.Mock).mockResolvedValue(createMockSession());(repository.update as jest.Mock).mockResolvedValue({ affected: 1 });diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 12a8bcfd2..e5a5cdad2 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -367,7 +367,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatsessionId: string,engine: IWhatsAppEngine,teardown: (e: IWhatsAppEngine) => Promise<void>,- label: 'destroy' | 'disconnect' | 'force-destroy',+ label: 'destroy' | 'disconnect' | 'force-destroy' | 'logout',): Promise<boolean> {let timer: ReturnType<typeof setTimeout> | undefined;try {@@ -2135,6 +2135,52 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatreturn this.findOne(id);}+ /**+ * Log out of WhatsApp — unlinks this device from the account — then tear the session down.+ *+ * 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.+ *+ * 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.+ *+ * 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().+ */+ async logout(id: string): Promise<Session> {+ const session = await this.findOne(id);+ const engine = this.engines.get(id);++ if (!engine) {+ throw new BadRequestException('Session is not started. Call POST /sessions/:id/start first.');+ }++ // Mark as tearing down BEFORE cleanup so an in-flight reconnect can't resurrect it.+ this.stoppingSessions.add(id);+ // Cancel any reconnection attempts+ this.cancelReconnect(id);++ await this.teardownEngineSafely(id, engine, e => e.logout(), 'logout');+ if (this.isLiveEngine(id, engine)) this.engines.delete(id);++ this.logger.log(`Session logged out: ${session.name}`, {+ sessionId: id,+ action: 'logout',+ });+ await this.updateStatus(id, SessionStatus.DISCONNECTED);+ return this.findOne(id);+ }+/*** Force-recover a stuck session: SIGKILL its engine's own resources (a wedged Chromium for the* whatsapp-web.js engine) and tear it down, even when a normal stop()/delete() can't because the