Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(events): rate-limit websocket handshakes, frames, and per-key sockets (#937)
Yudhi Armyndharis40098d49d2ea
diff --git a/.env.example b/.env.exampleindex d2509bda3..d386f89a5 100644--- a/.env.example+++ b/.env.example@@ -309,6 +309,21 @@ RATE_LIMIT_MEDIUM_LIMIT=100 # max requests per window# RATE_LIMIT_LONG_TTL=3600000 # 1h window (default)# RATE_LIMIT_LONG_LIMIT=1000+# WebSocket (/events Socket.IO) limits, enforced in-process by the gateway (WS frames bypass+# the HTTP guard pipeline). Any blank/non-positive/non-numeric value falls back to the default.+# Per-key token bucket on client frames (subscribe/unsubscribe/ping): the dashboard sends ~8+# subscribe frames at page mount and only occasional frames afterwards, so 60/s sustained with+# a 120-frame burst is ~6x headroom over legitimate traffic while bounding a flooding key.+# WS_RATE_LIMIT_FRAME_PER_SECOND=60 # sustained frames per second per API key (default 60)+# WS_RATE_LIMIT_FRAME_BURST=120 # burst capacity per API key (default 120)+# Pre-auth, per-IP throttle on NEW handshakes — gates the DB key validation so an+# unauthenticated handshake flood cannot force a validate per attempt. Socket.IO reconnect+# backs off exponentially (~6 attempts/min per tab), so 10/min covers a few re-mounting tabs.+# WS_RATE_LIMIT_HANDSHAKE_MAX=10 # max handshakes per IP per window (default 10)+# WS_RATE_LIMIT_HANDSHAKE_WINDOW_MS=60000 # window in ms (default 60000 = 1 min)+# Cap on simultaneous sockets per API key (multi-tab dashboards + SDK clients on one key).+# WS_MAX_SOCKETS_PER_KEY=16 # default 16+# Per-instance fairness cap on the Integration Fabric ingress route (POST /api/ingress/:pluginId/:instanceId/*).# Providers deliver every tenant's webhooks from one shared egress IP, so this is keyed on# (pluginId, instanceId) instead of IP — a noisy tenant gets 429'd without throttling its neighbors.diff --git a/docs/04-security-design.md b/docs/04-security-design.mdindex 82fc7f2ba..abcc234c6 100644--- a/docs/04-security-design.md+++ b/docs/04-security-design.md@@ -333,6 +333,18 @@ TTL values are in milliseconds. The `/api/metrics` and `/api/health*` routes areExceeding any window returns `429 Too Many Requests` with a `Retry-After` header. The `ThrottlerGuard` also sets `X-RateLimit-*` response headers (limit / remaining / reset) by default, and the API exposes them via CORS — but with three named windows in play, the `429` + `Retry-After` is the simplest backpressure signal to act on.+### WebSocket (`/events`) limits++Socket.IO frames never pass through the Nest enhancer pipeline, so the HTTP windows above do **not** apply to the WebSocket surface. `EventsGateway` enforces its own in-process limits instead (all keyed in-memory per process; any blank/non-positive/non-numeric env value falls back to the default):++| Limit | Keyed on | Default | Env overrides |+|-------|----------|---------|---------------|+| Client frames (subscribe/unsubscribe/ping) — token bucket | API key (IP before auth completes) | 60 frames/s sustained, 120-frame burst | `WS_RATE_LIMIT_FRAME_PER_SECOND` / `WS_RATE_LIMIT_FRAME_BURST` |+| New handshakes — sliding window, enforced **before** key validation | client IP (resolved through `TRUSTED_PROXIES`) | 10 per 60 s | `WS_RATE_LIMIT_HANDSHAKE_MAX` / `WS_RATE_LIMIT_HANDSHAKE_WINDOW_MS` |+| Simultaneous sockets | API key | 16 | `WS_MAX_SOCKETS_PER_KEY` |++The frame budget is sized ~6x above legitimate traffic: the dashboard emits ~8 subscribe frames at page mount and only occasional ping/unsubscribe frames afterwards (server→client event fan-out is not limited). The handshake window stops an unauthenticated connection flood from forcing a DB `validateApiKey` per attempt; Socket.IO's exponential-backoff reconnect (~6 attempts/min per tab) stays under it. The socket cap covers multi-tab dashboards and SDK clients sharing one key. A rejected handshake or excess socket is answered with a `RATE_LIMITED` error frame and a clean disconnect; an over-budget frame gets a `RATE_LIMITED` error frame and is not dispatched. Violations are audited as `rate_limit_exceeded`, sampled to at most one row per subject+kind per minute (suppressed occurrences are counted into the next row) so the audit trail itself cannot become the flood.+## 4.7 CORS Configuration### CORS Settingsdiff --git a/openapi.json b/openapi.jsonindex 079140c6b..6394a9ff8 100644--- a/openapi.json+++ b/openapi.json@@ -17,6 +17,7 @@"api_key_revoked","api_key_deleted","api_key_auth_failed",+ "rate_limit_exceeded","session_created","session_started","session_stopped",diff --git a/src/config/configuration.ts b/src/config/configuration.tsindex 5033b3d00..412cf0fb5 100644--- a/src/config/configuration.ts+++ b/src/config/configuration.ts@@ -1,5 +1,6 @@import { computeFeatureFlags } from './feature-flags';import { resolveInflightBodyBudgetBytes } from './inflight-body-budget';+import { readWsRateLimitConfig } from '../modules/events/ws-rate-limit';export default () => ({port: parseInt(process.env.PORT || '2785', 10),@@ -168,6 +169,14 @@ export default () => ({},},+ // WebSocket (/events Socket.IO) rate limits. The gateway sits outside the Nest enhancer+ // pipeline (global guards never run on WS frames), so EventsGateway enforces these+ // in-process. Single source of truth is readWsRateLimitConfig (with the same+ // missing/blank/non-positive/non-numeric → default fallback the MCP limiters use):+ // per-key frame token bucket (framePerSecond sustained + frameBurst capacity),+ // pre-auth per-IP handshake sliding window, and a per-key simultaneous-socket cap.+ websocket: readWsRateLimitConfig(),+// Security configurationsecurity: {// Comma-separated IPs/CIDRs of reverse proxies whose X-Forwarded-For headerdiff --git a/src/config/env.validation.ts b/src/config/env.validation.tsindex 11294b99e..a355375d4 100644--- a/src/config/env.validation.ts+++ b/src/config/env.validation.ts@@ -146,6 +146,12 @@ export function validateEnv(config: EnvConfig): EnvConfig {'RATE_LIMIT_SHORT_LIMIT','RATE_LIMIT_MEDIUM_LIMIT','RATE_LIMIT_LONG_LIMIT',+ // WebSocket (/events) limits: 0 would disable a tier entirely (a self-DoS on the WS surface).+ 'WS_RATE_LIMIT_FRAME_PER_SECOND',+ 'WS_RATE_LIMIT_FRAME_BURST',+ 'WS_RATE_LIMIT_HANDSHAKE_MAX',+ 'WS_RATE_LIMIT_HANDSHAKE_WINDOW_MS',+ 'WS_MAX_SOCKETS_PER_KEY','WEBHOOK_TIMEOUT','INGRESS_INSTANCE_LIMIT','REQUEST_TIMEOUT_MS',diff --git a/src/modules/audit/entities/audit-log.entity.ts b/src/modules/audit/entities/audit-log.entity.tsindex c495a597e..2bd7b72a2 100644--- a/src/modules/audit/entities/audit-log.entity.ts+++ b/src/modules/audit/entities/audit-log.entity.ts@@ -9,6 +9,10 @@ export enum AuditAction {API_KEY_DELETED = 'api_key_deleted',API_KEY_AUTH_FAILED = 'api_key_auth_failed',+ // Rate-limit enforcement (sampled: at most one row per subject+kind per minute — see+ // EventsGateway — so enforcing a limit never becomes an audit-write flood of its own).+ RATE_LIMIT_EXCEEDED = 'rate_limit_exceeded',+// Session eventsSESSION_CREATED = 'session_created',SESSION_STARTED = 'session_started',diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.tsindex 68eeeacb7..d90241a32 100644--- a/src/modules/events/events.gateway.spec.ts+++ b/src/modules/events/events.gateway.spec.ts@@ -451,3 +451,258 @@ describe('event catalog ⇔ emitter invariants (drift guard)', () => {}});});++// Rate limiting on the WS surface: the gateway sits outside the Nest guard pipeline, so the+// per-key frame bucket, the pre-auth per-IP handshake window, and the per-key socket cap are+// all enforced inside EventsGateway. The gateway reads its config from the env at construction,+// so these tests pin the WS_* env vars per test (and restore them afterwards).+describe('EventsGateway rate limiting', () => {+ const WS_ENV_KEYS = [+ 'WS_RATE_LIMIT_FRAME_PER_SECOND',+ 'WS_RATE_LIMIT_FRAME_BURST',+ 'WS_RATE_LIMIT_HANDSHAKE_MAX',+ 'WS_RATE_LIMIT_HANDSHAKE_WINDOW_MS',+ 'WS_MAX_SOCKETS_PER_KEY',+ ] as const;++ let gateway: EventsGateway;+ let authService: { validateApiKey: jest.Mock };+ let auditService: { logWarn: jest.Mock };+ let savedEnv: Record<string, string | undefined>;++ const makeSock = (id: string, auth: { apiKey?: string } = {}): MockSocket => ({+ id,+ handshake: { headers: {}, query: {}, auth, address: '203.0.113.5' },+ data: {},+ emit: jest.fn(),+ disconnect: jest.fn(),+ join: jest.fn(),+ rooms: new Set<string>(),+ });+ const asSocket = (s: MockSocket): Socket => s as unknown as Socket;+ const subscribeMsg = (sessionId: string, events: string[]): WSClientMessage =>+ ({ type: 'subscribe', sessionId, events, requestId: 'r1' }) as unknown as WSClientMessage;++ beforeEach(() => {+ savedEnv = {};+ for (const key of WS_ENV_KEYS) {+ savedEnv[key] = process.env[key];+ delete process.env[key];+ }+ authService = { validateApiKey: jest.fn() };+ auditService = { logWarn: jest.fn().mockResolvedValue(null) };+ });++ afterEach(() => {+ for (const key of WS_ENV_KEYS) {+ if (savedEnv[key] === undefined) delete process.env[key];+ else process.env[key] = savedEnv[key];+ }+ jest.useRealTimers();+ });++ const buildGateway = (): EventsGateway => {+ gateway = new EventsGateway(authService as unknown as AuthService, auditService as unknown as AuditService);+ return gateway;+ };++ // Typed view over the audit mock's calls so assertions on action/metadata don't wade through `any`.+ interface WarnContext {+ metadata?: Record<string, unknown>;+ }+ const warnCalls = (): [AuditAction, WarnContext?][] =>+ auditService.logWarn.mock.calls as [AuditAction, WarnContext?][];++ describe('per-key frame token bucket', () => {+ it('rejects the frame above the bucket with a RATE_LIMITED error frame and never reaches the handler', async () => {+ process.env.WS_RATE_LIMIT_FRAME_PER_SECOND = '2';+ process.env.WS_RATE_LIMIT_FRAME_BURST = '3';+ authService.validateApiKey.mockResolvedValue({ id: 'k1', name: 'k', allowedSessions: null });+ const gw = buildGateway();+ const sock = makeSock('s1', { apiKey: 'good' });+ await gw.handleConnection(asSocket(sock));+ expect(authService.validateApiKey).toHaveBeenCalledTimes(1);++ // The 3-frame burst passes; each subscribe re-validates the key.+ for (let i = 0; i < 3; i++) {+ const res = (await gw.handleMessage(asSocket(sock), subscribeMsg('sess-1', ['session.status']))) as {+ type: string;+ };+ expect(res.type).toBe('subscribed');+ }+ expect(authService.validateApiKey).toHaveBeenCalledTimes(4);++ // The frame above the bucket: error frame back to the client, and NOT dispatched —+ // in particular it never reaches the per-subscribe DB re-validation.+ const res = (await gw.handleMessage(+ asSocket(sock),+ subscribeMsg('sess-1', ['session.status']),+ )) as WSErrorResponse;+ expect(res.type).toBe('error');+ expect(res.code).toBe('RATE_LIMITED');+ expect(sock.emit).toHaveBeenCalledWith('message', expect.objectContaining({ code: 'RATE_LIMITED' }));+ expect(authService.validateApiKey).toHaveBeenCalledTimes(4);+ });++ it('lets a normal dashboard connect-time subscribe burst (8 frames) through untouched', async () => {+ // Defaults: 60 frames/s sustained + 120 burst — far above a page-mount burst.+ authService.validateApiKey.mockResolvedValue({ id: 'k1', name: 'k', allowedSessions: null });+ const gw = buildGateway();+ const sock = makeSock('s1', { apiKey: 'good' });+ await gw.handleConnection(asSocket(sock));++ for (let i = 0; i < 8; i++) {+ const res = (await gw.handleMessage(asSocket(sock), subscribeMsg('sess-1', ['session.status']))) as {+ type: string;+ };+ expect(res.type).toBe('subscribed');+ }+ });++ it('recovers after the refill window: a throttled key can send again', async () => {+ process.env.WS_RATE_LIMIT_FRAME_PER_SECOND = '2';+ process.env.WS_RATE_LIMIT_FRAME_BURST = '2';+ jest.useFakeTimers();+ authService.validateApiKey.mockResolvedValue({ id: 'k1', name: 'k', allowedSessions: null });+ const gw = buildGateway();+ const sock = makeSock('s1', { apiKey: 'good' });+ await gw.handleConnection(asSocket(sock));++ await gw.handleMessage(asSocket(sock), subscribeMsg('sess-1', ['session.status']));+ await gw.handleMessage(asSocket(sock), subscribeMsg('sess-1', ['session.status']));+ const limited = (await gw.handleMessage(asSocket(sock), subscribeMsg('sess-1', ['session.status']))) as {+ code?: string;+ };+ expect(limited.code).toBe('RATE_LIMITED');++ jest.advanceTimersByTime(1_000); // 2 tokens refill at 2/s+ const res = (await gw.handleMessage(asSocket(sock), subscribeMsg('sess-1', ['session.status']))) as {+ type: string;+ };+ expect(res.type).toBe('subscribed');+ });+ });++ describe('pre-auth per-IP handshake window', () => {+ it('rejects the handshake above the window BEFORE validateApiKey runs', async () => {+ process.env.WS_RATE_LIMIT_HANDSHAKE_MAX = '3';+ process.env.WS_RATE_LIMIT_HANDSHAKE_WINDOW_MS = '60000';+ authService.validateApiKey.mockResolvedValue({ id: 'k1', name: 'k', allowedSessions: null });+ const gw = buildGateway();++ for (let i = 0; i < 3; i++) {+ await gw.handleConnection(asSocket(makeSock(`s${i}`, { apiKey: 'good' })));+ }+ expect(authService.validateApiKey).toHaveBeenCalledTimes(3);++ // The 4th handshake from the same IP inside the window is gated pre-auth: the DB+ // validate is never reached.+ const blocked = makeSock('s-blocked', { apiKey: 'good' });+ await gw.handleConnection(asSocket(blocked));+ expect(authService.validateApiKey).toHaveBeenCalledTimes(3);+ expect(blocked.disconnect).toHaveBeenCalled();+ expect(blocked.emit).toHaveBeenCalledWith('message', expect.objectContaining({ code: 'RATE_LIMITED' }));+ const violations = warnCalls().filter(([action]) => action === AuditAction.RATE_LIMIT_EXCEEDED);+ expect(violations).toHaveLength(1);+ expect(violations[0]?.[1]?.metadata).toEqual(+ expect.objectContaining({ surface: 'websocket', kind: 'handshake' }),+ );+ });++ it('throttles an unauthenticated handshake flood before any credential/audit work', async () => {+ process.env.WS_RATE_LIMIT_HANDSHAKE_MAX = '2';+ const gw = buildGateway();++ // Three key-less handshakes from one IP: the first two reach the missing-key audit,+ // the third is gated by the limiter instead (no per-attempt auth failure processing).+ await gw.handleConnection(asSocket(makeSock('a')));+ await gw.handleConnection(asSocket(makeSock('b')));+ await gw.handleConnection(asSocket(makeSock('c')));++ const authFailed = warnCalls().filter(([action]) => action === AuditAction.API_KEY_AUTH_FAILED);+ expect(authFailed).toHaveLength(2);+ expect(authService.validateApiKey).not.toHaveBeenCalled();+ });++ it('recovers once the window slides past the oldest handshake', async () => {+ process.env.WS_RATE_LIMIT_HANDSHAKE_MAX = '1';+ process.env.WS_RATE_LIMIT_HANDSHAKE_WINDOW_MS = '60000';+ jest.useFakeTimers();+ authService.validateApiKey.mockResolvedValue({ id: 'k1', name: 'k', allowedSessions: null });+ const gw = buildGateway();++ await gw.handleConnection(asSocket(makeSock('a', { apiKey: 'good' })));+ const blocked = makeSock('b', { apiKey: 'good' });+ await gw.handleConnection(asSocket(blocked));+ expect(blocked.disconnect).toHaveBeenCalled();+ expect(authService.validateApiKey).toHaveBeenCalledTimes(1);++ jest.advanceTimersByTime(60_001);+ const recovered = makeSock('c', { apiKey: 'good' });+ await gw.handleConnection(asSocket(recovered));+ expect(recovered.disconnect).not.toHaveBeenCalled();+ expect(authService.validateApiKey).toHaveBeenCalledTimes(2);+ });++ it('samples the violation audit: one row per subject per minute, suppressed count folded in', async () => {+ process.env.WS_RATE_LIMIT_HANDSHAKE_MAX = '1';+ process.env.WS_RATE_LIMIT_HANDSHAKE_WINDOW_MS = '60000';+ jest.useFakeTimers();+ authService.validateApiKey.mockResolvedValue({ id: 'k1', name: 'k', allowedSessions: null });+ const gw = buildGateway();++ await gw.handleConnection(asSocket(makeSock('a', { apiKey: 'good' }))); // allowed+ await gw.handleConnection(asSocket(makeSock('b', { apiKey: 'good' }))); // rejected → audit #1+ await gw.handleConnection(asSocket(makeSock('c', { apiKey: 'good' }))); // rejected → suppressed++ jest.advanceTimersByTime(61_000);+ await gw.handleConnection(asSocket(makeSock('d', { apiKey: 'good' }))); // allowed again+ await gw.handleConnection(asSocket(makeSock('e', { apiKey: 'good' }))); // rejected → audit #2++ const rateLimited = warnCalls().filter(([action]) => action === AuditAction.RATE_LIMIT_EXCEEDED);+ expect(rateLimited).toHaveLength(2);+ expect(rateLimited[0]?.[1]?.metadata).toEqual(expect.objectContaining({ kind: 'handshake', suppressed: 0 }));+ expect(rateLimited[1]?.[1]?.metadata).toEqual(expect.objectContaining({ kind: 'handshake', suppressed: 1 }));+ });+ });++ describe('per-key simultaneous socket cap', () => {+ it('rejects the socket above the cap with a clear error, and frees the slot on disconnect', async () => {+ process.env.WS_MAX_SOCKETS_PER_KEY = '2';+ // Keep the handshake window out of the way: this test is about the socket cap.+ process.env.WS_RATE_LIMIT_HANDSHAKE_MAX = '100';+ authService.validateApiKey.mockResolvedValue({ id: 'k1', name: 'k', allowedSessions: null });+ const gw = buildGateway();++ const s1 = makeSock('s1', { apiKey: 'good' });+ const s2 = makeSock('s2', { apiKey: 'good' });+ await gw.handleConnection(asSocket(s1));+ await gw.handleConnection(asSocket(s2));+ expect(s1.disconnect).not.toHaveBeenCalled();+ expect(s2.disconnect).not.toHaveBeenCalled();++ // The 3rd simultaneous socket for the same key IS authenticated (the cap is a post-auth+ // fairness bound, not an auth failure) and then refused with a clear error.+ const s3 = makeSock('s3', { apiKey: 'good' });+ await gw.handleConnection(asSocket(s3));+ expect(authService.validateApiKey).toHaveBeenCalledTimes(3);+ expect(s3.disconnect).toHaveBeenCalled();+ expect(s3.emit).toHaveBeenCalledWith(+ 'message',+ expect.objectContaining({+ code: 'RATE_LIMITED',+ message: expect.stringContaining('Too many concurrent connections') as unknown,+ }),+ );+ const violations = warnCalls().filter(([action]) => action === AuditAction.RATE_LIMIT_EXCEEDED);+ expect(violations).toHaveLength(1);+ expect(violations[0]?.[1]?.metadata).toEqual(expect.objectContaining({ kind: 'sockets' }));++ // Disconnecting one socket frees the slot for the next connection.+ gw.handleDisconnect(asSocket(s2));+ const s4 = makeSock('s4', { apiKey: 'good' });+ await gw.handleConnection(asSocket(s4));+ expect(s4.disconnect).not.toHaveBeenCalled();+ });+ });+});diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex 08c9b33bb..dc52849ef 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -16,6 +16,12 @@ import { AuditAction } from '../audit/entities/audit-log.entity';import { resolveCorsPolicy } from '../../config/bootstrap-security';import { resolveClientIp as resolveRequestClientIp, type RequestLike } from '../../common/utils/ip';import type { ApiKey } from '../auth/entities/api-key.entity';+import {+ readWsRateLimitConfig,+ TokenBucketLimiter,+ SlidingWindowLimiter,+ type WsRateLimitConfig,+} from './ws-rate-limit';/*** WebSocket CORS origin: reuse the HTTP CORS policy instead of a hardcoded '*'.@@ -97,10 +103,37 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGateprivate readonly socketsByKeyId = new Map<string, Set<Socket>>();private expirySweepTimer?: ReturnType<typeof setInterval>;+ /**+ * Rate limiting for the WS surface (see ws-rate-limit.ts). Frames never pass through the+ * Nest guard pipeline, so these run in the gateway itself:+ * - frameLimiter: per-key token bucket on every inbound client frame (pre-auth sockets are+ * keyed by IP instead, since they have no validated key yet);+ * - handshakeLimiter: pre-auth per-IP sliding window on new connections, so a handshake+ * flood cannot force a DB validateApiKey per attempt;+ * - maxSocketsPerKey: cap on simultaneous sockets per key, enforced at connect.+ */+ private readonly rateLimits: WsRateLimitConfig;+ private readonly frameLimiter: TokenBucketLimiter;+ private readonly handshakeLimiter: SlidingWindowLimiter;++ /**+ * Rate-limit violation sampler: at most one audit row per kind+subject per minute. An abuser+ * held at a limit would otherwise generate an audit write per blocked frame/handshake — the+ * audit trail itself becoming the flood. `count` accumulates the suppressed violations since+ * the last emitted row and is folded into the next one.+ */+ private readonly violations = new Map<string, { count: number; since: number }>();+ private static readonly VIOLATION_AUDIT_WINDOW_MS = 60_000;+ private static readonly MAX_VIOLATION_KEYS = 10_000;+constructor(private readonly authService: AuthService,private readonly auditService: AuditService,- ) {}+ ) {+ this.rateLimits = readWsRateLimitConfig();+ this.frameLimiter = new TokenBucketLimiter(this.rateLimits.framePerSecond, this.rateLimits.frameBurst);+ this.handshakeLimiter = new SlidingWindowLimiter(this.rateLimits.handshakeMax, this.rateLimits.handshakeWindowMs);+ }afterInit() {this.logger.log('WebSocket Gateway initialized');@@ -187,13 +220,25 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate}async handleConnection(client: Socket) {+ // 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);++ // 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(clientIp)) {+ 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'));+ client.disconnect();+ return;+ }+// Accept the key only via Socket.IO's `auth` field or the header — never the query string, which// leaks the credential into proxy/access logs. (The deprecated `?apiKey=` fallback was removed.)const handshakeAuth = client.handshake.auth as { apiKey?: string } | undefined;const apiKey = handshakeAuth?.apiKey || (client.handshake.headers['x-api-key'] as string);- // Resolve the client IP once here so both the validation and the audit trail use the same- // trusted-proxy-aware value (parity with the REST guard / MCP mount).- const clientIp = this.resolveClientIp(client);if (!apiKey) {this.logger.warn(`Client ${client.id} rejected: No API key provided`);@@ -214,6 +259,26 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate// for "Client IP could not be determined".const validKey = await this.authService.validateApiKey(apiKey, clientIp);+ // Cap simultaneous sockets per key: each socket holds rooms, engine fan-out, and memory,+ // so one key must not open connections without bound. Enough for multi-tab dashboards;+ // excess connections get a clear error, not a silent drop.+ const existing = this.socketsByKeyId.get(validKey.id);+ if (existing && existing.size >= this.rateLimits.maxSocketsPerKey) {+ this.logger.warn(+ `Client ${client.id} rejected: socket cap reached for key ${validKey.id} (${this.rateLimits.maxSocketsPerKey})`,+ );+ this.noteRateLimitViolation('sockets', { apiKeyId: validKey.id, ipAddress: clientIp });+ client.emit(+ 'message',+ this.createError(+ 'RATE_LIMITED',+ `Too many concurrent connections for this API key (max ${this.rateLimits.maxSocketsPerKey})`,+ ),+ );+ client.disconnect();+ return;+ }+// Store the validated key AND the raw key — the raw key lets handleSubscribe// RE-validate on each subscription so a key revoked mid-connection is caught.(client.data as { apiKey: unknown; rawApiKey: string }).apiKey = validKey;@@ -243,6 +308,23 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate@SubscribeMessage('message')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+ // particular they never reach the per-subscribe DB re-validation.+ const frameSubject =+ (client.data as { apiKey?: Pick<ApiKey, 'id'> } | undefined)?.apiKey?.id ?? this.resolveClientIp(client);+ if (!this.frameLimiter.allow(frameSubject)) {+ const requestId = (message as { requestId?: string } | undefined)?.requestId;+ this.noteRateLimitViolation('frame', {+ apiKeyId: (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;+ }+switch (message.type) {case 'subscribe':return this.handleSubscribe(client, message);@@ -371,6 +453,41 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate};}+ /**+ * Sampled audit for rate-limit violations: emits at most one row per kind+subject per minute+ * (fire-and-forget, like the auth-failure audit). Violations suppressed inside the window are+ * counted and folded into the next emitted row's `suppressed` metadata, so the forensic trail+ * stays accurate without one audit write per blocked frame/handshake.+ */+ private noteRateLimitViolation(+ kind: 'handshake' | 'frame' | 'sockets',+ subject: { apiKeyId?: string; ipAddress?: string },+ ): void {+ const mapKey = `${kind}:${subject.apiKeyId ?? subject.ipAddress ?? 'unknown'}`;+ const now = Date.now();+ const prior = this.violations.get(mapKey);+ if (prior && now - prior.since < EventsGateway.VIOLATION_AUDIT_WINDOW_MS) {+ prior.count += 1;+ return;+ }+ const suppressed = prior?.count ?? 0;+ this.violations.delete(mapKey);+ this.violations.set(mapKey, { count: 0, since: now });+ while (this.violations.size > EventsGateway.MAX_VIOLATION_KEYS) {+ const oldest = this.violations.keys().next().value;+ if (oldest === undefined) break;+ this.violations.delete(oldest);+ }+ void this.auditService.logWarn(AuditAction.RATE_LIMIT_EXCEEDED, {+ // Only the id is read (for the apiKeyId column) — enough to correlate with the key+ // without a DB lookup on a hot path.+ apiKey: subject.apiKeyId ? ({ id: subject.apiKeyId } as ApiKey) : undefined,+ ipAddress: subject.ipAddress,+ metadata: { surface: 'websocket', kind, suppressed },+ errorMessage: `websocket ${kind} rate limit exceeded`,+ });+ }+// ========== Event Emission Methods (room-based) ==========/**diff --git a/src/modules/events/ws-rate-limit.spec.ts b/src/modules/events/ws-rate-limit.spec.tsnew file mode 100644index 000000000..8c356ed68--- /dev/null+++ b/src/modules/events/ws-rate-limit.spec.ts@@ -0,0 +1,138 @@+import { readWsRateLimitConfig, TokenBucketLimiter, SlidingWindowLimiter } from './ws-rate-limit';++describe('readWsRateLimitConfig', () => {+ it('returns the documented defaults when no env vars are set', () => {+ expect(readWsRateLimitConfig({})).toEqual({+ framePerSecond: 60,+ frameBurst: 120,+ handshakeMax: 10,+ handshakeWindowMs: 60_000,+ maxSocketsPerKey: 16,+ });+ });++ it('reads every override from the environment', () => {+ expect(+ readWsRateLimitConfig({+ WS_RATE_LIMIT_FRAME_PER_SECOND: '5',+ WS_RATE_LIMIT_FRAME_BURST: '9',+ WS_RATE_LIMIT_HANDSHAKE_MAX: '3',+ WS_RATE_LIMIT_HANDSHAKE_WINDOW_MS: '15000',+ WS_MAX_SOCKETS_PER_KEY: '4',+ }),+ ).toEqual({+ framePerSecond: 5,+ frameBurst: 9,+ handshakeMax: 3,+ handshakeWindowMs: 15_000,+ maxSocketsPerKey: 4,+ });+ });++ it('falls back to the default for blank, non-numeric, or non-positive values', () => {+ const bogus = ['', ' ', 'abc', '0', '-3', '1.5x'];+ for (const raw of bogus) {+ const cfg = readWsRateLimitConfig({ WS_RATE_LIMIT_FRAME_PER_SECOND: raw, WS_MAX_SOCKETS_PER_KEY: raw });+ expect(cfg.framePerSecond).toBe(60);+ expect(cfg.maxSocketsPerKey).toBe(16);+ }+ });+});++describe('TokenBucketLimiter (per-key frame budget)', () => {+ let nowMs: number;+ const now = () => nowMs;+ beforeEach(() => {+ nowMs = 1_000_000;+ });++ it('allows a burst up to the capacity, then rejects the frame above the bucket', () => {+ const limiter = new TokenBucketLimiter(60, 4, now);+ for (let i = 0; i < 4; i++) {+ expect(limiter.allow('k1')).toBe(true);+ }+ expect(limiter.allow('k1')).toBe(false);+ // A rejected frame consumes nothing: still rejected on the immediate retry.+ expect(limiter.allow('k1')).toBe(false);+ });++ it('refills at the sustained per-second rate (recovery after the burst)', () => {+ const limiter = new TokenBucketLimiter(2, 3, now);+ expect(limiter.allow('k1')).toBe(true);+ expect(limiter.allow('k1')).toBe(true);+ expect(limiter.allow('k1')).toBe(true);+ expect(limiter.allow('k1')).toBe(false);++ nowMs += 1_000; // 2 tokens refill at 2/s+ expect(limiter.allow('k1')).toBe(true);+ expect(limiter.allow('k1')).toBe(true);+ expect(limiter.allow('k1')).toBe(false);+ });++ it('never refills beyond the burst capacity', () => {+ const limiter = new TokenBucketLimiter(10, 2, now);+ expect(limiter.allow('k1')).toBe(true);+ nowMs += 60_000; // idle long enough to refill hundreds of tokens+ expect(limiter.allow('k1')).toBe(true);+ expect(limiter.allow('k1')).toBe(true);+ expect(limiter.allow('k1')).toBe(false);+ });++ it('meters subjects independently', () => {+ const limiter = new TokenBucketLimiter(1, 1, now);+ expect(limiter.allow('k1')).toBe(true);+ expect(limiter.allow('k1')).toBe(false);+ expect(limiter.allow('k2')).toBe(true);+ });++ it('caps the subject map so a distinct-subject flood cannot grow memory without limit', () => {+ const limiter = new TokenBucketLimiter(1, 1, now, 100);+ for (let i = 0; i < 500; i++) {+ limiter.allow(`flood-${i}`);+ }+ expect((limiter as unknown as { buckets: Map<string, unknown> }).buckets.size).toBeLessThanOrEqual(100);+ });+});++describe('SlidingWindowLimiter (pre-auth per-IP handshake budget)', () => {+ let nowMs: number;+ const now = () => nowMs;+ beforeEach(() => {+ nowMs = 1_000_000;+ });++ it('allows up to max attempts inside the window and rejects the next one', () => {+ const limiter = new SlidingWindowLimiter(3, 60_000, now);+ expect(limiter.allow('203.0.113.5')).toBe(true);+ expect(limiter.allow('203.0.113.5')).toBe(true);+ expect(limiter.allow('203.0.113.5')).toBe(true);+ expect(limiter.allow('203.0.113.5')).toBe(false);+ });++ it('does not count rejected attempts against the window', () => {+ const limiter = new SlidingWindowLimiter(1, 1_000, now);+ expect(limiter.allow('ip')).toBe(true);+ expect(limiter.allow('ip')).toBe(false); // rejected: must not extend the lockout+ nowMs += 1_001;+ expect(limiter.allow('ip')).toBe(true);+ });++ it('recovers once the window slides past the oldest attempt', () => {+ const limiter = new SlidingWindowLimiter(2, 1_000, now);+ expect(limiter.allow('ip')).toBe(true);+ nowMs += 500;+ expect(limiter.allow('ip')).toBe(true);+ expect(limiter.allow('ip')).toBe(false);+ nowMs += 501; // first attempt aged out; second still inside+ expect(limiter.allow('ip')).toBe(true);+ expect(limiter.allow('ip')).toBe(false);+ });++ it('caps the subject map so a spoofed-IP flood cannot grow memory without limit', () => {+ const limiter = new SlidingWindowLimiter(1, 60_000, now, 100);+ for (let i = 0; i < 500; i++) {+ limiter.allow(`10.0.0.${i % 256}.${i}`);+ }+ expect((limiter as unknown as { hits: Map<string, unknown> }).hits.size).toBeLessThanOrEqual(100);+ });+});diff --git a/src/modules/events/ws-rate-limit.ts b/src/modules/events/ws-rate-limit.tsnew file mode 100644index 000000000..1c3f5890f--- /dev/null+++ b/src/modules/events/ws-rate-limit.ts@@ -0,0 +1,146 @@+/**+ * In-process rate limiting for the `/events` Socket.IO gateway.+ *+ * WebSocket frames never pass through the Nest enhancer pipeline, so the global+ * guards/pipes (including the HTTP throttler) do not apply here — the gateway enforces+ * its own limits:+ * 1. per-key token bucket on client frames (subscribe/unsubscribe/ping),+ * 2. pre-auth per-IP sliding window on new handshakes (gates the DB key validation),+ * 3. a cap on simultaneous sockets per API key (enforced in the gateway, which already+ * tracks sockets per key for eviction).+ *+ * Default rationale (legitimate traffic is far below every limit):+ * - Frames: the dashboard sends a small burst of subscribe frames at page mount+ * (~8, one per event group) and afterwards only occasional ping/unsubscribe frames;+ * server→client event volume is irrelevant here (only client→server frames are+ * limited). 60 frames/s sustained is ~6x headroom over the connect burst and a+ * 120-token burst absorbs several dashboard tabs mounting at once, while still+ * bounding a flooding key to a survivable validate/subscribe rate.+ * - Handshakes: Socket.IO auto-reconnect backs off exponentially (~6 attempts/min+ * per tab); 10/min per IP leaves room for a few tabs re-mounting together and stops+ * an unauthenticated handshake flood from hitting the DB validate on every attempt.+ * - Sockets: 16 concurrent sockets per key covers multi-tab dashboards plus SDK+ * clients sharing one key; anything beyond it is almost certainly a leak or abuse.+ *+ * In-memory per-process, like the MCP limiters; move to Redis for multi-instance+ * deployments. Both limiter maps are capped with approximate LRU eviction so a+ * distinct-key (or spoofed-IP) flood cannot grow process memory without limit.+ */++const DEFAULT_FRAME_PER_SECOND = 60;+const DEFAULT_FRAME_BURST = 120;+const DEFAULT_HANDSHAKE_MAX = 10;+const DEFAULT_HANDSHAKE_WINDOW_MS = 60_000;+const DEFAULT_MAX_SOCKETS_PER_KEY = 16;+const DEFAULT_MAX_KEYS = 50_000;++const parsePositiveInt = (raw: string | undefined, fallback: number): number => {+ if (!raw || raw.trim() === '') return fallback;+ const n = Number(raw);+ if (!Number.isFinite(n)) return fallback;+ const i = Math.floor(n);+ return i >= 1 ? i : fallback;+};++export interface WsRateLimitConfig {+ framePerSecond: number;+ frameBurst: number;+ handshakeMax: number;+ handshakeWindowMs: number;+ maxSocketsPerKey: number;+}++/**+ * Read the WebSocket rate-limit configuration from the environment.+ * Falls back to the default for any missing, blank, non-positive, or non-numeric value+ * (same rule as the MCP limiters).+ */+export function readWsRateLimitConfig(env: NodeJS.ProcessEnv = process.env): WsRateLimitConfig {+ return {+ framePerSecond: parsePositiveInt(env['WS_RATE_LIMIT_FRAME_PER_SECOND'], DEFAULT_FRAME_PER_SECOND),+ frameBurst: parsePositiveInt(env['WS_RATE_LIMIT_FRAME_BURST'], DEFAULT_FRAME_BURST),+ handshakeMax: parsePositiveInt(env['WS_RATE_LIMIT_HANDSHAKE_MAX'], DEFAULT_HANDSHAKE_MAX),+ handshakeWindowMs: parsePositiveInt(env['WS_RATE_LIMIT_HANDSHAKE_WINDOW_MS'], DEFAULT_HANDSHAKE_WINDOW_MS),+ maxSocketsPerKey: parsePositiveInt(env['WS_MAX_SOCKETS_PER_KEY'], DEFAULT_MAX_SOCKETS_PER_KEY),+ };+}++/** Evict oldest-inserted keys once `map` exceeds `maxKeys` (approximate LRU when callers re-set on touch). */+function evictOverflow<K, V>(map: Map<K, V>, maxKeys: number): void {+ while (map.size > Math.max(1, maxKeys)) {+ const oldest = map.keys().next().value;+ if (oldest === undefined) break;+ map.delete(oldest);+ }+}++interface Bucket {+ tokens: number;+ lastRefill: number;+}++/**+ * Per-subject token bucket: `capacity` tokens, refilled at `refillPerSecond`. A subject may+ * burst up to the capacity and is then shaped to the sustained rate — no hard rejection of+ * normal connect-time bursts, no unbounded throughput for a flooding key.+ */+export class TokenBucketLimiter {+ private readonly buckets = new Map<string, Bucket>();++ constructor(+ private readonly refillPerSecond = DEFAULT_FRAME_PER_SECOND,+ private readonly capacity = DEFAULT_FRAME_BURST,+ private readonly now: () => number = () => Date.now(),+ private readonly maxKeys = DEFAULT_MAX_KEYS,+ ) {}++ /** Consume one token for `subject`; returns false (without consuming) when the bucket is empty. */+ allow(subject: string): boolean {+ const t = this.now();+ let bucket = this.buckets.get(subject);+ if (!bucket) {+ bucket = { tokens: this.capacity, lastRefill: t };+ } else if (t > bucket.lastRefill) {+ bucket.tokens = Math.min(this.capacity, bucket.tokens + ((t - bucket.lastRefill) * this.refillPerSecond) / 1000);+ bucket.lastRefill = t;+ }+ const allowed = bucket.tokens >= 1;+ if (allowed) bucket.tokens -= 1;++ // Touch on every check so an active abuser cannot drift to the LRU head, be evicted,+ // and receive a fresh bucket during a distinct-subject flood.+ this.buckets.delete(subject);+ this.buckets.set(subject, bucket);+ evictOverflow(this.buckets, this.maxKeys);+ return allowed;+ }+}++/**+ * Per-subject sliding-window counter (fixed `max` events per `windowMs`). Same shape as the+ * MCP KeyRateLimiter but returns a boolean instead of throwing an HttpException, since the+ * WS surface answers with an error frame, not an HTTP status.+ */+export class SlidingWindowLimiter {+ private readonly hits = new Map<string, number[]>();++ constructor(+ private readonly max = DEFAULT_HANDSHAKE_MAX,+ private readonly windowMs = DEFAULT_HANDSHAKE_WINDOW_MS,+ private readonly now: () => number = () => Date.now(),+ private readonly maxKeys = DEFAULT_MAX_KEYS,+ ) {}++ /** Record one attempt for `subject`; returns false when it exceeds `max` inside the window. */+ allow(subject: string): boolean {+ const t = this.now();+ const recent = (this.hits.get(subject) ?? []).filter(ts => t - ts < this.windowMs);+ const allowed = recent.length < this.max;+ if (allowed) recent.push(t);++ this.hits.delete(subject);+ this.hits.set(subject, recent);+ evictOverflow(this.hits, this.maxKeys);+ return allowed;+ }+}