node.jscontent-security-policytrix

Having difficulty getting the nonce workaround to work for trix-editor style-src content-security-policy violations


I am using the trix-editor (v1.3.1) in a node.js project. The module's trix.js includes some style elements that violate inline Content-Security-Policy rules. It seems that a workaround was implemented in v1.2.2, which requires that a nonce be included in a meta tag in the page where the trix editor is used, like so:

<meta name="csp-nonce" content="nonce-goes-here">

or

<meta name="trix-style-nonce" content="nonce-goes-here">

after which trix is expected to automatically pick up the nonce and use it in the style elements that generate the CSP violation.

I am using helmet to implement CSP, and create and use the nonce as suggested by the helmet instructions on npm, which is like this:

app.use((req, res, next) => {
  res.locals.cspNonce = crypto.randomBytes(16).toString("hex");
  next();
});
app.use(
  helmet.contentSecurityPolicy({
    useDefaults: true,
    directives: {
      styleSrc: ["'self'", "fonts.googleapis.com", (req, res) => `'nonce-${res.locals.cspNonce}'`],
    },
  })
);

Then, in the view I provide it using handlebars, like so:

<link href="/assets/vendor/trix/trix.css" rel="stylesheet" >
<meta name="trix-style-nonce" content="{{ cspNonce }}">
<meta name="csp-nonce" content="{{ cspNonce }}">

...

<script src='/assets/vendor/trix/trix.js'></script>

I can print out the nonce to the console and see that it is correctly provided anew to the page on each load. However, helmet continues to report CSP violations from the same trix style sources, so the nonce is not being attached to those style elements, it would seem. Any ideas what I am missing here?


Solution

  • My silly mistake: I had the meta element in the wrong place. In the meantime, I discovered that the nonce with meta name 'trix-style-nonce' doesn't work, while it does work with the meta name 'csp-nonce'.