You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
1.2 KiB

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