Files
certd/packages/ui/certd-server/src/modules/monitor/service/site-tester.ts
T

101 lines
2.5 KiB
TypeScript
Raw Normal View History

2025-05-28 00:57:52 +08:00
import { logger, safePromise, utils } from "@certd/basic";
import { merge } from "lodash-es";
import https from "https";
import { PeerCertificate } from "tls";
export type SiteTestReq = {
host: string; // 只用域名部分
port?: number;
method?: string;
retryTimes?: number;
2025-05-28 00:57:52 +08:00
ipAddress?: string;
};
export type SiteTestRes = {
certificate?: PeerCertificate;
};
2025-05-28 00:57:52 +08:00
export class SiteTester {
async test(req: SiteTestReq): Promise<SiteTestRes> {
2025-05-28 00:57:52 +08:00
logger.info("测试站点:", JSON.stringify(req));
const maxRetryTimes = req.retryTimes ?? 3;
let tryCount = 0;
let result: SiteTestRes = {};
while (true) {
try {
result = await this.doTestOnce(req);
return result;
} catch (e) {
tryCount++;
if (tryCount > maxRetryTimes) {
2025-01-04 20:17:08 +08:00
logger.error(`测试站点出错,重试${maxRetryTimes}次。`, e.message);
throw e;
}
//指数退避
const time = 2 ** tryCount;
logger.error(`测试站点出错,${time}s后重试`, e);
await utils.sleep(time * 1000);
}
}
}
async doTestOnce(req: SiteTestReq): Promise<SiteTestRes> {
const options: any = merge(
{
port: 443,
2025-05-28 00:57:52 +08:00
method: "GET",
rejectUnauthorized: false
},
req
);
2025-05-28 00:57:52 +08:00
if (req.ipAddress) {
//使用固定的ip
const ipAddress = req.ipAddress;
2025-05-28 01:22:23 +08:00
options.lookup = (hostname: string, options: any, callback: any) => {
2025-05-28 00:57:52 +08:00
//判断ip是v4 还是v6
2025-05-28 01:22:23 +08:00
console.log("options", options);
console.log("ipaddress", ipAddress);
2025-05-28 00:57:52 +08:00
if (ipAddress.indexOf(":") > -1) {
2025-05-28 01:22:23 +08:00
callback(null, ipAddress, 6);
2025-05-28 00:57:52 +08:00
} else {
2025-05-28 01:22:23 +08:00
callback(null, ipAddress, 4);
2025-05-28 00:57:52 +08:00
}
};
}
2025-05-28 01:22:23 +08:00
options.agent = new https.Agent({ keepAlive: false });
2025-05-28 00:57:52 +08:00
// 创建 HTTPS 请求
2025-04-30 09:38:44 +08:00
const requestPromise = safePromise((resolve, reject) => {
const req = https.request(options, res => {
// 获取证书
// @ts-ignore
const certificate = res.socket.getPeerCertificate();
// logger.info('证书信息', certificate);
if (certificate.subject == null) {
2025-05-28 00:57:52 +08:00
logger.warn("证书信息为空");
resolve({
2025-05-28 00:57:52 +08:00
certificate: null
});
}
resolve({
2025-05-28 00:57:52 +08:00
certificate
});
res.socket.end();
// 关闭响应
res.destroy();
});
2025-05-28 00:57:52 +08:00
req.on("error", e => {
reject(e);
});
req.end();
});
return await requestPromise;
}
}
export const siteTester = new SiteTester();