Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): validate :id as UUID (400 not 500) + self-review corrections (reconnect reap, QR close icon) (#641)
Yudhi Armyndharisa22a6bc3e359
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7bf94ece4..bfb2af1f7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **A malformed session id now returns `400` instead of a `500` on PostgreSQL.** The session routes validate the `:id` path param as a UUID at the boundary, so a non-UUID id (a typo or path fuzzing) is rejected with a clean `400` rather than reaching the `uuid` primary-key column and raising an uncaught cast error that surfaced as a generic `500` — a divergence that only appeared on PostgreSQL (SQLite treated the id as text and returned `404`).- **Baileys API sends now emit `message.sent`** (parity with the whatsapp-web.js engine). The wwjs engine fires this for the account's own sends; the Baileys engine's own socket-sends echo back only as a skipped history-sync upsert, so `message.sent` webhooks / WebSocket events / the `message:sent` hook never fired for Baileys API sends. They now fire for text and every media/location/contact/poll/reply/forward send (reactions and deletes excluded).- **Config & reliability hardening.** `DATABASE_STATEMENT_TIMEOUT_MS`, `DATABASE_IDLE_TIMEOUT_MS`, and `DATABASE_CONNECTION_TIMEOUT_MS` are validated at boot — a typo previously reached the config layer as `NaN` and broke the PostgreSQL pool. An unparseable `BODY_SIZE_LIMIT` no longer silently disables the request body-size cap (it falls back to the 25 MB default). The channel-messages endpoint no longer forwards `NaN` to the engine on a non-numeric `?limit`. The fire-and-forget session-row writes in the engine callbacks now handle a transient DB fault instead of surfacing an unhandled rejection, and a set of engine-adapter warning logs no longer mislabel their component name.- **A terminally-failed or un-reinitializable session no longer strands its browser process or wedges at "already started".** When an engine reports a terminal error, and when a reconnect attempt's re-initialization throws, the dead or half-built engine is now evicted from the session registry and its Chromium process is force-killed instead of being left in place — previously it kept holding a concurrency slot and caused a later start to be rejected as already running. Deleting a session likewise force-kills its browser (rather than a graceful close that could hang on a wedged Chromium and orphan the process).diff --git a/dashboard/src/pages/Sessions.tsx b/dashboard/src/pages/Sessions.tsxindex 628e384ce..44f04aa44 100644--- a/dashboard/src/pages/Sessions.tsx+++ b/dashboard/src/pages/Sessions.tsx@@ -450,7 +450,7 @@ export function Sessions() {<span className="session-name">{qrData.sessionName}</span></div><button className="btn-close" onClick={handleCloseQRModal} aria-label={t('common.close')}>- <X size={20} color="var(--text-muted)" />+ <X size={20} style={{ color: 'var(--text-muted)' }} /></button></div><div className="modal-body" style={{ textAlign: 'center' }}>diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex 619b604e7..e96b8e922 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -1,4 +1,4 @@-import { Controller, Get, Post, Delete, Param, Query, Body, HttpCode, HttpStatus } from '@nestjs/common';+import { Controller, Get, Post, Delete, Param, Query, Body, HttpCode, HttpStatus, ParseUUIDPipe } from '@nestjs/common';import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiQuery } from '@nestjs/swagger';import { SessionService } from './session.service';import {@@ -83,7 +83,7 @@ export class SessionController {type: SessionResponseDto,})@ApiResponse({ status: 404, description: 'Session not found' })- async findOne(@Param('id') id: string): Promise<SessionResponseDto> {+ async findOne(@Param('id', ParseUUIDPipe) id: string): Promise<SessionResponseDto> {const session = await this.sessionService.findOne(id);return this.transformSession(session);}@@ -95,7 +95,7 @@ export class SessionController {@ApiParam({ name: 'id', description: 'Session ID' })@ApiResponse({ status: 204, description: 'Session deleted' })@ApiResponse({ status: 404, description: 'Session not found' })- async delete(@Param('id') id: string): Promise<void> {+ async delete(@Param('id', ParseUUIDPipe) id: string): Promise<void> {const session = await this.sessionService.findOne(id);await this.sessionService.delete(id);await this.auditService.logInfo(AuditAction.SESSION_DELETED, {@@ -117,7 +117,7 @@ export class SessionController {})@ApiResponse({ status: 400, description: 'Session already started' })@ApiResponse({ status: 404, description: 'Session not found' })- async start(@Param('id') id: string): Promise<SessionResponseDto> {+ async start(@Param('id', ParseUUIDPipe) id: string): Promise<SessionResponseDto> {const session = await this.sessionService.start(id);await this.auditService.logInfo(AuditAction.SESSION_STARTED, {sessionId: session.id,@@ -136,7 +136,7 @@ export class SessionController {type: SessionResponseDto,})@ApiResponse({ status: 404, description: 'Session not found' })- async stop(@Param('id') id: string): Promise<SessionResponseDto> {+ async stop(@Param('id', ParseUUIDPipe) id: string): Promise<SessionResponseDto> {const session = await this.sessionService.stop(id);await this.auditService.logInfo(AuditAction.SESSION_STOPPED, {sessionId: session.id,@@ -155,7 +155,7 @@ export class SessionController {type: SessionResponseDto,})@ApiResponse({ status: 404, description: 'Session not found' })- async forceKill(@Param('id') id: string): Promise<SessionResponseDto> {+ async forceKill(@Param('id', ParseUUIDPipe) id: string): Promise<SessionResponseDto> {const session = await this.sessionService.forceKill(id);await this.auditService.logInfo(AuditAction.SESSION_FORCE_KILLED, {sessionId: session.id,@@ -178,7 +178,7 @@ export class SessionController {description: 'QR code not ready or session already authenticated',})@ApiResponse({ status: 404, description: 'Session not found' })- async getQRCode(@Param('id') id: string): Promise<QRCodeResponseDto> {+ async getQRCode(@Param('id', ParseUUIDPipe) id: string): Promise<QRCodeResponseDto> {const qrCode = await this.sessionService.getQRCode(id);await this.auditService.logInfo(AuditAction.SESSION_QR_GENERATED, {sessionId: id,@@ -194,7 +194,7 @@ export class SessionController {@ApiResponse({ status: 400, description: 'Session not started or already authenticated' })@ApiResponse({ status: 404, description: 'Session not found' })async requestPairingCode(- @Param('id') id: string,+ @Param('id', ParseUUIDPipe) id: string,@Body() dto: RequestPairingCodeDto,): Promise<PairingCodeResponseDto> {return this.sessionService.requestPairingCode(id, dto.phoneNumber);@@ -212,7 +212,7 @@ export class SessionController {@ApiQuery({ name: 'limit', required: false, description: 'Max groups to return (1–1000, default 1000)' })@ApiQuery({ name: 'offset', required: false, description: 'Number of groups to skip (for paging)' })async getGroups(- @Param('id') id: string,+ @Param('id', ParseUUIDPipe) id: string,@Query('limit') limit?: string,@Query('offset') offset?: string,): Promise<{ id: string; name: string; linkedParentJID?: string | null }[]> {@@ -231,7 +231,7 @@ export class SessionController {@ApiQuery({ name: 'limit', required: false, description: 'Max chats to return (1–1000, default 1000)' })@ApiQuery({ name: 'offset', required: false, description: 'Number of chats to skip (for paging)' })async getChats(- @Param('id') id: string,+ @Param('id', ParseUUIDPipe) id: string,@Query('limit') limit?: string,@Query('offset') offset?: string,): Promise<ChatSummary[]> {@@ -248,7 +248,10 @@ export class SessionController {@ApiResponse({ status: 200, description: 'Chat marked as read successfully' })@ApiResponse({ status: 400, description: 'Session not ready' })@ApiResponse({ status: 404, description: 'Session not found' })- async markChatRead(@Param('id') id: string, @Body() dto: MarkChatReadDto): Promise<{ success: boolean }> {+ async markChatRead(+ @Param('id', ParseUUIDPipe) id: string,+ @Body() dto: MarkChatReadDto,+ ): Promise<{ success: boolean }> {const success = await this.sessionService.sendSeen(id, dto.chatId);return { success };}@@ -260,7 +263,10 @@ export class SessionController {@ApiResponse({ status: 200, description: 'Chat marked as unread successfully' })@ApiResponse({ status: 400, description: 'Session not ready' })@ApiResponse({ status: 404, description: 'Session not found' })- async markChatUnread(@Param('id') id: string, @Body() dto: MarkChatReadDto): Promise<{ success: boolean }> {+ async markChatUnread(+ @Param('id', ParseUUIDPipe) id: string,+ @Body() dto: MarkChatReadDto,+ ): Promise<{ success: boolean }> {const success = await this.sessionService.markUnread(id, dto.chatId);return { success };}@@ -272,7 +278,7 @@ export class SessionController {@ApiResponse({ status: 200, description: 'Chat deleted successfully' })@ApiResponse({ status: 400, description: 'Session not ready' })@ApiResponse({ status: 404, description: 'Session not found' })- async deleteChat(@Param('id') id: string, @Body() dto: DeleteChatDto): Promise<{ success: boolean }> {+ async deleteChat(@Param('id', ParseUUIDPipe) id: string, @Body() dto: DeleteChatDto): Promise<{ success: boolean }> {const success = await this.sessionService.deleteChat(id, dto.chatId);return { success };}@@ -283,7 +289,10 @@ export class SessionController {@ApiParam({ name: 'id', description: 'Session ID' })@ApiResponse({ status: 200, description: 'Presence sent' })@ApiResponse({ status: 404, description: 'Session not found' })- async sendChatState(@Param('id') id: string, @Body() dto: SendChatStateDto): Promise<{ success: boolean }> {+ async sendChatState(+ @Param('id', ParseUUIDPipe) id: string,+ @Body() dto: SendChatStateDto,+ ): Promise<{ success: boolean }> {await this.sessionService.sendChatState(id, dto.chatId, dto.state);return { success: true };}diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 06145001d..2519bc7ec 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -684,6 +684,22 @@ describe('SessionService', () => {}});+ it('keeps a freshly-reconnected healthy engine when the post-init retirement check errors (transient DB)', async () => {+ const i = internals();+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());+ // Re-init succeeds and registers a live engine; the retirement DB read then fails transiently.+ // It must NOT be misread as a reconnect failure that reaps the healthy engine we just recovered.+ jest+ .spyOn(service as unknown as { isSessionRetired: () => Promise<boolean> }, 'isSessionRetired')+ .mockRejectedValue(new Error('transient db blip'));++ await i.executeReconnect('sess-uuid-1', createMockSession(), reconnectState);++ expect(mockEngine.forceDestroy).not.toHaveBeenCalled();+ expect(mockEngine.destroy).not.toHaveBeenCalled();+ expect(i.engines.has('sess-uuid-1')).toBe(true);+ });+it('does not stack reconnect timers when scheduled twice back-to-back', () => {jest.useFakeTimers();try {diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 5ce807238..d89731223 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -1180,7 +1180,16 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// registered so it isn't orphaned (the session is meant to be down). delete() clears its// teardown mark before this slow init resolves, so re-check the session row exists, not just// the mark — otherwise a delete that raced the reconnect leaks a live Chromium/socket.- if (await this.isSessionRetired(id)) {+ // Guard the retirement DB read itself: a transient findOne failure must NOT fall through to the+ // catch below, which would misread the freshly-built, HEALTHY engine as a half-built one and+ // force-kill the session we just recovered. On a read error, assume not-retired and keep it.+ let retired: boolean;+ try {+ retired = await this.isSessionRetired(id);+ } catch {+ retired = false;+ }+ if (retired) {const resurrected = this.engines.get(id);if (resurrected) {await this.teardownEngineSafely(id, resurrected, e => e.destroy(), 'destroy');