feat: support reverse proxy

This commit is contained in:
DIYgod
2023-07-23 20:28:38 +01:00
parent 7856617044
commit 3a5d293b7f
6 changed files with 111 additions and 12 deletions

View File

@@ -20,7 +20,13 @@ if (agent) {
const proxyRegex = new RegExp(proxyObj.url_regex);
const protocolMatch = (protocolLike) => protocolLike && protocolLike.toLowerCase().startsWith('http');
proxyWrapper = (url, options, urlHandler) => {
proxyWrapper = (url, options) => {
let urlHandler;
try {
urlHandler = new URL(url);
} catch (error) {
// ignore
}
if (proxyRegex.test(url)) {
if ((protocolMatch(options.protocol) || protocolMatch(url)) && (!urlHandler || urlHandler.host !== proxyUrlHandler.host)) {
options.agent = agent;
@@ -32,25 +38,34 @@ if (agent) {
}
return false;
};
} else if (config.reverseProxyUrl) {
proxyWrapper = (url, options) => {
if (!((options.url || url) + "").startsWith(config.reverseProxyUrl)) {
options.url = new URL(`${config.reverseProxyUrl}${encodeURIComponent(options.url || url)}`);
return true;
}
return false;
};
}
const requestWrapper = (url, options) => {
let urlHandler;
try {
urlHandler = new URL(url);
} catch (error) {
// ignore
}
options.headers = options.headers || {};
const headersLowerCaseKeys = Object.keys(options.headers).map((key) => key.toLowerCase());
proxyWrapper(url, options, urlHandler) ? logger.info(`Proxy for ${url}`) : logger.debug(`Requesting ${url}`);
proxyWrapper(url, options) ? logger.info(`Proxy for ${url}`) : logger.debug(`Requesting ${url}`);
// ua
if (!headersLowerCaseKeys.includes('user-agent')) {
options.headers['user-agent'] = config.ua;
}
let urlHandler;
try {
urlHandler = new URL(options.url || url);
} catch (error) {
// ignore
}
if (urlHandler) {
// referer
if (!headersLowerCaseKeys.includes('referer')) {
@@ -66,6 +81,7 @@ const requestWrapper = (url, options) => {
const httpWrap = (func) => {
const origin = func;
return function (url, request) {
const args = Array.prototype.slice.call(arguments);
if (typeof url === 'object') {
if (url instanceof URL) {
requestWrapper(url.toString(), request);
@@ -76,7 +92,8 @@ const httpWrap = (func) => {
} else {
requestWrapper(url, request);
}
return origin.apply(this, arguments);
args[0] = request.url || url;
return origin.apply(this, args);
};
};