Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): map WA auth-timeout to 504 instead of bare 500 (#733) (#740)
Yudhi Armyndharis6b969ce153b9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 74bf4b954..4f1e941e6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **Send-response semantics clarified (docs only).** The send endpoints' Swagger response and `docs/06` now state explicitly that `201` means the gateway accepted the message for sending — not that the recipient received it — and that WhatsApp does not reject an unregistered recipient synchronously, so a message to a number that is not on WhatsApp still returns `201` with a `messageId` but never delivers. `GET /sessions/{id}/contacts/check/{number}` is cross-referenced as the way to pre-validate a new recipient, and the async message `status` lifecycle (`sent → delivered → read`, or `failed`) as the source of real delivery state. No behavior change. Refs #738.+### Fixed++- **Engine auth-timeout now returns a diagnostic 504 instead of a bare 500.** When the WhatsApp Web+ engine's internal authentication poll exhausts its timeout (default 30s) — e.g. the session proxy+ is unreachable, so the browser launches but no QR is ever delivered — `POST /api/sessions/:id/start`+ previously let the primitive `'auth timeout'` string escape to NestJS's default handler as a+ meaningless `500 Internal Server Error`. It now maps to `504 Gateway Timeout` with a message+ pointing at the proxy / network-egress / firewall causes and the `WWEBJS_AUTH_TIMEOUT_MS` knob for+ legitimately slow first boots. The outer engine-init hang deadline (`EngineInitTimeoutError`) still+ surfaces as 500 and is tracked separately.+## [0.8.17] - 2026-07-13### Addeddiff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex a49bcd18e..3dd28e85c 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -1,7 +1,7 @@import { Test, TestingModule } from '@nestjs/testing';import { getRepositoryToken, getDataSourceToken } from '@nestjs/typeorm';import { Repository, DataSource, In } from 'typeorm';-import { NotFoundException, ConflictException, BadRequestException } from '@nestjs/common';+import { NotFoundException, ConflictException, BadRequestException, HttpException, HttpStatus } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { SessionService, ACK_RECONCILE_DELAY_MS, EngineInitTimeoutError } from './session.service';import { Session, SessionStatus } from './entities/session.entity';@@ -420,6 +420,26 @@ describe('SessionService', () => {expect(mockEngine.destroy).not.toHaveBeenCalled();});+ it('maps a whatsapp-web.js auth timeout (bare string) to HTTP 504, not a bare 500 (#733)', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ (engineFactory.create as jest.Mock).mockClear().mockReturnValue(mockEngine);+ // whatsapp-web.js throws the PRIMITIVE STRING 'auth timeout' (not an Error) when its inject poll+ // for WA Web's login bootstrap times out — e.g. a dead/unreachable proxy (the proxy.example.com+ // placeholder) blocks the WebSocket so no QR is ever delivered. This must surface as a diagnostic+ // 504, not escape as a meaningless bare 500.+ mockEngine.initialize.mockRejectedValueOnce('auth timeout');++ let caught: unknown;+ try {+ await service.start('sess-uuid-1');+ } catch (err) {+ caught = err;+ }+ expect(caught).toBeInstanceOf(HttpException);+ expect((caught as HttpException).getStatus()).toBe(HttpStatus.GATEWAY_TIMEOUT);+ });+it('allows a fresh start after the previous one completed (reservation is cleared)', 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 1be75c949..e2827136b 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -3,6 +3,8 @@ import {NotFoundException,ConflictException,BadRequestException,+ HttpException,+ HttpStatus,OnModuleDestroy,OnModuleInit,OnApplicationBootstrap,@@ -112,6 +114,26 @@ export class EngineInitTimeoutError extends Error {}}+/**+ * whatsapp-web.js throws this primitive STRING (not an Error) from its inject() auth poll when WA Web's+ * login bootstrap doesn't complete within authTimeoutMs (default 30s). Match it defensively as both the+ * bare string and an Error carrying the same message, since the library's throw shape isn't contracted.+ */+const ENGINE_AUTH_TIMEOUT = 'auth timeout';++/**+ * Diagnostic surfaced when the engine's internal auth-timeout fires (#733): points at the usual cause+ * (the session proxy / network egress / firewall blocking WhatsApp so no QR is ever delivered) and the+ * WWEBJS_AUTH_TIMEOUT_MS knob for legitimately slow first boots.+ */+const ENGINE_AUTH_TIMEOUT_MESSAGE =+ 'WhatsApp Web authentication timed out. Verify the session proxy URL and network egress can reach ' ++ 'WhatsApp; for slow first boots, raise WWEBJS_AUTH_TIMEOUT_MS.';++function isAuthTimeoutRejection(err: unknown): boolean {+ return err === ENGINE_AUTH_TIMEOUT || (err instanceof Error && err.message === ENGINE_AUTH_TIMEOUT);+}+@Injectable()export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicationBootstrap {private readonly logger = createLogger('SessionService');@@ -1202,6 +1224,14 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// teardownEngineSafely is itself time-bound, so this can't wedge a second time.await this.teardownEngineSafely(id, engine, e => e.forceDestroy(), 'force-destroy');await this.updateStatus(id, SessionStatus.DISCONNECTED);+ } else if (isAuthTimeoutRejection(err)) {+ // The engine's INTERNAL auth-timeout: whatsapp-web.js throws the primitive string 'auth timeout'+ // (see ENGINE_AUTH_TIMEOUT) when its inject poll exhausts authTimeoutMs (default 30s) — the common+ // pre-QR failure when the browser launched but couldn't reach WhatsApp, e.g. a dead/unreachable+ // session proxy (#733). onError already evicted the engine + wrote FAILED before this catch ran, so+ // only the HTTP mapping remains: surface a diagnostic 504 instead of letting the bare string escape+ // to NestJS's default handler as a meaningless 500.+ throw new HttpException(ENGINE_AUTH_TIMEOUT_MESSAGE, HttpStatus.GATEWAY_TIMEOUT);}throw err;} finally {