-
Notifications
You must be signed in to change notification settings - Fork 246
/
index.ts
212 lines (182 loc) · 6.2 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
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
206
207
208
209
210
211
212
import * as net from 'net';
import * as tls from 'tls';
import * as http from 'http';
import assert from 'assert';
import createDebug from 'debug';
import type { OutgoingHttpHeaders } from 'http';
import { Agent, AgentConnectOpts } from 'agent-base';
import { parseProxyResponse } from './parse-proxy-response';
const debug = createDebug('https-proxy-agent');
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type Protocol<T> = T extends `${infer Protocol}:${infer _}` ? Protocol : never;
type ConnectOptsMap = {
http: Omit<net.TcpNetConnectOpts, 'host' | 'port'>;
https: Omit<tls.ConnectionOptions, 'host' | 'port'>;
};
type ConnectOpts<T> = {
[P in keyof ConnectOptsMap]: Protocol<T> extends P
? ConnectOptsMap[P]
: never;
}[keyof ConnectOptsMap];
export type HttpsProxyAgentOptions<T> = ConnectOpts<T> &
http.AgentOptions & {
headers?: OutgoingHttpHeaders | (() => OutgoingHttpHeaders);
};
/**
* The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to
* the specified "HTTP(s) proxy server" in order to proxy HTTPS requests.
*
* Outgoing HTTP requests are first tunneled through the proxy server using the
* `CONNECT` HTTP request method to establish a connection to the proxy server,
* and then the proxy server connects to the destination target and issues the
* HTTP request from the proxy server.
*
* `https:` requests have their socket connection upgraded to TLS once
* the connection to the proxy server has been established.
*/
export class HttpsProxyAgent<Uri extends string> extends Agent {
static protocols = ['http', 'https'] as const;
readonly proxy: URL;
proxyHeaders: OutgoingHttpHeaders | (() => OutgoingHttpHeaders);
connectOpts: net.TcpNetConnectOpts & tls.ConnectionOptions;
constructor(proxy: Uri | URL, opts?: HttpsProxyAgentOptions<Uri>) {
super(opts);
this.options = { path: undefined };
this.proxy = typeof proxy === 'string' ? new URL(proxy) : proxy;
this.proxyHeaders = opts?.headers ?? {};
debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href);
// Trim off the brackets from IPv6 addresses
const host = (this.proxy.hostname || this.proxy.host).replace(
/^\[|\]$/g,
''
);
const port = this.proxy.port
? parseInt(this.proxy.port, 10)
: this.proxy.protocol === 'https:'
? 443
: 80;
this.connectOpts = {
// Attempt to negotiate http/1.1 for proxy servers that support http/2
ALPNProtocols: ['http/1.1'],
...(opts ? omit(opts, 'headers') : null),
host,
port,
};
}
/**
* Called when the node-core HTTP client library is creating a
* new HTTP request.
*/
async connect(
req: http.ClientRequest,
opts: AgentConnectOpts
): Promise<net.Socket> {
const { proxy } = this;
if (!opts.host) {
throw new TypeError('No "host" provided');
}
// Create a socket connection to the proxy server.
let socket: net.Socket;
if (proxy.protocol === 'https:') {
debug('Creating `tls.Socket`: %o', this.connectOpts);
const servername =
this.connectOpts.servername || this.connectOpts.host;
socket = tls.connect({
...this.connectOpts,
servername:
servername && net.isIP(servername) ? undefined : servername,
});
} else {
debug('Creating `net.Socket`: %o', this.connectOpts);
socket = net.connect(this.connectOpts);
}
const headers: OutgoingHttpHeaders =
typeof this.proxyHeaders === 'function'
? this.proxyHeaders()
: { ...this.proxyHeaders };
const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`;
// Inject the `Proxy-Authorization` header if necessary.
if (proxy.username || proxy.password) {
const auth = `${decodeURIComponent(
proxy.username
)}:${decodeURIComponent(proxy.password)}`;
headers['Proxy-Authorization'] = `Basic ${Buffer.from(
auth
).toString('base64')}`;
}
headers.Host = `${host}:${opts.port}`;
if (!headers['Proxy-Connection']) {
headers['Proxy-Connection'] = this.keepAlive
? 'Keep-Alive'
: 'close';
}
for (const name of Object.keys(headers)) {
payload += `${name}: ${headers[name]}\r\n`;
}
const proxyResponsePromise = parseProxyResponse(socket);
socket.write(`${payload}\r\n`);
const { connect, buffered } = await proxyResponsePromise;
req.emit('proxyConnect', connect);
this.emit('proxyConnect', connect, req);
if (connect.statusCode === 200) {
req.once('socket', resume);
if (opts.secureEndpoint) {
// The proxy is connecting to a TLS server, so upgrade
// this socket connection to a TLS connection.
debug('Upgrading socket connection to TLS');
const servername = opts.servername || opts.host;
return tls.connect({
...omit(opts, 'host', 'path', 'port'),
socket,
servername: net.isIP(servername) ? undefined : servername,
});
}
return socket;
}
// Some other status code that's not 200... need to re-play the HTTP
// header "data" events onto the socket once the HTTP machinery is
// attached so that the node core `http` can parse and handle the
// error status code.
// Close the original socket, and a new "fake" socket is returned
// instead, so that the proxy doesn't get the HTTP request
// written to it (which may contain `Authorization` headers or other
// sensitive data).
//
// See: https://hackerone.com/reports/541502
socket.destroy();
const fakeSocket = new net.Socket({ writable: false });
fakeSocket.readable = true;
// Need to wait for the "socket" event to re-play the "data" events.
req.once('socket', (s: net.Socket) => {
debug('Replaying proxy buffer for failed request');
assert(s.listenerCount('data') > 0);
// Replay the "buffered" Buffer onto the fake `socket`, since at
// this point the HTTP module machinery has been hooked up for
// the user.
s.push(buffered);
s.push(null);
});
return fakeSocket;
}
}
function resume(socket: net.Socket | tls.TLSSocket): void {
socket.resume();
}
function omit<T extends object, K extends [...(keyof T)[]]>(
obj: T,
...keys: K
): {
[K2 in Exclude<keyof T, K[number]>]: T[K2];
} {
const ret = {} as {
[K in keyof typeof obj]: (typeof obj)[K];
};
let key: keyof typeof obj;
for (key in obj) {
if (!keys.includes(key)) {
ret[key] = obj[key];
}
}
return ret;
}