v1.3 - added an sqlite db and built data structure
This commit is contained in:
parent
b0fba52c0e
commit
5efdafbb97
37 changed files with 6414 additions and 1988 deletions
49
server/src/rateLimit.js
Normal file
49
server/src/rateLimit.js
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
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();
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue