-
Notifications
You must be signed in to change notification settings - Fork 392
Expand file tree
/
Copy pathhttpRequest.ts
More file actions
161 lines (142 loc) · 5.56 KB
/
httpRequest.ts
File metadata and controls
161 lines (142 loc) · 5.56 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
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import type { RequestOptions } from 'https';
import { https, http, FollowOptions } from 'follow-redirects';
import { ProxyAgent } from 'proxy-agent';
import * as url from 'url';
import * as tls from 'tls';
import { Log, LogLevel } from './log';
import { readLocalFile } from './pfs';
export async function request(options: { type: string; url: string; headers: Record<string, string>; data?: Buffer }, output: Log) {
const secureContext = await secureContextWithExtraCerts(output);
return new Promise<Buffer>((resolve, reject) => {
const parsed = new url.URL(options.url);
const reqOptions: RequestOptions & tls.CommonConnectionOptions = {
hostname: parsed.hostname,
port: parsed.port,
path: parsed.pathname + parsed.search,
method: options.type,
headers: options.headers,
agent: new ProxyAgent(),
secureContext,
};
const plainHTTP = parsed.protocol === 'http:' || parsed.hostname === 'localhost';
if (plainHTTP) {
output.write('Sending as plain HTTP request', LogLevel.Warning);
}
const req = (plainHTTP ? http : https).request(reqOptions, res => {
if (res.statusCode! < 200 || res.statusCode! > 299) {
reject(new Error(`HTTP ${res.statusCode}: ${res.statusMessage}`));
output.write(`[-] HTTP request failed with status code ${res.statusCode}: : ${res.statusMessage}`, LogLevel.Trace);
} else {
res.on('error', reject);
const chunks: Buffer[] = [];
res.on('data', chunk => chunks.push(chunk as Buffer));
res.on('end', () => resolve(Buffer.concat(chunks)));
}
});
req.on('error', reject);
if (options.data) {
req.write(options.data);
}
req.end();
});
}
// HTTP HEAD request that returns status code.
export async function headRequest(options: { url: string; headers: Record<string, string> }, output: Log) {
const secureContext = await secureContextWithExtraCerts(output);
return new Promise<number>((resolve, reject) => {
const parsed = new url.URL(options.url);
const reqOptions: RequestOptions & tls.CommonConnectionOptions = {
hostname: parsed.hostname,
port: parsed.port,
path: parsed.pathname + parsed.search,
method: 'HEAD',
headers: options.headers,
agent: new ProxyAgent(),
secureContext,
};
const plainHTTP = parsed.protocol === 'http:' || parsed.hostname === 'localhost';
if (plainHTTP) {
output.write('Sending as plain HTTP request', LogLevel.Warning);
}
const req = (plainHTTP ? http : https).request(reqOptions, res => {
res.on('error', reject);
output.write(`HEAD ${options.url} -> ${res.statusCode}`, LogLevel.Trace);
resolve(res.statusCode!);
});
req.on('error', reject);
req.end();
});
}
// Send HTTP Request.
// Does not throw on status code, but rather always returns 'statusCode', 'resHeaders', and 'resBody'.
export async function requestResolveHeaders(options: { type: string; url: string; headers: Record<string, string>; data?: Buffer }, output: Log) {
const secureContext = await secureContextWithExtraCerts(output);
return new Promise<{ statusCode: number; resHeaders: Record<string, string>; resBody: Buffer }>((resolve, reject) => {
const parsed = new url.URL(options.url);
const reqOptions: RequestOptions & tls.CommonConnectionOptions & FollowOptions<any> = {
hostname: parsed.hostname,
maxBodyLength: Infinity,
port: parsed.port,
path: parsed.pathname + parsed.search,
method: options.type,
headers: options.headers,
agent: new ProxyAgent(),
secureContext,
};
const plainHTTP = parsed.protocol === 'http:' || parsed.hostname === 'localhost';
if (plainHTTP) {
output.write('Sending as plain HTTP request', LogLevel.Warning);
}
const req = (plainHTTP ? http : https).request(reqOptions, res => {
res.on('error', reject);
// Resolve response body
const chunks: Buffer[] = [];
res.on('data', chunk => chunks.push(chunk as Buffer));
res.on('end', () => {
resolve({
statusCode: res.statusCode!,
resHeaders: res.headers! as Record<string, string>,
resBody: Buffer.concat(chunks)
});
});
});
if (options.data) {
req.write(options.data);
}
req.on('error', reject);
req.end();
});
}
let _secureContextWithExtraCerts: Promise<tls.SecureContext | undefined> | undefined;
async function secureContextWithExtraCerts(output: Log, options?: tls.SecureContextOptions) {
// Work around https://github.com/electron/electron/issues/10257.
if (_secureContextWithExtraCerts) {
return _secureContextWithExtraCerts;
}
return _secureContextWithExtraCerts = (async () => {
if (!process.versions.electron || !process.env.NODE_EXTRA_CA_CERTS) {
return undefined;
}
try {
const content = await readLocalFile(process.env.NODE_EXTRA_CA_CERTS, { encoding: 'utf8' });
const certs = (content.split(/(?=-----BEGIN CERTIFICATE-----)/g)
.filter(pem => !!pem.length));
output.write(`Loading ${certs.length} extra certificates from ${process.env.NODE_EXTRA_CA_CERTS}.`);
if (!certs.length) {
return undefined;
}
const secureContext = tls.createSecureContext(options);
for (const cert of certs) {
secureContext.context.addCACert(cert);
}
return secureContext;
} catch (err) {
output.write(`Error loading extra certificates from ${process.env.NODE_EXTRA_CA_CERTS}: ${err.message}`, LogLevel.Error);
return undefined;
}
})();
}