2015-11-01 17:42:20 -08:00
|
|
|
import fs from 'fs';
|
|
|
|
|
import path from 'path';
|
|
|
|
|
import net from 'net';
|
2016-07-07 01:11:56 -07:00
|
|
|
import { sendPug } from './pug';
|
2015-11-01 17:42:20 -08:00
|
|
|
import Config from '../config';
|
|
|
|
|
import bodyParser from 'body-parser';
|
|
|
|
|
import cookieParser from 'cookie-parser';
|
|
|
|
|
import serveStatic from 'serve-static';
|
|
|
|
|
import morgan from 'morgan';
|
|
|
|
|
import csrf from './csrf';
|
2015-10-26 22:56:53 -07:00
|
|
|
import * as HTTPStatus from './httpstatus';
|
2015-10-27 20:44:40 -07:00
|
|
|
import { CSRFError, HTTPError } from '../errors';
|
2017-07-16 22:35:33 -07:00
|
|
|
import counters from '../counters';
|
2017-07-17 21:58:58 -07:00
|
|
|
import { Summary, Counter } from 'prom-client';
|
Skip full user auth for most page renders
Previously, the user's session cookie was being checked against the
database for all non-static requests. However, this is not really
needed and wastes resources (and is slow).
For most page views (e.g. index, channel page), just parsing the value
of the cookie is sufficient:
* The cookies are already HMAC signed, so tampering with them ought to
be for all reasonable purposes, impossible.
* Assuming the worst case, all a nefarious user could manage to do is
change the text of the "Welcome, {user}" and cause a (non-functional)
ACP link to appear clientside, both of which are already possible by
using the Inspect Element tool.
For authenticated pages (currently, the ACP, and anything under
/account/), the full database check is still performed (for now).
2017-08-01 21:40:26 -07:00
|
|
|
import session from '../session';
|
|
|
|
|
const verifySessionAsync = require('bluebird').promisify(session.verifySession);
|
2017-04-04 23:02:31 -07:00
|
|
|
|
2017-07-08 20:11:54 -07:00
|
|
|
const LOGGER = require('@calzoneman/jsli')('webserver');
|
2013-12-12 14:48:23 -06:00
|
|
|
|
2015-11-01 17:42:20 -08:00
|
|
|
function initializeLog(app) {
|
|
|
|
|
const logFormat = ':real-address - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"';
|
|
|
|
|
const logPath = path.join(__dirname, '..', '..', 'http.log');
|
|
|
|
|
const outputStream = fs.createWriteStream(logPath, {
|
|
|
|
|
flags: 'a', // append to existing file
|
|
|
|
|
encoding: 'utf8'
|
|
|
|
|
});
|
|
|
|
|
morgan.token('real-address', req => req.realIP);
|
|
|
|
|
app.use(morgan(logFormat, {
|
|
|
|
|
stream: outputStream
|
|
|
|
|
}));
|
|
|
|
|
}
|
2013-12-12 14:48:23 -06:00
|
|
|
|
2017-07-16 22:35:33 -07:00
|
|
|
function initPrometheus(app) {
|
|
|
|
|
const latency = new Summary({
|
2017-08-12 13:12:58 -07:00
|
|
|
name: 'cytube_http_req_duration_seconds',
|
2017-07-16 22:35:33 -07:00
|
|
|
help: 'HTTP Request latency from execution of the first middleware '
|
|
|
|
|
+ 'until the "finish" event on the response object.',
|
|
|
|
|
labelNames: ['method', 'statusCode']
|
|
|
|
|
});
|
2017-07-17 21:58:58 -07:00
|
|
|
const requests = new Counter({
|
2017-08-12 13:12:58 -07:00
|
|
|
name: 'cytube_http_req_total',
|
2017-07-17 21:58:58 -07:00
|
|
|
help: 'HTTP Request count',
|
|
|
|
|
labelNames: ['method', 'statusCode']
|
|
|
|
|
});
|
2017-07-16 22:35:33 -07:00
|
|
|
|
|
|
|
|
app.use((req, res, next) => {
|
|
|
|
|
const startTime = process.hrtime();
|
|
|
|
|
res.on('finish', () => {
|
|
|
|
|
try {
|
|
|
|
|
const diff = process.hrtime(startTime);
|
2017-08-12 13:12:58 -07:00
|
|
|
const diffSec = diff[0] + diff[1]*1e-9;
|
|
|
|
|
latency.labels(req.method, res.statusCode).observe(diffSec);
|
2017-07-17 21:58:58 -07:00
|
|
|
requests.labels(req.method, res.statusCode).inc(1, new Date());
|
2017-07-16 22:35:33 -07:00
|
|
|
} catch (error) {
|
|
|
|
|
LOGGER.error('Failed to record HTTP Prometheus metrics: %s', error.stack);
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
next();
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2014-01-22 21:12:43 -06:00
|
|
|
/**
|
|
|
|
|
* Redirects a request to HTTPS if the server supports it
|
|
|
|
|
*/
|
|
|
|
|
function redirectHttps(req, res) {
|
2015-12-12 16:25:59 -08:00
|
|
|
if (req.realProtocol !== 'https' && Config.get('https.enabled') &&
|
|
|
|
|
Config.get('https.redirect')) {
|
2015-11-01 17:42:20 -08:00
|
|
|
var ssldomain = Config.get('https.full-address');
|
2015-02-15 21:56:00 -06:00
|
|
|
if (ssldomain.indexOf(req.hostname) < 0) {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
2014-01-22 21:12:43 -06:00
|
|
|
res.redirect(ssldomain + req.path);
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
2017-08-23 23:15:30 -07:00
|
|
|
/**
|
|
|
|
|
* Legacy socket.io configuration endpoint. This is being migrated to
|
|
|
|
|
* /socketconfig/<channel name>.json (see ./routes/socketconfig.js)
|
|
|
|
|
*/
|
|
|
|
|
function handleLegacySocketConfig(req, res) {
|
|
|
|
|
if (/\.json$/.test(req.path)) {
|
|
|
|
|
res.json(Config.get('sioconfigjson'));
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
res.type('application/javascript');
|
|
|
|
|
|
|
|
|
|
var sioconfig = Config.get('sioconfig');
|
|
|
|
|
var iourl;
|
|
|
|
|
var ip = req.realIP;
|
|
|
|
|
var ipv6 = false;
|
|
|
|
|
|
|
|
|
|
if (net.isIPv6(ip)) {
|
|
|
|
|
iourl = Config.get('io.ipv6-default');
|
|
|
|
|
ipv6 = true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!iourl) {
|
|
|
|
|
iourl = Config.get('io.ipv4-default');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
sioconfig += 'var IO_URL=\'' + iourl + '\';';
|
|
|
|
|
sioconfig += 'var IO_V6=' + ipv6 + ';';
|
|
|
|
|
res.send(sioconfig);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function handleUserAgreement(req, res) {
|
|
|
|
|
sendPug(res, 'tos', {
|
|
|
|
|
domain: Config.get('http.domain')
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2015-11-01 17:42:20 -08:00
|
|
|
function initializeErrorHandlers(app) {
|
|
|
|
|
app.use((req, res, next) => {
|
|
|
|
|
return next(new HTTPError(`No route for ${req.path}`, {
|
|
|
|
|
status: HTTPStatus.NOT_FOUND
|
2014-08-19 00:21:32 -05:00
|
|
|
}));
|
2015-11-01 17:42:20 -08:00
|
|
|
});
|
2014-02-04 11:32:52 -06:00
|
|
|
|
2015-11-01 17:42:20 -08:00
|
|
|
app.use((err, req, res, next) => {
|
|
|
|
|
if (err) {
|
|
|
|
|
if (err instanceof CSRFError) {
|
|
|
|
|
res.status(HTTPStatus.FORBIDDEN);
|
2016-07-07 01:11:56 -07:00
|
|
|
return sendPug(res, 'csrferror', {
|
2015-11-01 17:42:20 -08:00
|
|
|
path: req.path,
|
|
|
|
|
referer: req.header('referer')
|
|
|
|
|
});
|
2015-02-15 21:56:00 -06:00
|
|
|
}
|
|
|
|
|
|
2015-11-01 17:42:20 -08:00
|
|
|
let { message, status } = err;
|
|
|
|
|
if (!status) {
|
|
|
|
|
status = HTTPStatus.INTERNAL_SERVER_ERROR;
|
|
|
|
|
}
|
|
|
|
|
if (!message) {
|
|
|
|
|
message = 'An unknown error occurred.';
|
2016-07-07 01:11:56 -07:00
|
|
|
} else if (/\.(pug|js)/.test(message)) {
|
2015-11-01 17:42:20 -08:00
|
|
|
// Prevent leakage of stack traces
|
|
|
|
|
message = 'An internal error occurred.';
|
2015-02-15 21:56:00 -06:00
|
|
|
}
|
|
|
|
|
|
2015-11-01 17:42:20 -08:00
|
|
|
// Log 5xx (server) errors
|
|
|
|
|
if (Math.floor(status / 100) === 5) {
|
2017-04-04 23:02:31 -07:00
|
|
|
LOGGER.error(err.stack);
|
2015-11-01 17:42:20 -08:00
|
|
|
}
|
2015-02-15 21:56:00 -06:00
|
|
|
|
2015-11-01 17:42:20 -08:00
|
|
|
res.status(status);
|
2016-07-07 01:11:56 -07:00
|
|
|
return sendPug(res, 'httperror', {
|
2015-11-01 17:42:20 -08:00
|
|
|
path: req.path,
|
|
|
|
|
status: status,
|
|
|
|
|
message: message
|
2015-02-15 21:56:00 -06:00
|
|
|
});
|
2015-11-01 17:42:20 -08:00
|
|
|
} else {
|
|
|
|
|
next();
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
2015-02-15 21:56:00 -06:00
|
|
|
|
2017-08-23 23:02:08 -07:00
|
|
|
function patchExpressToHandleAsync() {
|
|
|
|
|
const Layer = require('express/lib/router/layer');
|
|
|
|
|
// https://github.com/expressjs/express/blob/4.x/lib/router/layer.js#L86
|
|
|
|
|
Layer.prototype.handle_request = function handle(req, res, next) {
|
|
|
|
|
const fn = this.handle;
|
|
|
|
|
|
|
|
|
|
if (fn.length > 3) {
|
|
|
|
|
next();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const result = fn(req, res, next);
|
|
|
|
|
|
|
|
|
|
if (result && result.catch) {
|
|
|
|
|
result.catch(error => next(error));
|
|
|
|
|
}
|
|
|
|
|
} catch (error) {
|
|
|
|
|
next(error);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
2015-11-01 17:42:20 -08:00
|
|
|
module.exports = {
|
|
|
|
|
/**
|
|
|
|
|
* Initializes webserver callbacks
|
|
|
|
|
*/
|
2017-08-15 18:23:03 -07:00
|
|
|
init: function (
|
|
|
|
|
app,
|
|
|
|
|
webConfig,
|
|
|
|
|
ioConfig,
|
|
|
|
|
clusterClient,
|
|
|
|
|
channelIndex,
|
|
|
|
|
session,
|
|
|
|
|
globalMessageBus
|
|
|
|
|
) {
|
2017-08-23 23:02:08 -07:00
|
|
|
patchExpressToHandleAsync();
|
2017-06-16 00:16:59 -07:00
|
|
|
const chanPath = Config.get('channel-path');
|
|
|
|
|
|
2017-07-16 22:35:33 -07:00
|
|
|
initPrometheus(app);
|
2015-11-02 21:07:50 -08:00
|
|
|
app.use((req, res, next) => {
|
2015-10-28 23:38:17 -07:00
|
|
|
counters.add("http:request", 1);
|
2014-09-11 18:56:33 -05:00
|
|
|
next();
|
|
|
|
|
});
|
2017-06-27 23:37:18 -07:00
|
|
|
require('./middleware/x-forwarded-for').initialize(app, webConfig);
|
2015-11-01 17:42:20 -08:00
|
|
|
app.use(bodyParser.urlencoded({
|
|
|
|
|
extended: false,
|
|
|
|
|
limit: '1kb' // No POST data should ever exceed this size under normal usage
|
|
|
|
|
}));
|
|
|
|
|
if (webConfig.getCookieSecret() === 'change-me') {
|
2017-04-04 23:02:31 -07:00
|
|
|
LOGGER.warn('The configured cookie secret was left as the ' +
|
2015-11-01 17:42:20 -08:00
|
|
|
'default of "change-me".');
|
|
|
|
|
}
|
|
|
|
|
app.use(cookieParser(webConfig.getCookieSecret()));
|
|
|
|
|
app.use(csrf.init(webConfig.getCookieDomain()));
|
2017-06-16 00:16:59 -07:00
|
|
|
app.use(`/${chanPath}/:channel`, require('./middleware/ipsessioncookie').ipSessionCookieMiddleware);
|
2015-11-01 17:42:20 -08:00
|
|
|
initializeLog(app);
|
|
|
|
|
require('./middleware/authorize')(app, session);
|
|
|
|
|
|
|
|
|
|
if (webConfig.getEnableGzip()) {
|
|
|
|
|
app.use(require('compression')({
|
|
|
|
|
threshold: webConfig.getGzipThreshold()
|
|
|
|
|
}));
|
2017-04-04 23:02:31 -07:00
|
|
|
LOGGER.info('Enabled gzip compression');
|
2014-11-16 21:06:10 -06:00
|
|
|
}
|
|
|
|
|
|
2015-11-01 17:42:20 -08:00
|
|
|
if (webConfig.getEnableMinification()) {
|
|
|
|
|
const cacheDir = path.join(__dirname, '..', '..', 'www', 'cache');
|
2015-11-03 19:34:12 -08:00
|
|
|
if (!fs.existsSync(cacheDir)) {
|
|
|
|
|
fs.mkdirSync(cacheDir);
|
2014-02-24 18:32:54 -06:00
|
|
|
}
|
2016-08-30 21:20:42 -07:00
|
|
|
app.use((req, res, next) => {
|
|
|
|
|
if (/\.user\.js/.test(req.url)) {
|
|
|
|
|
res._no_minify = true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
next();
|
|
|
|
|
});
|
2015-11-01 17:42:20 -08:00
|
|
|
app.use(require('express-minify')({
|
|
|
|
|
cache: cacheDir
|
2014-02-24 18:32:54 -06:00
|
|
|
}));
|
2017-04-04 23:02:31 -07:00
|
|
|
LOGGER.info('Enabled express-minify for CSS and JS');
|
2014-02-04 11:32:52 -06:00
|
|
|
}
|
2014-08-19 00:21:32 -05:00
|
|
|
|
2017-06-16 00:16:59 -07:00
|
|
|
require('./routes/channel')(app, ioConfig, chanPath);
|
2016-05-21 16:59:28 -07:00
|
|
|
require('./routes/index')(app, channelIndex, webConfig.getMaxIndexEntries());
|
2017-08-23 23:15:30 -07:00
|
|
|
app.get('/sioconfig(.json)?', handleLegacySocketConfig);
|
2015-11-01 17:42:20 -08:00
|
|
|
require('./routes/socketconfig')(app, clusterClient);
|
2017-08-23 23:15:30 -07:00
|
|
|
app.get('/useragreement', handleUserAgreement);
|
2015-11-01 17:42:20 -08:00
|
|
|
require('./routes/contact')(app, webConfig);
|
|
|
|
|
require('./auth').init(app);
|
2017-08-15 18:23:03 -07:00
|
|
|
require('./account').init(app, globalMessageBus);
|
2015-11-01 17:42:20 -08:00
|
|
|
require('./acp').init(app);
|
|
|
|
|
require('../google2vtt').attach(app);
|
2016-08-23 21:50:18 -07:00
|
|
|
require('./routes/google_drive_userscript')(app);
|
2017-03-02 18:47:47 -08:00
|
|
|
require('./routes/ustream_bypass')(app);
|
2015-11-01 17:42:20 -08:00
|
|
|
app.use(serveStatic(path.join(__dirname, '..', '..', 'www'), {
|
|
|
|
|
maxAge: webConfig.getCacheTTL()
|
2014-11-16 21:06:10 -06:00
|
|
|
}));
|
2015-11-01 17:42:20 -08:00
|
|
|
|
|
|
|
|
initializeErrorHandlers(app);
|
2013-12-12 14:48:23 -06:00
|
|
|
},
|
|
|
|
|
|
Skip full user auth for most page renders
Previously, the user's session cookie was being checked against the
database for all non-static requests. However, this is not really
needed and wastes resources (and is slow).
For most page views (e.g. index, channel page), just parsing the value
of the cookie is sufficient:
* The cookies are already HMAC signed, so tampering with them ought to
be for all reasonable purposes, impossible.
* Assuming the worst case, all a nefarious user could manage to do is
change the text of the "Welcome, {user}" and cause a (non-functional)
ACP link to appear clientside, both of which are already possible by
using the Inspect Element tool.
For authenticated pages (currently, the ACP, and anything under
/account/), the full database check is still performed (for now).
2017-08-01 21:40:26 -07:00
|
|
|
redirectHttps: redirectHttps,
|
|
|
|
|
|
|
|
|
|
authorize: async function authorize(req) {
|
|
|
|
|
if (!req.signedCookies || !req.signedCookies.auth) {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
return await verifySessionAsync(req.signedCookies.auth);
|
|
|
|
|
} catch (error) {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
setAuthCookie: function setAuthCookie(req, res, expiration, auth) {
|
|
|
|
|
if (req.hostname.indexOf(Config.get("http.root-domain")) >= 0) {
|
|
|
|
|
// Prevent non-root cookie from screwing things up
|
|
|
|
|
res.clearCookie("auth");
|
|
|
|
|
res.cookie("auth", auth, {
|
|
|
|
|
domain: Config.get("http.root-domain-dotted"),
|
|
|
|
|
expires: expiration,
|
|
|
|
|
httpOnly: true,
|
|
|
|
|
signed: true
|
|
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
res.cookie("auth", auth, {
|
|
|
|
|
expires: expiration,
|
|
|
|
|
httpOnly: true,
|
|
|
|
|
signed: true
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|
2013-12-12 14:48:23 -06:00
|
|
|
};
|