-
Notifications
You must be signed in to change notification settings - Fork 37
/
index.js
71 lines (63 loc) · 2 KB
/
index.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
// 请求路径。请修改此路径,避免该 worker 所有人都能使用。
const endpointPath = '/dns-query';
// 上游 DoH 地址。必需是域名,不能是 IP。Cloudflare 有限制。
const upstream = 'https://dns.google/dns-query';
/**
* @param {Request} request
* @param {URL} clientUrl
*/
async function handleRequestGet(request, clientUrl) {
const dnsValue = clientUrl.searchParams.get('dns')
if (dnsValue == null) {
return new Response('missing parameters', { status: 400 });
}
if (request.headers.get('accept') != 'application/dns-message') {
return new Response('bad request header', { status: 400 });
}
const upstreamUrl = new URL(upstream);
upstreamUrl.searchParams.set('dns', dnsValue);
const upstreamRequest = new Request(upstreamUrl.toString(), {
headers: request.headers,
method: 'GET',
});
upstreamRequest.headers.set('host', upstreamUrl.hostname)
return await fetch(upstreamRequest);
}
/**
* @param {Request} request
* @param {URL} clientUrl
*/
async function handleRequestPost(request, clientUrl) {
if (request.headers.get('content-type') != 'application/dns-message') {
return new Response('bad request header', { status: 400 });
}
const upstreamRequest = new Request(upstream, {
method: 'POST',
headers: {
'accept': 'application/dns-message',
'content-type': 'application/dns-message',
},
body: await request.arrayBuffer()
});
return await fetch(upstreamRequest);
}
/**
* @param {Request} request
*/
async function handleRequest(request) {
const clientUrl = new URL(request.url);
if (clientUrl.pathname != endpointPath) {
return new Response('Hello World!', { status: 404 });
}
switch (request.method) {
case 'GET':
return handleRequestGet(request, clientUrl)
case 'POST':
return handleRequestPost(request, clientUrl)
default:
return new Response('method not allowed', { status: 405 });
}
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});