All files / packages/core/dist index.cjs

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

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 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
'use strict';
 
const node_events = require('node:events');
const mkcert = require('@https-enable/mkcert');
const http = require('node:http');
const net = require('node:net');
const process = require('node:process');
const tls = require('node:tls');
const Logger = require('@https-enable/logger');
 
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
 
const http__default = /*#__PURE__*/_interopDefaultCompat(http);
const net__default = /*#__PURE__*/_interopDefaultCompat(net);
const process__default = /*#__PURE__*/_interopDefaultCompat(process);
const tls__default = /*#__PURE__*/_interopDefaultCompat(tls);
const Logger__default = /*#__PURE__*/_interopDefaultCompat(Logger);
 
const defaultCA = {
  organization: "",
  countryCode: "",
  state: "",
  locality: "",
  force: false
};
class CertificateManager extends node_events.EventEmitter {
  options;
  pathOptions;
  currentCert;
  constructor(options) {
    super();
    if ("base" in options) {
      const { base, ...rest } = options;
      this.pathOptions = { base };
      this.options = {
        ...defaultCA,
        ...rest
      };
    } else {
      const { cert, key, ...rest } = options;
      this.pathOptions = { cert: options.cert, key: options.key };
      this.options = {
        ...defaultCA,
        ...rest
      };
    }
    this.currentCert = this.loadExistingCert();
  }
  /**
   * 初始化证书(生成或加载现有)
   */
  async initialize(force) {
    const verifyRes = await this.validCert();
    if ((force ?? this.options.force) || !verifyRes?.match)
      return await this.generateNewCert(this.options.cache);
    return this.currentCert;
  }
  async validCert() {
    if (!this.currentCert)
      return null;
    return await mkcert.verifyCertificate(this.currentCert.key, this.currentCert.cert);
  }
  /**
   * 确保当前证书有效
   * @description 无效证书则自动重新创建
   */
  async ensureValidCert() {
    const verifyRes = await this.validCert();
    if (!verifyRes?.match) {
      await this.generateNewCert(this.options.cache);
    }
  }
  async generateNewCert(isCache) {
    this.currentCert = await mkcert.createCertificate(this.options, this.pathOptions, isCache);
    this.emit("cert-renewed", { ...this.currentCert });
    return this.currentCert;
  }
  // 加载证书
  loadExistingCert() {
    return mkcert.readCertificate(this.pathOptions);
  }
}
 
function samePortSSL(app, options) {
  const isRedirect = options.redirect ?? false;
  const host = options.host;
  const port = Number(options.port);
  const tcpserver = net__default.createServer();
  let server = http__default.createServer(options, app);
  const redirectServer = http__default.createServer(isRedirect ? (req, res) => (res.writeHead(302, { location: `https://${req.headers.host || req.url}` }), res.end()) : app);
  tcpserver.listen(port, host);
  tcpserver.on("connection", (socket) => {
    socket.once("data", (data) => {
      socket.pause();
      if (data[0] === 22) {
        const sock = new tls__default.TLSSocket(socket, { isServer: true, ...options });
        server.emit("connection", sock);
        socket.unshift(data);
      } else {
        redirectServer.emit("connection", socket);
        socket.emit("data", data);
      }
      process__default.nextTick(() => socket.resume());
    });
  });
  class ServerInstance {
    isAlive = true;
    /**
     * Kill the server
     * @returns A promise that resolves when the server ends
     */
    kill() {
      return new Promise((resolve, fail) => {
        tcpserver.close((err) => {
          if (typeof err === "undefined") {
            server.closeAllConnections();
            redirectServer.closeAllConnections();
            this.isAlive = false;
            resolve();
          } else {
            fail(err);
          }
        });
      });
    }
    /**
     * Change the server options
     * @param newOptions The new server options
     * @param newOptions.cert cert content
     * @param newOptions.key key content
     */
    async refresh(newOptions) {
      if (newOptions && newOptions.cert && newOptions.key && typeof newOptions.cert === "string" && typeof newOptions.key === "string") {
        const verify = await mkcert.verifyCertificate(newOptions.key, newOptions.cert);
        if (!verify.match)
          return;
        options = { ...options, ...newOptions };
        return server = http__default.createServer(options, app);
      }
    }
  }
  return new Promise((resolve) => tcpserver.on("listening", () => resolve(new ServerInstance())));
}
 
class HttpsAdapter {
  constructor(app) {
    this.app = app;
  }
  serverInstance = null;
  /**
   * 启动 HTTPS 服务(可选,部分框架需要自定义逻辑)
   */
  async createServer(options, app) {
    let tempApp = app ?? this.app;
    if (this.init && typeof this.init === "function") {
      tempApp = await this.init();
    }
    if (!tempApp && !this.app) {
      throw new Error("`app` is no found");
    }
    this.serverInstance = await samePortSSL(tempApp ?? this.app, options);
    return this.serverInstance;
  }
}
 
function createLogFormat(colorize = false) {
  return Logger__default.createLogFormat(colorize, "https-enabler");
}
const logger = new Logger__default({
  format: createLogFormat(),
  transports: [
    new Logger.Transports.Console({
      format: createLogFormat(true)
    })
  ]
});
 
class HttpsEnabler extends node_events.EventEmitter {
  adapter;
  options;
  certificateOptions;
  certManager;
  constructor(config) {
    super();
    this.adapter = config.adapter;
    if (!this.adapter) {
      throw logger.error("Must provide the adapter");
    }
    if (!this.adapter.app && (!this.adapter.init || typeof this.adapter.init !== "function") || typeof this.adapter.createServer !== "function") {
      throw logger.error("The adapter is invalid");
    }
    this.options = config.options;
    this.certificateOptions = config.certificateOptions;
    this.certManager = new CertificateManager(this.certificateOptions);
    this.certManager.on("cert-renewed", async (newCert) => {
      this.emit("cert-renewed", newCert);
      await this.adapter.serverInstance?.refresh(newCert);
      this.adapter.onCertRenewed?.(newCert);
    });
  }
  async init() {
    await this.certManager.initialize().catch((err) => this.emit("error", err));
  }
  /**
   * 生成框架特定的中间件
   */
  middleware() {
    return this.adapter.createMiddleware?.(this.options);
  }
  refresh(options) {
    if (!this.adapter.serverInstance)
      return;
    return this.adapter.serverInstance.refresh(options);
  }
  kill() {
    if (!this.adapter.serverInstance)
      return;
    return this.adapter.serverInstance.kill();
  }
  /**
   * 启动 HTTPS 服务
   */
  async startServer(app) {
    await this.certManager.ensureValidCert();
    if (typeof this.adapter.createServer === "function" && this.certManager.currentCert) {
      const options = { ...this.options, ...this.certManager.currentCert };
      await this.adapter.createServer(options, app);
      return options;
    } else {
      throw new TypeError("Unsupported framework: default server logic requires an app with listen()");
    }
  }
}
 
exports.CertificateManager = CertificateManager;
exports.HttpsAdapter = HttpsAdapter;
exports.HttpsEnabler = HttpsEnabler;
exports.samePortSSL = samePortSSL;