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.

66 lines
1.8 KiB

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