-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
generateCertificate.js
130 lines (118 loc) Β· 2.75 KB
/
generateCertificate.js
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
const forge = require('node-forge');
const fs = require('fs');
const mkdirp = require('mkdirp');
const path = require('path');
const logger = require('@parcel/logger');
function generateCertificate(options = {}) {
const privateKeyPath = path.join(options.cacheDir, 'private.pem');
const certPath = path.join(options.cacheDir, 'primary.crt');
if (options.cache) {
const cachedKey =
fs.existsSync(privateKeyPath) && fs.readFileSync(privateKeyPath);
const cachedCert = fs.existsSync(certPath) && fs.readFileSync(certPath);
if (cachedKey && cachedCert) {
return {
key: cachedKey,
cert: cachedCert
};
}
}
logger.progress('Generating SSL Certificate...');
const pki = forge.pki;
const keys = pki.rsa.generateKeyPair(2048);
const cert = pki.createCertificate();
cert.publicKey = keys.publicKey;
cert.serialNumber = Date.now().toString();
cert.validity.notBefore = new Date();
cert.validity.notAfter = new Date();
cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1);
const attrs = [
{
name: 'commonName',
value: 'parceljs.org'
},
{
name: 'countryName',
value: 'US'
},
{
shortName: 'ST',
value: 'Virginia'
},
{
name: 'localityName',
value: 'Blacksburg'
},
{
name: 'organizationName',
value: 'parcelBundler'
},
{
shortName: 'OU',
value: 'Test'
}
];
cert.setSubject(attrs);
cert.setIssuer(attrs);
cert.setExtensions([
{
name: 'basicConstraints',
cA: true
},
{
name: 'keyUsage',
keyCertSign: true,
digitalSignature: true,
nonRepudiation: true,
keyEncipherment: true,
dataEncipherment: true
},
{
name: 'extKeyUsage',
serverAuth: true,
clientAuth: true,
codeSigning: true,
emailProtection: true,
timeStamping: true
},
{
name: 'nsCertType',
client: true,
server: true,
email: true,
objsign: true,
sslCA: true,
emailCA: true,
objCA: true
},
{
name: 'subjectAltName',
altNames: [
{
type: 6, // URI
value: 'http://example.org/webid#me'
},
{
type: 7, // IP
ip: '127.0.0.1'
}
]
},
{
name: 'subjectKeyIdentifier'
}
]);
cert.sign(keys.privateKey, forge.md.sha256.create());
const privPem = pki.privateKeyToPem(keys.privateKey);
const certPem = pki.certificateToPem(cert);
if (options.cache) {
mkdirp.sync(options.cacheDir);
fs.writeFileSync(privateKeyPath, privPem);
fs.writeFileSync(certPath, certPem);
}
return {
key: privPem,
cert: certPem
};
}
module.exports = generateCertificate;