Skip to content

Commit

Permalink
fix(csp): forward req original headers in middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
lsagetlethias committed Oct 5, 2023
1 parent c7407fa commit b8e805b
Showing 1 changed file with 12 additions and 7 deletions.
19 changes: 12 additions & 7 deletions packages/app/src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { StatusCodes } from "http-status-codes";
import { NextResponse } from "next/server";
import { type NextMiddlewareWithAuth, withAuth } from "next-auth/middleware";

const cspMiddleware = () => {
const cspMiddleware: NextMiddlewareWithAuth = req => {
const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
const cspHeader = `
default-src 'self' https://*.gouv.fr;
Expand All @@ -23,23 +23,28 @@ const cspMiddleware = () => {
require-trusted-types-for 'script';
trusted-types react-dsfr react-dsfr-asap nextjs#bundler matomo-next;`;

const requestHeaders = new Headers();
requestHeaders.set("x-nonce", nonce);
requestHeaders.set(
const responseHeaders = new Headers();
responseHeaders.set("x-nonce", nonce);
responseHeaders.set(
"Content-Security-Policy",
// Replace newline characters and spaces
cspHeader.replace(/\s{2,}/g, " ").trim(),
);

const requestHeaders = new Headers(req.headers);
responseHeaders.forEach((value, key) => {
requestHeaders.set(key, value);
});

return NextResponse.next({
headers: requestHeaders,
headers: responseHeaders,
request: {
headers: requestHeaders,
},
});
};

const nextMiddleware: NextMiddlewareWithAuth = async req => {
const nextMiddleware: NextMiddlewareWithAuth = async (req, event) => {
const { pathname, href } = req.nextUrl;

// handling authorization by ourselves (and not with authorize callback)
Expand All @@ -55,7 +60,7 @@ const nextMiddleware: NextMiddlewareWithAuth = async req => {
return new NextResponse(null, { status: StatusCodes.FORBIDDEN });
}

return process.env.NODE_ENV === "development" ? NextResponse.next() : cspMiddleware();
return process.env.NODE_ENV === "development" ? NextResponse.next() : cspMiddleware(req, event);
};

// export const middleware = nextMiddleware;
Expand Down

0 comments on commit b8e805b

Please sign in to comment.