All files / packages/core/src certificate-manager.ts

0% Statements 0/59
100% Branches 1/1
100% Functions 1/1
0% Lines 0/59

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                                                                                                                                                                           
import type { Certificate, CertificatePath, CreateOptions } from '@https-enable/mkcert'
import type { Prettify } from '@https-enable/types'
import type { CertificateEvents } from './emitter'
import type { CertificateManagerOptions } from './type'
import { EventEmitter } from 'node:events'
import { createCertificate, readCertificate, verifyCertificate } from '@https-enable/mkcert'
 
const defaultCA = {
  organization: '',
  countryCode: '',
  state: '',
  locality: '',
  force: false,
}
 
export class CertificateManager extends EventEmitter<CertificateEvents> {
  protected options: Prettify<CreateOptions & { cache?: boolean }>
  protected pathOptions: CertificatePath
  public currentCert: Certificate | null
 
  constructor(options: CertificateManagerOptions) {
    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?: boolean) {
    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 verifyCertificate(this.currentCert.key, this.currentCert.cert)
  }
 
  /**
   * 确保当前证书有效
   * @description 无效证书则自动重新创建
   */
  async ensureValidCert() {
    const verifyRes = await this.validCert()
    if (!verifyRes?.match) {
      await this.generateNewCert(this.options.cache)
    }
  }
 
  private async generateNewCert(isCache?: boolean) {
    this.currentCert = await createCertificate(this.options, this.pathOptions, isCache)
 
    // 触发 cert-renewed 事件
    this.emit('cert-renewed', { ...this.currentCert })
    return this.currentCert
  }
 
  // 加载证书
  private loadExistingCert() {
    return readCertificate(this.pathOptions)
  }
}