agent.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // Copyright 2013 Lovell Fuller and others.
  2. // SPDX-License-Identifier: Apache-2.0
  3. 'use strict';
  4. const url = require('url');
  5. const tunnelAgent = require('tunnel-agent');
  6. const is = require('./is');
  7. const proxies = [
  8. 'HTTPS_PROXY',
  9. 'https_proxy',
  10. 'HTTP_PROXY',
  11. 'http_proxy',
  12. 'npm_config_https_proxy',
  13. 'npm_config_proxy'
  14. ];
  15. function env (key) {
  16. return process.env[key];
  17. }
  18. module.exports = function (log) {
  19. try {
  20. const proxy = new url.URL(proxies.map(env).find(is.string));
  21. const tunnel = proxy.protocol === 'https:'
  22. ? tunnelAgent.httpsOverHttps
  23. : tunnelAgent.httpsOverHttp;
  24. const proxyAuth = proxy.username && proxy.password
  25. ? `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`
  26. : null;
  27. log(`Via proxy ${proxy.protocol}//${proxy.hostname}:${proxy.port} ${proxyAuth ? 'with' : 'no'} credentials`);
  28. return tunnel({
  29. proxy: {
  30. port: Number(proxy.port),
  31. host: proxy.hostname,
  32. proxyAuth
  33. }
  34. });
  35. } catch (err) {
  36. return null;
  37. }
  38. };