From ab45c5c42ce84f08d9be75d2f58f1f9d91bb48fa Mon Sep 17 00:00:00 2001 From: jviide Date: Thu, 20 Jul 2023 12:56:09 +0300 Subject: [PATCH] fix: generate one Content-Security-Policy nonce per render (#1480) Co-authored-by: Marvin Hagemeister --- src/server/render.ts | 42 +++++++++++++++++------------------------- tests/main_test.ts | 30 ++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 25 deletions(-) diff --git a/src/server/render.ts b/src/server/render.ts index 9f9068a6..7f4b9f47 100644 --- a/src/server/render.ts +++ b/src/server/render.ts @@ -309,28 +309,27 @@ export async function render( bodyHtml = bodyHtml as unknown as string; - const moduleScripts: [string, string][] = []; - - for (const url of opts.imports) { - const randomNonce = crypto.randomUUID().replace(/-/g, ""); - if (csp) { - csp.directives.scriptSrc = [ - ...csp.directives.scriptSrc ?? [], - nonce(randomNonce), - ]; + let randomNonce: undefined | string; + function getRandomNonce(): string { + if (randomNonce === undefined) { + randomNonce = crypto.randomUUID().replace(/-/g, ""); + if (csp) { + csp.directives.scriptSrc = [ + ...csp.directives.scriptSrc ?? [], + nonce(randomNonce), + ]; + } } - moduleScripts.push([url, randomNonce]); + return randomNonce; + } + + const moduleScripts: [string, string][] = []; + for (const url of opts.imports) { + moduleScripts.push([url, getRandomNonce()]); } const preloadSet = new Set(); function addImport(path: string): string { - const randomNonce = crypto.randomUUID().replace(/-/g, ""); - if (csp) { - csp.directives.scriptSrc = [ - ...csp.directives.scriptSrc ?? [], - nonce(randomNonce), - ]; - } const url = bundleAssetUrl(`/${path}`); preloadSet.add(url); for (const depPath of opts.dependenciesFn(path)) { @@ -412,15 +411,8 @@ export async function render( // Append the inline script. if (script !== "") { - const randomNonce = crypto.randomUUID().replace(/-/g, ""); - if (csp) { - csp.directives.scriptSrc = [ - ...csp.directives.scriptSrc ?? [], - nonce(randomNonce), - ]; - } bodyHtml += - ``; + ``; } if (ctx.styles.length > 0) { diff --git a/tests/main_test.ts b/tests/main_test.ts index 4e53a472..a44c5c64 100644 --- a/tests/main_test.ts +++ b/tests/main_test.ts @@ -896,3 +896,33 @@ Deno.test({ sanitizeOps: false, sanitizeResources: false, }); + +Deno.test({ + name: "Generate a single nonce value per page", + + async fn() { + await withPageName("./tests/fixture/main.ts", async (page, address) => { + await page.goto(address); + await page.waitForSelector("p"); + + const nonceValues = await page.evaluate(() => + Array.from( + new Set( + Array.from(document.querySelectorAll("[nonce]")).map((el) => + el.getAttribute("nonce") + ), + ), + ) + ); + + assertEquals( + nonceValues.length, + 1, + `Found more than 1 nonce value per render`, + ); + }); + }, + + sanitizeOps: false, + sanitizeResources: false, +});