1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
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 |
|
18 |
|
19 | function validateKeyAndCerts({ cert, key, keyFile, crtFile }) {
|
20 | let encrypted;
|
21 | try {
|
22 |
|
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 |
|
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 |
|
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 |
|
55 |
|
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;
|