Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Given code like this:

import { el, mount } from 'https://unpkg.com/[email protected]/dist/redom.es.js';

is there some way to enable subresource integrity verification to ensure that the CDN asset returns the expected content?

like image 261
jens1o Avatar asked Aug 21 '17 19:08

jens1o


3 Answers

You have to also define the module via

<script type="module" integrity="..." src="https://unpkg.com/[email protected]/dist/redom.es.js">

What you're asking specifically requires changes to ECMAScript itself and currently there's not even a proposal for it, so I don't expect it to appear anytime soon.


However in the case of UNPKG, if you trust UNPKG and Cloudflare not to mess with the content, you're fine. Neither npm nor the package author can modify the file as long as you specify the version.

like image 93
fregante Avatar answered Sep 24 '22 12:09

fregante


From an HTML document, you can use the <link rel="modulepreload"> element to perform that integrity check, which is unfortunately currently supported only in Blink browsers.

// default script
import( "https://unpkg.com/[email protected]/dist/redom.es.js" )
  .then( module => console.log( 'from default script:', typeof module.List ) )
  .catch( console.error );
<link rel="modulepreload" 
  href="https://unpkg.com/[email protected]/dist/redom.es.js"
  integrity="sha384-notthecorrectsha">
<script type="module">
  import { List } from "https://unpkg.com/[email protected]/dist/redom.es.js";
  console.log( 'from module script:', typeof List );
</script>

The same snippet without the integrity check:

// default script
import( "https://unpkg.com/[email protected]/dist/redom.es.js" )
  .then( module => console.log( 'from default script:', typeof module.List ) )
  .catch( console.error );
<link rel="modulepreload" 
  href="https://unpkg.com/[email protected]/dist/redom.es.js">
<script type="module">
  import { List } from "https://unpkg.com/[email protected]/dist/redom.es.js";
  console.log( 'from module script:', typeof List );
</script>

Note that this check would also apply to "sub-modules", but not to Workers.

like image 5
Kaiido Avatar answered Sep 21 '22 12:09

Kaiido


With Deno supporting such imports for its dependencies (and having no out-of-the-box package manager) and Node leaving open the chance for importing non-file URLS in the future, this issue becomes even more important.

While what @fregante mentions about there not being yet a proposal remains accurate, https://github.com/WICG/import-maps/issues/174 includes discussion, including via a referenced slide presentation, of some of the questions raised in modifying the syntax (e.g., transitive dependency cache invalidation) to support SRI as well as other possible alternatives.

like image 4
Brett Zamir Avatar answered Sep 25 '22 12:09

Brett Zamir