Skip to content

Commit 06786e4

Browse files
committed
Generate the integrity hash from compiled asset content
1 parent b1445c2 commit 06786e4

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

lib/propshaft/resolver/dynamic.rb

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ def integrity(logical_path)
1616
hash_algorithm = load_path.integrity_hash_algorithm
1717

1818
if hash_algorithm && (asset = find_asset(logical_path))
19-
asset.integrity(hash_algorithm:)
19+
generate_integrity(asset, hash_algorithm:)
2020
end
2121
end
2222

@@ -30,5 +30,25 @@ def read(logical_path, options = {})
3030
def find_asset(logical_path)
3131
load_path.find(logical_path)
3232
end
33+
34+
def generate_integrity(asset, hash_algorithm:)
35+
# Following the Subresource Integrity spec draft
36+
# https://w3c.github.io/webappsec-subresource-integrity/
37+
# allowing only sha256, sha384, and sha512
38+
bitlen = case hash_algorithm
39+
when "sha256"
40+
256
41+
when "sha384"
42+
384
43+
when "sha512"
44+
512
45+
else
46+
raise(StandardError.new("Subresource Integrity hash algorithm must be one of SHA2 family (sha256, sha384, sha512)"))
47+
end
48+
49+
content = load_path.compilers.compile(asset)
50+
51+
[hash_algorithm, Digest::SHA2.new(bitlen).base64digest(content)].join("-")
52+
end
3353
end
3454
end

0 commit comments

Comments
 (0)