Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | import { isNil } from '@https-enable/utils'; import fs from 'node:fs'; import path from 'node:path'; import process from 'node:process'; import { createCA, createCert } from 'mkcert'; import Logger, { Transports } from '@https-enable/logger'; import crypto from 'node:crypto'; import tls from 'node:tls'; import dayjs from 'dayjs'; import forge from 'node-forge'; function createLogFormat(colorize = false) { return Logger.createLogFormat(colorize, "mkcert"); } const logger = new Logger({ format: createLogFormat(), transports: [ new Transports.Console({ format: createLogFormat(true) }) ] }); const defaultCertificateBasePath = path.join(process.cwd(), "cert"); function processCertPath(certPath = { base: defaultCertificateBasePath }) { if ("cert" in certPath && "key" in certPath && certPath.cert && certPath.key) { return { keyPath: certPath.key, certPath: certPath.cert }; } const basePath = "base" in certPath && certPath.base || defaultCertificateBasePath; return { keyPath: path.join(basePath, "key.pem"), certPath: path.join(basePath, "cert.pem") }; } function readCertificate(options) { try { const { keyPath, certPath } = processCertPath(options); return { key: fs.readFileSync(keyPath, { encoding: "utf-8" }), cert: fs.readFileSync(certPath, { encoding: "utf-8" }) }; } catch (error) { logger.error(`${error}`); return null; } } function saveCertificate(cert, key, options) { const { keyPath, certPath } = processCertPath(options); const CERTS_DIR = path.dirname(certPath); if (!fs.existsSync(CERTS_DIR)) { fs.mkdirSync(CERTS_DIR, { recursive: true }); } fs.writeFileSync(keyPath, key, { encoding: "utf-8" }); fs.writeFileSync(certPath, cert, { encoding: "utf-8" }); logger.info(`Certificate saved to ${path.resolve(certPath)}`); return { keyPath, certPath }; } async function createCertificate(_options, pathOptions, isCache = true) { const { force, ...options } = _options; return new Promise((resolve, reject) => { createCA(options).then((ca) => { createCert({ ca: { key: ca.key, cert: ca.cert }, domains: Array.isArray(options.domains) ? options.domains : options.domains ? [options.domains] : [], validity: options.validity }).then((cert) => { isCache && saveCertificate(cert.cert, cert.key, pathOptions); resolve(cert); }).catch(reject); }).catch(reject); }); } function verifyCertificateByTLS(options) { const secureContext = tls.createSecureContext({ key: options.key, cert: options.cert }); const tlsOptions = { host: options.host, port: Number(options.port), secureContext, rejectUnauthorized: options.rejectUnauthorized }; const socket = tls.connect(tlsOptions, () => { logger.info("\u8BC1\u4E66\u6709\u6548"); socket.end(); }); socket.on("error", (err) => { logger.error(err.toString()); }); } function verifyCertificateValidityByTLS(options) { const tlsOptions = { host: options.host, port: Number(options.port), rejectUnauthorized: options.rejectUnauthorized }; const socket = tls.connect(tlsOptions, () => { const cert = socket.getPeerCertificate(); const validFrom = new Date(cert.valid_from).getTime(); const validTo = new Date(cert.valid_to).getTime(); const now = Date.now(); if (now > validFrom && now < validTo) logger.info("\u8BC1\u4E66\u6709\u6548"); else logger.warn("\u8BC1\u4E66\u65E0\u6548\uFF1A\u4E0D\u5728\u6709\u6548\u671F\u5185"); socket.end(); }); socket.on("error", (err) => { logger.error(`${err}`); }); } async function verifyCertificate(keyPem, certPem) { const cert = forge.pki.certificateFromPem(certPem); const privateKey = forge.pki.privateKeyFromPem(keyPem); const publicKey = cert.publicKey; const certModulus = publicKey.n.toString(16); const keyModulus = privateKey.n.toString(16); const certModulusMd5 = crypto.createHash("md5").update(certModulus).digest("hex"); const keyModulusMd5 = crypto.createHash("md5").update(keyModulus).digest("hex"); const matchs = []; const messages = []; if (certModulusMd5 === keyModulusMd5) { matchs.push(true); messages.push("\u8BC1\u4E66\u548C\u79C1\u94A5\u5339\u914D"); } else { matchs.push(false); messages.push("\u8BC1\u4E66\u548C\u79C1\u94A5\u4E0D\u5339\u914D"); } const now = /* @__PURE__ */ new Date(); const validFrom = cert.validity.notBefore; const validTo = cert.validity.notAfter; if (now > validFrom && now < validTo) { matchs.push(true); messages.push( `\u8BC1\u4E66\u5728\u6709\u6548\u671F\u5185\uFF0C\u6709\u6548\u671F\uFF1A${dayjs(validFrom).format("YYYY-MM-DD HH:mm:ss")} ~ ${dayjs(validTo).format("YYYY-MM-DD HH:mm:ss")}` ); } else { matchs.push(false); messages.push( `\u8BC1\u4E66\u4E0D\u5728\u6709\u6548\u671F\u5185\uFF0C\u6709\u6548\u671F\uFF1A${dayjs(validFrom).format("YYYY-MM-DD HH:mm:ss")} - ${dayjs(validTo).format("YYYY-MM-DD HH:mm:ss")}` ); } const match = matchs.every((m) => m); const message = messages.join(", "); return { match, message }; } async function initSSLCertificate(options, pathOptions) { const pem = readCertificate(pathOptions); if (pem !== null && !options.force) { const verifyRes = await verifyCertificate(pem.key, pem.cert); if (!verifyRes.match) { logger.error(`\u279C ${verifyRes.message}`); logger.warn("\u279C \u8BC1\u4E66\u548C\u5BC6\u94A5\u5931\u6548\uFF0C\u6B63\u5728\u91CD\u65B0\u751F\u6210\u8BC1\u4E66\u548C\u5BC6\u94A5\u2026\u2026"); const httpsOptions2 = await createCertificate(options, pathOptions); logger.info("\u279C \u8BC1\u4E66\u548C\u5BC6\u94A5\u5DF2\u66F4\u65B0"); return httpsOptions2; } logger.info(`\u279C ${verifyRes.message}`); return pem; } logger.warn(`\u279C ${options.force ? "\u5F3A\u5236\u751F\u6210\u8BC1\u4E66\u548C\u5BC6\u94A5\u2026\u2026" : "\u8BC1\u4E66\u548C\u5BC6\u94A5\u4E0D\u5B58\u5728\uFF0C\u6B63\u5728\u751F\u6210\u8BC1\u4E66\u548C\u5BC6\u94A5\u2026\u2026"}`); const httpsOptions = await createCertificate(options, pathOptions); logger.info("\u279C \u8BC1\u4E66\u548C\u5BC6\u94A5\u5DF2\u751F\u6210"); return httpsOptions; } async function defineCertificate(options, pathOptions) { const { organization = "", countryCode = "", state = "", locality = "", validity = 0, domains = "0.0.0.0", force = false } = options ?? {}; if (isNil(options?.validity, true)) { logger.warn("'validity' is undefined; defaulting to 0."); } if (isNil(options?.domains, true)) { logger.warn("'domains' is undefined; defaulting to '0.0.0.0'."); } return await initSSLCertificate({ organization, countryCode, state, locality, validity, domains, force }, pathOptions); } export { createCertificate, defaultCertificateBasePath, defineCertificate, initSSLCertificate, processCertPath, readCertificate, saveCertificate, verifyCertificate, verifyCertificateByTLS, verifyCertificateValidityByTLS }; |