Security hardening: 12 improvements across the stack

1. env.ts: APP_KEY placeholder detection with validation
2. schema.prisma: password column widened to varchar(255) for argon2id
3. auth.ts: trustHost restricted to development only
4. next.config.ts: added CSP, HSTS, X-Frame-Options, and other security headers
5. api.ts: CORS restricted to APP_URL instead of wildcard
6. register-form.tsx: migrated from REST API fetch to server action (useActionState)
7. twofactor.ts + 2fa page: TOTP recovery codes (8 one-time codes, generated and displayed)
8. register.ts: password min length 8 + complexity requirements (upper, lower, digit)
9. register.ts + help-tickets.ts + radio-shouts.ts: Zod schema validation
10. rate-limit.ts: improved periodic cleanup with aggressive eviction at 10k buckets
11. guard.ts + admin actions: rate-limited admin actions (30 req/min per staff)
12. help-tickets.ts + radio-shouts.ts: content moderation via moderateOrThrow
This commit is contained in:
openhands committed 2026-07-04 18:52:00 +02:00
1 parent a1950e5b65
commit 5628e7d6b7
19 files changed
+370 -220

No files matched your search

+25 -5
View File
@@ -5,6 +5,8 @@ import { headers } from "next/headers";
* (register, password reset, login). It's per-node (not shared across
* instances) — fine for a single-server retro hotel; swap for Redis if you
* ever scale out. Keys are typically `${action}:${ip}`.
*
* Periodic cleanup runs every 5 minutes to keep the map bounded.
*/
type Bucket = { count: number; resetAt: number };
const buckets = new Map<string, Bucket>();
@@ -15,13 +17,31 @@ export interface RateLimitResult {
retryAfter: number;
}
let lastCleanup = Date.now();
const CLEANUP_INTERVAL_MS = 300_000; // 5 min
const MAX_BUCKETS = 10_000;
function cleanup(): void {
const now = Date.now();
if (now - lastCleanup < CLEANUP_INTERVAL_MS) return;
lastCleanup = now;
if (buckets.size <= MAX_BUCKETS) {
// Quick eviction of completely expired entries
for (const [k, b] of buckets) if (now >= b.resetAt) buckets.delete(k);
} else {
// Aggressive: clear all expired, then delete oldest 20% if still too large
for (const [k, b] of buckets) if (now >= b.resetAt) buckets.delete(k);
if (buckets.size > MAX_BUCKETS) {
const sorted = [...buckets.entries()].sort((a, b) => a[1].resetAt - b[1].resetAt);
const toRemove = Math.floor(sorted.length * 0.2);
for (let i = 0; i < toRemove; i++) buckets.delete(sorted[i][0]);
}
}
}
export function rateLimit(key: string, limit: number, windowMs: number): RateLimitResult {
const now = Date.now();
// Opportunistic cleanup so the map can't grow without bound.
if (buckets.size > 5000) {
for (const [k, b] of buckets) if (now >= b.resetAt) buckets.delete(k);
}
cleanup();
const bucket = buckets.get(key);
if (!bucket || now >= bucket.resetAt) {