/** * 统一创建 HTTPS 出站代理 Agent,兼容 https-proxy-agent 各版本的导出方式。 */ function resolveHttpsProxyAgentClass() { const mod = require('https-proxy-agent') const AgentClass = mod.HttpsProxyAgent || mod.default || mod if (typeof AgentClass !== 'function') { throw new Error('https-proxy-agent 未正确安装或导出格式不兼容') } return AgentClass } function createHttpsProxyAgent(proxyUrl) { const HttpsProxyAgent = resolveHttpsProxyAgentClass() const rejectUnauthorized = process.env.NODE_TLS_REJECT_UNAUTHORIZED !== '0' return new HttpsProxyAgent(proxyUrl, { rejectUnauthorized }) } /** * Axios 对「HTTPS 目标 + 内置 proxy」在部分 Node 版本下会报 ERR_INVALID_PROTOCOL, * 改用 HttpsProxyAgent 走 CONNECT 隧道,并显式 proxy: false。 */ function buildAxiosOutboundConfig(fragment) { if (!fragment || fragment.proxy === false || !fragment.proxy) { return { proxy: false } } const { host, port, auth } = fragment.proxy let userPart = '' if (auth && String(auth.username || '').length > 0) { const u = encodeURIComponent(auth.username) const p = encodeURIComponent(auth.password != null ? String(auth.password) : '') userPart = `${u}:${p}@` } const proxyUrl = `http://${userPart}${host}:${port}` return { proxy: false, httpsAgent: createHttpsProxyAgent(proxyUrl) } } module.exports = { createHttpsProxyAgent, buildAxiosOutboundConfig }