All files / packages/mkcert/src index.ts

100% Statements 43/43
100% Branches 15/15
100% Functions 2/2
100% Lines 43/43

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    1x 1x 1x 1x   7x 7x 7x 3x   3x 2x 2x 2x 2x   2x 2x   1x 1x 1x   7x 7x 4x   4x 4x   7x 7x 7x 7x 7x 7x 7x 7x 7x 7x       7x   1x 1x     7x 6x 6x   7x 7x   1x   1x  
import type { CertificatePath, CreateOptions } from './type'
 
import { isNil } from '@https-enable/utils'
import { createCertificate, readCertificate } from './common'
import logger from './logger'
import { verifyCertificate } from './verify'
 
export async function initSSLCertificate(options: CreateOptions, pathOptions?: CertificatePath) {
  const pem = readCertificate(pathOptions)
  if (pem !== null && !options.force) {
    const verifyRes = await verifyCertificate(pem.key, pem.cert)
 
    if (!verifyRes.match) {
      logger.error(`➜  ${verifyRes.message}`)
      logger.warn('➜  证书和密钥失效,正在重新生成证书和密钥……')
      const httpsOptions = await createCertificate(options, pathOptions)
      logger.info('➜  证书和密钥已更新')
 
      return httpsOptions
    }
 
    logger.info(`➜  ${verifyRes.message}`)
    return pem
  }
 
  logger.warn(`➜  ${options.force ? '强制生成证书和密钥……' : '证书和密钥不存在,正在生成证书和密钥……'}`)
  const httpsOptions = await createCertificate(options, pathOptions)
  logger.info('➜  证书和密钥已生成')
 
  return httpsOptions
}
 
export async function defineCertificate(options?: Pick<CreateOptions, 'validity'> & Partial<Omit<CreateOptions, 'validity'>>, pathOptions?: CertificatePath) {
  const {
    organization = '',
    countryCode = '',
    state = '',
    locality = '',
    validity = 0,
    domains = '0.0.0.0',
    force = false,
  } = options ?? {}
 
  // eslint-disable-next-line ts/ban-ts-comment
  // @ts-ignore
  if (isNil(options?.validity, true)) {
    // "validity" is not defined and will be set to 0.
    logger.warn('\'validity\' is undefined; defaulting to 0.')
  }
  // eslint-disable-next-line ts/ban-ts-comment
  // @ts-ignore
  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 * from './common'
export type * from './type'
export * from './verify'