SearchCtrlK

  • ↑↓navigate
  • ↵open
  • escclose

Can’t find it? Contact us

Security headers and CSP

Remix CSP for nonces, plus typed HSTS and Permissions-Policy, violation reports, and a security.txt.

After reading this guide, you will know

  • How to write CSP with Remix's csp() and the rest as one typed policy
  • How to use nonces or hashes for the scripts you render
  • How to collect violation reports and publish a security.txt

A browser enforces what your response headers tell it: where scripts may load from, whether the page may be framed, which device APIs it may ask for, whether the site is HTTPS-only. This guide splits that work the way Remix 3.2 does: csp() owns Content-Security-Policy and the per-request nonce, and @sdxc/security-headers owns HSTS, Referrer-Policy, Permissions-Policy and the rest as one typed object. @sdxc/crypto hashes a fixed inline script, and @sdxc/well-known publishes the security.txt that tells a researcher where to report what the headers missed.

Terminal
npm add @sdxc/assets-middleware @sdxc/crypto @sdxc/result @sdxc/security-headers \
	@sdxc/well-known remix

Write the policies once

Keep the CSP directives next to the other headers, but as two exports: Remix's csp() takes the directives, and securityHeaders() takes everything else. The CSP model writes keywords unquoted and quotes them on output, so a missing quote cannot happen. "nonce" is a placeholder remixCsp replaces with the request nonce Remix generated.

config/security-policy.ts
import type { CSP, SecurityHeaders } from "@sdxc/security-headers";

export const BOOT_SCRIPT = `document.documentElement.classList.add("js");`;

export const CONTENT_SECURITY_POLICY: CSP.Directives = {
	defaultSrc: ["self"],
	scriptSrc: [
		"self",
		"nonce",
		"sha256-WZRJfWvsnNCPcxzZwvyhovnZGqhZaC+8gPGPRbx6wTk=",
		"https://challenges.cloudflare.com",
	],
	styleSrc: ["self", "unsafe-inline"],
	imgSrc: ["self", "data:"],
	frameSrc: ["https://challenges.cloudflare.com"],
	formAction: ["self", "https://auth.example.com"],
	frameAncestors: ["none"],
	objectSrc: ["none"],
	baseUri: ["none"],
	reportTo: "csp",
};

export const SECURITY_POLICY: SecurityHeaders.Policy = {
	strictTransportSecurity: { maxAge: 31536000, includeSubDomains: true },
	referrerPolicy: "strict-origin-when-cross-origin",
	crossOriginOpenerPolicy: "same-origin",
	xFrameOptions: "DENY",
	permissionsPolicy: { camera: [], microphone: [], geolocation: [], payment: [] },
};

formAction names your identity provider, because the login in Sign in with OpenID Connect redirects a form there. The Turnstile origin in scriptSrc and frameSrc is for the challenge from Protect forms. Set xFrameOptions: "DENY" beside frameAncestors: ["none"] when you want both the CSP and the legacy header.

Start with Remix's reportOnlyPolicy: the browser reports what it would have blocked without blocking it. Rename the option to policy when the reports show the policy can be enforced.

Install both middlewares before the renderer

csp() serializes the Content-Security-Policy (and Reporting-Endpoints) and publishes the nonce. securityHeaders(policy) writes the other headers onto whatever response the chain returns. Place them right before assets() and the renderer, so the nonce exists before the document asks for it.

app/initializers/router.ts
import { assets } from "@sdxc/assets-middleware";
import { remixCsp } from "@sdxc/security-headers/remix";
import { securityHeaders } from "@sdxc/security-headers/middleware";
import { csp, getCspNonce } from "remix/middleware/csp";
import { render } from "remix/middleware/render";
import { createRouter } from "remix/router";

import { assetResolver } from "~/app/initializers/assets";
import { CONTENT_SECURITY_POLICY, SECURITY_POLICY } from "~/config/security-policy";

export function createWebRouter() {
	let router = createRouter({
		middleware: [
			// …the middleware your app already runs
			csp({
				reportOnlyPolicy: ({ nonce }) =>
					remixCsp(CONTENT_SECURITY_POLICY, nonce),
				reportingEndpoints: { csp: "/reports/csp" },
			}),
			securityHeaders(SECURITY_POLICY),
			assets(assetResolver, {
				stylesheets: "resources/layouts/document.tsx",
				script: "bootstrap/browser.ts",
				nonce: (ctx) => getCspNonce(ctx),
			}),
			render({ assets: assetResolver }),
		],
	});
	// router.map(…) for each route
	return router;
}

The comment stands for the middleware from Wire the router. assets() publishes the stylesheets, entry script and nonce each page passes to its document as ctx.assets.

Put nonces on the scripts you render

Remix generates the nonce once per request. The document puts ctx.assets.nonce on its import map, which remix/component copies onto every import map it appends later, so client entries load under a nonce-based script-src:

resources/layouts/document.tsx
import type { DocumentAssets } from "@sdxc/assets-middleware";
import type { Handle, RemixNode } from "remix/component";

import { ImportMap } from "remix/component/server";

import { BOOT_SCRIPT } from "~/config/security-policy";

type DocumentProps = { assets: DocumentAssets; children?: RemixNode };

