Class: Middleware::CspScriptNonceInjector
- Inherits:
-
Object
- Object
- Middleware::CspScriptNonceInjector
- Defined in:
- lib/middleware/csp_script_nonce_injector.rb
Constant Summary collapse
- PLACEHOLDER_HEADER =
"Discourse-CSP-Nonce-Placeholder"
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app, settings = {}) ⇒ CspScriptNonceInjector
constructor
A new instance of CspScriptNonceInjector.
Constructor Details
#initialize(app, settings = {}) ⇒ CspScriptNonceInjector
Returns a new instance of CspScriptNonceInjector.
7 8 9 |
# File 'lib/middleware/csp_script_nonce_injector.rb', line 7 def initialize(app, settings = {}) @app = app end |
Instance Method Details
#call(env) ⇒ Object
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/middleware/csp_script_nonce_injector.rb', line 11 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 |