fix sync proxy with TLS

This commit is contained in:
zadam
2019-07-24 20:47:41 +02:00
parent ea0835561c
commit b3834324f6
3 changed files with 97 additions and 30 deletions

View File

@@ -8,7 +8,13 @@ const url = require('url');
// this allows to support system proxy
function exec(opts) {
// hack for cases where electron.net does not work but we don't want to set proxy
if (opts.proxy === 'noproxy') {
opts.proxy = null;
}
const client = getClient(opts);
const proxyAgent = getProxyAgent(opts);
const parsedTargetUrl = url.parse(opts.url);
return new Promise(async (resolve, reject) => {
@@ -24,34 +30,18 @@ function exec(opts) {
headers['Authorization'] = `Basic ${token}`;
}
let host = parsedTargetUrl.hostname;
let protocol = parsedTargetUrl.protocol;
let port = parsedTargetUrl.port;
let path = parsedTargetUrl.path;
if (opts.proxy) {
// see https://stackoverflow.com/questions/3862813/how-can-i-use-an-http-proxy-with-node-js-http-client
const parsedProxyUrl = url.parse(opts.proxy);
protocol = parsedProxyUrl.protocol;
host = parsedProxyUrl.hostname;
port = parsedProxyUrl.port;
path = opts.url;
headers['Host'] = parsedTargetUrl.host; // host also includes port
}
const request = client.request({
method: opts.method,
// url is used by electron net module
url: opts.url,
// 4 fields below are used by http and https node modules
protocol,
host,
port,
path,
protocol: parsedTargetUrl.protocol,
host: parsedTargetUrl.hostname,
port: parsedTargetUrl.port,
path: parsedTargetUrl.path,
timeout: opts.timeout,
headers
headers,
agent: proxyAgent
});
request.on('error', err => reject(generateError(opts, err)));
@@ -91,6 +81,24 @@ function exec(opts) {
})
}
function getProxyAgent(opts) {
if (!opts.proxy) {
return;
}
const {protocol} = url.parse(opts.url);
if (protocol === 'http:' || protocol === 'https:') {
const protoNoColon = protocol.substr(0, protocol.length - 1);
const AgentClass = require(protoNoColon + '-proxy-agent');
return new AgentClass(opts.proxy);
}
else {
return null;
}
}
function getClient(opts) {
// it's not clear how to explicitly configure proxy (as opposed to system proxy)
// so in that case we always use node's modules
@@ -98,14 +106,7 @@ function getClient(opts) {
return require('electron').net;
}
else {
// hack for cases where electron.net does not work but we don't want to set proxy
if (opts.proxy === 'noproxy') {
opts.proxy = null;
}
// in case there's explicit proxy then we need to use protocol of the proxy since we're actually
// connecting to the proxy server and not to the end-target server
const {protocol} = url.parse(opts.proxy || opts.url);
const {protocol} = url.parse(opts.url);
if (protocol === 'http:' || protocol === 'https:') {
return require(protocol.substr(0, protocol.length - 1));