Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subresource integrity for es6 import or worker

<script> accept integrity attribute, so I can load a module safely:

<script type="module"
  src="https://example.com/module.mjs"
  integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
  crossorigin="anonymous"
></script>

But how to keep safe when loading module inside script?

  • with import:
import foo from "https://example.com/module.mjs"
  • dynamic import:
import("https://example.com/module.mjs").then(console.log)
  • or even web worker:
const myWorker = new Worker('worker.js')
like image 734
Yukulélé Avatar asked Oct 03 '18 22:10

Yukulélé


People also ask

How does Subresource integrity work?

Subresource Integrity (SRI) is a security feature that enables browsers to verify that resources they fetch (for example, from a CDN) are delivered without unexpected manipulation. It works by allowing you to provide a cryptographic hash that a fetched resource must match.

What is integrity attribute in script tag?

The integrity attribute allows a browser to check the fetched script to ensure that the code is never loaded if the source has been manipulated. Subresource Integrity (SRI) is a W3C specification that allows web developers to ensure that resources hosted on third-party servers have not been altered.

How do you use SRI?

To use SRI, a website author wishing to include a resource from a third party can specify a cryptographic hash of the resource in addition to the location of the resource. Browsers fetching the resource can then compare the hash provided by the website author with the hash computed from the resource.


1 Answers

Please see this question

Is it possible to use subresource integrity with ES6 module imports?

You can use RequireJS, and transpile your code to AMD or UMD to achieve this. RequireJS has a hook onNodeCreated, which gives you access to the script tag before it is added to document. You can add the sri attribute onto the script tag:

onNodeCreated: function(node, config, module, path) { node.setAttribute('integrity', integrityForModule); node.setAttribute('crossorigin', 'anonymous'); }

credit: https://stackoverflow.com/a/37065379

I use Webpack (with a target of UMD) and RequireJS. With the relevant modules put in the external section of the webpack configuration file, so the modules are not compiled into the transpiled code.

like image 189
mayank1513 Avatar answered Sep 22 '22 08:09

mayank1513