-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
301 lines (258 loc) · 8.5 KB
/
worker.js
File metadata and controls
301 lines (258 loc) · 8.5 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
const ALLOWED_REPO = "XMOJ-Script-dev/ELXMOJ";
function json(data, status = 200) {
return new Response(JSON.stringify(data, null, 2), {
status,
headers: {
"content-type": "application/json; charset=UTF-8",
"cache-control": "no-store"
}
});
}
function parseVersionAndExt(fileToken) {
// Supports examples like:
// - 1.2.3.exe
// - v1.2.3-x64.exe
// - 1.2.3-beta.1.zip
const dotIndex = fileToken.lastIndexOf(".");
if (dotIndex <= 0 || dotIndex === fileToken.length - 1) {
return null;
}
const version = fileToken.slice(0, dotIndex).trim();
const ext = fileToken.slice(dotIndex + 1).trim().toLowerCase();
if (!version || !ext) {
return null;
}
return { version, ext };
}
function normalizeOs(osSegment) {
const raw = osSegment.toLowerCase();
if (["win", "windows"].includes(raw)) return "windows";
if (["linux"].includes(raw)) return "linux";
if (["mac", "macos", "darwin", "osx"].includes(raw)) return "macos";
return raw;
}
function normalizeArch(arch) {
const raw = arch.toLowerCase();
if (["x64", "amd64"].includes(raw)) return "x64";
if (["x86", "ia32", "i386"].includes(raw)) return "x86";
if (["arm64", "aarch64"].includes(raw)) return "arm64";
if (["armv7", "arm"].includes(raw)) return "armv7";
return raw;
}
function inferArchFromUserAgent(userAgent = "") {
const ua = userAgent.toLowerCase();
if (ua.includes("aarch64") || ua.includes("arm64")) return "arm64";
if (ua.includes("arm")) return "armv7";
if (ua.includes("x86_64") || ua.includes("win64") || ua.includes("x64")) return "x64";
if (ua.includes("i386") || ua.includes("i686") || ua.includes("x86")) return "x86";
return "x64";
}
function buildAssetName(version, os, arch, ext) {
return `ELXMOJ-${version}-${os}-${arch}.${ext}`;
}
function buildTagCandidates(version) {
const normalized = version.replace(/^v/i, "");
const candidates = [version, `v${normalized}`];
return [...new Set(candidates)];
}
function getGitHubToken(env) {
// Support common secret names and strip accidental wrapping quotes.
const raw = env.GITHUB_TOKEN || env.GITHUBTOKEN || env.GH_TOKEN || "";
return String(raw).trim().replace(/^['\"]|['\"]$/g, "");
}
function buildCacheKey(requestUrl, parsed) {
const keyUrl = new URL(requestUrl);
// Ensure cache key is stable and architecture-safe even when arch is inferred from UA.
keyUrl.searchParams.set("__resolved_arch", parsed.arch);
return new Request(keyUrl.toString(), { method: "GET" });
}
function withCacheStatus(response, status) {
const headers = new Headers(response.headers);
headers.set("x-downhelper-cache", status);
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers
});
}
async function fetchReleaseAsset(repo, version, assetName, request, env) {
const token = getGitHubToken(env);
const range = request.headers.get("range");
const upstreamHeaders = new Headers({
"user-agent": "downhelper-worker"
});
if (range) {
upstreamHeaders.set("range", range);
}
if (token) {
upstreamHeaders.set("authorization", `Bearer ${token}`);
}
const tagCandidates = buildTagCandidates(version);
let lastNon404 = null;
for (const tag of tagCandidates) {
const downloadUrl = `https://github.com/${repo}/releases/download/${encodeURIComponent(tag)}/${encodeURIComponent(assetName)}`;
const resp = await fetch(downloadUrl, {
method: "GET",
headers: upstreamHeaders,
redirect: "follow"
});
if (resp.ok || resp.status === 206) {
return { ok: true, response: resp, matchedTag: tag };
}
if (resp.status !== 404) {
lastNon404 = { status: resp.status, tag };
}
}
if (lastNon404) {
return { ok: false, errorType: "upstream", ...lastNon404 };
}
return { ok: false, errorType: "not_found", tagCandidates };
}
function pickResponseHeaders(upstreamHeaders, fallbackFileName) {
const headers = new Headers();
const passthrough = [
"content-type",
"content-length",
"content-range",
"accept-ranges",
"etag",
"last-modified",
"cache-control"
];
for (const key of passthrough) {
const value = upstreamHeaders.get(key);
if (value) {
headers.set(key, value);
}
}
if (!headers.get("content-disposition")) {
headers.set("content-disposition", `attachment; filename=\"${fallbackFileName}\"`);
}
// Versioned release assets are immutable and suitable for long edge/browser caching.
if (!headers.get("cache-control")) {
headers.set("cache-control", "public, max-age=86400, s-maxage=31536000, immutable");
}
// Keep browser/proxy behavior explicit.
headers.set("x-accel-source", "cloudflare-worker-proxy");
return headers;
}
function parseRequest(url, request) {
// Path format:
// /{os}/{version}[***].{ext}
// Example:
// /win/1.2.3.exe
// /linux/v1.2.3-x64.tar.gz (treated ext as gz; recommend simple ext like exe/zip/dmg/AppImage)
const parts = url.pathname.split("/").filter(Boolean);
if (parts.length < 2) {
return {
error: "Path should be /{os}/{version}.{ext}, for example /win/1.2.3.exe"
};
}
const os = normalizeOs(parts[0]);
const fileToken = parts.slice(1).join("/");
const parsed = parseVersionAndExt(fileToken);
if (!parsed) {
return {
error: "Cannot parse version/ext from URL. Expected /{os}/{version}.{ext}"
};
}
const requestArch = url.searchParams.get("arch");
const arch = normalizeArch(requestArch || inferArchFromUserAgent(request.headers.get("user-agent") || ""));
return {
os,
version: parsed.version,
ext: parsed.ext,
arch
};
}
export default {
async fetch(request, env) {
try {
const url = new URL(request.url);
if (url.pathname === "/" || url.pathname === "/healthz") {
return json({
ok: true,
usage: "GET /{os}/{version}.{ext}?arch=x64",
naming: "ELXMOJ-${version}-${os}-${arch}.${ext}",
repo: ALLOWED_REPO
});
}
const parsed = parseRequest(url, request);
if (parsed.error) {
return json({ ok: false, error: parsed.error }, 400);
}
const repo = ALLOWED_REPO;
const assetName = buildAssetName(parsed.version, parsed.os, parsed.arch, parsed.ext);
const cache = caches.default;
// Proxy download through Cloudflare Worker instead of redirecting.
// This keeps client URL on your domain and supports resume via Range.
const method = request.method.toUpperCase();
const range = request.headers.get("range");
const canUseCache = method === "GET" && !range;
const cacheKey = canUseCache ? buildCacheKey(request.url, parsed) : null;
if (canUseCache && cacheKey) {
const hit = await cache.match(cacheKey);
if (hit) {
return withCacheStatus(hit, "HIT");
}
}
const upstreamResult = await fetchReleaseAsset(repo, parsed.version, assetName, request, env);
if (!upstreamResult.ok) {
if (upstreamResult.errorType === "not_found") {
return json(
{
ok: false,
error: "Asset not found",
expectedAssetName: assetName,
repo,
tagCandidatesTried: upstreamResult.tagCandidates
},
404
);
}
return json(
{
ok: false,
error: "Failed to fetch GitHub asset",
status: upstreamResult.status,
matchedTag: upstreamResult.tag
},
502
);
}
const upstreamResp = upstreamResult.response;
if (!upstreamResp.ok && upstreamResp.status !== 206) {
return json(
{
ok: false,
error: "Failed to fetch GitHub asset",
status: upstreamResp.status,
expectedAssetName: assetName
},
502
);
}
const proxiedResponse = new Response(upstreamResp.body, {
status: upstreamResp.status,
headers: pickResponseHeaders(upstreamResp.headers, assetName)
});
if (canUseCache && cacheKey && proxiedResponse.status === 200) {
await cache.put(cacheKey, proxiedResponse.clone());
return withCacheStatus(proxiedResponse, "MISS-STORED");
}
if (range) {
return withCacheStatus(proxiedResponse, "BYPASS-RANGE");
}
return withCacheStatus(proxiedResponse, "BYPASS");
} catch (error) {
return json(
{
ok: false,
error: "Internal error",
detail: String(error)
},
500
);
}
}
};