Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(events): refund an authenticated IPv6 handshake on its /64
Yudhi Armyndharisebffe2b0ac3c
diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.tsindex beffd409a..da6b2a414 100644--- a/src/modules/events/events.gateway.spec.ts+++ b/src/modules/events/events.gateway.spec.ts@@ -973,6 +973,24 @@ describe('EventsGateway rate limiting', () => {const ipOf = ([, ctx]: [AuditAction, WarnContext?]): unknown =>(ctx as { ipAddress?: string } | undefined)?.ipAddress;+ it('refunds an authenticated handshake to the /64 bucket it was charged to', async () => {+ // The charge lands on the /64; a refund keyed on the full address finds no bucket, so every+ // authenticated connect from one IPv6 network would spend the shared window after all.+ process.env.WS_RATE_LIMIT_HANDSHAKE_MAX = '2';+ process.env.WS_RATE_LIMIT_HANDSHAKE_WINDOW_MS = '60000';+ process.env.WS_MAX_SOCKETS_PER_KEY = '99';+ authService.validateApiKey.mockResolvedValue({ id: 'k1', name: 'k', allowedSessions: null });+ const gw = buildGateway();++ const addresses = ['2001:db8:1:2::a', '2001:db8:1:2::a', '2001:db8:1:2::b', '2001:db8:1:2::c', '2001:db8:1:2::a'];+ for (const [i, address] of addresses.entries()) {+ const sock = makeSock(`ok${i}`, { apiKey: 'good' }, address);+ await gw.handleConnection(asSocket(sock));+ expect(sock.disconnect).not.toHaveBeenCalled();+ }+ expect(authService.validateApiKey).toHaveBeenCalledTimes(addresses.length);+ });+it('shares the handshake window and the violation sample across a /64, keeping the real address', async () => {process.env.WS_RATE_LIMIT_HANDSHAKE_MAX = '1';authService.validateApiKey.mockRejectedValue(new Error('bad key'));diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex 5e6f6e0b7..b145b9882 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -308,11 +308,14 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate// 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);+ // The handshake bucket key: an IPv6 client is charged on its /64. The refund below must name the+ // same bucket, or an authenticated IPv6 handshake is never given back.+ const handshakeKey = limiterKeyForIp(clientIp);// Pre-auth, per-IP handshake throttle. This must run BEFORE any credential handling: an// unauthenticated handshake flood otherwise reaches the DB validateApiKey below on every// attempt (same gap the MCP pre-auth IP throttle covers for the /mcp mount).- if (!this.handshakeLimiter.allow(limiterKeyForIp(clientIp))) {+ if (!this.handshakeLimiter.allow(handshakeKey)) {this.logger.warn(`Client ${client.id} rejected: handshake rate limit exceeded (ip: ${clientIp})`);this.noteRateLimitViolation('handshake', { ipAddress: clientIp });client.emit('message', this.createError('RATE_LIMITED', 'Too many connection attempts, retry later'));@@ -387,7 +390,7 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate// handshakes, and authenticated connections stay bounded by maxSocketsPerKey above. Without// 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);+ this.handshakeLimiter.refund(handshakeKey);// 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