Skip to content

Commit f2b0e4c

Browse files
committed
Read the csp meta's tag nonce attribute and fallback to the content attribute
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.
1 parent 9fb05e3 commit f2b0e4c

File tree

2 files changed

+14
-8
lines changed

2 files changed

+14
-8
lines changed

src/core/drive/progress_bar.js

+4-7
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { unindent, getMetaContent } from "../../util"
1+
import { unindent, getCspNonce } from "../../util"
22

33
export const ProgressBarID = "turbo-progress-bar"
44

@@ -108,8 +108,9 @@ export class ProgressBar {
108108
const element = document.createElement("style")
109109
element.type = "text/css"
110110
element.textContent = ProgressBar.defaultCSS
111-
if (this.cspNonce) {
112-
element.nonce = this.cspNonce
111+
const cspNonce = getCspNonce()
112+
if (cspNonce) {
113+
element.nonce = cspNonce
113114
}
114115
return element
115116
}
@@ -119,8 +120,4 @@ export class ProgressBar {
119120
element.className = "turbo-progress-bar"
120121
return element
121122
}
122-
123-
get cspNonce() {
124-
return getMetaContent("csp-nonce")
125-
}
126123
}

src/util.js

+10-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ export function activateScriptElement(element) {
55
return element
66
} else {
77
const createdScriptElement = document.createElement("script")
8-
const cspNonce = getMetaContent("csp-nonce")
8+
const cspNonce = getCspNonce()
99
if (cspNonce) {
1010
createdScriptElement.nonce = cspNonce
1111
}
@@ -173,6 +173,15 @@ export function getMetaContent(name) {
173173
return element && element.content
174174
}
175175

176+
export function getCspNonce() {
177+
const element = getMetaElement("csp-nonce")
178+
179+
if (element) {
180+
const { nonce, content } = element
181+
return nonce == "" ? content : nonce
182+
}
183+
}
184+
176185
export function setMetaContent(name, content) {
177186
let element = getMetaElement(name)
178187

0 commit comments

Comments
 (0)