Allow inline scripts to have a nonce added #644
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
The script insertion method introduced in 1.6.0 is very clean and avoids using
eval()
, which is great. However, it breaks when using CSPs that require a nonce for inline scripts. WhileevalScript
does try to copy all the incoming script's attributes, this doesn't work for nonce because a) it appears to be filtered from the attributes and b) wouldn't actually match the nonce for the original page anyway, since each request's nonce is different in most setups.The CSP
script-src 'self' 'nonce-9190f323fb54b166d23a0ad59387dabf' 'unsafe-eval'
used to work with HTMX, but no longer does if you were relying on inline scripts. Changing it to add 'unsafe-inline' would work, but at that point there feels like almost no point to having the CSP.This PR adds an
inlineScriptNonce
configuration setting to allow nonce-based CSPs to still work with the new script insertion method. It's not flawless from a security standpoint--it essentially just allows all inline scripts in HTMX requests to work, but at least then you can still have a stronger CSP for non-HTMX pages/requests. This also still isn't ideal since now an attacker could grab the nonce from the HTML.Usage-wise, it's working for me using this in my base HTML:
Which renders to include the original page's nonce:
Again, not flawless but at least you put a slight barrier up! Truly security conscious people should probably just put the dang script in a file and not inline.