addEventListener("fetch", event => event.respondWith(app(event)));
const backend = "origin_0";
async function app(event) {
try {
const req = event.request;
const anonymousRequest = req.clone();
const anonymousRequestDifferentOrigin = req.clone();
let cookieResponse = await fetch(req, {
backend: backend,
});
let cookieBuffer = await cookieResponse.arrayBuffer();
if (anonymousRequest.headers.has("cookie")) {
anonymousRequest.headers.delete("cookie");
let backendResponse = await fetch(anonymousRequest, {
backend: backend,
cacheOverride: new CacheOverride("pass"),
});
let responseBuffer = await backendResponse.arrayBuffer();
if (cookieResponse.status != backendResponse.status || !buffersAreEqual(cookieBuffer, responseBuffer)) {
console.log("URL requires cookie: " + req.url);
} else {
console.log("URL appears not to require a cookie: " + req.url);
}
} else {
console.log("Incoming request did not include a cookie: " + req.url);
}
if (!anonymousRequestDifferentOrigin.headers.has("Origin")) {
anonymousRequestDifferentOrigin.headers.set("Origin", "fastly.com");
let backendResponse = await fetch(anonymousRequestDifferentOrigin, {
backend: backend,
cacheOverride: new CacheOverride("pass"),
});
let responseBuffer = await backendResponse.arrayBuffer();
if (cookieResponse.status != backendResponse.status || !buffersAreEqual(cookieBuffer, responseBuffer)) {
console.log("URL requires same origin: " + req.url);
} else {
console.log("URL appears not to require same origin: " + req.url);
}
} else {
console.log("Incoming request is already cross-origin: " + req.url);
}
return new Response(cookieBuffer, {
headers: cookieResponse.headers,
status: cookieResponse.status,
});
}
catch (e) {
console.error(e);
return new Response("Error when processing " + req.url + ":" + String(e), {status: 500});
}
}
function buffersAreEqual(a, b) {
const aArray = new Uint8Array(a);
const bArray = new Uint8Array(b);
if (aArray.length != bArray.length) {
return false;
}
for (let i = 0; i < aArray.length; i++) {
if (aArray[i] !== bArray[i]) {
return false;
}
}
return true;
}