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