getProxyFromURI.js 2.2 KB

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