-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhttps-agent.ts
More file actions
84 lines (69 loc) · 2.63 KB
/
https-agent.ts
File metadata and controls
84 lines (69 loc) · 2.63 KB
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
import * as https from 'https';
import hyperid from 'hyperid';
import * as net from 'net';
import * as tls from 'tls';
import {
HttpProxy,
HttpsProxy,
ICallback,
NativeHttpsAgentOptions,
NativeRequestOptions
} from './types';
import { requestShouldUseProxy } from './utils';
export class HttpsAgent extends https.Agent {
public name: string;
constructor(options: https.AgentOptions & { name?: string }) {
super(options);
this.name = options.name || hyperid(true)();
}
private createConnectionHttpsAfterHttp(options: NativeHttpsAgentOptions, cb: ICallback) {
let socket: tls.TLSSocket | net.Socket;
if ((options.proxy as HttpProxy | HttpsProxy).protocol === 'https') {
socket = tls.connect(options.proxy as HttpsProxy);
} else {
socket = net.connect(options.proxy as HttpProxy);
if (options.keepAlive === true) {
socket.setKeepAlive(true);
}
}
const onError = (error: Error) => {
socket.destroy();
cb(error);
};
const onData = (data: Buffer) => {
socket.removeListener('error', onError);
const m: RegExpMatchArray | null = data.toString().match(/^HTTP\/1.1 (\d*)/);
if (m && m[1] !== '200') {
socket.destroy();
return cb(new Error(m[0]));
}
Object.assign(options, { socket });
// @ts-ignore, because of a bug on Agent @types https://github.com/DefinitelyTyped/DefinitelyTyped/issues/16735@types
return cb(null, super.createConnection(options));
};
socket.once('error', onError);
socket.once('data', onData);
let msg = `CONNECT ${options.hostname}:${options.port} HTTP/1.1\r\n`;
if ((options.proxy as HttpProxy | HttpsProxy).auth) {
const auth = Buffer.from((options.proxy as HttpProxy | HttpsProxy).auth).toString('base64');
msg += `Proxy-Authorization: Basic ${auth}\r\n`;
}
if ((options.proxy as HttpProxy | HttpsProxy).headers) {
Object.keys((options.proxy as HttpProxy | HttpsProxy).headers).forEach(header => {
msg += `${header}: ${(options.proxy as HttpProxy | HttpsProxy).headers[header]}\r\n`;
});
}
msg += `Host: ${options.hostname}:${options.port} \r\n`;
msg += '\r\n';
socket.write(msg);
return socket;
}
createConnection(options: NativeHttpsAgentOptions, cb: ICallback) {
if (options.proxy && requestShouldUseProxy(options as NativeRequestOptions)) {
return this.createConnectionHttpsAfterHttp(options, cb);
}
// @ts-ignore, because of a bug on Agent @types https://github.com/DefinitelyTyped/DefinitelyTyped/issues/16735@types
return super.createConnection(options, cb);
}
}
export default HttpsAgent;