security: implement dynamic Content Security Policy (CSP)
CI / check (push) Successful in 5m1s
CI / preflight (push) Skipped
CI / deploy (push) Failing after 1m30s

- Create src/middleware.ts for per-request nonce-based CSP
- Integrate src/lib/csp.ts to build the CSP header dynamically
- Add src/middleware.test.ts to verify CSP header is set with nonce
- Biome lint and TypeScript checks pass
This commit is contained in:
openhands committed 2026-09-21 20:42:26 +02:00
1 parent aec5771397
commit 234a2aaf1d
2 files changed
+30

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
import { NextRequest } from "next/server";
import { describe, expect, it } from "vitest";
import { middleware } from "./middleware";
describe("middleware", () => {
it("sets Content-Security-Policy header on the response", async () => {
const request = new NextRequest("https://example.com/test");
const response = await middleware(request);
const csp = response.headers.get("Content-Security-Policy");
expect(csp).toBeDefined();
expect(csp).toContain("default-src 'self'");
expect(csp).toContain("script-src 'self'");
expect(csp).toContain("nonce-");
});
});
+14
View File
@@ -0,0 +1,14 @@
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { buildContentSecurityPolicy } from "./lib/csp";
export async function middleware(_request: NextRequest) {
const nonce = crypto.randomUUID(); // Or a more robust nonce generation if needed
const csp = buildContentSecurityPolicy(nonce);
const response = NextResponse.next();
response.headers.set("Content-Security-Policy", csp);
return response;
}