-
Notifications
You must be signed in to change notification settings - Fork 76
/
wb-install-worker.js
100 lines (87 loc) · 2.47 KB
/
wb-install-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
const nodes = {
'/brew.sh': {
list: [
"https://gitee.com/ineo6/homebrew-install/raw/master/install.sh",
"https://raw.githubusercontent.com/ineo6/homebrew-install/master/install.sh"
]
}
}
function reverse(promise) {
return new Promise((resolve, reject) => Promise.resolve(promise).then(reject, resolve));
}
function promiseAny(iterable) {
return reverse(Promise.all([...iterable].map(reverse)));
};
async function contactServer(server) {
return new Promise((resolve, reject) => {
fetch(server, {
method: "GET"
}).then(response => {
resolve({
"server": server,
});
}).catch(function (error) {
reject(error);
});
});
}
addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event));
});
async function forwardRequestGET(apiURL) {
return new Promise((resolve, reject) => {
fetch(apiURL, {
method: "GET",
redirect: "follow"
}).then(response => {
resolve(response.text());
}).catch(function (error) {
reject(error);
});
});
}
async function handleRequest(event) {
const request = event.request;
const method = request.method.toUpperCase();
const urlStr = request.url
const urlObj = new URL(urlStr)
if (urlObj.pathname) {
const scriptConfig = nodes[urlObj.pathname]
if (scriptConfig && scriptConfig.list) {
return await proxyRequest(request, scriptConfig.list)
}
}
return Response.redirect('https://brew.idayer.com', 302)
}
/**
* Respond to the request
* @param {Request} request
*/
async function proxyRequest(request, nodeList) {
const country = request.headers.get('cf-ipcountry');
const servers = [];
for (const server of nodeList) {
servers.push(contactServer(server));
}
const load = await promiseAny(servers);
const forwardedURL = load['server'];
const method = request.method.toUpperCase();
let result;
let res;
try {
if (method === "GET") {
result = await forwardRequestGET(forwardedURL);
}
res = new Response(result, { status: 200 });
res.headers.set('Access-Control-Allow-Origin', '*');
res.headers.set("Origin", load['server']);
res.headers.set("Country", country);
} catch (e) {
res = new Response('get script error, please try again.', { status: 500 });
res.headers.set('Access-Control-Allow-Origin', '*');
res.headers.set("Origin", load['server']);
res.headers.set("Country", country);
res.headers.set("Error", JSON.stringify(e));
}
return res;
}