Skip to content

Commit

Permalink
fix: set proxy from env vars based on truthiness
Browse files Browse the repository at this point in the history
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
  • Loading branch information
lukekarrys committed Sep 30, 2023
1 parent 3e9dc12 commit c86d991
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 7 deletions.
15 changes: 9 additions & 6 deletions lib/proxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down
25 changes: 24 additions & 1 deletion test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => {
Expand All @@ -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)

Expand Down

0 comments on commit c86d991

Please sign in to comment.