Files
EpicNext-Cms/src/proxy.ts
T
openhands 7697728d07
Gitea Actions Runner Test / test-job (push) Successful in 0s
CI / check (push) Successful in 28s
CI / tests-unit (push) Successful in 1m39s
CI / tests-integration (push) Successful in 1m41s
CI / tests-ui (push) Successful in 2m27s
CI / preflight (push) Skipped
CI / deploy (push) Successful in 3m35s
feat(cache): single-owner caching across nginx, edge and content edits
Rebuild production nginx from the repo (deployment/proxy/*) with a single
Cache-Control owner per route: the app stays the source, nginx only manages
headers, and Cloudflare stores the public API allowlist at the edge.

- deployment/proxy: nginx.conf, mime.types, nginx-cms.conf and the
  blue/green upstream snippet; config backed by scripts/nginx-sync.sh
  (idempotent install + reload, --check/--force).
- nginx serves Cache-Tag headers on the public allowlist (cms-public),
  gamedata, client and camera responses so the edge and purge stay in sync.
- src/lib/edge-cache.ts + tests: coalesced, fire-and-forget edge purges that
  no-op unless Cloudflare is configured; scripts/cf-purge.sh and
  cf-setup-cache.sh create and purge the cache rule.
- src/lib/cloudflare-api.ts: purgeCacheByTags/purgeCacheByUrls.
- Purge hooks after catalog exports (public + gamedata) and on shop, team,
  guild, photo and rare-values edits; ci-deploy purges after each release.
- src/proxy.ts excludes the imaging/images docs from the middleware matcher.
2026-09-28 21:55:18 +02:00

84 lines
2.7 KiB
TypeScript

import { NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";
import { env } from "@/env";
import { buildContentSecurityPolicy, createCspNonce } from "@/lib/csp";
import { ddosReject, enforceDdosRateLimit } from "@/lib/ddos-guard";
import {
isCacheableAssetPath,
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.outcome === "suspect") {
return ddosReject(403);
}
if (decision.outcome === "block") {
return ddosReject(429, 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.
// Rendered avatars and uploaded media are immutable per key and already
// carry their own long-lived Cache-Control, so they keep it here.
if (!isCacheableAssetPath(pathname)) {
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|images).*)",
],
};