ssl.js: I want to use a proxy, but it hasn't been successful.
GWnbsp opened this issue · 1 comments
GWnbsp commented
const tls = require('tls'); // 引入Node.js的TLS模块,用于处理TLS/SSL连接
const middleware = require('./_common/middleware'); // 引入自定义的中间件
const { setupProxy } = require('./_common/setupProxy'); // 引入设置代理的函数
const handler = async (urlString) => {
try {
const parsedUrl = new URL(urlString); // 解析传入的URL字符串
// 配置TLS连接选项
const options = {
host: parsedUrl.hostname,
port: parsedUrl.port || 443,
servername: parsedUrl.hostname,
rejectUnauthorized: false, // 不拒绝未授权的连接
agent: setupProxy(), // 使用设置的代理
};
return new Promise((resolve, reject) => {
const socket = tls.connect(options, () => {
if (!socket.authorized) {
return reject(new Error(`SSL握手未经授权。原因:${socket.authorizationError}`));
}
const cert = socket.getPeerCertificate();
if (!cert || Object.keys(cert).length === 0) {
return reject(new Error(`
服务器未提供证书。\n
可能是因为服务器未使用SNI(Server Name Indication)来标识自身,您正在连接到主机名别名的IP地址。\n
或者可能是由于无效的SSL证书或在读取证书时SSL握手不完整。`));
}
const { raw, issuerCertificate, ...certWithoutRaw } = cert; // 移除原始证书和颁发者证书
resolve(certWithoutRaw); // 返回证书信息(不包含原始证书和颁发者证书)
socket.end();
});
socket.on('error', (error) => {
reject(new Error(`获取站点证书时发生错误:${error.message}`));
});
});
} catch (error) {
throw new Error(error.message);
}
};
// 导出中间件处理函数
module.exports = middleware(handler);
// 导出处理函数,以便其他模块可以直接使用
module.exports.handler = middleware(handler);
GWnbsp commented
tls.js: I want to use a proxy, but it hasn't been successful.