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 70 71 72 73 74 75 76 77 78 79 80
| export default { async fetch(request, env) { const ALLOWED_DOMAINS = [ "https://1997.run", "https://www.1997.run" ];
const origin = request.headers.get("Origin") || ""; const referer = request.headers.get("Referer") || ""; const isAllowed = ALLOWED_DOMAINS.some(domain => origin.startsWith(domain) || referer.startsWith(domain) );
if (request.method === "OPTIONS") { if (!isAllowed) { return new Response("Forbidden: Invalid domain.", { status: 403, headers: { "Access-Control-Allow-Origin": origin || ALLOWED_DOMAINS[0], "Access-Control-Allow-Methods": "GET,HEAD,OPTIONS", "Access-Control-Allow-Headers": request.headers.get("Access-Control-Request-Headers") || "*", "Access-Control-Max-Age": "86400", }, }); } return new Response(null, { status: 204, headers: { "Access-Control-Allow-Origin": origin || ALLOWED_DOMAINS[0], "Access-Control-Allow-Methods": "GET,HEAD,OPTIONS", "Access-Control-Allow-Headers": request.headers.get("Access-Control-Request-Headers") || "*", "Access-Control-Max-Age": "86400", }, }); }
if (!isAllowed) { return new Response("Forbidden: Invalid domain.", { status: 403, headers: { "Access-Control-Allow-Origin": origin || ALLOWED_DOMAINS[0] } }); }
if (!["GET", "HEAD"].includes(request.method)) { return new Response("Method Not Allowed", { status: 405 }); }
const url = new URL(request.url); const objectKey = decodeURIComponent(url.pathname.slice(1));
if (!objectKey || objectKey.length > 1024) { return new Response("Bad Request", { status: 400 }); }
const object = await env.R2_BUCKET.get(objectKey); if (!object) { return new Response("Not Found", { status: 404 }); }
const headers = new Headers(); object.writeHttpMetadata(headers); headers.set("etag", object.httpEtag); headers.set("Cache-Control", "public, max-age=31536000, immutable");
headers.set("Access-Control-Allow-Origin", origin || ALLOWED_DOMAINS[0]); headers.set("Vary", "Origin");
const ifNoneMatch = request.headers.get("If-None-Match"); if (ifNoneMatch && ifNoneMatch === object.httpEtag) { return new Response(null, { status: 304, headers }); }
return new Response(object.body, { headers }); } };
|