UNPKG

1.13 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5}); // Supported algorithms listed in the spec: https://w3c.github.io/webappsec-subresource-integrity/#hash-functions
6
7exports.SRI_HASH_ALGORITHMS = ['sha256', 'sha384', 'sha512'];
8
9function calculateBase64IntegrityFromFilename(path, hashFunction, hashDigest) {
10 if (!isHashAlgorithmSupportedByBrowsers(hashFunction)) {
11 return false;
12 }
13
14 if (hashDigest && hashDigest !== 'hex') {
15 return false;
16 }
17
18 const chunkInfo = // Anything ending in a hyphen + hex string (e.g., `foo-00000000.js`).
19 path.match(/.+?-(?:([a-f0-9]+))?\.[^.]+$/) || // Unnamed dynamic imports like `00000000.js`.
20 path.match(/^([a-f0-9]+)\.[^.]+$/);
21
22 if (!chunkInfo || !chunkInfo[1]) {
23 return false;
24 }
25
26 const hexHash = chunkInfo[1];
27 const base64Hash = Buffer.from(hexHash, 'hex').toString('base64');
28 return `${hashFunction}-${base64Hash}`;
29}
30
31exports.calculateBase64IntegrityFromFilename = calculateBase64IntegrityFromFilename;
32
33function isHashAlgorithmSupportedByBrowsers(hashFunction) {
34 return exports.SRI_HASH_ALGORITHMS.includes(hashFunction);
35}
\No newline at end of file