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
@@ -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) {