Add unpkg to Content Security Policy (CSP)

1k views Asked by At

How can I add specific libraries (ES modules) fetched through Unpkg to my Content Security Policy (CSP) policy - i.e. without allowing everything from Unpkg?

For example, this is how I add provide one library:

<script
  type="module"
  src="https://unpkg.com/web-social-share@latest/dist/websocialshare/websocialshare.esm.js"></script>

I tried various solution such as https://unpkg.com/web-social-share@latest/* or https://unpkg.com/web-social-share@* for my script-src policy but all resulted in an error:

Refused to load the script 'https://unpkg.com/web-social-share@latest/dist/websocialshare/websocialshare.esm.js' because it violates the following Content Security Policy directive: "script-src 'self' ...

Anything that seems to work is allowing everything from Unpkg which I would like to avoid.

<meta
  http-equiv="Content-Security-Policy"
  content="default-src 'self';
    script-src 'self' https://unpkg.com/;" />
1

There are 1 answers

1
Halvor Sakshaug On

This is available only in CSP level 3: https://www.w3.org/TR/CSP3/#external-hash. But unfortunately you'll still need to support level 2. You can however use Subresource Integrity in most browsers.