This commit is contained in:
SamTv12345 2024-08-20 16:09:06 +02:00
parent 73f70eb9e5
commit 8ab47761df
4 changed files with 37 additions and 31 deletions

View file

@ -56,8 +56,7 @@ const closeServer = async () => {
await events.once(socketsEvents, 'updated'); await events.once(socketsEvents, 'updated');
} }
await p; await p;
await appInstance?.shutdown() appInstance?.close()
appInstance!.close()
clearTimeout(timeout); clearTimeout(timeout);
exports.server = null; exports.server = null;
appInstance = null appInstance = null

View file

@ -15,6 +15,7 @@ exports.expressCreateServer = (hook_name:string, args: ArgsExpressType, cb:Funct
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!'}); //res.status(500).json({error: 'Sorry, something bad happened!'});
stats.meter('http500').mark(); stats.meter('http500').mark();
res.status(500).json({error: 'Sorry, something bad happened123!'});
}) })

View file

@ -6,27 +6,36 @@ const padManager = require('../../db/PadManager');
exports.expressCreateServer = (hookName:string, args:ArgsExpressType, cb:Function) => { exports.expressCreateServer = (hookName:string, args:ArgsExpressType, cb:Function) => {
// redirects browser to the pad's sanitized url if needed. otherwise, renders the html // redirects browser to the pad's sanitized url if needed. otherwise, renders the html
/*args.app.param('pad', (req:any, res:any, next:Function, padId:string) => { args.app.use(async (req, res, next) => {
(async () => { console.log("Hier gehe ich durch")
const possiblePad = req.params.pad
try {
if (!possiblePad) {
next()
}
// ensure the padname is valid and the url doesn't end with a / // ensure the padname is valid and the url doesn't end with a /
if (!padManager.isValidPadId(padId) || /\/$/.test(req.url)) { if (!padManager.isValidPadId(possiblePad) || /\/$/.test(req.url)) {
res.status(404).send('Such a padname is forbidden'); res.status(404).send('Such a padname is forbidden');
return; return;
} }
const sanitizedPadId = await padManager.sanitizePadId(padId); const sanitizedPadId = await padManager.sanitizePadId(possiblePad);
if (sanitizedPadId === padId) { if (sanitizedPadId === possiblePad) {
// the pad id was fine, so just render it // the pad id was fine, so just render it
next(); next();
} else { } else {
// the pad id was sanitized, so we redirect to the sanitized version // the pad id was sanitized, so we redirect to the sanitized version
const realURL = const realURL =
encodeURIComponent(sanitizedPadId) + new URL(req.url, 'http://invalid.invalid').search; encodeURIComponent(sanitizedPadId) + new URL(req.url, 'http://invalid.invalid').search;
res.header('Location', realURL); res.header('Location', realURL);
res.status(302).send(`You should be redirected to <a href="${realURL}">${realURL}</a>`); res.status(302).send(`You should be redirected to <a href="${realURL}">${realURL}</a>`);
} }
})().catch((err) => next(err || new Error(err))); }
});*/ catch (e) {
return e
}
})
return cb(); return cb();
}; };

View file

@ -18,8 +18,8 @@ const aCallFirst = (hookName: string, context:any, pred = null) => new Promise((
}); });
const aCallFirst0 = const aCallFirst0 =
// @ts-ignore // @ts-ignore
async (hookName: string, context:any, pred = null) => (await aCallFirst(hookName, context, pred))[0]; async (hookName: string, context:any, pred = null) => (await aCallFirst(hookName, context, pred))[0];
exports.normalizeAuthzLevel = (level: string|boolean) => { exports.normalizeAuthzLevel = (level: string|boolean) => {
if (!level) return false; if (!level) return false;
@ -63,19 +63,17 @@ const checkAccess = async (req:any, res:any, next: Function) => {
const preAuthorizeNext = (...args:any) => { skip = true; next(...args); }; const preAuthorizeNext = (...args:any) => { skip = true; next(...args); };
try { try {
results = await aCallFirst('preAuthorize', {req, res, next: preAuthorizeNext}, results = await aCallFirst('preAuthorize', {req, res, next: preAuthorizeNext},
// This predicate will cause aCallFirst to call the hook functions one at a time until one // This predicate will cause aCallFirst to call the hook functions one at a time until one
// of them returns a non-empty list, with an exception: If the request is for an /admin // of them returns a non-empty list, with an exception: If the request is for an /admin
// page, truthy entries are filtered out before checking to see whether the list is empty. // page, truthy entries are filtered out before checking to see whether the list is empty.
// This prevents plugin authors from accidentally granting admin privileges to the general // This prevents plugin authors from accidentally granting admin privileges to the general
// public. // public.
// @ts-ignore // @ts-ignore
(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) { if (!skip) res.status(500).send('Internal Server Error');
res.status(500).send('Internal Server Error'); return;
return;
}
} }
if (skip) return; if (skip) return;
if (requireAdmin) { if (requireAdmin) {
@ -130,8 +128,8 @@ const checkAccess = async (req:any, res:any, next: Function) => {
if (await authorize()) { if (await authorize()) {
if(requireAdmin) { if(requireAdmin) {
res.status(200).send('Authorized') res.status(200).send('Authorized')
return return
} }
return next(); return next();
} }
@ -151,7 +149,7 @@ const checkAccess = async (req:any, res:any, next: Function) => {
const httpBasicAuth = req.headers.authorization && req.headers.authorization.startsWith('Basic '); const httpBasicAuth = req.headers.authorization && req.headers.authorization.startsWith('Basic ');
if (httpBasicAuth) { if (httpBasicAuth) {
const userpass = const userpass =
Buffer.from(req.headers.authorization.split(' ')[1], 'base64').toString().split(':'); Buffer.from(req.headers.authorization.split(' ')[1], 'base64').toString().split(':');
ctx.username = userpass.shift(); ctx.username = userpass.shift();
// Prevent prototype pollution vulnerabilities in plugins. This also silences a prototype // Prevent prototype pollution vulnerabilities in plugins. This also silences a prototype
// pollution warning below (when setting settings.users[ctx.username]) that isn't actually a // pollution warning below (when setting settings.users[ctx.username]) that isn't actually a
@ -165,8 +163,8 @@ const checkAccess = async (req:any, res:any, next: Function) => {
const {[ctx.username]: {password} = {}} = settings.users as SettingsUser; const {[ctx.username]: {password} = {}} = settings.users as SettingsUser;
if (!httpBasicAuth || if (!httpBasicAuth ||
!ctx.username || !ctx.username ||
password == null || password.toString() !== ctx.password) { password == null || password.toString() !== ctx.password) {
httpLogger.info(`Failed authentication from IP ${req.ip}`); httpLogger.info(`Failed authentication from IP ${req.ip}`);
if (await aCallFirst0('authnFailure', {req, res})) return; if (await aCallFirst0('authnFailure', {req, res})) return;
if (await aCallFirst0('authFailure', {req, res, next})) return; if (await aCallFirst0('authFailure', {req, res, next})) return;
@ -191,7 +189,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');
throw new Error('authenticate hook failed to add user settings to session') return res.status(500).send('Internal Server Error');
} }
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}`);
@ -213,7 +211,6 @@ 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
}; };
/** /**
@ -221,5 +218,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); checkAccess(req, res, next).catch((err) => next(err || new Error(err)));
}; };