-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathworker.js
101 lines (75 loc) · 2.85 KB
/
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
export default {
async fetch(request, env, _ctx) {
const allowedOrigins = env.ALLOWED_ORIGINS.split(",");
const origin = request.headers.get("origin");
if (!allowedOrigins.includes(origin)) {
return notFound();
}
const { pathname, searchParams } = new URL(request.url);
const version = searchParams.has("v") ? searchParams.get("v") : null;
if (pathname.startsWith("/android")) {
return await respond(env, origin, pathname, version, "android", "", true);
}
if (pathname.startsWith("/ios")) {
return await respond(env, origin, pathname, version, "ios", ".zip", false);
}
if (pathname.startsWith("/desktop")) {
return await respond(env, origin, pathname, version, "desktop", ".gz", true);
}
return notFound(origin);
}
};
async function respond(env, origin, pathname, version, platform, extension, isAGzip) {
const regex = new RegExp("^[a-f0-9]{64}$");
const key = pathname.split("/")[2];
if (!regex.test(key)) {
return notFound(origin);
}
var url = env.DEBUGLOGS_ORIGIN + key + extension;
if (version !== null) {
url = env.DEBUGLOGS_ORIGIN + platform + "/" + version + "/" + key + extension;
}
const response = await fetch(url, { cf: { cacheTtl: 0 } });
if (!response.ok || response.headers.get("content-length") === "243") { // Hacky, but this is the length that errors have.
return notFound(origin);
}
const options = {
status: response.status,
headers: response.headers,
};
if (isAGzip) {
options.encodeBody = "manual";
}
const newResponse = new Response(response.body, options);
newResponse.headers.delete("cf-cache-status");
newResponse.headers.delete("age");
newResponse.headers.delete("last-modified");
newResponse.headers.delete("x-cache");
newResponse.headers.delete("via");
newResponse.headers.delete("date");
for (var pair of newResponse.headers.entries()) {
if (pair[0].startsWith("x-amz")) {
newResponse.headers.delete(pair[0]);
}
}
setAllowOrigin(newResponse, origin);
if (isAGzip) {
newResponse.headers.set("content-encoding", "gzip");
} else {
newResponse.headers.set("content-type", "application/zip");
}
newResponse.headers.set("cloudflare-cdn-cache-control", "no-store");
newResponse.headers.set("cache-control", "public, max-age=604800, immutable");
return newResponse;
}
function notFound(origin) {
let response = new Response("Not Found", { status: 404 });
if (origin) {
setAllowOrigin(response, origin);
}
return response;
}
function setAllowOrigin(response, origin) {
response.headers.set("access-control-allow-origin", origin);
response.headers.set("vary", "origin");
}