feat: add nonce support for inline style and script tags in CSP (#3709)

## Summary
- Auto-inject `nonce` attribute onto inline `<script>` and `<style>`
tags during server rendering
- Add `useNonce` option to the CSP middleware that replaces
`'unsafe-inline'` with per-request `'nonce-{value}'` directives
- Expose render nonce via `X-Fresh-Nonce` response header (internal,
stripped by CSP middleware)

## Usage

```ts
app.use(csp({ useNonce: true }));
```

This locks down the CSP policy so only Fresh-rendered inline
scripts/styles are allowed. Each request gets a unique nonce.

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Bartek Iwańczuk
2026-03-29 21:45:13 +02:00
committed by GitHub
co-authored by Claude Opus 4.6
parent 566a6ce5e4
commit dc2324807c
6 changed files with 364 additions and 64 deletions
+43
View File
@@ -25,6 +25,49 @@ const app = new App()
.get("/", () => new Response("hello"));
```
## Nonce-based CSP
For stricter security, you can use nonce-based CSP instead of `'unsafe-inline'`.
This ensures only inline `<script>` and `<style>` tags rendered by Fresh are
allowed to execute.
```ts main.ts
import { csp } from "fresh";
const app = new App()
.use(csp({ useNonce: true }))
.get("/", (ctx) => {
return ctx.render(
<html>
<head>
<style>{"body { color: red; }"}</style>
</head>
<body>
<h1>Hello</h1>
</body>
</html>,
);
});
```
When `useNonce` is enabled:
- Fresh automatically injects a unique `nonce` attribute onto every inline
`<script>` and `<style>` tag during server rendering.
- The CSP header replaces `'unsafe-inline'` with `'nonce-{value}'` in
`script-src`, `style-src`, `default-src`, `script-src-elem`, `style-src-elem`,
and `style-src-attr` directives.
- Each request gets a fresh nonce, so the value cannot be predicted by an
attacker.
- Non-rendered responses (e.g. API routes returning JSON) fall back to
`'unsafe-inline'` since there is no rendering step to generate a nonce.
> [warn]: If you set an explicit `nonce` attribute on a tag, it will be
> preserved in the HTML, but the CSP header will only contain the
> Fresh-generated nonce. The browser will block the tag unless its nonce matches
> the one in the CSP header. To avoid this, let Fresh manage nonces
> automatically.
## Options
See the [API docs](https://jsr.io/@fresh/core/doc/~/csp) for a list of all
+9 -1
View File
@@ -17,6 +17,7 @@ import {
RenderState,
setRenderState,
} from "./runtime/server/preact_hooks.ts";
import { NONCE_SYMBOL } from "./middlewares/csp.ts";
import { DEV_ERROR_OVERLAY_URL, PARTIAL_SEARCH_PARAM } from "./constants.ts";
import { tracer } from "./otel.ts";
import {
@@ -285,6 +286,7 @@ export class Context<State> {
headers.set("X-Fresh-Id", partialId);
}
let renderNonce = "";
const html = tracer.startActiveSpan("render", (span) => {
span.setAttribute("fresh.span_type", "render");
const state = new RenderState(
@@ -376,13 +378,19 @@ export class Context<State> {
headers.append("Link", link);
}
renderNonce = state.nonce;
state.clear();
setRenderState(null);
span.end();
}
});
return new Response(html, responseInit);
const response = new Response(html, responseInit);
// Expose the nonce to CSP middleware via a symbol so it never
// leaks as a response header.
// deno-lint-ignore no-explicit-any
(response as any)[NONCE_SYMBOL] = renderNonce;
return response;
}
/**
+67 -5
View File
@@ -10,8 +10,33 @@ export interface CSPOptions {
/** Additional CSP directives to add or override the defaults */
csp?: string[];
/**
* If true, replaces 'unsafe-inline' with a nonce-based policy for
* script-src and style-src directives. Fresh automatically injects
* nonce attributes on inline `<script>` and `<style>` tags during
* server rendering, so this option locks down the policy to only
* allow those Fresh-rendered inline elements.
*/
useNonce?: boolean;
}
/**
* Symbol used to pass the render nonce from ctx.render() to the CSP
* middleware without exposing it as a response header.
*/
export const NONCE_SYMBOL: unique symbol = Symbol.for("__freshNonce");
/** Directives that may contain 'unsafe-inline' for script/style sources */
const INLINE_DIRECTIVES = new Set([
"script-src",
"style-src",
"script-src-elem",
"style-src-elem",
"style-src-attr",
"default-src",
]);
/**
* Middleware to set Content-Security-Policy headers
*
@@ -27,12 +52,18 @@ export interface CSPOptions {
* ],
* }));
* ```
*
* @example Nonce-based CSP
* ```ts
* app.use(csp({ useNonce: true }));
* ```
*/
export function csp<State>(options: CSPOptions = {}): Middleware<State> {
const {
reportOnly = false,
reportTo,
csp = [],
useNonce = false,
} = options;
const defaultCsp = [
@@ -56,14 +87,45 @@ export function csp<State>(options: CSPOptions = {}): Middleware<State> {
cspDirectives.push(`report-to csp-endpoint`);
cspDirectives.push(`report-uri ${reportTo}`); // deprecated but some browsers still use it
}
const cspString = cspDirectives.join("; ");
const headerName = reportOnly
? "Content-Security-Policy-Report-Only"
: "Content-Security-Policy";
if (!useNonce) {
// Static CSP — no per-request nonce
const cspString = cspDirectives.join("; ");
return async (ctx) => {
const res = await ctx.next();
res.headers.set(headerName, cspString);
if (reportTo) {
res.headers.set("Reporting-Endpoints", `csp-endpoint="${reportTo}"`);
}
return res;
};
}
// Nonce-based CSP — replace 'unsafe-inline' with nonce per request
return async (ctx) => {
const res = await ctx.next();
const headerName = reportOnly
? "Content-Security-Policy-Report-Only"
: "Content-Security-Policy";
res.headers.set(headerName, cspString);
// deno-lint-ignore no-explicit-any
const nonce = (res as any)[NONCE_SYMBOL] as string | undefined;
let directives: string[];
if (nonce) {
directives = cspDirectives.map((d) => {
const spaceIdx = d.indexOf(" ");
const name = spaceIdx === -1 ? d : d.slice(0, spaceIdx);
if (INLINE_DIRECTIVES.has(name) && d.includes("'unsafe-inline'")) {
return d.replaceAll("'unsafe-inline'", `'nonce-${nonce}'`);
}
return d;
});
} else {
directives = cspDirectives;
}
res.headers.set(headerName, directives.join("; "));
if (reportTo) {
res.headers.set("Reporting-Endpoints", `csp-endpoint="${reportTo}"`);
}
@@ -1,58 +0,0 @@
import { expect } from "@std/expect/expect";
import { App } from "../app.ts";
import { csp } from "./csp.ts";
Deno.test("CSP - GET default", async () => {
const handler = new App()
.use(csp())
.get("/", () => new Response("ok"))
.handler();
const res = await handler(new Request("https://localhost/"));
expect(res.status).toBe(200);
expect(res.headers.get("Content-Security-Policy")).toBeDefined();
expect(res.headers.get("Content-Security-Policy")).toContain(
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data:; media-src 'self' data: blob:; worker-src 'self' blob:; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests",
);
});
Deno.test("CSP - GET with override options", async () => {
const handler = new App()
.use(csp({
reportTo: "/api/csp-reports",
csp: [
"font-src 'self' 'https://fonts.gstatic.com'",
"style-src 'self' 'https://fonts.googleapis.com'",
],
}))
.get("/", () => new Response("ok"))
.handler();
const res = await handler(new Request("https://localhost/"));
expect(res.status).toBe(200);
expect(res.headers.get("Content-Security-Policy")).toContain(
"font-src 'self' 'https://fonts.gstatic.com'; style-src 'self' 'https://fonts.googleapis.com'",
);
expect(res.headers.get("Content-Security-Policy")).toContain(
"report-uri /api/csp-reports",
);
expect(res.headers.get("Reporting-Endpoints")).toBe(
'csp-endpoint="/api/csp-reports"',
);
});
Deno.test("CSP - GET report only", async () => {
const handler = new App()
.use(csp({
reportOnly: true,
}))
.get("/", () => new Response("ok"))
.handler();
const res = await handler(new Request("https://localhost/"));
expect(res.status).toBe(200);
expect(res.headers.get("Content-Security-Policy-Report-Only")).toBeDefined();
expect(res.headers.get("Content-Security-Policy-Report-Only")).toContain(
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data:; media-src 'self' data: blob:; worker-src 'self' blob:; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests",
);
});
+233
View File
@@ -0,0 +1,233 @@
import { expect } from "@std/expect/expect";
import { App } from "../app.ts";
import { csp } from "./csp.ts";
import { FakeServer } from "../test_utils.ts";
import { NONCE_SYMBOL } from "./csp.ts";
Deno.test("CSP - GET default", async () => {
const handler = new App()
.use(csp())
.get("/", () => new Response("ok"))
.handler();
const res = await handler(new Request("https://localhost/"));
expect(res.status).toBe(200);
expect(res.headers.get("Content-Security-Policy")).toBeDefined();
expect(res.headers.get("Content-Security-Policy")).toContain(
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data:; media-src 'self' data: blob:; worker-src 'self' blob:; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests",
);
});
Deno.test("CSP - GET with override options", async () => {
const handler = new App()
.use(csp({
reportTo: "/api/csp-reports",
csp: [
"font-src 'self' 'https://fonts.gstatic.com'",
"style-src 'self' 'https://fonts.googleapis.com'",
],
}))
.get("/", () => new Response("ok"))
.handler();
const res = await handler(new Request("https://localhost/"));
expect(res.status).toBe(200);
expect(res.headers.get("Content-Security-Policy")).toContain(
"font-src 'self' 'https://fonts.gstatic.com'; style-src 'self' 'https://fonts.googleapis.com'",
);
expect(res.headers.get("Content-Security-Policy")).toContain(
"report-uri /api/csp-reports",
);
expect(res.headers.get("Reporting-Endpoints")).toBe(
'csp-endpoint="/api/csp-reports"',
);
});
Deno.test("CSP - GET report only", async () => {
const handler = new App()
.use(csp({
reportOnly: true,
}))
.get("/", () => new Response("ok"))
.handler();
const res = await handler(new Request("https://localhost/"));
expect(res.status).toBe(200);
expect(res.headers.get("Content-Security-Policy-Report-Only")).toBeDefined();
expect(res.headers.get("Content-Security-Policy-Report-Only")).toContain(
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data:; media-src 'self' data: blob:; worker-src 'self' blob:; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests",
);
});
Deno.test("CSP - useNonce replaces unsafe-inline with nonce", async () => {
const app = new App()
.use(csp({ useNonce: true }))
.get("/", (ctx) => {
return ctx.render(
<html>
<head>
<style>{"body { color: red; }"}</style>
</head>
<body>
<h1>hello</h1>
</body>
</html>,
);
});
const server = new FakeServer(app.handler());
const res = await server.get("/");
const html = await res.text();
const cspHeader = res.headers.get("Content-Security-Policy")!;
// Should contain nonce directive, not unsafe-inline
expect(cspHeader).not.toContain("'unsafe-inline'");
expect(cspHeader).toMatch(/script-src 'self' 'nonce-[a-f0-9]+'/);
expect(cspHeader).toMatch(/style-src 'self' 'nonce-[a-f0-9]+'/);
// Nonce should not leak as a response header
expect(res.headers.get("X-Fresh-Nonce")).toBeNull();
// HTML should contain nonce on the style tag
const nonceMatch = cspHeader.match(/nonce-([a-f0-9]+)/);
expect(nonceMatch).not.toBeNull();
const nonce = nonceMatch![1];
expect(html).toContain(`nonce="${nonce}"`);
});
Deno.test("CSP - useNonce injects nonce on inline script tags", async () => {
const app = new App()
.use(csp({ useNonce: true }))
.get("/", (ctx) => {
return ctx.render(
<html>
<head />
<body>
<script>console.log('hello')</script>
</body>
</html>,
);
});
const server = new FakeServer(app.handler());
const res = await server.get("/");
const html = await res.text();
const cspHeader = res.headers.get("Content-Security-Policy")!;
const nonceMatch = cspHeader.match(/nonce-([a-f0-9]+)/);
expect(nonceMatch).not.toBeNull();
const nonce = nonceMatch![1];
// Inline script should have the nonce
expect(html).toContain(`nonce="${nonce}"`);
});
Deno.test("CSP - useNonce with non-rendered response falls back to unsafe-inline", async () => {
const app = new App()
.use(csp({ useNonce: true }))
.get("/api", () => new Response(JSON.stringify({ ok: true })));
const server = new FakeServer(app.handler());
const res = await server.get("/api");
await res.body?.cancel();
const cspHeader = res.headers.get("Content-Security-Policy")!;
// Non-rendered response has no nonce, so unsafe-inline stays
expect(cspHeader).toContain("'unsafe-inline'");
});
Deno.test("CSP - useNonce generates unique nonce per request", async () => {
const app = new App()
.use(csp({ useNonce: true }))
.get("/", (ctx) => {
return ctx.render(
<html>
<head />
<body>hello</body>
</html>,
);
});
const server = new FakeServer(app.handler());
const res1 = await server.get("/");
await res1.body?.cancel();
const res2 = await server.get("/");
await res2.body?.cancel();
const nonce1 = res1.headers.get("Content-Security-Policy")!.match(
/nonce-([a-f0-9]+)/,
)![1];
const nonce2 = res2.headers.get("Content-Security-Policy")!.match(
/nonce-([a-f0-9]+)/,
)![1];
expect(nonce1).not.toEqual(nonce2);
});
Deno.test("CSP - existing nonce on tag is preserved", async () => {
const app = new App()
.use(csp({ useNonce: true }))
.get("/", (ctx) => {
return ctx.render(
<html>
<head>
<script nonce="custom-nonce">alert(1)</script>
</head>
<body>hello</body>
</html>,
);
});
const server = new FakeServer(app.handler());
const res = await server.get("/");
const html = await res.text();
// The explicit nonce should be preserved, not overwritten
expect(html).toContain('nonce="custom-nonce"');
});
Deno.test("CSP - nonce does not leak as header without CSP middleware", async () => {
const app = new App()
.get("/", (ctx) => {
return ctx.render(
<html>
<head />
<body>hello</body>
</html>,
);
});
const server = new FakeServer(app.handler());
const res = await server.get("/");
await res.body?.cancel();
// No CSP middleware — nonce must not appear as a response header
expect(res.headers.get("X-Fresh-Nonce")).toBeNull();
// But it should still be available via the symbol for middleware that needs it
// deno-lint-ignore no-explicit-any
expect((res as any)[NONCE_SYMBOL]).toBeDefined();
});
Deno.test("CSP - useNonce replaces unsafe-inline in default-src", async () => {
const app = new App()
.use(csp({
useNonce: true,
csp: ["default-src 'self' 'unsafe-inline'"],
}))
.get("/", (ctx) => {
return ctx.render(
<html>
<head />
<body>hello</body>
</html>,
);
});
const server = new FakeServer(app.handler());
const res = await server.get("/");
await res.body?.cancel();
const cspHeader = res.headers.get("Content-Security-Policy")!;
// default-src should have nonce, not unsafe-inline
expect(cspHeader).toMatch(/default-src 'self' 'nonce-[a-f0-9]+'/);
});
@@ -133,6 +133,18 @@ options[OptionsType.VNODE] = (vnode) => {
);
}
} else if (typeof vnode.type === "string") {
// Auto-inject nonce onto inline script/style tags
if (
RENDER_STATE !== null &&
(vnode.type === "script" || vnode.type === "style")
) {
// deno-lint-ignore no-explicit-any
const props = vnode.props as any;
if (!props.nonce) {
props.nonce = RENDER_STATE.nonce;
}
}
if (vnode.type === "body") {
const scripts = h(FreshScripts, null);
if (vnode.props.children == null) {