diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 105e5516cb4..8de56d2622a 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -66,12 +66,9 @@ module ApplicationHelper end def csp_nonce_placeholder - @csp_nonce_placeholder ||= - begin - placeholder = "[[csp_nonce_placeholder_#{SecureRandom.hex}]]" - response.headers["Discourse-CSP-Nonce-Placeholder"] = placeholder - placeholder - end + response.headers[ + ::Middleware::CspScriptNonceInjector::PLACEHOLDER_HEADER + ] ||= "[[csp_nonce_placeholder_#{SecureRandom.hex}]]" end def shared_session_key diff --git a/lib/middleware/csp_script_nonce_injector.rb b/lib/middleware/csp_script_nonce_injector.rb index 3f280a35ad1..eeeea4c6b28 100644 --- a/lib/middleware/csp_script_nonce_injector.rb +++ b/lib/middleware/csp_script_nonce_injector.rb @@ -2,6 +2,8 @@ module Middleware class CspScriptNonceInjector + PLACEHOLDER_HEADER = "Discourse-CSP-Nonce-Placeholder" + def initialize(app, settings = {}) @app = app end @@ -9,7 +11,7 @@ module Middleware def call(env) status, headers, response = @app.call(env) - if nonce_placeholder = headers.delete("Discourse-CSP-Nonce-Placeholder") + if nonce_placeholder = headers.delete(PLACEHOLDER_HEADER) nonce = SecureRandom.alphanumeric(25) parts = [] response.each { |part| parts << part.to_s.gsub(nonce_placeholder, nonce) }