quasar

Форк
0
113 строк · 2.4 Кб
1
import { existsSync, readFileSync, writeFileSync, statSync } from 'node:fs'
2
import fse from 'fs-extra'
3
import { generate } from 'selfsigned'
4

5
const certPath = new URL('../ssl-server.pem', import.meta.url)
6

7
export function generateCertificate ({
8
  log,
9
  fatal
10
}) {
11
  log('Generating self signed localhost SSL Certificate...')
12

13
  const attrs = [
14
    { name: 'commonName', value: 'localhost' }
15
  ]
16

17
  const pems = generate(attrs, {
18
    algorithm: 'sha256',
19
    days: 30,
20
    keySize: 2048,
21
    extensions: [
22
      {
23
        name: 'basicConstraints',
24
        cA: true
25
      },
26
      {
27
        name: 'keyUsage',
28
        keyCertSign: true,
29
        digitalSignature: true,
30
        nonRepudiation: true,
31
        keyEncipherment: true,
32
        dataEncipherment: true
33
      },
34
      {
35
        name: 'extKeyUsage',
36
        serverAuth: true,
37
        clientAuth: true,
38
        codeSigning: true,
39
        timeStamping: true
40
      },
41
      {
42
        name: 'subjectAltName',
43
        altNames: [
44
          {
45
            // type 2 is DNS
46
            type: 2,
47
            value: 'localhost'
48
          },
49
          {
50
            type: 2,
51
            value: 'localhost.localdomain'
52
          },
53
          {
54
            type: 2,
55
            value: 'lvh.me'
56
          },
57
          {
58
            type: 2,
59
            value: '*.lvh.me'
60
          },
61
          {
62
            type: 2,
63
            value: '[::1]'
64
          },
65
          {
66
            // type 7 is IP
67
            type: 7,
68
            ip: '127.0.0.1'
69
          },
70
          {
71
            type: 7,
72
            ip: 'fe80::1'
73
          }
74
        ]
75
      }
76
    ]
77
  })
78

79
  const certContent = pems.private + pems.cert
80
  try {
81
    writeFileSync(certPath, certContent, 'utf-8')
82
  }
83
  catch (err) {
84
    console.error(err)
85
    fatal('Cannot write localhost SSL certificate to: ' + certPath + '. Aborting...')
86
  }
87

88
  return certContent
89
}
90

91
export function getCertificate ({
92
  log,
93
  fatal
94
}) {
95
  let certExists = existsSync(certPath)
96

97
  if (certExists === true) {
98
    const certStat = statSync(certPath)
99
    const certTtl = 1000 * 60 * 60 * 24
100
    const now = new Date()
101

102
    // cert is more than 30 days old
103
    if ((now - certStat.ctime) / certTtl > 30) {
104
      log('Localhost SSL Certificate is more than 30 days old. Removing.')
105
      fse.removeSync(certPath)
106
      certExists = false
107
    }
108
  }
109

110
  return certExists === true
111
    ? readFileSync(certPath, 'utf-8')
112
    : generateCertificate({ log, fatal })
113
}
114

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.