mirror of
https://github.com/discourse/discourse.git
synced 2024-12-25 16:16:18 +08:00
1672a24490
That way, the same value is used even if the helper is called in the context of different controllers
Followup to c8a1b49ddd
29 lines
822 B
Ruby
29 lines
822 B
Ruby
# frozen_string_literal: true
|
|
|
|
module Middleware
|
|
class CspScriptNonceInjector
|
|
PLACEHOLDER_HEADER = "Discourse-CSP-Nonce-Placeholder"
|
|
|
|
def initialize(app, settings = {})
|
|
@app = app
|
|
end
|
|
|
|
def call(env)
|
|
status, headers, response = @app.call(env)
|
|
|
|
if nonce_placeholder = headers.delete(PLACEHOLDER_HEADER)
|
|
nonce = SecureRandom.alphanumeric(25)
|
|
parts = []
|
|
response.each { |part| parts << part.to_s.gsub(nonce_placeholder, nonce) }
|
|
%w[Content-Security-Policy Content-Security-Policy-Report-Only].each do |name|
|
|
next if headers[name].blank?
|
|
headers[name] = headers[name].sub("script-src ", "script-src 'nonce-#{nonce}' ")
|
|
end
|
|
[status, headers, parts]
|
|
else
|
|
[status, headers, response]
|
|
end
|
|
end
|
|
end
|
|
end
|