feat(security): add Redis-backed app-layer anti-DDoS rate limiting to proxy
Gitea Actions Runner Test / test-job (push) Successful in 1s
CI / check (push) Successful in 31s
CI / tests-integration (push) Successful in 1m42s
CI / tests-unit (push) Successful in 1m47s
CI / tests-ui (push) Successful in 2m40s
CI / preflight (push) Skipped
CI / deploy (push) Successful in 2m3s

This commit is contained in:
openhands committed 2026-09-22 21:48:40 +02:00
1 parent d8f2a21011
commit 98a184953a
5 files changed
+184 -8

No files matched your search

+117
View File
@@ -0,0 +1,117 @@
import "server-only";
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { env } from "@/env";
import { resolveClientIp } from "@/lib/client-ip";
import { classifyDdos, type DdosCategory } from "@/lib/ddos";
import { rateLimit } from "@/lib/rate-limit";
import { redis } from "@/lib/redis";
export interface DdosDecision {
limited: boolean;
retryAfterSeconds: number;
}
export interface DdosLimitRule {
limit: number;
windowSeconds: number;
}
const DEFAULT_LIMITS: Record<DdosCategory, DdosLimitRule> = {
// Anonymous HTML is cached at the nginx layer for 60s, so Node only pays
// for cache misses and authenticated traffic here.
pages: { limit: 300, windowSeconds: 60 },
// Game clients poll a handful of endpoints; generous burst headroom that
// still cuts off single-IP floods.
api: { limit: 600, windowSeconds: 60 },
// Login, register and admin — the valuable brute-force surface.
auth: { limit: 20, windowSeconds: 60 },
};
// Global safety valve: sheds aggregate load even when a DDoS spreads over
// many IPs, keeping the process and database alive with 429s instead of
// letting every connection through until the DB melts.
const GLOBAL_LIMIT: DdosLimitRule = { limit: 18_000, windowSeconds: 60 };
const VIOLATION_WINDOW_SECONDS = 600;
const MAX_VIOLATIONS = 10;
const BLOCK_TTL_SECONDS = 600;
function isEnabled(): boolean {
if (env.NODE_ENV !== "production") return false;
return env.ANTI_DDOS_ENABLED;
}
/**
* App-layer anti-DDoS gate for the Next.js proxy. Reuses the app-wide
* Redis/in-memory rate-limit buckets (so multi-instance deployments share
* state) and the audited IP resolver. Fails open: if Redis is down, buckets
* degrade to bounded in-process counters and the block-list is skipped.
*/
export async function enforceDdosRateLimit(
req: NextRequest,
): Promise<DdosDecision> {
if (!isEnabled()) return { limited: false, retryAfterSeconds: 0 };
const ip = resolveClientIp(req.headers);
const blockKey = `antiddos:block:${ip}`;
if (redis) {
try {
if ((await redis.get(blockKey)) !== null) {
return { limited: true, retryAfterSeconds: BLOCK_TTL_SECONDS };
}
} catch {
// fail-open: never let the limiter itself take the site down.
}
}
const global = await rateLimit(
"antiddos:global:all",
GLOBAL_LIMIT.limit,
GLOBAL_LIMIT.windowSeconds * 1000,
);
if (!global.ok) {
return {
limited: true,
retryAfterSeconds: Math.max(global.retryAfter, 1),
};
}
const category = classifyDdos(req.nextUrl.pathname);
const rule = DEFAULT_LIMITS[category];
const bucket = await rateLimit(
`antiddos:${category}:${ip}`,
rule.limit,
rule.windowSeconds * 1000,
);
if (bucket.ok) return { limited: false, retryAfterSeconds: 0 };
const violations = await rateLimit(
`antiddos:v:${ip}`,
MAX_VIOLATIONS,
VIOLATION_WINDOW_SECONDS * 1000,
);
if (!violations.ok && redis) {
try {
await redis.set(blockKey, "1", "EX", BLOCK_TTL_SECONDS);
} catch {
// fail-open — Redis merely unavailable.
}
}
return {
limited: true,
retryAfterSeconds: Math.max(bucket.retryAfter, 1),
};
}
export function ddosRejected(retryAfterSeconds: number): NextResponse {
return new NextResponse(null, {
status: 429,
headers: {
"Retry-After": String(retryAfterSeconds),
"X-Rate-Limit": "1",
"Cache-Control": "no-store",
},
});
}