Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(auth): refuse a chat-restricted key on WebSocket subscribe
Yudhi Armyndharisaf3a0d1e9894
diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.tsindex e99f4bd8c..74da0b1b7 100644--- a/src/modules/events/events.gateway.spec.ts+++ b/src/modules/events/events.gateway.spec.ts@@ -134,6 +134,20 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {expect(sock.emit).toHaveBeenCalled();});+ it('refuses a subscribe once the key has gained allowedChats after connect', async () => {+ authService.validateApiKey.mockResolvedValueOnce({ name: 'k', allowedSessions: null }); // connect+ const sock = makeSocket({ apiKey: 'good' });+ await gateway.handleConnection(asSocket(sock));+ expect(sock.disconnect).not.toHaveBeenCalled();++ authService.validateApiKey.mockResolvedValueOnce({ name: 'k', allowedSessions: null, allowedChats: ['[email protected]'] });+ const res = (await gateway.handleMessage(asSocket(sock), subscribeMsg('sess-1', ['*']))) as WSErrorResponse;++ expect(res.code).toBe('UNAUTHORIZED');+ expect(sock.disconnect).toHaveBeenCalled();+ expect(sessionRoomJoins(sock)).toEqual([]);+ });+it('re-validates on subscribe and disconnects a key revoked after connect', async () => {authService.validateApiKey.mockResolvedValueOnce({ name: 'k', allowedSessions: null }); // connectconst sock = makeSocket({ apiKey: 'good' });diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex d4b620a26..1227706dd 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -509,6 +509,19 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatereturn this.createError('UNAUTHORIZED', 'Connection is closed', requestId);}+ // The connect handshake refuses a chat-restricted key, but the key can gain allowedChats after+ // connect (an update on another node), so the fresh key is held to the same rule here.+ if ((subscriberKey.allowedChats?.length ?? 0) > 0) {+ const refusal = this.createError(+ 'UNAUTHORIZED',+ 'API keys restricted to selected chats cannot subscribe to events',+ requestId,+ );+ client.emit('message', refusal);+ client.disconnect();+ return refusal;+ }+// The fresh key decides THIS subscribe, and is deliberately not written back over the connect-time// snapshot in client.data: rooms joined earlier are never revisited, so a socket that refreshed its// snapshot here would look current to the sweep while still holding rooms its key has since lost.