Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): return 502 when the WhatsApp unlink is not confirmed (#997)
Yudhi Armyndharis190475141d6b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 476af63a4..04e18df38 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,8 +21,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0audit 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 unlinkthrough, 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.+ which treats an already-stopped session as a successful no-op). If the engine's logout does not+ complete, the session is still torn down locally but the route returns 502 — the unlink was not+ confirmed, no `SESSION_LOGGED_OUT` audit row is written, and the stored credentials survive so+ the retry needs no QR scan (#993). It is additive: the stop, delete, and force-kill semantics+ are unchanged.- **All five SDKs and the dashboard's API client gain the session logout operation** (#984). TheJavaScript, Python, Go, PHP, and Java SDKs each expose a `logout` method mirroring the neighbouringdiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex c3f83132b..b5bc06c0d 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -514,7 +514,12 @@ protocol-level unlink and clear that session's stored credentials, so a later `sfresh QR scan or pairing code.The session must be running — the unlink is a network round-trip that needs a live engine, so a-stopped session is rejected rather than reported as a success that never reached WhatsApp.+stopped session is rejected rather than reported as a success that never reached WhatsApp. If the+engine's logout does not complete (socket already gone, teardown deadline hit), the session is+still torn down locally but the route returns `502`: the unlink was not confirmed, the device may+still be listed under Linked Devices, and no `session_logged_out` audit row is written. Start the+session again and retry to confirm the unlink — the stored credentials survive a failed attempt,+so the retry needs no QR scan.**Auth:** API key (OPERATOR) · **Scope:** session-scoped@@ -546,7 +551,7 @@ No request body.Returned via `transformSession`; status becomes `disconnected`. Recorded in the audit log as`session_logged_out`, distinguishing an intentional unlink from a plain stop.-**Errors:** `400` session is not started · `401` · `403` · `404` not found+**Errors:** `400` session is not started · `401` · `403` · `404` not found · `502` unlink not confirmed (session stopped locally; retryable)#### POST /api/sessions/:id/force-killdiff --git a/openapi.json b/openapi.jsonindex e6cf90680..ad9265714 100644--- a/openapi.json+++ b/openapi.json@@ -562,6 +562,9 @@},"404": {"description": "Session not found"+ },+ "502": {+ "description": "Session was stopped locally, but WhatsApp did not confirm the device unlink — retryable"}},"summary": "Log out of WhatsApp (unlinks this device) and stop the session",diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 0c76653be..363bb55d7 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -248,6 +248,23 @@ 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.+ 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'));++ await expect(adapter.logout()).rejects.toThrow('stream errored out');+ expect(rmSpy).not.toHaveBeenCalled();+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED); // socket still ended locally+ } finally {+ rmSpy.mockRestore();+ }+ });+it('on a recoverable close: reconnects (re-creates the socket) and does NOT fire onDisconnected', async () => {const onDisconnected = jest.fn();const adapter = newAdapter();diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex e7e96efe7..2cd26a09a 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -555,10 +555,17 @@ export class BaileysAdapter implements IWhatsAppEngine {try {await this.sock?.logout();} 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);+ throw err;}this.sock = null;this.liveCalls.clear();diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex a17472f29..b2d33e9d1 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -1089,6 +1089,22 @@ describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {);});+ it('logout() rethrows after the destroy fallback so an unconfirmed unlink is observable', async () => {+ // Swallowing the failure would report a successful unlink that never reached WhatsApp —+ // and write a false SESSION_LOGGED_OUT audit row up-stack. The session must still die+ // locally (destroy fallback), but the error must reach the caller.+ const adapter = newAdapter();+ const unlinkError = new Error('evaluate failed');+ const { client } = attachFakeClient(adapter, {+ logout: jest.fn().mockRejectedValue(unlinkError),+ destroy: jest.fn().mockResolvedValue(undefined),+ });++ await expect(adapter.logout()).rejects.toBe(unlinkError);+ expect(client.destroy).toHaveBeenCalledTimes(1); // local teardown still happened+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);+ });+it('disables ready reconciliation before destroy awaits client teardown', async () => {await expectNoReadyDuringTeardown((client, teardownWait) => {diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 3b617e34f..d52939274 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -1356,12 +1356,15 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginawait client.logout();} catch (error) {this.logger.warn('Logout failed:', { error: String(error) });- // Fall back to destroy if logout fails+ // Fall back to destroy so the session still dies locally — but rethrow so the caller+ // learns the unlink never reached WhatsApp: the device may still be listed under the+ // account holder's Linked Devices, and reporting success would write a false audit row.try {await client.destroy();} catch (destroyError) {this.logger.warn('Client destroy also failed during logout fallback', { error: String(destroyError) });}+ throw error;} finally {this.finishClientTeardown(client);}diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex 5250a7599..ef057dbd2 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -167,6 +167,10 @@ export class SessionController {})@ApiResponse({ status: 400, description: 'Session is not started' })@ApiResponse({ status: 404, description: 'Session not found' })+ @ApiResponse({+ status: 502,+ description: 'Session was stopped locally, but WhatsApp did not confirm the device unlink — retryable',+ })async logout(@Param('id', ParseUUIDPipe) id: string): Promise<SessionResponseDto> {const session = await this.sessionService.logout(id);await this.auditService.logInfo(AuditAction.SESSION_LOGGED_OUT, {diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex f4939616b..8b401da0d 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -1,7 +1,14 @@import { Test, TestingModule } from '@nestjs/testing';import { getRepositoryToken, getDataSourceToken } from '@nestjs/typeorm';import { Repository, DataSource, In } from 'typeorm';-import { NotFoundException, ConflictException, BadRequestException, HttpException, HttpStatus } from '@nestjs/common';+import {+ NotFoundException,+ ConflictException,+ BadRequestException,+ BadGatewayException,+ HttpException,+ HttpStatus,+} from '@nestjs/common';import { ConfigService } from '@nestjs/config';import {SessionService,@@ -319,16 +326,23 @@ describe('SessionService', () => {expect(result).toBeDefined();});- it('logout() completes when engine.logout() rejects — map reconciled, status updated', async () => {+ it('logout() rejects with 502 when the unlink is unconfirmed — but the session is still torn down locally', 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();+ // 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);expect(engine.logout).toHaveBeenCalledTimes(1);- expect(enginesOf().has('sess-uuid-1')).toBe(false);+ expect(enginesOf().has('sess-uuid-1')).toBe(false); // map reconciled+ expect(repository.update).toHaveBeenCalledWith(+ 'sess-uuid-1',+ expect.objectContaining({ status: SessionStatus.DISCONNECTED }),+ );});it('logout() rejects with 400 when no engine is loaded (session already stopped)', async () => {diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex e5a5cdad2..fe082b5f8 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -3,6 +3,7 @@ import {NotFoundException,ConflictException,BadRequestException,+ BadGatewayException,HttpException,HttpStatus,OnModuleDestroy,@@ -2156,6 +2157,11 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat* 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().+ *+ * 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.*/async logout(id: string): Promise<Session> {const session = await this.findOne(id);@@ -2170,14 +2176,26 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// Cancel any reconnection attemptsthis.cancelReconnect(id);- await this.teardownEngineSafely(id, engine, e => e.logout(), 'logout');+ const unlinked = await this.teardownEngineSafely(id, engine, e => e.logout(), 'logout');if (this.isLiveEngine(id, engine)) this.engines.delete(id);+ await this.updateStatus(id, SessionStatus.DISCONNECTED);++ if (!unlinked) {+ this.logger.warn(`Session stopped locally but the unlink was not confirmed: ${session.name}`, {+ sessionId: id,+ action: 'logout_unconfirmed',+ });+ 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.',+ );+ }this.logger.log(`Session logged out: ${session.name}`, {sessionId: id,action: 'logout',});- await this.updateStatus(id, SessionStatus.DISCONNECTED);return this.findOne(id);}