Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 | 23x 23x 23x 23x 23x 23x 58x 10x 10x 23x 10x 6x 6x 18x 27x 27x 7x 20x 20x 1x 19x 24x 24x 24x 11x 11x 24x 24x 21x 24x 24x 24x 24x 23x 58x 58x 28x 1x 1x 27x 27x 8x 2x 2x 6x 6x 6x 6x 6x 6x 2x 2x 6x 1x 1x 1x 1x 1x 1x 5x 5x 19x 1x 1x 18x 18x 18x 18x 18x 18x 3x 3x 18x 2x 2x 2x 2x 2x 2x 2x 16x 23x 11x 2x | /**
* Rate Limiting Middleware
*
* Protects the MCP server from excessive anonymous requests.
* Authenticated users are NOT rate limited to avoid impacting legitimate usage.
*
* Design principles:
* - Per-IP rate limiting for anonymous requests (enabled by default)
* - Authenticated users skip rate limiting (they've proven who they are)
* - Standard rate limit headers (X-RateLimit-*)
*/
import { Request, Response, NextFunction, RequestHandler } from "express";
import {
RATE_LIMIT_IP_ENABLED,
RATE_LIMIT_IP_WINDOW_MS,
RATE_LIMIT_IP_MAX_REQUESTS,
RATE_LIMIT_SESSION_ENABLED,
RATE_LIMIT_SESSION_WINDOW_MS,
RATE_LIMIT_SESSION_MAX_REQUESTS,
} from "../config";
import { logDebug, logWarn } from "../logger";
import { getMinimalRequestContext, buildRateLimitInfo, truncateId } from "../utils/request-logger";
interface RateLimitEntry {
count: number;
resetAt: number;
}
// In-memory storage for rate limit tracking
const rateLimitStore = new Map<string, RateLimitEntry>();
// Cleanup interval (run every minute)
const CLEANUP_INTERVAL_MS = 60000;
let cleanupInterval: ReturnType<typeof setInterval> | null = null;
/**
* Start the cleanup interval for expired entries
*/
function startCleanup(): void {
if (cleanupInterval) return;
cleanupInterval = setInterval(() => {
const now = Date.now();
let cleaned = 0;
for (const [key, entry] of rateLimitStore.entries()) {
if (entry.resetAt <= now) {
rateLimitStore.delete(key);
cleaned++;
}
}
if (cleaned > 0) {
logDebug("Rate limiter cleanup: removed expired entries", { cleaned });
}
}, CLEANUP_INTERVAL_MS);
// Don't prevent process exit
cleanupInterval.unref();
}
/**
* Stop the cleanup interval
*/
export function stopCleanup(): void {
if (cleanupInterval) {
clearInterval(cleanupInterval);
cleanupInterval = null;
}
}
/**
* Get the IP address from a request
*/
function getIpAddress(req: Request): string {
return req.ip ?? req.socket.remoteAddress ?? "unknown";
}
/**
* Check if request is authenticated (has valid session)
*/
function isAuthenticated(req: Request, res: Response): boolean {
// Check for OAuth session ID set by auth middleware
const oauthSessionId = res.locals.oauthSessionId as string | undefined;
if (oauthSessionId) {
return true;
}
// Check for MCP session ID header (indicates active session)
const mcpSessionId = req.headers["mcp-session-id"] as string | undefined;
if (mcpSessionId) {
return true;
}
return false;
}
/**
* Check and update rate limit for a key
*/
function checkRateLimit(
key: string,
windowMs: number,
maxRequests: number
): {
allowed: boolean;
remaining: number;
resetAt: number;
total: number;
used: number;
} {
const now = Date.now();
let entry = rateLimitStore.get(key);
// Create or reset entry if expired
if (!entry || entry.resetAt <= now) {
entry = {
count: 0,
resetAt: now + windowMs,
};
rateLimitStore.set(key, entry);
}
// Check if limit exceeded
const allowed = entry.count < maxRequests;
// Increment count if allowed
if (allowed) {
entry.count++;
}
return {
allowed,
remaining: Math.max(0, maxRequests - entry.count),
resetAt: entry.resetAt,
total: maxRequests,
used: entry.count,
};
}
/**
* Set rate limit headers on response
*/
function setRateLimitHeaders(
res: Response,
info: { remaining: number; resetAt: number; total: number }
): void {
res.set("X-RateLimit-Limit", info.total.toString());
res.set("X-RateLimit-Remaining", info.remaining.toString());
res.set("X-RateLimit-Reset", Math.ceil(info.resetAt / 1000).toString());
}
/**
* Express middleware for rate limiting
*
* Behavior:
* - Authenticated requests: NOT rate limited (trusted users)
* - Anonymous requests: Rate limited by IP address
*
* When rate limit is exceeded, returns HTTP 429 with:
* - Retry-After header
* - JSON error body with details
* - Standard rate limit headers
*/
export function rateLimiterMiddleware(): RequestHandler {
// Start cleanup on first use
startCleanup();
return (req: Request, res: Response, next: NextFunction): void => {
// Skip health check endpoint (monitoring should always work)
if (req.path === "/health") {
next();
return;
}
// Check if user is authenticated
const authenticated = isAuthenticated(req, res);
// Authenticated users skip rate limiting by default
// (they've proven who they are and shouldn't suffer security measures)
if (authenticated) {
// Only apply session rate limit if explicitly enabled
if (!RATE_LIMIT_SESSION_ENABLED) {
next();
return;
}
// Apply per-session rate limiting (optional)
const sessionId =
(res.locals.oauthSessionId as string) || (req.headers["mcp-session-id"] as string);
const key = `session:${sessionId}`;
const info = checkRateLimit(
key,
RATE_LIMIT_SESSION_WINDOW_MS,
RATE_LIMIT_SESSION_MAX_REQUESTS
);
setRateLimitHeaders(res, info);
// Log warning when approaching limit (>80%)
const usagePercent = (info.used / info.total) * 100;
if (info.allowed && usagePercent >= 80) {
const rateLimitInfo = buildRateLimitInfo(
"session",
sessionId,
info.used,
info.total,
info.resetAt
);
logDebug("Approaching session rate limit threshold", {
event: "rate_limit_warning",
...getMinimalRequestContext(req),
rateLimit: rateLimitInfo,
});
}
if (!info.allowed) {
const retryAfter = Math.ceil((info.resetAt - Date.now()) / 1000);
const rateLimitInfo = buildRateLimitInfo(
"session",
sessionId,
info.used,
info.total,
info.resetAt
);
logWarn("Session rate limit exceeded", {
event: "rate_limit_exceeded",
...getMinimalRequestContext(req),
rateLimit: rateLimitInfo,
hasOAuthSession: !!res.locals.oauthSessionId,
hasMcpSessionHeader: !!req.headers["mcp-session-id"],
});
res.set("Retry-After", retryAfter.toString());
res.status(429).json({
error: "Too Many Requests",
message: "Session rate limit exceeded. Please slow down your requests.",
retryAfter,
limit: info.total,
remaining: info.remaining,
resetAt: new Date(info.resetAt).toISOString(),
});
return;
}
next();
return;
}
// Anonymous request - apply IP-based rate limiting
if (!RATE_LIMIT_IP_ENABLED) {
next();
return;
}
const ip = getIpAddress(req);
const key = `ip:${ip}`;
const info = checkRateLimit(key, RATE_LIMIT_IP_WINDOW_MS, RATE_LIMIT_IP_MAX_REQUESTS);
setRateLimitHeaders(res, info);
// Log warning when approaching limit (>80%)
const usagePercent = (info.used / info.total) * 100;
if (info.allowed && usagePercent >= 80) {
const rateLimitInfo = buildRateLimitInfo("ip", ip, info.used, info.total, info.resetAt);
logDebug("Approaching IP rate limit threshold", {
event: "rate_limit_warning",
...getMinimalRequestContext(req),
rateLimit: rateLimitInfo,
authClassification: "anonymous",
authReason: "no OAuth session and no MCP-Session-Id header",
});
}
if (!info.allowed) {
const retryAfter = Math.ceil((info.resetAt - Date.now()) / 1000);
const rateLimitInfo = buildRateLimitInfo("ip", ip, info.used, info.total, info.resetAt);
// Get MCP session header if present (helps debug why request was classified as anonymous)
const mcpSessionHeader = req.headers["mcp-session-id"] as string | undefined;
logWarn("IP rate limit exceeded", {
event: "rate_limit_exceeded",
...getMinimalRequestContext(req),
rateLimit: rateLimitInfo,
authClassification: "anonymous",
authReason: "no OAuth session and no MCP-Session-Id header",
mcpSessionId: truncateId(mcpSessionHeader),
});
res.set("Retry-After", retryAfter.toString());
res.status(429).json({
error: "Too Many Requests",
message: "Rate limit exceeded. Please authenticate or slow down your requests.",
retryAfter,
limit: info.total,
remaining: info.remaining,
resetAt: new Date(info.resetAt).toISOString(),
});
return;
}
next();
};
}
/**
* Get current rate limit stats (for debugging/monitoring)
*/
export function getRateLimitStats(): {
totalEntries: number;
entries: Array<{ key: string; count: number; resetAt: Date }>;
} {
const entries = Array.from(rateLimitStore.entries()).map(([key, entry]) => ({
key,
count: entry.count,
resetAt: new Date(entry.resetAt),
}));
return {
totalEntries: rateLimitStore.size,
entries,
};
}
|