CSP
Restrict the scripts a page runs with a Content-Security-Policy.
On this page
What the framework writes
The framework sets no policy; the application writes it. The framework only makes the inline scripts it writes into the HTML allowable by hash or nonce: the payload embedded for hydration, and React’s own script.
The framework also writes one empty <style> into <head>, which keeps the Server Components’ CSS before the Client Components’. It is allowable by hash or nonce as well.
Static mode
In static mode, the policy goes to the csp option of framework() and into each page’s <meta>. A static file is the same for every request, so a nonce cannot be used. nonce() exists in server mode only.
The csp option
vite.config.tsimport { framework } from '@k8ordo/framework/vite';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [
framework({
mode: 'static',
site: 'https://example.com',
csp: {
'script-src': ["'self'"],
'object-src': ["'none'"],
'base-uri': ["'none'"],
},
}),
],
});Give csp an array of sources per directive. Each page gets a <meta http-equiv="Content-Security-Policy"> in its <head>, right after the <meta charSet> that opens it. Without csp, no <meta> is written.
The build adds the hashes of the framework’s inline scripts to script-src, page by page.
When only default-src is given, script-src is made from it first. When script-src-elem is given, the hashes go there too. With none of them, scripts are not restricted, and no hash is added.
The build adds the <style>’s hash too, to style-src-elem or style-src, making style-src from default-src when neither is given. Where the policy lets it in with 'unsafe-inline', no hash is added: beside a hash, 'unsafe-inline' is ignored, and style attributes stop working too.
Your own scripts
vite.config.tsimport { colorSchemeScriptHash } from '@k8ordo/color-scheme';
import { framework } from '@k8ordo/framework/vite';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [
framework({
mode: 'static',
site: 'https://example.com',
csp: {
'script-src': ["'self'", await colorSchemeScriptHash()],
'object-src': ["'none'"],
'base-uri': ["'none'"],
},
}),
],
});The application’s own inline scripts are allowed by writing their hashes into the policy. On line 10, colorSchemeScriptHash() returns the hash of the @k8ordo/color-scheme script. A script the application writes itself is hashed with scriptHash().
If ColorSchemeScript is given a defaultPreference or a themeColor, pass the same values to colorSchemeScriptHash(). They change the script and its hash.
Every inline script whose hash is not in the policy is blocked. A script injected through the content does not run either.
Policy errors
The framework’s module script is allowed by 'self'. 'strict-dynamic' makes browsers ignore 'self', so 'strict-dynamic' in script-src (default-src without it) or script-src-elem is an error.
frame-ancestors, report-uri and sandbox are errors too. A <meta> ignores them, so set them as headers at the host.
report-to is an error as well. The endpoint it names is defined only by a Reporting-Endpoints response header, so set a policy that reports as a header at the host.
A header cannot carry the hashes the build adds page by page, and a script runs only when both the header’s policy and the <meta>’s allow it. Let the header’s script-src (default-src without it) and script-src-elem allow 'self' and 'unsafe-inline'. Beside a hash or a nonce, 'unsafe-inline' is ignored. Keep csp without report-to, so the <meta> still restricts inline scripts by hash.
The <style>’s hash is 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=' on every page, so a header that restricts styles can name it.
Pitfall
framework() throws as soon as it is called, with an error that starts the "csp" option cannot go into a page's <meta> as it is: and lists one problem per line.
Server mode
In server mode, every response gets a new nonce, and the root guard.ts writes the policy as a header.
The policy in guard.ts
src/routes/guard.tsimport { nonce, responseHeaders } from '@k8ordo/framework/server';
export default function guard() {
const scripts = [`'nonce-${nonce()}'`, "'strict-dynamic'"];
if (import.meta.env.DEV) scripts.push("'unsafe-eval'");
const policy = [
`script-src ${scripts.join(' ')}`,
"object-src 'none'",
"base-uri 'none'",
].join('; ');
responseHeaders().set('content-security-policy', policy);
}nonce() from @k8ordo/framework/server returns the nonce of the response. Line 4 writes it into the policy, and line 11 sets the header.
Note
Line 5 adds 'unsafe-eval' under vite dev only. React’s development build calls eval(), and without it every page load logs an error to the console. A production build never calls it, and the line is dropped from it.
The root guard.ts runs before the response of a page, its payload, a Server Action and a route.ts. The 404 for a URL no route matched carries the same policy.
The nonce is on the module script too. With 'strict-dynamic', that script can load the rest of the client code.
Scripts that carry the nonce
src/routes/layout.tsximport {
ColorSchemeProvider,
ColorSchemeScript,
} from '@k8ordo/color-scheme';
import type { LayoutProps } from '@k8ordo/framework';
import { nonce } from '@k8ordo/framework/server';
export default function RootLayout({
children,
}: LayoutProps<'/'>) {
return (
<html lang="en" suppressHydrationWarning>
<head>
<ColorSchemeScript nonce={nonce()} />
</head>
<body>
<ColorSchemeProvider>{children}</ColorSchemeProvider>
</body>
</html>
);
}The application’s own inline scripts carry the same nonce. For @k8ordo/color-scheme, pass nonce={nonce()} to ColorSchemeScript in the root layout’s <head>.
The framework’s <style> carries the same nonce. A policy that restricts styles names the nonce in style-src too. vite dev adds CSS as <style> elements nothing signs, so under vite dev allow 'unsafe-inline' instead.
Of the <style> elements with href and precedence, only those carrying the same nonce are written into the HTML. Give one a Server Component renders nonce={nonce()}. A Client Component cannot read the nonce, so one it renders is not written into the HTML.
nonce() returns the same value anywhere while the request is being answered. It can be called during the render too.
Called outside a request, at a module’s top level for example, it errors with a message that starts with nonce() needs a request.
Nonces and caches
Keep a response that carries a nonce out of shared caches such as a CDN. If the same nonce is served again and again, an attacker who learned it can inject a script that carries it.
A script that runs before the first paint
src/lib/density-script.tsimport { densityState } from '../state';
export const densityScript = `(() => {
const s = ${densityState.inlineRead()};
if (s && s.density === 'compact') {
document.documentElement.dataset.density = 'compact';
}
})();`;A preference only the browser applies has to reach <html> before the first paint. An inline script in the root layout’s <head> reads the stored value with @k8ordo/state’s inlineRead().
src/components/density-script.tsx'use client';
import { densityScript } from '../lib/density-script';
export function DensityScript({ nonce }: { nonce?: string }) {
return <script nonce={nonce}>{densityScript}</script>;
}Make that script a 'use client' component. The text of a <script> a Server Component renders goes into every page’s payload, though a script that arrives with a navigation never runs. A Client Component’s payload carries only its props.
Take the nonce as a prop. Under server mode, the root layout passes nonce().
vite.config.tsimport { colorSchemeScriptHash } from '@k8ordo/color-scheme';
import { framework, scriptHash } from '@k8ordo/framework/vite';
import { defineConfig } from 'vite';
import { densityScript } from './src/lib/density-script';
export default defineConfig({
plugins: [
framework({
mode: 'static',
site: 'https://example.com',
csp: {
'script-src': [
"'self'",
await colorSchemeScriptHash(),
await scriptHash(densityScript),
],
},
}),
],
});Under static mode, the csp option names the hash of the same text. Export the text from a module without a directive, and read it from both the component and vite.config.ts. Line 16 passes that text to scriptHash() from @k8ordo/framework/vite.
scriptHash() hashes the text as it is. A single space more or less makes another script, and it is blocked. A line break counts as the browser parses it, a CR LF as one LF.
The script changes <html> before React hydrates it, so <html> carries suppressHydrationWarning.