UNPKG

2.39 kBJavaScriptView Raw
1// copy from https://github.com/request/request/blob/90cf8c743bb9fd6a4cb683a56fb7844c6b316866/lib/getProxyFromURI.js
2
3'use strict'
4
5function formatHostname(hostname) {
6 // canonicalize the hostname, so that 'oogle.com' won't match 'google.com'
7 return hostname.replace(/^\.*/, '.').toLowerCase()
8}
9
10function parseNoProxyZone(zone) {
11 zone = zone.trim().toLowerCase()
12
13 var zoneParts = zone.split(':', 2)
14 , zoneHost = formatHostname(zoneParts[0])
15 , zonePort = zoneParts[1]
16 , hasPort = zone.indexOf(':') > -1
17
18 return {hostname: zoneHost, port: zonePort, hasPort: hasPort}
19}
20
21function uriInNoProxy(uri, noProxy) {
22 var port = uri.port || (uri.protocol === 'https:' ? '443' : '80')
23 , hostname = formatHostname(uri.hostname)
24 , noProxyList = noProxy.split(',')
25
26 // iterate through the noProxyList until it finds a match.
27 return noProxyList.map(parseNoProxyZone).some(function(noProxyZone) {
28 var isMatchedAt = hostname.indexOf(noProxyZone.hostname)
29 , hostnameMatched = (
30 isMatchedAt > -1 &&
31 (isMatchedAt === hostname.length - noProxyZone.hostname.length)
32 )
33
34 if (noProxyZone.hasPort) {
35 return (port === noProxyZone.port) && hostnameMatched
36 }
37
38 return hostnameMatched
39 })
40}
41
42function getProxyFromURI(uri) {
43 // Decide the proper request proxy to use based on the request URI object and the
44 // environmental variables (NO_PROXY, HTTP_PROXY, etc.)
45 // respect NO_PROXY environment variables (see: http://lynx.isc.org/current/breakout/lynx_help/keystrokes/environments.html)
46
47 var noProxy = process.env.NO_PROXY || process.env.no_proxy || ''
48
49 // if the noProxy is a wildcard then return null
50
51 if (noProxy === '*') {
52 return null
53 }
54
55 // if the noProxy is not empty and the uri is found return null
56
57 if (noProxy !== '' && uriInNoProxy(uri, noProxy)) {
58 return null
59 }
60
61 // Check for HTTP or HTTPS Proxy in environment Else default to null
62
63 if (uri.protocol === 'http:') {
64 return process.env.HTTP_PROXY ||
65 process.env.http_proxy || null
66 }
67
68 if (uri.protocol === 'https:') {
69 return process.env.HTTPS_PROXY ||
70 process.env.https_proxy ||
71 process.env.HTTP_PROXY ||
72 process.env.http_proxy || null
73 }
74
75 // if none of that works, return null
76 // (What uri protocol are you using then?)
77
78 return null
79}
80
81module.exports = getProxyFromURI