'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 = ""; } opts.body = opts.body.replace(/{{\s+PORT\s+}}/ig, 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.originalUrl || req.url); var host = req.headers.host || ''; if (!/:\d+/.test(host) && 443 !== opts.port) { // we are using standard port 80, but we aren't using standard port 443 host += ':80'; } var newLocation = 'https://' + host.replace(/:\d+/, ':' + opts.port) + url ; //var encodedLocation = encodeURI(newLocation); var escapedLocation = escapeHtml(newLocation); var decodedLocation; try { decodedLocation = decodeURIComponent(newLocation); } catch(e) { decodedLocation = newLocation; // "#/error/?error_message=" + e.toString(); } var body = opts.body .replace(/{{\s*HTML_URL\s*}}/ig, escapeHtml(decodedLocation)) .replace(/{{\s*URL\s*}}/ig, escapedLocation) .replace(/{{\s*UNSAFE_URL\s*}}/ig, newLocation) ; var metaRedirect = '' + '\n' + '
\n' //+ ' \n' + ' \n' + '\n' + '\n' + body + '\n\n' + '\n' ; if (opts.headerRedirect) { res.statusCode = opts.headerRedirect.responseCode || 302; res.setHeader('Location', newLocation); } res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end(metaRedirect); }; };