NGU-Web/server/src/rateLimit.js
Zaldimmar b165e612c2 Harden sign-in: __Host- session cookie and a per-email login lock
- The session cookie is __Host-ngu_session when Secure (production),
  so a sibling subdomain can't set or overwrite it; plain ngu_session
  over local http. Every admin signs in again once after deploying.
- Five wrong passwords for one email lock that email for 15 minutes,
  from any address; a correct password clears it. On top of the
  per-IP limit.
- CLAUDE.md: noImplicitAny stays off on purpose.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 02:11:57 -05:00

92 lines
3.3 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();
};
}
/* ── Failures per key ──────────────────────────────────────────
For login: count only failed attempts per account, so guessing
one person's password from many addresses still stops, and their
own successful sign-in clears it. Unknown emails are counted the
same way, so the limit says nothing about which accounts exist.
ponytail: in-memory like the IP limit (resets on restart, one
instance); a spray of random emails is swept each window.
───────────────────────────────────────────────────────────── */
export function failureLimit({ windowMs = 15 * 60_000, max = 5 } = {}) {
const failures = new Map(); // key → { count, resetAt }
setInterval(() => {
const now = Date.now();
for (const [key, entry] of failures) {
if (entry.resetAt <= now) failures.delete(key);
}
}, windowMs).unref();
const live = (key) => {
const entry = failures.get(key);
if (entry && entry.resetAt <= Date.now()) failures.delete(key);
return failures.get(key);
};
return {
/** Seconds until the key may try again, or 0. */
blockedFor(key) {
const entry = live(key);
return entry && entry.count >= max ? Math.ceil((entry.resetAt - Date.now()) / 1000) : 0;
},
fail(key) {
const entry = live(key) ?? { count: 0, resetAt: Date.now() + windowMs };
entry.count += 1;
failures.set(key, entry);
},
clear(key) {
failures.delete(key);
},
};
}