All files / packages/mkcert/dist index.cjs

0% Statements 0/202
0% Branches 0/1
0% Functions 0/1
0% Lines 0/202

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 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211                                                                                                                                                                                                                                                                                                                                                                                                                                     
'use strict';
 
const utils = require('@https-enable/utils');
const fs = require('node:fs');
const path = require('node:path');
const process = require('node:process');
const mkcert = require('mkcert');
const Logger = require('@https-enable/logger');
const crypto = require('node:crypto');
const tls = require('node:tls');
const dayjs = require('dayjs');
const forge = require('node-forge');
 
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
 
const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
const path__default = /*#__PURE__*/_interopDefaultCompat(path);
const process__default = /*#__PURE__*/_interopDefaultCompat(process);
const Logger__default = /*#__PURE__*/_interopDefaultCompat(Logger);
const crypto__default = /*#__PURE__*/_interopDefaultCompat(crypto);
const tls__default = /*#__PURE__*/_interopDefaultCompat(tls);
const dayjs__default = /*#__PURE__*/_interopDefaultCompat(dayjs);
const forge__default = /*#__PURE__*/_interopDefaultCompat(forge);
 
function createLogFormat(colorize = false) {
  return Logger__default.createLogFormat(colorize, "mkcert");
}
const logger = new Logger__default({
  format: createLogFormat(),
  transports: [
    new Logger.Transports.Console({
      format: createLogFormat(true)
    })
  ]
});
 
const defaultCertificateBasePath = path__default.join(process__default.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__default.join(basePath, "key.pem"),
    certPath: path__default.join(basePath, "cert.pem")
  };
}
function readCertificate(options) {
  try {
    const { keyPath, certPath } = processCertPath(options);
    return {
      key: fs__default.readFileSync(keyPath, { encoding: "utf-8" }),
      cert: fs__default.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__default.dirname(certPath);
  if (!fs__default.existsSync(CERTS_DIR)) {
    fs__default.mkdirSync(CERTS_DIR, { recursive: true });
  }
  fs__default.writeFileSync(keyPath, key, { encoding: "utf-8" });
  fs__default.writeFileSync(certPath, cert, { encoding: "utf-8" });
  logger.info(`Certificate saved to ${path__default.resolve(certPath)}`);
  return { keyPath, certPath };
}
async function createCertificate(_options, pathOptions, isCache = true) {
  const { force, ...options } = _options;
  return new Promise((resolve, reject) => {
    mkcert.createCA(options).then((ca) => {
      mkcert.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__default.createSecureContext({ key: options.key, cert: options.cert });
  const tlsOptions = {
    host: options.host,
    port: Number(options.port),
    secureContext,
    rejectUnauthorized: options.rejectUnauthorized
  };
  const socket = tls__default.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__default.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__default.pki.certificateFromPem(certPem);
  const privateKey = forge__default.pki.privateKeyFromPem(keyPem);
  const publicKey = cert.publicKey;
  const certModulus = publicKey.n.toString(16);
  const keyModulus = privateKey.n.toString(16);
  const certModulusMd5 = crypto__default.createHash("md5").update(certModulus).digest("hex");
  const keyModulusMd5 = crypto__default.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__default(validFrom).format("YYYY-MM-DD HH:mm:ss")} ~ ${dayjs__default(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__default(validFrom).format("YYYY-MM-DD HH:mm:ss")} - ${dayjs__default(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 (utils.isNil(options?.validity, true)) {
    logger.warn("'validity' is undefined; defaulting to 0.");
  }
  if (utils.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);
}
 
exports.createCertificate = createCertificate;
exports.defaultCertificateBasePath = defaultCertificateBasePath;
exports.defineCertificate = defineCertificate;
exports.initSSLCertificate = initSSLCertificate;
exports.processCertPath = processCertPath;
exports.readCertificate = readCertificate;
exports.saveCertificate = saveCertificate;
exports.verifyCertificate = verifyCertificate;
exports.verifyCertificateByTLS = verifyCertificateByTLS;
exports.verifyCertificateValidityByTLS = verifyCertificateValidityByTLS;