diff --git a/bin/web.js b/bin/web.js index a7baacec..a0ed6d66 100644 --- a/bin/web.js +++ b/bin/web.js @@ -3,6 +3,9 @@ var uuid = require('uuid'); var basicAuth = require('basic-auth'); var Analytics = require('analytics-node'); var nuts = require('../'); +var fs = require('fs'); +var https = require('https'); + var app = express(); @@ -17,6 +20,36 @@ if (process.env.ANALYTICS_TOKEN) { analytics = new Analytics(process.env.ANALYTICS_TOKEN); } +// Set up for https termination +var key = "", cert = "" + +if (process.env.HTTPS_KEYFILE !== 'undefined') { + try { + key = fs.readFileSync(process.env.HTTPS_KEYFILE); + } catch (e) { + if (e.code === 'ENOENT') { + console.log('Key file not found!'); + } else { + throw e; + } + } +} +if (process.env.HTTPS_CERTFILE !== 'undefined') { + try { + cert = fs.readFileSync(process.env.HTTPS_CERTFILE); + } catch (e) { + if (e.code === 'ENOENT') { + console.log('Certificate file not found!'); + } else { + throw e; + } + } +} +var https_options = { + key: key, + cert: cert +}; + var myNuts = nuts.Nuts({ repository: process.env.GITHUB_REPO, token: process.env.GITHUB_TOKEN, @@ -118,8 +151,19 @@ app.use(function(err, req, res, next) { myNuts.init() -// Start the HTTP server +// Start the HTTP and/or HTTPS server .then(function() { + + // Enable https endpoint if key and cert are set + if(key != "" && cert != "") { + var https_server = https.createServer(https_options, app).listen(process.env.HTTPSPORT || 5001, function () { + var hosts = https_server.address().address; + var ports = https_server.address().port; + + console.log('Listening at https://%s:%s', hosts, ports); + }); + } + var server = app.listen(process.env.PORT || 5000, function () { var host = server.address().address; var port = server.address().port; diff --git a/docs/deploy.md b/docs/deploy.md index ff669aea..93709901 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -27,9 +27,14 @@ $ npm install This service requires to be configured using environment variables: ``` -# Set the port for the service +# Set the port for the http service $ export PORT=6000 +# Set the port for the https service (optional) +$ export HTTPSPORT=6001 +$ export HTTPS_KEYFILE= +$ export HTTPS_CERTFILE= + # Access token for the GitHub API (requires permissions to access the repository) # If the repository is public you do not need to provide an access token # you can also use GITHUB_USERNAME and GITHUB_PASSWORD