Skip to content

Fix CSP nonce handling for Turbo Stream scripts#1

Open
tubaxenor wants to merge 1 commit intomainfrom
fix/stream-element-csp-nonce
Open

Fix CSP nonce handling for Turbo Stream scripts#1
tubaxenor wants to merge 1 commit intomainfrom
fix/stream-element-csp-nonce

Conversation

@tubaxenor
Copy link
Copy Markdown
Owner

Summary

  • StreamElement.templateContent clones template content via cloneNode(true), but browsers hide nonce attribute values after HTML parsing (Chrome nonce hiding). The cloned scripts have nonce="" and get blocked by CSP's script-src-elem directive. Fix: activate scripts in the cloned content using activateScriptElement, consistent with how FrameRenderer and ErrorRenderer already handle scripts.

  • activateScriptElement sets the CSP nonce before copyElementAttributes, which then overwrites it with an empty string (from the source element's hidden nonce). Fix: move nonce assignment after copyElementAttributes.

Related upstream issues

Test plan

  • Existing stream script test (receiving a message with a <script> element) continues to pass
  • Verify in a Rails app with CSP nonce-based script-src-elem that inline scripts in Turbo Stream responses execute without CSP violations

🤖 Generated with Claude Code

Two issues addressed:

1. StreamElement.templateContent clones template content via cloneNode(true),
   but browsers hide nonce attribute values after HTML parsing (Chrome security
   feature). The cloned scripts have nonce="" and get blocked by CSP's
   script-src-elem directive. Fix: activate scripts in the cloned content using
   activateScriptElement, consistent with FrameRenderer and ErrorRenderer.

2. activateScriptElement sets the CSP nonce before copyElementAttributes, which
   then overwrites it with an empty string (from the source element's hidden
   nonce). Fix: move nonce assignment after copyElementAttributes.

Fixes inline script CSP violations in Turbo Stream responses when a
Content-Security-Policy with nonce-based script-src-elem is in effect.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant