Read the CSP nonce on page load

Turbolinks replaces the CSP nonce <meta> tag on page change, but inline scripts inserted by UJS need the nonce from the initial page load. In general, it doesn't matter to UJS if the nonce changes after the page loads: only the initial value is relevant.
This commit is contained in:
George Claghorn 2019-03-08 15:25:24 -05:00 committed by GitHub
parent cc7483d3f0
commit ceeef26fd4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 10 additions and 4 deletions

View File

@ -2,6 +2,7 @@
fire, delegate
getData, $
refreshCSRFTokens, CSRFProtection
loadCSPNonce
enableElement, disableElement, handleDisabledElement
handleConfirm, preventInsignificantClick
handleRemote, formSubmitButtonClick,
@ -67,6 +68,7 @@ Rails.start = ->
delegate document, Rails.formInputClickSelector, 'click', formSubmitButtonClick
document.addEventListener('DOMContentLoaded', refreshCSRFTokens)
document.addEventListener('DOMContentLoaded', loadCSPNonce)
window._rails_loaded = true
if window.Rails is Rails and fire(document, 'rails:attachBindings')

View File

@ -1,4 +1,8 @@
# Content-Security-Policy nonce for inline scripts
cspNonce = Rails.cspNonce = ->
meta = document.querySelector('meta[name=csp-nonce]')
meta and meta.content
nonce = null
Rails.loadCSPNonce = ->
nonce = document.querySelector("meta[name=csp-nonce]")?.content
# Returns the Content-Security-Policy nonce for inline scripts.
Rails.cspNonce = ->
nonce ? Rails.loadCSPNonce()