Sharkey/packages/megalodon/src/proxy_config.ts

93 lines
2.2 KiB
TypeScript
Raw Normal View History

2023-09-24 16:20:03 -07:00
import { HttpsProxyAgent, HttpsProxyAgentOptions } from "https-proxy-agent";
import { SocksProxyAgent, SocksProxyAgentOptions } from "socks-proxy-agent";
2023-09-23 09:49:47 -07:00
export type ProxyConfig = {
2023-09-24 16:20:03 -07:00
host: string;
port: number;
auth?: {
username: string;
password: string;
};
protocol:
| "http"
| "https"
| "socks4"
| "socks4a"
| "socks5"
| "socks5h"
| "socks";
};
2023-09-23 09:49:47 -07:00
class ProxyProtocolError extends Error {}
2023-09-24 16:20:03 -07:00
const proxyAgent = (
proxyConfig: ProxyConfig,
): HttpsProxyAgent | SocksProxyAgent => {
switch (proxyConfig.protocol) {
case "http": {
let options: HttpsProxyAgentOptions = {
host: proxyConfig.host,
port: proxyConfig.port,
secureProxy: false,
};
if (proxyConfig.auth) {
options = Object.assign(options, {
auth: `${proxyConfig.auth.username}:${proxyConfig.auth.password}`,
});
}
const httpsAgent = new HttpsProxyAgent(options);
return httpsAgent;
}
case "https": {
let options: HttpsProxyAgentOptions = {
host: proxyConfig.host,
port: proxyConfig.port,
secureProxy: true,
};
if (proxyConfig.auth) {
options = Object.assign(options, {
auth: `${proxyConfig.auth.username}:${proxyConfig.auth.password}`,
});
}
const httpsAgent = new HttpsProxyAgent(options);
return httpsAgent;
}
case "socks4":
case "socks4a": {
let options: SocksProxyAgentOptions = {
type: 4,
hostname: proxyConfig.host,
port: proxyConfig.port,
};
if (proxyConfig.auth) {
options = Object.assign(options, {
userId: proxyConfig.auth.username,
password: proxyConfig.auth.password,
});
}
const socksAgent = new SocksProxyAgent(options);
return socksAgent;
}
case "socks5":
case "socks5h":
case "socks": {
let options: SocksProxyAgentOptions = {
type: 5,
hostname: proxyConfig.host,
port: proxyConfig.port,
};
if (proxyConfig.auth) {
options = Object.assign(options, {
userId: proxyConfig.auth.username,
password: proxyConfig.auth.password,
});
}
const socksAgent = new SocksProxyAgent(options);
return socksAgent;
}
default:
throw new ProxyProtocolError("protocol is not accepted");
}
};
export default proxyAgent;