Skip to content

Commit

Permalink
Read the csp meta's tag nonce attribute and fallback to the content a…
Browse files Browse the repository at this point in the history
…ttribute

This PR allows Turbo to support rails/rails#51729 to allow using the `nonce` attribute as well as the `content` attribute.

As described in rails/rails#51580 (comment) this makes it harder to extract the nonce value.
Removed getMetaElement from public API as well.
  • Loading branch information
codergeek121 committed Sep 26, 2024
1 parent 9fb05e3 commit f0aaca3
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 9 deletions.
11 changes: 4 additions & 7 deletions src/core/drive/progress_bar.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { unindent, getMetaContent } from "../../util"
import { unindent, getCspNonce } from "../../util"

export const ProgressBarID = "turbo-progress-bar"

Expand Down Expand Up @@ -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
}
Expand All @@ -119,8 +120,4 @@ export class ProgressBar {
element.className = "turbo-progress-bar"
return element
}

get cspNonce() {
return getMetaContent("csp-nonce")
}
}
13 changes: 11 additions & 2 deletions src/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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}"]`)
}

Expand All @@ -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)

Expand Down

0 comments on commit f0aaca3

Please sign in to comment.