shouldBypassProxy.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. const DEFAULT_PORTS = {
  2. http: 80,
  3. https: 443,
  4. ws: 80,
  5. wss: 443,
  6. ftp: 21,
  7. };
  8. const parseNoProxyEntry = (entry) => {
  9. let entryHost = entry;
  10. let entryPort = 0;
  11. if (entryHost.charAt(0) === '[') {
  12. const bracketIndex = entryHost.indexOf(']');
  13. if (bracketIndex !== -1) {
  14. const host = entryHost.slice(1, bracketIndex);
  15. const rest = entryHost.slice(bracketIndex + 1);
  16. if (rest.charAt(0) === ':' && /^\d+$/.test(rest.slice(1))) {
  17. entryPort = Number.parseInt(rest.slice(1), 10);
  18. }
  19. return [host, entryPort];
  20. }
  21. }
  22. const firstColon = entryHost.indexOf(':');
  23. const lastColon = entryHost.lastIndexOf(':');
  24. if (
  25. firstColon !== -1 &&
  26. firstColon === lastColon &&
  27. /^\d+$/.test(entryHost.slice(lastColon + 1))
  28. ) {
  29. entryPort = Number.parseInt(entryHost.slice(lastColon + 1), 10);
  30. entryHost = entryHost.slice(0, lastColon);
  31. }
  32. return [entryHost, entryPort];
  33. };
  34. const normalizeNoProxyHost = (hostname) => {
  35. if (!hostname) {
  36. return hostname;
  37. }
  38. if (hostname.charAt(0) === '[' && hostname.charAt(hostname.length - 1) === ']') {
  39. hostname = hostname.slice(1, -1);
  40. }
  41. return hostname.replace(/\.+$/, '');
  42. };
  43. export default function shouldBypassProxy(location) {
  44. let parsed;
  45. try {
  46. parsed = new URL(location);
  47. } catch (_err) {
  48. return false;
  49. }
  50. const noProxy = (process.env.no_proxy || process.env.NO_PROXY || '').toLowerCase();
  51. if (!noProxy) {
  52. return false;
  53. }
  54. if (noProxy === '*') {
  55. return true;
  56. }
  57. const port =
  58. Number.parseInt(parsed.port, 10) || DEFAULT_PORTS[parsed.protocol.split(':', 1)[0]] || 0;
  59. const hostname = normalizeNoProxyHost(parsed.hostname.toLowerCase());
  60. return noProxy.split(/[\s,]+/).some((entry) => {
  61. if (!entry) {
  62. return false;
  63. }
  64. let [entryHost, entryPort] = parseNoProxyEntry(entry);
  65. entryHost = normalizeNoProxyHost(entryHost);
  66. if (!entryHost) {
  67. return false;
  68. }
  69. if (entryPort && entryPort !== port) {
  70. return false;
  71. }
  72. if (entryHost.charAt(0) === '*') {
  73. entryHost = entryHost.slice(1);
  74. }
  75. if (entryHost.charAt(0) === '.') {
  76. return hostname.endsWith(entryHost);
  77. }
  78. return hostname === entryHost;
  79. });
  80. }