2021-11-10 01:40:57 +03:00
|
|
|
const fs = require('fs');
|
|
|
|
const util = require('util');
|
|
|
|
const https = require('https');
|
|
|
|
|
|
|
|
const promise = util.promisify;
|
|
|
|
const stat = promise(fs.stat);
|
|
|
|
|
2022-03-07 13:50:24 +03:00
|
|
|
const httpsCerts = {
|
|
|
|
private: process.env.SSL_PRIV_KEY_PATH || '/etc/ssl/certs/dashy-priv.key',
|
|
|
|
public: process.env.SSL_PUB_KEY_PATH || '/etc/ssl/certs/dashy-pub.pem',
|
|
|
|
};
|
|
|
|
|
|
|
|
const isDocker = !!process.env.IS_DOCKER;
|
|
|
|
const SSLPort = process.env.SSL_PORT || (isDocker ? 443 : 4001);
|
2022-03-07 14:11:06 +03:00
|
|
|
const redirectHttps = process.env.REDIRECT_HTTPS ? process.env.REDIRECT_HTTPS : true;
|
2021-11-10 01:40:57 +03:00
|
|
|
|
2022-03-07 13:50:24 +03:00
|
|
|
const printNotSoGood = (msg) => {
|
|
|
|
console.log(`SSL Not Enabled: ${msg}`);
|
|
|
|
};
|
2021-11-10 01:40:57 +03:00
|
|
|
|
2022-03-07 13:50:24 +03:00
|
|
|
const printSuccess = () => {
|
|
|
|
console.log(`🔐 HTTPS server successfully started (port: ${SSLPort} ${isDocker ? 'of container' : ''})`);
|
|
|
|
};
|
2021-11-10 01:40:57 +03:00
|
|
|
|
2022-03-07 13:50:24 +03:00
|
|
|
// Check if the SSL certs are present and SSL should be enabled
|
|
|
|
let enableSSL = false;
|
|
|
|
stat(httpsCerts.public).then(() => {
|
|
|
|
stat(httpsCerts.private).then(() => {
|
|
|
|
enableSSL = true;
|
|
|
|
}).catch(() => { printNotSoGood('Private key not present'); });
|
|
|
|
}).catch(() => { printNotSoGood('Public key not present'); });
|
2021-11-10 01:40:57 +03:00
|
|
|
|
2022-03-07 13:50:24 +03:00
|
|
|
const startSSLServer = (app) => {
|
|
|
|
// If SSL should be enabled, create a secured server and start it
|
|
|
|
if (enableSSL) {
|
2021-11-10 01:40:57 +03:00
|
|
|
const httpsServer = https.createServer({
|
|
|
|
key: fs.readFileSync(httpsCerts.private),
|
|
|
|
cert: fs.readFileSync(httpsCerts.public),
|
|
|
|
}, app);
|
|
|
|
httpsServer.listen(SSLPort, () => { printSuccess(); });
|
2022-03-07 13:50:24 +03:00
|
|
|
}
|
2021-11-10 01:40:57 +03:00
|
|
|
};
|
2022-03-07 13:50:24 +03:00
|
|
|
|
|
|
|
const middleware = (req, res, next) => {
|
|
|
|
if (enableSSL && redirectHttps && req.protocol === 'http') {
|
|
|
|
res.redirect(`https://${req.hostname + ((SSLPort === 443) ? '' : `:${SSLPort}`) + req.url}`);
|
|
|
|
} else {
|
|
|
|
next();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = { startSSLServer, middleware };
|