NGU-Web/server/src/rateLimit.js

49 lines
1.7 KiB
JavaScript

/* ═══════════════════════════════════════════════════════════════
RATE LIMIT
A fixed window counter held in process memory. It resets when
the service restarts and it doesn't survive a second instance,
both of which are fine for one systemd unit on one box.
The client IP comes from X-Forwarded-For, which nginx sets. That
header is only trustworthy because nothing but nginx can reach
this port — it binds to 127.0.0.1. Don't expose the port.
═══════════════════════════════════════════════════════════════ */
export function rateLimit({ windowMs = 60_000, max = 10 } = {}) {
const hits = new Map(); // ip → { count, resetAt }
// Drop expired entries occasionally so the map can't grow forever.
setInterval(() => {
const now = Date.now();
for (const [ip, entry] of hits) {
if (entry.resetAt <= now) hits.delete(ip);
}
}, windowMs).unref();
return async (c, next) => {
const ip =
c.req.header("x-forwarded-for")?.split(",")[0].trim() ?? "unknown";
const now = Date.now();
let entry = hits.get(ip);
if (!entry || entry.resetAt <= now) {
entry = { count: 0, resetAt: now + windowMs };
hits.set(ip, entry);
}
entry.count += 1;
if (entry.count > max) {
const retryAfter = Math.ceil((entry.resetAt - now) / 1000);
return c.json(
{ error: "Too many requests. Try again shortly." },
429,
{ "Retry-After": String(retryAfter) },
);
}
await next();
};
}