The Problem
To enable the sub-resource integrity feature, a cryptographic hash string of the resource file is required. For static files or resources hosted by a CDN, this hash string would also be static and is often provided. However, for resources generated at build time, we will need to calculate the hash string for each build.
Fortunately, Rails supports this natively. We can enable the feature.
The Solution
1) Configure the hash algorithm. (E.g., sha 384)
config.assets.integrity_hash_algorithm = "sha384"
2) Enable integrity hash for stylesheets.
<%= stylesheet_link_tag :app, "data-turbo-track": "reload", integrity: true %>
3) If importmap is used, we need to configure `importmap.rb`
enable_integrity! # Add this
pin "application"
pin "@hotwired/turbo-rails", to: "turbo.min.js"
pin "@hotwired/stimulus", to: "stimulus.min.js"
pin "@hotwired/stimulus-loading", to: "stimulus-loading.js"
pin_all_from "app/javascript/controllers", under: "controllers"
The Result
You will now see the sha384 integrity hash generated.
<link rel="stylesheet" href="/assets/application-2b...51.css" data-turbo-track="reload" integrity="sha384-+tCm0...rFL+LZ" />
<link rel="modulepreload" href="/assets/application-bf...40.js" nonce="0M...0vg==" integrity="sha384-HzsVkF25...RiKvPXZO">