From 4d4b70c2a99011909b8f3b58f1e23fcb45cf2ff2 Mon Sep 17 00:00:00 2001 From: Luke Karrys Date: Fri, 29 Sep 2023 18:43:23 -0700 Subject: [PATCH] fix: set proxy from env vars based on truthiness This matches the behavior of previous versions of the npm agent. We can't use default parameters since those will only evaluate if 'undefined' is passed in. Fixes npm/cli#6835 --- lib/proxy.js | 15 +++++++++------ test/index.js | 25 ++++++++++++++++++++++++- 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/lib/proxy.js b/lib/proxy.js index babedad..3a46774 100644 --- a/lib/proxy.js +++ b/lib/proxy.js @@ -64,14 +64,17 @@ const isNoProxy = (url, noProxy) => { }) } -const getProxy = (url, { - proxy = PROXY_ENV.https_proxy, - noProxy = PROXY_ENV.no_proxy, -}) => { +const getProxy = (url, { proxy, noProxy }) => { url = urlify(url) - if (!proxy && url.protocol !== 'https:') { - proxy = PROXY_ENV.http_proxy || PROXY_ENV.proxy + if (!proxy) { + proxy = url.protocol === 'https:' + ? PROXY_ENV.https_proxy + : PROXY_ENV.https_proxy || PROXY_ENV.http_proxy || PROXY_ENV.proxy + } + + if (!noProxy) { + noProxy = PROXY_ENV.no_proxy } if (!proxy || isNoProxy(url, noProxy)) { diff --git a/test/index.js b/test/index.js index 03747a9..66a5f9e 100644 --- a/test/index.js +++ b/test/index.js @@ -140,6 +140,29 @@ t.test('getAgent', (t) => { t.end() }) + t.test('respects proxy for http target if proxy=null is passed in', (t) => { + process.env.proxy = 'http://localhost' + t.teardown(() => { + delete process.env.proxy + }) + + const { getAgent: getEnvAgent, HttpAgent: EnvHttpAgent } = t.mock('../lib/index.js') + + const agent = getEnvAgent('http://localhost') + t.type(agent, EnvHttpAgent) + t.hasStrict(agent, { + proxy: { + url: { + protocol: 'http:', + hostname: 'localhost', + port: '', + }, + }, + }) + + t.end() + }) + t.test('ignores http_proxy for https target', (t) => { process.env.http_proxy = 'http://localhost' t.teardown(() => { @@ -148,7 +171,7 @@ t.test('getAgent', (t) => { const { getAgent: getEnvAgent, HttpsAgent: EnvHttpsAgent } = t.mock('../lib/index.js') - const agent = getEnvAgent('https://localhost') + const agent = getEnvAgent('https://localhost', { proxy: null }) t.type(agent, EnvHttpsAgent) t.notOk(agent.proxy.url)