From 61fff273fc85e2225fb17f6e2af0f8f2df6ff19d Mon Sep 17 00:00:00 2001 From: Thomas Cort Date: Mon, 10 Nov 2014 14:41:38 -0500 Subject: [PATCH] cli.js: add https support. Issue #71. --- conf/full.yaml | 6 ++++++ lib/cli.js | 30 ++++++++++++++++++++++++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/conf/full.yaml b/conf/full.yaml index 9185ac891..bff788303 100644 --- a/conf/full.yaml +++ b/conf/full.yaml @@ -84,6 +84,12 @@ packages: # to listen on INADDR_ANY use 0.0.0.0:4873 #listen: localhost:4873 +# Configure HTTPS. Set enable to true and supply a key and cert to enable HTTPS. +https: + enable: false + key: path/to/server.key + cert: path/to/server.crt + # type: file | stdout | stderr # level: trace | debug | info | http (default) | warn | error | fatal # diff --git a/lib/cli.js b/lib/cli.js index 47e092ea7..033891ea3 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -19,7 +19,10 @@ var logger = require('./logger') logger.setup() // default setup var commander = require('commander') +var constants = require('constants') var fs = require('fs') +var http = require('http') +var https = require('https') var YAML = require('js-yaml') var Path = require('path') var server = require('./index') @@ -73,16 +76,39 @@ function get_hostport() { function afterConfigLoad() { if (!config.self_path) config.self_path = Path.resolve(config_path) + if (!config.https) config.https = { enable: false }; var hostport = get_hostport() - server(config) + var app = server(config); + var webServer; + + if (config.https.enable === true) { // https + try { + webServer = https.createServer({ + secureProtocol: 'SSLv23_method', // disable insecure SSLv2 and SSLv3 + secureOptions: constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3, + key: fs.readFileSync(config.https.key), + cert: fs.readFileSync(config.https.cert) + }, app); + } catch (err) { // catch errors related to certificate loading + logger.logger.fatal({err: err}, 'cannot create server: @{err.message}') + process.exit(2) + } + } else { // http + webServer = http.createServer(app); + } + + webServer .listen(hostport[1], hostport[0]) .on('error', function(err) { logger.logger.fatal({ err: err }, 'cannot create server: @{err.message}') process.exit(2) }) - logger.logger.warn({ addr: 'http://'+hostport[0]+':'+hostport[1]+'/', version: 'Sinopia/'+pkg.version }, 'http address - @{addr}') + logger.logger.warn({ + addr: (config.https.enable === true ? 'https' : 'http') + '://'+hostport[0]+':'+hostport[1]+'/', + version: 'Sinopia/'+pkg.version, + }, 'http address - @{addr}') // undocumented stuff for tests if (typeof(process.send) === 'function') {