forked from johnpantini/ppp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ppp-proxy-netlify.js
91 lines (78 loc) · 2.17 KB
/
ppp-proxy-netlify.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
async function handleOptions(request) {
if (request.headers.get('Origin') !== null) {
// Handle CORS preflight requests.
return new Response(null, {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods':
'GET, POST, OPTIONS, PUT, PATCH, DELETE',
'Access-Control-Allow-Headers': '*'
}
});
} else {
// Handle standard OPTIONS request.
return new Response(null, {
headers: {
Allow: 'GET, POST, OPTIONS, PUT, PATCH, DELETE'
}
});
}
}
export default async function (req) {
if (req.method === 'OPTIONS') {
return handleOptions(req);
}
const host = req.headers.get('X-Host');
if (!host) {
return new Response(null, {
status: 404
});
} else {
const allowedHeaders = (req.headers.get('X-Allowed-Headers') ?? '').split(
','
);
const url = new URL(req.url);
url.hostname = host;
const newHeaders = new Headers();
const mandatoryHeaders = [
'Accept',
'Accept-Encoding',
'Content-Type',
'Content-Length',
'Connection',
'Upgrade'
];
for (const h of mandatoryHeaders) {
req.headers.has(h) && newHeaders.set(h, req.headers.get(h));
}
newHeaders.set('Host', host);
for (const h of allowedHeaders) {
h &&
req.headers.has(h) &&
!newHeaders.has(h) &&
newHeaders.set(h, req.headers.get(h));
}
const newRequest = new Request(
url.toString(),
new Request(req, {
method: req.method,
body: req.body,
redirect: req.redirect,
headers: newHeaders
})
);
const fetchResponse = await fetch(url.toString(), newRequest);
const res = new Response(fetchResponse.body, fetchResponse);
res.headers.set('Access-Control-Allow-Origin', '*');
res.headers.set(
'Access-Control-Allow-Methods',
'GET, POST, OPTIONS, PUT, PATCH, DELETE'
);
res.headers.set('Access-Control-Allow-Headers', '*');
res.headers.append('Vary', 'Origin');
res.headers.delete('Content-Security-Policy');
res.headers.delete('X-Frame-Options');
return res;
}
}
export const config = { path: '/*' };