0

I am trying to implement SubResource Integrity to the webpage. I have an inline javascript which gets constructed dynamically based on certain variables,

https://example.com/<DYNAMIC_VALUE>.js

Separate contents of the file is rendered for each dynamic value specified as part of the URL. As integrity hash is computed based on the content, it is really not possible to precompute the hash for the script tag (as the DYNAMIC_VALUE can either be 1001, 1002,...n).

<-- script src="https://example.com/<DYNAMIC_VALUE>.js" integrity="???" crossorigin="anonymous"> 
</script -->

Is there any best practice for SRI with this kind of scenario involving dynamic variables? Thanks!

Vignesh T I
  • 782
  • 1
  • 7
  • 22
  • "*I am trying to implement SubResource Integrity to the webpage.*" - why? Do you control the server that delivers the script file? – Bergi Apr 04 '21 at 16:08
  • 1
    "*it is really not possible to precompute the hash*" - well, maybe not to **pre**compute it, but you still can compute it every time the dynamic value changes. – Bergi Apr 04 '21 at 16:09
  • @Bergi Thank you so much! I ment I am trying to add hash to the integrity within the script tag. My third party contents will load dynamically based on the certain parameters within my main javascript. Will it be possible to add combination of certain potential hashes to integrity of script tag of the 3rd party javascript files? – Vignesh T I Apr 04 '21 at 19:23
  • No, but if you have a whitelist you can compute a mapping of allowed dynamic values to their respective script hash, and then decide which `integrity` to use. – Bergi Apr 04 '21 at 21:20
  • It might be worth to note that SRI (i.e. the value of the `integrity` attribute) supports multiple values. For browsers, it is sufficient to have *any* of these hashes to match to allow loading and executing the script. So there is no need to have a "dynamically choose the right one" logic to be in place - you may simply put your allow-list as value (and let the browser do the choosing). – EagleRainbow Jul 19 '23 at 14:52

1 Answers1

1

I used this plugin to process my build files: https://github.com/emmercm/metalsmith-html-sri

I used a hook to run this after the completion of a build. I hope this helps or get you close enough.