-
Notifications
You must be signed in to change notification settings - Fork 41
/
worker.js
205 lines (179 loc) · 5.51 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
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
/*
CORS Anywhere as a Cloudflare Worker
*/
const blacklist = []; // regexp for blacklisted urls
const whitelist = [".*"]; // regexp for whitelisted origins
const whitelistFetch = ["hendt.de", "ebay.com/"]; // regexp for whitelisted fetch url
const logUrl = ''; // e.g. from https://requestbin.com
const responseBody = `
HENDT eBay API Proxy<br>
Usage: https://ebay.hendt.workers.dev/https://hendt.de <br> or
https://ebay.hendt.workers.dev/?url=https%3A%2F%2Fhendt.de
<a href='https://github.com/hendt/ebay-api'>eBay API</a><br>\n
`;
function isListed(uri, listing) {
let ret = false;
if (typeof uri == "string") {
listing.forEach((m) => {
if (uri.match(m) != null) ret = true;
});
} else { // decide what to do when Origin is null
ret = true; // true accepts null origins false rejects them.
}
return ret;
}
function fixHeaders(headers, {isOptions, origin, requestMethod, accessControl}) {
headers.set("Access-Control-Allow-Origin", origin);
if (isOptions) {
headers.set("Access-Control-Allow-Methods", requestMethod);
if (accessControl) {
headers.set("Access-Control-Allow-Headers", accessControl);
}
headers.delete("X-Content-Type-Options");
}
return headers;
}
const log = (data) => {
if (!logUrl) {
console.log(JSON.stringify(data, null, 2));
return Promise.resolve();
}
return fetch(logUrl, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
};
const handleRequest = async (event) => {
try {
const isOptions = (event.request.method === "OPTIONS");
const origin = event.request.headers.get("Origin");
const originUrl = new URL(event.request.url);
let fetchUrl = originUrl.pathname.substr(1);
if (fetchUrl) {
fetchUrl = fetchUrl
.replace('https:/', 'https://')
.replace('http:/', 'http://');
fetchUrl = decodeURIComponent(fetchUrl) + originUrl.search;
} else {
const urlParams = new URLSearchParams(originUrl.search);
fetchUrl = urlParams.get('url');
}
if (!fetchUrl) {
return new Response(responseBody,
{
status: 403,
statusText: 'Forbidden',
headers: {
"Content-Type": "text/html"
}
});
}
if (!isListed(fetchUrl, whitelistFetch) || isListed(fetchUrl, blacklist) || !isListed(origin, whitelist)) {
return new Response(responseBody,
{
status: 403,
statusText: 'Forbidden',
headers: {
"Content-Type": "text/html"
}
});
}
const accessControl = event.request.headers.get("access-control-request-headers");
const requestMethod = event.request.headers.get("access-control-request-method");
const recHeaders = {};
for (let pair of event.request.headers.entries()) {
const key = pair[0];
if ((key.match("^origin") == null) &&
(key.match("eferer") == null) &&
(key.match("^cf-") == null) &&
(key.match("^x-forw") == null) &&
(key.match("^x-cors-headers") == null)
) {
recHeaders[key] = pair[1];
}
}
try {
const xHeaders = JSON.parse(event.request.headers.get("x-cors-headers"));
Object.entries(xHeaders).forEach((c) => recHeaders[c[0]] = c[1]);
} catch (e) {
}
try {
event.waitUntil(log({
type: 'newReq',
fetchUrl,
headers: recHeaders
}));
const newReq = new Request(event.request, {
"headers": recHeaders
});
const response = await fetch(encodeURI(fetchUrl), newReq);
let responseHeaders = new Headers(response.headers);
const corsHeaders = [];
const receivedHeaders = {};
for (let pair of response.headers.entries()) {
corsHeaders.push(pair[0]);
receivedHeaders[pair[0]] = pair[1];
}
corsHeaders.push("cors-received-headers");
responseHeaders = fixHeaders(responseHeaders, {isOptions, origin, requestMethod, accessControl});
responseHeaders.set("Access-Control-Expose-Headers", corsHeaders.join(","));
responseHeaders.set("cors-received-headers", JSON.stringify(receivedHeaders));
if (isOptions) {
event.waitUntil(log({
type: 'options',
fetchUrl,
headers: [...responseHeaders]
}));
return new Response(null, {
headers: responseHeaders,
status: 200,
statusText: "OK"
});
}
const init = {
headers: responseHeaders,
status: response.status,
statusText: response.statusText
};
event.waitUntil(log({
type: 'response',
fetchUrl,
headers: [...responseHeaders]
}));
const body = await response.arrayBuffer();
return new Response(body, init);
} catch (e) {
event.waitUntil(log({
type: 'error',
fetchUrl,
message: e.message,
error: e.stack || e
}));
return new Response(null,
{
status: 400,
statusText: 'Bad request',
headers: {
"Content-Type": "text/html"
}
});
}
} catch (err) {
// Return the error stack as the response
return new Response(err.stack || err.message, {
status: 400,
statusText: 'Bad Request',
headers: {
"Content-Type": "text/html"
}
});
}
};
addEventListener("fetch", async event => {
event.passThroughOnException();
event.respondWith(handleRequest(event));
});