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.
  • Loading branch information
codergeek121 committed May 3, 2024
1 parent 9fb05e3 commit f2b0e4c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 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")
}
}
11 changes: 10 additions & 1 deletion 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 @@ -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 f2b0e4c

Please sign in to comment.