export function Document(handle: Handle<DocumentProps>) {
	return () => {
		let { nonce, script } = handle.props.assets;
		return (
			<html lang="en">
				<head>
					<ImportMap value={script.importMap} nonce={nonce} />
					<script>{BOOT_SCRIPT}</script>
				</head>
				<body>
					{handle.props.children}
					<script type="module" async src={script.href}></script>
				</body>
			</html>
		);
	};
}

The boot script needs no nonce, because its hash is in the policy. Any other inline script a handler renders takes getCspNonce(ctx) the same way.

Hash a fixed inline script instead

For a script whose text never changes, list its hash instead. The policy module exports BOOT_SCRIPT and lists its sha256-… source as a literal, and a test fails when the two drift apart:

config/security-policy.test.ts
import { Base64, sha256 } from "@sdxc/crypto";
import { unwrap } from "@sdxc/result";
import { expect, test } from "vitest";

import { CONTENT_SECURITY_POLICY, BOOT_SCRIPT } from "./security-policy";

test("the policy allows the boot script exactly as written", async () => {
	let digest = Base64.encode(unwrap(await sha256(BOOT_SCRIPT)));
	let scriptSrc = CONTENT_SECURITY_POLICY.scriptSrc;
	expect(scriptSrc).toContain(`sha256-${digest}`);
});

Hashing in a test keeps the work out of the Worker's global scope and off every cold start.

Collect reports before enforcing

reportTo: "csp" names the endpoint Remix's reportingEndpoints points at. parseReports reads both report formats browsers send into one violation shape.

app/http/controllers/csp-reports.ts
import { isFailure } from "@sdxc/result";
import { parseReports } from "@sdxc/security-headers/reports";
import { createAction } from "remix/router";

import routes from "~/routes/web";

export default createAction(routes.cspReports, async (ctx) => {
	let parsed = await parseReports(ctx.request);
	if (isFailure(parsed)) return new Response(null, { status: 400 });

	for (let violation of parsed.data.slice(0, 20)) {
		ctx.log.warn("csp.violation", {
			document_url: violation.documentURL,
			blocked_url: violation.blockedURL,
			directive: violation.effectiveDirective,
		});
	}

	return new Response(null, { status: 204 });
});

Declare the route as cspReports: post("/reports/csp"). The slice caps how much one crafted batch can write to your logs. When the only violations left are browser extensions, switch reportOnlyPolicy to policy and the CSP is enforced. A route that has to differ, such as an embeddable widget, patches CSP with cspPatch() / patchCsp() and other headers with securityHeadersOverride instead of weakening the policy for every page.

Publish security.txt

RFC 9116's /.well-known/security.txt is where a researcher looks for your security contact:

config/security-txt.ts
import type { SecurityTxt } from "@sdxc/well-known/security-txt";

export const SECURITY_TXT: SecurityTxt = {
	contact: [new URL("mailto:security@example.com")],
	expires: new Date("2027-09-30T00:00:00Z"),
	encryption: [],
	acknowledgments: [],
	preferredLanguages: ["en"],
	canonical: [new URL("https://example.com/.well-known/security.txt")],
	policy: [],
	hiring: [],
	extensions: {},
};

Register wellKnown({ "security.txt": serve(securityTxt, () => SECURITY_TXT) }) — wellKnown and serve from @sdxc/well-known/middleware, securityTxt from @sdxc/well-known/security-txt — near the top of the chain, before session work. Keep expires a literal date, and add a test that fails 30 days before it with isExpired(SECURITY_TXT, thirtyDaysFromNow), so a stale contact cannot go unnoticed.

Test the headers

Request a page your app maps, / here, through the router and read the headers back, then post a report the way an older browser does:

app/http/controllers/csp-reports.test.ts
import { expect, test } from "vitest";

import { createWebRouter } from "~/app/initializers/router";
import routes from "~/routes/web";

test("every page carries the policy", async () => {
	let response = await createWebRouter().fetch(new URL("/", "https://example.com"));

	expect(response.headers.get("Content-Security-Policy-Report-Only")).toContain(
		"frame-ancestors 'none'",
	);
	expect(response.headers.get("Strict-Transport-Security")).toContain(
		"max-age=31536000",
	);
});

test("accepts a legacy violation report", async () => {
	let response = await createWebRouter().fetch(
		new Request(new URL(routes.cspReports.href(), "https://example.com"), {
			method: "POST",
			headers: { "Content-Type": "application/csp-report" },
			body: JSON.stringify({
				"csp-report": {
					"document-uri": "https://example.com/",
					"blocked-uri": "https://evil.example.com/x.js",
					"violated-directive": "script-src",
				},
			}),
		}),
	);

	expect(response.status).toBe(204);
});

The request URL is https:, because Strict-Transport-Security is written only on a response to a secure request.

Run it from the terminal

After a deploy, grade the headers a page really sends and check the security.txt beside them:

Terminal
sdxc pkg security-headers audit https://example.com
sdxc pkg security-headers csp parse < policy.txt
sdxc pkg well-known security-txt check https://example.com

audit exits 1 when any header is missing or weak, and security-txt check exits 1 on a missing field or an Expires in the past, so both work as a CI step. csp parse reads a policy copied from a response into its directives. Use a package from the terminal covers what every package command line shares.

Where to go next

Documentation

Can’t find it? Contact us