async function handler(event) {
const req = event.request
const url = new URL(req.url)
const [, productCode, digestFragment] = url.pathname.match(/^\/products\/(\d+)(....)/)
const encoder = new TextEncoder()
const data = encoder.encode(productCode)
const hash = await crypto.subtle.digest("SHA-1", data)
const hashArray = Array.from(new Uint8Array(hash))
const checksum = hashArray.map(b => b.toString(16)).join('')
if (!`${checksum}`.startsWith(digestFragment)) {
console.log(`Block request, checksum is ${checksum}, expecting ${digestFragment}....`)
let headers = new Headers({ "Content-Type": "text/plain" })
return new Response("Not a valid product code", {
status: 400,
headers,
})
}
console.log(`Passed checksum based on MD5 hash`)
return fetch(req, {
backend: "origin_0",
})
}
addEventListener("fetch", (event) => event.respondWith(handler(event)))