如何处理 Highcharts 内联样式以防止 Content-Security-Policy 违规?

How can I deal with Highcharts inline styles to prevent Content-Security-Policy violations?

我有一个使用 Highcharts 向用户显示数据的应用程序,它运行良好。我现在正在将 Content-Security-Policy header 应用到此应用程序,再次,它工作正常(目前处于 Report-Only 模式)。

问题是 Highcharts 使用内联样式,这些显然被报告为违反 CSP。因此,我想防止这些违反政策的行为,而不仅仅是允许内联样式(这会降低拥有 CSP 的价值)。

因此我的问题是:有没有办法将随机数注入 Highcharts 以停止违规行为?

报错为:

[Report Only] Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' https: 'nonce-M/dyQoRv6ZpuH6yj1/q6tA=='". Either the 'unsafe-inline' keyword, a hash ('sha256-7wj/+4oyhC/Un8WKFeS81vcvueSVhV/Hk8Tuw/NlDC8='), or a nonce ('nonce-...') is required to enable inline execution. H @ highcharts.js:91

该应用程序是使用 Rails 6.0.2 使用 webpacker 和 Highcharts 7.2.1 构建的。

我的 config/initializers/content_security_policy.rb 文件几乎是默认文件:

# frozen_string_literal: true

Rails.application.config.content_security_policy do |policy|
  policy.default_src :self, :https
  policy.font_src    :self, :https, :data
  policy.img_src     :self, :https, :data
  policy.object_src  :none
  policy.script_src  :self, :https
  policy.style_src   :self, :https
  # If you are using webpack-dev-server then specify webpack-dev-server host
  policy.connect_src :self, :https, "http://localhost:3035", "ws://localhost:3035" if Rails.env.development? || Rails.env.test?

  # Specify URI for violation reports
  # policy.report_uri "/csp-violation-report-endpoint"
end

# If you are using UJS then enable automatic nonce generation
Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }

Rails.application.config.content_security_policy_report_only = true

如对原始问题的评论中所述,答案是启用 styledMode。这会停止使用内联样式的 HighCharts,而是使用样式表。这可能意味着更新默认样式表以反映您希望图表的外观,因为在默认模式下用于执行此操作的命令现在将不执行任何操作(对于颜色、线条、标记等)。

API: https://api.highcharts.com/highcharts/chart.styledMode