-1

I'm using node.js, and I would like to set a CSP for certain things, such as JavaScript and CSS. I could use nonces and hashes, but how would I allow an HTML attribute, such as:

<div style="color:blue;" onclick="myFunction()"></div>

Since both of these are either CSS or JavaScript, my CSP blocks them. What can I do? I don't want to implement unsafe-inline.

code
  • 5,690
  • 4
  • 17
  • 39

1 Answers1

0

'unsafe-hashes' token was intended in CSP spec for HTML attributes. But it still is not supported in Safari.

Therefore you have a lot of programmer's opts whose depends how deeply you are ready to rewrite code:

  1. Do intercept the finished HTML code on the server before sending it to the browser, to pull out the style='...' and onclick='...' constructs, and to replace them with safe constructs (classes for styles and addEventListeners() for scripts).
    May be NodeJS has some useful plugins for that.

  2. With styles you can replace style="color:blue;" to data-style="color:blue;" and handle all of these by script like that.
    Just adapt it accordingly and use safe constructs like el.style.backgroundColor = ... but not unsafe Element.setAttribute(style).

  3. For inline event handlers you can use this techique (it's for jQuery, rewrite it to use addEventListeners).

  4. Totally rewrite code with best practice - separate markup and datas.
    Move all style="color:blue;" into classes (class='blueColor'`). You can assign classes names like 'color-blue', 'display-hidden' etc. for ease of understanding.
    Replace all inline event handlers by addEventListener() in a separate script.

granty
  • 7,234
  • 1
  • 14
  • 21