diff --git a/packages/plugins/plugin-lib/src/cert/cert-reader.ts b/packages/plugins/plugin-lib/src/cert/cert-reader.ts index 0bf366c5b..49cfb8c63 100644 --- a/packages/plugins/plugin-lib/src/cert/cert-reader.ts +++ b/packages/plugins/plugin-lib/src/cert/cert-reader.ts @@ -280,9 +280,14 @@ export class CertReader { return `${prefix}_${domain}_${timeStr}.${suffix}`; } - buildCertName(prefix: string = "") { + buildCertName(prefix: string = "", useHash: boolean = false) { let domain = this.getMainDomain(); domain = domain.replaceAll(".", "_").replaceAll("*", "_"); + if (useHash) { + const domains = JSON.stringify(this.getAllDomains()); + const hash = cryptoLib.createHash("md5").update(domains).digest("hex").slice(0, 16); + return `${prefix}_${domain}_${hash}`; + } return `${prefix}_${domain}_${dayjs().format("YYYYMMDDHHmmssSSS")}`; } @@ -293,7 +298,7 @@ export class CertReader { return name + "_" + dayjs().format("YYYYMMDDHHmmssSSS"); } - static buildCertName(cert: CertInfo) { - return new CertReader(cert).buildCertName(); + static buildCertName(cert: CertInfo, useHash: boolean = false) { + return new CertReader(cert).buildCertName("", useHash); } } diff --git a/packages/ui/certd-server/src/plugins/plugin-asiaisp/client.ts b/packages/ui/certd-server/src/plugins/plugin-asiaisp/client.ts index eedb337ed..81bd6636e 100644 --- a/packages/ui/certd-server/src/plugins/plugin-asiaisp/client.ts +++ b/packages/ui/certd-server/src/plugins/plugin-asiaisp/client.ts @@ -188,21 +188,40 @@ export class AsiaIspClient { */ async uploadCert(req: { cert: CertInfo; name?: string }): Promise { const certReader = new CertReader(req.cert); - const certName = req.name || certReader.buildCertName(); + const certName = req.name || certReader.buildCertName("", true); - const res = await this.doRequest({ - method: "POST", - action: "certificateUpload", - data: { - name: certName, - publicKey: req.cert.crt, - privateKey: req.cert.key, - }, - }); + try { + const res = await this.doRequest({ + method: "POST", + action: "certificateUpload", + data: { + name: certName, + publicKey: req.cert.crt, + privateKey: req.cert.key, + }, + }); + const certId = res.data; + this.logger.info(`上传证书成功,证书ID: ${certId}`); + return certId; + } catch (e: any) { + const msg = e.message || ""; + const isExists = msg.includes("Certificate already exists") || e.code ==='80003' || + msg.includes("Certificate note name already exists") || e.code ==='80010' + //返回数据: {"code":"80010","msg":"Certificate note name already exists","data":null} + if (!isExists) { + throw e; + } - const certId = res.data; - this.logger.info(`上传证书成功,证书ID: ${certId}`); - return certId; + this.logger.info(`证书已存在,按名称查找: ${certName}`); + const list = await this.getCertList(); + const found = list.find((item: any) => item.name === certName); + if (!found) { + throw new Error(`证书已存在但无法查询到: ${certName}`); + } + const certId = Number(found.certId); + this.logger.info(`复用已有证书,证书ID: ${certId}`); + return certId; + } } /**