webpacker 和 injectStylesIntoStyleTag.js 破坏了 CSP

webpacker and injectStylesIntoStyleTag.js breaks CSP

我在 rails 应用的 CSP 上的 ruby 在我添加 webpacker 之前一直运行良好。现在我明白了:

Content Security Policy: The page’s settings observed the loading of a resource at inline (“style-src”). A CSP report is being sent. injectStylesIntoStyleTag.js:117
Content Security Policy: The page’s settings observed the loading of a resource at inline (“style-src”). A CSP report is being sent. injectStylesIntoStyleTag.js:190

有问题的代码如下所示:

function insertStyleElement(options) {
  var style = document.createElement('style');
  
  ...

  if (typeof options.insert === 'function') {
    options.insert(style);
  } else {
    var target = getTarget(options.insert || 'head');

    if (!target) {
      throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");
    }

    target.appendChild(style); //LINE 117//
  }

  return style;
}

并且:

function applyToTag(style, options, obj) {
  var css = obj.css;

  ...

  if (style.styleSheet) {
    style.styleSheet.cssText = css;
  } else {
    while (style.firstChild) {
      style.removeChild(style.firstChild);
    }

    style.appendChild(document.createTextNode(css)); //LINE 190//
  }
}

如何添加随机数? This 说要将 __webpack_nonce__ = 'random'; 添加到我的条目文件(在本例中为 app/javascript/packs/application.js),但是将那个随机数添加到我的 csp 文件对 style-src 违规没有影响。在这种情况下,看起来像这样:config.style_src :self, 'https://fonts.googleapis.com', 'nonce-random'

我不知何故无法在源代码中找到注入的样式,但答案是在 Chrome 中打开页面(我使用的是 Firefox)并从控制台日志中复制 sha-256 哈希进入应用程序的 CSP。