-
Notifications
You must be signed in to change notification settings - Fork 1
/
fetch.ts
53 lines (49 loc) · 1.62 KB
/
fetch.ts
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
let password = '';
let passwordHeader = 'x-fetch-password';
let excludeHeadersPrefix = ['cf-', 'x-forwarded-proto', 'x-real-ip', 'true-client-ip', 'x-forwarded-for', passwordHeader];
async function handleFetch(request: Request): Promise<Response> {
let url = new URL(request.url);
let requestUrl = url.pathname + url.search;
requestUrl = requestUrl.replace(/^\/*(https?:)(\/*)/, '$1//');
let newHeaders = new Headers();
for (let [key, value] of request.headers.entries()) {
let exclude = false;
for (let excludePrefix of excludeHeadersPrefix) {
if (key.toLowerCase().startsWith(excludePrefix)) {
exclude = true;
break;
}
}
if (!exclude) newHeaders.append(key, value);
}
let newRequest = new Request(requestUrl, {
method: request.method,
headers: newHeaders,
body: request.body,
redirect: 'manual',
});
return fetch(newRequest);
}
function validateRequest(request: Request): boolean {
if (password && password !== request.headers.get(passwordHeader)) {
return false;
}
let url = new URL(request.url);
if (url.pathname.startsWith('/http:/') || url.pathname.startsWith('/https:/')) {
return true;
}
return false;
}
async function handle(request: Request): Promise<Response> {
console.log(request.url);
if (validateRequest(request)) {
return handleFetch(request);
} else {
return new Response(request.headers.get('x-real-ip') || "OK");
}
}
export default {
fetch(request: Request) {
return handle(request);
}
}