Files
EpicNext-Cms/src/proxy.ts
T
openhands 98a184953a
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
feat(security): add Redis-backed app-layer anti-DDoS rate limiting to proxy
2026-09-22 21:48:40 +02:00

74 lines
2.4 KiB
TypeScript

import { NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";
import { env } from "@/env";
import { buildContentSecurityPolicy, createCspNonce } from "@/lib/csp";
import { ddosRejected, enforceDdosRateLimit } from "@/lib/ddos-guard";
import { shouldRedirectAdminRequest } from "@/lib/proxy-access";
const SECURITY_HEADERS: Record<string, string> = {
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"X-XSS-Protection": "0",
"Referrer-Policy": "strict-origin-when-cross-origin",
"Permissions-Policy": "camera=(), microphone=(), geolocation=()",
"Strict-Transport-Security": "max-age=63072000; includeSubDomains; preload",
};
export const proxy = async (req: import("next/server").NextRequest) => {
const decision = await enforceDdosRateLimit(req);
if (decision.limited) {
return ddosRejected(decision.retryAfterSeconds);
}
const pathname = req.nextUrl.pathname;
// Only /admin needs a real session token for the redirect guard; skipping
// JWT decoding on every other request keeps the proxy cheap under load.
const adminPath = pathname === "/admin" || pathname.startsWith("/admin/");
const token = adminPath
? await getToken({
req,
secret: env.AUTH_SECRET,
secureCookie: true,
})
: null;
if (shouldRedirectAdminRequest(pathname, token)) {
return NextResponse.redirect(new URL("/login", req.url));
}
const nonce = createCspNonce();
const csp = buildContentSecurityPolicy(nonce);
const headers = new Headers(req.headers);
headers.set("x-pathname", pathname);
headers.set("x-nonce", nonce);
// A client may supply this legacy derived header; no consumer should trust it.
headers.delete("x-real-client-ip");
const response = NextResponse.next({ request: { headers } });
// HTML is never cached (browser/CDN/edge) so that after a deploy the page
// always references the current build's chunks. Static assets are
// content-hashed + immutable and can be cached aggressively; a stale HTML
// document would reference chunk URLs that no longer exist after a rebuild.
response.headers.set(
"Cache-Control",
"private, no-cache, no-store, max-age=0, must-revalidate",
);
for (const [key, value] of Object.entries(SECURITY_HEADERS)) {
response.headers.set(key, value);
}
response.headers.set("Content-Security-Policy", csp);
return response;
};
export const config = {
matcher: [
"/((?!_next/static|_next/image|assets|favicon.ico|swf|nitro-assets|imaging).*)",
],
};