Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(events): exactly-once WebSocket delivery + bridge session lifecycle events (#468)
Yudhi Armyndharisab423efae207
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bc8ccac87..274a68f0e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed++- WebSocket events are now delivered exactly once to a client subscribed to overlapping rooms (for example both a specific event and the `*` wildcard for the same session). The real-time fan-out previously sent one copy per matching room, so such a client could receive the same event two to four times. The bundled dashboard was unaffected (its pages subscribe to disjoint rooms); this fixes duplicate delivery for custom WebSocket clients.+- `session.authenticated` and `session.disconnected` are now emitted over the WebSocket (with `{ phone, pushName }` and `{ reason }` respectively), matching the existing webhook payloads. They were advertised as subscribable but were only ever delivered via webhooks, so socket subscribers never received them.++### Changed++- The WebSocket `group.join` / `group.leave` / `group.update` events are no longer accepted as socket subscriptions — they have no engine source and were never delivered on the socket. Subscribing to one now returns a clear validation error instead of silently never delivering. They remain reserved on the webhook side. Webhook subscriptions are unaffected.+## [0.7.3] - 2026-06-25### Addeddiff --git a/src/modules/events/dto/ws-messages.dto.ts b/src/modules/events/dto/ws-messages.dto.tsindex 846757e96..28ab8333c 100644--- a/src/modules/events/dto/ws-messages.dto.ts+++ b/src/modules/events/dto/ws-messages.dto.ts@@ -10,7 +10,10 @@ export type WSClientMessageType = 'subscribe' | 'unsubscribe' | 'ping';// Server -> Client message typesexport type WSServerMessageType = 'subscribed' | 'unsubscribed' | 'event' | 'error' | 'pong';-// Valid event types that can be subscribed to+// Valid event types that can be subscribed to over the socket. Every entry here MUST have a+// matching EventsGateway.emit* producer — the drift guard in events.gateway.spec asserts this.+// (group.* are NOT listed: they have no engine emit source and were never delivered; they stay+// reserved on the webhook side via WEBHOOK_RESERVED_EVENTS.)export const SUBSCRIBABLE_EVENTS = ['message.received','message.sent',@@ -21,9 +24,6 @@ export const SUBSCRIBABLE_EVENTS = ['session.qr','session.authenticated','session.disconnected',- 'group.join',- 'group.leave',- 'group.update',] as const;export type SubscribableEvent = (typeof SUBSCRIBABLE_EVENTS)[number] | '*';diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.tsindex 61726287b..d90a123ad 100644--- a/src/modules/events/events.gateway.spec.ts+++ b/src/modules/events/events.gateway.spec.ts@@ -2,7 +2,9 @@ import { UnauthorizedException } from '@nestjs/common';import { Socket } from 'socket.io';import { EventsGateway, isSessionSubscriptionAllowed } from './events.gateway';import { AuthService } from '../auth/auth.service';-import type { WSClientMessage, WSErrorResponse, WSSubscribedResponse } from './dto/ws-messages.dto';+import { SUBSCRIBABLE_EVENTS, buildRoomName } from './dto/ws-messages.dto';+import type { WSClientMessage, WSErrorResponse, WSSubscribedResponse, WSEventMessage } from './dto/ws-messages.dto';+import { WEBHOOK_RESERVED_EVENTS } from '../webhook/dto/webhook.dto';describe('isSessionSubscriptionAllowed (WS session-scope enforcement)', () => {it('allows an unrestricted key (null allowedSessions) to subscribe to anything, including *', () => {@@ -106,4 +108,112 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {expect(res.type).toBe('subscribed');expect(sock.join).toHaveBeenCalled();});++ it('rejects a subscription to a reserved, never-emitted event (group.*) with INVALID_EVENTS', async () => {+ authService.validateApiKey.mockResolvedValue({ name: 'k', allowedSessions: null });+ const sock = makeSocket({ apiKey: 'good' });+ await gateway.handleConnection(asSocket(sock));++ const res = (await gateway.handleMessage(+ asSocket(sock),+ subscribeMsg('sess-1', ['group.join']),+ )) as WSErrorResponse;++ expect(res.type).toBe('error');+ expect(res.code).toBe('INVALID_EVENTS');+ expect(sock.join).not.toHaveBeenCalled();+ });++ it('keeps the valid events when a subscription mixes a valid and a reserved event', async () => {+ authService.validateApiKey.mockResolvedValue({ name: 'k', allowedSessions: null });+ const sock = makeSocket({ apiKey: 'good' });+ await gateway.handleConnection(asSocket(sock));++ const res = (await gateway.handleMessage(+ asSocket(sock),+ subscribeMsg('sess-1', ['message.received', 'group.join']),+ )) as WSSubscribedResponse;++ expect(res.type).toBe('subscribed');+ expect(res.events).toEqual(['message.received']);+ expect(sock.join).toHaveBeenCalledWith(buildRoomName('sess-1', 'message.received'));+ });+});++// A capturing, chainable Socket.IO server stub: server.to(r1).to(r2)...emit(...) all+// resolve to one operator whose emit() we count. Mirrors the real BroadcastOperator,+// where chained .to() accumulates rooms into a single deduped broadcast.+const makeCapturingServer = () => {+ const rooms: string[] = [];+ const emit = jest.fn();+ const op: { to: jest.Mock; emit: jest.Mock } = { to: jest.fn(), emit };+ op.to.mockImplementation((r: string) => {+ rooms.push(r);+ return op;+ });+ const server = { to: jest.fn((r: string) => (rooms.push(r), op)) };+ return { server, emit, rooms };+};++describe('EventsGateway.emitToRooms fan-out', () => {+ const gw = () => new EventsGateway({ validateApiKey: jest.fn() } as unknown as AuthService);++ it('delivers one event with a single broadcast across all four rooms (no per-room duplicate emit)', () => {+ const gateway = gw();+ const { server, emit, rooms } = makeCapturingServer();+ (gateway as unknown as { server: unknown }).server = server;++ gateway.emitMessage('sess-1', { id: 'm1' });++ // One broadcast, not one-emit-per-room: a socket in several of the rooms gets it once.+ expect(emit).toHaveBeenCalledTimes(1);+ const [channel, message] = emit.mock.calls[0] as [string, WSEventMessage];+ expect(channel).toBe('message');+ expect(message.type).toBe('event');+ expect(message.payload.event).toBe('message.received');+ expect(message.payload.sessionId).toBe('sess-1');+ // Still targets the specific room plus the three wildcard rooms.+ expect(new Set(rooms)).toEqual(+ new Set([+ buildRoomName('sess-1', 'message.received'),+ buildRoomName('sess-1', '*'),+ buildRoomName('*', 'message.received'),+ buildRoomName('*', '*'),+ ]),+ );+ });+});++describe('event catalog ⇔ emitter invariants (drift guard)', () => {+ // Derive the events the gateway ACTUALLY emits by invoking every public emit* room+ // method against a capturing server. Reflection-based so it cannot rot: a new emit*+ // method is auto-discovered; an advertised-but-unemitted event fails the equality.+ const deriveEmittedEvents = (): Set<string> => {+ const gateway = new EventsGateway({ validateApiKey: jest.fn() } as unknown as AuthService);+ const captured: string[] = [];+ const op: { to: () => unknown; emit: (ch: string, msg: WSEventMessage) => boolean } = {+ to: () => op,+ emit: (_ch, msg) => (captured.push(msg.payload.event), true),+ };+ (gateway as unknown as { server: unknown }).server = { to: () => op };++ const proto = Object.getPrototypeOf(gateway) as object;+ const emitMethods = Object.getOwnPropertyNames(proto).filter(+ n => n.startsWith('emit') && n !== 'emitToRooms' && n !== 'emitWebhookStatus',+ );+ for (const name of emitMethods) {+ (gateway as unknown as Record<string, (...a: unknown[]) => void>)[name]('sess-1', {});+ }+ return new Set(captured);+ };++ it('every advertised SUBSCRIBABLE_EVENT has a gateway emitter, and every emitter is advertised', () => {+ expect(new Set(SUBSCRIBABLE_EVENTS)).toEqual(deriveEmittedEvents());+ });++ it('reserved webhook group.* events are NOT advertised as socket-subscribable', () => {+ for (const reserved of WEBHOOK_RESERVED_EVENTS) {+ expect(SUBSCRIBABLE_EVENTS).not.toContain(reserved);+ }+ });});diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex e5c2f8786..45f2ec8c5 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -248,13 +248,16 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatetimestamp: new Date().toISOString(),};- // Emit to specific session + event room- this.server.to(buildRoomName(sessionId, event)).emit('message', eventMessage);-- // Emit to wildcard rooms- this.server.to(buildRoomName(sessionId, '*')).emit('message', eventMessage);- this.server.to(buildRoomName('*', event)).emit('message', eventMessage);- this.server.to(buildRoomName('*', '*')).emit('message', eventMessage);+ // Emit once to the specific room + the three wildcard rooms. Chaining .to()+ // unions the rooms into a single broadcast, so a socket joined to several of+ // them receives the event exactly once (Socket.IO dedups recipients per+ // broadcast). Four separate .emit() calls would deliver one copy per room.+ this.server+ .to(buildRoomName(sessionId, event))+ .to(buildRoomName(sessionId, '*'))+ .to(buildRoomName('*', event))+ .to(buildRoomName('*', '*'))+ .emit('message', eventMessage);}/**@@ -264,6 +267,20 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatethis.emitToRooms(sessionId, 'session.status', { status, ...data });}+ /**+ * Emit session authenticated (engine reached READY). Mirrors the webhook payload.+ */+ emitSessionAuthenticated(sessionId: string, data: { phone: string; pushName: string }) {+ this.emitToRooms(sessionId, 'session.authenticated', data);+ }++ /**+ * Emit session disconnected. Carries the `reason` that the session.status flip drops.+ */+ emitSessionDisconnected(sessionId: string, data: { reason: string }) {+ this.emitToRooms(sessionId, 'session.disconnected', data);+ }+/*** Emit QR code update for a session*/diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex bf089f647..e9bd69c86 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -91,6 +91,8 @@ describe('SessionService', () => {eventsGateway = {emitSessionStatus: jest.fn(),+ emitSessionAuthenticated: jest.fn(),+ emitSessionDisconnected: jest.fn(),emitMessage: jest.fn(),emitMessageSent: jest.fn(),emitMessageAck: jest.fn(),@@ -583,6 +585,32 @@ describe('SessionService', () => {);});+ it('bridges session.authenticated to the socket when the live engine becomes ready', async () => {+ const callbacks = await startAndCapture();+ (eventsGateway.emitSessionAuthenticated as jest.Mock).mockClear();++ callbacks.onReady?.('628123', 'Tester');++ expect(eventsGateway.emitSessionAuthenticated).toHaveBeenCalledWith('sess-uuid-1', {+ phone: '628123',+ pushName: 'Tester',+ });+ });++ it('bridges session.disconnected (with reason) to the socket from the live engine', async () => {+ const callbacks = await startAndCapture();+ // The live onDisconnected handler schedules a reconnect timer after emitting; neutralize+ // it so the test leaves no pending timer (same pattern as the reconnect specs).+ jest+ .spyOn(service as unknown as { scheduleReconnect: (id: string, s: unknown) => void }, 'scheduleReconnect')+ .mockImplementation(() => {});+ (eventsGateway.emitSessionDisconnected as jest.Mock).mockClear();++ callbacks.onDisconnected?.('socket closed');++ expect(eventsGateway.emitSessionDisconnected).toHaveBeenCalledWith('sess-uuid-1', { reason: 'socket closed' });+ });+it('ignores onReady from an engine that was torn down (post-stop window)', async () => {const callbacks = await startAndCapture();enginesOf().delete('sess-uuid-1'); // stop()/forceKill() removes the engine from the live mapdiff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex e2dceda42..3f517c2af 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -565,6 +565,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat});void this.webhookService.dispatch(id, 'session.authenticated', { sessionId: id, phone, pushName });+ this.eventsGateway.emitSessionAuthenticated(id, { phone, pushName });// Execute hook for ready eventvoid this.hookManager.execute(@@ -880,6 +881,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat});void this.webhookService.dispatch(id, 'session.disconnected', { sessionId: id, reason });+ this.eventsGateway.emitSessionDisconnected(id, { reason });// Execute hook for disconnected eventvoid this.hookManager.execute(diff --git a/src/modules/webhook/dto/webhook.dto.ts b/src/modules/webhook/dto/webhook.dto.tsindex 57bde9b3d..ee3c4aacf 100644--- a/src/modules/webhook/dto/webhook.dto.ts+++ b/src/modules/webhook/dto/webhook.dto.ts@@ -27,6 +27,11 @@ const FILTERS_API_EXAMPLE = {],};+// Reserved: valid webhook subscription targets that are not dispatched yet (no engine+// emit source). Kept in WEBHOOK_EVENTS so existing subscriptions validate; tracked+// separately so the catalog/emitter drift guard can whitelist them as intentional.+export const WEBHOOK_RESERVED_EVENTS = ['group.join', 'group.leave', 'group.update'] as const;+export const WEBHOOK_EVENTS = ['message.received','message.sent',@@ -38,10 +43,7 @@ export const WEBHOOK_EVENTS = ['session.qr','session.authenticated','session.disconnected',- // Reserved: accepted on subscribe but not dispatched yet (no engine emit source).- 'group.join',- 'group.leave',- 'group.update',+ ...WEBHOOK_RESERVED_EVENTS,] as const;export type WebhookEventType = (typeof WEBHOOK_EVENTS)[number];