http-client/proxy.ts

65 lines
1.6 KiB
TypeScript
Raw Normal View History

2020-01-09 23:32:59 +00:00
import * as url from 'url';
export function getProxyUrl(reqUrl: url.Url): url.Url | undefined {
2020-01-09 23:32:59 +00:00
let usingSsl = reqUrl.protocol === 'https:';
let proxyUrl: url.Url;
if (checkBypass(reqUrl)) {
2020-01-09 23:32:59 +00:00
return proxyUrl;
}
2020-01-09 23:32:59 +00:00
let proxyVar: string;
if (usingSsl) {
proxyVar = process.env["https_proxy"] ||
process.env["HTTPS_PROXY"];
} else {
proxyVar = process.env["http_proxy"] ||
process.env["HTTP_PROXY"];
}
2020-01-10 23:12:28 +00:00
2020-01-09 23:32:59 +00:00
if (proxyVar) {
proxyUrl = url.parse(proxyVar);
}
return proxyUrl;
}
export function checkBypass(reqUrl: url.Url): boolean {
if (!reqUrl.hostname) {
return false
}
let noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || '';
if (!noProxy) {
return false
}
// Determine the request port
let reqPort: number
if (reqUrl.port) {
reqPort = Number(reqUrl.port)
}
else if (reqUrl.protocol === 'http:') {
reqPort = 80
}
else if (reqUrl.protocol === 'https:') {
reqPort = 443
}
// Format the request hostname and hostname with port
let upperReqHosts = [reqUrl.hostname.toUpperCase()]
if (typeof reqPort === 'number') {
upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`)
}
// Compare request host against noproxy
for (let upperNoProxyItem of noProxy.split(',').map(x => x.trim().toUpperCase()).filter(x => x)) {
if (upperReqHosts.some(x => x === upperNoProxyItem)) {
return true
}
}
return false
2020-01-09 23:32:59 +00:00
}