Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(events): refund the handshake attempt that succeeded

Yudhi Armyndharisc3d8be04b20a
diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.ts
index f1cc9969c..5edabf812 100644
--- a/src/modules/events/events.gateway.spec.ts
+++ b/src/modules/events/events.gateway.spec.ts
@@ -11,6 +11,7 @@ import { AuditAction } from '../audit/entities/audit-log.entity';
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';
+import { SlidingWindowLimiter } from './ws-rate-limit';
describe('isSessionSubscriptionAllowed (WS session-scope enforcement)', () => {
it('allows an unrestricted key (null allowedSessions) to subscribe to anything, including *', () => {
@@ -1205,6 +1206,40 @@ describe('EventsGateway rate limiting', () => {
expect(authService.validateApiKey).toHaveBeenCalledTimes(6);
});
+ it.each([false, true])(
+ 'keeps newer failures charged after a delayed valid handshake (pruned: %s)',
+ async pruned => {
+ let now = 0;
+ let finish!: (key: unknown) => void;
+ const validation = new Promise(resolve => (finish = resolve));
+ authService.validateApiKey.mockImplementation((raw: string) =>
+ raw === 'good' ? validation : Promise.reject(new UnauthorizedException('Invalid API key')),
+ );
+ const gw = buildGateway();
+ (gw as unknown as { handshakeLimiter: SlidingWindowLimiter }).handshakeLimiter = new SlidingWindowLimiter(
+ 2,
+ 1000,
+ () => now,
+ );
+ const good = makeSock('good', { apiKey: 'good' });
+ const connecting = gw.handleConnection(asSocket(good));
+ now = pruned ? 1001 : 500;
+ await gw.handleConnection(asSocket(makeSock('bad-1', { apiKey: 'bad' })));
+ now = pruned ? 1002 : 600;
+ finish({ id: 'k1', name: 'k', allowedSessions: null });
+ await connecting;
+ expect(good.disconnect).not.toHaveBeenCalled();
+ expect(authService.validateApiKey).toHaveBeenCalledWith('good', '203.0.113.5');
+ now = pruned ? 1003 : 1001;
+ await gw.handleConnection(asSocket(makeSock('bad-2', { apiKey: 'bad' })));
+ const blocked = makeSock('bad-3', { apiKey: 'bad' });
+ await gw.handleConnection(asSocket(blocked));
+ expect(blocked.emit).toHaveBeenCalledWith('message', expect.objectContaining({ code: 'RATE_LIMITED' }));
+ expect(authService.validateApiKey).toHaveBeenCalledTimes(3);
+ gw.handleDisconnect(asSocket(good));
+ },
+ );
+
it('throttles an unauthenticated handshake flood before any credential/audit work', async () => {
process.env.WS_RATE_LIMIT_HANDSHAKE_MAX = '2';
const gw = buildGateway();
diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.ts
index 79a17946f..8e0a4fbc1 100644
--- a/src/modules/events/events.gateway.ts
+++ b/src/modules/events/events.gateway.ts
@@ -397,7 +397,8 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
// 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(handshakeKey)) {
+ const handshakeReservation = {};
+ if (!this.handshakeLimiter.allow(handshakeKey, handshakeReservation)) {
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'));
@@ -459,7 +460,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(handshakeKey);
+ this.handshakeLimiter.refund(handshakeKey, handshakeReservation);
// 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
diff --git a/src/modules/events/ws-rate-limit.spec.ts b/src/modules/events/ws-rate-limit.spec.ts
index f9f5bf316..66b0e711c 100644
--- a/src/modules/events/ws-rate-limit.spec.ts
+++ b/src/modules/events/ws-rate-limit.spec.ts
@@ -166,4 +166,45 @@ describe('SlidingWindowLimiter.refund', () => {
limiter.refund('never-seen');
expect(limiter.allow('never-seen')).toBe(true);
});
+
+ it.each([false, true])('keeps newer failures charged after an old success is refunded (pruned: %s)', pruned => {
+ let now = 0;
+ const limiter = new SlidingWindowLimiter(2, 1000, () => now);
+ const success = {};
+ expect(limiter.allow('ip', success)).toBe(true);
+ now = pruned ? 1001 : 500;
+ expect(limiter.allow('ip', {})).toBe(true);
+ limiter.refund('ip', success);
+ now = pruned ? 1002 : 1001;
+ expect(limiter.allow('ip')).toBe(true);
+ expect(limiter.allow('ip')).toBe(false);
+ });
+
+ it('distinguishes reservations from the same clock tick and refunds each only once', () => {
+ const limiter = new SlidingWindowLimiter(2, 1000, () => 0);
+ const first = {};
+ const second = {};
+ expect(limiter.allow('ip', first)).toBe(true);
+ expect(limiter.allow('ip', second)).toBe(true);
+ limiter.refund('ip', first);
+ limiter.refund('ip', first);
+ expect(limiter.allow('ip')).toBe(true);
+ expect(limiter.allow('ip')).toBe(false);
+ limiter.refund('ip', second);
+ expect(limiter.allow('ip')).toBe(true);
+ });
+
+ it('does not refund another subject or an admission that was refused', () => {
+ const limiter = new SlidingWindowLimiter(1, 1000, () => 0);
+ const admitted = {};
+ const other = {};
+ const denied = {};
+ expect(limiter.allow('a', admitted)).toBe(true);
+ expect(limiter.allow('b', other)).toBe(true);
+ expect(limiter.allow('a', denied)).toBe(false);
+ limiter.refund('a', other);
+ limiter.refund('a', denied);
+ expect(limiter.allow('a')).toBe(false);
+ expect(limiter.allow('b')).toBe(false);
+ });
});
diff --git a/src/modules/events/ws-rate-limit.ts b/src/modules/events/ws-rate-limit.ts
index 3a3adcc2e..1ca8eb8da 100644
--- a/src/modules/events/ws-rate-limit.ts
+++ b/src/modules/events/ws-rate-limit.ts
@@ -116,7 +116,7 @@ export class TokenBucketLimiter {
* KeyRateLimiter wraps it for the HTTP side.
*/
export class SlidingWindowLimiter {
- private readonly hits = new Map<string, number[]>();
+ private readonly hits = new Map<string, { at: number; reservation?: object }[]>();
constructor(
private readonly max = DEFAULT_HANDSHAKE_MAX,
@@ -125,12 +125,15 @@ export class SlidingWindowLimiter {
private readonly maxKeys = DEFAULT_MAX_KEYS,
) {}
- /** Record one attempt for `subject`; returns false when it exceeds `max` inside the window. */
- allow(subject: string): boolean {
+ /**
+ * Record one attempt for `subject`; returns false when it exceeds `max` inside the window. A caller that
+ * gives the attempt back after an await passes a `reservation` object to name it (see refund).
+ */
+ allow(subject: string, reservation?: object): boolean {
const t = this.now();
- const recent = (this.hits.get(subject) ?? []).filter(ts => t - ts < this.windowMs);
+ const recent = (this.hits.get(subject) ?? []).filter(hit => t - hit.at < this.windowMs);
const allowed = recent.length < this.max;
- if (allowed) recent.push(t);
+ if (allowed) recent.push({ at: t, reservation });
this.hits.delete(subject);
this.hits.set(subject, recent);
@@ -139,7 +142,9 @@ export class SlidingWindowLimiter {
}
/**
- * Give back the most recent attempt recorded for `subject`.
+ * Give back the attempt recorded for `subject` under `reservation`, or the most recent one when none is given.
+ * A caller that awaits between allow and refund must pass its reservation: by then newer attempts, a failed
+ * handshake among them, are on the list, and the most recent one is not its own.
*
* The handshake window is consumed BEFORE authentication (that is the point — an unauthenticated
* flood must not reach the DB key validation on every attempt), which also charges every
@@ -148,9 +153,14 @@ export class SlidingWindowLimiter {
* Refunding a handshake that turned out to be authentic keeps the budget aimed at failures;
* authenticated abuse is bounded separately by the per-key socket cap.
*/
- refund(subject: string): void {
+ refund(subject: string, reservation?: object): void {
const recent = this.hits.get(subject);
if (!recent?.length) return;
- recent.pop();
+ if (!reservation) {
+ recent.pop();
+ return;
+ }
+ const index = recent.findIndex(hit => hit.reservation === reservation);
+ if (index !== -1) recent.splice(index, 1);
}
}