This commit is contained in:
xiaojunnuo
2024-09-06 00:13:21 +08:00
parent af388ec39f
commit 3bad0b2685
13 changed files with 292 additions and 240 deletions

View File

@@ -6,10 +6,11 @@ import { crypto } from "@certd/acme-client";
import { ILogger } from "@certd/pipeline";
import dayjs from "dayjs";
export type CertReaderHandleContext = { reader: CertReader; tmpCrtPath: string; tmpKeyPath: string };
export type CertReaderHandleContext = { reader: CertReader; tmpCrtPath: string; tmpKeyPath: string; tmpPfxPath?: string; tmpDerPath?: string };
export type CertReaderHandle = (ctx: CertReaderHandleContext) => Promise<void>;
export type HandleOpts = { logger: ILogger; handle: CertReaderHandle };
export class CertReader implements CertInfo {
export class CertReader {
cert: CertInfo;
crt: string;
key: string;
csr: string;
@@ -17,30 +18,31 @@ export class CertReader implements CertInfo {
detail: any;
expires: number;
constructor(certInfo: CertInfo) {
this.cert = certInfo;
this.crt = certInfo.crt;
this.key = certInfo.key;
this.csr = certInfo.csr;
const { detail, expires } = this.getCrtDetail(this.crt);
const { detail, expires } = this.getCrtDetail(this.cert.crt);
this.detail = detail;
this.expires = expires.getTime();
}
toCertInfo(): CertInfo {
return {
crt: this.crt,
key: this.key,
csr: this.csr,
};
return this.cert;
}
getCrtDetail(crt: string = this.crt) {
getCrtDetail(crt: string = this.cert.crt) {
const detail = crypto.readCertificateInfo(crt.toString());
const expires = detail.notAfter;
return { detail, expires };
}
saveToFile(type: "crt" | "key", filepath?: string) {
saveToFile(type: "crt" | "key" | "pfx" | "der", filepath?: string) {
if (!this.cert[type]) {
return;
}
if (filepath == null) {
//写入临时目录
filepath = path.join(os.tmpdir(), "/certd/tmp/", Math.floor(Math.random() * 1000000) + "", `cert.${type}`);
@@ -50,8 +52,11 @@ export class CertReader implements CertInfo {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
fs.writeFileSync(filepath, this[type]);
if (type === "crt" || type === "key") {
fs.writeFileSync(filepath, this.cert[type]);
} else {
fs.writeFileSync(filepath, Buffer.from(this.cert[type], "base64"));
}
return filepath;
}
@@ -60,18 +65,24 @@ export class CertReader implements CertInfo {
logger.info("将证书写入本地缓存文件");
const tmpCrtPath = this.saveToFile("crt");
const tmpKeyPath = this.saveToFile("key");
const tmpPfxPath = this.saveToFile("pfx");
const tmpDerPath = this.saveToFile("der");
logger.info("本地文件写入成功");
try {
await opts.handle({
reader: this,
tmpCrtPath: tmpCrtPath,
tmpKeyPath: tmpKeyPath,
tmpPfxPath: tmpPfxPath,
tmpDerPath: tmpDerPath,
});
} finally {
//删除临时文件
logger.info("删除临时文件");
fs.unlinkSync(tmpCrtPath);
fs.unlinkSync(tmpKeyPath);
fs.unlinkSync(tmpPfxPath);
fs.unlinkSync(tmpDerPath);
}
}