Skip to content

Commit

Permalink
Merge pull request #36 from aeris/csp-nonce
Browse files Browse the repository at this point in the history
Support for nonce CSP
  • Loading branch information
igorkasyanchuk authored Dec 18, 2024
2 parents c57b4b3 + 16473ad commit 6dcd66f
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions lib/rails_live_reload/middleware/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ def call!(env)
@app.call(env)
end
else
request = Rack::Request.new(env)
request = ActionDispatch::Request.new(env)
status, headers, body = @app.call(env)

if html?(headers) && (status == 500 || (status.to_s =~ /20./ && request.get?))
return inject_rails_live_reload(status, headers, body)
return inject_rails_live_reload(request, status, headers, body)
end

[status, headers, body]
Expand All @@ -28,25 +28,26 @@ def call!(env)

private

def inject_rails_live_reload(status, headers, body)
def inject_rails_live_reload(request, status, headers, body)
response = Rack::Response.new([], status, headers)


nonce = request&.content_security_policy_nonce
if String === body
response.write make_new_response(body)
response.write make_new_response(body, nonce)
else
body.each { |fragment| response.write make_new_response(fragment) }
body.each { |fragment| response.write make_new_response(fragment, nonce) }
end
body.close if body.respond_to?(:close)
response.finish
end

def make_new_response(body)
def make_new_response(body, nonce)
index = body.rindex(/<\/body>/i) || body.rindex(/<\/html>/i)
return body if index.nil?

body.insert(index, <<~HTML.html_safe)
<script defer type="text/javascript" src="#{RailsLiveReload.config.url}/script"></script>
<script id="rails-live-reload-options" type="application/json">
<script id="rails-live-reload-options" type="application/json" nonce="#{nonce}">
#{{
files: CurrentRequest.current.data.to_a,
time: Time.now.to_i,
Expand Down

0 comments on commit 6dcd66f

Please sign in to comment.