(options: { type: string; url: string; headers: Record<string, string>; data?: Buffer }, output: Log)
| 12 | import { readLocalFile } from './pfs'; |
| 13 | |
| 14 | export async function request(options: { type: string; url: string; headers: Record<string, string>; data?: Buffer }, output: Log) { |
| 15 | const secureContext = await secureContextWithExtraCerts(output); |
| 16 | return new Promise<Buffer>((resolve, reject) => { |
| 17 | const parsed = new url.URL(options.url); |
| 18 | const reqOptions: RequestOptions & tls.CommonConnectionOptions = { |
| 19 | hostname: parsed.hostname, |
| 20 | port: parsed.port, |
| 21 | path: parsed.pathname + parsed.search, |
| 22 | method: options.type, |
| 23 | headers: options.headers, |
| 24 | agent: new ProxyAgent(), |
| 25 | secureContext, |
| 26 | }; |
| 27 | |
| 28 | const plainHTTP = parsed.protocol === 'http:' || parsed.hostname === 'localhost'; |
| 29 | if (plainHTTP) { |
| 30 | output.write('Sending as plain HTTP request', LogLevel.Warning); |
| 31 | } |
| 32 | |
| 33 | const req = (plainHTTP ? http : https).request(reqOptions, res => { |
| 34 | if (res.statusCode! < 200 || res.statusCode! > 299) { |
| 35 | reject(new Error(`HTTP ${res.statusCode}: ${res.statusMessage}`)); |
| 36 | output.write(`[-] HTTP request failed with status code ${res.statusCode}: : ${res.statusMessage}`, LogLevel.Trace); |
| 37 | } else { |
| 38 | res.on('error', reject); |
| 39 | const chunks: Buffer[] = []; |
| 40 | res.on('data', chunk => chunks.push(chunk as Buffer)); |
| 41 | res.on('end', () => resolve(Buffer.concat(chunks))); |
| 42 | } |
| 43 | }); |
| 44 | req.on('error', reject); |
| 45 | if (options.data) { |
| 46 | req.write(options.data); |
| 47 | } |
| 48 | req.end(); |
| 49 | }); |
| 50 | } |
| 51 | |
| 52 | // HTTP HEAD request that returns status code. |
| 53 | export async function headRequest(options: { url: string; headers: Record<string, string> }, output: Log) { |
no test coverage detected