2015-07-07 23:19:44 +00:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
module.exports = function (opts) {
|
|
|
|
var escapeHtml = require('escape-html');
|
|
|
|
|
|
|
|
if (!opts) {
|
|
|
|
opts = {};
|
|
|
|
}
|
|
|
|
if (isNaN(opts.port)) {
|
|
|
|
opts.port = 443;
|
|
|
|
}
|
|
|
|
if (!('body' in opts)) {
|
|
|
|
opts.body = "<!-- Hello Mr Developer! We don't serve insecure resources around here."
|
|
|
|
+ "\n Please use HTTPS instead. -->";
|
|
|
|
}
|
|
|
|
opts.body = opts.body.replace(/{{\s+PORT\s+}}/i, opts.port);
|
|
|
|
|
|
|
|
return function (req, res, next) {
|
|
|
|
if (req.connection.encrypted
|
|
|
|
|| 'https' === req.protocol
|
|
|
|
|| (opts.trustProxy && 'https' === req.headers['x-forwarded-proto'])
|
|
|
|
) {
|
|
|
|
next();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
var url = req.url;
|
|
|
|
var host = req.headers.host || '';
|
2016-11-21 22:45:05 +00:00
|
|
|
if (!/:\d+/.test(host) && 443 !== opts.port) {
|
|
|
|
// we are using standard port 80, but we aren't using standard port 443
|
|
|
|
host += ':80';
|
|
|
|
}
|
2015-07-07 23:19:44 +00:00
|
|
|
var newLocation = 'https://'
|
|
|
|
+ host.replace(/:\d+/, ':' + opts.port) + url
|
|
|
|
;
|
|
|
|
//var encodedLocation = encodeURI(newLocation);
|
|
|
|
var escapedLocation = escapeHtml(newLocation);
|
2018-02-26 19:02:44 +00:00
|
|
|
var encodedLocation;
|
|
|
|
try {
|
|
|
|
encodedLocation = decodeURIComponent(newLocation);
|
|
|
|
} catch(e) {
|
2018-02-27 21:20:43 +00:00
|
|
|
encodedLocation = newLocation; // "#/error/?error_message=" + e.toString();
|
2018-02-26 19:02:44 +00:00
|
|
|
}
|
2015-07-07 23:19:44 +00:00
|
|
|
var body = opts.body
|
2018-02-26 19:02:44 +00:00
|
|
|
.replace(/{{\s*HTML_URL\s*}}/ig, escapeHtml(encodedLocation))
|
2015-07-07 23:19:44 +00:00
|
|
|
.replace(/{{\s*URL\s*}}/ig, escapedLocation)
|
|
|
|
.replace(/{{\s*UNSAFE_URL\s*}}/ig, newLocation)
|
|
|
|
;
|
|
|
|
|
|
|
|
var metaRedirect = ''
|
|
|
|
+ '<html>\n'
|
|
|
|
+ '<head>\n'
|
|
|
|
//+ ' <style>* { background-color: white; color: white; text-decoration: none; }</style>\n'
|
|
|
|
+ ' <META http-equiv="refresh" content="0;URL=\'' + escapedLocation + '\'">\n'
|
|
|
|
+ '</head>\n'
|
2016-11-21 01:49:14 +00:00
|
|
|
+ '<body>\n' + body + '\n</body>\n'
|
2015-07-07 23:19:44 +00:00
|
|
|
+ '</html>\n'
|
|
|
|
;
|
|
|
|
|
|
|
|
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
|
|
res.end(metaRedirect);
|
|
|
|
};
|
|
|
|
};
|