Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
refactor(mcp): reuse the sliding window limiter
Yudhi Armyndharisb83450a5218b
diff --git a/src/modules/events/ws-rate-limit.ts b/src/modules/events/ws-rate-limit.tsindex 425dd0811..3a3adcc2e 100644--- a/src/modules/events/ws-rate-limit.ts+++ b/src/modules/events/ws-rate-limit.ts@@ -111,9 +111,9 @@ export class TokenBucketLimiter {}/**- * 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.+ * Per-subject sliding-window counter (fixed `max` events per `windowMs`). Returns a boolean rather+ * than throwing, since the WS surface answers with an error frame, not an HTTP status; the MCP+ * KeyRateLimiter wraps it for the HTTP side.*/export class SlidingWindowLimiter {private readonly hits = new Map<string, number[]>();diff --git a/src/modules/mcp/mcp-rate-limit.spec.ts b/src/modules/mcp/mcp-rate-limit.spec.tsindex 284a65231..e791e0ada 100644--- a/src/modules/mcp/mcp-rate-limit.spec.ts+++ b/src/modules/mcp/mcp-rate-limit.spec.ts@@ -89,6 +89,24 @@ describe('readIpRateLimitConfig', () => {});});+describe('rate limit config from the process environment', () => {+ const keys = ['MCP_RATE_LIMIT_MAX', 'MCP_IP_RATE_LIMIT_MAX'] as const;+ const saved = Object.fromEntries(keys.map(key => [key, process.env[key]]));+ afterEach(() => {+ for (const key of keys) {+ if (saved[key] === undefined) delete process.env[key];+ else process.env[key] = saved[key];+ }+ });++ it('reads process.env when called without an environment', () => {+ process.env.MCP_RATE_LIMIT_MAX = '7';+ process.env.MCP_IP_RATE_LIMIT_MAX = '9';+ expect(readRateLimitConfig().max).toBe(7);+ expect(readIpRateLimitConfig().max).toBe(9);+ });+});+describe('KeyRateLimiter', () => {it('allows up to max per window, then throws 429', () => {let now = 1_000;@@ -99,6 +117,14 @@ describe('KeyRateLimiter', () => {now = 2_500; // window passedexpect(() => rl.check('k')).not.toThrow();});++ it('defaults to 60 calls per key per minute on the real clock', () => {+ const rl = new KeyRateLimiter();+ for (let i = 0; i < 60; i++) rl.check('k');+ expect(() => rl.check('k')).toThrow(/rate limit/i);+ expect(() => rl.check('other')).not.toThrow();+ });+it('buckets per key', () => {const rl = new KeyRateLimiter(1, 1000, () => 0);rl.check('a');@@ -137,7 +163,7 @@ describe('KeyRateLimiter', () => {// The underlying hits Map should hold exactly 1 entry per key (only the fresh hit),// confirming expired entries are deleted rather than accumulating.// Access the private field via casting to verify the Map state.- const map = (rl as unknown as { hits: Map<string, number[]> }).hits;+ const map = (rl as unknown as { window: { hits: Map<string, number[]> } }).window.hits;expect(map.size).toBe(1000);@@ -155,7 +181,7 @@ describe('KeyRateLimiter', () => {rl.check('a'); // touch a; b is now least recently usedrl.check('d');- const map = (rl as unknown as { hits: Map<string, number[]> }).hits;+ const map = (rl as unknown as { window: { hits: Map<string, number[]> } }).window.hits;expect([...map.keys()]).toEqual(['c', 'a', 'd']);});diff --git a/src/modules/mcp/mcp-rate-limit.ts b/src/modules/mcp/mcp-rate-limit.tsindex 4ad327846..8e108ea08 100644--- a/src/modules/mcp/mcp-rate-limit.ts+++ b/src/modules/mcp/mcp-rate-limit.ts@@ -1,5 +1,6 @@import { HttpException, HttpStatus } from '@nestjs/common';import { positiveIntOrDefault } from '../../common/utils/env-int';+import { SlidingWindowLimiter } from '../events/ws-rate-limit';const DEFAULT_MAX = 60;const DEFAULT_WINDOW_MS = 60_000;@@ -38,31 +39,14 @@ export function readIpRateLimitConfig(env: NodeJS.ProcessEnv = process.env): { m* approximate LRU eviction so a distinct-key flood cannot grow process memory without limit.*/export class KeyRateLimiter {- private readonly hits = new Map<string, number[]>();- constructor(- private readonly max = 60,- private readonly windowMs = 60_000,- private readonly now: () => number = () => Date.now(),- private readonly maxKeys = DEFAULT_MAX_KEYS,- ) {}+ private readonly window: SlidingWindowLimiter;- check(key: string): void {- const t = this.now();- const recent = (this.hits.get(key) ?? []).filter(ts => t - ts < this.windowMs);- const throttled = recent.length >= this.max;- if (!throttled) recent.push(t);-- // Touch on every check, including throttled checks, so an active abuser cannot drift to the LRU- // head, be evicted, and receive a fresh budget during a distinct-key flood.- this.hits.delete(key);- this.hits.set(key, recent);- while (this.hits.size > Math.max(1, this.maxKeys)) {- const oldest = this.hits.keys().next().value;- if (oldest === undefined) break;- this.hits.delete(oldest);- }+ constructor(max = 60, windowMs = 60_000, now: () => number = () => Date.now(), maxKeys = DEFAULT_MAX_KEYS) {+ this.window = new SlidingWindowLimiter(max, windowMs, now, maxKeys);+ }- if (throttled) {+ check(key: string): void {+ if (!this.window.allow(key)) {throw new HttpException('MCP rate limit exceeded', HttpStatus.TOO_MANY_REQUESTS);}}