Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/html-server-document-nonce.md
Original file line number Diff line number Diff line change
@@ -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.
43 changes: 35 additions & 8 deletions packages/effect/src/ui/html/HtmlServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand All @@ -261,6 +276,11 @@ export const serializeState = (state: Renderer.State): string =>
* `<!--app-html-->` marker with `html`, and adds the state as
* `<script type="application/json" id="state">` before `</body>`.
*
* A non-empty `options.nonce` adds an escaped `nonce` attribute to the state
* script. When `options.noncePlaceholder` is also non-empty, the escaped
* nonce replaces that token in the static template before the rendered
* markup, attributes or state are inserted.
*
* **Gotchas**
*
* It throws if the template has no `<!--app-html-->`, `</head>` or
Expand Down Expand Up @@ -293,22 +313,29 @@ export const serializeState = (state: Renderer.State): string =>
*/
export const document = (
template: string,
rendered: Rendered<unknown>
rendered: Rendered<unknown>,
options?: DocumentOptions
): string => {
if (!template.includes(appMarker)) {
const nonce = options?.nonce
// The template may use either kind of quote around attribute values.
const escapedNonce = nonce === undefined || nonce === ""
? undefined
: server.escapeAttribute(nonce).replaceAll("'", "&#39;")
const placeholder = options?.noncePlaceholder
let html = escapedNonce !== undefined && placeholder !== undefined && placeholder !== ""
? template.replaceAll(placeholder, () => escapedNonce)
: template
if (!html.includes(appMarker)) {
throw new Error(`The document template has no ${appMarker} marker`)
}
let html = withAttributes(
template,
/<html(?=[\s/>])/i,
rendered.htmlAttributes
)
html = withAttributes(html, /<html(?=[\s/>])/i, rendered.htmlAttributes)
html = withAttributes(html, /<body(?=[\s/>])/i, rendered.bodyAttributes)
html = insertBefore(html, "</head>", rendered.head)
const nonceAttribute = escapedNonce === undefined ? "" : ` nonce="${escapedNonce}"`
html = insertBefore(
html,
"</body>",
`<script type="application/json" id="state">${serializeState(rendered.state)}</script>`
`<script${nonceAttribute} type="application/json" id="state">${serializeState(rendered.state)}</script>`
)
// Last, so no search above runs over the app's markup.
return html.replace(appMarker, () => rendered.html)
Expand Down
13 changes: 12 additions & 1 deletion packages/effect/src/ui/html/HtmlServerVite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@
* that module's types. `index.html` holds the static markup and the
* `<!--app-html-->` 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
Expand Down Expand Up @@ -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<string | undefined>
configureServer(server: DevServer): () => void
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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}`) {
Expand Down
5 changes: 3 additions & 2 deletions packages/effect/src/ui/html/HtmlServerViteDocument.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<unknown>) => string
export const document: (rendered: Rendered<unknown>, options?: DocumentOptions) => string
}
3 changes: 2 additions & 1 deletion packages/effect/src/ui/html/internal/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,8 @@ const escapeText = (text: string): string =>
? text.replace(/[&<>]/g, (char) => char === "&" ? "&amp;" : char === "<" ? "&lt;" : "&gt;")
: text

const escapeAttribute = (value: string): string =>
/** @internal */
export const escapeAttribute = (value: string): string =>
attributeSpecial.test(value)
? value.replace(
/[&"<>]/g,
Expand Down
45 changes: 45 additions & 0 deletions packages/effect/test/ui/html/HtmlServer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4313,4 +4313,49 @@ describe("HtmlServer.document", () => {
/<!--app-html-->/
)
})

it("adds a nonce to the state script without requiring a template placeholder", () => {
const template = "<html><head></head><body><!--app-html--></body></html>"
const expected = "<html lang=\"en\"><head><title>Home</title></head><body><h1>Home</h1>" +
"<script nonce=\"request-1\" type=\"application/json\" id=\"state\">" +
"{\"~static\":true,\"note\":\"\\u003c/script>\"}</script></body></html>"

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 = "<!doctype html><html><head><style nonce='__CSP_NONCE__'>h1 {color: red}</style></head>" +
"<body><div id=\"app\"><!--app-html--></div>" +
"<script type=\"module\" nonce=\"__CSP_NONCE__\" src=\"/app.js\"></script></body></html>"
const renderedWithPlaceholder: HtmlServer.Rendered<unknown> = {
...rendered,
html: "<h1>__CSP_NONCE__</h1>",
head: "<title>__CSP_NONCE__</title>",
state: { note: "__CSP_NONCE__" },
bodyAttributes: "data-note=\"__CSP_NONCE__\""
}

expect(HtmlServer.document(template, renderedWithPlaceholder, {
nonce: "abc$&\"'<>",
noncePlaceholder: "__CSP_NONCE__"
})).toBe(
"<!doctype html><html lang=\"en\"><head>" +
"<style nonce='abc$&amp;&quot;&#39;&lt;&gt;'>h1 {color: red}</style>" +
"<title>__CSP_NONCE__</title></head>" +
"<body data-note=\"__CSP_NONCE__\"><div id=\"app\"><h1>__CSP_NONCE__</h1></div>" +
"<script type=\"module\" nonce=\"abc$&amp;&quot;&#39;&lt;&gt;\" src=\"/app.js\"></script>" +
"<script nonce=\"abc$&amp;&quot;&#39;&lt;&gt;\" type=\"application/json\" id=\"state\">" +
"{\"note\":\"__CSP_NONCE__\"}</script></body></html>"
)
})

it("keeps the original output when the nonce is missing or empty", () => {
const template = "<html><head></head><body><!--app-html-->" +
"<script nonce=\"__CSP_NONCE__\" src=\"/app.js\"></script></body></html>"
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)
})
})
59 changes: 59 additions & 0 deletions packages/effect/test/ui/html/HtmlServerVite.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(/<script\b(?=[^>]*\btype="module")(?=[^>]*\bsrc=")[^>]*>/)?.[0])
.toContain(`nonce="${nonce}"`)
expect(page.match(/<link\b(?=[^>]*\brel="stylesheet")[^>]*>/)?.[0]).toContain(`nonce="${nonce}"`)
expect(page).toContain(`<script nonce="${nonce}" type="application/json" id="state">`)
expect(page).not.toContain(placeholder)
}

const dir = await fs.mkdtemp(path.join(fixtureRoot, ".out-nonce-"))
const sharedConfig = { html: { cspNonce: placeholder }, cacheDir: path.join(dir, "cache") }
try {
const server = await createServer(config({
...sharedConfig,
server: { port: 0, strictPort: false, ws: false },
plugins: [plugin({ entry })]
}))
try {
await server.listen()
const get = async (nonce: string) => {
const response = await fetch(server.resolvedUrls!.local[0]!, { headers: { "x-nonce": nonce } })
expect(response.status).toBe(200)
return response.text()
}
expectNonce(await get("dev-1"), "dev-1")
const second = await get("dev-2")
expectNonce(second, "dev-2")
expect(second).not.toContain("nonce=\"dev-1\"")
} finally {
await server.close()
}

const clientOutDir = path.join(dir, "client")
const serverOutDir = path.join(dir, "server")
const builder = await createBuilder(config({
...sharedConfig,
build: { outDir: clientOutDir, emptyOutDir: true },
plugins: [plugin({ entry, serverOutDir })]
}))
await builder.buildApp()

const built = (await import(pathToFileURL(path.join(serverOutDir, "index.js")).href)) as {
readonly handler: (request: Request) => Promise<Response>
readonly dispose: () => Promise<void>
}
try {
const response = await built.handler(new Request("http://localhost/", { headers: { "x-nonce": "prod-1" } }))
expect(response.status).toBe(200)
expectNonce(await response.text(), "prod-1")
} finally {
await built.dispose()
}
} finally {
await fs.rm(dir, { recursive: true, force: true })
}
}, 60_000)

// Bun's and Deno's `node:http` report a response as handled after the reload starts disposing the old entry.
it.skipIf(process.versions.bun !== undefined || process.versions.deno !== undefined)(
"disposes a server entry once its requests end, on reload and on close",
Expand Down
12 changes: 12 additions & 0 deletions packages/effect/test/ui/html/fixtures/vite/src/entry.nonce.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Effect } from "effect"
import { HttpRouter, HttpServerResponse } from "effect/http"
import { HtmlServer } from "effect/ui/html"
import { document } from "virtual:effect/ui/document"
import { App, AppRoute, People } from "../../routed.ts"

export default HttpRouter.add("GET", "*", ({ source }) =>
Effect.gen(function*() {
const nonce = source instanceof Request ? source.headers.get("x-nonce") ?? undefined : undefined
const rendered = yield* HtmlServer.renderToHtml(App, { route: AppRoute.Home() })
return HttpServerResponse.text(document(rendered, { nonce }), { contentType: "text/html; charset=utf-8" })
}).pipe(Effect.provide(People.layer)))
Loading