Skip to content

Commit

Permalink
refactor(docs): improve csp
Browse files Browse the repository at this point in the history
  • Loading branch information
branko-stripe committed Oct 30, 2024
1 parent 23defb5 commit 4f19e09
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 49 deletions.
2 changes: 0 additions & 2 deletions apps/docs/src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ import { Sidebar } from "@/components/Sidebar";

import "@/styles/globals.css";

import Script from "next/script";

import Fathom from "@/components/Fathom";
import { Header } from "@/components/header/header";

Expand Down
112 changes: 66 additions & 46 deletions apps/docs/src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,59 +1,79 @@
import { NextResponse, type NextRequest } from "next/server";

// file: middleware.ts
export function middleware(request: NextRequest) {
const requestHeaders = new Headers(request.headers);
const response = initResponse();
const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
const reportUri =
"https://o4505075539902464.ingest.us.sentry.io/api/4505075559825408/security/?sentry_key=e137a5ec37cf03e1ed168b772c98c0bc";

const cspHeader = `
default-src 'self';
script-src 'self' 'nonce-${nonce}' 'strict-dynamic';
style-src 'self' 'nonce-${nonce}';
img-src 'self' blob: data:;
font-src 'self';
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'none';
upgrade-insecure-requests;
`;

// Replace newline characters and spaces
const contentSecurityPolicyHeaderValue = cspHeader.replace(/\s{2,}/g, " ").trim();
response.headers.set(
"Content-Security-Policy",
getContentSecurityPolicyHeaderValue(nonce, reportUri)
);
response.headers.set("Report-To", getReportToHeaderValue(reportUri));

const requestHeaders = new Headers(request.headers);
request.headers.set(
"Content-Security-Policy",
getContentSecurityPolicyHeaderValue(nonce, reportUri)
);
requestHeaders.set("x-nonce", nonce);

if (process.env.NODE_ENV === "production") {
requestHeaders.set("Content-Security-Policy", contentSecurityPolicyHeaderValue);
}
return response;
}

const response = NextResponse.next({
request: {
headers: requestHeaders,
},
});
function initResponse(): NextResponse {
return NextResponse.next();
}

if (process.env.NODE_ENV === "production") {
response.headers.set("Content-Security-Policy", contentSecurityPolicyHeaderValue);
}
function getReportToHeaderValue(reportUri: string): string {
const reportTo = {
group: "csp",
max_age: 10886400, // 1 day
endpoints: [{ url: reportUri }],
};

return response;
return JSON.stringify(reportTo);
}

export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
{
source: "/((?!api|_next/static|_next/image|favicon.ico).*)",
missing: [
{ type: "header", key: "next-router-prefetch" },
{ type: "header", key: "purpose", value: "prefetch" },
],
},
],
};
function getContentSecurityPolicyHeaderValue(nonce: string, reportUri: string): string {
// Default CSP for Next.js
const contentSecurityPolicyDirective = {
"base-uri": [`'self'`],
"default-src": [`'none'`],
"frame-ancestors": [`'none'`],
"font-src": [`'self'`],
"form-action": [`'self'`],
"frame-src": [`'self'`],
"connect-src": [`'self'`],
"img-src": [`'self'`, "cdn.usefathom.com"],
"manifest-src": [`'self'`],
"object-src": [`'none'`],
"report-uri": [reportUri], // for old browsers like Firefox
"report-to": ["csp"], // for modern browsers like Chrome
"script-src": [
`'nonce-${nonce}'`,
`'strict-dynamic'`, // force hashes and nonces over domain host lists
],
"style-src": [`'self'`, `'unsafe-inline'`],
};

if (process.env.NODE_ENV === "development") {
// Webpack use eval() in development mode for automatic JS reloading
contentSecurityPolicyDirective["script-src"].push(`'unsafe-eval'`);
}

if (process.env.NEXT_PUBLIC_VERCEL_ENV === "preview") {
contentSecurityPolicyDirective["connect-src"].push("https://vercel.live");
contentSecurityPolicyDirective["connect-src"].push("wss://*.pusher.com");
contentSecurityPolicyDirective["img-src"].push("https://vercel.com");
contentSecurityPolicyDirective["font-src"].push("https://vercel.live");
contentSecurityPolicyDirective["frame-src"].push("https://vercel.live");
contentSecurityPolicyDirective["style-src"].push("https://vercel.live");
}

return Object.entries(contentSecurityPolicyDirective)
.map(([key, value]) => `${key} ${value.join(" ")}`)
.join("; ");
}
3 changes: 2 additions & 1 deletion turbo.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@
"WEBFLOW_API_KEY",
"WEBFLOW_BLOG_ID",
"WEBFLOW_CASE_STUDIES_ID",
"NODE_ENV"
"NODE_ENV",
"NEXT_PUBLIC_VERCEL_ENV"
]
},
"clean": {
Expand Down

0 comments on commit 4f19e09

Please sign in to comment.