javascript / expert
Snippet
Runtime Subresource Integrity Validation for React Dynamic Chunk Loader
Dynamic code splitting in React components exposed to untrusted CDNs risks execution of tampered JavaScript bundles. Calculating cryptographic SHA-256 hashes of fetched chunk buffers using Web Crypto API before dynamic import invocation enforces subresource integrity at runtime.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
async function secureImport(moduleUrl, expectedSubresourceHash) {const response = await fetch(moduleUrl);const buffer = await response.arrayBuffer();const hashBuffer = await crypto.subtle.digest('SHA-256', buffer);const hashArray = Array.from(new Uint8Array(hashBuffer));const base64Hash = 'sha256-' + btoa(String.fromCharCode(...hashArray));if (base64Hash !== expectedSubresourceHash) {throw new SecurityError(`Subresource Integrity match failed for ${moduleUrl}`);}const blob = new Blob([buffer], { type: 'application/javascript' });const objectUrl = URL.createObjectURL(blob);return import(/* webpackIgnore: true */ objectUrl);}
react
Breakdown
1
const hashBuffer = await crypto.subtle.digest('SHA-256', buffer);
Computes a SHA-256 digest over raw binary module bytes utilizing the hardware-accelerated Web Crypto API.
2
const base64Hash = 'sha256-' + btoa(String.fromCharCode(...hashArray));
Converts the calculated digest byte array into a standard Base64-encoded Subresource Integrity (SRI) string.
3
if (base64Hash !== expectedSubresourceHash) {
Compares the runtime calculated hash against expected manifest signature, preventing execution of tampered payloads.
4
return import(/* webpackIgnore: true */ objectUrl);
Imports verified JavaScript execution code dynamically via blob URL after integrity clearance.