|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const fs = require('fs'); |
| 4 | +const path = require('path'); |
| 5 | +const crypto = require('crypto'); |
| 6 | +const paths = require('./paths'); |
| 7 | + |
| 8 | +// Ensure the certificate and key provided are valid and if not |
| 9 | +// throw an easy to debug error |
| 10 | +function validateKeyAndCerts({ cert, key, keyFile, crtFile }) { |
| 11 | + let encrypted; |
| 12 | + try { |
| 13 | + // publicEncrypt will throw an error with an invalid cert |
| 14 | + encrypted = crypto.publicEncrypt(cert, Buffer.from('test')); |
| 15 | + } catch (err) { |
| 16 | + throw new Error( |
| 17 | + `The certificate "${crtFile}" is invalid.\n${err.message}` |
| 18 | + ); |
| 19 | + } |
| 20 | + |
| 21 | + try { |
| 22 | + // privateDecrypt will throw an error with an invalid key |
| 23 | + crypto.privateDecrypt(key, encrypted); |
| 24 | + } catch (err) { |
| 25 | + throw new Error( |
| 26 | + `The certificate key "${keyFile}" is invalid.\n${ |
| 27 | + err.message |
| 28 | + }` |
| 29 | + ); |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +// Read file and throw an error if it doesn't exist |
| 34 | +function readEnvFile(file, type) { |
| 35 | + if (!fs.existsSync(file)) { |
| 36 | + throw new Error( |
| 37 | + `You specified ${type} in your env, but the file "${file}" can't be found.` |
| 38 | + ); |
| 39 | + } |
| 40 | + return fs.readFileSync(file); |
| 41 | +} |
| 42 | + |
| 43 | +// Get the https config |
| 44 | +// Return cert files if provided in env, otherwise just true or false |
| 45 | +function getHttpsConfig() { |
| 46 | + const { SSL_CRT_FILE, SSL_KEY_FILE, HTTPS } = process.env; |
| 47 | + const isHttps = HTTPS === 'true'; |
| 48 | + |
| 49 | + if (isHttps && SSL_CRT_FILE && SSL_KEY_FILE) { |
| 50 | + const crtFile = path.resolve(paths.appPath, SSL_CRT_FILE); |
| 51 | + const keyFile = path.resolve(paths.appPath, SSL_KEY_FILE); |
| 52 | + const config = { |
| 53 | + cert: readEnvFile(crtFile, 'SSL_CRT_FILE'), |
| 54 | + key: readEnvFile(keyFile, 'SSL_KEY_FILE'), |
| 55 | + }; |
| 56 | + |
| 57 | + validateKeyAndCerts({ ...config, keyFile, crtFile }); |
| 58 | + return config; |
| 59 | + } |
| 60 | + return isHttps; |
| 61 | +} |
| 62 | + |
| 63 | +module.exports = getHttpsConfig; |
0 commit comments