network-proxy.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. import * as undici from 'undici';
  2. import { Agent, Dispatcher, ProxyAgent } from 'undici';
  3. const LOOPBACK_NO_PROXY_ENTRIES = ['localhost', '127.0.0.1', '::1'] as const;
  4. interface ProxyValue {
  5. readonly name: string;
  6. readonly value: string;
  7. }
  8. export type TuiProxyConfiguration =
  9. | { readonly mode: 'direct' }
  10. | {
  11. readonly mode: 'proxy';
  12. readonly httpProxy: string;
  13. readonly httpsProxy: string;
  14. readonly noProxy: string;
  15. };
  16. export interface ConfigureTuiNetworkProxyOptions {
  17. readonly environment?: NodeJS.ProcessEnv;
  18. readonly createProxyDispatcher?: (options: {
  19. httpProxy: string;
  20. httpsProxy: string;
  21. noProxy: string;
  22. }) => Dispatcher;
  23. readonly setGlobalDispatcher?: (dispatcher: Dispatcher) => void;
  24. readonly installFetch?: () => void;
  25. }
  26. export function resolveTuiProxyConfiguration(
  27. environment: NodeJS.ProcessEnv = process.env,
  28. ): TuiProxyConfiguration {
  29. const allProxy = firstProxyValue(environment, 'ALL_PROXY', 'all_proxy');
  30. const httpProxy = firstProxyValue(environment, 'HTTP_PROXY', 'http_proxy') ?? allProxy;
  31. const httpsProxy =
  32. firstProxyValue(environment, 'HTTPS_PROXY', 'https_proxy') ?? allProxy ?? httpProxy;
  33. if (!httpProxy && !httpsProxy) return { mode: 'direct' };
  34. validateProxyValue(httpProxy);
  35. validateProxyValue(httpsProxy);
  36. return {
  37. mode: 'proxy',
  38. httpProxy: httpProxy?.value ?? '',
  39. httpsProxy: httpsProxy?.value ?? '',
  40. noProxy: withLoopbackNoProxy(firstProxyValue(environment, 'NO_PROXY', 'no_proxy')?.value),
  41. };
  42. }
  43. export function configureTuiNetworkProxy(
  44. options: ConfigureTuiNetworkProxyOptions = {},
  45. ): TuiProxyConfiguration {
  46. const configuration = resolveTuiProxyConfiguration(options.environment);
  47. if (configuration.mode === 'direct') return configuration;
  48. const createProxyDispatcher =
  49. options.createProxyDispatcher ?? ((proxyOptions) => new TuiProxyDispatcher(proxyOptions));
  50. const dispatcher = createProxyDispatcher({
  51. httpProxy: configuration.httpProxy,
  52. httpsProxy: configuration.httpsProxy,
  53. noProxy: configuration.noProxy,
  54. });
  55. (options.setGlobalDispatcher ?? undici.setGlobalDispatcher)(dispatcher);
  56. (options.installFetch ?? installUndiciFetch)();
  57. return configuration;
  58. }
  59. function firstProxyValue(
  60. environment: NodeJS.ProcessEnv,
  61. ...names: readonly string[]
  62. ): ProxyValue | undefined {
  63. for (const name of names) {
  64. const value = environment[name]?.trim();
  65. if (value) return { name, value };
  66. }
  67. return undefined;
  68. }
  69. function validateProxyValue(proxy: ProxyValue | undefined): void {
  70. if (!proxy) return;
  71. let url: URL;
  72. try {
  73. url = new URL(proxy.value);
  74. } catch {
  75. throw new Error(`${proxy.name} must be an http:// or https:// URL.`);
  76. }
  77. if ((url.protocol !== 'http:' && url.protocol !== 'https:') || !url.hostname) {
  78. throw new Error(`${proxy.name} must be an http:// or https:// URL.`);
  79. }
  80. }
  81. function withLoopbackNoProxy(existing: string | undefined): string {
  82. const entries: string[] = [];
  83. for (const raw of (existing ?? '').split(',')) {
  84. const entry = raw.trim();
  85. if (entry && !entries.includes(entry)) entries.push(entry);
  86. }
  87. for (const entry of LOOPBACK_NO_PROXY_ENTRIES) {
  88. if (!entries.includes(entry)) entries.push(entry);
  89. }
  90. return entries.join(',');
  91. }
  92. function installUndiciFetch(): void {
  93. (undici as typeof undici & { install?: () => void }).install?.();
  94. }
  95. class TuiProxyDispatcher extends Dispatcher {
  96. readonly #directDispatcher = new Agent();
  97. readonly #httpDispatcher: Dispatcher;
  98. readonly #httpsDispatcher: Dispatcher;
  99. readonly #dispatchers: readonly Dispatcher[];
  100. readonly #noProxy: string;
  101. constructor(options: { httpProxy: string; httpsProxy: string; noProxy: string }) {
  102. super();
  103. this.#httpDispatcher = options.httpProxy
  104. ? new ProxyAgent({ uri: options.httpProxy })
  105. : this.#directDispatcher;
  106. this.#httpsDispatcher = options.httpsProxy
  107. ? options.httpsProxy === options.httpProxy
  108. ? this.#httpDispatcher
  109. : new ProxyAgent({ uri: options.httpsProxy })
  110. : this.#directDispatcher;
  111. this.#dispatchers = [
  112. ...new Set([this.#directDispatcher, this.#httpDispatcher, this.#httpsDispatcher]),
  113. ];
  114. this.#noProxy = options.noProxy;
  115. }
  116. override dispatch(
  117. options: Dispatcher.DispatchOptions,
  118. handler: Dispatcher.DispatchHandler,
  119. ): boolean {
  120. const url = new URL(options.origin ?? '');
  121. if (shouldBypassTuiProxy(url, this.#noProxy)) {
  122. return this.#directDispatcher.dispatch(options, handler);
  123. }
  124. const dispatcher = url.protocol === 'https:' ? this.#httpsDispatcher : this.#httpDispatcher;
  125. return dispatcher.dispatch(options, handler);
  126. }
  127. override close(): Promise<void>;
  128. override close(callback: () => void): void;
  129. override close(callback?: () => void): Promise<void> | void {
  130. const operation = Promise.all(this.#dispatchers.map((dispatcher) => dispatcher.close())).then(
  131. () => undefined,
  132. );
  133. if (!callback) return operation;
  134. void operation.then(callback, callback);
  135. }
  136. override destroy(): Promise<void>;
  137. override destroy(error: Error | null): Promise<void>;
  138. override destroy(callback: () => void): void;
  139. override destroy(error: Error | null, callback: () => void): void;
  140. override destroy(
  141. errorOrCallback?: Error | null | (() => void),
  142. callback?: () => void,
  143. ): Promise<void> | void {
  144. const error = typeof errorOrCallback === 'function' ? null : (errorOrCallback ?? null);
  145. const completion = typeof errorOrCallback === 'function' ? errorOrCallback : callback;
  146. const operation = Promise.all(
  147. this.#dispatchers.map((dispatcher) => dispatcher.destroy(error)),
  148. ).then(() => undefined);
  149. if (!completion) return operation;
  150. void operation.then(completion, completion);
  151. }
  152. }
  153. export function shouldBypassTuiProxy(url: URL, noProxy: string): boolean {
  154. const hostname = normalizeHostname(url.hostname);
  155. const port = Number(url.port) || (url.protocol === 'https:' ? 443 : 80);
  156. for (const rawEntry of noProxy.split(/[\s,]+/u)) {
  157. const entry = parseNoProxyEntry(rawEntry);
  158. if (!entry) continue;
  159. if (entry.hostname === '*') return true;
  160. if (entry.port !== undefined && entry.port !== port) continue;
  161. if (hostname === entry.hostname) return true;
  162. if (entry.includeSubdomains && hostname.endsWith(`.${entry.hostname}`)) return true;
  163. }
  164. return false;
  165. }
  166. function parseNoProxyEntry(
  167. rawEntry: string,
  168. ): { hostname: string; port?: number; includeSubdomains: boolean } | undefined {
  169. let value = rawEntry.trim().toLowerCase();
  170. if (!value) return undefined;
  171. if (value === '*') return { hostname: '*', includeSubdomains: true };
  172. let port: number | undefined;
  173. if (value.startsWith('[')) {
  174. const bracket = value.indexOf(']');
  175. if (bracket > 0) {
  176. const suffix = value.slice(bracket + 1);
  177. if (/^:\d+$/u.test(suffix)) port = Number(suffix.slice(1));
  178. value = value.slice(1, bracket);
  179. }
  180. } else if (value.split(':').length === 2) {
  181. const [hostname, rawPort] = value.split(':');
  182. if (hostname && /^\d+$/u.test(rawPort ?? '')) {
  183. value = hostname;
  184. port = Number(rawPort);
  185. }
  186. }
  187. const includeSubdomains = value.startsWith('.') || value.startsWith('*');
  188. value = value.replace(/^\*?\./u, '');
  189. const hostname = normalizeHostname(value);
  190. return hostname ? { hostname, port, includeSubdomains } : undefined;
  191. }
  192. function normalizeHostname(hostname: string): string {
  193. return hostname.toLowerCase().replace(/^\[|\]$/gu, '');
  194. }