lite-youtube icon indicating copy to clipboard operation
lite-youtube copied to clipboard

Add a nonce for CSP policy enforcement

Open heddn opened this issue 2 years ago • 3 comments

Is there a way I can add a nonce to the short-code that would work for CSP?

                                <lite-youtube
                                    videoid="abc123"
                                    videotitle="Video of cats"
                                    autoload
                                    nonce="{{ csp_nonce() }}"
                                ></lite-youtube>
                                ```
Adding a nonce didn't work.

heddn avatar Feb 09 '22 17:02 heddn

CSP more than a nonce for this. One, you'd have to update your CSP rules for img-src and frame-src (otherwise things will block and youtube's iframe will not load):

img-src 'self' https://i.ytimg.com; 
frame-src youtube.com www.youtube.com;

And example of such action is here: https://github.com/justinribeiro/blog-pwa/blob/main/appengine/main.py#L45

In terms of a nonce, it wouldn't be applied to the element but rather the script. A high level example of that would be something along the lines of:

<script type="module" src="./where/ever/lite-youtube/build/is" nonce="{your_nonce}"></script>

This assumes several things of course; that the file is not part of a bigger build, that you're not simply using script-src with a sha256 of the contents, et cetera.

How are you importing the lite-youtube? From the CDN or in your build, or somewhere local?

justinribeiro avatar Feb 09 '22 18:02 justinribeiro

I add import '@justinribeiro/lite-youtube'; to my app.js and have laravel-mix configured.

I also added: img-src 'self' https://i.ytimg.com; frame-src youtube.com www.youtube.com;

But it is complaining about style-src Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' fonts.googleapis.com". Either the 'unsafe-inline' keyword, a hash ('sha256-zGutAkW/6q1r8uR50tTPbFplxtBTvDjhu0oQPGZqU8A='), or a nonce ('nonce-...') is required to enable inline execution.

heddn avatar Feb 09 '22 19:02 heddn

Ahhh, yes, the style-src issue. That's my bad; I forget that'll throw because of the shadowDom inject, better known as the old 627 issue https://github.com/WICG/webcomponents/issues/627. Your original question makes a lot more sense to me know. :-)

What you likely want to do is use strict-dynamic with script-src, since your lite-youtube is in the build pack and nonce will be applied to that script. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src#strict-dynamic Offhand, I don't have an example of this, but I believe web.dev uses lite-youtube with CSP in a similar fashion (with a single loader script as I recall).

justinribeiro avatar Feb 09 '22 20:02 justinribeiro