From 09a6e5def66210ce5bf172755a31874c4f0ddb7a Mon Sep 17 00:00:00 2001 From: simon Date: Wed, 1 Mar 2017 12:59:51 +0100 Subject: [PATCH 1/2] Added beforeMiddleware to force https --- lib/force-https.js | 13 +++++++++++++ server.js | 9 ++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 lib/force-https.js diff --git a/lib/force-https.js b/lib/force-https.js new file mode 100644 index 0000000..b4d82ec --- /dev/null +++ b/lib/force-https.js @@ -0,0 +1,13 @@ +'use strict'; + +function forceHttpsMiddleware(req, res, next) { + // Skip redirect if header indicates edge server received request over HTTPS or request is ELB health check + if (req.headers['x-forwarded-proto'] === 'https' || req.headers['user-agent'].indexOf('HealthChecker') >= 0) { + return next(); + } else { + // Otherwise redirect! + return res.redirect(301, `https://${req.hostname}${req.url}`); + } +}; + +module.exports = forceHttpsMiddleware; \ No newline at end of file diff --git a/server.js b/server.js index 2aec673..70264e7 100644 --- a/server.js +++ b/server.js @@ -4,12 +4,14 @@ const S3Downloader = require('fastboot-s3-downloader'); const S3Notifier = require('fastboot-s3-notifier'); const RedisCache = require('fastboot-redis-cache'); const FastBootAppServer = require('fastboot-app-server'); +const forceHttps = require('./lib/force-https'); const S3_BUCKET = process.env.FASTBOOT_S3_BUCKET; const S3_KEY = process.env.FASTBOOT_S3_KEY; const REDIS_HOST = process.env.FASTBOOT_REDIS_HOST; const REDIS_PORT = process.env.FASTBOOT_REDIS_PORT; const REDIS_EXPIRY = process.env.FASTBOOT_REDIS_EXPIRY; +const FORCE_HTTPS = process.env.FORCE_HTTPS; const USERNAME = process.env.FASTBOOT_USERNAME; const PASSWORD = process.env.FASTBOOT_PASSWORD; @@ -37,7 +39,12 @@ if (REDIS_HOST || REDIS_PORT) { let server = new FastBootAppServer({ downloader: downloader, notifier: notifier, - cache: cache + cache: cache, + beforeMiddleware(app) { + if (FORCE_HTTPS) { + app.use(forceHttps); + } + } }); server.start(); From 6b409f2bf7f65f97a8ca6402d195ac1a9b53cbe2 Mon Sep 17 00:00:00 2001 From: simon Date: Thu, 9 Mar 2017 11:12:26 +0100 Subject: [PATCH 2/2] fix for undefined user-agent --- lib/force-https.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/force-https.js b/lib/force-https.js index b4d82ec..b9ac354 100644 --- a/lib/force-https.js +++ b/lib/force-https.js @@ -1,8 +1,9 @@ 'use strict'; function forceHttpsMiddleware(req, res, next) { + let ua = req.headers['user-agent']; // Skip redirect if header indicates edge server received request over HTTPS or request is ELB health check - if (req.headers['x-forwarded-proto'] === 'https' || req.headers['user-agent'].indexOf('HealthChecker') >= 0) { + if (req.headers['x-forwarded-proto'] === 'https' || (ua && ua.indexOf('HealthChecker') >= 0)) { return next(); } else { // Otherwise redirect!