shouldBypassProxy.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. import { domainToASCII } from 'url';
  2. const LOOPBACK_HOSTNAMES = new Set(['localhost', '0.0.0.0']);
  3. const trimTrailingDots = (value) => {
  4. let end = value.length;
  5. while (end && value.charCodeAt(end - 1) === 46) {
  6. end--;
  7. }
  8. return end === value.length ? value : value.slice(0, end);
  9. };
  10. const isIPv4Loopback = (host) => {
  11. const parts = host.split('.');
  12. if (parts.length !== 4) return false;
  13. if (parts[0] !== '127') return false;
  14. return parts.every((p) => /^\d+$/.test(p) && Number(p) >= 0 && Number(p) <= 255);
  15. };
  16. /**
  17. * Canonicalize an IPv4 address written in shorthand, octal, or hex form into
  18. * dotted-decimal. IPv6 addresses and non-IP strings are returned unchanged so
  19. * the existing IPv4-mapped IPv6 unmap path and the isLoopback path can still
  20. * see them.
  21. *
  22. * Shorthand expansion mirrors Node's URL parser: literal parts fill from the
  23. * left, the final part fills the remaining octets from the right with
  24. * zero-padding on the left.
  25. * 127.1 -> 127.0.0.1
  26. * 127.0.1 -> 127.0.0.1
  27. * 1.2.3 -> 1.2.0.3
  28. *
  29. * Each octet is parsed with an explicit base: 16 for `0x`/`0X` prefix, 8 for
  30. * zero-prefixed multi-digit all-`0-7` parts, 10 otherwise. Zero-prefixed
  31. * decimal-looking parts that contain `8` or `9` are rejected to match Node's
  32. * URL parser, and the comparison layer falls through to non-bypass if either
  33. * side rejects the form (fail-safe).
  34. *
  35. * Returns the input unchanged on any parse failure, out-of-range octet, or
  36. * unusual shape (1-part, 5+ parts) so the comparison layer fails closed.
  37. */
  38. const parseIPv4Octet = (text) => {
  39. if (/^0[xX][0-9a-fA-F]+$/.test(text)) {
  40. const n = parseInt(text.slice(2), 16);
  41. return Number.isFinite(n) ? n : null;
  42. }
  43. if (text.length > 1 && /^0[0-7]+$/.test(text)) {
  44. const n = parseInt(text, 8);
  45. return Number.isFinite(n) ? n : null;
  46. }
  47. if (text.length > 1 && /^0[0-9]+$/.test(text)) {
  48. return null;
  49. }
  50. if (/^[0-9]+$/.test(text)) {
  51. const n = parseInt(text, 10);
  52. return Number.isFinite(n) ? n : null;
  53. }
  54. return null;
  55. };
  56. const normalizeIPAddress = (host) => {
  57. if (typeof host !== 'string' || !host || host.indexOf(':') !== -1) {
  58. return host;
  59. }
  60. let h = host;
  61. if (h.charAt(0) === '[' && h.charAt(h.length - 1) === ']') {
  62. h = h.slice(1, -1);
  63. }
  64. h = trimTrailingDots(h);
  65. // Allowed characters for any IPv4 shape: digits, dot, 'x', 'X', hex digits.
  66. if (!/^[0-9.xXa-fA-F]+$/.test(h)) return host;
  67. const parts = h.split('.');
  68. // No part may be empty (e.g. "127..0.1" or "127.0.0."). Trailing dots are
  69. // already stripped above; this guards against the empty-middle case.
  70. if (parts.some((p) => p === '')) return host;
  71. if (parts.length === 4) {
  72. // Full IPv4 form: each part is an octet.
  73. const octets = parts.map(parseIPv4Octet);
  74. if (octets.some((n) => n === null || n < 0 || n > 255)) return host;
  75. return octets.join('.');
  76. }
  77. if (parts.length > 4) {
  78. return host;
  79. }
  80. // Shorthand: 1..3 parts. Node's URL parser treats a 1-part input as a 32-bit
  81. // integer split into octets, which has surprising semantics (e.g. "127" ->
  82. // "0.0.0.127"). Reject 1-part inputs to keep the helper predictable: the
  83. // fail-safe returns the input unchanged and the comparison layer falls
  84. // through to non-bypass.
  85. if (parts.length === 1) return host;
  86. // 2..3 parts: literal parts fill from the left, tail fills remaining octets
  87. // from the right with zero-padding.
  88. const literalOctets = parts.slice(0, -1);
  89. const tail = parts[parts.length - 1];
  90. const tailSlots = 4 - literalOctets.length;
  91. // Tail is parsed as a full IPv4 number (hex/octal/decimal) and packed
  92. // low-byte-right into the remaining octets, matching Node's URL parser.
  93. // e.g. 127.65535 (tail 0xFFFF into 3 slots) -> 127.0.255.255;
  94. // 127.0x00ff (tail 0xFF into 3 slots) -> 127.0.0.255;
  95. // 127.0.65535 (tail 0xFFFF into 2 slots) -> 127.0.255.255.
  96. const tailValue = parseIPv4Octet(tail);
  97. if (tailValue === null) return host;
  98. const maxTail = (1 << (8 * tailSlots)) - 1;
  99. if (tailValue < 0 || tailValue > maxTail) return host;
  100. const tailOctets = new Array(tailSlots).fill(0);
  101. for (let i = tailSlots - 1, v = tailValue; i >= 0; i--, v >>= 8) {
  102. tailOctets[i] = v & 0xff;
  103. }
  104. const literal = literalOctets.map(parseIPv4Octet);
  105. if (literal.some((n) => n === null || n < 0 || n > 255)) return host;
  106. return [...literal, ...tailOctets].join('.');
  107. };
  108. const isIPv6ZeroGroup = (group) => /^0{1,4}$/.test(group);
  109. // The unspecified address (IPv4 0.0.0.0 / IPv6 ::) resolves to the local host
  110. // for outbound connections, so treat it as loopback-equivalent for NO_PROXY
  111. // matching. 0.0.0.0 is covered by LOOPBACK_HOSTNAMES; this handles compressed
  112. // and full IPv6 all-zero forms so both families bypass symmetrically.
  113. const isIPv6Unspecified = (host) => {
  114. if (host === '::') return true;
  115. const compressionIndex = host.indexOf('::');
  116. if (compressionIndex !== -1) {
  117. if (compressionIndex !== host.lastIndexOf('::')) return false;
  118. const left = host.slice(0, compressionIndex);
  119. const right = host.slice(compressionIndex + 2);
  120. const leftGroups = left ? left.split(':') : [];
  121. const rightGroups = right ? right.split(':') : [];
  122. const explicitGroups = leftGroups.length + rightGroups.length;
  123. return (
  124. explicitGroups < 8 && leftGroups.every(isIPv6ZeroGroup) && rightGroups.every(isIPv6ZeroGroup)
  125. );
  126. }
  127. const groups = host.split(':');
  128. return groups.length === 8 && groups.every(isIPv6ZeroGroup);
  129. };
  130. const isIPv6Loopback = (host) => {
  131. // Collapse all-zero groups: any form of ::1 / 0:0:...:0:1
  132. // First, strip any leading "::" by normalising with Set lookup of common forms,
  133. // then fall back to structural check.
  134. if (host === '::1') return true;
  135. // Check IPv4-mapped IPv6 loopback: ::ffff:<v4-loopback> or ::ffff:<hex-v4-loopback>
  136. // Node's URL parser normalises ::ffff:127.0.0.1 → ::ffff:7f00:1
  137. const v4MappedDotted = host.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);
  138. if (v4MappedDotted) return isIPv4Loopback(v4MappedDotted[1]);
  139. const v4MappedHex = host.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);
  140. if (v4MappedHex) {
  141. const high = parseInt(v4MappedHex[1], 16);
  142. // High 16 bits must start with 127 (0x7f) — i.e. 0x7f00..0x7fff
  143. return high >= 0x7f00 && high <= 0x7fff;
  144. }
  145. // Full-form ::1 variants: any number of zero groups followed by trailing 1
  146. // e.g. 0:0:0:0:0:0:0:1, 0000:...:0001
  147. const groups = host.split(':');
  148. if (groups.length === 8) {
  149. for (let i = 0; i < 7; i++) {
  150. if (!/^0+$/.test(groups[i])) return false;
  151. }
  152. return /^0*1$/.test(groups[7]);
  153. }
  154. return false;
  155. };
  156. const isLoopback = (host) => {
  157. if (!host) return false;
  158. if (LOOPBACK_HOSTNAMES.has(host)) return true;
  159. if (isIPv4Loopback(host)) return true;
  160. if (isIPv6Unspecified(host)) return true;
  161. return isIPv6Loopback(host);
  162. };
  163. const DEFAULT_PORTS = {
  164. http: 80,
  165. https: 443,
  166. ws: 80,
  167. wss: 443,
  168. ftp: 21,
  169. };
  170. const parseNoProxyEntry = (entry) => {
  171. let entryHost = entry;
  172. let entryPort = 0;
  173. if (entryHost.charAt(0) === '[') {
  174. const bracketIndex = entryHost.indexOf(']');
  175. if (bracketIndex !== -1) {
  176. const host = entryHost.slice(1, bracketIndex);
  177. const rest = entryHost.slice(bracketIndex + 1);
  178. if (rest.charAt(0) === ':' && /^\d+$/.test(rest.slice(1))) {
  179. entryPort = Number.parseInt(rest.slice(1), 10);
  180. }
  181. return [host, entryPort];
  182. }
  183. }
  184. const firstColon = entryHost.indexOf(':');
  185. const lastColon = entryHost.lastIndexOf(':');
  186. if (
  187. firstColon !== -1 &&
  188. firstColon === lastColon &&
  189. /^\d+$/.test(entryHost.slice(lastColon + 1))
  190. ) {
  191. entryPort = Number.parseInt(entryHost.slice(lastColon + 1), 10);
  192. entryHost = entryHost.slice(0, lastColon);
  193. }
  194. return [entryHost, entryPort];
  195. };
  196. // Convert IPv4-mapped IPv6 (::ffff:0:0/96 prefix) to IPv4 dotted form so both
  197. // sides of a NO_PROXY comparison see the same canonical address. Without this,
  198. // `NO_PROXY=192.168.1.5` would not match a request to `http://[::ffff:192.168.1.5]/`
  199. // (Node's URL parser normalises that to `[::ffff:c0a8:105]`), and vice-versa,
  200. // allowing the proxy-bypass policy to be circumvented by using the alternate
  201. // representation. Returns the input unchanged when not IPv4-mapped.
  202. const IPV4_MAPPED_DOTTED_RE = /^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:(\d+\.\d+\.\d+\.\d+)$/i;
  203. const IPV4_MAPPED_HEX_RE =
  204. /^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i;
  205. const unmapIPv4MappedIPv6 = (host) => {
  206. if (typeof host !== 'string' || host.indexOf(':') === -1) return host;
  207. const dotted = host.match(IPV4_MAPPED_DOTTED_RE);
  208. if (dotted) return dotted[1];
  209. const hex = host.match(IPV4_MAPPED_HEX_RE);
  210. if (hex) {
  211. const high = parseInt(hex[1], 16);
  212. const low = parseInt(hex[2], 16);
  213. return `${high >> 8}.${high & 0xff}.${low >> 8}.${low & 0xff}`;
  214. }
  215. return host;
  216. };
  217. const IPV4_OCTET_RE = /^(?:0|[1-9]\d{0,2})$/;
  218. const ipv4ToBytes = (host) => {
  219. const parts = host.split('.');
  220. return parts.length === 4 &&
  221. parts.every((part) => IPV4_OCTET_RE.test(part) && Number(part) <= 255)
  222. ? parts.map(Number)
  223. : null;
  224. };
  225. const IPV6_GROUP_RE = /^[0-9a-f]{1,4}$/i;
  226. const ipv6ToBytes = (host) => {
  227. const halves = host.split('::');
  228. if (halves.length > 2) {
  229. return null;
  230. }
  231. const groups = halves[0] ? halves[0].split(':') : [];
  232. if (halves.length === 2) {
  233. const rear = halves[1] ? halves[1].split(':') : [];
  234. const missing = 8 - groups.length - rear.length;
  235. if (missing < 1) {
  236. return null;
  237. }
  238. groups.push(...new Array(missing).fill('0'), ...rear);
  239. }
  240. if (groups.length !== 8 || groups.some((group) => !IPV6_GROUP_RE.test(group))) {
  241. return null;
  242. }
  243. return groups.flatMap((group) => {
  244. const value = Number.parseInt(group, 16);
  245. return [(value >> 8) & 0xff, value & 0xff];
  246. });
  247. };
  248. const ipToBytes = (host) => {
  249. if (typeof host !== 'string' || !host) {
  250. return null;
  251. }
  252. return host.indexOf(':') !== -1 ? ipv6ToBytes(host) : ipv4ToBytes(host);
  253. };
  254. const normalizeNoProxyHost = (hostname) => {
  255. if (!hostname) {
  256. return hostname;
  257. }
  258. if (hostname.charAt(0) === '[' && hostname.charAt(hostname.length - 1) === ']') {
  259. hostname = hostname.slice(1, -1);
  260. }
  261. let trimmed = trimTrailingDots(hostname);
  262. if (trimmed.indexOf(':') !== -1) {
  263. try {
  264. trimmed = new URL('http://[' + trimmed + ']/').hostname.slice(1, -1);
  265. } catch (_err) {
  266. return trimmed;
  267. }
  268. } else if (/[\u0080-\uffff]/.test(trimmed)) {
  269. const prefix = /^[*.]+/.exec(trimmed);
  270. const start = prefix ? prefix[0] : '';
  271. const ascii = domainToASCII(trimmed.slice(start.length));
  272. if (!ascii) return '';
  273. trimmed = start + trimTrailingDots(ascii);
  274. }
  275. // IPv4 shorthand/octal/hex → dotted-decimal; helper is a no-op for inputs
  276. // containing ':' (IPv6 and IPv4-mapped IPv6) so we fall through to unmap.
  277. const ipv4 = normalizeIPAddress(trimmed);
  278. if (ipv4 !== trimmed) {
  279. return ipv4;
  280. }
  281. return unmapIPv4MappedIPv6(trimmed);
  282. };
  283. const normalizeCidrBase = (input) => {
  284. let base = input;
  285. const startsBracket = base.charAt(0) === '[';
  286. const endsBracket = base.charAt(base.length - 1) === ']';
  287. const hasBracket = base.includes('[') || base.includes(']');
  288. if (startsBracket || endsBracket) {
  289. if (!startsBracket || !endsBracket) {
  290. return null;
  291. }
  292. base = base.slice(1, -1);
  293. if (base.indexOf(':') === -1 || base.includes('[') || base.includes(']')) {
  294. return null;
  295. }
  296. } else if (hasBracket) {
  297. return null;
  298. }
  299. if (!base || base.charAt(base.length - 1) === '.') {
  300. return null;
  301. }
  302. const wasIPv6 = base.indexOf(':') !== -1;
  303. if (wasIPv6) {
  304. try {
  305. base = new URL(`http://[${base}]/`).hostname.slice(1, -1);
  306. } catch (_err) {
  307. return null;
  308. }
  309. } else {
  310. base = normalizeIPAddress(base);
  311. if (!ipv4ToBytes(base)) {
  312. return null;
  313. }
  314. }
  315. return { normalized: unmapIPv4MappedIPv6(base), wasIPv6 };
  316. };
  317. const CIDR_ENTRY_RE = /^(.+)\/(0|[1-9]\d{0,2})$/;
  318. const parseCidrEntry = (entry) => {
  319. if (entry.indexOf('/') === -1) {
  320. return undefined;
  321. }
  322. const match = CIDR_ENTRY_RE.exec(entry);
  323. if (!match) {
  324. return null;
  325. }
  326. let prefix = Number(match[2]);
  327. const parsedBase = normalizeCidrBase(match[1]);
  328. if (!parsedBase) {
  329. return null;
  330. }
  331. const { normalized, wasIPv6 } = parsedBase;
  332. if (wasIPv6 && normalized.indexOf(':') === -1) {
  333. if (prefix < 96) {
  334. return null;
  335. }
  336. prefix -= 96;
  337. }
  338. const bytes = ipToBytes(normalized);
  339. if (!bytes || prefix > bytes.length * 8) {
  340. return null;
  341. }
  342. return { bytes, prefix };
  343. };
  344. const isInSubnet = (addressBytes, networkBytes, prefix) => {
  345. const fullBytes = prefix >> 3;
  346. for (let i = 0; i < fullBytes; i++) {
  347. if (addressBytes[i] !== networkBytes[i]) {
  348. return false;
  349. }
  350. }
  351. const remainingBits = prefix & 7;
  352. if (remainingBits) {
  353. const mask = (0xff << (8 - remainingBits)) & 0xff;
  354. if ((addressBytes[fullBytes] & mask) !== (networkBytes[fullBytes] & mask)) {
  355. return false;
  356. }
  357. }
  358. return true;
  359. };
  360. export default function shouldBypassProxy(location) {
  361. let parsed;
  362. try {
  363. parsed = new URL(location);
  364. } catch (_err) {
  365. return false;
  366. }
  367. const noProxy = (process.env.no_proxy || process.env.NO_PROXY || '').toLowerCase();
  368. if (!noProxy) {
  369. return false;
  370. }
  371. if (noProxy === '*') {
  372. return true;
  373. }
  374. const port =
  375. Number.parseInt(parsed.port, 10) || DEFAULT_PORTS[parsed.protocol.split(':', 1)[0]] || 0;
  376. const hostname = normalizeNoProxyHost(parsed.hostname.toLowerCase());
  377. const hostnameBytes = ipToBytes(hostname);
  378. return noProxy.split(/[\s,]+/).some((entry) => {
  379. if (!entry) {
  380. return false;
  381. }
  382. if (entry === '*') {
  383. return true;
  384. }
  385. const cidr = parseCidrEntry(entry);
  386. if (cidr !== undefined) {
  387. return (
  388. cidr !== null &&
  389. !!hostnameBytes &&
  390. hostnameBytes.length === cidr.bytes.length &&
  391. isInSubnet(hostnameBytes, cidr.bytes, cidr.prefix)
  392. );
  393. }
  394. let [entryHost, entryPort] = parseNoProxyEntry(entry);
  395. entryHost = normalizeNoProxyHost(entryHost);
  396. if (!entryHost) {
  397. return false;
  398. }
  399. if (entryPort && entryPort !== port) {
  400. return false;
  401. }
  402. if (entryHost.charAt(0) === '*') {
  403. entryHost = entryHost.slice(1);
  404. }
  405. if (entryHost.charAt(0) === '.') {
  406. return hostname.endsWith(entryHost);
  407. }
  408. return hostname === entryHost || (isLoopback(hostname) && isLoopback(entryHost));
  409. });
  410. }