-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCSP Header SHA Generator.js
More file actions
37 lines (29 loc) · 1.84 KB
/
CSP Header SHA Generator.js
File metadata and controls
37 lines (29 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
async function generateCSPHashes() {
const htmlContent = document.documentElement.outerHTML;
const scriptRegex = /<script>([\s\S]*?)<\/script>/g;
const styleRegex = /<style>([\s\S]*?)<\/style>/g;
const svgStyleRegex = /<svg style([\s\S]*?)<\/svg>/g;
let cspHeader = "Content-Security-Policy: upgrade-insecure-requests; block-all-mixed-content; frame-ancestors 'self'; default-src 'self'; default-src 'self'; script-src 'self'";
let match;
while ((match = scriptRegex.exec(htmlContent)) !== null) {
const hashBuffer = await window.crypto.subtle.digest('SHA-256', new TextEncoder().encode(match));
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashBase64 = btoa(String.fromCharCode.apply(null, hashArray));
cspHeader += ` 'sha256-${hashBase64}'`;
}
cspHeader += "; style-src 'self'";
while ((match = styleRegex.exec(htmlContent)) !== null) {
const hashBuffer = await window.crypto.subtle.digest('SHA-256', new TextEncoder().encode(match));
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashBase64 = btoa(String.fromCharCode.apply(null, hashArray));
cspHeader += ` 'sha256-${hashBase64}'`;
}
while ((match = svgStyleRegex.exec(htmlContent)) !== null) {
const hashBuffer = await window.crypto.subtle.digest('SHA-256', new TextEncoder().encode(match));
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashBase64 = btoa(String.fromCharCode.apply(null, hashArray));
cspHeader += ` 'sha256-${hashBase64}'`;
}
console.log(cspHeader);
}
generateCSPHashes();