diff --git a/.changeset/html-server-document-nonce.md b/.changeset/html-server-document-nonce.md new file mode 100644 index 00000000000..ff4b159b8cc --- /dev/null +++ b/.changeset/html-server-document-nonce.md @@ -0,0 +1,5 @@ +--- +"effect": minor +--- + +Add Content Security Policy nonces to `HtmlServer.document`. Pass the per-response nonce in `DocumentOptions` to set it on the hydration state script and replace a placeholder in the static HTML template. `virtual:effect/ui/document` uses Vite's `html.cspNonce` as its default placeholder. diff --git a/packages/effect/src/ui/html/HtmlServer.ts b/packages/effect/src/ui/html/HtmlServer.ts index 2c2f5dbb256..3707541951d 100644 --- a/packages/effect/src/ui/html/HtmlServer.ts +++ b/packages/effect/src/ui/html/HtmlServer.ts @@ -246,6 +246,21 @@ export const serializeState = (state: Renderer.State): string => (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}` ) +/** + * Content Security Policy (CSP) options for {@link document}. + * + * @stability unstable + * @category models + * @since 4.3.0 + */ +export interface DocumentOptions { + /** The per-response nonce used in the response's CSP header. An empty value is treated as omitted. */ + readonly nonce?: string | undefined + + /** A unique placeholder in quoted attribute values in the static template, such as Vite's `html.cspNonce`. */ + readonly noncePlaceholder?: string | undefined +} + /** * Fills an HTML template with a rendered page. * @@ -261,6 +276,11 @@ export const serializeState = (state: Renderer.State): string => * `` marker with `html`, and adds the state as * `` + `${serializeState(rendered.state)}` ) // Last, so no search above runs over the app's markup. return html.replace(appMarker, () => rendered.html) diff --git a/packages/effect/src/ui/html/HtmlServerVite.ts b/packages/effect/src/ui/html/HtmlServerVite.ts index 9fae415fd69..df0ff041b5a 100644 --- a/packages/effect/src/ui/html/HtmlServerVite.ts +++ b/packages/effect/src/ui/html/HtmlServerVite.ts @@ -13,6 +13,9 @@ * that module's types. `index.html` holds the static markup and the * `` marker where the page goes. * + * To use a CSP nonce, configure Vite's `html.cspNonce` with a placeholder + * and pass the response's nonce to `document(rendered, { nonce })`. + * * In dev, Vite answers module, asset and `/@vite` requests first, and every * other request goes to the server entry. The template is `index.html` * after Vite's HTML transforms. Editing a module or `index.html` reloads @@ -168,6 +171,9 @@ export interface Plugin { config: unknown, env: { readonly isPreview?: boolean | undefined } ): object + configResolved(config: { + readonly html?: { readonly cspNonce?: string | undefined } | undefined + }): void resolveId(source: string): string | undefined load(this: LoadContext, id: string): Promise configureServer(server: DevServer): () => void @@ -276,6 +282,7 @@ const declaration = [ export const plugin = (options: Options): Plugin => { const origin = options.origin ?? "http://localhost" let devServer: DevServer | undefined + let cspNonce: string | undefined // The app's `index.html` in dev, and the client build's in a build. let templateFile = "" // Closes each dev server, by its client environment. A restart @@ -310,13 +317,17 @@ export const plugin = (options: Options): Plugin => { } } }), + configResolved(config) { + cspNonce = config.html?.cspNonce + }, resolveId: (source) => source === documentId || source === serverId ? `\0${source}` : undefined, async load(id) { if (id === `\0${documentId}`) { return [ `import { document as fill } from "effect/ui/html/HtmlServer"`, `const template = ${JSON.stringify(await template(this))}`, - `export const document = (rendered) => fill(template, rendered)` + `const noncePlaceholder = ${JSON.stringify(cspNonce)}`, + `export const document = (rendered, options) => fill(template, rendered, options && { noncePlaceholder, ...options })` ].join("\n") } if (id === `\0${serverId}`) { diff --git a/packages/effect/src/ui/html/HtmlServerViteDocument.d.ts b/packages/effect/src/ui/html/HtmlServerViteDocument.d.ts index 2786f1f8757..41bfc0cd04d 100644 --- a/packages/effect/src/ui/html/HtmlServerViteDocument.d.ts +++ b/packages/effect/src/ui/html/HtmlServerViteDocument.d.ts @@ -9,11 +9,12 @@ * @since 4.2.0 */ declare module "virtual:effect/ui/document" { - import type { Rendered } from "effect/ui/html/HtmlServer" + import type { DocumentOptions, Rendered } from "effect/ui/html/HtmlServer" /** * Fills the app's `index.html` with a rendered page, using * `HtmlServer.document`. In dev the template is `index.html` after Vite's * HTML transforms, and in a build it is the client build's `index.html`. + * Vite's `html.cspNonce` supplies the default `noncePlaceholder`. */ - export const document: (rendered: Rendered) => string + export const document: (rendered: Rendered, options?: DocumentOptions) => string } diff --git a/packages/effect/src/ui/html/internal/server.ts b/packages/effect/src/ui/html/internal/server.ts index a96c8e34c1f..e1160285a6e 100644 --- a/packages/effect/src/ui/html/internal/server.ts +++ b/packages/effect/src/ui/html/internal/server.ts @@ -111,7 +111,8 @@ const escapeText = (text: string): string => ? text.replace(/[&<>]/g, (char) => char === "&" ? "&" : char === "<" ? "<" : ">") : text -const escapeAttribute = (value: string): string => +/** @internal */ +export const escapeAttribute = (value: string): string => attributeSpecial.test(value) ? value.replace( /[&"<>]/g, diff --git a/packages/effect/test/ui/html/HtmlServer.test.ts b/packages/effect/test/ui/html/HtmlServer.test.ts index 43b7695be7e..dd3285c9fea 100644 --- a/packages/effect/test/ui/html/HtmlServer.test.ts +++ b/packages/effect/test/ui/html/HtmlServer.test.ts @@ -4313,4 +4313,49 @@ describe("HtmlServer.document", () => { // ) }) + + it("adds a nonce to the state script without requiring a template placeholder", () => { + const template = "" + const expected = "Home

Home

" + + "" + + expect(HtmlServer.document(template, rendered, { nonce: "request-1" })).toBe(expected) + expect(HtmlServer.document(template, rendered, { nonce: "request-1", noncePlaceholder: "" })).toBe(expected) + }) + + it("escapes nonces and substitutes placeholders only in the static template", () => { + const template = "" + + "
" + + "" + const renderedWithPlaceholder: HtmlServer.Rendered = { + ...rendered, + html: "

__CSP_NONCE__

", + head: "__CSP_NONCE__", + state: { note: "__CSP_NONCE__" }, + bodyAttributes: "data-note=\"__CSP_NONCE__\"" + } + + expect(HtmlServer.document(template, renderedWithPlaceholder, { + nonce: "abc$&\"'<>", + noncePlaceholder: "__CSP_NONCE__" + })).toBe( + "" + + "" + + "__CSP_NONCE__" + + "

__CSP_NONCE__

" + + "" + + "" + ) + }) + + it("keeps the original output when the nonce is missing or empty", () => { + const template = "" + + "" + const expected = HtmlServer.document(template, rendered) + + expect(HtmlServer.document(template, rendered, { noncePlaceholder: "__CSP_NONCE__" })).toBe(expected) + expect(HtmlServer.document(template, rendered, { nonce: "", noncePlaceholder: "__CSP_NONCE__" })).toBe(expected) + }) }) diff --git a/packages/effect/test/ui/html/HtmlServerVite.test.ts b/packages/effect/test/ui/html/HtmlServerVite.test.ts index 4239a7d6d09..3daccf42301 100644 --- a/packages/effect/test/ui/html/HtmlServerVite.test.ts +++ b/packages/effect/test/ui/html/HtmlServerVite.test.ts @@ -337,6 +337,65 @@ describe("HtmlServerVite.plugin", () => { expect(build).not.toHaveBeenCalled() }) + it("fills Vite's CSP nonce placeholder per request in dev and production builds", async () => { + const placeholder = "__TEST_CSP_NONCE__" + const entry = "/src/entry.nonce.ts" + const expectNonce = (page: string, nonce: string) => { + expect(page.match(/]*\btype="module")(?=[^>]*\bsrc=")[^>]*>/)?.[0]) + .toContain(`nonce="${nonce}"`) + expect(page.match(/]*\brel="stylesheet")[^>]*>/)?.[0]).toContain(`nonce="${nonce}"`) + expect(page).toContain(`