Fixed most errors in middleware

This commit is contained in:
SamTV12345 2024-08-19 22:35:49 +02:00
parent 43c0cdfd1e
commit 7db8b54476
9 changed files with 138 additions and 173 deletions

View file

@ -140,6 +140,27 @@ exports.restartServer = async () => {
} }
exports.appInstance = app exports.appInstance = app
// Measure response time
app.use((_, res, next) => {
const stopWatch = stats.timer('httpRequests').start();
const sendFn = res.send.bind(res);
res.send = (...args) => { stopWatch.end(); return sendFn(...args); };
next();
});
// If the log level specified in the config file is WARN or ERROR the application server never
// starts listening to requests as reported in issue #158. Not installing the log4js connect
// logger when the log level has a higher severity than INFO since it would not log at that level
// anyway.
if (!(settings.loglevel === 'WARN' && settings.loglevel === 'ERROR')) {
app.use((request, _, next)=>{
console.debug(`${request.method} ${request.url}`);
next()
});
}
app.use((req, res, next) => { app.use((req, res, next) => {
// res.header("X-Frame-Options", "deny"); // breaks embedded pads // res.header("X-Frame-Options", "deny"); // breaks embedded pads
if (settings.ssl) { if (settings.ssl) {
@ -178,24 +199,7 @@ exports.restartServer = async () => {
opts.trust_proxy = true opts.trust_proxy = true
} }
// Measure response time
app.use((req, res, next) => {
const stopWatch = stats.timer('httpRequests').start();
const sendFn = res.send.bind(res);
res.send = (...args) => { stopWatch.end(); return sendFn(...args); };
next();
});
// If the log level specified in the config file is WARN or ERROR the application server never
// starts listening to requests as reported in issue #158. Not installing the log4js connect
// logger when the log level has a higher severity than INFO since it would not log at that level
// anyway.
if (!(settings.loglevel === 'WARN' && settings.loglevel === 'ERROR')) {
app.use(log4js.connectLogger(logger, {
level: log4js.levels.DEBUG.levelStr,
format: ':status, :method :url',
}));
}
const {keyRotationInterval, sessionLifetime} = settings.cookie; const {keyRotationInterval, sessionLifetime} = settings.cookie;
let secret = settings.sessionKey; let secret = settings.sessionKey;

View file

@ -8,11 +8,12 @@ const stats = require('../../stats')
exports.expressCreateServer = (hook_name:string, args: ArgsExpressType, cb:Function) => { exports.expressCreateServer = (hook_name:string, args: ArgsExpressType, cb:Function) => {
// Handle errors // Handle errors
args.app.set_error_handler((req, res, error)=>{ args.app.set_error_handler((req, res, error)=>{
console.log('Error: ', error);
// if an error occurs Connect will pass it down // if an error occurs Connect will pass it down
// through these "error-handling" middleware // through these "error-handling" middleware
// allowing you to respond however you like // allowing you to respond however you like
res.status(500).json({error: 'Sorry, something bad happened!'});
console.error(error.stack ? error.stack : error.toString()); console.error(error.stack ? error.stack : error.toString());
//res.status(500).json({error: 'Sorry, something bad happened!'});
stats.meter('http500').mark(); stats.meter('http500').mark();
}) })

View file

@ -26,7 +26,7 @@ exports.expressCreateServer = (hookName:string, args:ArgsExpressType, cb:Functio
// handle export requests // handle export requests
args.app.use('/p/pad/rev/export/type', limiter); args.app.use('/p/pad/rev/export/type', limiter);
args.app.get('/p/:pad/:rev?/export/:type', (req:any, res:any, next:Function) => { args.app.get('/p/:pad/:rev?/export/:type', (req, res, next) => {
(async () => { (async () => {
const types = ['pdf', 'doc', 'txt', 'html', 'odt', 'etherpad']; const types = ['pdf', 'doc', 'txt', 'html', 'odt', 'etherpad'];
// send a 404 if we don't support this filetype // send a 404 if we don't support this filetype
@ -67,7 +67,7 @@ exports.expressCreateServer = (hookName:string, args:ArgsExpressType, cb:Functio
console.log(`Exporting pad "${req.params.pad}" in ${req.params.type} format`); console.log(`Exporting pad "${req.params.pad}" in ${req.params.type} format`);
await exportHandler.doExport(req, res, padId, readOnlyId, req.params.type); await exportHandler.doExport(req, res, padId, readOnlyId, req.params.type);
} }
})().catch((err) => next(err || new Error(err))); })();
}); });
// handle import requests // handle import requests

View file

@ -24,8 +24,8 @@ const pwa = {
} }
exports.expressCreateServer = (hookName:string, args:ArgsExpressType, cb:Function) => { exports.expressCreateServer = (hookName:string, args:ArgsExpressType, cb:Function) => {
args.app.get('/manifest.json', (req:any, res:any) => { args.app.get('/manifest.json', (req, res) => {
res.json(pwa); return res.json(pwa);
}); });
return cb(); return cb();

View file

@ -76,7 +76,7 @@ export const expressCreateServer = (hookName:string, args:ArgsExpressType, cb:Fu
maxHttpBufferSize: settings.socketIo.maxHttpBufferSize, maxHttpBufferSize: settings.socketIo.maxHttpBufferSize,
}) })
io.attachApp(args.app) io.attachApp(args.app.uws_instance)
const handleConnection = (socket:Socket) => { const handleConnection = (socket:Socket) => {

View file

@ -12,6 +12,8 @@ const webaccess = require('./webaccess');
const plugins = require('../../../static/js/pluginfw/plugin_defs'); const plugins = require('../../../static/js/pluginfw/plugin_defs');
import {build, buildSync} from 'esbuild' import {build, buildSync} from 'esbuild'
import {ArgsExpressType} from "../../types/ArgsExpressType";
import LiveDirectory from "live-directory";
let ioI: { sockets: { sockets: any[]; }; } | null = null let ioI: { sockets: { sockets: any[]; }; } | null = null
exports.socketio = (hookName: string, {io}: any) => { exports.socketio = (hookName: string, {io}: any) => {
@ -19,7 +21,7 @@ exports.socketio = (hookName: string, {io}: any) => {
} }
exports.expressPreSession = async (hookName:string, {app}:any) => { exports.expressPreSession = async (hookName:string, {app}:ArgsExpressType) => {
// This endpoint is intended to conform to: // This endpoint is intended to conform to:
// https://www.ietf.org/archive/id/draft-inadarei-api-health-check-06.html // https://www.ietf.org/archive/id/draft-inadarei-api-health-check-06.html
app.get('/health', (req:any, res:any) => { app.get('/health', (req:any, res:any) => {
@ -50,36 +52,35 @@ exports.expressPreSession = async (hookName:string, {app}:any) => {
}); });
}); });
app.get('/favicon.ico', (req:any, res:any, next:Function) => { app.get('/favicon.ico', async (req, res, next) => {
(async () => {
/* /*
If this is a url we simply redirect to that one. If this is a url we simply redirect to that one.
*/ */
if (settings.favicon && settings.favicon.startsWith('http')) { if (settings.favicon && settings.favicon.startsWith('http')) {
res.redirect(settings.favicon); res.redirect(settings.favicon);
res.send(); res.send();
return; return;
} }
const fns = [ const fns = [
...(settings.favicon ? [path.resolve(settings.root, settings.favicon)] : []), ...(settings.favicon ? [path.resolve(settings.root, settings.favicon)] : []),
path.join(settings.root, 'src', 'static', 'skins', settings.skinName, 'favicon.ico'), path.join(settings.root, 'src', 'static', 'skins', settings.skinName, 'favicon.ico'),
path.join(settings.root, 'src', 'static', 'favicon.ico'), path.join(settings.root, 'src', 'static', 'favicon.ico'),
]; ];
for (const fn of fns) { for (const fn of fns) {
try { try {
await fsp.access(fn, fs.constants.R_OK); await fsp.access(fn, fs.constants.R_OK);
} catch (err) { } catch (err) {
continue; continue;
}
res.setHeader('Cache-Control', `public, max-age=${settings.maxAge}`);
await util.promisify(res.sendFile.bind(res))(fn);
return;
} }
next(); res.setHeader('Cache-Control', `public, max-age=${settings.maxAge}`);
})().catch((err) => next(err || new Error(err))); res.sendFile.bind(res)(fn);
}); return;
}
next();
})
}; };
@ -111,131 +112,85 @@ const convertTypescript = (content: string) => {
} }
} }
const handleLiveReload = async (args: any, padString: string, timeSliderString: string, indexString: any) => { const handleLiveReload = async (args: ArgsExpressType, padString: string, timeSliderString: string, indexString: any) => {
const chokidar = await import('chokidar')
const watcher = chokidar.watch(path.join(settings.root, 'src', 'static', 'js'));
let routeHandlers: { [key: string]: Function } = {};
const setRouteHandler = (path: string, newHandler: Function) => {
routeHandlers[path] = newHandler;
};
args.app.use((req: any, res: any, next: Function) => {
if (req.path.startsWith('/p/') && req.path.split('/').length == 3) {
req.padId = req.path.split('/')[2]
routeHandlers['/p/:pad'](req, res);
} else if (req.path.startsWith('/p/') && req.path.split('/').length == 4) {
req.padId = req.path.split('/')[2]
routeHandlers['/p/:pad/timeslider'](req, res);
} else if (req.path == "/"){
routeHandlers['/'](req, res);
} else if (routeHandlers[req.path]) {
routeHandlers[req.path](req, res);
} else {
next();
}
});
function handleUpdate() {
convertTypescriptWatched(indexString, (output, hash) => {
setRouteHandler('/watch/index', (req: any, res: any) => {
res.header('Content-Type', 'application/javascript');
res.send(output)
})
setRouteHandler('/', (req: any, res: any) => {
res.send(eejs.require('ep_etherpad-lite/templates/index.html', {req, entrypoint: '/watch/index?hash=' + hash, settings}));
})
})
convertTypescriptWatched(padString, (output, hash) => {
console.log("New pad hash is", hash)
setRouteHandler('/watch/pad', (req: any, res: any) => {
res.header('Content-Type', 'application/javascript');
res.send(output)
})
const livedir = new LiveDirectory(path.join(settings.root, 'src', 'static', 'js'))
let indexJS = convertTypescript(indexString)
let padJS = convertTypescript(padString)
let timeSliderJS = convertTypescript(timeSliderString)
const updateLive = ()=>{
indexJS = convertTypescript(indexString)
padJS = convertTypescript(padString)
timeSliderJS = convertTypescript(timeSliderString)
setRouteHandler("/p/:pad", (req: any, res: any, next: Function) => { ioI!.sockets.sockets.forEach(socket => socket.emit('liveupdate'))
// The below might break for pads being rewritten
const isReadOnly = !webaccess.userCanModify(req.padId, req);
hooks.callAll('padInitToolbar', {
toolbar,
isReadOnly
});
const content = eejs.require('ep_etherpad-lite/templates/pad.html', {
req,
toolbar,
isReadOnly,
entrypoint: '/watch/pad?hash=' + hash
})
res.send(content);
})
ioI!.sockets.sockets.forEach(socket => socket.emit('liveupdate'))
})
convertTypescriptWatched(timeSliderString, (output, hash) => {
// serve timeslider.html under /p/$padname/timeslider
console.log("New timeslider hash is", hash)
setRouteHandler('/watch/timeslider', (req: any, res: any) => {
res.header('Content-Type', 'application/javascript');
res.send(output)
})
setRouteHandler("/p/:pad/timeslider", (req: any, res: any, next: Function) => {
console.log("Reloading pad")
// The below might break for pads being rewritten
const isReadOnly = !webaccess.userCanModify(req.padId, req);
hooks.callAll('padInitToolbar', {
toolbar,
isReadOnly
});
const content = eejs.require('ep_etherpad-lite/templates/timeslider.html', {
req,
toolbar,
isReadOnly,
entrypoint: '/watch/timeslider?hash=' + hash
})
res.send(content);
})
})
} }
watcher.on('change', path => {
console.log(`File ${path} has been changed`);
handleUpdate();
});
handleUpdate()
}
const convertTypescriptWatched = (content: string, cb: (output:string, hash: string)=>void) => { args.app.get('/', (req, res)=>{
build({ res.send(eejs.require('ep_etherpad-lite/templates/index.html', {req, entrypoint: '/watch/index?hash=' + indexJS.hash, settings}));
stdin: { })
contents: content, args.app.get('/watch/index', (req, res)=>{
resolveDir: path.join(settings.root, 'var','js'), res.header('Content-Type', 'application/javascript');
loader: 'js' res.send(indexJS.output)
}, })
alias:{
"ep_etherpad-lite/static/js/browser": 'ep_etherpad-lite/static/js/vendors/browser', args.app.get('/watch/pad', (req, res)=>{
"ep_etherpad-lite/static/js/nice-select": 'ep_etherpad-lite/static/js/vendors/nice-select' res.header('Content-Type', 'application/javascript');
}, res.send(padJS.output)
bundle: true, // Bundle the files together })
minify: process.env.NODE_ENV === "production", // Minify the output
sourcemap: !(process.env.NODE_ENV === "production"), // Generate source maps args.app.get('/watch/timeslider', (req, res)=>{
sourceRoot: settings.root+"/src/static/js/", res.header('Content-Type', 'application/javascript');
target: ['es2020'], // Target ECMAScript version res.send(timeSliderJS.output)
metafile: true, })
write: false, // Do not write to file system,
}).then((outputRaw) => { args.app.get('/p/:pad', (req, res, next)=>{
cb( const isReadOnly = !webaccess.userCanModify(req.params.pad, req);
outputRaw.outputFiles[0].text,
outputRaw.outputFiles[0].hash.replaceAll('/','2').replaceAll("+",'5').replaceAll("^","7") hooks.callAll('padInitToolbar', {
) toolbar,
isReadOnly
});
const content = eejs.require('ep_etherpad-lite/templates/pad.html', {
req,
toolbar,
isReadOnly,
entrypoint: '/watch/pad?hash=' + padJS.hash
})
res.send(content);
})
args.app.get('/p/:pad/timeslider', (req, res, next)=>{
console.log("Reloading pad")
// The below might break for pads being rewritten
const isReadOnly = !webaccess.userCanModify(req.params.pad, req);
hooks.callAll('padInitToolbar', {
toolbar,
isReadOnly
});
const content = eejs.require('ep_etherpad-lite/templates/timeslider.html', {
req,
toolbar,
isReadOnly,
entrypoint: '/watch/timeslider?hash=' + timeSliderJS.hash
})
res.send(content);
})
livedir.on('ready', (path: string) => {
livedir.on('update', ()=>{
updateLive()
})
})
livedir.on('delete', ()=>{
updateLive()
}) })
} }

View file

@ -72,8 +72,10 @@ const checkAccess = async (req:any, res:any, next: Function) => {
(r) => (skip || (r != null && r.filter((x) => (!requireAdmin || !x)).length > 0))) as boolean[]; (r) => (skip || (r != null && r.filter((x) => (!requireAdmin || !x)).length > 0))) as boolean[];
} catch (err:any) { } catch (err:any) {
httpLogger.error(`Error in preAuthorize hook: ${err.stack || err.toString()}`); httpLogger.error(`Error in preAuthorize hook: ${err.stack || err.toString()}`);
if (!skip) res.status(500).send('Internal Server Error'); if (!skip) {
return; res.status(500).send('Internal Server Error');
return;
}
} }
if (skip) return; if (skip) return;
if (requireAdmin) { if (requireAdmin) {
@ -189,7 +191,7 @@ const checkAccess = async (req:any, res:any, next: Function) => {
} }
if (req.session.user == null) { if (req.session.user == null) {
httpLogger.error('authenticate hook failed to add user settings to session'); httpLogger.error('authenticate hook failed to add user settings to session');
return res.status(500).send('Internal Server Error'); throw new Error('authenticate hook failed to add user settings to session')
} }
const {username = '<no username>'} = req.session.user; const {username = '<no username>'} = req.session.user;
httpLogger.info(`Successful authentication from IP ${req.ip} for user ${username}`); httpLogger.info(`Successful authentication from IP ${req.ip} for user ${username}`);
@ -211,6 +213,7 @@ const checkAccess = async (req:any, res:any, next: Function) => {
if (await aCallFirst0('authFailure', {req, res, next})) return; if (await aCallFirst0('authFailure', {req, res, next})) return;
// No plugin handled the authorization failure. // No plugin handled the authorization failure.
res.status(403).send('Forbidden'); res.status(403).send('Forbidden');
return
}; };
/** /**
@ -218,5 +221,5 @@ const checkAccess = async (req:any, res:any, next: Function) => {
* express-session middleware. * express-session middleware.
*/ */
exports.checkAccess = (req:any, res:any, next:Function) => { exports.checkAccess = (req:any, res:any, next:Function) => {
checkAccess(req, res, next).catch((err) => next(err || new Error(err))); checkAccess(req, res, next);
}; };

View file

@ -251,6 +251,7 @@ exports.exit = async (err: ErrorCaused|string|null = null) => {
} else if (typeof err == "object" && err != null) { } else if (typeof err == "object" && err != null) {
logger.error(`Metrics at time of fatal error:\n${JSON.stringify(stats.toJSON(), null, 2)}`); logger.error(`Metrics at time of fatal error:\n${JSON.stringify(stats.toJSON(), null, 2)}`);
logger.error(err.stack || err.toString()); logger.error(err.stack || err.toString());
console.trace();
process.exitCode = 1; process.exitCode = 1;
if (exitCalled) { if (exitCalled) {
logger.error('Error occurred while waiting to exit. Forcing an immediate unclean exit...'); logger.error('Error occurred while waiting to exit. Forcing an immediate unclean exit...');

View file

@ -16,6 +16,7 @@ import {Attribute} from "./types/Attribute";
import AttributePool from "./AttributePool"; import AttributePool from "./AttributePool";
import {opsFromText, pack} from "./Changeset"; import {opsFromText, pack} from "./Changeset";
/** /**
* @param {number} oldLen - Old length * @param {number} oldLen - Old length
* @returns {Builder} * @returns {Builder}