Commit 9122acce authored by Jim Tittsler's avatar Jim Tittsler

NodeJS-based web & Faye server for WEnotes

parents
# compiled python
*.py[co]
build
build-stamp
# editor debris
*~
.#*
._*
.*.sw?
# OS debris
.DS_Store
# ignore temp/state files
.netrwhist
#
node_modules
# don't include the sag couch library
sag*
# don't include the configuration file
options.json
tools/docopt
Copyright 2012 Open Education Resource Foundation
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# WEnotes-server
This is a simple NodeJS-based web and [Faye](http://faye.jcoglan.com)server used for WEnotes. Its main purpose is to allow WEnotes
clients to subscribe to topics (channels, tags, rooms) of
interest.
`server.js` is intended to be run under a supervisor such as
[forever](https://www.npmjs.com/package/forever) or
[pm2](http://pm2.keymetrics.io/).
## License
MIT
{"version": "v1.0.0"}
{
"url": "http://user:pass@account.iriscouch.com:5984",
"localcouch": "http://userl:passl@127.0.0.1:5984",
"db": "databasename",
"dbfeeds": "feedsdatabase",
"dbvotes": "votesdatabase",
"avatars": "avatarsdatabase",
"log": {
"couchwatch": {
"level": 7,
"file": "/tmp/couchwatch.txt"
}
},
"fayeurl": "http://your.faye.server/faye",
"fayepass": "secret string to restrict posting",
"moodleuser": "username",
"moodlepass": "password"
"tags": ["wikieducator", "ocl4ed", "oeru", "ast1000"]
}
{
"name": "WEnotes-server",
"version": "1.0.0",
"description": "WEnotes Faye (Bayeux) Server",
"author": "Jim Tittsler <jimt@OnJapan.net>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://git.gitorious.org/wikieducator/wenotes.git"
},
"dependencies": {
"faye": "1.1.x",
"log": "1.4.0",
"node-static": "0.7.x"
},
"engine": "node >= 4.4.3"
}
used in SSL certificate generation/renewal
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8">
<title>WikiEducator WEnotes</title>
</head>
<body>
<h1>WikiEducator Aggregator</h1>
</body>
</html>
User-agent: *
Disallow: /
/*
* a simple web and Faye server for WEnotes
*
* Copyright 2016 Open Education Resource Foundation
* @license MIT
*/
/* jshint node:true, esversion:6 */
"use strict";
var util = require('util'),
fs = require('fs'),
http = require('http'),
https = require('https'),
Log = require('log'),
nodeStatic = require ('node-static'),
url = require('url'),
faye = require('faye'),
options = require('./options.json');
var log = new Log(options.log.server.level,
fs.createWriteStream(options.log.server.file, {
flags: 'a'}));
process.addListener('uncaughtException', (err, stack) => {
log.alert('Exception: ' + err);
log.alert(err.stack);
});
var ServerAuth = {
incoming: function(message, callback) {
if (/^\/meta\//.test(message.channel)) {
if ((message.channel === '/meta/subscribe') || (message.channel === '/meta/unsubscribe')) {
// log channel subscriptions and unsubscriptions
log.info(message.channel, message);
}
return callback(message);
}
// limit publishing to people that know APP_PASSWORD
var password = message.ext && message.ext.password;
if (password !== options.fayepass) {
log.warning('bad password, message discarded', message);
message.error = faye.Error.extMismatch();
return;
}
if (password) {
// don't pass the password along
delete message.ext.password;
}
callback(message);
}
};
var ClientAuth = {
outgoing: function(message, callback) {
message.ext = message.ext || {};
message.ext.password = options.fayepass;
callback(message);
}
};
function createBayeuxServer(mount) {
var bayeux = new faye.NodeAdapter({
mount: mount || '/faye',
timeout: 45
});
return bayeux;
}
function httpHandler(request, response) {
log.debug(`handle ${request.method} request ${request.url}`);
var file = new nodeStatic.Server('./public', {
cache: false
});
var body = [];
request.on('error', (e) => {
log.critical('HTTP request error', e);
}).on('data', (d) => {
body.push(d);
}).on('end', () => {
var couchURL, jsonp, jsonString,
location = url.parse(request.url, true),
params = (location.query || request.headers);
if (body.length) {
body = Buffer.concat(body).toString();
log.debug('BODY:', body);
}
// simple port 80 proxy to CouchDB
if (location.pathname.indexOf('/DB/') === 0 && request.method === 'GET') {
jsonp = params && params.callback;
couchURL = options.url + request.url.slice(3);
log.debug('***GET DB ' + location.pathname, couchURL);
http.get(couchURL, (res) => {
var data = '';
response.writeHead(res.statusCode, res.headers);
res.setEncoding('utf8');
res.on('data', (d) => {
data += d;
});
res.on('end', () => {
response.write(data);
response.end();
});
}).on('error', (e) => {
log.critical(`error fetching from CouchDB ${couchURL}`);
response.writeHead(502, {
'Content-Type': jsonp ? 'application/javascript' : 'application/json'
});
response.write('{"error":"DB_read_failed"}');
response.end();
});
} else if ((location.pathname === '/config.json') && request.method === 'GET') {
jsonp = params && params.callback;
log.debug('***GET ' + location.pathname);
response.writeHead(200, {
'Content-Type': jsonp ? 'application/javascript' : 'application/json'
});
jsonString = JSON.stringify({
port: 80 // lie that we are on port 80
});
if (jsonp) {
jsonString = params.callback + '(' + jsonString + ')';
}
response.write(jsonString);
response.end();
} else if ((location.pathname.indexOf('/_in/') === 0) && request.method === 'POST') {
jsonp = params && params.callback;
log.debug('POST: params:', params);
//log.debug('POST: location:', location);
//log.debug('POST: request: ', util.inspect(request));
log.debug('POST: body:', body);
response.writeHead(200, {
'Content-Type': jsonp ? 'application/javascript' : 'application/json'
});
jsonString = JSON.stringify({text: 'Right!'});
if (jsonp) {
jsonString = params.callback + '(' + jsonString + ')';
}
response.write(jsonString);
response.end();
} else {
file.serve(request, response, (err, result) => {
if (err) {
let headers = err.headers;
headers['Content-Type'] = 'text/plain';
log.warning(`Error serving ${request.url} - ${err.message}`);
log.warning(`status: ${err.status} headers:`, headers);
response.writeHead(err.status, headers);
response.write("404 Not Found\n");
response.end();
}
});
}
}).resume();
}
var bayeux = createBayeuxServer();
// require a token on proper messages
bayeux.addExtension(ServerAuth);
bayeux.getClient().addExtension(ClientAuth);
if (options.server.port) {
let httpServer = http.createServer(httpHandler);
bayeux.attach(httpServer);
httpServer.listen(options.server.port, options.server.ip);
log.notice(`Server started on ${options.server.ip}:${options.server.port}`);
}
if (options.server.secureport) {
let sslOptions = {
key: fs.readFileSync(options.server.privkey),
cert: fs.readFileSync(options.server.fullchain)
},
httpsServer = https.createServer(sslOptions, httpHandler);
bayeux.attach(httpsServer);
httpsServer.listen(options.server.secureport, options.server.ip);
log.notice(`Secure server started on ${options.server.ip}:${options.server.secureport}`);
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment