forked from netnr/workers
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcors.js
More file actions
153 lines (134 loc) · 5.06 KB
/
cors.js
File metadata and controls
153 lines (134 loc) · 5.06 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
/*
* https://github.com/netnr/workers
*
* 2019-10-12 - 2026-05-03
* netnr
*/
const DEFAULT_ALLOW_HEADERS = "Accept, Authorization, Cache-Control, Content-Type, DNT, If-Modified-Since, Keep-Alive, Origin, User-Agent, X-Requested-With, Token, x-access-token";
const ALLOW_METHODS = "GET, POST, PUT, PATCH, DELETE, OPTIONS";
const DROP_REQUEST_HEADERS = [
"host",
"content-length",
"cf-connecting-ip",
"cf-ipcountry",
"cf-ray",
"cf-visitor",
"x-forwarded-proto",
"x-real-ip"
];
export default {
async fetch(request, env, ctx) {
const setCorsHeaders = (headers) => {
headers.set("Access-Control-Allow-Origin", "*");
headers.set("Access-Control-Allow-Methods", ALLOW_METHODS);
headers.set(
"Access-Control-Allow-Headers",
request.headers.get("Access-Control-Request-Headers") || DEFAULT_ALLOW_HEADERS
);
headers.set("Access-Control-Expose-Headers", "*");
headers.set("Access-Control-Max-Age", "86400");
headers.set("Vary", "Origin, Access-Control-Request-Headers");
};
const jsonResponse = (payload, status = 200) => {
const headers = new Headers({ "content-type": "application/json; charset=utf-8" });
setCorsHeaders(headers);
return new Response(JSON.stringify(payload), { status, headers });
};
if (request.method === "OPTIONS") {
const headers = new Headers();
setCorsHeaders(headers);
return new Response(null, { status: 204, headers });
}
let targetUrl = "";
let response;
try {
const current = new URL(request.url);
const raw = request.url.slice(current.origin.length + 1);
const decoded = decodeURIComponent(raw || "").trim();
if (!decoded || decoded === "favicon.ico" || decoded === "robots.txt") {
targetUrl = "";
} else {
if (!decoded.includes(".")) {
throw new Error("invalid target url");
}
// fix missing protocol
targetUrl = decoded.includes("://")
? decoded
: decoded.includes(":/")
? decoded.replace(":/", "://")
: `http://${decoded}`;
}
if (!targetUrl) {
response = jsonResponse({
code: 0,
usage: "Host/{URL}",
source: 'https://github.com/netnr/workers',
note: 'Blocking a large number of requests, please deploy it yourself'
});
} else {
const headers = new Headers(request.headers);
for (const name of DROP_REQUEST_HEADERS) {
headers.delete(name);
}
const init = {
method: request.method,
headers,
redirect: "follow"
};
if (["POST", "PUT", "PATCH", "DELETE"].includes(request.method)) {
init.body = request.body;
}
const upstream = await fetch(targetUrl, init);
const outHeaders = new Headers(upstream.headers);
setCorsHeaders(outHeaders);
response = new Response(upstream.body, {
status: upstream.status,
statusText: upstream.statusText,
headers: outHeaders
});
}
} catch (err) {
response = jsonResponse({
code: -1,
msg: err && err.message ? err.message : String(err)
}, 500);
}
logStack.add(ctx, request, response, targetUrl, env.logglyCustomerToken);
return response;
}
};
const logStack = {
add: (ctx, request, response, targetUrl, customerToken) => {
if (customerToken) {
ctx.waitUntil(fetch(`http://logs-01.loggly.com/inputs/${customerToken}/tag/http/`, {
method: "POST",
headers: { "Content-Type": "application/json; charset=utf-8" },
body: JSON.stringify(logStack.buildBody(request, response, targetUrl)),
}));
}
},
buildBody: (request, response, targetUrl) => {
const hua = request.headers.get("user-agent")
const hip = request.headers.get("cf-connecting-ip")
const hrf = request.headers.get("referer")
const url = new URL(request.url)
const body = {
method: request.method,
statusCode: response.status,
clientIp: hip,
referer: hrf,
userAgent: hua,
host: url.host,
path: url.pathname,
proxyHost: null,
}
const turl = (targetUrl || "").trim();
if (turl) {
try {
body.path = turl;
body.proxyHost = new URL(turl).host;
} catch { }
}
return body;
}
};