UNPKG

@epmkit/cra-template-epm-plugin

Version:

The base template for EPM plugins.

66 lines (57 loc) 1.88 kB
'use strict'; const fs = require('fs'); const path = require('path'); const crypto = require('crypto'); const chalk = require('react-dev-utils/chalk'); const paths = require('./paths'); // 确保提供的证书和密钥有效,如果无效则抛出易于调试的错误 function validateKeyAndCerts({ cert, key, keyFile, crtFile }) { let encrypted; try { // 如果证书无效,publicEncrypt 会抛出错误 encrypted = crypto.publicEncrypt(cert, Buffer.from('test')); } catch (err) { throw new Error( `The certificate "${chalk.yellow(crtFile)}" is invalid.\n${err.message}` ); } try { // 如果密钥无效,privateDecrypt 会抛出错误 crypto.privateDecrypt(key, encrypted); } catch (err) { throw new Error( `The certificate key "${chalk.yellow(keyFile)}" is invalid.\n${ err.message }` ); } } // 读取文件,如果文件不存在则抛出错误 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.` ); } return fs.readFileSync(file); } // 获取 HTTPS 配置 // 如果环境变量中提供了证书文件,则返回证书文件,否则返回 true 或 false function getHttpsConfig() { const { SSL_CRT_FILE, SSL_KEY_FILE, HTTPS } = process.env; const isHttps = HTTPS === 'true'; if (isHttps && SSL_CRT_FILE && SSL_KEY_FILE) { const crtFile = path.resolve(paths.appPath, SSL_CRT_FILE); const keyFile = path.resolve(paths.appPath, SSL_KEY_FILE); const config = { cert: readEnvFile(crtFile, 'SSL_CRT_FILE'), key: readEnvFile(keyFile, 'SSL_KEY_FILE'), }; validateKeyAndCerts({ ...config, keyFile, crtFile }); return config; } return isHttps; } module.exports = getHttpsConfig;