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:
co-authored by
Claude Opus 4.6
parent
566a6ce5e4
commit
dc2324807c
@@ -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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user