- Replace every em-dash in src and server/src with a colon, comma or hyphen - Give every relative import its file extension (.jsx imports of .tsx fixed) - Delete old-historyMock.ts, unused exports, unused CSS utilities, the unused @ alias and the fallback option nothing passed - One copy each of initials, capitalize, byName and the server's marks() - Move the organization, chapter and event hooks from src/data to src/lib - Schema sync always throws on a mismatch (strict was never turned off) - Replace the placeholder README Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
50 lines
1.7 KiB
JavaScript
50 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 clientIp() in auth.js (the entry nginx
|
|
adds to X-Forwarded-For). That is only trustworthy because
|
|
nothing but nginx can reach this port, it binds to 127.0.0.1. Don't expose the port.
|
|
═══════════════════════════════════════════════════════════════ */
|
|
|
|
import { clientIp } from "./auth.js";
|
|
|
|
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 = clientIp(c) ?? "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();
|
|
};
|
|
}
|