hustcc / size-sensor

:herb: 1Kb DOM element size sensor which will callback when size changed.
https://git.hust.cc/size-sensor
164 stars 23 forks source link

Allow usage of this library without forcing CSP `unsafe-inline` #12

Closed tzimmermann closed 4 years ago

tzimmermann commented 4 years ago

We are currently trying to enforce stricter Content Security Policies on our webapp. The webapp uses echarts-for-react, and this one in turn uses size-sensor.

Unfortunately, we are forced to set style-src: 'unsafe-inline' due to this dependency, because there is a code snippet in object.js that sets an inline style here: https://github.com/hustcc/size-sensor/blob/3e71e3d9ae83b533c25ed9d2d971f077d7b4301a/src/sensors/object.js#L30

It would be really good if we could enhance the security of our webapp by removing unsafe-inline and still be able to use echarts.

I see a couple of ways to fix this:

hustcc commented 4 years ago

The second way means add style as below:

<style>
   .size-sensor-object {
     // ...
   }
</style>

then use class name instead of inline style? What the meaning of a nonce attribute?

tzimmermann commented 4 years ago

then use class name instead of inline style? What the meaning of a nonce attribute?

It is basically a way to whitelist which scripts/styles are allowed to be executed on a page to protect against certain scripting attacks.

The nonce is a random token that is generated on the server new for every page visit.

Look for example here for a detailed explanation: https://stackoverflow.com/a/42924000

We would need a way to "inject" our nonce attribute from the document into the <style> tag that size-sensor generates. Not sure what is best practice here for other libraries, but I quite like JSS's approach, they read the value from the document's <meta> tag.

hustcc commented 4 years ago

@tzimmermann can give me a pr for this? I would like to see whether it will increase the complexity of usage.