forked from http-party/node-http-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathws-incoming.ts
205 lines (179 loc) · 4.97 KB
/
ws-incoming.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import * as http from 'node:http';
import * as https from 'node:https';
import { Duplex } from 'node:stream';
import {
getPort,
hasEncryptedConnection,
isSSL,
setupOutgoing,
setupSocket,
} from '../common';
import { WebSocketErrorCallback } from '../eventCallbacks';
import { ProxyServer, ResolvedProxyServerOptions } from '../proxyServer';
/*
* Array of passes.
*
* A `pass` is just a function that is executed on `req, socket, options`
* so that you can easily add new checks while still keeping the base
* flexible.
*/
/*
* Websockets Passes
*
*/
export type WebSocketIncomingPass = (
this: ProxyServer,
req: http.IncomingMessage,
socket: Duplex,
options: ResolvedProxyServerOptions,
head: Buffer,
server: ProxyServer,
errorCallback?: WebSocketErrorCallback,
) => boolean | unknown;
/**
* WebSocket requests must have the `GET` method and
* the `upgrade:websocket` header
*
* @internal
*/
export const checkMethodAndHeader = (
req: http.IncomingMessage,
socket: Duplex,
) => {
if (req.method !== 'GET' || !req.headers.upgrade) {
socket.destroy();
return true;
}
if (req.headers.upgrade.toLowerCase() !== 'websocket') {
socket.destroy();
return true;
}
};
/**
* Sets `x-forwarded-*` headers if specified in config.
*
* @internal
*/
export const XHeaders = (
req: http.IncomingMessage,
socket: Duplex,
options: ResolvedProxyServerOptions,
) => {
if (!options.xfwd) return;
const values = {
for: req.connection.remoteAddress || req.socket.remoteAddress,
port: getPort(req),
proto: hasEncryptedConnection(req) ? 'wss' : 'ws',
};
(['for', 'port', 'proto'] as const).forEach(function (header) {
req.headers['x-forwarded-' + header] =
(req.headers['x-forwarded-' + header] || '') +
(req.headers['x-forwarded-' + header] ? ',' : '') +
values[header];
});
};
/**
* Does the actual proxying. Make the request and upgrade it
* send the Switching Protocols request and pipe the sockets.
*
* @internal
*/
export const stream = (
req: http.IncomingMessage,
socket: Duplex,
options: ResolvedProxyServerOptions,
head: Buffer,
server: ProxyServer,
errorCallback?: WebSocketErrorCallback,
) => {
const createHttpHeader = function (
line: string,
headers: http.IncomingHttpHeaders,
) {
return (
Object.keys(headers)
.reduce(
function (head, key) {
const value = headers[key];
if (!Array.isArray(value)) {
head.push(key + ': ' + value);
return head;
}
for (let i = 0; i < value.length; i++) {
head.push(key + ': ' + value[i]);
}
return head;
},
[line],
)
.join('\r\n') + '\r\n\r\n'
);
};
if (head && head.length) socket.unshift(head);
const proxyReq = (isSSL(options.target?.protocol) ? https : http).request(
setupOutgoing(options.ssl || {}, options, req),
);
// Enable developers to modify the proxyReq before headers are sent
if (server) {
server.emit('proxyReqWs', proxyReq, req, socket, options, head);
}
// Error Handler
proxyReq.on('error', onOutgoingError);
proxyReq.on('response', function (res) {
// TODO: Does this actually do anything? `upgrade` isn't on `res`.
// if upgrade event isn't going to happen, close the socket
// @ts-ignore
if (!res.upgrade) {
socket.write(
createHttpHeader(
'HTTP/' +
res.httpVersion +
' ' +
res.statusCode +
' ' +
res.statusMessage,
res.headers,
),
);
res.pipe(socket);
}
});
proxyReq.on('upgrade', function (proxyRes, proxySocket, proxyHead) {
proxySocket.on('error', onOutgoingError);
// Allow us to listen when the websocket has completed
proxySocket.on('end', function () {
server.emit('close', proxyRes, proxySocket, proxyHead);
});
// The pipe below will end proxySocket if socket closes cleanly, but not
// if it errors (eg, vanishes from the net and starts returning
// EHOSTUNREACH). We need to do that explicitly.
socket.on('error', function () {
proxySocket.end();
});
setupSocket(proxySocket);
if (proxyHead && proxyHead.length) proxySocket.unshift(proxyHead);
//
// Remark: Handle writing the headers to the socket when switching protocols
// Also handles when a header is an array
//
socket.write(
createHttpHeader('HTTP/1.1 101 Switching Protocols', proxyRes.headers),
);
proxySocket.pipe(socket).pipe(proxySocket);
server.emit('open', proxySocket);
});
return proxyReq.end(); // XXX: CHECK IF THIS IS THIS CORRECT
function onOutgoingError(err: Error) {
if (errorCallback) {
errorCallback(err, req, socket);
} else {
server.emit('error', err, req, socket);
}
socket.end();
}
};
export const websocketIncomingPasses: WebSocketIncomingPass[] = [
checkMethodAndHeader,
XHeaders,
stream,
];