forked from msasanmh/cf-workers-dns-over-https
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
52 lines (47 loc) · 1.82 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
addEventListener('fetch', function(event) {
const { request } = event
const response = handleRequest(request)
event.respondWith(response)
})
// request path. Please modify this path to prevent everyone from using this worker.
const endpointPath = '/dns-query';
// you can replace below server with any other DoH servers.
const doh = 'https://cloudflare-dns.com/dns-query'
// NOTE: below server is in JSON format. For example Google DoH JSON is https://dns.google/resolve (it's not always dns-query).
const dohjson = 'https://cloudflare-dns.com/dns-query'
const contype = 'application/dns-message'
const jstontype = 'application/dns-json'
async function handleRequest(request) {
const clientUrl = new URL(request.url);
const { method, headers, url } = request
const searchParams = new URL(url).searchParams
if (clientUrl.pathname != endpointPath) {
return new Response('Not Found. HTTP 404.', { status: 404 });
} else if (method == 'GET' && searchParams.has('dns')) {
return await fetch(doh + '?dns=' + searchParams.get('dns'), {
method: 'GET',
headers: {
'Accept': contype,
}
});
} else if (method == 'POST' && headers.get('content-type') == contype) {
return await fetch(doh, {
method: 'POST',
headers: {
'Accept': contype,
'Content-Type': contype,
},
body: await request.arrayBuffer()
});
} else if (method == 'GET' && headers.get('Accept') == jstontype) {
const search = new URL(url).search
return await fetch(dohjson + search, {
method: 'GET',
headers: {
'Accept': jstontype,
}
});
} else {
return new Response("Not Found. HTTP 404.", {status: 404})
}
}