Blame Raw
Cohee · 51ad27fb · · 63 lines (2.3 KB)
2 contributors
1import process from 'node:process';
2import http from 'node:http';
3import https from 'node:https';
4import { ProxyAgent } from 'proxy-agent';
5import { isValidUrl, color } from './util.js';
6
7const LOG_HEADER = '[Request Proxy]';
8
9/**
10 * Initialize request proxy.
11 * @param {ProxySettings} settings Proxy settings.
12 * @typedef {object} ProxySettings
13 * @property {boolean} enabled Whether proxy is enabled.
14 * @property {string} url Proxy URL.
15 * @property {string[]} bypass List of URLs to bypass proxy.
16 * @property {boolean} enableKeepAlive Enable HTTP/HTTPS keep-alive.
17 * @property {boolean} privateRequestFilterEnabled Whether the private request filter is enabled.
18 */
19export default function initRequestProxy({ enabled, url, bypass, enableKeepAlive, privateRequestFilterEnabled }) {
20 try {
21 // No proxy is enabled, so return
22 if (!enabled) {
23 return;
24 }
25
26 if (privateRequestFilterEnabled) {
27 console.warn(color.yellow(LOG_HEADER), 'Warning: Request proxy is enabled while private request filter is also enabled. Only URLs that BYPASS the request proxy will be checked.');
28 console.warn(color.yellow(LOG_HEADER), 'To ensure all requests are properly filtered, disable the request proxy.');
29 }
30
31 if (!url) {
32 console.error(color.red(LOG_HEADER), 'No proxy URL provided');
33 return;
34 }
35
36 if (!isValidUrl(url)) {
37 console.error(color.red(LOG_HEADER), 'Invalid proxy URL provided');
38 return;
39 }
40
41 // ProxyAgent uses proxy-from-env under the hood
42 // Reference: https://github.com/Rob--W/proxy-from-env
43 process.env.all_proxy = url;
44
45 if (Array.isArray(bypass) && bypass.length > 0) {
46 process.env.no_proxy = bypass.join(',');
47 }
48
49 const httpAgent = http.globalAgent;
50 const httpsAgent = https.globalAgent;
51
52 const proxyAgent = new ProxyAgent({ httpAgent, httpsAgent, keepAlive: enableKeepAlive });
53
54 http.globalAgent = proxyAgent;
55 https.globalAgent = proxyAgent;
56
57 console.info();
58 console.info(color.green(LOG_HEADER), 'Proxy URL is used:', color.blue(url));
59 console.info();
60 } catch (error) {
61 console.error(color.red(LOG_HEADER), 'Failed to initialize request proxy:', error);
62 }
63}