redirect localhost and IP addresses to real domains

This commit is contained in:
tigerbot 2017-05-11 19:16:23 -06:00
parent 5777a885a4
commit 87de2c65ad
3 changed files with 41 additions and 2 deletions

View File

@ -19,6 +19,8 @@ tls:
http:
trustProxy: true
allowInsecure: false
primaryDomain: localhost.foo.daplie.me
modules:
- name: proxy
domains:

View File

@ -54,7 +54,7 @@ module.exports.create = function (deps, config) {
}
function netHandler(conn, opts) {
opts = opts || {};
console.log('[netHandler]', conn.localAddres, conn.localPort, opts.encrypted);
console.log('[netHandler]', conn.localAddress, conn.localPort, opts.encrypted);
// XXX PEEK COMMENT XXX
// TODO we can have our cake and eat it too

View File

@ -13,18 +13,55 @@ module.exports.create = function (deps, conf, greenlockMiddleware) {
, /\balpha\.localhost\./
];
function verifyHost(fullHost) {
var host = /^(.*?)(:\d+)?$/.exec(fullHost)[1];
if (host === 'localhost') {
return fullHost.replace(host, 'localhost.daplie.me');
}
// Test for IPv4 and IPv6 addresses. These patterns will match some invalid addresses,
// but since those still won't be valid domains that won't really be a problem.
if (/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host) || /^\[[0-9a-fA-F:]+\]$/.test(host)) {
if (!conf.http.primaryDomain) {
(conf.http.modules || []).some(function (mod) {
return mod.domains.some(function (domain) {
if (domain[0] !== '*') {
conf.http.primaryDomain = domain;
return true;
}
});
});
}
return fullHost.replace(host, conf.http.primaryDomain || host);
}
return fullHost;
}
// We handle both HTTPS and HTTP traffic on the same ports, and we want to redirect
// any unencrypted requests to the same port they came from unless it came in on
// the default HTTP port, in which case there wont be a port specified in the host.
var redirecters = {};
function redirectHttps(req, res, next) {
var port = req.headers.host.split(':')[1];
if (conf.http.allowInsecure) {
next();
return;
}
var port = (/:(\d+)$/.exec(req.headers.host) || [])[1];
if (!redirecters[port]) {
redirecters[port] = require('redirect-https')({
port: port
, trustProxy: conf.http.trustProxy
});
}
// localhost and IP addresses cannot have real SSL certs (and don't contain any useful
// info for redirection either), so we direct some hosts to either localhost.daplie.me
// or the "primary domain" ie the first manually specified domain.
req.headers.host = verifyHost(req.headers.host);
redirecters[port](req, res, next);
}