Merge branch 'staging' into staging-3071-v2

This commit is contained in:
Eradev
2025-01-28 10:49:53 -05:00
74 changed files with 1581 additions and 314 deletions

View File

@ -18,10 +18,9 @@ import { hideBin } from 'yargs/helpers';
// express/server related library imports
import cors from 'cors';
import { doubleCsrf } from 'csrf-csrf';
import { csrfSync } from 'csrf-sync';
import express from 'express';
import compression from 'compression';
import cookieParser from 'cookie-parser';
import cookieSession from 'cookie-session';
import multer from 'multer';
import responseTime from 'response-time';
@ -40,7 +39,6 @@ util.inspect.defaultOptions.depth = 4;
import { loadPlugins } from './src/plugin-loader.js';
import {
initUserStorage,
getCsrfSecret,
getCookieSecret,
getCookieSessionName,
getAllEnabledUsers,
@ -67,6 +65,7 @@ import {
forwardFetchResponse,
removeColorFormatting,
getSeparator,
safeReadFileSync,
setupLogLevel,
} from './src/util.js';
import { UPLOADS_DIRECTORY } from './src/constants.js';
@ -348,8 +347,8 @@ if (enableCorsProxy) {
}
function getSessionCookieAge() {
// Defaults to 24 hours in seconds if not set
const configValue = getConfigValue('sessionTimeout', 24 * 60 * 60);
// Defaults to "no expiration" if not set
const configValue = getConfigValue('sessionTimeout', -1);
// Convert to milliseconds
if (configValue > 0) {
@ -378,27 +377,38 @@ app.use(setUserDataMiddleware);
// CSRF Protection //
if (!disableCsrf) {
const COOKIES_SECRET = getCookieSecret();
const { generateToken, doubleCsrfProtection } = doubleCsrf({
getSecret: getCsrfSecret,
cookieName: 'X-CSRF-Token',
cookieOptions: {
sameSite: 'strict',
secure: false,
const csrfSyncProtection = csrfSync({
getTokenFromState: (req) => {
if (!req.session) {
console.error('(CSRF error) getTokenFromState: Session object not initialized');
return;
}
return req.session.csrfToken;
},
size: 64,
getTokenFromRequest: (req) => req.headers['x-csrf-token'],
getTokenFromRequest: (req) => {
return req.headers['x-csrf-token']?.toString();
},
storeTokenInState: (req, token) => {
if (!req.session) {
console.error('(CSRF error) storeTokenInState: Session object not initialized');
return;
}
req.session.csrfToken = token;
},
size: 32,
});
app.get('/csrf-token', (req, res) => {
res.json({
'token': generateToken(res, req),
'token': csrfSyncProtection.generateToken(req),
});
});
app.use(cookieParser(COOKIES_SECRET));
app.use(doubleCsrfProtection);
// Customize the error message
csrfSyncProtection.invalidCsrfTokenError.message = color.red('Invalid CSRF token. Please refresh the page and try again.');
csrfSyncProtection.invalidCsrfTokenError.stack = undefined;
app.use(csrfSyncProtection.csrfSynchronisedProtection);
} else {
console.warn('\nCSRF protection is disabled. This will make your server vulnerable to CSRF attacks.\n');
app.get('/csrf-token', (req, res) => {
@ -925,6 +935,16 @@ async function verifySecuritySettings() {
}
}
/**
* Registers a not-found error response if a not-found error page exists. Should only be called after all other middlewares have been registered.
*/
function apply404Middleware() {
const notFoundWebpage = safeReadFileSync('./public/error/url-not-found.html') ?? '';
app.use((req, res) => {
res.status(404).send(notFoundWebpage);
});
}
// User storage module needs to be initialized before starting the server
initUserStorage(dataRoot)
.then(ensurePublicDirectoriesExist)
@ -932,4 +952,5 @@ initUserStorage(dataRoot)
.then(migrateSystemPrompts)
.then(verifySecuritySettings)
.then(preSetupTasks)
.then(apply404Middleware)
.finally(startServer);