walnut.js/lib/vhost-server.js

344 lines
12 KiB
JavaScript
Raw Normal View History

2015-02-19 06:06:56 +00:00
'use strict';
module.exports.create = function (securePort, vhostsdir) {
2015-02-20 21:21:37 +00:00
var PromiseA = require('bluebird').Promise;
var serveStatic;
2015-02-20 21:21:37 +00:00
var fs = require('fs');
var path = require('path');
var dummyCerts;
2015-10-05 19:51:58 +00:00
var loopbackToken = require('crypto').randomBytes(32).toString('hex');
2015-02-19 22:08:33 +00:00
2015-06-06 00:05:37 +00:00
function handleAppScopedError(tag, domaininfo, req, res, fn) {
2015-03-02 22:42:14 +00:00
function next(err) {
if (!err) {
fn(req, res);
return;
}
2015-03-02 21:45:16 +00:00
2015-06-06 00:05:37 +00:00
if (res.headersSent) {
console.error('[ERROR] handleAppScopedError headersSent');
console.log(err);
console.log(err.stack);
return;
}
console.error('[ERROR] handleAppScopedError');
console.log(err);
console.log(err.stack);
2015-03-02 22:42:14 +00:00
res.writeHead(500);
res.end(
"<html>"
+ "<head>"
+ '<link rel="icon" href="favicon.ico" />'
+ "</head>"
+ "<body>"
+ "<pre>"
+ "<code>"
2015-03-05 22:07:45 +00:00
+ "Method: " + encodeURI(req.method)
2015-03-02 22:42:14 +00:00
+ '\n'
2015-03-05 22:07:45 +00:00
+ "Hostname: " + encodeURI(domaininfo.hostname)
2015-03-02 22:42:14 +00:00
+ '\n'
2015-03-05 22:07:45 +00:00
+ "App: " + encodeURI(domaininfo.pathname ? (domaininfo.pathname + '/') : '')
2015-03-02 22:42:14 +00:00
+ '\n'
2015-03-05 22:07:45 +00:00
+ "Route: " + encodeURI(req.url)//.replace(/^\//, '')
2015-03-02 22:42:14 +00:00
+ '\n'
// TODO better sanatization
+ 'Error: ' + (err.message || err.toString()).replace(/</g, '&lt;')
+ "</code>"
+ "</pre>"
+ "</body>"
+ "</html>"
);
2015-03-02 21:45:16 +00:00
}
2015-03-02 22:42:14 +00:00
return next;
2015-03-02 21:45:16 +00:00
}
2015-02-20 21:21:37 +00:00
function createPromiseApps(secureServer) {
return new PromiseA(function (resolve) {
var forEachAsync = require('foreachasync').forEachAsync.create(PromiseA);
var connect = require('connect');
2015-03-29 03:29:40 +00:00
// TODO make lazy
var app = connect().use(require('compression')());
2015-02-20 21:21:37 +00:00
var vhost = require('vhost');
var domainMergeMap = {};
var domainMerged = [];
function getDomainInfo(apppath) {
var parts = apppath.split(/[#%]+/);
var hostname = parts.shift();
var pathname = parts.join('/').replace(/\/+/g, '/').replace(/^\//, '');
return {
hostname: hostname
, pathname: pathname
, dirpathname: parts.join('#')
, dirname: apppath
, isRoot: apppath === hostname
};
}
2015-02-19 06:06:56 +00:00
2015-02-20 21:21:37 +00:00
function loadDomainMounts(domaininfo) {
var connectContext = {};
2015-02-20 21:21:37 +00:00
var appContext;
// should order and group by longest domain, then longest path
if (!domainMergeMap[domaininfo.hostname]) {
// create an connect / express app exclusive to this domain
// TODO express??
domainMergeMap[domaininfo.hostname] = {
hostname: domaininfo.hostname
, apps: connect()
, mountsMap: {}
};
domainMerged.push(domainMergeMap[domaininfo.hostname]);
}
2015-02-19 06:06:56 +00:00
2015-02-20 21:21:37 +00:00
if (domainMergeMap[domaininfo.hostname].mountsMap['/' + domaininfo.dirpathname]) {
return;
2015-02-19 06:06:56 +00:00
}
2015-02-20 21:21:37 +00:00
console.log('[log] [once] Preparing mount for', domaininfo.hostname + '/' + domaininfo.dirpathname);
2015-02-20 21:21:37 +00:00
domainMergeMap[domaininfo.hostname].mountsMap['/' + domaininfo.dirpathname] = function (req, res, next) {
2015-09-25 08:06:47 +00:00
res.setHeader('Strict-Transport-Security', 'max-age=10886400; includeSubDomains; preload');
2015-03-29 03:29:40 +00:00
function loadThatApp() {
var time = Date.now();
2015-02-21 04:43:10 +00:00
console.log('[log] LOADING "' + domaininfo.hostname + '/' + domaininfo.pathname + '"', req.url);
2015-03-29 03:29:40 +00:00
return getAppContext(domaininfo).then(function (localApp) {
console.info((Date.now() - time) + 'ms Loaded ' + domaininfo.hostname + ':' + securePort + '/' + domaininfo.pathname);
//if (localApp.arity >= 2) { /* connect uses .apply(null, arguments)*/ }
if ('function' !== typeof localApp) {
localApp = getDummyAppContext(null, "[ERROR] no connect-style export from " + domaininfo.dirname);
}
2015-11-04 11:26:18 +00:00
function fourohfour(req, res) {
res.writeHead(404);
res.end(
"<html>"
+ "<head>"
+ '<link rel="icon" href="favicon.ico" />'
+ "</head>"
+ "<body>"
+ "Cannot "
+ encodeURI(req.method)
+ " 'https://"
+ encodeURI(domaininfo.hostname)
+ '/'
+ encodeURI(domaininfo.pathname ? (domaininfo.pathname + '/') : '')
+ encodeURI(req.url.replace(/^\//, ''))
+ "'"
+ "<br/>"
+ "<br/>"
+ "Domain: " + encodeURI(domaininfo.hostname)
+ "<br/>"
+ "App: " + encodeURI(domaininfo.pathname)
+ "<br/>"
+ "Route : " + encodeURI(req.url)
+ "</body>"
+ "</html>"
);
}
// Note: pathname should NEVER have a leading '/' on its own
// we always add it explicitly
function localAppWrapped(req, res) {
console.log('[debug]', domaininfo.hostname + '/' + domaininfo.pathname, req.url);
2015-11-04 11:26:18 +00:00
localApp(req, res, handleAppScopedError('localApp', domaininfo, req, res, fourohfour));
}
try {
2015-03-29 03:29:40 +00:00
var localConnect = connect();
localConnect.use(require('connect-query')());
localConnect.use(localAppWrapped);
domainMergeMap[domaininfo.hostname].apps.use('/' + domaininfo.pathname, localConnect);
return localConnect;
} catch(e) {
console.error('[ERROR] '
+ domaininfo.hostname + ':' + securePort
+ '/' + domaininfo.pathname
);
console.error(e);
// TODO this may not work in web apps (due to 500), probably okay
res.writeHead(500);
res.end('{ "error": { "message": "[ERROR] could not load '
+ encodeURI(domaininfo.hostname) + ':' + securePort + '/' + encodeURI(domaininfo.pathname)
+ 'or default error app." } }');
}
});
}
function suckItDubDubDub(req, res) {
var newLoc = 'https://' + (req.headers.host||'').replace(/^www\./) + req.url;
res.statusCode = 301;
res.setHeader('Location', newLoc);
res.end("<html><head><title></title></head><body><!-- redirecting nowww --></body><html>");
}
2015-03-29 03:29:40 +00:00
function nextify() {
if (!appContext) {
appContext = loadThatApp();
}
if (!appContext.then) {
appContext(req, res, next);
} else {
appContext.then(function (localConnect) {
appContext = localConnect;
appContext(req, res, next);
});
}
}
if (!serveStatic) {
serveStatic = require('serve-static');
}
if (!connectContext.static) {
console.log('[static]', path.join(vhostsdir, domaininfo.dirname, 'public'));
connectContext.static = serveStatic(path.join(vhostsdir, domaininfo.dirname, 'public'));
}
if (/^www\./.test(req.headers.host)) {
if (/\.appcache\b/.test(req.url)) {
res.setHeader('Content-Type', 'text/cache-manifest');
res.end('CACHE MANIFEST\n\n# v0__DELETE__CACHE__MANIFEST__\n\nNETWORK:\n*');
return;
}
suckItDubDubDub(req, res);
return;
}
if (/^\/api\//.test(req.url)) {
nextify();
return;
}
connectContext.static(req, res, nextify);
2015-02-20 21:21:37 +00:00
};
domainMergeMap[domaininfo.hostname].apps.use(
'/' + domaininfo.pathname
, domainMergeMap[domaininfo.hostname].mountsMap['/' + domaininfo.dirpathname]
);
2015-02-20 21:21:37 +00:00
return PromiseA.resolve();
2015-02-19 06:06:56 +00:00
}
2015-02-20 21:21:37 +00:00
function readNewVhosts() {
return fs.readdirSync(vhostsdir).filter(function (node) {
// not a hidden or private file
return '.' !== node[0] && '_' !== node[0];
}).map(getDomainInfo).sort(function (a, b) {
var hlen = b.hostname.length - a.hostname.length;
var plen = b.pathname.length - a.pathname.length;
// A directory could be named example.com, example.com# example.com##
// to indicate order of preference (for API addons, for example)
var dlen = b.dirname.length - a.dirname.length;
if (!hlen) {
if (!plen) {
return dlen;
}
return plen;
}
return plen;
2015-02-19 06:06:56 +00:00
});
}
2015-02-20 21:21:37 +00:00
function getDummyAppContext(err, msg) {
console.error('[ERROR] getDummyAppContext');
console.error(err);
console.error(msg);
return function (req, res) {
2015-03-05 22:07:45 +00:00
res.writeHead(500);
2015-02-20 21:21:37 +00:00
res.end('{ "error": { "message": "' + msg + '" } }');
2015-03-29 03:29:40 +00:00
};
2015-02-20 21:21:37 +00:00
}
2015-02-19 06:06:56 +00:00
2015-10-05 19:51:58 +00:00
function getLoopbackApp() {
return function (req, res) {
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify({ "success": true, "token": loopbackToken }));
};
}
2015-02-20 21:21:37 +00:00
function getAppContext(domaininfo) {
var localApp;
2015-02-19 06:06:56 +00:00
2015-10-05 19:51:58 +00:00
if ('loopback.daplie.invalid' === domaininfo.dirname) {
return getLoopbackApp();
}
2015-02-20 21:21:37 +00:00
try {
// TODO live reload required modules
localApp = require(path.join(vhostsdir, domaininfo.dirname, 'app.js'));
if (localApp.create) {
// TODO read local config.yml and pass it in
// TODO pass in websocket
localApp = localApp.create(secureServer, {
dummyCerts: dummyCerts
, hostname: domaininfo.hostname
, port: securePort
, url: domaininfo.pathname
});
2015-02-21 04:43:10 +00:00
2015-02-20 21:21:37 +00:00
if (!localApp) {
2015-02-21 04:43:10 +00:00
localApp = getDummyAppContext(null, "[ERROR] no app was returned by app.js for " + domaininfo.dirname);
2015-02-20 21:21:37 +00:00
}
}
2015-02-21 04:43:10 +00:00
2015-02-20 21:21:37 +00:00
if (!localApp.then) {
localApp = PromiseA.resolve(localApp);
} else {
return localApp.catch(function (e) {
2015-03-29 03:29:40 +00:00
console.error("[ERROR] initialization failed during create() for " + domaininfo.dirname);
console.error(e);
throw e;
//return getDummyAppContext(e, "[ERROR] initialization failed during create() for " + domaininfo.dirname);
2015-02-20 21:21:37 +00:00
});
}
} catch(e) {
localApp = getDummyAppContext(e, "[ERROR] could not load app.js for " + domaininfo.dirname);
localApp = PromiseA.resolve(localApp);
}
return localApp;
}
function loadDomainVhosts() {
domainMerged.forEach(function (domainApp) {
if (domainApp._loaded) {
return;
}
console.log('[log] [once] Loading all mounts for ' + domainApp.hostname);
domainApp._loaded = true;
2015-02-20 21:21:37 +00:00
app.use(vhost(domainApp.hostname, domainApp.apps));
2015-11-04 11:26:18 +00:00
app.use(vhost('www.' + domainApp.hostname, function (req, res) {
res.send({
error: {
message: "this is an api. ain't no www belong here"
, code: "E_WWW"
}
});
}));
2015-02-20 21:21:37 +00:00
});
}
// TODO pre-cache these once the server has started?
// return forEachAsync(rootDomains, loadCerts);
// TODO load these even more lazily
return forEachAsync(readNewVhosts(), loadDomainMounts).then(loadDomainVhosts).then(function () {
console.log('[log] TODO fix and use hotload');
//app.use(hotloadApp);
2015-02-20 21:21:37 +00:00
resolve(app);
return;
});
});
}
2015-02-19 06:06:56 +00:00
return { create: createPromiseApps };
};