Skip to content

Commit

Permalink
Merge pull request #1254 from codergeek121/use-nonce-and-content-attr…
Browse files Browse the repository at this point in the history
…ibute-for-csp

Read the csp meta tag nonce attribute and fall back to content
  • Loading branch information
jorgemanrubia authored Oct 15, 2024
2 parents 73cde75 + f0aaca3 commit 7d915cc
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 @@ -169,7 +169,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 @@ -178,6 +178,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 7d915cc

Please sign in to comment.