forked from davewasmer/devcert
/
certificates.ts
46 lines (39 loc) · 2.05 KB
/
certificates.ts
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
// import path from 'path';
import createDebug from 'debug';
import { sync as mkdirp } from 'mkdirp';
import { chmodSync as chmod } from 'fs';
import { pathForDomain, withDomainSigningRequestConfig, withDomainCertificateConfig } from './constants';
import { openssl } from './utils';
import { withCertificateAuthorityCredentials } from './certificate-authority';
const debug = createDebug('devcert:certificates');
/**
* Generate a domain certificate signed by the devcert root CA. Domain
* certificates are cached in their own directories under
* CONFIG_ROOT/domains/<domain>, and reused on subsequent requests. Because the
* individual domain certificates are signed by the devcert root CA (which was
* added to the OS/browser trust stores), they are trusted.
*/
export default async function generateDomainCertificate(domains: string[]): Promise<void> {
mkdirp(pathForDomain(domains[0]));
debug(`Generating private key for ${domains}`);
let domainKeyPath = pathForDomain(domains[0], 'private-key.key');
generateKey(domainKeyPath);
debug(`Generating certificate signing request for ${domains}`);
let csrFile = pathForDomain(domains[0], `certificate-signing-request.csr`);
withDomainSigningRequestConfig(domains, (configpath) => {
openssl(`req -new -config "${configpath}" -key "${domainKeyPath}" -out "${csrFile}"`);
});
debug(`Generating certificate for ${domains} from signing request and signing with root CA`);
let domainCertPath = pathForDomain(domains[0], `certificate.crt`);
await withCertificateAuthorityCredentials(({caKeyPath, caCertPath}) => {
withDomainCertificateConfig(domains, (domainCertConfigPath) => {
openssl(`ca -config "${domainCertConfigPath}" -in "${csrFile}" -out "${domainCertPath}" -keyfile "${caKeyPath}" -cert "${caCertPath}" -days 825 -batch`)
});
});
}
// Generate a cryptographic key, used to sign certificates or certificate signing requests.
export function generateKey(filename: string): void {
debug(`generateKey: ${ filename }`);
openssl(`genrsa -out "${ filename }" 2048`);
chmod(filename, 400);
}