goldilocks.js/lib/app.js

462 lines
13 KiB
JavaScript
Raw Normal View History

2015-06-24 21:36:17 +00:00
'use strict';
module.exports = function (myDeps, conf, overrideHttp) {
2017-03-02 07:58:45 +00:00
var express = require('express');
//var finalhandler = require('finalhandler');
2015-06-24 21:36:17 +00:00
var serveStatic = require('serve-static');
var serveIndex = require('serve-index');
2017-03-02 07:58:45 +00:00
//var assetServer = serveStatic(opts.assetsPath);
2017-02-23 01:48:34 +00:00
var path = require('path');
2017-03-02 07:58:45 +00:00
//var wellKnownServer = serveStatic(path.join(opts.assetsPath, 'well-known'));
2017-03-02 07:58:45 +00:00
var serveStaticMap = {};
var serveIndexMap = {};
var content = conf.content;
2017-03-02 07:58:45 +00:00
//var server;
2017-02-28 21:55:48 +00:00
var serveInit;
2017-03-02 07:58:45 +00:00
var app;
2017-04-13 22:50:48 +00:00
var request;
2015-06-24 21:36:17 +00:00
2017-03-02 07:58:45 +00:00
function createServeInit() {
var PromiseA = require('bluebird');
2017-04-06 01:02:51 +00:00
var OAUTH3 = require('../packages/assets/org.oauth3');
require('../packages/assets/org.oauth3/oauth3.domains.js');
require('../packages/assets/org.oauth3/oauth3.dns.js');
require('../packages/assets/org.oauth3/oauth3.tunnel.js');
OAUTH3._hooks = require('../packages/assets/org.oauth3/oauth3.node.storage.js');
2017-03-02 07:58:45 +00:00
var fs = PromiseA.promisifyAll(require('fs'));
var ownersPath = path.join(__dirname, '..', 'var', 'owners.json');
2017-04-06 01:02:51 +00:00
var scmp = require('scmp');
2017-04-13 22:50:48 +00:00
request = request || PromiseA.promisify(require('request'));
2017-04-06 01:02:51 +00:00
2017-04-28 01:46:54 +00:00
var owners = {
all: function () {
var owners;
try {
owners = require(ownersPath);
} catch(e) {
owners = {};
}
return PromiseA.resolve(Object.keys(owners).map(function (key) {
var owner = owners[key];
owner.id = key;
return owner;
}));
}
, get: function (id) {
var me = this;
return me.all().then(function (owners) {
return owners.filter(function (owner) {
return scmp(id, owner.id);
})[0];
});
}
, exists: function (id) {
var me = this;
return me.get(id).then(function (owner) {
return !!owner;
});
}
, set: function (id, obj) {
var owners;
try {
owners = require(ownersPath);
} catch(e) {
owners = {};
}
obj.id = id;
owners[id] = obj;
return fs.mkdirAsync(path.dirname(ownersPath)).catch(function (err) {
if (err.code !== 'EEXIST') {
console.error('failed to mkdir', path.dirname(ownersPath), err.toString());
}
}).then(function () {
return fs.writeFileAsync(ownersPath, JSON.stringify(owners), 'utf8');
});
2017-04-28 01:46:54 +00:00
}
};
myDeps.PromiseA = PromiseA;
myDeps.OAUTH3 = OAUTH3;
2017-06-09 17:18:05 +00:00
myDeps.storage = Object.assign({ owners: owners }, myDeps.storage);
myDeps.recase = require('recase').create({});
myDeps.request = request;
myDeps.api = {
// TODO move loopback to oauth3.api('tunnel:loopback')
loopback: function (deps, session, opts2) {
var crypto = require('crypto');
var token = crypto.randomBytes(16).toString('hex');
var keyAuthorization = crypto.randomBytes(16).toString('hex');
var nonce = crypto.randomBytes(16).toString('hex');
// TODO set token and keyAuthorization to /.well-known/cloud-challenge/:token
return request({
method: 'POST'
, url: 'https://oauth3.org/api/org.oauth3.tunnel/loopback'
, json: {
address: opts2.address
, port: opts2.port
, token: token
, keyAuthorization: keyAuthorization
, servername: opts2.servername
, nonce: nonce
, scheme: 'https'
, iat: Date.now()
}
}).then(function (result) {
// TODO this will always fail at the moment
console.log('loopback result:');
return result;
});
2017-03-02 07:58:45 +00:00
}
, tunnel: function (deps, session) {
// TODO save session to config and turn tunnel on
var OAUTH3 = deps.OAUTH3;
var owner = session.id;
var url = require('url');
var providerUri = session.token.aud;
var urlObj = url.parse(OAUTH3.url.normalize(session.token.azp));
var oauth3 = OAUTH3.create(urlObj, {
providerUri: providerUri
, session: session
});
return oauth3.setProvider(providerUri).then(function () {
/*
return oauth3.api('domains.list').then(function (domains) {
var domainsMap = {};
domains.forEach(function (d) {
if (!d.device) {
return;
}
if (d.device !== conf.device.hostname) {
return;
}
domainsMap[d.name] = true;
});
*/
2017-04-13 22:50:48 +00:00
//console.log('domains matching hostname', Object.keys(domainsMap));
//console.log('device', conf.device);
return oauth3.api('tunnel.token', {
data: {
// filter to all domains that are on this device
//domains: Object.keys(domainsMap)
device: {
hostname: conf.device.hostname
, id: conf.device.uid || conf.device.id
2017-04-06 01:02:51 +00:00
}
}
}).then(function (result) {
console.log('got a token from the tunnel server?');
result.owner = owner;
2017-05-29 19:41:09 +00:00
return deps.tunneler.add(result);
2017-04-06 01:02:51 +00:00
});
/*
2017-04-06 01:02:51 +00:00
});
*/
});
2017-04-06 01:02:51 +00:00
}
};
return require('../packages/apis/com.daplie.goldilocks').create(myDeps, conf);
2017-03-02 07:58:45 +00:00
}
app = express();
var Sites = {
add: function (sitesMap, site) {
if (!sitesMap[site.$id]) {
sitesMap[site.$id] = site;
}
if (!site.paths) {
site.paths = [];
}
if (!site.paths._map) {
site.paths._map = {};
}
site.paths.forEach(function (path) {
site.paths._map[path.$id] = path;
if (!path.modules) {
path.modules = [];
}
if (!path.modules._map) {
path.modules._map = {};
}
path.modules.forEach(function (module) {
path.modules._map[module.$id] = module;
});
});
}
};
2017-04-27 22:50:03 +00:00
var opts = overrideHttp || conf.http;
if (!opts.defaults) {
opts.defaults = {};
}
if (!opts.global) {
opts.global = {};
}
2017-03-13 22:39:43 +00:00
if (!opts.sites) {
opts.sites = [];
}
opts.sites._map = {};
opts.sites.forEach(function (site) {
Sites.add(opts.sites._map, site);
2017-03-13 22:39:43 +00:00
});
function mapMap(el, i, arr) {
arr._map[el.$id] = el;
}
opts.global.modules._map = {};
opts.global.modules.forEach(mapMap);
opts.global.paths._map = {};
opts.global.paths.forEach(function (path, i, arr) {
mapMap(path, i, arr);
//opts.global.paths._map[path.$id] = path;
path.modules._map = {};
path.modules.forEach(mapMap);
});
opts.sites.forEach(function (site) {
site.paths._map = {};
site.paths.forEach(function (path, i, arr) {
mapMap(path, i, arr);
//site.paths._map[path.$id] = path;
path.modules._map = {};
path.modules.forEach(mapMap);
});
});
opts.defaults.modules._map = {};
opts.defaults.modules.forEach(mapMap);
opts.defaults.paths._map = {};
opts.defaults.paths.forEach(function (path, i, arr) {
mapMap(path, i, arr);
//opts.global.paths._map[path.$id] = path;
path.modules._map = {};
path.modules.forEach(mapMap);
});
2017-03-02 07:58:45 +00:00
return app.use('/', function (req, res, next) {
if (!req.headers.host) {
next(new Error('missing HTTP Host header'));
return;
}
2017-04-28 01:34:13 +00:00
if (0 === req.url.indexOf('/api/com.daplie.goldilocks/')) {
2017-02-28 21:55:48 +00:00
if (!serveInit) {
2017-03-02 07:58:45 +00:00
serveInit = createServeInit();
2017-02-28 21:55:48 +00:00
}
2017-03-02 07:58:45 +00:00
}
2017-04-28 01:34:13 +00:00
if ('/api/com.daplie.goldilocks/init' === req.url) {
2017-03-02 07:58:45 +00:00
serveInit.init(req, res);
return;
}
2017-04-28 01:34:13 +00:00
if ('/api/com.daplie.goldilocks/tunnel' === req.url) {
2017-04-06 01:02:51 +00:00
serveInit.tunnel(req, res);
return;
}
2017-04-28 01:34:13 +00:00
if ('/api/com.daplie.goldilocks/config' === req.url) {
2017-03-02 07:58:45 +00:00
serveInit.config(req, res);
2017-02-28 21:55:48 +00:00
return;
}
2017-04-28 01:34:13 +00:00
if ('/api/com.daplie.goldilocks/request' === req.url) {
2017-03-18 20:48:49 +00:00
serveInit.request(req, res);
return;
}
2017-02-28 21:55:48 +00:00
2015-06-30 23:11:01 +00:00
if (content && '/' === req.url) {
// res.setHeader('Content-Type', 'application/octet-stream');
res.end(content);
return;
}
2017-03-02 07:58:45 +00:00
//var done = finalhandler(req, res);
var host = req.headers.host;
2017-03-02 07:58:45 +00:00
var hostname = (host||'').split(':')[0].toLowerCase();
console.log('opts.global', opts.global);
2017-03-13 22:39:43 +00:00
var sites = [ opts.global || null, opts.sites._map[hostname] || null, opts.defaults || null ];
2017-03-02 07:58:45 +00:00
var loadables = {
serve: function (config, hostname, pathname, req, res, next) {
var originalUrl = req.url;
2017-03-13 22:39:43 +00:00
var dirpaths = config.paths.slice(0);
2017-03-02 07:58:45 +00:00
function nextServe() {
2017-03-13 22:39:43 +00:00
var dirname = dirpaths.pop();
2017-03-02 07:58:45 +00:00
if (!dirname) {
req.url = originalUrl;
next();
return;
}
2017-03-13 22:39:43 +00:00
console.log('[serve]', req.url, hostname, pathname, dirname);
dirname = path.resolve(conf.cwd, dirname.replace(/:hostname/, hostname));
2017-03-02 07:58:45 +00:00
if (!serveStaticMap[dirname]) {
serveStaticMap[dirname] = serveStatic(dirname);
}
serveStaticMap[dirname](req, res, nextServe);
}
req.url = req.url.substr(pathname.length - 1);
nextServe();
}
, indexes: function (config, hostname, pathname, req, res, next) {
var originalUrl = req.url;
2017-03-13 22:39:43 +00:00
var dirpaths = config.paths.slice(0);
2017-03-02 07:58:45 +00:00
function nextIndex() {
2017-03-13 22:39:43 +00:00
var dirname = dirpaths.pop();
2017-03-02 07:58:45 +00:00
if (!dirname) {
req.url = originalUrl;
next();
return;
}
2017-03-13 22:39:43 +00:00
console.log('[indexes]', req.url, hostname, pathname, dirname);
dirname = path.resolve(conf.cwd, dirname.replace(/:hostname/, hostname));
2017-03-02 07:58:45 +00:00
if (!serveStaticMap[dirname]) {
serveIndexMap[dirname] = serveIndex(dirname);
}
serveIndexMap[dirname](req, res, nextIndex);
}
req.url = req.url.substr(pathname.length - 1);
nextIndex();
}
2017-03-13 22:39:43 +00:00
, app: function (config, hostname, pathname, req, res, next) {
//var appfile = path.resolve(/*process.cwd(), */config.path.replace(/:hostname/, hostname));
var appfile = config.path.replace(/:hostname/, hostname);
var app = require(appfile);
app(req, res, next);
}
2017-03-02 07:58:45 +00:00
};
2017-03-13 22:39:43 +00:00
function runModule(module, hostname, pathname, modulename, req, res, next) {
2017-03-02 07:58:45 +00:00
if (!loadables[modulename]) {
next(new Error("no module '" + modulename + "' found"));
return;
}
2017-03-13 22:39:43 +00:00
loadables[modulename](module, hostname, pathname, req, res, next);
2017-03-02 07:58:45 +00:00
}
function iterModules(modules, hostname, pathname, req, res, next) {
2017-03-13 22:39:43 +00:00
console.log('modules');
console.log(modules);
var modulenames = Object.keys(modules._map);
2017-03-02 07:58:45 +00:00
function nextModule() {
var modulename = modulenames.pop();
if (!modulename) {
next();
return;
}
console.log('modules', modules);
2017-03-13 22:39:43 +00:00
runModule(modules._map[modulename], hostname, pathname, modulename, req, res, nextModule);
2017-03-02 07:58:45 +00:00
}
nextModule();
}
function iterPaths(site, hostname, req, res, next) {
2017-03-13 22:39:43 +00:00
console.log('site', hostname);
console.log(site);
var pathnames = Object.keys(site.paths._map);
console.log('pathnames', pathnames);
2017-03-02 07:58:45 +00:00
pathnames = pathnames.filter(function (pathname) {
// TODO ensure that pathname has trailing /
return (0 === req.url.indexOf(pathname));
//return req.url.match(pathname);
});
pathnames.sort(function (a, b) {
return b.length - a.length;
});
2017-03-13 22:39:43 +00:00
console.log('pathnames', pathnames);
2017-03-02 07:58:45 +00:00
function nextPath() {
2017-03-13 22:39:43 +00:00
var pathname = pathnames.shift();
2017-03-02 07:58:45 +00:00
if (!pathname) {
next();
return;
}
console.log('iterPaths', hostname, pathname, req.url);
2017-03-13 22:39:43 +00:00
iterModules(site.paths._map[pathname].modules, hostname, pathname, req, res, nextPath);
2017-03-02 07:58:45 +00:00
}
nextPath();
}
function nextSite() {
2017-03-13 22:39:43 +00:00
console.log('hostname', hostname, sites);
var site;
if (!sites.length) {
2017-03-02 07:58:45 +00:00
next(); // 404
return;
}
2017-03-13 22:39:43 +00:00
site = sites.shift();
if (!site) {
nextSite();
return;
}
2017-03-02 07:58:45 +00:00
iterPaths(site, hostname, req, res, nextSite);
}
nextSite();
/*
2017-02-23 01:48:34 +00:00
function serveStaticly(server) {
function serveTheStatic() {
server.serve(req, res, function (err) {
if (err) { return done(err); }
server.index(req, res, function (err) {
if (err) { return done(err); }
req.url = req.url.replace(/\/assets/, '');
assetServer(req, res, function () {
if (err) { return done(err); }
req.url = req.url.replace(/\/\.well-known/, '');
wellKnownServer(req, res, done);
});
});
});
}
if (server.expressApp) {
2017-02-23 01:48:34 +00:00
server.expressApp(req, res, serveTheStatic);
return;
}
2017-02-23 01:48:34 +00:00
serveTheStatic();
}
2015-12-06 06:43:33 +00:00
if (opts.livereload) {
res.__my_livereload = '<script src="//'
2017-02-02 03:00:00 +00:00
+ (host || opts.sites[0].name).split(':')[0]
2015-12-06 06:43:33 +00:00
+ ':35729/livereload.js?snipver=1"></script>';
res.__my_addLen = res.__my_livereload.length;
2015-12-06 06:43:33 +00:00
// TODO modify prototype instead of each instance?
res.__write = res.write;
res.write = _reloadWrite;
}
2016-08-06 20:15:12 +00:00
2017-02-23 01:48:34 +00:00
console.log('hostname:', hostname, opts.sites[0].paths);
addServer(hostname);
server = hostsMap[hostname] || hostsMap[opts.sites[0].name];
2017-02-23 01:48:34 +00:00
serveStaticly(server);
2017-03-02 07:58:45 +00:00
*/
});
2015-06-24 21:36:17 +00:00
};