const textFileTypes = [
'application/javascript',
'text/html; charset=utf-8',
'text/css; charset=utf-8',
'text/xml; charset=utf-8'
];
const imageFileTypes = [
'image/jpeg'
];
function uint8ArrayToHex(arr) {
return Array.prototype.map
.call(arr, (x) => (('0' + x.toString(16)).slice(-2)))
.join('');
}
async function checkAndResponse(response, hash, algorithm) {
const headers = response.headers;
let checkHash = 'sorry! not match';
let data = null;
const contentType = headers.get('Content-Type');
if (textFileTypes.includes(contentType) || imageFileTypes.includes(contentType)) {
data = await response.arrayBuffer();
}
let ret = await crypto.subtle.digest({name: algorithm}, data);
checkHash = uint8ArrayToHex(new Uint8Array(ret));
headers.append(`X-Content-${algorithm}-Check`, checkHash);
if (checkHash !== hash) {
return new Response(null, {
headers,
status: 416
});
}
return new Response(data, {
headers,
status: 200
});
}
async function handleEvent(event) {
const response = await fetch(event.request);
if (response.status === 200) {
const headers = response.headers;
const hash = headers.get('X-Content-Sha256');
if (hash) {
return checkAndResponse(response, hash, 'Sha-256');
}
}
return response;
}
addEventListener('fetch', event => {
event.respondWith(handleEvent(event));
});
本页内容是否解决了您的问题?