-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
113 lines (109 loc) · 2.43 KB
/
index.ts
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
import proxy from "http2-proxy";
import finalhandler from "finalhandler";
import type {
IncomingMessage,
ServerResponse,
Server as HttpServer,
} from "http";
import type { Socket, Server } from "net";
import type {
Http2ServerRequest,
Http2ServerResponse,
Http2Server,
} from "http2";
const defaultWebHandler = (err, req, res) => {
if (err) {
finalhandler(req, res)(err);
}
};
const defaultWSHandler = (err, req, socket, head) => {
if (err) {
socket.destroy();
}
};
function createProxy<T extends Http2Server>(options: {
server: T;
webProxy: proxy.http2WebOptions;
wsProxy: proxy.wsHttp2Options;
webCallback?: (
err: Error,
req: Http2ServerRequest,
res: Http2ServerResponse
) => void;
wsCallback?: (
err: Error,
req: Http2ServerRequest,
socket: Socket,
head: Buffer
) => void;
bypassHost?: boolean;
}): void;
function createProxy<T extends HttpServer>(options: {
server: T;
webProxy: proxy.http1WebOptions;
wsProxy: proxy.wsHttp1Options;
webCallback?: (err: Error, req: IncomingMessage, res: ServerResponse) => void;
wsCallback?: (
err: Error,
req: IncomingMessage,
socket: Socket,
head: Buffer
) => void;
bypassHost?: boolean;
}): void;
function createProxy<T extends Server>({
server,
webProxy,
wsProxy,
webCallback = defaultWebHandler,
wsCallback = defaultWSHandler,
bypassHost = false,
}: {
server: T;
webProxy: any;
wsProxy: any;
webCallback?: (err: Error, req: any, res: any) => void;
wsCallback?: (err: Error, req: any, socket: Socket, head: Buffer) => void;
bypassHost?: boolean;
}) {
server.on("request", (req, res) => {
proxy.web(
req,
res,
bypassHost
? {
...webProxy,
hostname:
req.headers[":authority"] ||
req.headers.host ||
webProxy.hostname,
}
: webProxy,
webCallback
);
});
server.on("upgrade", (req, socket, head) => {
proxy.ws(
req,
socket,
head,
bypassHost
? {
...wsProxy,
hostname:
req.headers[":authority"] || req.headers.host || wsProxy.hostname,
}
: wsProxy,
wsCallback
);
});
server.on("secureConnection", (sock) => {
sock.on("error", (err) => {
if (err.code === "ECONNRESET" || err.code === 'EPIPE') {
return;
}
throw err;
});
});
}
export { createProxy };