From f0aaca315933dacf9028c4f3659b77670606c0b1 Mon Sep 17 00:00:00 2001 From: Niklas Haeusele Date: Fri, 3 May 2024 22:18:58 +0200 Subject: [PATCH] Read the csp meta's tag nonce attribute and fallback to the content attribute This PR allows Turbo to support https://github.com/rails/rails/pull/51729 to allow using the `nonce` attribute as well as the `content` attribute. As described in https://github.com/rails/rails/issues/51580#issue-2246912613 this makes it harder to extract the nonce value. Removed getMetaElement from public API as well. --- src/core/drive/progress_bar.js | 11 ++++------- src/util.js | 13 +++++++++++-- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/src/core/drive/progress_bar.js b/src/core/drive/progress_bar.js index 76e8e55a7..10c004101 100644 --- a/src/core/drive/progress_bar.js +++ b/src/core/drive/progress_bar.js @@ -1,4 +1,4 @@ -import { unindent, getMetaContent } from "../../util" +import { unindent, getCspNonce } from "../../util" export const ProgressBarID = "turbo-progress-bar" @@ -108,8 +108,9 @@ export class ProgressBar { const element = document.createElement("style") element.type = "text/css" element.textContent = ProgressBar.defaultCSS - if (this.cspNonce) { - element.nonce = this.cspNonce + const cspNonce = getCspNonce() + if (cspNonce) { + element.nonce = cspNonce } return element } @@ -119,8 +120,4 @@ export class ProgressBar { element.className = "turbo-progress-bar" return element } - - get cspNonce() { - return getMetaContent("csp-nonce") - } } diff --git a/src/util.js b/src/util.js index dcb15c31b..e67b4031c 100644 --- a/src/util.js +++ b/src/util.js @@ -5,7 +5,7 @@ export function activateScriptElement(element) { return element } else { const createdScriptElement = document.createElement("script") - const cspNonce = getMetaContent("csp-nonce") + const cspNonce = getCspNonce() if (cspNonce) { createdScriptElement.nonce = cspNonce } @@ -164,7 +164,7 @@ export function getVisitAction(...elements) { return isAction(action) ? action : null } -export function getMetaElement(name) { +function getMetaElement(name) { return document.querySelector(`meta[name="${name}"]`) } @@ -173,6 +173,15 @@ export function getMetaContent(name) { return element && element.content } +export function getCspNonce() { + const element = getMetaElement("csp-nonce") + + if (element) { + const { nonce, content } = element + return nonce == "" ? content : nonce + } +} + export function setMetaContent(name, content) { let element = getMetaElement(name)