From abe5f3b25d97512ed5cae3b42f2f4e3aa72bde2c Mon Sep 17 00:00:00 2001 From: Nick Date: Sun, 24 Feb 2019 14:05:38 -0500 Subject: [PATCH] feat: HTTP redirect to HTTPS server option --- config.sample.yml | 4 ++++ server/master.js | 40 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/config.sample.yml b/config.sample.yml index fc802660..7ee36eaa 100644 --- a/config.sample.yml +++ b/config.sample.yml @@ -66,6 +66,10 @@ ssl: # to 1024 bits (default: null): dhparam: null + # Listen on this HTTP port and redirect all requests to HTTPS. + # Set to false to disable (default: 80): + redirectNonSSLPort: 80 + # --------------------------------------------------------------------- # IP address the server should listen to # --------------------------------------------------------------------- diff --git a/server/master.js b/server/master.js index b3440aba..5b2f78f8 100644 --- a/server/master.js +++ b/server/master.js @@ -165,7 +165,7 @@ module.exports = async () => { }) // ---------------------------------------- - // HTTP server + // HTTP/S server // ---------------------------------------- let srvConnections = {} @@ -193,6 +193,14 @@ module.exports = async () => { return process.exit(1) } WIKI.server = https.createServer(tlsOpts, app) + + // HTTP Redirect Server + if (WIKI.config.ssl.redirectNonSSLPort) { + WIKI.serverAlt = http.createServer((req, res) => { + res.writeHead(301, { 'Location': 'https://' + req.headers['host'] + req.url }) + res.end() + }) + } } else { WIKI.logger.info(`HTTP Server on port: [ ${WIKI.config.port} ]`) WIKI.server = http.createServer(app) @@ -229,6 +237,32 @@ module.exports = async () => { WIKI.server.on('listening', () => { if (WIKI.config.ssl.enabled) { WIKI.logger.info('HTTPS Server: [ RUNNING ]') + + // Start HTTP Redirect Server + if (WIKI.config.ssl.redirectNonSSLPort) { + WIKI.serverAlt.listen(WIKI.config.ssl.redirectNonSSLPort, WIKI.config.bindIP) + + WIKI.serverAlt.on('error', (error) => { + if (error.syscall !== 'listen') { + throw error + } + + switch (error.code) { + case 'EACCES': + WIKI.logger.error('(HTTP Redirect) Listening on port ' + WIKI.config.port + ' requires elevated privileges!') + return process.exit(1) + case 'EADDRINUSE': + WIKI.logger.error('(HTTP Redirect) Port ' + WIKI.config.port + ' is already in use!') + return process.exit(1) + default: + throw error + } + }) + + WIKI.serverAlt.on('listening', () => { + WIKI.logger.info('HTTP Server: [ RUNNING in redirect mode ]') + }) + } } else { WIKI.logger.info('HTTP Server: [ RUNNING ]') } @@ -239,6 +273,10 @@ module.exports = async () => { for (let key in srvConnections) { srvConnections[key].destroy() } + + if (WIKI.config.ssl.enabled && WIKI.config.ssl.redirectNonSSLPort) { + WIKI.serverAlt.close(cb) + } } return true