forked from serverless-dns/serverless-dns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
doh.js
66 lines (55 loc) · 1.74 KB
/
doh.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
/*
* Copyright (c) 2021 RethinkDNS and its authors.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import RethinkPlugin from "./plugin.js";
import * as pres from "../plugins/plugin-response.js";
import * as util from "../commons/util.js";
import * as dnsutil from "../commons/dnsutil.js";
import IOState from "./io-state.js";
/**
* @param {*} event
* @returns {Promise<Response>}
*/
export function handleRequest(event) {
return proxyRequest(event);
}
/**
* @param {*} event
* @returns {Promise<Response>}
*/
async function proxyRequest(event) {
if (optionsRequest(event.request)) return util.respond204();
const io = new IOState();
try {
const plugin = new RethinkPlugin(event);
await plugin.initIoState(io);
// if an early response has been set by plugin.initIoState, return it
if (io.httpResponse) {
const ua = event.request.headers.get("User-Agent");
if (util.fromBrowser(ua)) io.setCorsHeadersIfNeeded();
return io.httpResponse;
}
await util.timedSafeAsyncOp(
/* op*/ async () => plugin.execute(),
/* waitMs*/ dnsutil.requestTimeout(),
/* onTimeout*/ async () => errorResponse(io)
);
} catch (err) {
log.e("doh", "proxy-request error", err.stack);
errorResponse(io, err);
}
const ua = event.request.headers.get("User-Agent");
if (util.fromBrowser(ua)) io.setCorsHeadersIfNeeded();
return io.httpResponse;
}
function optionsRequest(request) {
return request.method === "OPTIONS";
}
function errorResponse(io, err = null) {
const eres = pres.errResponse("doh.js", err);
io.dnsExceptionResponse(eres);
}