getHttpsConfig.js 1.8 KB
Newer Older
zhanghaozhe committed
1
"use strict"
zhanghaozhe committed
2

zhanghaozhe committed
3 4 5 6 7
const fs = require("fs")
const path = require("path")
const crypto = require("crypto")
const chalk = require("react-dev-utils/chalk")
const paths = require("./paths")
zhanghaozhe committed
8 9 10 11

// Ensure the certificate and key provided are valid and if not
// throw an easy to debug error
function validateKeyAndCerts({ cert, key, keyFile, crtFile }) {
zhanghaozhe committed
12
  let encrypted
zhanghaozhe committed
13 14
  try {
    // publicEncrypt will throw an error with an invalid cert
zhanghaozhe committed
15
    encrypted = crypto.publicEncrypt(cert, Buffer.from("test"))
zhanghaozhe committed
16 17 18
  } catch (err) {
    throw new Error(
      `The certificate "${chalk.yellow(crtFile)}" is invalid.\n${err.message}`
zhanghaozhe committed
19
    )
zhanghaozhe committed
20 21 22 23
  }

  try {
    // privateDecrypt will throw an error with an invalid key
zhanghaozhe committed
24
    crypto.privateDecrypt(key, encrypted)
zhanghaozhe committed
25 26 27 28 29
  } catch (err) {
    throw new Error(
      `The certificate key "${chalk.yellow(keyFile)}" is invalid.\n${
        err.message
      }`
zhanghaozhe committed
30
    )
zhanghaozhe committed
31 32 33 34 35 36 37 38 39 40
  }
}

// Read file and throw an error if it doesn't exist
function readEnvFile(file, type) {
  if (!fs.existsSync(file)) {
    throw new Error(
      `You specified ${chalk.cyan(
        type
      )} in your env, but the file "${chalk.yellow(file)}" can't be found.`
zhanghaozhe committed
41
    )
zhanghaozhe committed
42
  }
zhanghaozhe committed
43
  return fs.readFileSync(file)
zhanghaozhe committed
44 45 46 47 48
}

// Get the https config
// Return cert files if provided in env, otherwise just true or false
function getHttpsConfig() {
zhanghaozhe committed
49 50
  const { SSL_CRT_FILE, SSL_KEY_FILE, HTTPS } = process.env
  const isHttps = HTTPS === "true"
zhanghaozhe committed
51 52

  if (isHttps && SSL_CRT_FILE && SSL_KEY_FILE) {
zhanghaozhe committed
53 54
    const crtFile = path.resolve(paths.appPath, SSL_CRT_FILE)
    const keyFile = path.resolve(paths.appPath, SSL_KEY_FILE)
zhanghaozhe committed
55
    const config = {
zhanghaozhe committed
56 57 58
      cert: readEnvFile(crtFile, "SSL_CRT_FILE"),
      key: readEnvFile(keyFile, "SSL_KEY_FILE"),
    }
zhanghaozhe committed
59

zhanghaozhe committed
60 61
    validateKeyAndCerts({ ...config, keyFile, crtFile })
    return config
zhanghaozhe committed
62
  }
zhanghaozhe committed
63
  return isHttps
zhanghaozhe committed
64 65
}

zhanghaozhe committed
66
module.exports = getHttpsConfig