1 | 'use strict';
|
---|
2 |
|
---|
3 | const path = require('path');
|
---|
4 | const fs = require('fs');
|
---|
5 | const del = require('del');
|
---|
6 | const createCertificate = require('./createCertificate');
|
---|
7 |
|
---|
8 | function getCertificate(logger) {
|
---|
9 | // Use a self-signed certificate if no certificate was configured.
|
---|
10 | // Cycle certs every 24 hours
|
---|
11 | const certificatePath = path.join(__dirname, '../../ssl/server.pem');
|
---|
12 |
|
---|
13 | let certificateExists = fs.existsSync(certificatePath);
|
---|
14 |
|
---|
15 | if (certificateExists) {
|
---|
16 | const certificateTtl = 1000 * 60 * 60 * 24;
|
---|
17 | const certificateStat = fs.statSync(certificatePath);
|
---|
18 |
|
---|
19 | const now = new Date();
|
---|
20 |
|
---|
21 | // cert is more than 30 days old, kill it with fire
|
---|
22 | if ((now - certificateStat.ctime) / certificateTtl > 30) {
|
---|
23 | logger.info('SSL Certificate is more than 30 days old. Removing.');
|
---|
24 |
|
---|
25 | del.sync([certificatePath], { force: true });
|
---|
26 |
|
---|
27 | certificateExists = false;
|
---|
28 | }
|
---|
29 | }
|
---|
30 |
|
---|
31 | if (!certificateExists) {
|
---|
32 | logger.info('Generating SSL Certificate');
|
---|
33 |
|
---|
34 | const attributes = [{ name: 'commonName', value: 'localhost' }];
|
---|
35 | const pems = createCertificate(attributes);
|
---|
36 |
|
---|
37 | fs.writeFileSync(certificatePath, pems.private + pems.cert, {
|
---|
38 | encoding: 'utf8',
|
---|
39 | });
|
---|
40 | }
|
---|
41 |
|
---|
42 | return fs.readFileSync(certificatePath);
|
---|
43 | }
|
---|
44 |
|
---|
45 | module.exports = getCertificate;
|
---|