getHttpsConfig.js 2.0 KB

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