Defer middleware HTML file reads

This commit is contained in:
Cohee 2025-01-26 01:46:30 +02:00
parent 96143177ce
commit 9aac5a22f1
2 changed files with 10 additions and 9 deletions

View File

@ -10,13 +10,13 @@ import { getConfig, getConfigValue, safeReadFileSync } from '../util.js';
const PER_USER_BASIC_AUTH = getConfigValue('perUserBasicAuth', false);
const ENABLE_ACCOUNTS = getConfigValue('enableUserAccounts', false);
const unauthorizedWebpage = safeReadFileSync('./public/error/unauthorized.html') ?? '';
const unauthorizedResponse = (res) => {
res.set('WWW-Authenticate', 'Basic realm="SillyTavern", charset="UTF-8"');
return res.status(401).send(unauthorizedWebpage);
};
const basicAuthMiddleware = async function (request, response, callback) {
const unauthorizedWebpage = safeReadFileSync('./public/error/unauthorized.html') ?? '';
const unauthorizedResponse = (res) => {
res.set('WWW-Authenticate', 'Basic realm="SillyTavern", charset="UTF-8"');
return res.status(401).send(unauthorizedWebpage);
};
const config = getConfig();
const authHeader = request.headers.authorization;

View File

@ -11,9 +11,6 @@ const whitelistPath = path.join(process.cwd(), './whitelist.txt');
const enableForwardedWhitelist = getConfigValue('enableForwardedWhitelist', false);
let whitelist = getConfigValue('whitelist', []);
let knownIPs = new Set();
const forbiddenWebpage = Handlebars.compile(
safeReadFileSync('./public/error/forbidden-by-whitelist.html') ?? '',
);
if (fs.existsSync(whitelistPath)) {
try {
@ -56,6 +53,10 @@ function getForwardedIp(req) {
* @returns {import('express').RequestHandler} The middleware function
*/
export default function whitelistMiddleware(whitelistMode, listen) {
const forbiddenWebpage = Handlebars.compile(
safeReadFileSync('./public/error/forbidden-by-whitelist.html') ?? '',
);
return function (req, res, next) {
const clientIp = getIpFromRequest(req);
const forwardedIp = getForwardedIp(req);