Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(events): hold client frames until the handshake is validated
Yudhi Armyndharisc71e8e82c0ee
diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.tsindex 7537d083e..568be6409 100644--- a/src/modules/events/events.gateway.spec.ts+++ b/src/modules/events/events.gateway.spec.ts@@ -328,6 +328,43 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {}});+ it('holds a frame that arrives while the handshake is still validating until it completes', async () => {+ // socket.io sends CONNECT before Nest runs handleConnection, so a client that subscribes from its+ // 'connect' handler can land here before the key is stored on the socket.+ let finishHandshake!: (key: unknown) => void;+ authService.validateApiKey.mockReturnValueOnce(new Promise(resolve => (finishHandshake = resolve)));+ authService.validateApiKey.mockResolvedValue({ id: 'k1', name: 'k', allowedSessions: null });+ const sock = makeSocket({ apiKey: 'good' });+ const connecting = gateway.handleConnection(asSocket(sock));++ const subscribing = gateway.handleMessage(asSocket(sock), subscribeMsg('sess-1', ['message.received']));+ finishHandshake({ id: 'k1', name: 'k', allowedSessions: null });+ await connecting;++ const res = (await subscribing) as WSSubscribedResponse;+ expect(res.type).toBe('subscribed');+ expect(sock.disconnect).not.toHaveBeenCalled();+ expect(sessionRoomJoins(sock)).toEqual([buildRoomName('sess-1', 'message.received')]);+ });++ it('drops a frame that arrived during a handshake that was then refused', async () => {+ let failHandshake!: (err: Error) => void;+ authService.validateApiKey.mockReturnValueOnce(new Promise((_, reject) => (failHandshake = reject)));+ const sock = makeSocket({ apiKey: 'bad' });+ sock.disconnect.mockImplementation(() => (sock.disconnected = true));+ const connecting = gateway.handleConnection(asSocket(sock));++ const subscribing = gateway.handleMessage(asSocket(sock), subscribeMsg('sess-1', ['message.received']));+ failHandshake(new UnauthorizedException('Invalid API key'));+ await connecting;++ expect(await subscribing).toBeUndefined();+ // Only the handshake's own refusal reached the client, and the frame never re-validated.+ expect(sock.emit).toHaveBeenCalledTimes(1);+ expect(authService.validateApiKey).toHaveBeenCalledTimes(1);+ expect(sessionRoomJoins(sock)).toEqual([]);+ });+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' });diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex 20d7e09e0..b2e1090cd 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -314,7 +314,17 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate}}- async handleConnection(client: Socket) {+ handleConnection(client: Socket): Promise<void> {+ // socket.io sends CONNECT to the client before Nest calls this, and Nest binds the frame handlers+ // without waiting for it, so a client that subscribes from its 'connect' handler can send a frame+ // while the key below is still being validated. handleMessage waits on this promise; it is stored+ // synchronously, before any frame can be dispatched.+ const ready = this.authenticate(client);+ (client.data as { authReady?: Promise<void> }).authReady = ready;+ return ready;+ }++ private async authenticate(client: Socket): Promise<void> {// Resolve the client IP once here so the handshake throttle, the validation, and the// audit trail all use the same trusted-proxy-aware value (parity with the REST guard / MCP mount).const clientIp = this.resolveClientIp(client);@@ -474,6 +484,14 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatereturn this.reply(client, this.createError('RATE_LIMITED', 'Frame rate limit exceeded, slow down', requestId));}+ // A frame sent during the handshake waits for it. Without this a subscribe found no key on the socket+ // and was refused as 'API key is no longer valid', a server-side close the client does not retry.+ // A socket the handshake refused has already been answered and closed, so its frame is dropped.+ await (client.data as { authReady?: Promise<void> }).authReady;+ if (client.disconnected) {+ return undefined;+ }+switch (message?.type) {case 'subscribe':return this.reply(client, await this.handleSubscribe(client, message));