-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathnonce-worker.js
69 lines (61 loc) · 1.78 KB
/
nonce-worker.js
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event.request));
});
function dec2hex(dec) {
return ("0" + dec.toString(16)).substr(-2);
}
function generateNonce() {
const arr = new Uint8Array(12);
crypto.getRandomValues(arr);
const values = Array.from(arr, dec2hex);
return [
btoa(values.slice(0, 5).join("")).substr(0, 14),
btoa(values.slice(5).join("")),
].join("/");
}
/**
* Respond to the request
* @param {Request} request
*/
async function handleRequest(request) {
const nonce = generateNonce();
const originresponse = await fetch(request, {
redirect: "manual",
});
const html = (await originresponse.text())
.replace(/DhcnhD3khTMePgXw/gi, nonce)
.replace(
'src="https://ajax.cloudflare.com',
`nonce="${nonce}" src="https://ajax.cloudflare.com`
)
.replace(
'src="https://static.cloudflareinsights.com',
`nonce="${nonce}" src="https://static.cloudflareinsights.com`
)
.replace(
'cloudflare-static/email-decode.min.js"',
`cloudflare-static/email-decode.min.js" nonce="${nonce}"`
);
const clientresponse = new Response(html, {
status: originresponse.status,
statusText: originresponse.statusText,
});
for (var [header, value] of originresponse.headers.entries()) {
if (["via", "server"].includes(header)) {
continue;
}
if (
[
"content-security-policy",
"content-security-policy-report-only",
].includes(header)
) {
// Reuse previously sent Content-Security-Policy
if (originresponse.status === 304) continue
value = value.replace(/DhcnhD3khTMePgXw/gi, nonce);
}
clientresponse.headers.set(header, value);
clientresponse.headers.set("cf-nonce-generator", "HIT");
}
return clientresponse;
}