Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(events): push WebSocket command replies, and free an aborted slot
Yudhi Armyndharisa86e40429872
diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.tsindex 38bb452db..b5012893c 100644--- a/src/modules/events/events.gateway.spec.ts+++ b/src/modules/events/events.gateway.spec.ts@@ -44,6 +44,8 @@ interface MockSocket {address: string;};data: Record<string, unknown>;+ /** socket.io sets this the moment the transport closes, before the disconnect handler runs. */+ disconnected?: boolean;emit: jest.Mock;disconnect: jest.Mock;join: jest.Mock;@@ -210,6 +212,31 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {expect(sessionRoomJoins(sock)).toEqual([]);});+ it('pushes a command reply on the message event, not only through the ack callback', async () => {+ // The Socket.IO adapter delivers a handler's return value through the ack callback and nothing+ // else, so a client that emits without one (the dashboard, and the documented example client)+ // saw no answer at all: no subscribe confirmation, and none of the refusals.+ authService.validateApiKey.mockResolvedValue({ name: 'k', allowedSessions: ['sess-1'] });+ const sock = makeSocket({ apiKey: 'good' });+ await gateway.handleConnection(asSocket(sock));+ sock.emit.mockClear();++ const granted = (await gateway.handleMessage(+ asSocket(sock),+ subscribeMsg('sess-1', ['message.received']),+ )) as WSSubscribedResponse;+ expect(sock.emit).toHaveBeenCalledWith('message', granted);++ sock.emit.mockClear();+ const refused = (await gateway.handleMessage(asSocket(sock), subscribeMsg('sess-2', ['*']))) as WSErrorResponse;+ expect(refused.code).toBe('FORBIDDEN_SESSION');+ expect(sock.emit).toHaveBeenCalledWith('message', refused);++ sock.emit.mockClear();+ const pong = await gateway.handleMessage(asSocket(sock), { type: 'ping' } as unknown as WSClientMessage);+ expect(sock.emit).toHaveBeenCalledWith('message', pong);+ });+it('forbids a session-scoped key from subscribing to the * wildcard', async () => {authService.validateApiKey.mockResolvedValue({ name: 'k', allowedSessions: ['sess-1'] });const sock = makeSocket({ apiKey: 'good' });@@ -945,5 +972,26 @@ describe('EventsGateway rate limiting', () => {await gw.handleConnection(asSocket(s4));expect(s4.disconnect).not.toHaveBeenCalled();});++ it('does not spend a cap slot on a handshake whose transport closed while it was validating', async () => {+ // Nest runs the disconnect handler as soon as the transport closes, which can be before+ // handleConnection returns. That untrack ran before the key was on client.data and found+ // nothing, so the socket tracked a moment later stayed in the per-key set forever.+ process.env.WS_MAX_SOCKETS_PER_KEY = '1';+ process.env.WS_RATE_LIMIT_HANDSHAKE_MAX = '100';+ authService.validateApiKey.mockResolvedValue({ id: 'k1', name: 'k', allowedSessions: null });+ const gw = buildGateway();++ const aborted = makeSock('aborted', { apiKey: 'good' });+ const connecting = gw.handleConnection(asSocket(aborted));+ aborted.disconnected = true; // the client went away mid-validation+ gw.handleDisconnect(asSocket(aborted)); // Nest dispatches it before the connect resolves+ await connecting;++ // The one slot the key has must still be free.+ const next = makeSock('next', { apiKey: 'good' });+ await gw.handleConnection(asSocket(next));+ expect(next.disconnect).not.toHaveBeenCalled();+ });});});diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex 885713a34..80e1aaf5d 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -375,6 +375,14 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate// this, every client behind one NAT/proxy IP shares a 10/min budget and normal dashboard// re-mounts lock each other out.this.handshakeLimiter.refund(clientIp);+ // The transport can close while validateApiKey is in flight, and Nest runs the disconnect+ // handler before this one returns. That untrack found no key on client.data yet and did+ // nothing, so the socket just tracked would stay in the per-key set for the life of the+ // process, holding a slot of the cap above and keeping the Socket object reachable.+ if (client.disconnected) {+ this.untrackSocket(client);+ return;+ }this.logger.log(`Client connected: ${client.id} (key: ${validKey.name})`);} catch (error) {this.logger.warn(`Client ${client.id} rejected: Auth error`, {@@ -397,8 +405,27 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatethis.logger.log(`Client disconnected: ${client.id}`);}+ /**+ * Answer a client command on the documented `message` event, and hand the same frame back so a+ * client that passed an ack callback still receives it.+ *+ * Returning alone is not enough. The Socket.IO adapter delivers a handler's return value through+ * the ack callback and nothing else, so a client that emits without one, which the dashboard and+ * the documented example client both do, never saw a subscribe confirmation, a pong, or any of the+ * refusals (FORBIDDEN_SESSION, INVALID_SESSION, INVALID_EVENTS, INVALID_MESSAGE).+ *+ * A path that answered and then closed the socket keeps its own emit; emitting to a socket that is+ * already gone is a no-op, and skipping it here keeps that frame single.+ */+ private reply<T>(client: Socket, frame: T): T {+ if (!client.disconnected) {+ client.emit('message', frame);+ }+ return frame;+ }+@SubscribeMessage('message')- handleMessage(@ConnectedSocket() client: Socket, @MessageBody() message: WSClientMessage) {+ async handleMessage(@ConnectedSocket() client: Socket, @MessageBody() message: WSClientMessage) {// Per-key token bucket on every inbound frame. Keyed by the validated key id; a socket// whose handshake validation is still in flight has no key yet and is metered by IP.// Over-budget frames get an error frame back and are NOT dispatched to a handler — in@@ -411,23 +438,20 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGateapiKeyId: (client.data as { apiKey?: Pick<ApiKey, 'id'> } | undefined)?.apiKey?.id,ipAddress: this.resolveClientIp(client),});- const error = this.createError('RATE_LIMITED', 'Frame rate limit exceeded, slow down', requestId);- client.emit('message', error);- return error;+ return this.reply(client, this.createError('RATE_LIMITED', 'Frame rate limit exceeded, slow down', requestId));}switch (message.type) {case 'subscribe':- return this.handleSubscribe(client, message);+ return this.reply(client, await this.handleSubscribe(client, message));case 'unsubscribe':- return this.handleUnsubscribe(client, message);+ return this.reply(client, this.handleUnsubscribe(client, message));case 'ping':- return this.handlePing(client, message.requestId);+ return this.reply(client, this.handlePing(client, message.requestId));default:- return this.createError(- 'INVALID_MESSAGE',- `Unknown message type`,- (message as { requestId?: string }).requestId,+ return this.reply(+ client,+ this.createError('INVALID_MESSAGE', `Unknown message type`, (message as { requestId?: string }).requestId),);}}